branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>Tubbz-alt/course-programming-languages<file_sep>/README.md
# course-programming-languages
Lecture notes, assignments, and other materials for a one-semester course on programming language concepts and theory, interpretation and compilation, and programming paradigms.
Git, PHP 5.4 or later, and the [Sheaf](http://sheaf.io) library are required to render the notes as HTML. The latest version of the Sheaf library is retrieved automatically by the `install.sh` script. You can install the notes on a Linux server in a directory such as `example` (e.g., under the web root directory) as follows:
git clone https://github.com/lapets/course-programming-languages.git example
cd example
chmod 0755 install.sh
./install.sh
On a running server, `index.php` will render the notes in their HTML form. In a Linux environment, it is also possible to build the HTML version of the notes as follows:
php index.php > index.html
chmod 0644 index.html
The `gh-pages` branch of this repository also contains the rendered HTML version of the notes; they can be viewed at http://lapets.github.io/course-programming-languages.
<file_sep>/install.sh
git clone https://github.com/lapets/sheaf.git sheaf
chmod 0644 *.xml *.html *.py *.hs sheaf/*.css sheaf/*.js hw*/*
chmod 0755 . *.php machine.php sheaf sheaf/*.php sheaf/hooks sheaf/hooks/*.php
|
a8e0cee0699d0f25e6f41c978d10fe4a0b874606
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
Tubbz-alt/course-programming-languages
|
4d044b11eda468ff54c0ac3bd55350fe75d45d6f
|
f379d190af878db56206888fab25809ff71d2f09
|
refs/heads/master
|
<file_sep>from fabric.api import env, roles, sudo, execute, put, run, local, lcd, prompt, cd, parallel
import os
env.roledefs = {
"webserver" : [ "172.31.35.226", "172.31.24.2", "172.31.17.13" ],
"database" : [ "172.31.117.35", "172.31.112.114" ],
}
env.roledefs["all"] = [h for r in env.roledefs.values() for h in r]
packages_required = {
"webserver" : [ "httpd", "php", "ntp", "php-myqli" ],
"database" : [ "mariadb-server" ]
}
download_files = {
"database" : [ "http://labfiles.linuxacademy.com/python/fabric/sakila.sql",
"http://labfiles.linuxacademy.com/python/fabric/sakila-data.sql"],
"webserver" : [ "http://labfiles.linuxacademy.com/python/fabric/index.php"]
}
@roles("database")
def install_database():
sudo("yum -y install %s" % " ".join(packages_required["database"]), pty=True)
sudo("systemctl enable mariadb", pty=True)
sudo("systemctl start mariadb", pty=True)
sudo(r""" mysql -h 127.0.0.1 -u root -e "CREATE USER 'web'@'%' IDENTIFIED BY 'web'; GRANT ALL PRIVILEGES ON *.* TO 'web'@'%'; FLUSH PRIVILEGES;" """)
run("ps -ef | grep mysql")
@parallel
@roles("database")
def setup_database():
tmpdir = "/tmp"
with cd(tmpdir):
for url in download_files["database"]:
filename = "%s/%s" %(tmpdir, os.path.basename(url));
run("wget --no-cache %s -O %s" %(url, filename))
run("mysql -u root < %s" %filename)
@roles("webserver")
def install_webserver():
sudo("yum -y install %s" % " ".join(packages_required["webserver"]), pty=True)
sudo("systemctl enable httpd.service", pty=True)
sudo("systemctl start httpd.service", pty=True)
sudo("setsebool -P httpd_can_network_connect=1", pty=True)
sudo("setsebool -P httpd_read_user_content=1", pty=True)
@roles("webserver")
def setup_webserver():
tmpdir = "/tmp"
remote_dir = "/var/www/html"
with lcd(tmpdir):
for url in download_files["webserver"]:
filename = "%s/%s" %(tmpdir, os.path.basename(url));
local("wget --no-cache %s -O %s" %(url,filename))
put(filename,"/var/www/html/", mode=0755, use_sudo=True)
database = pick_server(env.roledefs["database"])
sudo(r""" echo "<?php \\$db = '%s'; ?> " > /var/www/html/db.php """ % env.roledefs['database'][database])
def pick_server(mylist):
database = 0
while not 1<=database<=len(mylist):
for i, db in enumerate(mylist,1):
print "[%s] - %s" % (i, db)
database = prompt("Enter the number of the database should I connect %s to: " % (env.host), validate=int)
return int(database)-1
@roles("all")
def upgrade_servers():
sudo("yum -y upgrade", pty=True)
def deploy():
execute(upgrade_servers)
execute(install_database)
execute(install_webserver)
execute(setup_database)
execute(setup_webserver)
print "t|x > tw"
<file_sep>#!/usr/bin/env python
def user_input():
temp = float(raw_input("What is the temp? "))
scale = raw_input("Is it in Celcius or Fahrenheit? ").lower().strip()
return (temp,scale)
def compute(temp,scale='celsius'):
if scale == 'celcius':
conv = temp * 9/5 +32
x = 'F'
else:
conv = (temp - 32) * 5/9
x = 'C'
print "%s %s is converted to %s %s" % (temp,scale,conv,x)
while True:
temp,scale = user_input()
if scale.startswith('c'):
compute(temp,scale='celcius')
break
elif scale.startswith('f'):
compute(temp,scale='fahrenheit')
break
else:
print ("CELSIUS and FAHRENHEIGHT ONLY!!")
<file_sep>#!/usr/bin/env python
import subprocess
def activeProcess(lookup_user,lookup_cmd):
process_running_all = 0
process_running_search = 0
for line in subprocess.check_output("ps -ef", shell=True).splitlines()[1:]:
user = line.split()[0]
if lookup_user == user:
process_running_all+=1
if lookup_cmd in line:
process_running_search+=1
return process_running_all, process_running_search
process_total, process_searched = activeProcess('root','xfs')
print process_total, process_searched
<file_sep>#!/usr/bin/env python
import subprocess
command = subprocess.Popen('/sbin/ifconfig eth0', shell=True, stdout=subprocess.PIPE)
print command.stdout.read()
output = command.communicate()[0]
##################### 1 PIPE ################################################
#!/usr/bin/env python
import subprocess
command = subprocess.Popen('/sbin/ifconfig eth0'.split(), stdout=subprocess.PIPE)
pipe1 = subprocess.Popen('grep inet'.split(), stdin=command.stdout, stdout=subprocess.PIPE)
command.stdout.close()
print pipe1.stdout.read()
output = pipe1.communicate()[0]
############################################################################
##################### 2 PIPE ################################################
#!/usr/bin/env python
import subprocess
command = subprocess.Popen('/sbin/ifconfig eth0'.split(), stdout=subprocess.PIPE)
pipe1 = subprocess.Popen('grep inet'.split(), stdin=command.stdout, stdout=subprocess.PIPE)
command.stdout.close()
pipe2 = subprocess.Popen(['awk', '{print $2}'], stdin=pipe1.stdout, stdout=subprocess.PIPE)
pipe1.stdout.close()
print pipe2.stdout.read()
output = pipe2.communicate()[0]
############################################################################
##################### 3 PIPE ################################################
#!/usr/bin/env python
import subprocess
command = subprocess.Popen('/sbin/ifconfig eth0'.split(), stdout=subprocess.PIPE)
pipe1 = subprocess.Popen('grep inet'.split(), stdin=command.stdout, stdout=subprocess.PIPE)
command.stdout.close()
pipe2 = subprocess.Popen(['awk', '{print $2}'], stdin=pipe1.stdout, stdout=subprocess.PIPE)
pipe1.stdout.close()
pipe3 = subprocess.Popen(['awk', '-F', ':','{print $2}'], stdin=pipe2.stdout, stdout=subprocess.PIPE)
pipe2.stdout.close()
print pipe3.stdout.read()
output = pipe3.communicate()[0]
########################################################################################################
<file_sep>#!/usr/bin/env python
from pyfirmata import Arduino, util
from time import sleep
import os
port = "/dev/ttyUSB0"
board = Arduino(port)
sleep(2)
it = util.Iterator(board)
it.start()
servoPin = board.get_pin('d:4:s')
potenPin = board.get_pin('a:0:i')
def turnservo(angle):
servoPin.write(angle)
sleep(.020)
try:
while True:
sleep(.030)
analogRead_0 = potenPin.read()
analogRead_0 = int(((analogRead_0 * 1000) * 180) / 1000)
turnservo(analogRead_0)
print analogRead_0
except KeyboardInterrupt:
board.exit()
os._exit
<file_sep>#!/usr/bin/env python
import subprocess
iplink_cmd = subprocess.check_output(['ip','link']).strip()
lines = (iplink_cmd.splitlines())[2]
iface = lines.split()
iface = iface[1].replace(':','').strip()
print iface
<file_sep>#!/usr/bin/env python
import subprocess
users = {}
ps_cmd = subprocess.check_output(['ps', '-ef'])
for line in ps_cmd.splitlines()[1:]:
user = line.split()[0]
if users.get(user):
users[user]+=1
else:
users[user]=1
print ','.join(users.keys())
for user, process_count in users.items():
print "%s us running %s processes" %(user,process_count)
print users
print users.get('root')
<file_sep>#!/usr/bin/env python
import subprocess
command = subprocess.Popen('ip link',shell=True, stdout=subprocess.PIPE)
pipe1 = subprocess.Popen('grep BROADCAST,MULTICAST,UP,LOWER_UP'.split(), stdin=command.stdout, stdout=subprocess.PIPE)
command.stdout.close()
pipe2 = subprocess.Popen(['awk', '-F', ':', '{print $2}'], stdin=pipe1.stdout, stdout=subprocess.PIPE)
pipe1.stdout.close()
iface = pipe2.communicate()[0].strip()
command2 = subprocess.Popen('ip addr', shell=True, stdout=subprocess.PIPE)
grep1 = subprocess.Popen('grep inet'.split(), stdin=command2.stdout, stdout=subprocess.PIPE)
command2.stdout.close()
grep2 = subprocess.Popen(['grep', '%s' %iface], stdin=grep1.stdout, stdout=subprocess.PIPE)
grep1.stdout.close()
awk1 = subprocess.Popen("awk '{print $2}'", shell=True, stdin=grep2.stdout, stdout=subprocess.PIPE)
grep2.stdout.close()
awk2 = subprocess.Popen(['awk', '-F', '/', '{print $1}'], stdin=awk1.stdout, stdout=subprocess.PIPE)
awk1.stdout.close()
ipaddr = awk2.communicate()[0].strip()
ipoct = ipaddr.split('.')
firstoct = ipoct[0]
secondoct = ipoct[1]
thirdoct = ipoct[2]
fourthoct = ipoct[3]
print firstoct + "." + secondoct + "." + thirdoct + "." + fourthoct
<file_sep>#!/usr/bin/env python
import subprocess
command1 = subprocess.Popen('ip addr', shell=True, stdout=subprocess.PIPE)
grep1 = subprocess.Popen('grep BROADCAST,MULTICAST,UP,LOWER_UP'.split(), stdin=command1.stdout, stdout=subprocess.PIPE)
command1.stdout.close()
awk1 = subprocess.Popen(['awk','-F',':','{print $2}'], stdin=grep1.stdout, stdout=subprocess.PIPE)
grep1.stdout.close()
ipadd = awk1.communicate()[0].strip()
command1 = subprocess.Popen(['ip','addr','show','%s' %ipadd], stdout=subprocess.PIPE)
grep2 = subprocess.Popen('grep -w inet'.split(), stdin=command1.stdout, stdout=subprocess.PIPE)
command1.stdout.close()
awk2 = subprocess.Popen(['awk','{print $2}'], stdin=grep2.stdout, stdout=subprocess.PIPE)
grep2.stdout.close()
awk3 = subprocess.Popen(['awk','-F','/','{print $1}'], stdin=awk2.stdout, stdout=subprocess.PIPE)
awk2.stdout.close()
ip = awk3.communicate()[0].strip()
ipoct = ip[:ip.rfind(".")] + "."
for i in range(1,10):
print "IP %s%s" %(ipoct,i)
subprocess.call('ping -c 1 %s%s' %(ipoct,i), shell=True)
print " "
<file_sep>#!/usr/bin/env python
import re
line = "Nov 4 00:02:40 shirazk2141 sshd[13506]: Invalid user jira from 172.16.58.3"
match = re.search('^(.*?)\s\d{2}\:\d{2}\:\d{2}\s\w+\ssshd.*?user\s(\w+)\sfrom\s(.*$)', line)
print match.groups()
print match.group(1)
print match.group(2)
print match.group(3)
<file_sep>#!/usr/bin/env python
from pyfirmata import Arduino, OUTPUT, INPUT, util
from time import sleep
import os
port = '/dev/ttyUSB0'
board = Arduino(port)
it = util.Iterator(board)
it.start()
board.digital[13].mode = OUTPUT
analogpin = board.get_pin('a:0:i')
try:
while True:
sleep(.006) # added due to pindata has nonetype value
pindata = analogpin.read()
print pindata
except KeyboardInterrupt:
board.exit()
os._exit()
<file_sep>#!/usr/bin/env python
import csv
filename = "storelist.csv"
with open (filename, "r") as f:
# readr = csv.reader(f, delimiter=",")
# for i in readr:
# print i[0],i[1],i[2]
firstcolumn = [line.split(',') for line in f]
for i in firstcolumn:
print i[0],i[1],i[2]
f.close()
# With output write on a file
#!/usr/bin/env python
filewrite = open("stores","w")
with open ("storelist.csv","r") as f:
storeno = [line.split(',') for line in f]
for i in storeno:
filewrite.write(i[0] + "\n") # Write 1 column
filewrite.write(i[0] + " " + i[1] + "\n") # Write multiple columns
filewrite.close()
# Add columns and write to file
#!/usr/bin/env python
new = open("shit.csv", "w")
with open("storelist.csv","ro")as f:
ff = [line.split(' ')[0] for line in f]
for i in ff:
w = i.strip()
new.write (w + "," + "Manila" + "," + "mycompany" + "\n")
new.close()
<file_sep>#!/usr/bin/env python
import subprocess
command = subprocess.Popen('/bin/netstat -r'.split(), stdout=subprocess.PIPE)
pipe1 = subprocess.Popen('grep default'.split(), stdin=command.stdout, stdout=subprocess.PIPE)
command.stdout.close()
pipe2 = subprocess.Popen(['awk','{print $8}'], stdin=pipe1.stdout, stdout=subprocess.PIPE)
pipe1.stdout.close()
iface = pipe2.stdout.read()
output = pipe2.communicate()[0]
command2 = subprocess.Popen("/sbin/ifconfig %s" %iface, shell=True, stdout=subprocess.PIPE)
print command2.stdout.read()
<file_sep>#!/usr/bin/env python
from pyfirmata import Arduino, util
from time import sleep
import os
port = '/dev/ttyUSB0'
board = Arduino(port)
sleep(2)
it = util.Iterator(board)
it.start()
analog0 = board.get_pin('a:0:i')
analog1 = board.get_pin('a:1:i')
analog2 = board.get_pin('a:2:i')
digital9 = board.get_pin('d:9:p')
digital10 = board.get_pin('d:10:p')
digital11 = board.get_pin('d:11:p')
def rgbcolor(red, green, blue):
digital9.write(red)
digital10.write(blue)
digital11.write(green)
try:
while True:
sleep(.020)
analog_0 = analog0.read()
analog_1 = analog1.read()
analog_2 = analog2.read()
rgbcolor(analog_0,analog_1,analog_2)
except KeyboardInterrupt:
board.exit()
os._exit
<file_sep>#!/usr/bin/env python
import csv
filename = "drivers.csv"
with open(filename) as file_handle:
reader = csv.reader(file_handle,delimiter=",")
for i in reader:
hardware = i[3].strip()
if hardware == "Display":
print i[0]+i[1]+i[3]+i[4]+i[5]+i[6]
<file_sep>#!/usr/bin/env python
import pyfirmata
from time import sleep
def blinkled(pin):
board.digital[pin].write(1)
sleep(1)
board.digital[pin].write(0)
sleep(1)
port = "/dev/ttyUSB0"
board = pyfirmata.Arduino(port)
it = pyfirmata.util.Iterator(board)
it.start()
buttonpin = board.get_pin('d:3:i')
yellowpin = 13
redpin = 6
while True:
value=buttonpin.read()
print (value)
if value is True:
blinkled(yellowpin)
else:
blinkled(redpin)
board.exit()
<file_sep>import urllib
from bs4 import BeautifulSoup
url = "http://labfiles.linuxacademy.com/python/scraping/courses.html"
html_data = urllib.urlopen(url).read()
soup = BeautifulSoup(html_data,"lxml")
sections = soup.find_all('a', attrs={'class':'col-xs-12 p-x-0 library-content-box-container content-aws'})
for section in sections:
title = section.find('span', attrs={"class":"library-content-title"})
length = section.find('span', attrs={"class":"library-content-length"})
url = section['href']
html_data = urllib.urlopen(url).read()
# soup2 = BeautifulSoup(html_data, "lxml")
# instructor = soup2.find_all('span', attrs={"class":"instructor-name"})
instructor = BeautifulSoup(html_data,"lxml").find_all('span', attrs={"class":"instructor-name"})
print title.text + instructor[0].text + length.text
<file_sep>>>> line = "Oct 6 23:59:32 campBIGfalcon sshd[945]: Server listening on 0.0.0.0 port 22."
>>> print line
Oct 6 23:59:32 campBIGfalcon sshd[945]: Server listening on 0.0.0.0 port 22.
>>> import re
>>> match = re.search('sshd', line)
>>> print match
<_sre.SRE_Match object at 0x233c2a0>
>>> match = re.search('hello', line)
>>> print match
None
>>> match = re.search('[A-Z][a-z]{2}\s{1,2}\d{1,2}\s\d{2}:\d{2}:\d{2}\s\w+\ssshd\[\d*\]: Server listening on \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\ port \d*', line)
>>> print match
<_sre.SRE_Match object at 0x233c308>
>>> match = re.search('[A-Z][a-z]{2}\s{1,2}\d{1,2}\s\d{2}:\d{2}:\d{2}\s\w+\ssshd\[\d*\]: Server listening on \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\ port', line)
>>> print match
<_sre.SRE_Match object at 0x233c370>
>>> match = re.search('[A-Z][a-z]{2}\s{1,2}\d{1,2}\s\d{2}:\d{2}:\d{2}\s\w+\ssshd\[\d*\]: Server listening on \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\ port \d*', line)
>>> print match
<_sre.SRE_Match object at 0x233c308>
>>> match = re.search('^(.*?)\s(\w+)\ssshd.*?on\s(.*?)\sport.*$', line)
>>> print match
<_sre.SRE_Match object at 0x7fa199d2aa48>
>>> print match.groups()
('Oct 6 23:59:32', 'campBIGfalcon', '0.0.0.0')
>>> print match.group(1)
Oct 6 23:59:32
>>> print match.group(2)
campBIGfalcon
>>> print match.group(3)
0.0.0.0
<file_sep>#!/usr/bin/env python
from pyfirmata import Arduino
from time import sleep
import os
port = '/dev/ttyUSB0'
board = Arduino(port)
def motorun(speed,ti):
motorpin.write(speed)
sleep(ti)
motorpin.write(0)
motorpin = board.get_pin('d:3:p')
try:
while True:
run = input("Input Speed: ")
if (run >= 100) or (run <=0):
print "Values from 0 to 100 only."
board.exit()
break
t = input("Time in sec: ")
motorun(run,t)
except KeyboardInterrupt:
board.exit()
os._exit
|
a05f9ad2e714579bf6501978129d1173edcdebff
|
[
"Python"
] | 19
|
Python
|
tixsalvador/py
|
4efbf3f77282c7a410d901c5f7de8e1ea358cd8a
|
11fd38e2ca9a0c858a24bf925465b24570af0cc7
|
refs/heads/main
|
<file_sep>from tkinter import *
# from macosx import *
root=Tk()
root.title("Dictionary")
root.geometry("600x400")
label_of_mutable = Label(root)
label_of_immutable = Label(root)
label_of_tkinter = Label(root)
dictionary = {'Mutable': 'Values can be changed just like a list',
'Immutable': 'Values can not be changed just like a tuple',
'Tkinter': 'it is the GUI library of python'}
def mutable():
label_of_mutable["text"] = dictionary['Mutable']
def immutable():
label_of_immutable['text'] = dictionary['Immutable']
def tkinter():
label_of_tkinter["text"] = dictionary['Tkinter']
button_mutable= Button(root , text = "Meaning of Mutable",command = mutable)
button_mutable.place(relx = 0.5, rely =0.2, anchor = CENTER)
label_of_mutable.place(relx = 0.5, rely =0.3, anchor = CENTER)
button_immutable= Button(root , text = "Meaning of Immutable",command = immutable)
button_immutable.place(relx = 0.5, rely =0.4, anchor = CENTER)
label_of_immutable.place(relx = 0.5, rely =0.5, anchor = CENTER)
button_tkinter= Button(root , text = "Meaning of Tkinter",command = tkinter)
button_tkinter.place(relx = 0.5, rely =0.6, anchor = CENTER)
label_of_tkinter.place(relx = 0.5, rely =0.7, anchor = CENTER)
root.mainloop()
|
1b95f20374fb651174010b9bfe46f441aa991eff
|
[
"Python"
] | 1
|
Python
|
JashnaO/Project_155
|
2dcf6a0a6bf439e22d19c79f2959644a91e94a29
|
f63c54ff70496c2be04c473724babfed17db94f5
|
refs/heads/master
|
<repo_name>Unleashed97/portfolio-test<file_sep>/js/slider.js
// https://github.com/kenwheeler/slick
$('#worksSlider').slick({
infinite: true,
slidesToShow: 1,
slidesToScroll: 1,
fade: true,
arrows: false,
dots: true,
});
$('.modal-work__btn--prev').on('click', function(event)
{
event.preventDefault();
$('#worksSlider').slick("slickPrev");
});
$('.modal-work__btn--next').on('click', function(event)
{
event.preventDefault();
$('#worksSlider').slick("slickNext");
});
<file_sep>/js/lang.js
// header language switch
//footer language switch
let mainBlock = document.querySelector('.footer-lang__main');
let drop = document.querySelector('.footer-lang__dropdown');
let toggleDrop = () =>
{
drop.classList.toggle('show');
}
mainBlock.addEventListener('click', e =>
{
e.stopPropagation();
toggleDrop();
});
document.addEventListener('click', e =>
{
let target = e.target;
let its_mainBlock = target == mainBlock;
let its_drop = target == drop || drop.contains(target);
let drop_showed = drop.classList.contains('show');
if(!its_mainBlock && !its_drop && drop_showed)
{
toggleDrop();
}
});
<file_sep>/README.md
# portfolio-test
simple portfolio
<file_sep>/js/mobile-nav.js
// let btnMenu = document.getElementById("nav-toggle");
// let nav = document.getElementById("nav");
// btnMenu.onclick = function (event)
// {
// event.preventDefault();
// nav.classList.toggle("show");
// if(nav.classList.contains('show')) document.body.classList.add("no-scroll");
// else document.body.classList.remove("no-scroll");
// }
let btnMenu = document.getElementById("nav-toggle");
let nav = document.getElementById("nav");
btnMenu.onclick = function (event)
{
event.preventDefault();
nav.classList.toggle("show");
btnMenu.classList.toggle("open")
if(nav.classList.contains('show')) document.body.classList.add("no-scroll");
else document.body.classList.remove("no-scroll");
}
<file_sep>/js/filter-works.js
let filter = document.getElementById('menu');
let content = document.querySelectorAll('[data-cat]');
filter.onclick = function(event)
{
let target = event.target;
event.preventDefault();
if(target.getAttribute('data-filter'))
{
let cat = target.getAttribute('data-filter');
for(let i=0; i<content.length; i++)
{
let catContent = content[i].getAttribute('data-cat');
if(catContent != cat)
{
content[i].classList.add('hide');
}
else content[i].classList.remove('hide');
}
if(cat == 'all')
{
for(let i=0; i<content.length; i++)
{
content[i].classList.remove('hide');
}
}
}
}
|
1a0c8a474338b2e577d03c810df8cecbc88cb136
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
Unleashed97/portfolio-test
|
4c0ac631933dadc37019c43fca10fadfc7cfc4c6
|
c570b4c4253d0557c077debff9972ddbd374bd2f
|
refs/heads/master
|
<file_sep>/**
This program is a representation of a Vertical Histogram
Author : <NAME>
*/
#include <stdio.h>
#include <string.h>
void main()
{
char a[100]="<NAME>";
int l=strlen(a);
int freq[26]; // array to store the frequency of each letter in the string a
for(int i=0;i<26;i++)
{
freq[i]=0;
}
for(char i='A';i<='Z' ;i++)
{
for(int j=0;j<l;j++)
{
if(a[j]==i || a[j]==i+32) //the frequency is stored for both uppercase and lowercase letters
{
freq[i-'A']++;
}
}
}
int max=freq[0];
for(int i=0;i<26;i++) // Calculates the maximum frequency in the frequency array as it will be required to
{ // y=triangulate the height of the histogram
max=(max<freq[i])?freq[i]:max;
}
printf("The sentence in consideration is - %s\n",a);
for(int i=1;i<=max;i++) // Main loop responsible for printing the histogram the way it's printed
{
for(int j=0;j<26;j++)
{
if(freq[j]==(max-i+1))
{
printf("*");
freq[j]--;
}
else
{
printf(" ");
}
}
printf("\n");
}
for(char q='A';q<='Z';q++) // This is responsible for printing the x-axis i.e. the base of the histogram
{
printf("%c",q);
}
printf("\n");
for(char q='a';q<='z';q++) // This is responsible for printing the x-axis i.e. the base of the histogram
{
printf("%c",q);
}
}
<file_sep># Vertical_Histogram
This program aims to display the frequency of the alphabets in a sentence or a portion of text
|
5f2c0ac8e793c0203d0d4b342e486b82cd977e2c
|
[
"Markdown",
"C"
] | 2
|
C
|
mishrraG/Vertical-histogram
|
d1af40313f0fd29326a81b8c090c1e6b9ffd7d19
|
ab7861b736bec29f69068bdf47bcfa3b2e66d30c
|
refs/heads/master
|
<repo_name>hcnode/getSelector.js<file_sep>/spec/getSelectorSpec.js
describe('getSelector', function(){
var iframe = document.createElement('iframe');
iframe.style.position = 'absolute';
iframe.style.top = '-999px';
iframe.style.left = '-999px';
beforeEach(function(){
if (!iframe.contentDocument){
document.body.appendChild(iframe);
var d = iframe.contentDocument;
d.open();
d.write('<!DOCTYPE html><body></body>');
d.close();
}
});
// A custom attribute 'selectthis' is added to the element to be selected.
var tests = [
{
it: 'should get the ID',
selector: '#test',
html: '<div id="test" selectthis></div>'
},
{
it: 'should get the ID with tag name when there are multiple same IDs',
selector: "div[id='test']",
html: '<p id="test"></p><div id="test" selectthis></div>'
},
{
it: 'should get the class',
selector: 'div.test',
html: '<div class="test" selectthis></div>'
},
{
it: 'should get the first div element',
selector: 'div:first-child',
html: '<div selectthis></div><div></div><div></div>'
},
{
it: 'should get the last div element',
selector: 'div:last-child',
html: '<div></div><div></div><div selectthis></div>'
},
{
it: 'should get the second div element',
selector: 'div:nth-child(2)',
html: '<div></div><div selectthis></div><div></div>'
},
{
it: 'should ignore multiple same IDs and get the second div element',
selector: 'div:nth-child(2)',
html: '<div id="test"></div><div id="test" selectthis></div><div id="test"></div>'
},
{
it: 'should ignore multiple same classes and get the second div element',
selector: 'div:nth-child(2)',
html: '<div class="test"></div><div class="test" selectthis></div><div class="test"></div>'
},
{
it: 'should get the ID and class together if element has both',
selector: "div[id='test'].test",
html: '<div id="test"></div><div class="test"></div><div id="test" class="test" selectthis></div>'
},
{
it: 'should traverse and get the child div',
selector: 'div>div',
html: '<div><div selectthis></div></div>'
},
{
it: 'should get the unique (least popular) class',
selector: 'div.b',
html: '<div class="a"></div><div class="a b c" selectthis></div><div class="c"></div>'
},
{
it: 'should get the a element "href" with hash',
selector: "a[href='#test']",
html: '<a href="#test" selectthis></a>'
},
{
it: 'should get the a element "href" with file name',
selector: "a[href*='test.html']",
html: '<a href="http://test.com/test.html?test=1" selectthis></a>'
},
{
it: 'should get the a element "href" with hostname',
selector: "a[href*='test.com']",
html: '<a href="http://test.com/test1/test2?test=1" selectthis></a>'
},
{
it: 'should get the a element "href" with pathname',
selector: "a[href*='/test1/test2']",
html: '<a href="http://test.com/"></a><a href="http://test.com/test1/test2" selectthis></a>'
},
{
it: 'should get the img element "src" with filename',
selector: "img[src*='test.png']",
html: '<img src="http://test.com/test.png?test=1" selectthis>'
},
{
it: 'should get the input element with "name"',
selector: "input[name='test']",
html: '<input name="test" selectthis>'
},
{
it: 'should get the button element with "name"',
selector: "button[name='test']",
html: '<button name="test" selectthis></button>'
},
{
it: 'should get the select element with "name"',
selector: "select[name='test']",
html: '<select name="test" selectthis></select>'
},
{
it: 'should get the textarea element with "name"',
selector: "textarea[name='test']",
html: '<textarea name="test" selectthis></textarea>'
},
{
it: 'should get the label element with "for"',
selector: "label[for='test']",
html: '<label for="test" selectthis></label>'
},
{
it: 'should get the ID, escaped',
selector: "#\\#♥©\\{\\}“‘’”\\\'\\?\\@\\.\\:\\(\\)\\<\\>\\{\\}\\+-\\\\\\/\\[\\]\\_\\~",
html: '<div id="#♥©{}“‘’”\'?@.:()<>{}+-\\/[]_~" selectthis></div>'
},
{
it: 'should get the ID with tag name when there are multiple same IDs, escaped',
selector: "div[id='\\#♥©\\{\\}“‘’”\\\'\\?\\@\\.\\:\\(\\)\\<\\>\\{\\}\\+-\\\\\\/\\[\\]\\_\\~']",
html: '<p id="#♥©{}“‘’”\'?@.:()<>{}+-\\/[]_~"></p><div id="#♥©{}“‘’”\'?@.:()<>{}+-\\/[]_~" selectthis></div>'
},
{
it: 'should get the class, escaped',
selector: "div.\\#♥©\\{\\}“‘’”\\\'\\?\\@\\.\\:\\(\\)\\<\\>\\{\\}\\+-\\\\\\/\\[\\]\\_\\~",
html: '<div class="#♥©{}“‘’”\'?@.:()<>{}+-\\/[]_~" selectthis></div>'
}
];
tests.forEach(function(test){
var selector = test.selector;
it(test.it + ' - ' + selector, function(){
var d = iframe.contentDocument;
d.body.innerHTML = test.html;
expect(getSelector(d.querySelector('[selectthis]'))).toEqual(selector);
});
});
});<file_sep>/getSelector.js
// getSelector.js (c) 2011, <NAME>. Licensed under the MIT license.
module.exports = (function(d){
if (!d.querySelector) return function(){};
// https://github.com/mathiasbynens/mothereffingcssescapes
function cssEscape(str) {
var firstChar = str.charAt(0),
result = '';
if (/^-+$/.test(str)){
return '\\-' + str.slice(1);
}
if (/\d/.test(firstChar)){
result = '\\3' + firstChar + ' ';
str = str.slice(1);
}
result += str.split('').map(function(chr){
if (/[\t\n\v\f]/.test(chr)){
return '\\' + chr.charCodeAt().toString(16) + ' ';
}
return (/[ !"#$%&'()*+,./:;<=>?@\[\\\]^_`{|}~]/.test(chr) ? '\\' : '') + chr;
}).join('');
return result;
}
function qsm(str, el){ // querySelector match
return d.querySelector(str) === el;
};
return function(el){
if (!el) return;
if (d !== el.ownerDocument) d = el.ownerDocument;
var originalEl = el,
selector = '';
do {
var tagName = el.tagName;
if (!tagName || /html|body|head/i.test(tagName)) return '';
tagName = tagName.toLowerCase();
var id = el.id,
className = el.className.trim(),
classList = el.classList || className.split(/\s+/);
// Select the ID, which is supposed to be unique.
// If there are multiple elements with the same ID, only first will be selected.
if (id){
id = cssEscape(id);
var s = '#' + id + selector;
if (qsm(s, originalEl)) return s;
s = tagName + "[id='" + id + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// If there's no ID or has multiple elements with same ID, select the className.
// Some authors use "unique" classes, like IDs, so use it.
// If one element contains multiple classes, choose the least popular class name.
var uniqueClass;
if (className){
var uniqueClassCount = Infinity;
for (var i=0, l=classList.length; i<l; i++){
var c = classList[i],
count = d.getElementsByClassName(c).length;
if (count < uniqueClassCount){
uniqueClassCount = count;
uniqueClass = cssEscape(c);
}
}
var s = tagName + '.' + uniqueClass + selector;
if (qsm(s, originalEl)) return s;
// If className can't work and the element has an ID, try combine both.
// Eg: div[id*='id'].class
if (id){
s = tagName + "[id='" + id + "']." + uniqueClass + selector;
if (qsm(s, originalEl)) return s;
}
}
// If ID and className fails, try get something "unique" from the element
switch (tagName){
case 'a':
var href = el.getAttribute('href'),
s;
// URL hash
var hash = el.hash;
if (hash){
s = tagName + "[href='" + hash + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// URL filename
var pathname = el.pathname || '',
filename = (pathname.match(/\/([^\/]+\.[^\/\.]+)$/i) || [, ''])[1];
if (filename){
s = tagName + "[href*='" + filename + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// URL hostname
var hostname = el.hostname;
if (hostname){
s = tagName + "[href*='" + hostname + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// "short" URL pathname, ignore the longer ones (50 chars max)
if (pathname && pathname.length <= 50){
s = tagName + "[href*='" + pathname + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'img':
var src = el.getAttribute('src'),
pathname = (function(src){
var a = d.createElement('a');
a.href = src;
var pathname = a.pathname;
a = null;
return pathname;
})(src),
filename = (pathname.match(/\/([^\/]+\.[^\/\.]+)$/i) || [, ''])[1];
if (filename){
var s = tagName + "[src*='" + filename + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'input':
case 'button':
case 'select':
case 'textarea':
var name = el.getAttribute('name');
if (name){
var s = tagName + "[name='" + name + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'label':
var _for = el.getAttribute('for');
if (_for){
var s = tagName + "[for='" + _for + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
}
// Select the nth-child if all above fails.
var siblings = el.parentNode.children,
siblingsLength = siblings.length,
index = 0,
theOnlyType = true;
for (var i=0, l=siblings.length; i<l; i++){
var sibling = siblings[i];
if (sibling === el){
index = i+1;
} else if (sibling.tagName.toLowerCase() == tagName){
theOnlyType = false;
}
}
// See if the there are siblings and if there's not only one "type" (tagName) that's the same as selected element.
// Eg: <a><b><c> = only one type; <a><b><b><c><b> = three types
// Also, intelligently use first-child or last-child.
if (siblingsLength>1 && !theOnlyType){
var pseudoChild;
if (index == 1){
pseudoChild = ':first-child';
} else if (index == siblingsLength){
pseudoChild = ':last-child';
} else {
pseudoChild = ':nth-child(' + index + ')';
}
selector = tagName + pseudoChild + selector;
if (qsm(selector, originalEl)) return selector;
} else { // Last step, clean up before traversing to the parent level
if (id){
selector = tagName + "[id='" + id + "']" + selector;
} else if (uniqueClass){
selector = tagName + '.' + uniqueClass + selector;
} else {
selector = tagName + selector;
if (qsm(selector, originalEl)) return selector;
}
}
} while((el = el.parentNode) && (selector = '>' + selector));
return selector;
};
})(window.document);
<file_sep>/README.md
getSelector.js
==============
getSelector.js provides a simple function to get the **shortest possible** CSS selector path of an element.
Example
-------
Here's some HTML:
<!DOCTYPE html>
<div id="container">
<ul>
<li>1</li>
<li>2</li><!-- second 'li' here -->
<li>3</li>
</ul>
</div>
... and for some reason, your JavaScript code has a variable reference to the second `<li>` tag (let's call it the `el` variable). You can get the CSS selector path to it by calling the `getSelector` function:
getSelector(el); // Returns "li:nth-child(2)"
It's that simple.
Supported & Tested Browsers
-----------------------------
getSelector.js should work on browsers that support [`querySelector`](https://developer.mozilla.org/En/DOM/Document.querySelector), [`getElementsByClassName`](https://developer.mozilla.org/en/DOM/document.getElementsByClassName) and [`String.trim`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/trim), which *probably* includes:
- Chrome 4+
- Firefox 3.5+
- Internet Explorer 9+
- Opera 10.5+
- Safari 5+
**But**, currently it's only tested on:
- Chrome 14+
- Firefox 7+
License
-------
Licensed under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
|
6f5ea26575c02effe4f1309b1c1d5a5507f16271
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
hcnode/getSelector.js
|
d5fff3eb4191538525fd413fdfcf09de1824d09f
|
957f6444b6273fb9f5676d8e1f74b0fcf19b8f87
|
refs/heads/master
|
<repo_name>JaonLin/Insanity-Framework<file_sep>/enc.py
#!/usr/bin/env python
# -.- coding: utf-8 -.-
# Copyright 2017 Insanity Framework (IF)
# Written by: * <NAME> - 4w4k3
# https://github.com/4w4k3/Insanity-Framework
# Licensed under the BSD-3-Clause
from Crypto.Cipher import AES
from base64 import b64encode
import string
import random
import time, os, sys
abc = ''.join(random.sample((string.ascii_uppercase+string.digits),32))
BLOCO = 32
PAD = '@'
def skdbksalnksancas(abdasbdio, chave):
extra = (BLOCO - len(abdasbdio)) % BLOCO
aes = AES.new(chave, AES.MODE_ECB)
cript = aes.encrypt(abdasbdio + PAD * extra)
return b64encode(cript)
def beirfwihfsajps(path, output, chave):
sahdvowhiohqwrqw = open(path, 'r')
abdasbdio = sahdvowhiohqwrqw.read()
abdasbdio_cifrado = skdbksalnksancas(abdasbdio, chave)
payload = "from Crypto.Cipher import AES\n"
payload += "from base64 import b64decode\n"
payload += "from time import sleep\n"
payload += "sleep(30)\n"
payload += "aes = AES.new('%s', AES.MODE_ECB)\n" % chave
payload += "exec(aes.decrypt(b64decode('%s')).rstrip('%s'))" % (abdasbdio_cifrado, PAD)
andasndaasa = open(output, 'w')
andasndaasa.write(payload)
sahdvowhiohqwrqw.close()
andasndaasa.close()
def run():
a1 = 'Templates/Insane.py'
a2 = 'Templates/insane_enc.py'
beirfwihfsajps(a1, a2, abc)
run()
<file_sep>/striker.py
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
# Copyright 2017 Insanity Framework (IF)
# Written by: * <NAME> - 4w4k3
# https://github.com/4w4k3/Insanity-Framework
# Licensed under the BSD-3-Clause
from socket import *
import os
import sys
import base64
from time import sleep
if not os.geteuid() == 0:
sys.exit('Insanity must be run as root')
HOST = ''
PORT = int(raw_input('Tʏᴘᴇ ᴛʜᴇ ᴘᴏʀᴛ: '))
BLUE, RED, WHITE, YELLOW, BOLD, GREEN, END = '\33[94m', '\033[91m', '\33[97m', '\33[93m', '\033[1m', '\033[1;32m', '\033[0m'
def clear():
os.system('clear')
def heading():
sys.stdout.write(RED + '''
.o oOOOOOOOo OOOo
Ob.OOOOOOOo OOOo. oOOo. .adOOOOOOO
OboO"""""""""""".OOo. .oOOOOOo. OOOo.oOOOOOo.."""""""""'OO
OOP.oOOOOOOOOOOO "POOOOOOOOOOOo. `"OOOOOOOOOP,OOOOOOOOOOOB'
`O'OOOO' `OOOOo"OOOOOOOOOOO` .adOOOOOOOOO"oOOO' `OOOOo
.OOOO' `OOOOOOOOOOOOOOOOOOOOOOOOOO' `OO
OOOOO '"OOOOOOOOOOOOOOOO"` oOO
oOOOOOba. .adOOOOOOOOOOba .adOOOOo.
oOOOOOOOOOOOOOba. .adOOOOOOOOOO@^OOOOOOOba. .adOOOOOOOOOOOO
OOOOOOOOOOOOOOOOO.OOOOOOOOOOOOOO"` '"OOOOOOOOOOOOO.OOOOOOOOOOOOOO
"OOOO" "YOoOOOOMOIONODOO"` . '"OOROAOPOEOOOoOY" "OOO"
Y 'OOOOOOOOOOOOOO: .oOOo. :OOOOOOOOOOO?' :`
: .oO%OOOOOOOOOOo.OOOOOO.oOOOOOOOOOOOO? .
. oOOP"%OOOOOOOOoOOOOOOO?oOOOOO?OOOO"OOo
'%o OOOO"%OOOO%"%OOOOO"OOOOOO"OOO':
`$" `OOOO' `O"Y ' `OOOO' o .
. . OP" : o .
: ʙʏ: ''' + WHITE + '''ᴀʟɪssᴏɴ ᴍᴏʀᴇᴛᴛᴏ(''' + RED + '''4ᴡ4ᴋ3''' + WHITE + ''')''' + RED + '''
-- [I]ɴsᴀɴɪᴛʏ [F]ʀᴀᴍᴇᴡᴏʀᴋ -- Version: 0.1
''' + END)
def pp():
sys.stdout.write(RED + '''
$u #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$~
$# `"$$$$$$$$$$$$$$$$$$$$$$$$$$| [PROPANE |$$$$$$$
$i $$$$$$$$$$$$$$$$$$$$$$$$$$| [NIGHTMARE |$$$$$$$$
$$ #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#$. $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#
$$ $iW$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$!
$$i $$$$$$$#"" `"""#$$$$$$$$$$$$$$$$$#""""""#$$$$$$$$$$$$$$$W
#$$W `$$$#" " !$$$$$` `"#$$$$$$$$$$#
$$$ `` ! !iuW$$$$$ #$$$$$$$#
#$$ $u $ $$$$$$$ $$$$$$$~
"# #$$i. # $$$$$$$. `$$$$$$
$$$$$i. """#$$$$i. .$$$$#
$$$$$$$$! . ` $$$$$$$$$i $$$$$
`$$$$$ $iWW .uW` #$$$$$$$$$W. .$$$$$$#
"#$$$$$$$$$$$$#` $$$$$$$$$$$iWiuuuW$$$$$$$$W
!#"" "" `$$$$$$$##$$$$$$$$$$$$$$$$
i$$$$ . !$$$$$$ .$$$$$$$$$$$$$$$#
$$$$$$$$$$` $$$$$$$$$Wi$$$$$$#"#$$`
#$$$$$$$$$W. $$$$$$$$$$$# ``
`$$$$##$$$$! i$u. $. .i$$$$$$$$$#""''' + WHITE + ''' InSaNiTy FrAmEwOrK''' + RED + '''
" `#W $$$$$$$$$$$$$$$$$$$` u$#
W$$$$$$$$$$$$$$$$$$ $$$$W
$$`!$$$##$$$$``$$$$ $$$$!
i$" $$$$ $$#"` """ W$$$$
''' + END)
clear()
heading()
def mess():
print '[*] Oᴘᴇʀᴀᴛɪᴏɴᴀʟ Sʏsᴛᴇᴍ: ' + data2
if vm == 'True':
print '[*] Vɪʀᴛᴜᴀʟ ᴍᴀᴄʜɪɴᴇ: {0}Dᴇᴛᴇᴄᴛᴇᴅ{1}'.format(RED, END)
else:
print '[*] Vɪʀᴛᴜᴀʟ ᴍᴀᴄʜɪɴᴇ: ɴᴏᴛ ᴅᴇᴛᴇᴄᴛᴇᴅ'
print '[*] Lᴏᴄᴀʟ ɪᴘ: ' + ip
# print '[*] Rᴇᴍᴏᴛᴇ Hᴏsᴛ: ' + oss
print '-{0} ᴛʏᴘᴇ ᴀ ʀᴇᴍᴏᴛᴇ sʜᴇʟʟ ᴄᴏᴍᴍᴀɴᴅ{1} - {0}[{1}ᴇx: ɪᴘᴄᴏɴꜰɪɢ{0}]{1}: '.format(BLUE, END)
print '- {0}ʀᴜɴ ᴀ ɪɴsᴀɴɪᴛʏ ᴍᴏᴅᴜʟᴇ{1} - {0}[{1}ᴠɪᴇᴡ ᴀᴠᴀɪʟᴀʙʟᴇ ᴍᴏᴅᴜʟᴇs ᴏɴ ʜᴇʟᴘ ᴍᴇssᴀɢᴇ{0}]{1}: '.format(BLUE, END)
print '-{0} ʜᴇʟᴘ {1}- {0}[{1}ᴠɪᴇᴡ ʜᴇʟᴘ ᴍᴇssᴀɢᴇ ᴀɴᴅ ᴍᴏᴅᴜʟᴇs{0}]{1}: '.format(BLUE, END)
s = socket(AF_INET, SOCK_STREAM)
print '[!] Wᴀɪᴛɪɴɢ ꜰᴏʀ ᴄᴏɴɴᴇᴄᴛɪᴏɴs '
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
print "[*] Lɪsᴛᴇɴɪɴɢ ᴏɴ: 0.0.0.0:%s" % str(PORT)
s.listen(10)
conn, addr = s.accept()
print '[*] Cᴏɴɴᴇᴄᴛɪᴏɴ: ' + '{0}ESTABLISHED{2}'.format(GREEN, WHITE, END)
data = conn.recv(1024)
ip = conn.recv(1024)
conn.send('whoami')
data2 = conn.recv(1024)
vm = conn.recv(1024)
#oss = conn.recv(1024)
mess()
def help():
print '''
- [I]ɴsᴀɴɪᴛʏ [F]ʀᴀᴍᴇᴡᴏʀᴋ -
ᴛʏᴘᴇ {0}ɪɴꜰᴏ{1} - {0}[{1}sʜᴏᴡ ɪɴꜰᴏ's ᴀʙᴏᴜᴛ ᴠɪᴄᴛɪᴍ{0}]{1}
ᴛʏᴘᴇ {0}ᴘᴇʀsɪsᴛᴇɴᴄᴇ{1} - {0}[{1}ᴇɴᴀʙʟᴇ ᴘᴇʀsɪsᴛᴇɴᴄᴇ{0}]{1}
ᴛʏᴘᴇ {0}sʜᴜᴛᴅᴏᴡɴ{1} - {0}[{1}ᴛᴜʀɴ ᴏꜰꜰ ʀᴇᴍᴏᴛᴇ ᴘᴄ{0}]{1}
ᴛʏᴘᴇ {0}ʀᴇsᴛᴀʀᴛ{1} - {0}[{1}ᴛᴜʀɴ ᴏꜰꜰ & ᴛᴜʀɴ ᴏɴ ʀᴇᴍᴏᴛᴇ ᴘᴄ{0}]{1}
ᴛʏᴘᴇ {0}ʙᴀᴄᴋ{1} - {0}[{1}ʀᴇᴛᴜʀɴ ᴛᴏ ᴍᴀɪɴ ᴍᴇɴᴜ{0}]{1}
ᴛʏᴘᴇ {0}ǫᴜɪᴛ{1} - {0}[{1}ᴛᴏᴏʟ ᴇxɪᴛ{0}]{1}
'''.format(BLUE, END)
# start loop
def main():
try:
while 1:
# enter shell command
header = ('{0}InSaNiTy{1} > {2}'.format(RED, WHITE, END))
command = raw_input(header)
if command.upper() == 'QUIT':
clear()
pp()
conn.close()
elif command.upper() == 'HELP':
help()
elif command.upper() == 'INFO':
mess()
elif command.upper() == 'BACK':
os.system('python2.7 insanity.py')
elif command.upper() == 'PERSISTENCE':
try:
conn.send('persistence')
print '[*] Pᴇʀsɪsᴛᴇɴᴄᴇ Mᴏᴅᴜʟᴇ Eɴᴀʙʟᴇᴅ'
except:
print '\n'
print '{0}ʀᴇᴍᴏᴛᴇ ʜᴏsᴛ ʜᴀs ʙᴇᴇɴ ᴅɪsᴄᴏɴɴᴇᴄᴛᴇᴅ{1} '.format(RED, END)
print '\n' + 'ᴛʏᴘᴇ {0}ʙᴀᴄᴋ{1} - {0}[{1}ʀᴇᴛᴜʀɴ ᴛᴏ ᴍᴀɪɴ ᴍᴇɴᴜ{0}]{1}'.format(BLUE, END)
print 'ᴛʏᴘᴇ {0}ǫᴜɪᴛ{1} - {0}[{1}ᴛᴏᴏʟ ᴇxɪᴛ{0}]{1}'.format(BLUE, END)
elif command.upper() == 'SHUTDOWN':
try:
conn.send('shutdown -s -t 00 -f')
except:
print '\n'
print '{0}ʀᴇᴍᴏᴛᴇ ʜᴏsᴛ ʜᴀs ʙᴇᴇɴ ᴅɪsᴄᴏɴɴᴇᴄᴛᴇᴅ{1} '.format(RED, END)
print '\n' + 'ᴛʏᴘᴇ {0}ʙᴀᴄᴋ{1} - {0}[{1}ʀᴇᴛᴜʀɴ ᴛᴏ ᴍᴀɪɴ ᴍᴇɴᴜ{0}]{1}'.format(BLUE, END)
print 'ᴛʏᴘᴇ {0}ǫᴜɪᴛ{1} - {0}[{1}ᴛᴏᴏʟ ᴇxɪᴛ{0}]{1}'.format(BLUE, END)
elif command.upper() == 'RESTART':
try:
conn.send('shutdown -r -t 00 -f')
except:
print '\n'
print '{0}ʀᴇᴍᴏᴛᴇ ʜᴏsᴛ ʜᴀs ʙᴇᴇɴ ᴅɪsᴄᴏɴɴᴇᴄᴛᴇᴅ{1} '.format(RED, END)
print '\n' + 'ᴛʏᴘᴇ {0}ʙᴀᴄᴋ{1} - {0}[{1}ʀᴇᴛᴜʀɴ ᴛᴏ ᴍᴀɪɴ ᴍᴇɴᴜ{0}]{1}'.format(BLUE, END)
print 'ᴛʏᴘᴇ {0}ǫᴜɪᴛ{1} - {0}[{1}ᴛᴏᴏʟ ᴇxɪᴛ{0}]{1}'.format(BLUE, END)
else:
try:
if command != '':
data = ''
conn.send(command)
try:
s.settimeout(5.0)
conn.settimeout(5.0)
data = conn.recv(4096)
print data
s.settimeout(None)
conn.settimeout(None)
except:
print '[*] ᴄᴏᴍᴍᴀɴᴅ ᴇxᴇᴄᴜᴛᴇᴅ'
except:
print '\n'
print '{0}ʀᴇᴍᴏᴛᴇ ʜᴏsᴛ ʜᴀs ʙᴇᴇɴ ᴅɪsᴄᴏɴɴᴇᴄᴛᴇᴅ{1} '.format(RED, END)
print '\n' + 'ᴛʏᴘᴇ {0}ʙᴀᴄᴋ{1} - {0}[{1}ʀᴇᴛᴜʀɴ ᴛᴏ ᴍᴀɪɴ ᴍᴇɴᴜ{0}]{1}'.format(BLUE, END)
print 'ᴛʏᴘᴇ {0}ǫᴜɪᴛ{1} - {0}[{1}ᴛᴏᴏʟ ᴇxɪᴛ{0}]{1}'.format(BLUE, END)
except KeyboardInterrupt:
clear()
pp()
conn.close()
if __name__ == '__main__':
main()
|
ad4872d0cc383568faffc71b07339dd5a9a5e3b8
|
[
"Python"
] | 2
|
Python
|
JaonLin/Insanity-Framework
|
00c021e92a8c03de696c270cc33166148022190e
|
943d5574e0107213dbdd41193c4ff86a2f65e583
|
refs/heads/master
|
<file_sep># optimal-exchange
Challenge for +Team application as a full stack developer
<file_sep>function getClosestCoins(num, set) {
let total = 0;
const coins = [];
while (total !== num) {
const abs = set.map((coin) => Math.abs(num - (total > num ? total - coin : total + coin)));
const coinIndex = abs.indexOf(Math.min(...abs));
coins.push(set[coinIndex]);
total = total > num ? total - set[coinIndex] : total + set[coinIndex];
}
return coins;
}
module.exports = {
getClosestCoins,
}
<file_sep>const fs = require('fs');
const utils = require('./utils/index.js');
const input = fs.readFileSync('../assets/input.txt', 'utf8');
const lines = input.split('\n');
const result = lines.reduce((obj, line, index) => {
const val = `line${index}`;
if (line.split(' ').length < 3) return { ...obj, testsQty: Number(line) };
const test = {
n: Number(line.split(' ')[0]),
k: Number(line.split(' ')[1]),
d: line.split(' ')
.slice(2)
.map((num) => Number(num))
.sort((a, b) => a - b),
};
return {
...obj,
tests: [ ...obj.tests, test ],
};
}, { testQty: 0, tests: [] });
|
153a7dfdb5b3e10e1617808b8bd4a4da28cbca2e
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
svictoreq/optimal-exchange
|
ea72d84a2f6c88e4c31634afedbf46baaa1c5feb
|
656c1fe2d4c259c1a4f4754c4aa98951253f238c
|
refs/heads/master
|
<file_sep>package com.person.yvan.test.threadPool;
public interface RunnableQueue {
// task queue : use for caching the tasks that have submitted to thread pool
void offer(Runnable runnable);
//work thread get Runnable by take method
Runnable take();
//get task count of task queue
int size();
}
<file_sep>package com.person.yvan.service;
import com.person.yvan.entity.User;
import java.util.List;
public interface UserService {
String getUserById(List<Integer> list);
Integer insertUser(User user);
void insertUser2(User user);
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.person.yvan</groupId>
<artifactId>TransactionDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TransactionDemo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java-version>1.8</java-version>
<servlet-version>2.5</servlet-version>
<junit-version>4.12</junit-version>
<springframework-version>4.3.5.RELEASE</springframework-version>
<mybatis-version>3.2.8</mybatis-version>
<mybatis-spring-version>1.2.2</mybatis-spring-version>
<mysql-version>5.1.38</mysql-version>
<druid-version>1.0.27</druid-version>
<commons-lang-version>2.6</commons-lang-version>
<commons-lang3-version>3.3.1</commons-lang3-version>
<commons-fileupload-version>1.3.2</commons-fileupload-version>
<commons-io-version>2.5</commons-io-version>
<commons-codec-version>1.10</commons-codec-version>
<commons-configuration-version>1.10</commons-configuration-version>
<commons-logging-version>1.2</commons-logging-version>
<slf4j-version>1.7.19</slf4j-version>
<log4j-version>1.2.17</log4j-version>
<fastjson-version>1.2.23</fastjson-version>
<shiro-version>1.3.2</shiro-version>
<quartz-version>2.2.3</quartz-version>
<kaptcha-version>0.0.9</kaptcha-version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>
<jstl-version>1.2</jstl-version>
<taglibs-version>1.1.2</taglibs-version>
<freemarker-version>2.3.23</freemarker-version>
<jedis-version>2.8.1</jedis-version>
<commons-pool2-version>2.2</commons-pool2-version>
<swagger-version>1.0.2</swagger-version>
<jackson-version>2.7.5</jackson-version>
<codehaus-version>1.9.4</codehaus-version>
<log4j2-version>2.10.0</log4j2-version>
<!-- redis依赖-->
<redis.version>2.9.0</redis.version>
<spring-data-redis-version>1.7.1.RELEASE</spring-data-redis-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.8.RELEASE</version>
<scope>test</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring-version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid-version}</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${springframework-version}</version>
</dependency>
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
</dependency>
<!--引入全新的log4j2 依赖jar包-->
<!-- <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2-version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2-version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.9.1</version>
</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>servlet-api</artifactId>-->
<!--<version>${servlet-version}</version>-->
<!--</dependency>-->
<!--redis依赖包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis-version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>TransactionDemo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<!-- 资源文件拷贝插件 -->
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>8</source><target>8</target></configuration></plugin></plugins>
</build>
</project>
<file_sep># TransactionDemo
creating the repository for Transaction
<file_sep>package com.person.yvan.test.threadPool;
public interface ThreadPool {
//submit task to thread pool
void execute(Runnable runnable);
//shutdown thread pool
void shutdown();
//get init size of thread pool
int getInitSize();
//get max size of thread pool
int getMaxSize();
//get core size of thread pool
int getCoreSize();
//get queue size of queue for caching the tasks
int getQueueSize();
//get active threads of thread pool
int getActiveCount();
//check if the thread pool is shutdown
boolean isShutdown();
}
<file_sep>package com.person.yvan.controller;
import com.person.yvan.entity.User;
import com.person.yvan.service.UserService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@Autowired
private static Logger logger = LogManager.getLogger(UserController.class);
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping(value = "/get",method = RequestMethod.GET)
public @ResponseBody String getUser(@RequestParam(value = "id") Integer id){
/*System.out.println("id:"+id);
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
String name = userService.getUserById(list);
System.out.println(name);
logger.info("name:"+name);*/
// redis
redisTemplate.opsForValue().set("name","tom");
System.out.print(redisTemplate.opsForValue().get("name"));
return "name";
}
@RequestMapping(value = "insert" , method = RequestMethod.GET)
public @ResponseBody Integer insertUser(@RequestParam(value = "id") Integer id){
System.out.println(333333);
User user = new User();
user.setId(9);
user.setName("yva3");
user.setAge(24);
user.setSex(1);
user.setAddress("123123123123");
return userService.insertUser(user);
}
@RequestMapping(value = "insert2" , method = RequestMethod.GET)
public @ResponseBody String insertUser2(@RequestParam(value = "id") Integer id){
System.out.println(333333);
User user = new User();
user.setId(9);
user.setName("yva3");
user.setAge(24);
user.setSex(1);
user.setAddress("123123123123");
userService.insertUser2(user);
return "1";
}
}
<file_sep>package com.person.yvan.test;
import java.util.ArrayDeque;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.lang.System.out;
public class test3 {
public static void main(String[] args){
/*ArrayDeque ad = new ArrayDeque(10);
out.println(ad);
ad.add(123);
ad.add(456);
ad.add(789);
out.println(ad.size());
out.println(ad.pollFirst());
out.println(ad.size());
ad.pop();
ad.push(22);
out.println(ad.peekLast());
out.println(ad.peekFirst());
int b = 0b11000;
out.println(b);
b = b >>> 2;
out.println(b);*/
Map<String,String> linkedHashMap = new LinkedHashMap<String, String>(10,0.75f,true);
linkedHashMap.put("NO1","小明");
linkedHashMap.put("NO2","小赵");
linkedHashMap.put("NO3","小周");
// 对NO1进行get操作
linkedHashMap.get("NO1");
System.out.println("----按访问顺序遍历LinkedHashMap----");
for(Map.Entry entry:linkedHashMap.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
<file_sep>package com.person.yvan.utils.redisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisTest {
@Autowired
RedisTemplate redisTemplate;
public static void main(String[] args){
}
}
|
5ab083e5799b58ac962bab7d72294fbd3ca23b15
|
[
"Markdown",
"Java",
"Maven POM"
] | 8
|
Java
|
gaoyuhub/TransactionDemo
|
cd7653b7d81351dcffd244775b66d656ea1114d8
|
68babf34be65e6a9db58a121e62b1238b079d898
|
refs/heads/main
|
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Test the manual framework on a simple example
"""
# ----- Libraries ----- #
#Utils
from torch import set_grad_enabled
set_grad_enabled(False)
#Ours
import datasets
import act_func as act
import loss
import layers
import modules
from lr_adapter import LearningRateAdapter
# ----- Parameters ----- #
N = 1000 #nb of dats in both train and test dataset
N_EPOCHS = 30 #nb of epoch for the train
eta0 = 1e-1 #initial learning rate
N_ITER = 10 #nb of iter to compute mean and std
AUTO_LR_REDUCE = True #enable auto lr updater
IMPROVEMENT_TH = 0.01 #min improvement th to increase counter
LR_RED = 0.5 #lr update factor
MAX_LR_CNT = 2 #value that the counter needs to reach before lr update
BOOL_SAVE = False #to save or not the data
VERBOSE = True #display information
# ----- Log tables ----- #
train_perf = [] #final perf train of each iter
test_perf = [] #fian perf test of each iter
train_perf_i_e = [] #perf train of each iter along epochs
test_perf_i_e = [] #perf test of each iter along epochs
# ----- Main ----- #
#repeat for stat info
for iter in range(N_ITER):
eta = eta0 # reset learning rate
#Get data
train_points, train_labels, test_points, test_labels = \
datasets.generate_circle_dataset(N)
train_perf_e = [] #perf train along epochs
test_perf_e = [] #perf test along epochs
#Define the network
seq = modules.Sequential()
seq.append(layers.FCLayer(2, 25, True))
seq.append(act.Tanh())
seq.append(layers.FCLayer(25, 25, True))
seq.append(act.Tanh())
seq.append(layers.FCLayer(25, 1, True))
seq.append(act.Sigmoid())
if VERBOSE and iter == 0:
seq.names()
#Define the lr adapter if needed
if AUTO_LR_REDUCE:
lr_adapter = LearningRateAdapter(eta0, IMPROVEMENT_TH, LR_RED, MAX_LR_CNT)
if VERBOSE:
print("\nIter: "+str(iter))
#Train the network
for epoch in range(N_EPOCHS): #for each epoch
err_train = 0
err_test = 0
for i in range(N): #for each point
#predict the output and backward the loss
pred_train = seq.forward(train_points[i, :])
seq.backward(loss.dMSE(pred_train.view(1, -1), \
train_labels[i].view(1, -1)))
seq.grad_step(eta)
#check performance
if (train_labels[i] and pred_train <= 0.5) \
or (not train_labels[i] and pred_train >= 0.5):
err_train += 1
pred_test = seq.forward(test_points[i, :])
if (test_labels[i] and pred_test <= 0.5) \
or (not test_labels[i] and pred_test >= 0.5):
err_test += 1
if epoch > 1 and AUTO_LR_REDUCE: #decrease eta if stagnation
improvement = (train_perf_e[epoch-1]-err_train/N)
eta = lr_adapter.step(improvement)
train_perf_e.append(err_train / N)
test_perf_e.append(err_test / N)
#Test the network
#on test
err_test = 0
for i in range(N): #for each point
#predict the output
pred_test = seq.forward(test_points[i, :])
#add errors
if (test_labels[i] and pred_test <= 0.5) \
or (not test_labels[i] and pred_test >= 0.5):
err_test += 1
#on train
err_train = 0
for i in range(N): #for each point
#predict the output
pred_train = seq.forward(train_points[i, :])
#add errors
if (train_labels[i] and pred_train <= 0.5) \
or (not train_labels[i] and pred_train >= 0.5):
err_train += 1
#save and print
train_perf.append(err_train / N)
test_perf.append(err_test / N)
train_perf_i_e.append(train_perf_e)
test_perf_i_e.append(test_perf_e)
if VERBOSE:
print("train epoch at {} = {:.2%}".format(epoch+1, err_train / N))
print("test error at epoch {} = {:.2%}".format(epoch+1, err_test / N))
#save in file
if BOOL_SAVE:
with open('train_perf.txt', 'w+') as f:
for val in train_perf:
f.write(str(val)+" ")
with open('test_perf.txt', 'w+') as f:
for val in test_perf:
f.write(str(val)+" ")
with open('train_perf_e.txt', 'w+') as f:
for l in train_perf_i_e:
for val in l:
f.write(str(val)+" ")
f.write("\n")
with open('test_perf_e.txt', 'w+') as f:
for l in test_perf_i_e:
for val in l:
f.write(str(val)+" ")
f.write("\n")
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Plot the results obtained by test.py
"""
# ----- Libraries ----- #
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
# ----- Constants ----- #
PATH = "pytorch"+"/"
# ----- Loading ----- #
test_e = np.genfromtxt(PATH+'test_perf_e.txt', delimiter=' ')
train_e = np.genfromtxt(PATH+'train_perf_e.txt', delimiter=' ')
test = np.genfromtxt(PATH+'test_perf.txt', delimiter=' ')
train = np.genfromtxt(PATH+'train_perf.txt', delimiter=' ')
# ----- Stats ----- #
test_e_m = np.mean(test_e,axis=0)
test_e_s = np.std(test_e,axis=0)
train_e_m = np.mean(train_e,axis=0)
train_e_s = np.std(train_e,axis=0)
test_m = np.mean(test)
test_s = np.std(test)
train_m = np.mean(train)
train_s = np.std(train)
# ----- Plot ----- #
#Plot normal perf
print("Mean train perf is "+str(train_m*100)+"% with std "+str(train_s*100)+"%")
print("Mean test perf is "+str(test_m*100)+"% with std "+str(test_s*100)+"%")
#Plot the evolution on all the epochs for each parameter
epochs_arr = np.arange(0, len(test_e_m))
plt.errorbar(epochs_arr, train_e_m,yerr=test_e_s, label="Train",capsize=5)
plt.errorbar(epochs_arr, test_e_m,yerr=test_e_s, label="Test", linestyle="--",capsize=5)
plt.title("Evolution of the error rate along epochs, with std")
plt.xlabel("Epoch")
plt.ylabel("Error rate")
plt.legend()<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Test the manual framework on a very simple example (code in the report)
"""
# ----- Libraries ----- #
import datasets, loss, layers, modules, act_func
# ----- Parameters ----- #
N = 1000 #nb of datas in both train and test dataset
N_EPOCHS = 30 #nb of epoch for the train
eta = 1e-1 #learning rate
# ----- Get the data ----- #
train_points, train_labels, test_points, test_labels = datasets.generate_circle_dataset(N)
# ----- Define the network ----- #
seq = modules.Sequential() #create the sequential
seq.append(layers.FCLayer(2, 25, True)) #add an FC layer with bias
seq.append(act_func.Tanh()) #add a Tanh layer
seq.append(layers.FCLayer(25, 25, True))
seq.append(act_func.Tanh())
seq.append(layers.FCLayer(25, 1, True))
seq.append(act_func.Sigmoid()) #add a Sigmoid layer
# ----- Train the network ----- #
for epoch in range(N_EPOCHS): #for each epoch
for i in range(N): #for each point
#predict the output and backward the loss
pred_train = seq.forward(train_points[i, :])
seq.backward(loss.dMSE(pred_train.view(1, -1), train_labels[i].view(1, -1)))
seq.grad_step(eta)
# ----- Test the network ----- #
err_test = 0
for i in range(N): #for each point
#predict the output
pred_test = seq.forward(test_points[i, :])
#add errors
if (test_labels[i] and pred_test <= 0.5) or (not test_labels[i] and pred_test >= 0.5):
err_test += 1
print("The error percentage is "+str(err_test*100/N)+"%")
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Plot a comparison btw results obtained by test.py
"""
# ----- Libraries ----- #
import numpy as np
import matplotlib.pyplot as plt
plt.close("all")
import sys
# ----- Parameters ----- #
PATHS = ["ours_no_lr/","pytorch/"]
NAMES = ["Ours (without lr update)","Pytorch"]
COLORS = ["green","blue","red","black"]
fig0, ax0 = plt.subplots()
for i in range(len(NAMES)):
if i > len(COLORS):
sys.exit("ADD COLORS TO COLORS")
# ----- Loading ----- #
test_e = np.genfromtxt(PATHS[i]+'test_perf_e.txt', delimiter=' ')
train_e = np.genfromtxt(PATHS[i]+'train_perf_e.txt', delimiter=' ')
test = np.genfromtxt(PATHS[i]+'test_perf.txt', delimiter=' ')
train = np.genfromtxt(PATHS[i]+'train_perf.txt', delimiter=' ')
# ----- Stats ----- #
test_e_m = np.mean(test_e,axis=0)
test_e_s = np.std(test_e,axis=0)
train_e_m = np.mean(train_e,axis=0)
train_e_s = np.std(train_e,axis=0)
test_m = np.mean(test)
test_s = np.std(test)
train_m = np.mean(train)
train_s = np.std(train)
# ----- Plot ----- #
#Plot normal perf
ax0.errorbar(i, test_m, yerr = test_s, capsize=10, label = "Test", color = "blue")
ax0.errorbar(i, train_m, yerr = train_s, capsize=10, label = "Train", color = "red")
#Plot the evolution on all the epochs for each parameter
plt.figure(2)
epochs_arr = np.arange(0, len(test_e_m))
plt.errorbar(epochs_arr, train_e_m,yerr=train_e_s, label=NAMES[i]+" (train)",capsize=5, color = COLORS[i])
plt.errorbar(epochs_arr, test_e_m,yerr=test_e_s, label=NAMES[i]+" (test)", linestyle="--",capsize=5, color = COLORS[i])
ax0.set_title("Error rate for different models, with std")
ax0.set_xlabel("Models")
ax0.set_ylabel("Error rate")
ax0.set_xticks(np.arange(len(NAMES)))
ax0.set_xticklabels(NAMES)
ax0.legend()
plt.figure(2)
plt.title("Evolution of the error rate along epochs, with std")
plt.xlabel("Epoch")
plt.ylabel("Error rate")
plt.legend()<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Define loss function for the network
"""
# ----- Libraries ----- #
#Utils
from torch import set_grad_enabled
set_grad_enabled(False)
def MSE(value, target):
#Compute the mean square error btw a given value tensor and a target tensor
return ((value - target)**2).sum()/value.shape[0]
def dMSE(value, target):
#Compute derivative of the mean square error btw a given tensor and a target tensor
return 2 * (value - target)/value.shape[0]<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Generate datasets for the NN to learn
"""
# ----- Libraries ----- #
import math
from torch import empty
from torch import set_grad_enabled
set_grad_enabled(False)
# ----- Constants ----- #
R = 1/math.sqrt(2*math.pi) #radius of the disk
X_OFF = 0.5 #disk X offset
Y_OFF = 0.5 #disk Y offset
# ----- Functions ----- #
def generate_circle_dataset(N=1000):
#generates a train and a test dataset with N points generated uniformly btw 0 and 1
#points outside of the disk centered at [0.5 0.5] with a radius 1/sqrt(2*pi)
#are classified as 0, the points inside (or on the boundary) as 1
#Create points
test_points = empty(N, 2).uniform_()
train_points = empty(N, 2).uniform_()
#Label the points
test_labels = (test_points[:,0]-X_OFF)**2+(test_points[:,1]-Y_OFF)**2 <= R**2
train_labels = (train_points[:,0]-X_OFF)**2+(train_points[:,1]-Y_OFF)**2 <= R**2
#Conver to float (needed for MSE computation)
test_labels = test_labels.type(test_points.dtype)
train_labels = train_labels.type(train_points.dtype)
return train_points, train_labels, test_points, test_labels
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Define activation functions for the NN implementation
"""
# ----- Libraries ----- #
from modules import Module
from torch import set_grad_enabled, empty
set_grad_enabled(False)
# ----- Activation definitions ----- #
#Tanh
class Tanh(Module):
#Applies the Tanh activation layer to the input tensor
def __init__(self):
self.name = "Tanh Activation Layer"
self.output = None
def forward(self, input):
self.output = input.tanh()
return self.output
def backward(self, gradwrtoutput):
return (1-self.output.tanh().pow(2))*gradwrtoutput
#ReLU
class ReLU(Module):
#Applies the ReLU activation layer to the input tensor
def __init__(self):
self.name = "ReLU Activation Layer"
self.output = None
def forward(self, input):
input[input<0] = 0
self.output = input
return self.output
def backward(self, gradwrtoutput):
out = empty(size=(self.output.shape))
out[self.output < 0] = 0
out[self.output >= 0] = 1
return out*gradwrtoutput
#Sigmoid
class Sigmoid(Module):
#Applies the Sigmoid activation layer to the input tensor
def __init__(self):
self.name = "Sigmoid Activation Layer"
self.output = None
def forward(self, input):
self.output = input.sigmoid()
return self.output
def backward(self, gradwrtoutput):
return self.output.sigmoid()*(1-self.output.sigmoid()) * gradwrtoutput
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Define the common strucutre for the different element of NN
"""
# ----- Libraries ----- #
#Utils
from torch import set_grad_enabled
set_grad_enabled(False)
# ----- Classes definition ----- #
#Basic Module
class Module(object):
#parent class for NN elements
def __init__(self):
self.name = "Basic Module"
def forward(self, input):
raise NotImplementedError
def backward(self, gradwrtoutput):
raise NotImplementedError
def param(self):
return []
def grad_step(self, eta):
return
#Sequential
class Sequential(Module):
#Sequential class to create sequential networks
def __init__(self):
self.name = "Sequential Structure"
self.layers = []
def append(self, layer):
self.layers.append(layer)
def forward(self, input):
for layer in self.layers:
input=layer.forward(input)
return input
def backward(self, gradwrtoutput):
for layer in self.layers[::-1]:
gradwrtoutput = layer.backward(gradwrtoutput)
return input
def grad_step(self, eta):
for layer in self.layers:
layer.grad_step(eta)
def param(self):
params = []
for layer in self.layers:
params.append(layer.param())
return params
def names(self):
print(self.name+" with "+str(len(self.layers))+" layers:")
for layer in self.layers:
print(layer.name)
print("\n")<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Implement an automatic learning rate adapter
"""
# ----- Libraries ----- #
#Utils
from torch import set_grad_enabled
set_grad_enabled(False)
# ----- Learning Rate adapter ----- #
class LearningRateAdapter(object):
#Learning Rate Adapter instance.
#Each time the improvement is smaller than th, a counter is incremented,
#when this counter is higher er equal to max_cnt_red, the learning rate,
#initialised at init_lr is multiplied by lr_red and returned
def __init__(self, init_lr, th, lr_red, max_cnt_red):
self.lr = init_lr
self.th = th
self.lr_red = lr_red
self.max_cnt_red = max_cnt_red
self.cnt = 0
def step(self, improvement):
#increment counter if big improvement
if improvement < self.th:
self.cnt += 1
#if the counter exceeded the max value update the lr and reset the cnt
if self.cnt >= self.max_cnt_red:
self.cnt = 0
self.lr = self.lr * self.lr_red
return self.lr
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Define classic NN layers
"""
# ----- Libraries ----- #
from math import sqrt
from torch import empty
from modules import Module
from torch import set_grad_enabled
set_grad_enabled(False)
# ----- Layers definitions and functions ----- #
#Layer init
def layer_init(X, init="Normal", param1=None, param2=None, input_w=0, output_w=0):
#initialise the layer following the instructions or default choices
# - X: the tensor to initialise (maybe W or b)
# - init: the type of init (Normal, Uniform or Xavier)
# - param1/2 the parameters of the init (for normal it is mean and std,
# for uniform it is min and max value, no param for xavier)
# - input_w: size of the input (nb input connections)
# - output_w: size of the output (nb output connections)
if init=="Normal":
if param1==None:
mean=0
if param2==None:
std=1
X = X.normal_(mean=mean, std=std)
elif init=="Uniform":
if param1==None:
v_min=-sqrt(input_w)
if param2==None:
v_max=sqrt(input_w)
X = X.uniform_(v_min, v_max)
elif init=="Xavier":
v_min=-sqrt(6)/sqrt(output_w+input_w)
v_max=sqrt(6)/sqrt(output_w+input_w)
X = X.uniform_(v_min, v_max)
else:
print("This initialiation is unknown")
return X
#FC Layer
class FCLayer(Module):
#Generates a Fully Connected Layer
#Parameters:
# - input_w: size of the input (nb input connections)
# - output_w: size of the output (nb output connections)
# - bias_bool: boolean, if a bias is added to the output of the FC
# - init: the type of init (Normal, Uniform or Xavier)
# - param1/2 the parameters of the init (for normal it is mean and std,
# for uniform it is min and max value, no param for xavier)
def __init__(self, input_w, output_w, bias_bool, init="Normal", param1=None,
param2=None):
self.name = "FC Layer with input "+str(input_w)+", output "+str(output_w)+\
" and bias set to "+str(bias_bool)
self.bias_bool = bias_bool
self.input = empty(size=(input_w,1))
self.output = empty(size=(output_w,1))
self.dl_dw = empty(size=(output_w, input_w)).zero_()
self.W = empty(size=(output_w, input_w)) # weights of the layer
self.W = layer_init(self.W, init, param1, param2, input_w, output_w)
if bias_bool:
self.b = empty(output_w)
self.b = layer_init(self.b, init, param1, param2, input_w, output_w)
self.dl_db = empty(output_w).zero_()
def forward(self, input):
self.input = input
self.output = self.W.matmul(input)
if self.bias_bool:
self.output += self.b
return self.output
def backward(self, gradwrtoutput):
self.dl_dw.add_(gradwrtoutput.view(-1, 1).matmul(self.input.view(1, -1)))
if self.bias_bool:
self.dl_db.add_(gradwrtoutput.squeeze())
return self.W.t().matmul(gradwrtoutput).squeeze()
def grad_step(self,eta):
self.W -= eta * self.dl_dw
self.dl_dw.zero_()
if self.bias_bool:
self.b -= eta * self.dl_db
self.dl_db.zero_()
def param(self):
params = []
params.append((self.W,self.dl_dw))
if self.bias:
params.append((self.b,self.dl_db))
return params
<file_sep># -*- coding: utf-8 -*-
"""
@authors: <NAME> & <NAME>
@aim: Test the simple example with PyTorch
"""
# ----- Libraries ----- #
#Ours
import datasets
#Utils
from torch import nn
import torch.optim as optim
from torch import set_grad_enabled
set_grad_enabled(True)
# ----- Parameters ----- #
N = 1000 #nb of dats in both train and test dataset
N_EPOCHS = 30 #nb of epoch for the train
eta = 1e-1 #learning rate
N_ITER = 10 #nb of iter to compute mean and std
BOOL_SAVE = True #to save or not the data
# ----- Log tables ----- #
train_perf = [] #final perf train of each iter
test_perf = [] #final perf test of each iter
train_perf_i_e = [] #perf train of each iter along epochs
test_perf_i_e = [] #perf test of each iter along epochs
# ----- Functions ----- #
def init_weights(m):
#Init all the FC layers with normal init as our implementation
if type(m) == nn.Linear:
m.weight.data.normal_(mean=0, std=1)
m.bias.data.normal_(mean=0, std=1)
# ----- Main ----- #
#repeat for stat info
for iter in range(N_ITER):
print("\nIter: "+str(iter)+"\n")
#Get data
train_points, train_labels, test_points, test_labels = \
datasets.generate_circle_dataset(N)
train_perf_e = [] #perf train along epochs
test_perf_e = [] #perf test along epochs
#Define the network
seq = nn.Sequential(
nn.Linear(2,25),
nn.Tanh(),
nn.Linear(25,25),
nn.Tanh(),
nn.Linear(25,1),
nn.Sigmoid()
)
seq.apply(init_weights)
#Define the optimisation
optimizer = optim.SGD(seq.parameters(), lr=eta)
criterion = nn.MSELoss()
#Train the network
for epoch in range(N_EPOCHS): #for each epoch
err_train = 0
err_test = 0
for i in range(N): #for each point
#predict the output, backward the loss and change the wheights
pred_train = seq(train_points[i, :])
loss = criterion(pred_train, train_labels[i].view(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
#check performance
if (train_labels[i] and pred_train <= 0.5) \
or (not train_labels[i] and pred_train >= 0.5):
err_train += 1
pred_test = seq(test_points[i, :])
if (test_labels[i] and pred_test <= 0.5) \
or (not test_labels[i] and pred_test >= 0.5):
err_test += 1
#Print and save epoch performance
print("train epoch {} err = {:.2%}".format(epoch, err_train / N))
print("test epoch {} err = {:.2%}".format(epoch, err_test / N))
train_perf_e.append(err_train / N)
test_perf_e.append(err_test / N)
#Test the network
#on test
err_test = 0
for i in range(N): #for each point
#predict the output
pred_test = seq(test_points[i, :])
#add errors
if (test_labels[i] and pred_test <= 0.5) \
or (not test_labels[i] and pred_test >= 0.5):
err_test += 1
#on train
err_train = 0
for i in range(N): #for each point
#predict the output
pred_train = seq(train_points[i, :])
#add errors
if (train_labels[i] and pred_train <= 0.5) \
or (not train_labels[i] and pred_train >= 0.5):
err_train += 1
#save and print
train_perf.append(err_train / N)
test_perf.append(err_test / N)
train_perf_i_e.append(train_perf_e)
test_perf_i_e.append(test_perf_e)
print("\nFinal train {} err = {:.2%}".format(epoch, err_train / N))
print("Final test {} err = {:.2%}".format(epoch, err_test / N))
#save in file
if BOOL_SAVE:
with open('train_perf.txt', 'w+') as f:
for val in train_perf:
f.write(str(val)+" ")
with open('test_perf.txt', 'w+') as f:
for val in test_perf:
f.write(str(val)+" ")
with open('train_perf_e.txt', 'w+') as f:
for l in train_perf_i_e:
for val in l:
f.write(str(val)+" ")
f.write("\n")
with open('test_perf_e.txt', 'w+') as f:
for l in test_perf_i_e:
for val in l:
f.write(str(val)+" ")
f.write("\n")
|
551a73ea985c71571ec788ddc921af440fd33548
|
[
"Python"
] | 11
|
Python
|
asreva/Deep_Learning_Project_2
|
07930c161cfd3cddef93a01843416bcdd701cc30
|
f2d574620f345567707afa5c753a22b7ce3acec4
|
refs/heads/master
|
<repo_name>satpeisoe24/ViewModel<file_sep>/app/src/main/java/com/example/viewmodel/viewmodel/CountViewModel.kt
package com.example.viewmodel.viewmodel
import androidx.lifecycle.ViewModel
class CountViewModel : ViewModel() {
private var count : Int = 0 //variable
fun getCount(): Int = count // getter
fun setCount(num: Int): Int{ // setter
count = num
count ++
return count
}
}<file_sep>/app/src/main/java/com/example/viewmodel/ViewmodelActivity.kt
package com.example.viewmodel
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.example.viewmodel.viewmodel.CountViewModel
import kotlinx.android.synthetic.main.activity_main.*
class ViewmodelActivity : AppCompatActivity() {
lateinit var countViewModel: CountViewModel
private val sharedFile = "SHAREDCOUNT"
var sharedPreferences: SharedPreferences? = null
var editor : SharedPreferences.Editor? = null //
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_viewmodel)
sharedPreferences = this.getSharedPreferences(sharedFile, Context.MODE_PRIVATE)
editor = sharedPreferences?.edit()
countViewModel = ViewModelProvider(this).get(CountViewModel::class.java)
// var count = sharedPreferences?.getInt("COUNT", 0)
//zero.text = count.toString()
var storedCount = sharedPreferences?.getInt("COUNT",0)
Log.d("count", storedCount.toString())
zero.text = storedCount.toString()
button.setOnClickListener {
Log.d("click", "clicked")
Log.d("store count", storedCount.toString())
var count = zero.text.toString().toInt()
countViewModel.setCount(count)
zero.text = countViewModel.getCount().toString()
}
}
override fun onPause() {
super.onPause()
editor?.putInt("COUNT", countViewModel.getCount())
editor?.apply()
}
}<file_sep>/app/src/main/java/com/example/viewmodel/MainActivity.kt
package com.example.viewmodel
import androidx.appcompat.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)
button.setOnClickListener {
var count: Int = zero.text.toString().toInt()
count += 1
zero.text = count.toString()
}
}
}
|
f265023d91bf2a146a50cb31c54a705fa9ad2e84
|
[
"Kotlin"
] | 3
|
Kotlin
|
satpeisoe24/ViewModel
|
fc7715b1dbe5885df478100c1b3d1dbc54276bc3
|
37a1977a5cc14a91d0e804a71318e46698197776
|
refs/heads/main
|
<repo_name>ineverbee/fibonacci<file_sep>/internal/app/cache/cache.go
package cache
import "time"
// Cache interface
type Cache interface {
Get(key interface{}) (int, error)
Set(key, val interface{}, ttl time.Duration) error
}
<file_sep>/internal/app/cache/rediscache/cache_test.go
package rediscache_test
import (
"testing"
"time"
"github.com/ineverbee/fibonacci/internal/app/cache/rediscache"
"github.com/stretchr/testify/assert"
)
func TestCache_Set(t *testing.T) {
cache, teardown := rediscache.TestCache(t)
defer teardown()
err := cache.Set(0, 0, time.Minute)
assert.NoError(t, err)
}
func TestCache_Get(t *testing.T) {
cache, teardown := rediscache.TestCache(t)
defer teardown()
err := cache.Set(1, 1, time.Minute)
assert.NoError(t, err)
data, err := cache.Get(1)
val := data
assert.NoError(t, err)
assert.Equal(t, 1, val)
}
<file_sep>/Makefile
create:
protoc -I . \
--go_out ./gen/go/pb/ --go_opt paths=source_relative \
--go-grpc_out ./gen/go/pb/ --go-grpc_opt paths=source_relative \
fibonacci.proto
protoc -I . --grpc-gateway_out ./gen/go/pb/ \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
fibonacci.proto
build:
go build -v ./cmd/server
go build -v ./cmd/client
run: build
./server
<file_sep>/gen/go/fibonacci/grpcserver.go
package fibonacci
import (
"context"
"time"
pb "github.com/ineverbee/fibonacci/gen/go/pb"
"github.com/ineverbee/fibonacci/internal/app/cache/rediscache"
"github.com/ineverbee/fibonacci/internal/app/fibo"
)
//GRPCServer ...
type GRPCServer struct {
pb.UnimplementedFibonacciServer
Cache *rediscache.Cache
}
func (s *GRPCServer) Fibo(ctx context.Context, req *pb.IntRequest) (*pb.IntSliceResponse, error) {
x, y := req.X, req.Y
if x > y {
x, y = y, x
}
if y > 47 {
y = 47
}
res := make([]uint32, y+1)
if y < 2 {
res[1] = 1
for j, v := range res {
if _, err := s.Cache.Get(uint32(j)); err != nil && (j == 0 || v != 0) {
s.Cache.Set(uint32(j), v, time.Hour*24)
}
}
return &pb.IntSliceResponse{Result: res[x : y+1]}, nil
}
for i := x; i <= y; i++ {
if val, err := s.Cache.Get(i); err == nil {
res[i] = uint32(val)
continue
}
if (i - x) >= 2 {
fibo.Fibo(i, y, &res)
} else if val, err := s.Cache.Get(i - 2); err == nil && (i-x) == 1 {
res[i-2] = uint32(val)
fibo.Fibo(i, y, &res)
} else {
res[1] = 1
fibo.Fibo(2, y, &res)
}
break
}
for j, v := range res {
if _, err := s.Cache.Get(uint32(j)); err != nil && (j == 0 || v != 0) {
s.Cache.Set(uint32(j), v, time.Hour*24)
}
}
return &pb.IntSliceResponse{Result: res[x : y+1]}, nil
}
<file_sep>/internal/app/fibo/fibo.go
package fibo
// Fibonacci numbers slice
func Fibo(m, n uint32, f *[]uint32) {
arr := *f
for i := m; i <= n; i++ {
arr[i] = arr[i-1] + arr[i-2]
}
}
<file_sep>/Dockerfile
#build stage
FROM golang:alpine AS builder
RUN apk add --no-cache git
WORKDIR /go/src/app
COPY . .
RUN go get -d -v ./...
RUN go build -o /go/bin/server -v ./cmd/server
RUN go build -o /go/bin/client -v ./cmd/client
#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/client /client
COPY --from=builder /go/bin/server /server
ENTRYPOINT /server
LABEL Name=fibonacci Version=0.0.1
<file_sep>/internal/app/cache/rediscache/cache.go
package rediscache
import (
"fmt"
"time"
redigo "github.com/gomodule/redigo/redis"
)
// Cache ...
type Cache struct {
password string
pool *redigo.Pool
}
// New redis cache
func New(pool *redigo.Pool, password string) *Cache {
return &Cache{
password: <PASSWORD>,
pool: pool,
}
}
func (s *Cache) getClient() (redigo.Conn, error) {
c := s.pool.Get()
if _, err := c.Do("AUTH", s.password); err != nil {
c.Close()
return nil, err
}
return c, nil
}
// Get ...
func (s *Cache) Get(key interface{}) (int, error) {
c, err := s.getClient()
if err != nil {
return 0, err
}
defer c.Close()
data, err := redigo.Int(c.Do("GET", key))
if err != nil {
return 0, err
}
return data, nil
}
// Set ...
func (s *Cache) Set(key, val interface{}, ttl time.Duration) error {
c, err := s.getClient()
if err != nil {
return err
}
defer c.Close()
_, err = c.Do("SET", key, val)
if err != nil {
return fmt.Errorf("error setting key %d to %d: %v", key, val, err)
}
return nil
}
<file_sep>/cmd/client/main.go
package main
import (
"context"
"flag"
"fmt"
"log"
"strconv"
pb "github.com/ineverbee/fibonacci/gen/go/pb"
"google.golang.org/grpc"
)
func main() {
flag.Parse()
if flag.NArg() != 2 {
log.Fatal("pass 2 arguments")
}
x, err := strconv.Atoi(flag.Arg(0))
if err != nil {
log.Fatal(err)
}
y, err := strconv.Atoi(flag.Arg(1))
if err != nil {
log.Fatal(err)
}
for x < 0 || y < 0 {
log.Println("arguments should be >= 0")
log.Println("Enter 2 non-negative arguments:")
fmt.Scanf("%d %d", &x, &y)
}
conn, err := grpc.Dial(":8080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
c := pb.NewFibonacciClient(conn)
res, err := c.Fibo(context.Background(), &pb.IntRequest{X: uint32(x), Y: uint32(y)})
if err != nil {
log.Fatal(err)
}
log.Println(res.GetResult())
}
<file_sep>/README.md
# fibonacci
## Микросервис для создания среза чисел Фибоначчи.
**Сервис:**
Реализован микросервис для создания среза чисел Фибоначчи с порядковыми номерами от `x` до `y`. В данном сервисе реализованы два протокола: HTTP REST и GRPC.
## Запуск приложения:
```
docker-compose up
```
Приложение будет доступно на порте `8081` для `curl` запросов
## gRPC
Чтобы создать запрос к серверу запустите клиент в другом терминале
```
docker-compose exec fibonacci ./client -- X Y
```
`X`,`Y` - аргументы, порядковые номера начала и конца среза
## REST
#### /fibo
* `POST` : Создать срез с числами Фибоначчи
Запрос:
```
curl --header "Content-Type: application/json" \
--request POST \
--data '{"x":7,"y":9}' \
http://localhost:8081/fibo
```
`x,y` - порядковые номера начала и конца среза, `result` - срез с числами Фибоначчи
```
{
"result": [
13,
21,
34
]
}
```
<file_sep>/cmd/server/main.go
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"time"
"github.com/gomodule/redigo/redis"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/ineverbee/fibonacci/gen/go/fibonacci"
"github.com/ineverbee/fibonacci/internal/app/cache/rediscache"
"google.golang.org/grpc"
pb "github.com/ineverbee/fibonacci/gen/go/pb"
)
var (
port = flag.Int("port", 8080, "The server port")
)
func run(cache *rediscache.Cache) error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Register gRPC server endpoint
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
err := pb.RegisterFibonacciHandlerServer(ctx, mux, &fibonacci.GRPCServer{Cache: cache})
if err != nil {
return err
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
log.Println("Listening and serving on :8081")
return http.ListenAndServe(":8081", mux)
}
func main() {
flag.Parse()
pool := newPool("redis:6379")
cache := rediscache.New(pool, "FIBONACCI")
go run(cache)
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
srv := &fibonacci.GRPCServer{Cache: cache}
pb.RegisterFibonacciServer(grpcServer, srv)
log.Println("Listening and serving on :8080")
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func newPool(server string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
|
29dbc848f0fae4e91bb62d03daa5412c2f38c617
|
[
"Makefile",
"Go",
"Dockerfile",
"Markdown"
] | 10
|
Go
|
ineverbee/fibonacci
|
e7b6067287fab2b825275b34535078b329b20721
|
5c05be141243a076a89b6a53d6547ca878d666a6
|
refs/heads/master
|
<repo_name>samaita/IsometricSVG<file_sep>/README.md
# IsometricSVG
An isometric map create using svg and mapped using javascript.
<file_sep>/index.php
<html>
<head>
<title>ISOMETRIC</title>
<style>
body{
margin:0px;
}
object, svg{
position: absolute;
}
svg{
transition: all 250ms;
transform: scale(0.5);
-webkit-transform:scale(0.5);
-ms-transform:scale(0.5);
-o-transform:scale(0.5);
}
div#loadCanvas {
width: 100%;
overflow:hidden;
height:100%;
}
.selected{
transform: scale(1.5) !important;
-webkit-transform:scale(1.5) !important;
-ms-transform:scale(1.5) !important;
-o-transform:scale(1.5) !important;
z-index: 1000 !important;
}
#blackLayer{
background: rgba(0,0,0,0.5);
width:100%;
height:100%;
position:absolute;
z-index: 999;
top: 0;
}
</style>
<script src='assets/jquery/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('#blackLayer').hide();
var frst1 = getSVG("frst-1");
var rd13 = getSVG("rd-1-3");
var rd24 = getSVG("rd-2-4");
var rdbrdg13 = getSVG("rd-brdg-1-3");
var rdbrdg24 = getSVG("rd-brdg-2-4");
var rdtrn12 = getSVG("rd-trn-1-2");
var rdtrn23 = getSVG("rd-trn-2-3");
var rdtrn34 = getSVG("rd-trn-3-4");
var rdtrn41 = getSVG("rd-trn-4-1");
var rdintrsc31 = getSVG("rd-intrsc-3-1");
var rdintrsc32 = getSVG("rd-intrsc-3-2");
var rdintrsc33 = getSVG("rd-intrsc-3-3");
var rdintrsc34 = getSVG("rd-intrsc-3-4");
var rdintrsc4 = getSVG("rd-intrsc-4");
var rvr13 = getSVG("rvr-1-3");
var rvr24 = getSVG("rvr-2-4");
var rvrtrn12 = getSVG("rvr-trn-1-2");
var rvrtrn23 = getSVG("rvr-trn-2-3");
var rvrtrn34 = getSVG("rvr-trn-3-4");
var rvrtrn41 = getSVG("rvr-trn-4-1");
var map = [
[frst1, frst1, frst1, frst1, frst1, frst1, frst1, frst1],
[rd24, rdintrsc33, rd24, rd24, rd24, rdtrn34, frst1, frst1],
[frst1, rd13, frst1, frst1, frst1, rd13, frst1, rvrtrn23],
[rvr24, rdbrdg13, rvr24, rvrtrn34, frst1, rd13, frst1, rvr13],
[frst1, rd13, frst1, rvr13, frst1, rdintrsc32, rd24, rdbrdg24],
[frst1, rd13, frst1, rvrtrn12, rvr24, rdbrdg13, rvr24, rvrtrn41],
[rd24, rdintrsc4, rd24, rd24, rd24, rdintrsc31, rdtrn34, frst1],
[frst1, rd13, frst1, frst1, frst1, frst1, rd13, frst1],
[frst1, rd13, frst1, frst1, frst1, frst1, rd13, frst1]
];
// var map = [
// [frst1, frst1, frst1],
// [rd24, rdintrsc33, rd24 ],
// [frst1, rd13, frst1],
// ];
// var map = [
// [9,5,1],
// [10,6,2],
// [11,7,3],
// [12, 8,4],
// ];
// var map = [
// [-2,-1,0,1,2],
// [-2,-1,0,1,2],
// [-2,-1,0,1,2],
// ];
var maxCount = 1;
for(var zCount = map[0].length - 1;zCount > -1 ; zCount--){
for(var xCount = 0; xCount < map.length; xCount++){
//console.log(xCount, zCount);
var objectName = (map[xCount][zCount]);
//console.log(map[xCount][zCount]);
//$("#loadCanvas").append(setProp(objectName, xCount, zCount, map[0].length-1));
setObj(objectName, xCount, zCount, map[0].length-1, maxCount);
//setObjPosition(xCount, zCount, map[0].length-1);
maxCount++;
}
}
});
// Load as SVG Not Object
function setObj(data, xIndex, zIndex, max, Count){
$.get(data, function( data ) {
marginLeft = (xIndex + zIndex - Math.floor(max/2)) * 59.2;
marginTop = (xIndex - zIndex - Math.floor(max/2)) * 34.2;
a = (new XMLSerializer()).serializeToString(data);
a = a.substring(4);
a = "<svg id=obj"+ xIndex + zIndex +" style='margin-left:"+ marginLeft +"px;margin-top:"+ marginTop +"px; z-index:"+Count+"'" + a;
$("#loadCanvas").append(a);
addInteractivity("svg#obj"+xIndex+zIndex);
return a;
});
}
function addInteractivity(id){
//fly(id);
select(id);
}
function fly(object){
// console.log(object+':hover');
// marginTopValue = $(object).css('margin-top');
// marginTopValue = Number(marginTopValue.substring(0, marginTopValue.length-2));
// $(object+':hover').css('margin-top',marginTopValue-10 + '!important');
// $(object).hover(function(){
// marginTopValue = $(this).css('margin-top');
// marginTopValue = Number(marginTopValue.substring(0, marginTopValue.length-2));
// $(this).css('margin-top',marginTopValue-10);
// console.log(marginTopValue-10);
// });
$(object)
.mouseenter(
function(){
marginTopValue = $(this).css('margin-top');
marginTopValue = Number(marginTopValue.substring(0, marginTopValue.length-2));
$(this).css('margin-top',marginTopValue-10);
})
.mouseleave(
function(){
marginTopValue = $(this).css('margin-top');
marginTopValue = Number(marginTopValue.substring(0, marginTopValue.length-2));
$(this).css('margin-top',marginTopValue+10);
});
}
function select(object){
$(object).click(function(){
$(this).attr("class",'selected');
$('#blackLayer').fadeIn();
});
$(object).dblclick(function(){
$(this).attr("class",'');
$('#blackLayer').fadeOut();
})
}
// function setObjIdPosition(xIndex, zIndex, max, Count){
// $("#loadCanvas svg:nth-child("+Count+")").attr('id','obj'+xCount+ zCount);
// console.log("LOAD");
// }
//Attempt of reducing total request by assign every map as an object, then load it to map, not request it again and again
// function getSVG(param){
// var assetsLocation = "assets/svg/";
// mapTile(assetsLocation + param + ".svg");
// return assetsLocation + param + ".svg";
// }
// function mapTile(param){
// this.desc = param;
// this.map = $.get(param, function( data ) {
// //marginLeft = (xIndex + zIndex - Math.floor(max/2)) * 122.20;
// //marginTop = (xIndex - zIndex - Math.floor(max/2)) * 70.5;
// a = (new XMLSerializer()).serializeToString(data);
// }).done(function() {
// return data.responseText;
// });
// }
//Load SVG file
function getSVG(param){
var assetsLocation = "assets/svg/";
return assetsLocation + param + ".svg";
}
// function setProp(data, xIndex, zIndex, max){
// marginLeft = (xIndex + zIndex - Math.floor(max/2)) * 122.20;
// marginTop = (xIndex - zIndex - Math.floor(max/2)) * 70.5;
// return "<object id=obj"+ xIndex + zIndex +" data="+ data +" style='margin-left:"+ marginLeft +"px;margin-top:"+ marginTop +"px' onload=setClick('"+data+"',"+xIndex+"," +zIndex+");></object>";
// }
// function setClick(objectName, xCount, zCount){
// b = "obj"+xCount+zCount;
// c = objectName.substring(11, objectName.length-4);
// var a = document.getElementById(b).contentDocument.getElementById(c);
// //console.log(a, b, c);
// $(a).click(function(){
// console.log(c);
// });
// // console.log('done');
// }
</script>
</head>
<body>
<div id='loadCanvas'>
<div id='blackLayer'></div>
</div>
</body>
</html>
|
5f45aa7a0f2e54dd863b2b3219425c1501364822
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
samaita/IsometricSVG
|
12022ca64bf8f38a8c09e41c84f8e82b171d4a5d
|
f46056feec03bb4fea9e37c45f2e02177c5bb861
|
refs/heads/master
|
<repo_name>DivyaRaghuwanshi/left-facotring<file_sep>/lfact.c
#include<stdio.h>
#include<string.h>
int main() {
char input[100],*l,*r,productions[25][50],c[10],d[10],e[10],c1=0,c2=0,c3=0;
int i=0,j=0,flag=0;
printf("Enter the production\n");
scanf("%s",input);
l=strtok(input,"->");
r=strtok(NULL,"->");
temp=strtok(r,"|");
temp=strtok(NULL,"|");
int n=strlen(r);
int m=strlen(temp);
for(i=0;i<n;i++){
if(r[i]==temp[i]){
c[c1]=r[i];
c1++;}
else{
d[c2]=r[i];
c2++;}}
for(i=c1;i<m;i++){
e[c3]=temp[i];
c3++;
}
if(r[0]!=temp[0])
printf("No left factoring\n");
printf("%s->",l);
for(i=0;i<c1;i++)
printf("%c",c[i]);
printf("%s'",l);
printf("\n");
if(c2==0)
printf("%s'->\356",l);
else{
printf("%s'->",l);
for(i=0;i<c2;i++){
printf("%c",d[i]);}}
printf("\n");
printf("%s'->",l);
for(i=0;i<c3;i++)
printf("%c",e[i]);
}
|
d0c4bc29e60faeea56da3f56188a2536639012ff
|
[
"C"
] | 1
|
C
|
DivyaRaghuwanshi/left-facotring
|
db802b3b4a0c7bbd895fd8036983a9d10e544b35
|
b10b98af577e38415bebda5682a31f305a0aaa8b
|
refs/heads/master
|
<repo_name>ChinaVolvocars/Jetpack<file_sep>/app/src/main/java/com/volvo/Api.java
package com.volvo;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Api {
public static ApiService createGitHubService() {
Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.github.com");
return builder.build().create(ApiService.class);
}
}
<file_sep>/app/src/main/java/com/volvo/UserViewModel.java
package com.volvo;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;
import java.util.concurrent.Executor;
public class UserViewModel extends ViewModel {
public LiveData<PagedList<User>> userList;
public LiveData<NetworkState> networkState;
Executor executor;
LiveData<ItemKeyedUserDataSource> tDataSource;
private final GitHubUserDataSourceFactory githubUserDataSourceFacteory;
private final PagedList.Config pagedListConfig;
public UserViewModel() {
githubUserDataSourceFacteory = new GitHubUserDataSourceFactory(executor);
tDataSource = githubUserDataSourceFacteory.getMutableLiveData();
networkState = Transformations.switchMap(githubUserDataSourceFacteory.getMutableLiveData(), dataSource -> {
return dataSource.getNetworkState();
});
pagedListConfig = (new PagedList.Config.Builder()).setEnablePlaceholders(false)
.setInitialLoadSizeHint(10)
.setPageSize(20).build();
userList = (new LivePagedListBuilder(githubUserDataSourceFacteory, pagedListConfig))
.build();
}
public LiveData<PagedList<User>> getRefreshLiveData() {
userList = (new LivePagedListBuilder(githubUserDataSourceFacteory, pagedListConfig))
.build();
return userList;
}
}
|
ac58123aec052d12046674d5cf0d5004c5591e66
|
[
"Java"
] | 2
|
Java
|
ChinaVolvocars/Jetpack
|
c8bc2804ffd669612c60c059e0416b0c374ab7f3
|
7fcbd3d3f2f43c137785afb3bb2f7fd11c319d1e
|
refs/heads/master
|
<repo_name>grgrzybek/sopel-docker<file_sep>/scripts/modules/review_requests.py
from sopel.formatting import colors, color, bold, underline
from sopel.module import commands, NOLIMIT, example, rule, rate
from threading import Thread
import json
import os
import requests
import sched
import sys
import time
import web
channels = [
"#paolo",
"#fusesustaining"
]
projects = [
"fabric8",
"camel",
"hawtio",
"fuse",
"cxf",
"fuseenterprise",
"karaf",
"aries",
"felix"
]
bot_instance = None
urls = (
# the second param here is a Class
'/', 'webhook',
'/hello', 'index'
)
class index:
def GET(self):
# print bot_instance
print ("Hello, world!")
for channel in channels:
bot_instance.say("message", channel)
return ""
class webhook:
def POST(self):
print ("web hook invoked")
data = web.data()
message = inspect_event(data)
for channel in channels:
bot_instance.say(message, channel)
print (data)
# listen on port 8080
app = web.application(urls, globals())
server = Thread(target=app.run)
server.setDaemon(True)
server.start()
def inspect_event(event_string):
message = ""
event = json.loads(event_string)
if "pull_request" in event:
print ("it's a pull request")
print ("Action is: " + event["action"])
if event["action"] in ["review_requested", "opened", "reopened"]:
url = event["pull_request"]["_links"]["html"]["href"]
user = event["sender"]["login"]
message = "NEW Review Request from " + user + ": " + url
else:
print ("it's something else")
return message
# curl -H 'Accept: application/vnd.github.black-cat-preview+json' -H 'Authorization: token <KEY>' https://api.github.com/repos/jboss-fuse/camel/pulls
# .url
# .state == open
# .locked == false
#
# curl -H 'Accept: application/vnd.github.black-cat-preview+json' -H 'Authorization: token <KEY>' https://api.github.com/repos/jboss-fuse/camel/pulls/142/reviews
#
# if( output empty then post)
def setup(bot):
print ("\ninvoking setup\n")
global bot_instance
bot_instance = bot
def configure(config):
config.core
base_url = "https://api.github.com"
token = os.environ['GH_TOKEN']
pulls_url = base_url + "/repos/jboss-fuse/:project/pulls"
single_pull_url = pulls_url + '/:pull/reviews'
headers = {
'Accept': 'application/vnd.github.black-cat-preview+json',
'Authorization': 'token ' + token
}
def query_jira(jira_id):
response = requests.get(jboss_org_rest + jira_id, headers=headers)
response = response.json()
if "fields" in response:
return "[{0}] {1} - {2}".format(jira_id, response["fields"]["summary"], color(jboss_org_case + jira_id , colors.GREY))
color(text, colors.PINK)
else:
return "Sorry but I couldn't fetch the URL"
@commands('pr')
@example('.pr')
@rate(600)
def pr(bot, trigger):
#text = trigger.group(2)
for project in projects:
url = pulls_url.replace(':project', project)
# print "[PR URL] " + url
response = requests.get(url, headers=headers)
prs = response.json()
for pr in prs:
print (pr)
if pr["state"] == "open" and pr["locked"] == False :
pr_url = pr["url"]
pr_html_url = pr["html_url"]
pr_number = pr["number"]
url = single_pull_url.replace(':project', project).replace(':pull', str(pr_number))
# print "[PR reviews] " + url
response = requests.get(url, headers=headers)
response = response.json()
# print response
if len(response) == 0:
bot.say( "[Approval Required] {0} - {1} - {2}".format(pr_html_url, pr["user"]["login"], color(pr["title"], colors.GREY)))
<file_sep>/start.sh
#!/bin/bash
envsubst < /.sopel/default.cfg.tpl > /.sopel/default.cfg
exec sopel<file_sep>/scripts/modules/versions.py
import json
from sopel.module import commands, NOLIMIT, example
versions_json = """
{
"6.2" : {
"6.2.1 ga" : "6.2.1.redhat-084",
"6.2.1 r1" : "6.2.1.redhat-090",
"6.2.1 r2" : "6.2.1.redhat-107",
"6.2.1 r3" : "6.2.1.redhat-117",
"6.2.1 r4" : "6.2.1.redhat-159",
"6.2.1 r5" : "6.2.1.redhat-169",
"6.2.1 r6" : "6.2.1.redhat-177",
"6.2.1 r7" : "6.2.1.redhat_186"
},
"6.3" : {
"6.3 ga" : "6.3.0.redhat-187",
"6.3 r1" : "6.3.0.redhat-224",
"6.3 r2" : "6.3.0.redhat-254",
"6.3 r3" : "6.3.0.redhat-262"
}
}
"""
@commands('versions', 'v')
@example('.versions')
@example('.v ga')
def versions(bot, trigger):
text = trigger.group(2)
vv = json.loads(versions_json)
for v in vv:
if text == None:
bot.say( "--------------------------")
bot.say( v)
subvv = vv[v]
for w in sorted(subvv):
w = w.lower()
if text != None:
text = text.lower()
if text in w:
bot.say( "{0} - {1}".format(w, subvv[w]) )
else:
bot.say( "{0} - {1}".format(w, subvv[w]) )
|
2bdfbbcfaf55e3755e5841f8d6c64dddcbeb3fb1
|
[
"Python",
"Shell"
] | 3
|
Python
|
grgrzybek/sopel-docker
|
1ef6b9cfe72840cb4ba74e1adc2a0a89b74970a8
|
5bd17a18dfcca89256361598f8ae49567866a6f1
|
refs/heads/master
|
<repo_name>maurobpt/unity-tests-mb<file_sep>/test_07/Assets/CustomGrid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustomGrid : MonoBehaviour
{
//object follow another
/*public GameObject target,structure;
private Vector3 truePos;
public float gridSize;
void LateUpdate()
{
truePos.x = Mathf.Floor(target.transform.position.x/gridSize)*gridSize;
truePos.y = Mathf.Floor(target.transform.position.y / gridSize) * gridSize;
truePos.z = Mathf.Floor(target.transform.position.z / gridSize) * gridSize;
structure.transform.position = truePos;
}*/
//smooth camera
/*public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
void FixedUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}*/
// player movement
private float moveSpeed;
public GameObject player;
private bool onGround;
// Use this for initialization
void Start()
{
moveSpeed =1f;
}
// Update is called once per frame
void Update()
{
//jump action
if(onGround && Input.GetKey(KeyCode.Space)) {
Jump();
onGround = false;
}
else {
if (player.transform.position.y >= 0.5f)
{
Vector3 downForce = new Vector3(0, -4.6f, 0);
player.transform.Translate(downForce * Time.deltaTime);
}
onGround = true;
}
//update player position
player.transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
}
public void Jump()
{
float jumpSpeed=1f;
float yPosition = 0.5f;
// Don't let player fall through floor
if (player.transform.position.y <= 0.5f)
{
jumpSpeed = 0.0f;
}
else
{
jumpSpeed -= 9.8f * Time.deltaTime;
yPosition += jumpSpeed * Time.deltaTime;
}
// Translate y-position with max height jump
if (player.transform.position.y <= 5f) { player.transform.Translate(new Vector3(0, yPosition, 0)); }
}
}
<file_sep>/test_11/Assets/Scripts/Welcome.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class Welcome : MonoBehaviour
{
public void StartGame()
{
Debug.Log("WELCOME - START GAME");
SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex+1);
}
}
<file_sep>/test_02/Assets/MazeCell.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MazeCell : MonoBehaviour
{
public int sizeX, sizeZ;
public MazeCell cellPrefab;
private MazeCell[,] cells;
}
<file_sep>/test_00/Assets/Cube.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cube : MonoBehaviour
{
// Start is called before the first frame update
/*void Start()
{
}*/
// Update is called once per frame
//void Update()
//{
//basic movement
/*float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0, vertical);
gameObject.transform.Translate(direction.normalized * Time.deltaTime * speed);*/
//rigid body 3d
/*if(Input.GetAxisRaw("Horizontal") != 0) {
GetComponent<Rigidbody>().angularVelocity = Vector3.right * Input.GetAxisRaw("Horizontal") * speed;
} else if (Input.GetAxisRaw("Vertical") != 0)
{
GetComponent<Rigidbody>().angularVelocity = Vector3.forward * -Input.GetAxisRaw("Vertical") * speed;
}*/
//rotate test
//gameObject.transform.Rotate(direction, Time.deltaTime * speed * 30);
//}
public float rotationPeriod = 0.3f; // Time for the next position
public float sideLength = 1f; // Length of Cube
bool isRotate = false; // Is Cube rotating now?
float directionX = 0; // Direction for rotation
float directionZ = 0; // Direction for rotation
Vector3 startPos; // Position before rotation
float rotationTime = 0; // past time for rotation
float radius; // Radius of the center of cube
Quaternion fromRotation; // Quaternion before rotation
Quaternion toRotation; // Quaternion after rotation
// Use this for initialization
void Start()
{
// Radius of the center of cube
radius = sideLength * Mathf.Sqrt(2f) / 2f;
}
// Update is called once per frame
void Update()
{
float x = 0;
float y = 0;
// key input
x = Input.GetAxisRaw("Horizontal");
if (x == 0)
{
y = Input.GetAxisRaw("Vertical");
}
// Key input AND cube is not rotating, rotate cube.
if ((x != 0 || y != 0) && !isRotate)
{
directionX = y; // x direction
directionZ = x; // y direction
startPos = transform.position; // start position
fromRotation = transform.rotation; // transform position
transform.Rotate(directionZ * 90, 0, directionX * 90, Space.World); // rotate inside world
toRotation = transform.rotation; // amount rotation
transform.rotation = fromRotation; // Cube delta Rotation
rotationTime = 0; // time start
isRotate = true; // rotation bool
}
}
void FixedUpdate()
{
if (isRotate)
{
rotationTime += Time.fixedDeltaTime; // increment time
float ratio = Mathf.Lerp(0, 1, rotationTime / rotationPeriod); // get radios
// Move
float thetaRad = Mathf.Lerp(0, Mathf.PI / 2f, ratio); // delta radios
float distanceX = -directionX * radius * (Mathf.Cos(45f * Mathf.Deg2Rad) - Mathf.Cos(45f * Mathf.Deg2Rad + thetaRad)); // Y delta
float distanceY = radius * (Mathf.Sin(45f * Mathf.Deg2Rad + thetaRad) - Mathf.Sin(45f * Mathf.Deg2Rad)); // Y delta
float distanceZ = directionZ * radius * (Mathf.Cos(45f * Mathf.Deg2Rad) - Mathf.Cos(45f * Mathf.Deg2Rad + thetaRad)); // Z delta
transform.position = new Vector3(startPos.x + distanceX, startPos.y + distanceY, startPos.z + distanceZ); // update direction
// Rotate
transform.rotation = Quaternion.Lerp(fromRotation, toRotation, ratio); // Quaternion.Lerp
// initialize parameters
if (ratio == 1)
{
isRotate = false;
directionX = 0;
directionZ = 0;
rotationTime = 0;
}
}
}
}
|
216668720caf11271571f383adce5bcc179fbda8
|
[
"C#"
] | 4
|
C#
|
maurobpt/unity-tests-mb
|
5fa488bb358a11f51813ca0bec9cd4e4bf202923
|
cd8e73371436af74e62a60deace2fad430129899
|
refs/heads/master
|
<file_sep>---
title: "Game Developers Conference 2017"
date: 2017-03-18 13:00:00
categories: [programming, unity, general]
---
This years [GDC](http://www.gdconf.com) is over again already. It was an exciting new experience for me because I was one of the speakers. This post is about how I got there and how it was like.
{: .center-image }
GDC is the oldest conference in the game development industry and this year they expected 27.000 professionals gathering from all over the world in beautiful San Francisco.
## How does it work? How to land a talk at GDC?
Let me give you a quick overview. Remember this is my personal experience and it could be different next year or even this year depending on what you wanted to talk about.
### Proposal
It all starts with a proposal. GDC has an online portal where you have to put in everything. Pretty straight forward. They ask you for all kinds of information: Title, Short Description, Long Description, Key Takeaways, Session Length, ...
Everything has limits like how many words or characters you are allowed to use so that you don't go too crazy. You also have to provide your bio, track record and social security number (just kidding)
### Phase2
Roughly a month after the proposal deadline, mids of September I got an exciting email telling me that my submission was accepted to the next stage - Phase 2.
I was super psyched - Awesome I got accepted at GDC!! Or didn't I? No, not so quick. What the hell is Phase 2?
Phase 2 means you have 3 weeks to write a scientific quality article about your topic. They connect you to a professional out of the industry, a member of the advisory board as your mentor. Together with this mentor you work the rest of the details of the talk out.
They provided me with an example paper of a talk that got accepted 2 years ago - a 21 pager full of graphs and schemas - I was intimidated.
But what the hell I wrote it. After all it is a great way to find out for yourself what you actually want to talk about and what is the essence of your topic.
### Slides
After that I got finally accepted fully and my next goal was to transform the article into the slides and do a first rehearsal with my mentor in december over skype.
Actually having a 21 pager of my topic helped a lot in creating the actual slides. It gives you confidence you have worked out everything you want to talk about and lets you focus on *how* to tell it. This is where you appreciate the loops the process made you jump through.
### Talk
Finally after countless rehearsals with porfessionals and total tech noobs the day came and my actual presentation was about to begin.
It was an undescribable feeling to be in that room 30 minutes before the talk was supposed to start. You build up your tech, you have a couple of supporting coworkers with you, you joke around, you stay hydrated, you try to convince youself not to be excited.
10 min before the talk, you are wired up, you can't deny it is going to happen and it freaks you out. On my way to the restroom for a last time I joke with the audio/video guy to keep the mic off until I am back.
5 min - I want to run away. BAM it starts!
Everything flies by, you have no time to think. Keep breathing!
Done!
It was a massive experience and right after the talk you do not want to stop, it is awesome, all the adrenalin, all the nodding heads, the laughters when u planned a joke, the laughters for moments you did not plan. Everything is so empowering. I can only recommend doing it and leave your comfort zone to get this rush!
## Would I do it again?
Absofuckenlutly ;)
Didn't you read the above?
It was worth all the effort and I would do it again every time.
## What happens at GDC stays at GDC Vault
I dont really know how many people were really sitting in the crowd but I definitly know most of all the GDC visitors have GDC Vault access after the conference. This is where all the talks are uploaded: video, audio transcript and slides, all there.
Sometimes I look it up just to check if it all was just a crazy dream:
[My talk in the Vault](http://www.gdcvault.com/play/1023978/Data-Binding-Architectures-for-Rapid)
So what is left to say? See you at GDC2018<file_sep>---
title: "GDC2017 by the numbers"
date: 2017-04-02 12:00:00
categories: [general, talks]
---
<img style="float: right; padding-left: 10px; width: 300px" src="{{ site.url }}/assets/gdc2017.jpg" />
[In my last post](http://blog.extrawurst.org/programming/unity/general/2017/03/18/gdc2017.html) I already talked about the experience of talking at a big developer conference like [GDC](http://www.gdconf.com).
This time I want to share some research that I did regarding the number of talks at GDC.
## GDC by the numbers
I want to talk about the number of visitors, speakers, sponsored talks and more.
Two reasons why I checked those numbers for GDC:
1. I wanted to mention in this post how many speakers actually talk at GDC.
2. GDC gives you a Deck of Cards: It features the best speakers of last year and I was curious how the odds are to land in there next time ;)
So I mentioned GDC aimed to get **27.000 visitors** in the beginning, right? Thats massive, but what is also massive is how many speakers they have.
I counted how many speakers are in there for letter 'A' through 'D' and it is 256 (give or take) that makes for an average of 66 per letter and that leads us to round about **1.200 speakers** overall (considering some special chars like 'x' and 'y' with less names.
Now I talked in the programming track and so I focused a little more on that and counted again. There were **150 programming talks** overall.
What caught my eye while counting those was the many presentation titles with the words "(presented by XYZ)" in the title. Turns out these are sponsored sessions - companies payed money to place that talk. So I counted again: **66 sponsored talks**.
Now there are also a couple of 'Tutorials' and 'Roundtables' and leaving all of these out there were only **56 raw talks** left in the programming track.
That made me humble actually because it means **out of 56** non-sponsored programming session slots possible I got one! Wow!
But seriously it will be quite interesting to see if those numbers change over time, if the amount of sponsored sessions increase.<file_sep>---
title: "Hello World"
date: 2015-03-08 14:00:00
categories: [general, dlang]
---
So this is my new blog driven by github-pages.
{% highlight d %}
void main(){
import std.stdio:writeln;
writeln("hello world");
}
{% endhighlight %}
<file_sep>---
title: "live-ask.com and the VADA stack"
date: 2018-02-05 12:00:00
categories: [general, dlang, webdev]
---
# Intro
[live-ask.com](www.live-ask.com) is a little website project I worked on every once in a while lately. The idea is to provide a simple, free and realtime service to moderate panel discussions, conference presentations, meetups, heck basically everything where someone wants to moderate a discussion.
{: .center-image .image-border }
# What to expect
This post kicks off a series of posts about my journey through modern web technology lately:
* My tech stack: VADA (this post)
* Angular
* Docker
* CD with Gitlab CI
* AWS - moving to the cloud
* Make it look great
* Animating lists in Angular
* The day angular was broken
* Automated unittests with Angular
For now this is the broad roadmap of how I think it makes sense to split it up into digestable pieces. But lets see where we go from here.
# VADA Stack - 'i am your father'
What the hell is VADA?
* V - Vibe.d - the server framework ([vibed.org](http://vibed.org/))
* A - AWS - the hosting platform ([aws.amazon.com](https://aws.amazon.com/))
* D - Dlang - in the backend ([dlang.org](https://dlang.org/))
* A - Angular - in the frontend ([angular.io](https://angular.io/))
I know AWS is not a database that you would usually find in a stack like this, but I could not come up with any accronym that works with DynamoDB and therefore 3 'D's.
# V as in Vibe.d
# A as in AWS
# D as in the D programming language
# A as in Angular<file_sep>---
title: "Worth Reading (May 2015)"
date: 2015-05-26 20:00:00
categories: [reading, greenlight, math, physics]
---
The following stuff is what caught my eye in the last couple of weeks. Consider this post an entry in my personal knowledge base ;)
###SCM for social graphs
Interesting idea to use SCM to generate social graphs for code bases and analyze if the organizational structure fits the technical architecture:
[social side of code](http://www.adamtornhill.com/articles/socialside/socialsideofcode.htm)
###Blender 2.7 Tutorials
A very good series to introduce Blender 2.7 as a modelling tool and much more. It is a good source for me to create the basic kind of models I am capable of ^^
<iframe width="560" height="315" src="https://www.youtube.com/embed/videoseries?list=PLda3VoSoc_TR7X7wfblBGiRz-bvhKpGkS" frameborder="0" allowfullscreen></iframe>
###"Greenlit in 8 days" by <NAME>
A great article for everyone interested in the backgrounds of the steam greenlight process:
[article](http://www.gamasutra.com/blogs/JamieKavanagh/20150410/240659/Getting_greenlit_in_8_days.php)
###"The Butterfly Effect" by <NAME>
Kevin, the programmer of the classic "the incredible machines" talks about how today he still needs to program his physics calculation in fixed point math to be deterministic:
[fixednum physics](http://gamasutra.com/blogs/KevinRyan/20150331/239636/The_Butterfly_Effect.php)
###Warm words by <NAME>
Really funny, emotional and motivating talk about programming, gamedev and the whole charme of the industry:
* [Gamasutra Article](http://www.gamasutra.com/view/news/241011/Video_Michael_Abrash_shares_game_programming_wisdom_at_GDC_2000.php)
* [<NAME>'s GDC2000 Talk](http://www.gdcvault.com/play/1016641/It-s-Great-to-be)
Here is my personal honor for Michael and what he sparked in myself ages ago:
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">Good old times - a piece of <a href="https://twitter.com/hashtag/gamedev?src=hash">#gamedev</a> history: <a href="http://t.co/V4H0mWBfvS">pic.twitter.com/V4H0mWBfvS</a></p>— <NAME> (@Extrawurst) <a href="https://twitter.com/Extrawurst/status/603186173213814784">May 26, 2015</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<file_sep>---
title: "Article on pocketgamer.biz"
date: 2016-12-02 00:00:00
categories: [reading, innogames]
---
Some time ago I was asked to write an article about how we approach assembling teams for our current mobile game productions. This article is now live on pocketgamer.biz: [article](http://www.pocketgamer.biz/comment-and-opinion/64296/4-keys-to-assembling-a-great-mobile-tech-team/)
### What can I expect?
We were facing the challenge of having ever smaller teams working highly effecient on mobile products in a technology new to them.
I am breaking our approach down into four key areas in this article:
* Strong team lead
* Senior and mentor
* Team mix
* Trust and empowerment
There even is footage of some of our upcoming games in there :)
I am looking forward for your feedback:
{: .center-image }<file_sep>---
title: "Projects"
layout: projectspage
entries:
- name: Live-Ask.com
link: https://www.live-ask.com
thumb: liveask.png
shortdesc: 'Real-Time questions from your audience! Have you ever organized a meetup, conference, or moderated a panel discussion and wanted an easy way to receive real-time questions from your audience?'
- name: 'Alexa Skill: Name that tune'
link: https://www.amazon.de/stephandilly-liederraten/dp/B079ZD2GT3
thumb: songquiz.png
shortdesc: 'This unique skill allows you to guess songs based on your spotify playlists! A Spotify account is required! You are able to use the current "top 50" of your country or set one your own playlists! Have fun and happy guessing!'
- name: 'Alexa Skill: Toast'
link: https://www.amazon.com/dp/B07L4W8D7C
thumb: prost.png
shortdesc: 'Have Alexa toast to you and have a lough. Just say "Alexa, let''s have a toast" and Alexa will make a toast. Perfect for a party with friends'
- name: 'Alexa Skill: Burp'
link: https://www.amazon.com/Extrawurst-Burp/dp/B0792C8FGY
thumb: burp.png
shortdesc: 'A funny skill that makes Alexa burp and joke. Say "Alexa, burp ahead" to make her belch. If you have more funny jokes and comments that we should teach Alexa let us know on Twitter: @AlexaBelch.'
- name: STACK4
gplay: com.Extrawurst.FIR
ios: stack4/id845108076
thumb: stack4.png
shortdesc: Based on the "Connect 4"™ game classic STACK4 reaches into the third dimension introducing a unique "Arcade Mode" that lets you develop astonishing new strategies and utilize powerful extras.
- name: JUMP OVER
gplay: com.Extrawurst.over
ios: jump-over/id877846952
thumb: jumpover.png
shortdesc: Just like the "Peg Solitaire" and "checkers" boardgame classic you squish game pieces by jumping with one over the other. Swipe to swap! But be aware, JUMP OVER adds a couple of modern twists to the classic
- name: BombBob
gplay: com.Extrawurst.bombbob3
ios: bomb-bob/id863008425
thumb: bombob.png
shortdesc: Forget flapping bird games! Bomb Bob is here! Be Bob and become a HERO like no one ever before! The evil Dr. Zed is trying to destroy your City and you are the last best hope! Defuse all the bombs which have been placed
---<file_sep>---
title: "The cimgui project"
date: 2015-04-26 18:45:00
categories: [dlang, cpp]
---
So I needed a flexible and easy to use [intermediate GUI](http://www.johno.se/book/imgui.html) for one of my projects in D. There was a pretty descent library natively written in D called [dimgui](https://github.com/d-gamedev-team/dimgui) that I started to use. It made me fall in love with the simple concept of an IMGUI but I was soon wanting more features than this library provided.
I started looking around for something similar but more mature. I found [IMGUI](https://github.com/ocornut/imgui) written in C++ but with a very simple C-like interface. I wrote a c-wrapper [cimgui](https://github.com/Extrawurst/cimgui) for it and afterwards added bindings for the D programming lanugage in a [derelict-like](https://github.com/DerelictOrg) style.
See the original imgui example below in a D application:

This is a screenshot of my user interface written in it:

This (pseudo) code shows the cimgui usage in the D programming language:
{% highlight d %}
import derelict.imgui.imgui;
void main()
{
... load opengl and initialize window ...
DerelictImgui.load(); // initialize dynamic bindings
ImGuiIO* io = ig_GetIO();
// callback that imgui calls to let us render everything for it
// (that makes imgui very platform independent, you can render using opengl, directX ... whatever)
io.RenderDrawListsFn = &renderImgui;
while(true)
{
io.MousePos = ImVec2(123,456);
... fill mouse and keyboard input info into the io variable ...
ig_NewFrame(); // tell imgui that a new frame begins
static float f = 0.0f;
float[3] clear_color = [0.3f, 0.4f, 0.8f];
ig_Text("Hello, world!");
ig_SliderFloat("float", &f, 0.0f, 1.0f);
ig_ColorEdit3("clear color", clear_color);
if (ig_Button("Test Button")) { ... }
// close this frames UI and makes imgui call our render callback
ig_Render();
}
ig_Shutdown(); // shutdown
}
{% endhighlight %}
You can find the full example D project on github: [imgui_d_test](https://github.com/Extrawurst/imgui_d_test)
<file_sep># extrawurst.github.io
My github pages driven(soon to be) blog: http://blog.extrawurst.org
<file_sep>---
title: "Worth Reading (December 2015)"
date: 2015-12-25 15:00:00
categories: [reading, unity]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
###Posts regarding Unity
["10000 UPDATE() CALLS"](http://blogs.unity3d.com/2015/12/23/1k-update-calls/)
Useful insights into Unity internals and how to profile/optimize certain areas of code.
["AN INTRODUCTION TO IL2CPP INTERNALS"](http://blogs.unity3d.com/2015/05/06/an-introduction-to-ilcpp-internals/)
Very interesting insights in il2cpp backend and how to avoid certain performance pitfalls.
###Website: "Vulkan Tutorial"
[Website](http://vulkan-tutorial.com/)
Vulkan is coming soon and this is a good starting point of how to use it and what it introduces. Especially interesting is SPIR-V the new IL for shader programming.
###Post: "Understanding C by learning assembly" by <NAME>
[Blog Link](https://www.recurse.com/blog/7-understanding-c-by-learning-assembly)
Never used assembly ? This is a good starting point to understand system level programming by inspecting the generated assembly. I suggest every descent programmer should be familiar with assembly since even in times of highlevel VMs it all boils down to assembly in the end. This bring implications even on the highest level that you should be familiar with.
###rbenv
Making Jekyll work again on my mac was a strange hustle and it came down to the version of ruby preinstalled with osx. rbenv simplifies managing ruby versions and this instructions shows you how:
[usage instructions](https://github.com/rbenv/rbenv#homebrew-on-mac-os-x)
**note**: do not forget to reshash after installing the jekyll gem:
{% highlight bash %}
$ rbenv rehash
{% endhighlight %}<file_sep>---
title: "make alexa toast in go"
date: 2018-12-15 9:00:00
categories: [general]
---
I always looked for a chance to dig into the `go` programming language. Recently I found the perfect opportunity: writing an **Alexa Skill in go**!

## Why go?
Why did I feel the urge to look into go? Because I like to keep up to date with the latest programming languages and developments.
One other reason why I chose go was: **AWS lambda support** - out of a bunch of scripting/VM based languages go was the only system programming language that is natively supported. Alexa Skills are best developed on lambda and since I was fed up using JS it was go this time.
go is a tool in a toolbox, this particular one is trying to be a system programming language (no VM) and to be more modern than crusty old C/C++.
Like any other tool, it is solving a particular purpose. go's primary purpose is to be *modern* (having a GC and all) while still cater the needs of system developers (*runtime speed* and statically typed'ness) and still be attractive to script programmers (fast iteration - aka. *quick compilation*). On top of that, go wants to simplify *concurrency* (don't dare to call it [parallelism](https://www.youtube.com/watch?v=cN_DpYBzKso)) with built in support for coroutines (ahem, I mean goroutines) and message passing using channels.
## First impressions
*TL;DR*
* ❤️ really easy setup
* ❤️ all-in-one installation
* ❤️ easy cross compilation
* 👍 imports == dependencies
* 👍 tight git integration
* 👍 multiple return values
* 👍 somewhat familiar syntax
* 👎 no versioned dependencies *
* 💔 no deterministic builds *
* 💔 workspace concept feels weird *
* 💔 `err` everywhere
* 😱 no generics
\* Those are worked on and with version 1.11 and it's modules concept much of this might disappear ([see my post on this](https://blog.extrawurst.org/general/2018/12/05/go-and-gitlab-ci.html)).
*Disclaimer:* I want to emphasize that I am not a go expert by any means, so take these with a grain of salt.
### Generics
For me, the lack of generics was the biggest downer because it introduces other disadvantages. For example, I was looking for a HashSet implementation in go - guess what: does not exist - because of missing generics. If you need such a container, write it exactly for the one type that you need it for.
This means that for most things you either take built in stuff or you have to write it specially tailored for yourself - I ended up abusing `map` as a HashSet 🙈.
### Error handling
Error Handling is my second biggest concern. go wanted to rise from the past of crusty old C and still they implemented error handling in a very C-ish way. Everything returns an error-code or object. Thanks to multiple return values, this is not as bad as in C, but still bloats my code a lot.
```go
sess, err := awssession.NewSession(...)
if err != nil {
log.Fatalf("session error: %s\n", err)
return nil
}
```
I ended up checking for `err != nil` everywhere and felt like it is tempting to plaster my code with `panic()` everywhere, as an easy out. I am not sure this concept proves good, since the dirty/easy way out is so damn tempting.
## Alexa skills in go
My use case for go was writing an Alexa Skill, remember?
Unfortunately AWS does not offer an off-the-shelf SDK for alexa skills in go like it does for javascript but thanks to open source this does not matter much: [alexa-skills-kit-golang](https://github.com/ericdaugherty/alexa-skills-kit-golang)
Therefore writing a skill in go is similarly easy:
```
func (h *HelloWorld) OnLaunch(ctx context.Context, request *alexa.Request, session *alexa.Session, ctxPtr *alexa.Context, response *alexa.Response) error {
speechText := "Welcome to the Alexa Skills Kit, you can say hello"
response.SetOutputText(speechText)
return nil
}
```
Fortunately accessing other AWS services like DynamoDB is even easier, there is an official SDK: [aws-sdk-go](https://github.com/aws/aws-sdk-go)
Why do I need DynamoDB access? Because I need to persist the last jokes my skill response uses to not repeat her over and over again but prefer not used sentences.
## Conclusion
Thanks to this all-in-one easy setup, I was productive very quickly and thanks to the 'golang' nickname, it was easy to find on the internet (good luck searching for `go`) - after all, go is not that new.
I am not sure how much further I want to dig into go. Although I want to look more into the concurrency model before departing. I feel like go is a good middle ground for small to mid size projects and the blazing fast compilation is definitely something I would miss.
In certain areas I wish go would get away even further from its C-ancestors, but maybe I will think differently once I checked out `Rust` 😊.
But for now, go remains my `goto`-language 😉 when it comes to AWS lambda functions. IMHO it's the best in the pool of natively supported languages. It is statically typed, compiled, safe and blazing fast.<file_sep>---
title: "golang and gitlab ci"
date: 2018-12-05 18:00:00
categories: [general]
---
This is a quick writeup of how to set up a simple ci pipeline for a `go` project on gitlab using golang's 1.11 modules.

## The why
I was working on an [Alexa Skill](https://www.amazon.com/dp/B07L4W8D7C) written in go and in fact did my first steps in go. I am still a noob when it comes to the go-world, so I googled on how to set up continuous integration for a go project...
Turns out using go in a CI Job was not as easy as I thought. Let's see what different approaches the top hits on the google search for 'golang gitlab ci' propose:
1. [about.gitlab.com/2017/11/27/go-tools-and-gitlab-how-to-do-continuous-integration-like-a-boss](https://about.gitlab.com/2017/11/27/go-tools-and-gitlab-how-to-do-continuous-integration-like-a-boss/)
* ✅ shows usage of lots of nice tools: code coverage, linter ...
* ⛔️ uses crude bash scripts
* ⛔️ uses copy-code-to-gopath hack (read below)
* ⛔️ spreads wrong information: [my rant tweet](https://twitter.com/Extrawurst/status/1070363661687029760)
* ⛔️ pretty sad for an official blog post by gitlab itself
2. [blog.boatswain.io/post/build-go-project-with-gitlab-ci](https://blog.boatswain.io/post/build-go-project-with-gitlab-ci/)
* ✅ short and sweet read
* ⛔️ uses 3rd party tool [glide](https://glide.sh/)
* ⛔️ same old copy-code-to-gopath hack like the rest of the bunch
3. [blog.netways.de/2018/06/07/continuous-integration-with-golang-and-gitlab](https://blog.netways.de/2018/06/07/continuous-integration-with-golang-and-gitlab/)
* ✅ the tool [dep](https://github.com/golang/dep) feels more official being part of go
* ⛔️ still dep does not ship with go
* ⛔️ same old copy-code-to-gopath hack like the rest of the bunch
{: .center-image }
## A single workspace
As you can see it does not turn out to be an easy topic.
Most hassle in this area comes from go having this concept of a workspace. Workspaces were a design decision that go took on day 1. They enforce a certain mindset on you: All go projects have to live in a central folder on your hard drive (including the downloaded dependencies). This is for some (or most) a very unnatural way of structuring their projects. It also comes with lots of strings attached: Like CI jobs copying their code on the fly into the $HOME/go folder to build and resolve 🤢.
I am not an early adopter (lucky me 🥳) and go was working on this already. This years release 1.11 comes with a first version of module support: [golang modules](https://github.com/golang/go/wiki/Modules)
Modules allow you to have your projects independently structured much like most of the third party package managers eg. glide/dep. Since this concept is so new, most of the online sources do not mention it as being an easy alternative to build go projects yet, hence my post here.
## The setup with modules
Lets look at our source code: go files' import-statements act as depdencies right away, some of them can be renamed to protect name collisions. go deeply connects to git using git repos as the definition of a dependency:
```
package main
import (
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/aws"
awssession "github.com/aws/aws-sdk-go/aws/session"
alexa "github.com/ericdaugherty/alexa-skills-kit-golang"
)
...
```
To initialise go modules in your project ('alexa-prost' being my project name here) simply run:
```
go mod init alexa-prost
```
This generates a `go.mod` file looking like this:
```
module alexa-prost
require (
github.com/aws/aws-lambda-go v1.8.0
github.com/aws/aws-sdk-go v1.15.90
github.com/ericdaugherty/alexa-skills-kit-golang v0.0.0-20181003210505-70580a479839
)
```
This file contains the versions of the dependencies that were downloaded. These versions enable a reliable deterministic build that can be reproduced everywhere.
Now this allows us to leave our repository wherever we want and makes our gitlab-ci script super simple:
```
test:
image: golang:1.11
script:
- go test
```
## The caveats
1. 👎 **mod is not final** - We are using a very early feature of go here and it might change and contain bugs.
2. 👎 **gitlab ci caching not supported** - if you want to use gitlab-ci's caching, you still need to use the same ol' copy-around trick.
### Regarding gitlab CI caching
Even with go 1.11's modules the dependencies will live in the `$GOPATH` - so no `node_modules`-like folder in your project's path.
This can still be solved a little more elegantly than copying your project code around. Since you just want to cache the dependencies, we copy those around which is less verbose:
```
test:
image: golang:1.11
cache:
paths:
- .cache
script:
- mkdir -p .cache
- export GOPATH="$CI_PROJECT_DIR/.cache"
- make test
```
**Note:** My OCD felt better once I had caching of dependencies working - but the build still was not faster. That might be due to it currently being too small to be limited by the dependency download/build process.<file_sep>---
title: "osx terminal colors"
date: 2015-07-21 15:00:00
categories: [general, osx]
---
This short post is just a wrap up of how to setup linux like terminal (bash) colors on osx.
This is how the terminal coloring is default on osx:

Simply edit or create the bash_profile file like so:
{% highlight sh %}
vim ~/.bash_profile
{% endhighlight %}
and paste the following in there:
{% highlight sh %}
export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "
export CLICOLOR=1
export LSCOLORS=ExFxBxDxCxegedabagacad
alias ls='ls -GFh'
{% endhighlight %}
This is from a blog post [here](http://osxdaily.com/2013/02/05/improve-terminal-appearance-mac-os-x/).
The end result will look like this:
<file_sep>---
title: "Old page"
date: 2018-01-20 12:00:00
categories: [general]
---
[img]: {{ site.url }}/assets/oldpage/screenshot.jpg "img"
I finally disabled my old page/bog that was still running, outdated and ugly ;). Why did it take so long? Because it still had some vsluable content that people regularly looked for and read. Especially my articles about gameserver developmont in D, media streaming with Nodejs and more. This content is now exported into PDF article versions (see bottom of this post) that I can provide here.
And here is a last screenshot of the old version of the page for memories:
![alt text][img]
## Articles
* [Stack4 and the D programming language (#1)]({{ site.url }}/assets/oldpage/Stack4AndD-1.pdf)
* [Stack4 and the D programming language (#2)]({{ site.url }}/assets/oldpage/Stack4AndD-2.pdf)
* [Stack4 and the D programming language (#3)]({{ site.url }}/assets/oldpage/Stack4AndD-3.pdf)
* [Android Immersive Mode in Unity3D]({{ site.url }}/assets/oldpage/AndroidImmersiveModeInUnity3d.pdf)
* [Streaming with Nodejs]({{ site.url }}/assets/oldpage/StreamingWithNode.pdf)<file_sep>---
title: "Worth Reading (June 2015)"
date: 2015-06-30 23:00:00
categories: [reading]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
###Talk: <NAME>
Presentations by <NAME> are always entertaining.
This one is kind of a meta presentation by him not 100% about c++ specifics but about how to present to an expert audience.
He talks about how to write a book and how to transport a message in a convincing and captivating way. And of course it shows yet again some c++ guts that only amaze :D
[talk on youtube](https://www.youtube.com/watch?v=smqT9Io_bKo)
###Book: "Game Engine Architecture"
This particular book written by <NAME> - an industry veteran - is new on my shelf and very good for beginner and intermediate game engine developers.
I found bits and pieces in every chapter that were new to me and consider this a good reference material.
<NAME> covers an amazing broad spectrum and shows further readings for most of the in depth details that cannot be covered in such a compendium.
[book at amazon](http://www.amazon.com/Engine-Architecture-Second-Jason-Gregory/dp/1466560010)
###Book: "Game Programming Patterns"
This book is a must read for every game programmer - well every programmer in general! It actually is available for [free online](http://gameprogrammingpatterns.com/) so there is no excuse :)
The author <NAME> wraps up reusable patterns in such a crystal clear way that it is very worth your time. His analytical way and attitude to always improve professionally are an inspiration. No buzzwording, no nonesense - just applicable ideas and the motivation behind them. Every word in this book shows that this piece was not written by someone in an ivory tower but a dry pragmatist who openly took feedback and incorporated it even in very early stages of the book. One could argue that this book was a community effort.
The highlights in short:
* distilled knowledge based on years of professional game development
* good structured chapters
* thoughtful examples
* neat hand-drawn diagrams
* filtered and improved over the thousands of readers involed in the creation of this book
[book at amazon](http://www.amazon.com/Game-Programming-Patterns-Robert-Nystrom/dp/0990582906)
###Post: "Mercurial at Unity"
<NAME> writes about the large scale usage of mercurial at Unity and how it improved their workflows and productivity:
[blog post](http://natoshabard.com/post/122632480712/mercurial-at-unity)
I consider this a very good read for people still sceptical to choose mercurial for their game dev projects (yes even considering big binary blob files like graphics assets).
<file_sep>---
title: "Homebrew contribution"
date: 2015-07-15 21:00:00
categories: [general, osx]
---
I recently made my first [homebrew](http://brew.sh/) contribution. homebrew is a package manager for osx much like yum/apt-get and the like you know from linux systems.
Since this may not be the last time I did this or have to do this I will elaborate what the workflow was.
This may help me remember and others get a grip how to do that the first time.
I am using the [freeimage library](http://freeimage.sourceforge.net/) in lot of my projects and since it turned out to be pretty hairy to build this lib on osx by hand I tried to find it in homebrew.
Indeed homebrew has a formular for it:
[freeimage on homebrew](http://brewformulas.org/Freeimage)
### Updating a formular
Unfortunately the freeimage formular was a bit dated and just supported version 3.16.0.
Since I needed the most recent version I opened a ticket for version 3.17.0 on github: [issue #41609](https://github.com/Homebrew/homebrew/issues/41609).
@bfontaine suggested to do the update myself ;)
After looking into the [formular](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/freeimage.rb) of this version I tried to apply the patches to the src-download of freeimage by hand and found it working.
So the update was pretty streight forward using the [instructions for getting a pull request merged](https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/How-To-Open-a-Homebrew-Pull-Request-(and-get-it-merged).md#how-to-open-a-homebrew-pull-request-and-get-it-merged) for homebrew.
In the case of the freeimage update there were essentially four changes:
* update the download url
* update the version number
* update the file hash
* update the patches
### Updating the file hash
Here it got a little tricky, since the sourceforge download info just provided md5 or sha1 hashes.
A little googling later I had a working shell line to create the file hash in sha256:
{% highlight sh %}
shasum -a 256 FreeImage3170.zip
{% endhighlight %}
### Update the patching
This was the most work since the old patch did not work anymore because the makefiles of freeimage changed from 3.16.0 to 3.17.0.
So I created a copy of the targeted makefiles and applied the patches by hand and created the diff using git:
{% highlight sh %}
git diff Makefile.gnu p.Makefile.gnu > patch.diff
{% endhighlight %}
### TL;DR - The pull request

So the final change that got merged into homebrew to update the freeimage formular: [pull request #41619](https://github.com/Homebrew/homebrew/pull/41619/files)<file_sep>---
title: "Worth Reading (June 2017)"
date: 2017-06-11 16:00:00
categories: [reading, dlang]
---
Oh wow its more than a year since my last '[worthreading](http://blog.extrawurst.org/reading/dlang/2016/04/30/worthreading.html)' :(
It was a crazy ride! Crazy hours at work, speaking at 4 conferences and 2 vacations later I am here now.
I tried to recollect the some discoveries since then:
### Website: All D compilers usable in travis-ci on a glance
[link](https://semitwist.com/travis-d-compilers)
### Talk: ACCU 2016 Keynote by <NAME>
* c++ concepts
* sentinels
* Design by Introspection
* (re)invents fast partitioning algorithm
Andrei and his unique and entertaining way of doing presentations at prestigous ACCU 2016:
[link to youtube](https://www.youtube.com/watch?v=AxnotgLql0k)
Here another link that is worth mentioning since Andrei is talking about it in his talk:
["Why Concepts didn’t make C++17"](http://honermann.net/blog/?p=3)
### Post: "Minimal Dev Setup on OXS" by <NAME>
This post was insanely useful to me, since it introduced me to (among a ton of other things) [brew-cask](https://caskroom.github.io/)
[Blog Post](http://blog.coldflake.com/posts/Minimal-Development-Setup-for-Mac-OS/)
### Book: "Drive" by <NAME>
[Amazon Link](https://www.amazon.com/Drive-Daniel-H-Pink/dp/184767769X)
An amazing book, good overview of the current state of science about what motivates us. Historical catchup from Motiviation 1.0, 2.0, 2.1 and now 3.0. I recommend this book for everyone leading people, working with people or if you just want to get a better understanding about yourself :)
### Book: "Elon Musk" by <NAME>
[Amazon Link](https://www.amazon.com/Elon-Musk-SpaceX-Fantastic-Future/dp/006230125X)
I was blown away by this story - admittedly I knew little about the details of Musk's life other than being this huge entrepeneur and founder of paypal, tesla and spaceX. This book really comes close convincing you that this guy is going to change the world (if he did not already) and sent us to mars.
### Post: "Public Speaking Transformed My Life…and Can Change Yours Too" by <NAME>
[link](https://medium.freecodecamp.com/public-speaking-transformed-my-life-and-can-change-yours-too-ca8acdbcc188)
A fascinating read about how to stop worrying and transforming into a public speaker. If you spoke on conferences already you will love to see parallels to what you experienced - if you have never tried it you will want to after reading this! Very inspiring.<file_sep>---
title: "STACK4 Life Sign"
date: 2015-12-31 15:00:00
categories: [general, unity, dlang]
---
{: .center-image }
During the holidays I finally found the time to work a little bit on my mobile app [STACK4](http://www.stack4.de).
It has been a while but I still have a few points on my todo list for this project.
### Multiplayer on iOS
I want to update the iOS Version to be on par with android, especially to support online multiplayer too. Finally iOS Players will be able to play against Android users.
In order to do that the biggest roadblock was connecting to the Apple Push Notification Service (APNS).
The STACK4 backend is written in [dlang](http://dlang.org/) and there is no implementation yet that supports APNS.
To have a working version on the market soon I decided to use a working proven software as a middleware instead of rewriting it in D (for now): [node-apn](https://github.com/argon/node-apn)
The plan is still to implement it later in D natively: [apn-d](https://github.com/Extrawurst/apn-d).
It is easy to provide a REST interface in node and to connect to a REST interface from D so this is the route I am taking for now.
### New UI
Unity for years had only one official method to implement user interfaces: OnGUI (an intermediate GUI) which was ineffiecient and difficult to get visually appealing.
It was easy to prototype stuff with it but hard to get a scalable UI that worked for all display sizes and used little drawcalls. Another caveat: No out-of-the-box support for gamepad/key input.
Supporting more platforms and more sophisticated UI screens was no option with the old system. So switching to the new uGUI was also on my list. The screenshots today all show the new UI using uGUI that is fully controllable using gamepads and keyboards too.
### FireTV & AppleTV
I am a big fan of the FireTV and new Apple-TV and supporting these platforms aswell would be cool.
The biggest issue with them is the input. STACK4 used to be controlled via touch exclusively and now it needed GameController Input aswell. As mentioned before this was hard to do with the old UI. Thanks to the new UI we have key/gamepad support now (an early version).
Some screens are not yet implemented and some flows do not work yet but I am on a good way and hope to finish this in January 2016. Following you see a low-res gif-video of the new UI and how it is controlled using Keys:
{: .center-image }
And now "einen guten Rutsch" as we say in germany - Happy new year!
<file_sep>---
title: "Extending github pages blog"
date: 2015-12-26 15:00:00
categories: [general]
---
### Categories Page
<img style="float: left; width: 250px;" src="{{ site.url }}/assets/blog-categories.png"/>
First I wanted to make use of the categories labels I kept adding to my posts. Since I am using github pages to host this site dynamic jekyll plugins are no option for me.
Fortunately I found the great [blog post](http://christianspecht.de/2014/10/25/separate-pages-per-tag-category-with-jekyll-without-plugins/) "Separate pages per tag/category with Jekyll (without plugins)" by <NAME>.
<NAME> writes about how to create a page per tag/category using jekyll without plugins. This was the foundation for my approach.
### Apps Page
<img style="float: left; width: 250px;" src="{{ site.url }}/assets/blog-apps.png"/>
I added an "Apps" page to this site: [Apps]({{ site.url }}/apps.html)
In order to do that the jekyll way you simply add a "layout" to the _layouts folder that uses markdown and html to define how to visualize the content (see [appspage.html](https://github.com/Extrawurst/extrawurst.github.io/blob/master/_layouts/appspage.html)). This is like a template. The actual content lies in raw form (yml) in the [apps.html](https://github.com/Extrawurst/extrawurst.github.io/blob/master/apps.html) file in the root.
<file_sep>---
title: "Worth Reading (Februar 2016)"
date: 2016-03-03 15:00:00
categories: [reading, unity, dlang]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
### Unity
* "Integrating Visual Studio with Unity3d on Mac using UnityVS Tools" by <NAME> ([link](https://www.yunspace.com/post/integrating-visual-studio-with-unity3d-on-mac-using-unityvs-tools/))
* "why foreach creates garbage in unity" by <NAME> ([link](http://codingadventures.me/2016/02/15/unity-mono-runtime-the-truth-about-disposable-value-types/))
* "monodis" Dis/Assembling CIL Code (kind of like ILSpy for mono) ([link](http://www.mono-project.com/docs/tools+libraries/tools/monodis/))
* "Unity Debug with Rider-EAP On OSX" by <NAME> ([link](http://www.leroyshirto.co.uk/2016/03/unity-debug-with-rider-eap-on-osx/))
### Article: "Compile-time Argument Lists" on dlang.org
This is an [awesome article](http://dlang.org/ctarguments.html) differntiating compiletime tuples from generic compile time argument lists that allow for crazy stuff like this in D:
{% highlight d %}
import std.meta;
alias Params = AliasSeq!(int, double, string);
void foo(Params); // void foo(int, double, string);
{% endhighlight %}
### Book: "D Web Development"
As I already twittered I finally received a copy of the book about D web development by <NAME> that I reviewed:
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Great! My copy of "D Web Development" arrived - look who was a reviewer :P <a href="https://twitter.com/hashtag/dlang?src=hash">#dlang</a> <a href="https://t.co/S828YvJCs1">https://t.co/S828YvJCs1</a> <a href="https://t.co/Wx8cKNa4HT">pic.twitter.com/Wx8cKNa4HT</a></p>— <NAME> (@Extrawurst) <a href="https://twitter.com/Extrawurst/status/702234903384031232">February 23, 2016</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
### Post: "Declarative OpenGL (sort of) in D" by profan
Great article about automatic wrapping of C based APIs using D's strong meta programming features:
[blog post](https://pagefault.se/dlang/2016/02/26/declarative-opengl-dlang/)
###Post: "Practical tips to make the most out of your first GDC" by <NAME>
Last but not least, a guide how to survive GDC San Francisco on Gamasutra:
[link to post](http://www.gamasutra.com/blogs/ElineMuijres/20160225/266607/Practical_tips_to_make_the_most_out_of_your_first_GDC.php)
Hope to see you there!<file_sep>---
title: "Worth Reading (March+April 2016)"
date: 2016-04-30 21:00:00
categories: [reading, dlang]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
### Tools: oh my zsh
Great tool to have a an extendended and improved feature set on the shell in osx: zsh with iterm. I use them both now for months successfully and do not want to miss them, it looks better and is a lot more powerful:
{: .center-image }
[setup zsh on osx](http://devsnaps.herokuapp.com/blog/2013/11/09/setting-up-the-terminal-for-development-in-os-x/)
### GDC: "Story of making Diablo" by <NAME>
An awesome background story about the creation of one of my alltime fave games Diable by Blizzard. Learn how it at first was supposed to be a round based RPG:
[gamasutra](http://www.gamasutra.com/view/news/268507/20_years_later_David_Brevik_shares_the_story_of_making_Diablo.php)
### Post: "From Browser to Mobile Game Development – An InnoGames Retrospective" by <NAME>
My colleague and friend <NAME> wrote a insightful article how our employer - a traditional browser games company - made the transition to mobile:
[article on gamasutra](http://www.gamasutra.com/blogs/DennisRohlfing/20160427/271347/From_Browser_to_Mobile_Game_Development__An_InnoGames_Retrospective.php)
### Podcast: JS Jabber with <NAME> on "Growing Happy Developers"
I really enjoyed this podcast about how to make your employee developers happy, how to be a good boss. I think a lot more focus should be put into discussing these topics, because there is nothing more important than being a boss that your developers like to work with:
[podcast on js jabber](https://devchat.tv/js-jabber/207-jsj-growing-happy-developers-with-marcus-blankenship)
### Podcsat: SE Radio with <NAME> on "Developer Anarchy"
<NAME> has the opportunity to be working in a field where your software product can be deployed in a fast paced manner and get feedback equally rapid (online advertising). In this podcast he talks about what changes this brings to the agile process and how well a managerless approach works here. He agrassively calls it "developer anarchy". Unfortunately this does not fit all:
[podcst on se radio](http://www.se-radio.net/2016/03/se-radio-episode-253-fred-george-on-developer-anarchy/)
### Tweet: Ebay starts looking into D
Finally another big company starts to play around with D and it is nothing less than ebay:
<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">EBay discovers <a href="https://twitter.com/hashtag/Dlang?src=hash">#Dlang</a>! <a href="https://t.co/qpjOttnfFo">https://t.co/qpjOttnfFo</a> <a href="https://t.co/CGak4FWcEm">https://t.co/CGak4FWcEm</a></p>— D Language (@D_Programming) <a href="https://twitter.com/D_Programming/status/720310640531808261">April 13, 2016</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
### Post: "PGO: Optimizing D's virtual function calls"
Read about LDC the LLVM based D compiler does optimize virtual function calls now:
[PGO for D](https://johanengelen.github.io/ldc/2016/04/13/PGO-in-LDC-virtual-calls.html)
### Dconf 2016
Finally the soon to be held dconf schedule is out and it is going to be awesome:
[Dconf 2016 Schedule](http://dconf.org/2016/schedule/)
I am especially excited to hear about Remedys usage of D in their latest AAA game Quantum Break by <NAME>: "Quantum Break: AAA Gaming With Some D Code" [link to talk](http://dconf.org/2016/talks/watson.html)
<file_sep>jekyll serve --unpublished --config _config.local.yml
<file_sep>---
title: "#dlang, annotations and menus"
date: 2015-05-28 18:00:00
categories: [dlang, metaprogramming, imgui]
---
What do menus and annotations have to do with the [D programming language](http://dlang.org/) ?
These three aspects form a very nice little system in my current spare time project of a game engine called [unecht](https://github.com/Extrawurst/unecht).
The whole engine borrows a lot of ideas and concepts from the [Unity3D game engine](http://unity3d.com/) and one of these concepts is the way the editor is extendable through user scripts in a conveniant way.
In any user defined class Unity3D allows you to define a static function that automatically appears in the editor menu when annotated like this:
{% highlight csharp %}
[MenuItem ("MyMenu/Do Something")]
static void DoSomething () {
Debug.Log ("Doing Something...");
}
{% endhighlight %}
Clicking this menu entry will call the DoSomething function. I like this design a lot, it is simple and easy to grasp.
So unecht mimicks this behaviour fairly similar with code like this:
{% highlight d %}
@MenuItem("MyMenu/Do Something")
static void DoSomething () {
...
}
{% endhighlight %}
The only difference is that this code is compiled and that the whole magic for this to work happens at compile time.
In this implementation though I improved the design for validation functions (These functions get called to determine if a certain menu item should be enabled right now).
Unity3D makes you annotate these functions in a very specific way so that they match the name of the menuItem they correspond to.
Errors like typos or a wrong signature are first caught at runtime.
In unecht it is as simple as adding a second parameter to the annotation which has to be another static method that returns a boolean:
{% highlight d %}
static bool ValidateDoSomething () {return true;}
@MenuItem("MyMenu/Do Something", &ValidateDoSomething)
static void DoSomething () {
...
}
{% endhighlight %}
If the validation function has a wrong signature or there is some typo these errors are all get caught already at compile time.
The end result is demonstrated here:

Elegant implementations like these allowing such simple designs in the user code are what I like about D.
Although I am still missing a good getUDA/hasUDA method in the standard library to query for type annotations in D! It is a shame that these are being implemented by everyone in their libraries again and again.
For reference: the GUI itself uses [cimgui](https://github.com/Extrawurst/cimgui) (see my post about cimgui [here]({% post_url 2015-04-26-cimgui %})) wrapped for D based upon the fantastic [imgui](https://github.com/ocornut/imgui) c++ library by <NAME>.
I am using the about to be released 1.39 version here that supports the new menu API.<file_sep>---
title: "Developing Atlassian Bitbucket plugins"
date: 2018-10-23 9:00:00
categories: [general]
---
At work we are using bitbucket server for our source code and slack for our communication.
The following gives you an insight into how to make a bitbucket plugin that talks to Slack.
{: .center-image }
## The Why
My team at InnoGames is responsible for a long list of repositories and is heavily utilizing pull-requests to do code-review.
PRs were lying around a lot unless authors pro-actively asked for reviews. So we wanted to automate this better and found a bitbucket plugin that forwards pull-request reviews to slack: Stash2Slack ([see in Marketplace](https://marketplace.atlassian.com/apps/1213042/slack-notifications-plugin)).
Unfortunately Stash2Slack turned out not to have a rest api to have its settings configured which is a requirement for us since we have automation of settings configuration on our multitude of repositories (we checked the [source code on github](https://github.com/pragbits/stash2slack)).
I decided to add this feature to the plugin and this post is a summary on steps necessary to develop a bitbucket plugin that I wish I had when I started.
The following is a short recap of the (sometimes) not so obvious steps to take to work on an Atlassian Bitbucket plugin.
* find the plugin here: [Stash2Slack on Atlassian Marketplace](https://marketplace.atlassian.com/apps/1213042/slack-notifications-plugin)
* find the source of this plugin here: [Stash2Slack Github](https://github.com/pragbits/stash2slack)
## The Setup (on mac)
Three simple steps to get up and running:
* Install prerequisites
* Run local BB server
* Build/Deploy/Test your plugin
### Install Prerequisites (see [Atlassian Docs](https://developer.atlassian.com/server/framework/atlassian-sdk/set-up-the-atlassian-plugin-sdk-and-build-a-project/))
* JDK
* check `javac -version` (tested with 1.8.0_121)
* check `java -version`
* Atlassian SDK using brew `brew install atlassian/tap/atlassian-plugin-sdk`
* check `atlas-version` (tested with 6.3.10)
### Run local BB server
* Start server process
* run `atlas-run-standalone --product bitbucket`
* *this runs a bitbucket server instance in foreground (so you can overlook the stdout)*
* Server state / clean server
* `cd amps-standalone-bitbucket-LATEST/`
* *this folder is used to persist the entire servers state, if you want a clean install, just delete this one*
* Debug logs
* run `less amps-standalone-bitbucket-LATEST/target/bitbucket/home/log/atlassian-bitbucket.log`
* *now you can search/follow the log for anything you print with log4j*
### Run your plugin
* Build your plugin
* run `atlas-package` where your plugins `pom.xml` is located
* *this will run maven build scripts to create the plugins .jar*
* Install plugin in running server
* run `atlas-install-plugin` next to the `pom.xml` again
* *this will install the plugin into the running bitbucket server instance*
## The actual change
Now the actual change was pretty simple:
* add a rest description to the plugin manifest
* add a standard spring style REST endpoint
See the manifest changes here:
```xml
<rest key="slack-rest" path="/stash2slack" version="1.0">
<description>Stash2Slack Rest API</description>
</rest>
```
See an example REST endpoint here:
```java
@Path("/settings")
public class RestResource {
...
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getGlobalSettings() {
validate(() -> validationService.validateForGlobal(Permission.ADMIN));
return Response.ok(getDTOFromGlobalSettings(globalSettingsService)).build();
}
}
```
Find the entire changeset [here on github](https://github.com/pragbits/stash2slack/pull/71/files).
## Outlook
This was obviously just a quick overview but working with atlassian plugins seems fun and I found a couple of possible improvements I would like to tackle.
### Debug local instance
For my testing so far I did not need to connect via debugger right into my plugin but I can see how knowing how is beneficial.
So here is an explanation on how to run your local instance to be able to debug it (on port 8000): [Run in debug mode](https://scriptrunner.adaptavist.com/4.3.5/bitbucket/DevEnvironment.html#_b_new_app_with_a_href_https_developer_atlassian_com_docs_developer_tools_working_with_the_sdk_command_reference_atlas_run_standalone_atlas_run_standalone_a)
And here you find how to configure your IntelliJ to be able to connect to it: [Setup IntelliJ](https://scriptrunner.adaptavist.com/4.3.5/bitbucket/DevEnvironment.html#_3_create_debug_configuration_in_idea)
### Thread support to improve readability
For now the plugin dumps all updates into a single slack channel sequentially. As said we handle a lot of repositories and one thing I would like to integrate is thread support for those messages to have a cleaner overview (one thread per PR).
Unfortunately this is not that easy so it ended up in the backlog: The simple webhooks for sending slack messages does not support threading so this idea was a deadend unless I want to invest into a bigger more sophisticated implementation.
Although I see a lot of opportunities to cleanup the current code that creates the webrequests manually when switching to [jslack](https://github.com/seratch/jslack) (a very nice java client lib for communicating with slack)
### Server State and Active objects
Another problem I came across is the flawed way settings are saved. This manifests in this plugin being very error prone when used in a bitbucket server setup with multiple nodes.
It uses `PluginSettings` to store settings which are not synchronized between nodes and it should use `ActiveObjects` which is even stated in this forum thread: [here](https://community.atlassian.com/t5/Answers-Developer-Questions/JiraPluginSettings-with-Data-Center/qaq-p/529283) - too bad the docs for atlassian plugin development are rather lacking.
### Repo is dormant
My addition to the plugin in shape of a [PR](https://github.com/pragbits/stash2slack/pull/71) is completely ignored now, no wonder since the repo was not updated in a year. The author clearly moved on. I would like to dig into how to distribute an Atlassian plugin to maybe supply this updated version to a broader audience. If only I had time...
<file_sep>---
title: "Worth Reading (April 2015)"
date: 2015-04-15 17:00:00
categories: [reading, networking, physics, unity]
---
The following stuff is what caught my eye in the last couple of weeks. Consider this post an entry in my personal knowledge base ;)
### "Networking for Physics Programmers" at GDC2015
<NAME> - famous for his insightful [blog](http://www.gafferongames.com) and games like Titan Fall - speaks about his accumulated experience about networking physics in large AAA games.
* [Blog Post](http://gafferongames.com/networked-physics/introduction-to-networked-physics/)
* [GDC Vault Video](http://gdcvault.com/play/1022195/Physics-for-Game-Programmers-Networking)
### "New Unity Networking" at Unite 2014
<NAME> - working for Unity - presents the new Networking System (formerly known as UNET) that Unity integrates in Unity 5.x. It shows how intuitive an interface can be to allow even non-engineers create descent multiplayer experiences.
<iframe width="560" height="315" src="https://www.youtube.com/embed/ywbdVTRe-aA" frameborder="0" allowfullscreen></iframe>
* [Announcement Post](http://blogs.unity3d.com/2014/05/12/announcing-unet-new-unity-multiplayer-technology/)<file_sep>---
title: "Apple osx app bundles with #dlang"
date: 2015-06-29 21:00:00
categories: [code, osx, dlang]
---
Recently I wanted to package an application that I have written in D so that it would feel like a native osx application bundle. Nothing fancy.. Boy little did I know..
Even though an app bundle is nothing more than a special kind of folder structure that an osx finder interprets in a special way.
Actually it is pretty hairy to create such a bundle by hand without the help of XCode.
Since I am in dland nothing is normal so here is how you do it:
### "App Bundles with a Makefile"
<NAME> wrote an excellent blog post about the creation of an app bundle using makefiles and that was the foundation of my work:
[blog post](http://joseph-long.com/writing/app-bundles-with-a-makefile/)
Using these instructions got me to the point where I had an app bundle that started on my system.
Still no app icon or bundled dependencies.
### App Icon
Defining the app logo is 'just' a matter of adding a compatible image file and modifying the Info.plist file of the app:
{% highlight xml %}
...
<key>CFBundleIconFile</key>
<string>iconfile</string>
...
{% endhighlight %}
Unfortunately an ICNS File is needed.
So here I was with my icon PNG and found these instructions to convert it to the appropriate format:
[SO Thread](http://stackoverflow.com/questions/12306223/how-to-manually-create-icns-files-using-iconutil)
Now we have an app logo and still need to fix the dependencies...
### How to find locations inside app bundles
So the last bastion was to use the bundle to bundle up the necessary frameworks and dependencies with it. This allows us to save the user the trouble of installing all kinds of libs and maybe even having to built libs themselves.
Since we use dynamic bindings of libs like SDL the binary of our app looks for those *.dylib files in system folders and near the executable itself. The problem is that even though the bundle is just a folder the current directory maybe total different and in this current working dir it is where the bindings look for the dynlib files.
I found the solution in [this SO Thread](http://stackoverflow.com/a/520951/2458533) explaining how to query the system for bundle paths:
{% highlight c %}
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::cout << "Current Path: " << path << std::endl;
{% endhighlight %}
The next problem was how to do this in dland? Well actually pretty straight forward with yet another dynamic binding to the CoreFoundation Framework of the osx system itself...
### CoreFoundation library bindings for D
To be able to use the system libs you need to have bindings which I created (with JUST the functionality needed for this case, so please feel free to add and PR):
* [dub package](http://code.dlang.org/packages/derelict-cf)
* [github repository](https://github.com/Extrawurst/DerelictCF)
Using these bindings we can do the exact same as in the c++ example above and change the working directory appropriately after app start.
Now we are finished, we can use whatever content we bundle up in the app and give it an icon image!
### "Bundle Programming Guide"
The rest of the info needed and for reference here are the official docs by Apple: [bundle programming guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html)
<file_sep>---
title: "Worth Reading (March 2015)"
date: 2015-03-14 18:30:00
categories: [reading, programming, cpp]
---
The following stuff is what caught my eye in the last couple of weeks. Consider this post an entry in my personal knowledge base ;)
### Talk about Efficiency at CppCon2014
<NAME> gave a talk named "Efficiency with Algorithms, Performance with Data Structures" at CppCon2014 that I just recently saw and advice everybody to watch.
<iframe src="//channel9.msdn.com/Events/CPP/C-PP-Con-2014/Efficiency-with-Algorithms-Performance-with-Data-Structures/player" width="960" height="540" allowFullScreen frameBorder="0"></iframe>
He talks about effective algorithms and performance of data structures on modern CPUs in our post-moore's-law-world. He considers Linked-Lists and HashMaps evil and advises us to use std::vector whereever possible. But don't think there is nothing to learn there if you are a java guy!
### DOD and Entity Systems
These topics are somewhat related and caught my interest especially in the last couple of weeks.
Data Oriented Design is related to the talk above because it tries to optimize data structures for fast cache aware processing.
Entity Systems are the foundation for game engines like unity3D that model the game logic in a very modular and decoupled way.
Artemis is a very nice example of an Entity System Framework written in Java.
I whish I find the time to make use of these very interesting concepts in my next game project.
* [Data Oriented Design Presentation](https://www.youtube.com/watch?v=16ZF9XqkfRY)
* [Blog posts about Entity Systems](http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/)
* [artemis website](http://gamadu.com/artemis/index.html)
* [GDC Talk: Data Driven Gameobject System](http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides.pdf)
<file_sep>---
title: "Live-Ask.com"
date: 2018-04-02 12:00:00
categories: [general, webdev]
---
[Live-Ask.com](https://www.live-ask.com) provides a simple, free, and real-time service for the audience to ask questions before and during panel discussions, conference presentations, meetups, and more. Think of Live-Ask as your one-stop solution for moderating discussions.
{: .center-image }
# Background
The idea for Live-Ask evolved while being the organizer of one of the biggest meetup groups in Hamburg, Germany – the [Hamburg Unity Meetup](https://www.meetup.com/Hamburg-Unity-Meetup/)! With over 530 awesome members and 8 organized events, our group has been meeting since 2016.
{: .center-image }
Initially, our meetups consisted of two speakers and time for socializing and networking afterwards. When we sensed our members were craving more, we decided to introduce a discussion panel guided by audience-driven topics.
While we were excited about our new feature, we worried that the audience might not feel courageous or engaged enough to ask questions.
We took a proactive approach in advance by gathering questions, ideas, and topics that would fill our first discussion-focused event. We displayed these talking points in a slide during the discussion. This solution worked in the moment, but it left room for improvement.

We wanted an interactive option, allowing our audiences to ask questions in real-time and vote on topics that they liked. After scouring the internet and app options, we found that our ideal solution didn’t yet exist. The idea for Live-Ask was born.
# The platform
Live-Ask was born out of our desire to create a platform that made it easy to moderate group discussions. Using Live-Ask, one can easily create an event, invite participants to contribute questions and topics, and give participants the opportunity to vote on what they’re interested in. Live-Ask is all online, cross-platform, and interactive.
This is what our Unity Meetup discussion could have looked like, if we had used Live-Ask:
{: .center-image }
In the above view the participant can vote on questions by a simple click and see the list of questions ordered by the number of votes. The page is always up to date and shows everyone's changes in real-time.
Events like these are all about the social dimension, so Live-Ask makes it as simple as possible to share. Simply click the 'share' button and pick one of the many options to send a simple short link to friends and colleagues. Participants do not need any registration aswell, just open the link and participate.
{: .center-image }
# Summary (tl;dr)
Live-Ask...
* provides a simple event setup for a moderator, with no login necessary
* is open and anonymous for everyone - just share a link
* allows participants to easily add any question to a discussion
* operates in real time – see what others vote for instantly
* works on all platforms – use it on your phone, tablet, or laptop
* is completly free to use
so go visit [Live-Ask.com](https://www.live-ask.com) now.
# Where to use Live-Ask
* meetups
* conference talks
* panel discussions
* company Q&A sessions
* video live streams
* ...
# How to use Live-Ask
* Drop a QR code into your slides
* Share a link via social media or email
We are passionate about growing and improving Live-Ask to make it the perfect solution for you. Reach out to us on Twitter at [@liveask1](https://twitter.com/liveask1).<file_sep>---
title: "Video Lunch"
date: 2017-08-10 21:00:00
categories: [general, leadership]
---
[img]: {{ site.url }}/assets/night-television-tv-theme-machines.jpg "img"
As mentioned in my last “[worth reading](http://blog.extrawurst.org/reading/2017/08/07/worthreading.html)” (which was really a ‘worth watching’) my team and I do Video Lunches regularly. This post focuses on that great concept and hopefully leaves you considering it in your team as well. Note that you don’t have to be the lead of your team to be able to do this.
## Concept
* Video Lunch happens roughly every two weeks.
* We order in food (perfect for bad weather as well).
* We gather video suggestions in a backlog.
* Everyone can suggest videos.
* We vote upfront for videos from the backlog.
* We eat and watch together.
* Optional: we ask for opinions afterwards to shape a discussion.
* Mandatory: we learn and enjoy :)
![alt text][img]
## Video Lunch Background
For me learning is daily business. I am a believer in [live long learning](https://medium.com/r/?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FLifelong_learning). One great source to learn from is inspiring speakers, udacity lessons, conference talks, TED talks or essentially any other video you think is interesting.
Youtube offers over [500 petabyte](https://medium.com/r/?url=https%3A%2F%2Ftechexpectations.org%2Ftag%2Fhow-much-data-does-youtube-store%2F) in videos, how do I ever watch everything that might be interesting for me? There is simply just so much **time**, right? That’s why finding additional slots to squeeze in time to learn from these is a win! Our video lunches are a great way to sneak in such time.
> “Man is by nature a social animal” (Aristotle)
The social animal I am I get less distracted when watching something when I am not alone. But what is even better is to be able to **discuss** what you saw afterwards. If you are easily excited like me you want feedback on stuff you are psyched about right away and not wait until someone found the time to watch it, too.
Aside from being able to discuss the video and get **others perspective** on it I usually tend to remember things better when I was able to talk about it. I am a very auditive person so my mind works this way and I **memorize** more easily.
> “Man is largely a creature of habit” (<NAME>)
When your team reaches a certain size maintaining a healthy team spirit and culture is not as easy anymore as being just two or three people. Naturally sympathy varies and sub groups emerge and tend to stick together because we are creatures of habit. Shared, uniting activities like team events cannot be held every week but concepts like the team lunch are easy for members to buy in and have the benefit of subtle **team building** on top of the other advantages. You talk to people that otherwise you did not know much about maybe, you learn to respect their opinions and interests.
## Benefits Summary
* Time effective utilizing the lunch break
* Uniting bigger teams / team building
* Knowledge sharing, looking outside the box (breaking habits)
* Discussions lead to better memorizing
* Little management overhead
Of course this is a concept not new but I rarely hear it happening at other teams or companies. I can just suggest to try it out and obviously adjust it accordingly to your teams needs.
Happy watching! 📺<file_sep>---
title: "Worth Reading (October 2015)"
date: 2015-10-29 19:00:00
categories: [reading, dlang]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
###Book: "Endurance: Shackleton's Incredible Voyage"
[Amazon.com link](http://www.amazon.com/Endurance-Shackletons-Incredible-Alfred-Lansing/dp/0465062881)
I found this book by <NAME> absolutely stunning. Both a great adventure and a documentary about one of the most spectacular expeditions in modern history. It tells the story of an trans-antartic expedition turned into an breathtaking adventure of an inspiring leader trying to save the lives of his crew. This story is not only tense and freaking real it is an extraordinary example of inspiring leadership!
###Post: "SpringSource Certified Spring Professional" by <NAME>
[Blog Post](http://jakubstas.com/springsource-certified-spring-professional)
I was looking for information on a Spring Certification and stumbled upon this very interesting blog post from a guy who took this certification too.
###Post: "Using Google Protocol Buffers with Spring MVC-based REST Services"
[Spring.io Post](https://spring.io/blog/2015/03/22/using-google-protocol-buffers-with-spring-mvc-based-rest-services)
In this post it is described how to make Spring able to return webrequest results in protobuf format automatically.
Note: Maybe worth mentioning to be sure to add maven project "protobuf-java-format" into the dependencies to be actually able to convert proto results to json etc.
###Sound Library: "SoLoud" by <NAME>
Thanks to a twitter tweet (that I can't seem to find again) I stumbled upon this nice little sound library:
[SoLoud](http://sol.gfxile.net/soloud/index.html)
It is crossplatform and feature most of the features that an indie dev needs and more. I was always looking for a really free alternative to [fmod](http://www.fmod.org/) and will definitely look into this as soon as I find the time. Especially since it features a [dlang](http://dlang.org/) binding right off the shelve: [SoLoud D-API](http://sol.gfxile.net/soloud/d_api.html).
###Post: "es_core: an experimental framework for low latency, high fps multiplayer games" by TTimo
[Blog Post](http://ttimo.typepad.com/blog/2013/05/es_core-an-experimental-framework-for-low-latency-high-fps-multiplayer-games.html)
TTimo talks about an interesting multiplayer game engine design specificly with low latency FPS multiplayer games in mind. He uses a highly concurrent design with no data sharing but message passing only while avoiding copys and "all memory heap operations". I like this design, I maybe adopt some of it in [unecht](https://github.com/Extrawurst/unecht) once I finally have some time to work on that again!
<file_sep>---
title: "General Update"
date: 2015-11-01 16:00:00
categories: [general, dlang]
---
I want to use this way to announce some news that I did not have the time to blog about. These news divide esentually in two categories: career and projects update:
##Career Update:
Since August 2015 I am back to the games industry! After an intermezzo as a consultant I am now a Team Lead Software Developer at [InnoGames](https://www.innogames.com/) in Hamburg, Germany. I love to be back in this vibrant and challenging branche.
I am lucky and have the opportunity to lead my team from the ground up in a whole new and exciting project. If you are an experienced Unity3D Developer or Java Backend Developer and you would like to work with me please drop me a line or find infos on these jobs here: [InnoGames Careers](http://corporate.innogames.com/de/career/jobs.html)
##Project Updates:
There are also some new open source efforts that maybe of interest:
####[bgfxd-examples: bgfx examples ported to D](https://github.com/Extrawurst/bgfxd-examples)
I started to like [bgfx](https://github.com/bkaradzic/bgfx) a lot and since there are [D bindings](https://github.com/DerelictOrg/DerelictBgfx) I tried to learn using it by porting the official examples to D. I did not finish a lot yet but it is an ongoing process.

####[file2d: create embedable files in/for D](https://github.com/Extrawurst/file2d)
This little helper was designed to create embedable binary files for D. You can pass in any file and it will be read as binary and converted to a module containing a symbol that contains this files content as a hex string like this:
{% highlight d %}
static immutable ubyte[1234] = [0x12, ...];
{% endhighlight %}
####[FMOD D Bindings](https://github.com/Extrawurst/DerelictFmod)
I created and maintain [FMOD](http://www.fmod.org/) bindings for the D programming language for a couple of months now but I only recently added a simple but illustrative application on how to actually use it in D. See the example app [here on github](https://github.com/Extrawurst/DerelictFmod/blob/master/source/app.d)
Actually it uses a freeware sound converted to compile time string using file2d mentioned above (and it is this usecase for which i created file2d)
####[Steamworks D Bindings](https://github.com/Extrawurst/DerelictSteamworks)
I also created Steamworks SDK bindings a couple of months back already. The first version of the SDK that was supported is 1.34 since it was the first that included the c-api that I am binding. The Bindings include a simple demo app too to demonstrate on how to use the API.
<file_sep>---
title: "unity coroutines at editor time"
date: 2016-09-06 02:00:00
categories: [unity, general]
---
Did you ever try to do non-blocking [WWW](https://docs.unity3d.com/ScriptReference/WWW.html)-requests in Unity without being in playmode ? Then you know about the problems here:
* WWW uses coroutines to be used non-blocking
* Coroutines do not work outside the playmode
* Triggering a coroutine in the editor using Update only works with an Editor-Window
The solution is twofold:
* Use [EditorApplication.update](https://docs.unity3d.com/ScriptReference/EditorApplication-update.html) to 'tick' in non-playmode
* Trigger coroutine manually
Pseudocode says more than a thousand words:
{% highlight csharp %}
IEnumerator coroutine;
void Init()
{
EditorApplication.update += EditorUpdate;
// StartRequest is build like a normal
// coroutine and yield returns on WWW
coroutine = StartRequest();
}
void EditorUpdate()
{
coroutine.MoveNext();
}
{% endhighlight %}
This does the trick and is not widely known unfortunately. Using EditorApplication.update we can register arbitrary callbacks that get called periodically in Editor-Mode.
Additionally understanding unity coroutines is necessary to understand what we are doing here:
A coroutine is nothing but a resumable method that is identified by the return type ```IEnumerator``` and the usage of ```yield return xyz;``` in its body.
Under the hood it works by 'someone' calling [MoveNext](https://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext(v=vs.110).aspx) of its IEnumerable interface. Usually this 'someone' is Unity internally. But since that does not happen outside the playmode we can force it to still do the same by calling it manually.
Final note: [EditorApplication.timeSinceStartup](https://docs.unity3d.com/ScriptReference/EditorApplication-timeSinceStartup.html) is great for actual timing in the registered update-callback.
<file_sep>---
title: "Github Pages"
date: 2015-03-14 16:30:00
category: general
---
Recently I decided to start a new blog/website based on Github Pages.
For now this site runs in parallel with my old website [www.extrawurst.org](www.extrawurst.org) but eventually this pages is gonna be shutdown.
This post is about my first impressions using Github Pages!
TL;DR; These are my findings:
* Easy to setup
* Easy to edit
* Git Integration
* No hosting hustle
--- Setup ---
The setup was extremly easy following the steps on github itself: [https://pages.github.com](https://pages.github.com)
Github Pages supports jekyll to design and write your static pages: [http://jekyllrb.com/](http://jekyllrb.com/)
Then I browsed jekyll themes here: [http://jekyllthemes.org/](http://jekyllthemes.org/)
Finally I choose one and simply forked it on github - nifty!
To be able to test the site and write posts locally before committing you can setup jekyll on your machine:
{% highlight sh %}
~ $ gem install jekyll
~ $ jekyll new my-site
~ $ cd my-site
~/my-site $ jekyll serve
# => Now browse to http://localhost:4000
{% endhighlight %}
Ok then I thought "how to enable comments by the readers on a statically deployed site?" - Here [disqus.com](https://disqus.com/) comes to the rescue and enables to outsource the whole commenting feature to a service - nifty again!
--- Editing ---
Posts are written in markdown just like wiki pages on Github. For those like me who write markdown just rarely enough not to remember the details here are the docs: [Markdown](http://daringfireball.net/projects/markdown/syntax)
--- Git Integration ---
Since Github Pages deploys the website right from your github repo publishing a new post is just a matter of commit/push - nifty!
Then again maybe this is a feature that only developers really can appreciate ;)
--- No hosting hustle anymore ---
That is the main reason for me to switch. I always have periods where I have time to post occasionally and keep my page up to date but then there comes the time when I don't and then my old wordpress page gathered a backlog of updates and eventually unmaintained plugins that are rendered incompatible... sigh. Then there is always the problem with keeping the vserver up to date and the security risks arising from self hosting. All this is gone with this approach and since I don't mind for my blog to be open source Github Pages is a perfect fit for me!
<file_sep>---
title: "Worth Reading (January 2016)"
date: 2016-01-31 15:00:00
categories: [reading, unity]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
### Podcast: "<NAME> on Marketing Yourself and Managing Your Career"
Really interesting podcast that I encourage every software developer to hear:
"<NAME> talks to <NAME>, the author of Soft Skills—'the software developer’s life manual.'"
[Podcast on se-radio.net](http://www.se-radio.net/2015/12/se-radio-episode-245-john-sonmez-on-marketing-yourself-and-managing-your-career/)
### Unity: "ASSETBUNDLES AND THE ASSETBUNDLE MANAGER"
A really useful kickstart on the how-tos of using asset bundles in unity on the official unity blog:
[Blog Post on unity3d.com](https://unity3d.com/learn/tutorials/topics/scripting/assetbundles-and-assetbundle-manager)
### Modeling for Coders
* [creating a 3d star wars scene in voxels](http://blog.sketchfab.com/post/135254660559/tutorial-creating-a-3d-star-wars-scene-in-voxels)
* [Turning Pixels sprites into voxels](http://forum.zdoom.org/viewtopic.php?f=39&t=45680)
* [MagicaVoxel Tutorial- Trove Edition](https://ritztales.wordpress.com/2014/07/18/magicavoxel-tutorial-trove-edition/)
The mentioned tools:
* Voxelshop: [https://blackflux.com/node/11](https://blackflux.com/node/11)
* MagicaVoxel: [https://ephtracy.github.io/](https://ephtracy.github.io/)
Here is my little take on being an artist. I converted the 2d pixel art of one of my previous games to 3D with this outcome:
<blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">first steps as an artist :D converted my <a href="https://twitter.com/hashtag/beachwars?src=hash">#beachwars</a> <a href="https://twitter.com/hashtag/pixelart?src=hash">#pixelart</a> to 3D using <a href="https://twitter.com/hashtag/magicavoxel?src=hash">#magicavoxel</a> <a href="https://t.co/M2zetP3Ot1">pic.twitter.com/M2zetP3Ot1</a></p>— <NAME> (@Extrawurst) <a href="https://twitter.com/Extrawurst/status/683712335769415680">January 3, 2016</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
### Github: "A pixel art generator on a Unity custom inspector"
This little project allows to randomly generate pixel art graphics directly inside of unity:

[PixelArtGen](https://github.com/abagames/PixelArtGen)
### OpenSource: Lock-Free Data Structures
liblfds is "a portable, license-free, lock-free data structure library written in C", with extensive testing on all the different platforms:
[www.liblfds.org](http://www.liblfds.org/)
### Post: "The Hardest Program I've Ever Written" by <NAME>
[journal.stuffwithstuff.com](http://journal.stuffwithstuff.com/2015/09/08/the-hardest-program-ive-ever-written/)
<file_sep>---
title: "Alexa Skill written in D"
date: 2017-01-06 16:00:00
categories: [programming, dlang, alexa]
---
<img style="float: right; padding-left: 10px; width: 300px" src="{{ site.url }}/assets/alexa-plus-dlang.png"/>
As I wrote last week in my post [about Alexa](http://blog.extrawurst.org/reading/programming/dlang/alexa/2017/01/01/alexa.html) I started looking into developing custom skills for Alexa.
Custom Skills for Alexa are like apps for mobile devices. Amazon makes it easy to upload the source into their Lambda service. Custom Skills are webservices - everyhing happens in the cloud. [Amazon Lambda]() lets you choose between:
* C#
* Java
* Nodejs
* Python
When facing the options I remembered the article I read on the [dlang forums](http://forum.dlang.org) about how to use a D application in there. [AWS Lambda Functions in D](http://awslambda-d.readthedocs.io/en/latest/)
## Why D then?
So why chose D over the alternatives ?
* blazing fast
* statically typed
* insane compile time functionality
* personal taste and freedom to choose
Blazing fast ? Yes this is meant in two ways:
1. fast compile time
2. fast execution time
**The dlang was designed to be fast** - written by a experienced C++ compiler writer it was created to be compiled in a faster way.
And since D is a system programming language and even shares the same compiler backend as a lot of other system languages it is equally fast as C++ and co.
Why is performance especially interesting for an Alexa Skill? Because if you host it on AWS Lambda you pay per use - this means you pay per CPU/memory usage.
**Template programming for the sane** - D has a [meta programming](https://en.wikipedia.org/wiki/Metaprogramming) capability that is so strong because it allows the average programmer to go wild in it. I am using this to delegate incoming requests to the right endpoint [here](https://github.com/Extrawurst/alexa-skill-kit-d/blob/master/source/ask/alexaskill.d#L54) and to create simple to use [REST interfaces](http://vibed.org/docs#rest-interface-generator) to existing services like [openwebif](https://github.com/Extrawurst/openwebif-client-d)
You are not familiar with D yet? Then I have some resources for you to start:
* [dlang feature overview](http://dlang.org/overview.html)
* [free online book](http://ddili.org/ders/d.en/index.html)
* [vibe.d](http://vibed.org/features) (the web framework I am using)
* great article for people who came from C++ like me: [How-does-D-improve-on-C++17](https://p0nce.github.io/d-idioms/#How-does-D-improve-on-C++17?)
## How does it work?
steps (tl;dr):
0. prepare nodejs wrapper
1. start up vagrant box
2. build linux binary
3. bundle zip for upload to lambda
4. upload to lambda
5. do a test invoke of lambda function
6. setup alexa skill in Amazon developer console
7. talk to a D application :)
### Nodejs wrapper (0.)
This is necessary since Amazon Lambda does not natively support dlang in their service. I chose nodejs because I had the basis for the wrapper already in the mentioned "D in Lambda" [article](http://awslambda-d.readthedocs.io/en/latest/).
### Vagrant and bulding ... (1. - 5.)
Since Amazon Lambda is powered by linux machines we have to build a Linux binary of our D application. I am a mac and windows user, so I had to find a way to build and test my code on linux. Previously I would have set up a virtual box myself but I rememberd how tedious and error prone that is and decided to give [vagrant](https://www.vagrantup.com/) a try. This makes the setup of exactly the kind of machine I needed a piece of cake:
{% highlight ruby %}
Vagrant.configure(2) do |config|
config.vm.box = "centos72"
config.vm.provision "shell", path: "src/vagrant/install.sh", env: {
"IN_OPENWEBIF_URL" => ENV['OPENWEBIF_URL'],
"IN_AWS_LAMBDA_NAME" => ENV['AWS_LAMBDA_NAME'],
"AWS_REGION" => ENV['AWS_REGION'],
"AWS_KEY_ID" => ENV['AWS_KEY_ID'],
"AWS_KEY_SECRET" => ENV['AWS_KEY_SECRET']
}
end
{% endhighlight %}
As you can see it is based on a centos machine (that apparently is closest to the amayon AMI images) and only sets a couple of environment variables that we need to access AWS. The rest of the initialization of the box is delagated to a [install.sh](https://github.com/Extrawurst/alexa-openwebif/blob/master/src/vagrant/install.sh) script that is run on first boot:
* install depedendencies like libevent
* download and install dmd d compiler
* download and install aws cli tool
* setup environment variables
* setup aws cli config based ont provided env
Using this box I have a new dev machine up and running after 2 minutes.
Then it is just a matter of running the `run.sh` ([see on github](https://github.com/Extrawurst/alexa-openwebif/blob/master/src/run.sh)) in the box and it will compile, bundle, upload, configure and test the lambda function to and on AWS.
### Setup alexa skill (6.)
This is a whole different beast unfortunately. Amazon does not yet support cli/remote control of their Amazon developer console. This means you have to setup the skill manually in a web interface. There are lots of tutorials on how to do that though and all the information needed to fill in the fields that my skill expects are in the repository: [speech assets](https://github.com/Extrawurst/alexa-openwebif/tree/master/speechAssets).
Fortunately Amazon acknowledged this to be a big concern by developers and claims to be working on it.
One tutorial I found very good to follow by Amazon: [Build a Trivia Skill in under an Hour](https://developer.amazon.com/blogs/post/TxDJWS16KUPVKO/new-alexa-skills-kit-template-build-a-trivia-skill-in-under-an-hour)
### Talk to a D application (7.)
So what can this skill do for me now ?
Alexa is capable of controlling my televison tuner now and reacts to sentences like these now (although it is only in german currently):
Alexa, ask telly what is currently running
Alexa, ask telly for a list of channels
Alexa, ask telly what I recorded
Alexa, mute with telly
Alexa, switch to CNN with telly
Alexa, ask telly to go to standby
Alexa, start recording with telly
Alexa, ask telly to go to sleep in 30 minutes
You can find that skill on github: [alexa-openwebif](https://github.com/Extrawurst/alexa-openwebif)
<iframe src="https://player.vimeo.com/video/198379430?title=0" width="320" height="569" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="display:block; margin: 0 auto;"></iframe>
<file_sep>---
title: "#dlang Fibers and a lightweight eventloop"
date: 2015-05-31 12:00:00
categories: [dlang, gamedev, events, fibers]
---
###D and Fibers
[Fibers](http://dlang.org/phobos/core_thread.html#.Fiber) are D's concept for resumable functions and the barebone behind the popular event driven framework [vibe.d](http://vibed.org/).
In the [unecht](https://github.com/Extrawurst/unecht) project I recently added a generic system to use resumable functions much like [Unity3D](http://unity3d.com/) supports it using their [coroutine system](http://docs.unity3d.com/Manual/Coroutines.html).
In Unity3D a simple usage example is this:
{% highlight csharp %}
IEnumerator DeferedPrint() {
Debug.Log("hello");
yield return new WaitForSeconds(1f);
Debug.Log("... 1s later");
}
// start the coroutine:
StartCoroutine(DeferedPrint);
{% endhighlight %}
The same behaviour in D and unecht looks like this:
{% highlight d %}
void DeferedPrint() {
writefln("hello");
UEFibers.yield(waitFiber!"1.seconds");
writefln("... 1s later");
}
// start the fiber:
UEFibers.startFiber(DeferedPrint);
{% endhighlight %}
###Lightweight Eventloop
The eventloop necessary to allow this is simply resuming all active fibers each frame.
The main addition to the Fibers in the standard library is that each Fiber can have a child Fiber that has to finish before the parent Fiber can resume.
Following code shows a practical example:
{% highlight d %}
@MenuItem("test/deleteAll")
static void removeOnePerX()
{
UEFibers.startFiber({
while(ballRoot.sceneNode.children.length > 0)
{
UEFibers.yield(waitFiber!"200.msecs");
removeBall();
}
});
}
{% endhighlight %}
This way the execution of a single function can be defered over a specific time span. The result of that example is demonstrated here:
{: .center-image }
The whole code of this is available on github [here](https://github.com/Extrawurst/unecht/blob/master/source/unecht/core/fibers.d)<file_sep>---
title: "Worth Reading (July 2015)"
date: 2015-07-22 20:00:00
categories: [reading]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
###Post: "How to Use Docker on OS X: The Missing Guide"
So I recently tried to use [Docker](https://www.docker.com/) on my mac and was tought that even though osx is based on unix it far from similar in running docker on there. Thankfully I found this missing guide about the specifics of using Docker on osx:
[blog post](http://viget.com/extend/how-to-use-docker-on-os-x-the-missing-guide)
###Github: Profilig
I recently extended my native programming toolbox with two additional profilers:
* [lukestackwalker](http://lukestackwalker.sourceforge.net/) similar to [very sleepy](https://github.com/VerySleepy/verysleepy) this is a very simple [sampling profiler](https://en.wikipedia.org/wiki/Profiling_(computer_programming)#Statistical_profilers).
* [brofiler](http://brofiler.com/) this profiler has a very sweet GUI and supports [instrumentation](https://en.wikipedia.org/wiki/Profiling_(computer_programming)#Instrumentation) and sampling
###Github: Command line tutorial
The author writes that "This is a selection of notes and tips on using the command-line that I've found useful when working on Linux" - and indeed it is, go ahead and be amazed what there is that you did not know about using the bash:
[art of command line](https://github.com/jlevy/the-art-of-command-line)
###Github: Terminal recorder
The project page says it can "Record your terminal and compile it to a GIF or APNG without any external dependencies, bash scripts, gif concatenation, etc." and indeed it is based on nodejs and is pretty simple to use:
[ttystudio](https://github.com/chjj/ttystudio)
###Articles: "64 Network DO’s and DON’Ts for Game Engine Developers"
This extensive article series on [ITHare.com](http://ithare.com/) consists of the following parts and is very well written and full of interesting and practical working experience:
* [Part I: Client Side](http://ithare.com/64-network-dos-and-donts-for-game-engine-developers-part-i-client-side/)
* [Part IIa: Protocols and APIs](http://ithare.com/64-network-dos-and-donts-for-game-engine-developers-part-iia-protocols-and-apis/)
* [Part IIb: Protocols and APIs (continued)](http://ithare.com/64-network-dos-and-donts-for-game-engine-developers-part-iib-protocols-and-apis-continued/)
* [Part IIIa: Server-Side (Store-Process-and-Forward Architecture)](http://ithare.com/64-network-dos-and-donts-for-game-engines-part-iiia-server-side-store-process-and-forward-architecture/)
* [Part IIIb: Server-Side (deployment, optimizations, and testing)](http://ithare.com/64-network-dos-and-donts-for-game-engines-part-iiib-server-side-deployment-optimizations-and-testing/)
* [Part IV: Great TCP-vs-UDP Debate](http://ithare.com/64-network-dos-and-donts-for-game-engines-part-iv-great-tcp-vs-udp-debate/)
* [Part V: UDP](http://ithare.com/64-network-dos-and-donts-for-game-engines-part-v-udp/)
* [Part VI: TCP](http://ithare.com/64-network-dos-and-donts-for-multi-player-game-developers-part-vi-tcp/)
* [Part VIIa: Security (TLS/SSL)](http://ithare.com/64-network-dos-and-donts-for-multi-player-game-developers-part-viia-security-tls-ssl/)
### entypo.com
Thanks to Ray for hinting me to this very nice compilation of free cc-licenced vector graphics:
<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">Useful <a href="http://t.co/K8vr0i4dIr">http://t.co/K8vr0i4dIr</a> <a href="http://t.co/jrDrsIcQO1">pic.twitter.com/jrDrsIcQO1</a></p>— <NAME> (@MutantSparrow) <a href="https://twitter.com/MutantSparrow/status/620936370345914368">July 14, 2015</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<file_sep>---
title: "Alexa meets german developer"
date: 2017-01-01 14:00:00
categories: [reading, programming, dlang, alexa]
---
<img style="float: right; padding-left: 10px; width: 350px" src="{{ site.url }}/assets/echo-dot.png"/>
About 2 weeks ago I suddenly got my inventation to order an echo dot. The echo device family is the entry point to using the Alexa natural language processing service from Amazon. That is like having Apple Siri at home, or Microsofts Cortana.
I have to admit I was not entirely sure about this tech befor I got it, simply because of the practical usefulness that I was not able to imagine befor starting to put my hands on it.
### TL;DR
My quick summary: This kind of speech control interface to modern technology (or VUI - Voice User Interface - as Amazon calls it) will revulutionize the way we interact with devices in the near future. I did not expect it to be as far as it is already. There is still things to do like *keeping context* in the 'conversations' but for me the experience was mindblowing: **control your home** using Alexa, control your **music streaming** with alexa, have her **wake you up** in the morning and stop the playback of chillout music at night when I sleep, have her manage my **todo and shopping lists** ... and lots more.
### Developing for Alexa
Only after I had bootet up Alexa the first time a colleague of mine told me he developed stuff for extending Alexa himself. Amazon did a great job allowing nerds like me to extend Alexa with **custom skills** in virtually **every language** because interfacing with it you only have to access and provide http and json ([docs](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/overviews/understanding-custom-skills)). This allowed me to use my favorite hobby programming language: [dlang](http://www.dlang.org)
The first skill I developed so far is already on github: [alexa-openwebif](https://github.com/Extrawurst/alexa-openwebif)
I will cover details on the development of custom skills using D in future post.
### Food for thought for the guys at the Amazon Alexa team
Despite my enthusiasm there is a lot of topics that I have critique to raise. It is nothing major but I am hoping they will be tackled before the roll out in Germany starts big (right now you only can subscribe to get invited).
#### no multi language support and foreign skills
Right now you have to switch your language in the alexa app, you cannot just talk english or tell alexa to switch to english.
Even if you change the language of your device you cannot access the existing thousands of skills in the U.S., you have to switch your whole amazon account country to the U.S.. It is not clear to me why you want to make it that tough to use the original U.S. skills in germany, after all english is a very *commonly spoken language here*.
This makes it for developers even harder to find out what skills it is actually worth developing from scratch. U.S. skills will likely be translated at some point.
#### built in slot types not in german
As you can see in the [slot-type-reference](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference#list-types) most of the predefined slots that Amazon provides are not supported in German yet. This makes it very hard to convert skills and for German devs it is harder to create the same user experience that U.S. users benefit from. This has to change befor the open rollout of Alexa happens in Germany. This maybe one of the reasons why there is almost no skill in German yet.
#### updating skill through api
As a developer I am a fan of automating as much as possible. There is already a lot of functionality I can automate when it comes to alexa skill development because AWS is so [CLI](http://docs.aws.amazon.com/cli/latest/reference/) friendly. The Amazon developer console on the other hand is just a web portal. It would be great if the whole update lifecycle of a skill could be automated:
* set activation name
* add/set languages
* update language model:
* update intent schema
* update custom slot types
* sample utterances
#### lang tags in ssml
Defining the way Alexa is supposed to speak out text the System supports SSML as a markup language. What I would like to have is a language markup (like `<language lang="english">`) to give Alea a hint how to pronounce certain foreign words.
#### custom settings per skill
Alexa skills are plain web APIs in the cloud. As a skill developer you dont have a mean to save any state for the user accessing it on the device. The user is used to be able to configure Alexa in their Alexa App - this only applys to settings Amazon specifies (like language, volume and such). I would like to see a **Skill-Settings-Panel** that lets the user specify settings per skill that Amazon then provides to us developers when calling our API. This is for most of the skills more than enough compared to be forced to provide a custom user portal with OAuth account linking and the whole ceremony.
#### smaller issues
* crossing things off todo list is not supported
* sleep timer badly translated (setting sleep timer using example in 'things to try' does not work 99% of the times)
* alexa skill search broken on amazon.com (seems to be limited to U.S. users, makes it particularly hard for devs to assess what skills are already there)
* loud music prevents Alexa to sometimes hear the magic word to activate her
* you can't control your FireTV using your echo dot - that is simply pathetic
<file_sep>---
title: "Worth Reading (August 2017)"
date: 2017-08-07 17:00:00
categories: [reading]
---
The following stuff is what caught my eye in the last couple of weeks. Consider these kind of posts as an entry in my personal knowledge base ;)
In this installment I focus less on reading but on watching. These are particularly great talks/interviews that I watched over the course of the last few weeks. Very inspiring stuff:
| Title | Link | Duration |
|---|---|---|
| New Tech Start-Up Bubble | [youtube](https://www.youtube.com/watch?v=G7vrCpWbmDw) | 21 min |
| Why you should define your fears instead of your goals (<NAME>) | [youtube](https://www.youtube.com/watch?v=5J6jAC6XxAI) | 14 min |
| Why Do Planes Crash? <NAME> on Outliers, Work, Culture, Communication | [youtube](https://www.youtube.com/watch?v=a4TXS7ck8bQ) | 67 min |
| <NAME>' 2005 Stanford Commencement Address | [youtube](https://www.youtube.com/watch?v=UF8uR6Z6KLc) | 15 min |
| The future we're building -- and boring (<NAME>) | [youtube](https://www.youtube.com/watch?v=zIwLWfaAg-8) | 40 min |
### Video Lunch
Most of these Videos my team and I watched during lunch time. We do this every two weeks: Order in and watch a video in our office together. But I will devote a whole article on that later. Stay tuned..
|
ec7bf2608d63470961e6febdaa1f8f87579a6d77
|
[
"Markdown",
"HTML",
"Shell"
] | 39
|
Markdown
|
Extrawurst/extrawurst.github.io
|
f17d233ae3d1e3ca10f08b5292042d5a4ce9c34e
|
ae16604ac8bbd3216475a9c8eebe0c3d62108aac
|
refs/heads/master
|
<repo_name>m0rrigan/project-euler-solutions<file_sep>/ruby/problem1.rb
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_multiples(max_num)
sum_multiples = 0
n = max_num - 1
(0..n).each do |n|
if n%3 == 0
sum_multiples += n
elsif n%5 == 0
sum_multiples += n
end
end
puts "The sum of all multiples is #{sum_multiples}"
end
sum_multiples(10)
sum_multiples(1000)
<file_sep>/ruby/problem3.rb
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?
require 'prime'
limit = 13195
result = limit.prime_division
print "The largest prime factor is #{result.last[0]}"
limit = 600851475143
result = limit.prime_division
print "The largest prime factor is #{result.last[0]}"
<file_sep>/README.md
This repository is to house my solutions for [Project Euler](https://projecteuler.net/about).
I thought it would be a fun way to test my skills in any language I begin to learn!
|
562308adeda2f93742391b4783540309920a876b
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
m0rrigan/project-euler-solutions
|
36baffae5d39c32f26a0c6f9eaf156d2be7daed0
|
39a7f0096040a1e10862eae557c00597c128a467
|
refs/heads/main
|
<file_sep>#include "tipslabel.h"
#include <QFontDatabase>
TipsLabel::TipsLabel(const QString &text, QWidget *parent)
: QLabel(parent),
m_nOpacity(500)
{
// Formatting
QFont font(QFontDatabase::applicationFontFamilies(0).at(0), 16, QFont::Normal);
setFont(font);
setFixedHeight(80);
setMargin(20);
// Initialize timer
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &TipsLabel::updateBackground);
// Popup label
popup(text);
}
void TipsLabel::popup(const QString &text)
{
setText(text);
m_nOpacity = 500;
updateBackground();
show();
m_timer->start(30);
}
void TipsLabel::updateBackground()
{
if (m_nOpacity <= 0)
{
hide();
m_timer->stop();
return;
}
m_nOpacity -= 10;
if (m_nOpacity > 250)
{
setStyleSheet("color:rgba(255,255,255,255); background-color:rgba(45,45,45,255);");
}
else
{
setStyleSheet(QString("color:rgba(255,255,255,%1); background-color:rgba(45,45,45,%1);").arg(QString::number(m_nOpacity)));
}
}
<file_sep>#include "unitmover.h"
#include <QTimer>
#include <QDebug>
UnitMover::UnitMover(Settings *settings, Map *map, QObject *parent)
: QObject(parent),
m_settings(settings),
m_map(map),
m_nCurrentMove(0),
m_bVisible(true),
m_movingBlock{nullptr, nullptr},
m_bMoving(false),
m_movingUnit(nullptr),
m_movingRoute(),
m_currentStep()
{
m_nTotalMoves = m_settings->m_nMoveSteps;
m_refreshTimer = new QTimer(this);
connect(m_refreshTimer, &QTimer::timeout, this, &UnitMover::updateSingleMovement);
connect(this, &UnitMover::stepFinished, this, &UnitMover::updateRouteMovement);
}
void UnitMover::paint(QPainter *painter) const
{
painter->setPen(Qt::white);
if (m_bMoving && m_bVisible)
{
QPoint pos[2] = {m_movingBlock[0]->getCenter(), m_movingBlock[1]->getCenter()};
QPoint center = (pos[0] * (m_nTotalMoves - m_nCurrentMove) +
pos[1] * m_nCurrentMove) / m_nTotalMoves;
int size = m_map->getBlockSize();
m_movingUnit->paint(painter,
QRect(center - QPoint(size, 1.5 * size), center + QPoint(size, 0.5 * size)),
m_map->getDynamicsId());
}
}
void UnitMover::moveUnit(Block *fromBlock, Block *toBlock)
{
if (m_movingUnit == nullptr)
{
return;
}
m_movingBlock[0] = fromBlock;
m_movingBlock[1] = toBlock;
m_bVisible = fromBlock->isVisible() || toBlock->isVisible();
m_movingUnit->setDirection(toBlock->getCenter().x() < fromBlock->getCenter().x());
m_nCurrentMove = 0;
}
void UnitMover::moveUnit(QVector<Block *> &blocks)
{
if (m_bMoving)
{
return; // invalid
}
if (blocks.size() < 2)
{
qDebug() << "Movement finished";
emit movementFinished(blocks.first()->getUnit());
return; // no movement required
}
if (blocks.first()->getUnit() == nullptr)
{
return; // nothing to move
}
if (blocks.last()->getUnit() != nullptr)
{
return; // cannot move
}
m_movingRoute = blocks;
m_movingUnit = m_movingRoute.first()->getUnit();
m_movingRoute.first()->setUnit(nullptr);
m_currentStep = m_movingRoute.begin();
moveUnit(*m_currentStep, *(m_currentStep + 1));
m_bMoving = true;
m_refreshTimer->start(m_settings->m_nRefreshTime);
}
bool UnitMover::isBusy() const
{
return m_bMoving;
}
void UnitMover::updateSingleMovement()
{
if (m_movingUnit == nullptr)
{
return;
}
if (m_nCurrentMove < m_nTotalMoves)
{
m_nCurrentMove++;
}
else if (m_nCurrentMove == m_nTotalMoves)
{
// moving finished
emit stepFinished();
}
}
void UnitMover::updateRouteMovement()
{
m_currentStep++;
if (m_currentStep + 1 == m_movingRoute.end())
{
// moving finished
qDebug() << "Movement finished";
m_movingRoute.last()->setUnit(m_movingUnit);
m_movingRoute.clear();
m_bMoving = false;
m_refreshTimer->stop();
emit movementFinished(m_movingUnit);
}
else
{
// next step
moveUnit(*m_currentStep, *(m_currentStep + 1));
}
}
<file_sep>#include "battlewidget.h"
#include "ui_battlewidget.h"
#include <QPropertyAnimation>
BattleWidget::BattleWidget(Block *activeBlock, Block *passiveBlock,
GameInfo *gameInfo, QWidget *parent)
: QWidget(parent),
ui(new Ui::BattleWidget),
m_gameInfo(gameInfo),
m_activeImages(),
m_passiveImages(),
m_nDynamicsId(0),
m_activeBlock(activeBlock),
m_passiveBlock(passiveBlock),
m_nActiveDamage(0),
m_nPassiveDamage(0),
m_bActiveCritical(false),
m_bActiveKilled(false),
m_bPassiveKilled(false)
{
ui->setupUi(this);
setAttribute(Qt::WA_StyledBackground, true);
ui->imageWidget->setAttribute(Qt::WA_StyledBackground, true);
setFixedSize(900, 400);
m_activeLabel = new QLabel(ui->imageWidget);
m_passiveLabel = new QLabel(ui->imageWidget);
m_damageLabel = new QLabel(ui->imageWidget);
m_damageLabel->setGeometry(-100, -100, 300, 50);
// Initialize images
QVector<QImage> v;
m_activeBlock->getUnit()->getImages(&v);
for (const auto &img : qAsConst(v))
{
m_activeImages.push_back(QPixmap::fromImage(img.scaledToHeight(150)));
}
m_activeLabel->setPixmap(m_activeImages[m_nDynamicsId]);
m_passiveBlock->getUnit()->getImages(&v);
for (const auto &img : qAsConst(v))
{
m_passiveImages.push_back(QPixmap::fromImage(img.scaledToHeight(150).mirrored(true, false)));
}
m_passiveLabel->setPixmap(m_passiveImages[m_nDynamicsId]);
// Initialize labels
ui->activeAttackLabel->setText(
QString::number(static_cast<int>(m_gameInfo->getUnitInfo()[m_activeBlock->getUnit()->getId()][5])));
ui->passiveAttackLabel->setText(
QString::number(static_cast<int>(m_gameInfo->getUnitInfo()[m_passiveBlock->getUnit()->getId()][5])));
ui->activeShieldLabel->setText(
QString::number(m_gameInfo->getTerrainInfo()[m_passiveBlock->getTerrain()][5]));
ui->passiveShieldLabel->setText(
QString::number(m_gameInfo->getTerrainInfo()[m_passiveBlock->getTerrain()][5]));
ui->activeHPBar->setValue(100 * m_activeBlock->getUnit()->getHPPercentage());
ui->activeHPLabel->setText(QString::number(m_activeBlock->getUnit()->getHP()));
ui->passiveHPBar->setValue(100 * m_passiveBlock->getUnit()->getHPPercentage());
ui->passiveHPLabel->setText(QString::number(m_passiveBlock->getUnit()->getHP()));
// Load background picture
QImage img;
Unit *unit = m_passiveBlock->getUnit();
if (unit != nullptr)
{
int unitId = unit->getId();
if (unitId >= 10 && unitId <= 13)
{
// Air unit
img = QImage(":/image/background/0");
}
else
{
img = QImage(":/image/background/" + QString::number(m_passiveBlock->getTerrain()));
}
}
else
{
img = QImage(":/image/background/" + QString::number(m_passiveBlock->getTerrain()));
}
show();
// Set background picture
QPalette palette = ui->imageWidget->palette();
palette.setBrush(ui->imageWidget->backgroundRole(),
QBrush(img.scaled(ui->imageWidget->size(),
Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)));
ui->imageWidget->setPalette(palette);
// Initialize timer
m_dynamicsTimer = new QTimer(this);
m_dynamicsTimer->start(300);
// Connect all animations
connect(m_dynamicsTimer, &QTimer::timeout, this, &BattleWidget::updateDynamics);
}
BattleWidget::~BattleWidget()
{
delete ui;
}
void BattleWidget::setActiveAttack(int damage, bool killed, bool critical)
{
m_nActiveDamage = damage;
m_bActiveCritical = critical;
m_bActiveKilled = killed;
}
void BattleWidget::setPassiveAttack(int damage, bool killed)
{
m_nPassiveDamage = damage;
m_bPassiveKilled = killed;
}
void BattleWidget::adjustScreen()
{
// Reset size
int parentWidth = static_cast<QWidget *>(parent())->width();
int parentHeight = static_cast<QWidget *>(parent())->height();
setGeometry(parentWidth / 2 - 450, parentHeight / 2 - 200, 900, 400);
}
void BattleWidget::begin()
{
show();
adjustScreen();
goOnStage();
}
void BattleWidget::updateDynamics()
{
m_nDynamicsId = 1 - m_nDynamicsId;
m_activeLabel->setPixmap(m_activeImages[m_nDynamicsId]);
m_passiveLabel->setPixmap(m_passiveImages[m_nDynamicsId]);
}
void BattleWidget::goOnStage()
{
QPropertyAnimation *activeAnimation = new QPropertyAnimation(m_activeLabel, "pos", this);
activeAnimation->setDuration(500);
activeAnimation->setStartValue(QPoint(-300, 70));
activeAnimation->setEndValue(QPoint(100, 70));
activeAnimation->setEasingCurve(QEasingCurve::Linear);
QPropertyAnimation *passiveAnimation = new QPropertyAnimation(m_passiveLabel, "pos", this);
passiveAnimation->setDuration(500);
passiveAnimation->setStartValue(QPoint(1050, 70));
passiveAnimation->setEndValue(QPoint(650, 70));
passiveAnimation->setEasingCurve(QEasingCurve::Linear);
m_activeLabel->show();
m_passiveLabel->show();
activeAnimation->start();
passiveAnimation->start();
connect(passiveAnimation, &QPropertyAnimation::finished, this, &BattleWidget::activeAttack);
}
void BattleWidget::activeAttack()
{
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(1000);
QPropertyAnimation *activeAttackAnimation = new QPropertyAnimation(m_activeLabel, "pos", this);
activeAttackAnimation->setDuration(200);
activeAttackAnimation->setStartValue(QPoint(100, 70));
activeAttackAnimation->setEndValue(QPoint(1000, 70));
activeAttackAnimation->setEasingCurve(QEasingCurve::Linear);
QPropertyAnimation *activeReturnAnimation = new QPropertyAnimation(m_activeLabel, "pos", this);
activeReturnAnimation->setDuration(500);
activeReturnAnimation->setStartValue(QPoint(-300, 70));
activeReturnAnimation->setEndValue(QPoint(100, 70));
activeReturnAnimation->setEasingCurve(QEasingCurve::Linear);
m_damageLabel->setText((m_bActiveCritical ? "CRIT. " : " ") + QString::number(-m_nActiveDamage));
QPropertyAnimation *activeDamageAnimation = new QPropertyAnimation(m_damageLabel, "pos", this);
activeDamageAnimation->setDuration(1000);
activeDamageAnimation->setStartValue(QPoint(700, 100));
activeDamageAnimation->setEndValue(QPoint(700, -50));
activeDamageAnimation->setEasingCurve(QEasingCurve::Linear);
// start() has a default parameter, so I have to use SIGNAL(), SLOT()
connect(activeAttackAnimation, SIGNAL(finished()), activeReturnAnimation, SLOT(start()));
connect(activeAttackAnimation, SIGNAL(finished()), activeDamageAnimation, SLOT(start()));
if (m_bActiveKilled)
{
QPropertyAnimation *passiveKilledAnimation = new QPropertyAnimation(m_passiveLabel, "pos", this);
passiveKilledAnimation->setDuration(800);
passiveKilledAnimation->setStartValue(QPoint(650, 70));
passiveKilledAnimation->setEndValue(QPoint(650, 400));
passiveKilledAnimation->setEasingCurve(QEasingCurve::Linear);
connect(activeAttackAnimation, SIGNAL(finished()), passiveKilledAnimation, SLOT(start()));
connect(activeAttackAnimation, &QPropertyAnimation::finished, this, [ = ]()
{
ui->passiveHPBar->setValue(0);
ui->passiveHPLabel->setText(QString::number(0));
});
connect(activeDamageAnimation, &QPropertyAnimation::finished, this, &BattleWidget::ending);
}
else
{
connect(activeAttackAnimation, &QPropertyAnimation::finished, this, [ = ]()
{
ui->passiveHPBar->setValue(m_passiveBlock->getUnit()->getHPPercentage() * 100);
ui->passiveHPLabel->setText(QString::number(m_passiveBlock->getUnit()->getHP()));
});
if (m_passiveBlock->getUnit() != nullptr && m_nPassiveDamage == 0)
{
connect(activeDamageAnimation, &QPropertyAnimation::finished, this, &BattleWidget::ending);
}
else
{
connect(activeDamageAnimation, &QPropertyAnimation::finished, this, &BattleWidget::passiveAttack);
}
}
connect(timer, SIGNAL(timeout()), activeAttackAnimation, SLOT(start()));
timer->start(1000);
}
void BattleWidget::passiveAttack()
{
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
timer->start(1000);
QPropertyAnimation *passiveAttackAnimation = new QPropertyAnimation(m_passiveLabel, "pos", this);
passiveAttackAnimation->setDuration(200);
passiveAttackAnimation->setStartValue(QPoint(650, 70));
passiveAttackAnimation->setEndValue(QPoint(-250, 70));
passiveAttackAnimation->setEasingCurve(QEasingCurve::Linear);
QPropertyAnimation *passiveReturnAnimation = new QPropertyAnimation(m_passiveLabel, "pos", this);
passiveReturnAnimation->setDuration(500);
passiveReturnAnimation->setStartValue(QPoint(1050, 70));
passiveReturnAnimation->setEndValue(QPoint(650, 70));
passiveReturnAnimation->setEasingCurve(QEasingCurve::Linear);
m_damageLabel->setText(QString::number(-m_nPassiveDamage));
QPropertyAnimation *passiveDamageAnimation = new QPropertyAnimation(m_damageLabel, "pos", this);
passiveDamageAnimation->setDuration(1000);
passiveDamageAnimation->setStartValue(QPoint(150, 100));
passiveDamageAnimation->setEndValue(QPoint(150, -50));
passiveDamageAnimation->setEasingCurve(QEasingCurve::Linear);
// start() has a default parameter, so I have to use SIGNAL(), SLOT()
connect(passiveAttackAnimation, SIGNAL(finished()), passiveReturnAnimation, SLOT(start()));
connect(passiveAttackAnimation, SIGNAL(finished()), passiveDamageAnimation, SLOT(start()));
if (m_bPassiveKilled)
{
QPropertyAnimation *activeKilledAnimation = new QPropertyAnimation(m_activeLabel, "pos", this);
activeKilledAnimation->setDuration(800);
activeKilledAnimation->setStartValue(QPoint(100, 70));
activeKilledAnimation->setEndValue(QPoint(100, 400));
activeKilledAnimation->setEasingCurve(QEasingCurve::Linear);
connect(passiveAttackAnimation, SIGNAL(finished()), activeKilledAnimation, SLOT(start()));
connect(passiveAttackAnimation, &QPropertyAnimation::finished, this, [ = ]()
{
ui->activeHPBar->setValue(0);
ui->activeHPLabel->setText(QString::number(0));
});
}
else
{
connect(passiveAttackAnimation, &QPropertyAnimation::finished, this, [ = ]()
{
ui->activeHPBar->setValue(m_activeBlock->getUnit()->getHPPercentage() * 100);
ui->activeHPLabel->setText(QString::number(m_activeBlock->getUnit()->getHP()));
});
}
connect(passiveDamageAnimation, &QPropertyAnimation::finished, this, &BattleWidget::ending);
connect(timer, SIGNAL(timeout()), passiveAttackAnimation, SLOT(start()));
timer->start(1000);
}
void BattleWidget::ending()
{
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &BattleWidget::end);
timer->setSingleShot(true);
timer->start(1000);
}
<file_sep>#include "gamewidget.h"
#include "ui_gamewidget.h"
#include <QPainter>
#include <QFontDatabase>
#include <QMouseEvent>
GameWidget::GameWidget(Settings *settings, QWidget *parent)
: QWidget(parent),
ui(new Ui::GameWidget),
m_bClosing(false),
m_pDragBeginPoint(0, 0),
m_bMouseEventConnected(false)
{
// Initialize cursor
QPixmap pixmap(":/pointer");
QCursor cursor(pixmap);
setCursor(cursor);
// Initialize ui
ui->setupUi(this);
ui->unitMoveWidget->hide();
ui->gameOverLabel->hide();
// Initialize background
setAttribute(Qt::WA_StyledBackground, true);
QPalette palette;
palette.setBrush(backgroundRole(), QBrush(QPixmap(":/image/bricks_background")));
setPalette(palette);
// Initialize game data
m_settings = settings;
m_gameInfo = new GameInfo(this);
m_stats = new GameStats(this);
int mapIndex = m_settings->m_nCurrentMap;
m_map = new Map(m_settings->m_mapSizes[mapIndex], this,
m_settings->m_nBlockSize, QPoint(100, 100));
m_map->loadTerrain(":/maps/terrain/" + m_settings->m_mapNames[mapIndex], m_settings->m_bFogMode);
m_map->loadUnits(":/maps/units/" + m_settings->m_mapNames[mapIndex], m_gameInfo, m_stats);
// Initialize graphic widgets
m_tipsLabel = new TipsLabel(tr("Here are the tips. "), this);
ui->verticalLayout->addWidget(m_tipsLabel);
m_unitSelectionWidget = new UnitSelectionWidget(m_gameInfo, this);
m_descriptionWidget = new DescriptionWidget(m_gameInfo, this);
QString customStyleSheet = "\
QMenu {\
background-color: #d1bead;\
border: 3px solid #f4f6e9;\
}\
QMenu::item {\
font-size: 10pt; \
color: #3d4265;\
border: 3px solid #f4f6e9;\
background-color: #dfc686;\
padding: 2px 10px; \
margin: 2px 2px;\
}\
QMenu::item:selected {\
color: #f4f4e8;\
background-color: #a47750;\
}\
QMenu::item:pressed {\
color: #f4f4e8;\
background-color: #a47750;\
}";
m_actionContextMenu = new QMenu(this);
m_actionContextMenu->setStyleSheet(customStyleSheet);
m_mainContextMenu = new QMenu(this);
m_mainContextMenu->setStyleSheet(customStyleSheet);
// Initialize audio player
m_mediaPlayer = new QMediaPlayer(this);
m_mediaPlayer->setMedia(QUrl(m_settings->m_backgroundMusic));
m_mediaPlayer->setVolume(m_settings->m_nVolume);
m_mediaPlayer->play();
m_SEPlayer = new QMediaPlayer(this);
m_SEPlayer->setMedia(QUrl("./music/click.mp3"));
m_SEPlayer->setVolume(m_settings->m_nSEVolume);
// Initialize game engine
m_processor = new GameProcessor(m_settings, m_gameInfo, m_map, m_stats, m_SEPlayer,
m_tipsLabel, ui->unitMoveWidget,
m_unitSelectionWidget, m_descriptionWidget,
m_actionContextMenu, m_mainContextMenu, this);
m_ai = new AIProcessor *[1]; // Currently one ai
for (int i = 0; i < 1; i++) // Number of AIs
{
m_ai[i] = new AIProcessor(m_settings, m_gameInfo, m_map, m_stats, m_SEPlayer, this, i + 1);
}
// Initialize graphics timers
m_graphicsTimer = new QTimer(this);
m_graphicsTimer->start(m_settings->m_nRefreshTime);
connect(m_graphicsTimer, &QTimer::timeout, this, &GameWidget::updateAll);
m_dynamicsTimer = new QTimer(this);
m_dynamicsTimer->start(300);
connect(m_dynamicsTimer, &QTimer::timeout, m_map, &Map::updateDynamics);
// Connect signals related to AI
connect(m_processor, &GameProcessor::roundForSide, this, &GameWidget::initializeSide);
for (int i = 0; i < 1; i++) // Number of AIs
{
connect(m_ai[i], &AIProcessor::finished, m_processor, &GameProcessor::changeSide);
}
initializeSide(0);
// Connect other signals to slots
connect(m_mediaPlayer, &QMediaPlayer::stateChanged, this, &GameWidget::resetMedia);
// Track mouse movements
setMouseTracking(true);
}
GameWidget::~GameWidget()
{
delete ui;
}
void GameWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter *painter = new QPainter(this);
// Set general font
QFont font(QFontDatabase::applicationFontFamilies(0).at(0), 12, QFont::Bold);
painter->setFont(font);
m_map->paint(painter, 1); // terrain
m_processor->paint(painter);
for (int i = 0; i < 1; i++)
{
m_ai[i]->paint(painter);
}
m_map->paint(painter, 2); // units
delete painter;
}
void GameWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
emit mouseLeftButtonClicked(event->pos());
}
else if (event->button() == Qt::RightButton)
{
emit mouseRightButtonClicked(event->pos());
}
else if (event->button() == Qt::MiddleButton)
{
m_pDragBeginPoint = event->pos();
emit mouseMiddleButtonClicked(event->pos());
}
}
void GameWidget::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::MiddleButton)
{
const QPoint newPos = event->pos();
emit mouseMiddleButtonMoved(newPos - m_pDragBeginPoint);
m_pDragBeginPoint = newPos;
}
emit mouseMoved(event->pos());
}
void GameWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
emit mouseLeftButtonReleased(event->pos());
}
}
void GameWidget::wheelEvent(QWheelEvent *event)
{
emit mouseScrolled(event->angleDelta().y() > 0 ? 1 : -1, event->position());
}
void GameWidget::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
m_unitSelectionWidget->adjustSize();
m_descriptionWidget->adjustBackground();
}
void GameWidget::closeEvent(QCloseEvent *event)
{
m_bClosing = true;
m_mediaPlayer->stop();
emit windowClosed();
QWidget::closeEvent(event);
}
void GameWidget::updateAll()
{
update();
}
void GameWidget::resetMedia(QMediaPlayer::State newState)
{
if (!m_bClosing && newState == QMediaPlayer::StoppedState)
{
m_mediaPlayer->play();
}
}
void GameWidget::initializeSide(int side)
{
if (m_settings->m_bAI)
{
// Single player: activate AI and disconnect signals properly
if (side <= 0)
{
if (!m_bMouseEventConnected)
{
m_bMouseEventConnected = true;
connect(this, &GameWidget::mouseLeftButtonClicked, m_processor, &GameProcessor::selectPosition);
connect(this, &GameWidget::mouseLeftButtonReleased, m_processor, &GameProcessor::unselectPosition);
connect(this, &GameWidget::mouseRightButtonClicked, m_processor, &GameProcessor::escapeMenu);
connect(this, &GameWidget::mouseMiddleButtonMoved, m_processor, &GameProcessor::moveMap);
connect(this, &GameWidget::mouseMoved, m_processor, &GameProcessor::mouseToPosition);
connect(this, &GameWidget::mouseScrolled, m_processor, &GameProcessor::zoomMap);
}
m_processor->activate();
}
else
{
if (m_bMouseEventConnected)
{
m_bMouseEventConnected = false;
disconnect(this, &GameWidget::mouseLeftButtonClicked, m_processor, &GameProcessor::selectPosition);
disconnect(this, &GameWidget::mouseLeftButtonReleased, m_processor, &GameProcessor::unselectPosition);
disconnect(this, &GameWidget::mouseRightButtonClicked, m_processor, &GameProcessor::escapeMenu);
disconnect(this, &GameWidget::mouseMiddleButtonMoved, m_processor, &GameProcessor::moveMap);
disconnect(this, &GameWidget::mouseMoved, m_processor, &GameProcessor::mouseToPosition);
disconnect(this, &GameWidget::mouseScrolled, m_processor, &GameProcessor::zoomMap);
}
m_ai[side - 1]->activate();
}
}
else
{
// Multiplayer: no AIs, connect signals
if (!m_bMouseEventConnected)
{
m_bMouseEventConnected = true;
connect(this, &GameWidget::mouseLeftButtonClicked, m_processor, &GameProcessor::selectPosition);
connect(this, &GameWidget::mouseLeftButtonReleased, m_processor, &GameProcessor::unselectPosition);
connect(this, &GameWidget::mouseRightButtonClicked, m_processor, &GameProcessor::escapeMenu);
connect(this, &GameWidget::mouseMiddleButtonMoved, m_processor, &GameProcessor::moveMap);
connect(this, &GameWidget::mouseMoved, m_processor, &GameProcessor::mouseToPosition);
connect(this, &GameWidget::mouseScrolled, m_processor, &GameProcessor::zoomMap);
}
m_processor->activate();
}
}
<file_sep>#ifndef MAP_H
#define MAP_H
#include "block.h"
#include "gameinfo.h"
#include "gamestats.h"
#include <QObject>
#include <QSize>
class Map : public QObject
{
Q_OBJECT
public:
// Constructor-related functions
explicit Map(QSize size,
QObject *parent = nullptr,
int blockSize = 100,
QPoint offset = QPoint(200, 200));
~Map();
void loadTerrain(const QString &filename, bool fogMode = false);
void loadUnits(const QString &filename, GameInfo *gameInfo, GameStats *stats);
// Get functions
Block *getBlock(int row, int col) const;
Block *getBlock(QPoint position) const;
QSize getSize() const;
int getDynamicsId() const;
QPoint getCenterPosition(const Block *block) const;
int getBlockSize() const;
int getScale() const;
void getAdjacentBlocks(QVector<Block *> &blockVector, Block *block) const;
void getAdjacentBlocks(QVector<Block *> &blockVector, Block *block, int rangeHigh, int rangeLow = 0) const;
void getAllBlocks(QVector<Block *> &blockVector, int side) const;
// Adjust functions
void adjustOffset(QPoint deltaPos);
void adjustScale(int deltaScale, QPointF center);
// Update after adjustments to blocks
void updateAllBlocks() const;
// Paint functions
// @param part: 0-terrain & units, 1-terrain, 2-units
void paint(QPainter *painter, int part = 0) const;
public slots:
void updateDynamics();
private:
Block ***m_matrix;
QSize m_size;
QPoint m_pOffset; // the relative position of the upper-left corner
int m_nDynamicsId; // showing dynamics of the units
int m_nBlockSize;
int m_nScale; // 30 to 150
signals:
};
#endif // MAP_H
<file_sep>#ifndef TIPSLABEL_H
#define TIPSLABEL_H
#include <QLabel>
#include <QTimer>
class TipsLabel : public QLabel
{
public:
TipsLabel(const QString &text, QWidget *parent = nullptr);
void popup(const QString &text);
public slots:
void updateBackground();
private:
QTimer *m_timer;
int m_nOpacity;
};
#endif // TIPSLABEL_H
<file_sep>#include "aiprocessor.h"
#include "building.h"
#include <QDebug>
AIProcessor::AIProcessor(Settings *settings,
GameInfo *gameInfo,
Map *map,
GameStats *stats,
QMediaPlayer *SEplayer,
QObject *parent,
int side)
: QObject(parent),
m_settings(settings),
m_gameInfo(gameInfo),
m_map(map),
m_stats(stats),
m_SEplayer(SEplayer),
m_battleWidget(nullptr),
m_remainingBlocks(),
m_movingRoute(),
m_confrontingBlock(nullptr),
m_tempUnit(nullptr),
m_nSide(side),
m_nStage(0)
{
// Initialize unit mover
m_unitMover = new UnitMover(m_settings, m_map, this);
connect(m_unitMover, &UnitMover::movementFinished, this, &AIProcessor::confrontUnit);
connect(this, &AIProcessor::operationFinished, this, &AIProcessor::nextMove);
}
void AIProcessor::paint(QPainter *painter)
{
m_unitMover->paint(painter);
}
void AIProcessor::getAccessibleBlocks(QVector<BlockValue> &accessibleBlocks, Block *block, int unitType, int movement)
{
int **terrainInfo = m_gameInfo->getTerrainInfo(); // move cost: terrainInfo[terrainId][unitType]
accessibleBlocks.clear();
QVector<BlockValue> remainingBlocks;
remainingBlocks.push_back({block, nullptr, nullptr, 0, 0}); // the vector only has the origin at first
while (!remainingBlocks.isEmpty())
{
// sort by distance, get the one with the shortest distance
std::sort(remainingBlocks.begin(), remainingBlocks.end(), [](const BlockValue & v1, const BlockValue & v2)
{
return v1.distance > v2.distance;
});
const BlockValue temp = remainingBlocks.last();
remainingBlocks.pop_back();
if (temp.distance > movement) // other blocks are all out of reach
{
break;
}
QVector<Block *> adjacentBlocks;
m_map->getAdjacentBlocks(adjacentBlocks, temp.block);
for (const auto &adjBlock : qAsConst(adjacentBlocks))
{
if (adjBlock->getUnit() != nullptr)
{
continue;
}
int distance = temp.distance + terrainInfo[adjBlock->getTerrain()][unitType];
bool counted = false;
// find out whether the block is contained
for (auto iter = remainingBlocks.begin(); iter != remainingBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
if (iter->distance > distance)
{
// update distance and route
iter->distance = distance;
iter->lastBlock = temp.block;
}
counted = true;
break;
}
}
if (!counted)
{
// find out whether the block has been submitted
for (auto iter = accessibleBlocks.begin(); iter != accessibleBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
counted = true;
break;
}
}
if (!counted)
{
// not considered
remainingBlocks.push_back({adjBlock, temp.block, nullptr, distance, 0});
}
}
}
accessibleBlocks.push_back(temp);
}
}
void AIProcessor::updateAttackPoints(QVector<BlockValue> &accessibleBlocks, Unit *unit)
{
int **terrainInfo = m_gameInfo->getTerrainInfo();
float **unitInfo = m_gameInfo->getUnitInfo();
float **damageMatrix = m_gameInfo->getDamageMatrix();
int unitId = unit->getId();
int rangeLow = unitInfo[unitId][2];
int rangeHigh = unitInfo[unitId][3];
int attack = unitInfo[unitId][5];
for (auto &blockValue : accessibleBlocks)
{
Block *block = blockValue.block;
QVector<Block *> blocksInRange;
int maxAttackPoints = 0;
Block *maxPassiveBlock = nullptr;
for (int radius = rangeLow; radius <= rangeHigh; radius++)
{
// different distances are also given different points (*1 ~ *1.5)
m_map->getAdjacentBlocks(blocksInRange, block, radius, radius);
for (const auto &passiveBlock : qAsConst(blocksInRange))
{
Unit *passiveUnit = passiveBlock->getUnit();
if (passiveUnit != nullptr && passiveUnit->getSide() != m_nSide)
{
if ((passiveUnit->getId() == 19 && passiveUnit->getSide() < 0)
&& (radius > 1 || unitInfo[unitId][7] == 0))
{
// Can't capture a building or it's far away
break;
}
// Able to attack the unit
int passiveId = passiveUnit->getId();
// Check damage matrix
double multiplier = damageMatrix[unitId][passiveId];
// Check terrain shields
if (passiveId < 10 || passiveId > 13)
{
// Enemy not an air unit
int shields = terrainInfo[passiveBlock->getTerrain()][5];
multiplier *= ((10.0 - shields) / 10.0);
}
int damagePoints = multiplier * attack;
int passiveHP = passiveUnit->getHP();
if (damagePoints > passiveHP)
{
// killed
damagePoints *= 2;
}
if (passiveId >= 18)
{
// commander or building
damagePoints *= 1.5;
}
// Multiplied by a ratio related to distance
damagePoints *= ((radius - 1) * 0.1 + 1);
// Check whether the damagePoints is the greatest
if (damagePoints > maxAttackPoints)
{
maxAttackPoints = damagePoints;
maxPassiveBlock = passiveBlock;
}
}
}
}
blockValue.value += maxAttackPoints;
blockValue.confrontingBlock = maxPassiveBlock;
}
}
void AIProcessor::updateDefencePoints(QVector<BlockValue> &accessibleBlocks, Unit *unit)
{
int **terrainInfo = m_gameInfo->getTerrainInfo();
float **unitInfo = m_gameInfo->getUnitInfo();
float **damageMatrix = m_gameInfo->getDamageMatrix();
int unitId = unit->getId();
for (auto &blockValue : accessibleBlocks)
{
Block *block = blockValue.block;
int defensivePoints = 0;
QVector<Block *> blocksInRange;
m_map->getAdjacentBlocks(blocksInRange, block, 4); // The distance is currently set to 4
for (const auto &objBlock : qAsConst(blocksInRange))
{
Unit *objUnit = objBlock->getUnit();
if (objUnit != nullptr && objUnit->getSide() != m_nSide)
{
// May get attacked
int passiveId = objUnit->getId();
int passiveAttack = unitInfo[passiveId][5];
// Check damage matrix
double multiplier = damageMatrix[passiveId][unitId];
int damagePoints = multiplier * passiveAttack;
int hp = unit->getHP();
if (damagePoints > hp)
{
// killed
damagePoints *= 2;
}
defensivePoints += damagePoints;
}
}
// Check terrain
defensivePoints *= ((10.0 - terrainInfo[block->getTerrain()][5]) / 10.0);
// Defence factor
defensivePoints *= 0.5;
// Add to blockValue
blockValue.value -= defensivePoints;
}
}
void AIProcessor::updateNearbyBlocks(QVector<BlockValue> &accessibleBlocks, Block *block, int unitType, int movement)
{
int **terrainInfo = m_gameInfo->getTerrainInfo(); // move cost: terrainInfo[terrainId][unitType]
QVector<BlockValue> allBlocks;
QVector<BlockValue> remainingBlocks;
remainingBlocks.push_back({block, nullptr, nullptr, 0, 0}); // the vector only has the origin at first
while (!remainingBlocks.isEmpty())
{
// sort by distance, get the one with the shortest distance
std::sort(remainingBlocks.begin(), remainingBlocks.end(), [](const BlockValue & v1, const BlockValue & v2)
{
return v1.distance > v2.distance;
});
const BlockValue temp = remainingBlocks.last();
remainingBlocks.pop_back();
QVector<Block *> adjacentBlocks;
m_map->getAdjacentBlocks(adjacentBlocks, temp.block);
bool findBuilding = false;
for (const auto &adjBlock : qAsConst(adjacentBlocks))
{
if (adjBlock->getUnit() != nullptr)
{
// Check if there's an enemy unit nearby
if (adjBlock->getUnit()->getSide() != m_nSide)
{
findBuilding = true;
break;
}
continue;
}
int distance = temp.distance + terrainInfo[adjBlock->getTerrain()][unitType];
bool counted = false;
// find out whether the block is contained
for (auto iter = remainingBlocks.begin(); iter != remainingBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
if (iter->distance > distance)
{
// update distance and route
iter->distance = distance;
iter->lastBlock = temp.block;
}
counted = true;
break;
}
}
if (!counted)
{
// find out whether the block has been submitted
for (auto iter = allBlocks.begin(); iter != allBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
counted = true;
break;
}
}
if (!counted)
{
// not considered
remainingBlocks.push_back({adjBlock, temp.block, nullptr, distance, 0});
}
}
}
allBlocks.push_back(temp);
if (findBuilding)
{
break;
}
}
qDebug() << allBlocks.size();
// Filter the path to the enemy unit
accessibleBlocks.clear();
Block *temp = allBlocks.last().block;
while (temp != nullptr)
{
// Find the blockValue related to temp
BlockValue *blockValue = nullptr;
for (auto &b : allBlocks)
{
if (b.block == temp)
{
blockValue = &b;
break;
}
}
if (blockValue == nullptr)
{
qDebug() << "error: nullptr in setting the route";
break;
}
if (blockValue->distance <= movement)
{
accessibleBlocks.push_back(*blockValue);
}
temp = blockValue->lastBlock;
}
accessibleBlocks.first().value = 100;
}
void AIProcessor::moveSingleUnit(Block *block)
{
// Selecting an ordinary unit
qDebug() << "AI moving block" << block->getRow() << block->getColumn();
// Find the best choice
float **unitInfo = m_gameInfo->getUnitInfo();
int unitId = block->getUnit()->getId();
QVector<BlockValue> accessibleBlocks;
getAccessibleBlocks(accessibleBlocks, block, unitInfo[unitId][0], unitInfo[unitId][1]);
// update attacking points
updateAttackPoints(accessibleBlocks, block->getUnit());
// check if there is no update on attack points (not able to attack)
bool attackable = false;
for (const auto &block : qAsConst(accessibleBlocks))
{
if (block.value > 0)
{
attackable = true;
break;
}
}
if (attackable)
{
qDebug() << "attack";
// Able to attack: update defensive points
updateDefencePoints(accessibleBlocks, block->getUnit());
}
else
{
qDebug() << "not able to attack";
// Not able to attack: find a path to the nearby enemy
updateNearbyBlocks(accessibleBlocks, block, unitInfo[unitId][0], unitInfo[unitId][1]);
}
// Set route
BlockValue *idealBlock = std::max_element(accessibleBlocks.begin(), accessibleBlocks.end(),
[](const BlockValue & v1, const BlockValue & v2)
{
return v1.value < v2.value;
});
m_movingRoute.clear();
Block *temp = idealBlock->block;
while (temp != nullptr)
{
m_movingRoute.push_front(temp);
// Find the blockValue related to temp
const BlockValue *blockValue = nullptr;
for (const auto &b : qAsConst(accessibleBlocks))
{
if (b.block == temp)
{
blockValue = &b;
break;
}
}
if (blockValue == nullptr)
{
qDebug() << "error: nullptr in setting the route";
break;
}
temp = blockValue->lastBlock;
}
// Set confronting block
m_confrontingBlock = idealBlock->confrontingBlock;
// End operation, begin simulation
m_unitMover->moveUnit(m_movingRoute); // end with a signal connected to confrontUnit()
}
void AIProcessor::operateBuilding(Block *block)
{
// Selecting a building
qDebug() << "AI operating block" << block->getRow() << block->getColumn();
// Set moving route (only the building)
m_movingRoute.clear();
m_movingRoute.push_back(block);
// Set unit confrontation & new unit (if needed) (confrontingBlock = nullptr - do not generate)
m_confrontingBlock = nullptr;
QVector<Block *> adjacentBlocks;
int coins = m_stats->getCoins(m_nSide);
int unitId = -8; // do not generate units if not reset
int innerType = block->getUnit()->getInnerType();
if (innerType == 1)
{
// Choose from soldier (100C) & archer (500C)
m_map->getAdjacentBlocks(adjacentBlocks, block, 4);
// Count enemy/uncaptured units
int count = 0;
for (const auto &b : qAsConst(adjacentBlocks))
{
if (b->getUnit() != nullptr && b->getUnit()->getSide() != m_nSide)
{
count++;
}
}
if (count > 0)
{
// Enemy nearby: choose soldier
if (coins >= m_gameInfo->getUnitInfo()[0][9])
{
unitId = 0;
}
}
else
{
// No enemy nearby: check own units
m_map->getAdjacentBlocks(adjacentBlocks, block, 6);
// Count own units
int count = 0;
for (const auto &b : qAsConst(adjacentBlocks))
{
if (b->getUnit() != nullptr && b->getUnit()->getSide() == m_nSide
&& b->getUnit()->getId() <= 18)
{
count++;
}
}
if (count > 5)
{
// Too many own units: choose trebuchet
if (coins >= m_gameInfo->getUnitInfo()[9][9])
{
unitId = 9;
}
}
else if (count > 3)
{
// Not so many own units: choose archer
if (coins >= m_gameInfo->getUnitInfo()[4][9])
{
unitId = 4;
}
}
else
{
// Not enough own units: choose soldier
if (coins >= m_gameInfo->getUnitInfo()[0][9])
{
unitId = 0;
}
}
}
}
else if (innerType == 2)
{
// Choose from sky rider (800C) & dragon (1250C)
// Count own flying units
m_map->getAdjacentBlocks(adjacentBlocks, block, 6);
int count = 0;
for (const auto &b : qAsConst(adjacentBlocks))
{
if (b->getUnit() != nullptr && b->getUnit()->getSide() == m_nSide
&& b->getUnit()->getId() >= 10 && b->getUnit()->getId() <= 13)
{
count++;
}
}
if (count > 2)
{
// Too many own units: choose dragon
if (coins >= m_gameInfo->getUnitInfo()[13][9])
{
unitId = 13;
}
}
else
{
// Not enough own units: choose sky rider
if (coins >= m_gameInfo->getUnitInfo()[12][9])
{
unitId = 12;
}
}
}
else if (innerType == 3)
{
// Choose from turtle (400C) & warship (900C)
// Count own water units
m_map->getAdjacentBlocks(adjacentBlocks, block, 6);
int count = 0;
for (const auto &b : qAsConst(adjacentBlocks))
{
if (b->getUnit() != nullptr && b->getUnit()->getSide() == m_nSide
&& b->getUnit()->getId() >= 14 && b->getUnit()->getId() <= 17)
{
count++;
}
}
if (count > 2)
{
// Too many own units: choose warship
if (coins >= m_gameInfo->getUnitInfo()[17][9])
{
unitId = 17;
}
}
else
{
// Not enough own units: choose turtle
if (coins >= m_gameInfo->getUnitInfo()[15][9])
{
unitId = 15;
}
}
}
if (unitId >= 0)
{
// A unit selected
// Check if there is an empty block for unit generation
QVector<Block *> nearbyBlocks;
QVector<Block *> placeableBlocks;
m_map->getAdjacentBlocks(nearbyBlocks, block);
int **terrainInfo = m_gameInfo->getTerrainInfo();
int unitType = m_gameInfo->getUnitInfo()[unitId][0];
for (const auto &b : qAsConst(nearbyBlocks))
{
if (b->getUnit() == nullptr &&
terrainInfo[b->getTerrain()][unitType] < 10)
{
placeableBlocks.push_back(b);
}
}
if (!placeableBlocks.isEmpty())
{
// Can generate a unit
createUnit(unitId, m_nSide);
std::random_shuffle(placeableBlocks.begin(), placeableBlocks.end());
m_confrontingBlock = placeableBlocks[0];
}
}
// End operation, begin simulation
// m_movingRoute: one element - the building
// m_confrontingBlock: where the unit generates
confrontUnit(); // no need to move, go directly to confrontUnit()
}
void AIProcessor::createUnit(int unitId, int side)
{
if (m_tempUnit != nullptr)
{
delete m_tempUnit;
}
int maxHP = m_gameInfo->getUnitInfo()[unitId][6];
m_tempUnit = new Unit(unitId, side, maxHP, m_map);
}
void AIProcessor::activate()
{
qDebug() << "AI for side" << m_nSide + 1 << "activated";
float **unitInfo = m_gameInfo->getUnitInfo();
m_remainingBlocks.clear();
m_map->getAllBlocks(m_remainingBlocks, m_nSide);
std::sort(m_remainingBlocks.begin(), m_remainingBlocks.end(), [ = ](const Block * b1, const Block * b2)
{
// sort by attacking range in ascending order (process last block first)
return unitInfo[b1->getUnit()->getId()][3] < unitInfo[b2->getUnit()->getId()][3];
});
nextMove();
}
void AIProcessor::nextMove()
{
if (m_remainingBlocks.size() <= 0)
{
finishRound();
return;
}
Block *block = m_remainingBlocks.last();
m_remainingBlocks.pop_back();
int unitId = block->getUnit()->getId();
if (unitId <= 18)
{
moveSingleUnit(block);
}
else
{
if (block->getUnit()->getInnerType() >= 1 || block->getUnit()->getInnerType() <= 3)
{
operateBuilding(block);
}
}
}
void AIProcessor::confrontUnit()
{
if (m_confrontingBlock == nullptr || m_movingRoute.last() == nullptr)
{
emit operationFinished();
return;
}
// Battle
bool battle = false;
Unit *activeUnit = m_movingRoute.last()->getUnit();
Unit *passiveUnit = m_confrontingBlock->getUnit();
if (passiveUnit != nullptr)
{
if (passiveUnit->isCarrier() && passiveUnit->getSide() == m_nSide)
{
// Get in the carrier
passiveUnit->setCarrier(activeUnit);
m_movingRoute.last()->setUnit(nullptr);
}
else
{
// Two real units battle
m_battleWidget = new BattleWidget(m_movingRoute.last(), m_confrontingBlock,
m_gameInfo, static_cast<QWidget *>(parent()));
battle = true;
connect(m_battleWidget, &BattleWidget::end, this, [ = ]()
{
// Battle animation ends: delete battle widget
delete m_battleWidget;
emit operationFinished();
});
m_battleWidget->begin();
// Attack/Capture
int **terrainInfo = m_gameInfo->getTerrainInfo();
float **unitInfo = m_gameInfo->getUnitInfo();
float **damageMatrix = m_gameInfo->getDamageMatrix();
int activeId = activeUnit->getId();
int passiveId = passiveUnit->getId();
int activeAttack = unitInfo[activeId][5];
int passiveAttack = unitInfo[passiveId][5];
// Check critical hit
bool critical = activeUnit->checkCritical();
double multiplier = (critical ? unitInfo[activeId][11] : 1.0);
// Check terrain shields
if (passiveId < 10 || passiveId > 13)
{
// Enemy not an air unit
int shields = terrainInfo[m_confrontingBlock->getTerrain()][5];
multiplier *= ((10.0 - shields) / 10.0);
}
// Calculate damage
bool killed = false;
double activeRandom = (std::rand() % 10 + 95) / 100.0;
int activeDamage = damageMatrix[activeId][passiveId] * multiplier * activeAttack * activeRandom;
killed = passiveUnit->injured(activeDamage);
m_battleWidget->setActiveAttack(activeDamage, killed, critical);
if (killed)
{
// killed
if (passiveUnit->getId() <= 18)
{
// not a building
if (passiveUnit->getCarrier() != nullptr)
{
// is a carrier and with a unit in it
m_stats->removeUnit(passiveUnit->getCarrier());
delete passiveUnit->getCarrier();
}
m_stats->removeUnit(passiveUnit);
delete passiveUnit;
m_confrontingBlock->setUnit(nullptr);
}
else
{
// building
Building *building = static_cast<Building *>(passiveUnit);
if (building->getSide() >= 0)
{
m_stats->removeUnit(building);
building->setSide(-1);
}
else
{
building->regenerate(0.5);
building->setSide(m_nSide);
m_stats->addUnit(building);
}
}
}
if (!killed)
{
// Find out if they are adjacent blocks
QVector<Block *> v;
m_map->getAdjacentBlocks(v, m_movingRoute.last());
if (v.contains(m_confrontingBlock))
{
// Adjacent: counter-attack
double passiveRandom = (std::rand() % 10 + 95) / 100.0;
int passiveDamage = damageMatrix[passiveId][activeId] * passiveAttack * passiveRandom / 2;
killed = activeUnit->injured(passiveDamage);
m_battleWidget->setPassiveAttack(passiveDamage, killed);
if (killed)
{
m_stats->removeUnit(activeUnit);
delete activeUnit;
m_movingRoute.last()->setUnit(nullptr);
// activeUnit = nullptr;
}
}
}
}
}
else
{
if (activeUnit->isCarrier())
{
// Get out of the carrier
m_confrontingBlock->setUnit(activeUnit->getCarrier());
activeUnit->setCarrier(nullptr);
}
else
{
// A building generating a unit
m_confrontingBlock->setUnit(m_tempUnit);
m_stats->addUnit(m_tempUnit);
m_stats->addCoins(-m_gameInfo->getUnitInfo()[m_tempUnit->getId()][9], m_nSide);
m_tempUnit = nullptr;
}
}
// Battle ends (if there is a battle)
m_confrontingBlock = nullptr;
if (!battle)
{
emit operationFinished();
}
}
void AIProcessor::finishRound()
{
// Regenerate buildings, add coins
for (const auto &unit : m_stats->getUnits(m_nSide))
{
// Regenerate buildings
if (unit->getId() > 18)
{
unit->regenerate(0.1);
if (unit->getInnerType() >= 4 || unit->getInnerType() == 0)
{
// Village/Base: coins + 100
m_stats->addCoins(100, m_nSide);
}
}
}
qDebug() << "Units remaining" << m_stats->getUnits(m_nSide).size();
qDebug() << "Coins remaining" << m_stats->getCoins(m_nSide);
emit finished();
}
<file_sep>#ifndef GAMEINFO_H
#define GAMEINFO_H
#include <QObject>
class GameInfo : public QObject
{
Q_OBJECT
public:
explicit GameInfo(QObject *parent = nullptr);
~GameInfo();
void loadFile();
int **getTerrainInfo() const;
float **getUnitInfo() const;
float **getDamageMatrix() const;
const QStringList &getUnitNames() const;
const QStringList &getCommanderNames() const;
const QStringList &getBuildingNames() const;
const QStringList &getUnitDescription() const;
const QStringList &getCommanderDescription() const;
const QStringList &getBuildingDescription() const;
const QStringList &getTerrainNames() const;
private:
int **m_terrainInfo;
float **m_unitInfo;
float **m_damageMatrix;
int m_nTerrainNumber;
int m_nUnitType;
int m_nUnitNumber;
QStringList m_sUnitNames;
QStringList m_sCommanderNames;
QStringList m_sBuildingNames;
QStringList m_sUnitDescription;
QStringList m_sCommanderDescription;
QStringList m_sBuildingDescription;
QStringList m_sTerrainNames;
};
#endif // GAMEINFO_H
<file_sep>#ifndef GAMESTATS_H
#define GAMESTATS_H
#include "unit.h"
#include <QObject>
class GameStats : public QObject
{
Q_OBJECT
public:
explicit GameStats(QObject *parent = nullptr, int totalSides = 2, int coins = 100);
// Getters and setters
int getCoins(int side) const;
void addCoins(int deltaCoins, int side);
const QVector<Unit *> &getUnits(int side) const;
void addUnit(Unit *unit);
void removeUnit(Unit *unit);
private:
int m_nTotalSides;
int *m_nCoins;
QVector<Unit *> *m_units;
signals:
};
#endif // GAMESTATS_H
<file_sep>#ifndef UNIT_H
#define UNIT_H
#include <QObject>
#include <QPainter>
#include <QImage>
class Unit : public QObject
{
Q_OBJECT
public:
explicit Unit(int unitId, int side, int maxHP, QObject *parent = nullptr,
int innerType = 0, float HPPercentage = 1.0);
virtual void paint(QPainter *painter, const QRect &rect, int dynamicsId = 0, int side = -8) const;
// Getters and setters
int getId() const;
int getInnerType() const;
int getSide() const;
bool getActivity() const;
int getHP() const;
int getMaxHP() const;
float getHPPercentage() const;
Unit *getCarrier() const;
virtual void getImages(QVector<QImage> *images) const;
virtual bool isOperable() const;
bool isCarrier() const;
void setDirection(int direction);
void setActivity(bool active);
void setCarrier(Unit *unit);
// Game-related
bool injured(int damage); // return true if killed
bool checkCritical() const; // check if reach critical-hit criteria
void regenerate(double ratio); // recover by ratio (maxHP)
// Convert Image color to gray
static QImage grayImage(const QImage *image);
protected:
// Attributes
int m_nId; // value: 0~20
int m_nInnerType; // inner type of the unit (e.g. three commanders)
QImage m_images[4]; // images: 2 facing right, 2 left
// Properties
int m_nSide; // side of the unit: 0~1 (0-player)
int m_nDirection; // value: 0-right, 1-left
bool m_bActive; // can be moved in this round
Unit *m_carryingUnit; // (just for wagons, balloons and barges) the unit they carry
// Game info
int m_nHealthPoint; // HP
int m_nMaxHealthPoint; // max HP
signals:
};
#endif // UNIT_H
<file_sep>#ifndef BUILDING_H
#define BUILDING_H
#include "unit.h"
class Building : public Unit
{
public:
explicit Building(int unitId, int side, int maxHP, QObject *parent = nullptr, int innerType = 0);
virtual void paint(QPainter *painter, const QRect &rect, int dynamicsId = 0, int side = -8) const;
// NEW Getter and setter
void setSide(int side);
virtual void getImages(QVector<QImage> *images) const;
virtual bool isOperable() const;
};
#endif // BUILDING_H
<file_sep>#include "settings.h"
Settings::Settings(QObject *parent)
: QObject(parent),
m_nRefreshTime(15), // refresh time WARNING: game might crash if too low
m_nMoveSteps(4), // unit move steps
m_mapNames{"ai_test", "standard", "lake", "mountain", "river_delta"}, // map names
m_mapSizes{QSize(20, 20), QSize(20, 20), QSize(20, 20), QSize(20, 20), QSize(50, 59)}, // map sizes (width, height)
m_nCurrentMap(0), // current map
m_nBlockSize(30), // initial size of a block
m_nZoomScale(10), // scale change per scroll
m_bFogMode(true), // fog mode
m_bAI(false), // use AI
m_backgroundMusic("./music/bgm05.mp3"), // bgm filename
m_nVolume(5), // music volume
m_nSEVolume(15) // sound effect volume
{
}
<file_sep>#include "map.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
Map::Map(QSize size, QObject *parent, int blockSize, QPoint offset)
: QObject(parent),
m_size(size),
m_pOffset(offset),
m_nDynamicsId(0),
m_nBlockSize(blockSize),
m_nScale(100)
{
m_matrix = new Block **[m_size.height()];
for (int i = 0; i < m_size.height(); i++)
{
m_matrix[i] = new Block *[m_size.width()]();
}
}
Map::~Map()
{
for (int i = 0; i < m_size.height(); i++)
{
delete m_matrix[i];
}
delete m_matrix;
}
void Map::loadTerrain(const QString &filename, bool fogMode)
{
QFile data(filename);
if (!data.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&data);
QStringList sizeStr = in.readLine().split(" ");
if (sizeStr[0].toInt() != m_size.height() || sizeStr[1].toInt() != m_size.width())
{
qDebug() << "Map size doesn't match";
return;
}
for (int i = 0; i < m_size.height(); i++)
{
QStringList rowStr = in.readLine().simplified().split(" ");
for (int j = 0; j < m_size.width(); j++)
{
if (j >= rowStr.size())
{
qDebug() << "Map incomplete";
break;
}
int id = rowStr[j].toInt();
if (id == 0)
{
m_matrix[i][j] = nullptr;
}
else
{
m_matrix[i][j] = new Block(id, i, j, this, fogMode);
}
}
}
qDebug() << "Map" << filename << "loaded";
data.close();
updateAllBlocks();
}
void Map::loadUnits(const QString &filename, GameInfo *gameInfo, GameStats *stats)
{
QFile data(filename);
if (!data.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&data);
in.readLine(); // skip comments
float **unitInfo = gameInfo->getUnitInfo();
while (!in.atEnd())
{
QStringList rowStr = in.readLine().simplified().split(" ");
if (rowStr.size() == 5)
{
Block *block = getBlock(rowStr[0].toInt(), rowStr[1].toInt());
if (block != nullptr && block->getUnit() == nullptr)
{
int unitId = rowStr[3].toInt();
int side = rowStr[2].toInt();
block->setUnit(unitId, side, unitInfo[unitId][6], rowStr[4].toInt());
if (side >= 0)
{
stats->addUnit(block->getUnit());
}
}
}
}
qDebug() << "Units" << filename << "loaded";
data.close();
}
Block *Map::getBlock(int row, int col) const
{
if (row < 0 || row >= m_size.height() || col < 0 || col >= m_size.width())
return nullptr;
return m_matrix[row][col];
}
Block *Map::getBlock(QPoint position) const
{
int newBlockSize = m_nBlockSize * m_nScale / 100;
int deltaX = newBlockSize * 2;
int deltaY = newBlockSize * 1.8;
int row = (position.y() - m_pOffset.y() + deltaY) / deltaY;
if (row < 0 || row > m_size.height())
{
return nullptr; // outside the map
}
int col = (position.x() - m_pOffset.x() + deltaX / 2) / deltaX;
if (col < 0 || col > m_size.width())
{
return nullptr; // outside the map
}
// Narrow down to two columns and two rows: row-1~row, col-1~col
for (int i = row - 1; i <= row; i++)
{
if (i < 0 || i >= m_size.height())
{
continue;
}
for (int j = col - 1; j <= col; j++)
{
if (j < 0 || j >= m_size.width())
{
continue;
}
if (m_matrix[i][j]->getArea()->containsPoint(position, Qt::OddEvenFill))
{
return m_matrix[i][j];
}
}
}
return nullptr;
}
QSize Map::getSize() const
{
return m_size;
}
int Map::getDynamicsId() const
{
return m_nDynamicsId;
}
QPoint Map::getCenterPosition(const Block *block) const
{
int row = block->getRow();
int col = block->getColumn();
int newBlockSize = m_nBlockSize * m_nScale / 100;
int deltaX = newBlockSize * 2;
int deltaY = newBlockSize * 1.8;
QPoint pos = m_pOffset + QPoint((row % 2 ? newBlockSize : 0) + col * deltaX,
row * deltaY);
return pos;
}
int Map::getBlockSize() const
{
return m_nBlockSize * m_nScale / 100;
}
int Map::getScale() const
{
return m_nScale;
}
void Map::getAdjacentBlocks(QVector<Block *> &blockVector, Block *block) const
{
if (block == nullptr)
{
return;
}
static int deltaCoordinates[2][6][2] =
{
{{-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, -1}, {1, 0}}, // even rows
{{-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, 0}, {1, 1}} // odd rows
}; // index delta of blocks that are adjacent to the selected block
blockVector.clear();
int row = block->getRow();
int col = block->getColumn();
int parity = row % 2;
for (int i = 0; i < 6; i++)
{
Block *temp = getBlock(row + deltaCoordinates[parity][i][0], col + deltaCoordinates[parity][i][1]);
if (temp != nullptr)
{
blockVector.push_back(temp);
}
}
}
void Map::getAdjacentBlocks(QVector<Block *> &blockVector, Block *block, int rangeHigh, int rangeLow) const
{
if (block == nullptr)
{
return;
}
struct Vertex
{
Block *block;
int distance;
};
QVector<Vertex> remainingBlocks;
QVector<Vertex> countedBlocks;
remainingBlocks.push_back({block, 0}); // the vector only has the origin at first
while (!remainingBlocks.isEmpty())
{
// sort by distance, get the one with the shortest distance
std::sort(remainingBlocks.begin(), remainingBlocks.end(), [](const Vertex & v1, const Vertex & v2)
{
return v1.distance > v2.distance;
});
const Vertex temp = remainingBlocks.last();
remainingBlocks.pop_back();
if (temp.distance > rangeHigh) // other blocks are all out of reach
{
break;
}
QVector<Block *> adjacentBlocks;
getAdjacentBlocks(adjacentBlocks, temp.block);
for (const auto &adjBlock : qAsConst(adjacentBlocks))
{
int distance = temp.distance + 1;
bool counted = false;
// find out whether the block is counted
for (auto iter = remainingBlocks.begin(); iter != remainingBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
counted = true;
break;
}
}
if (!counted)
{
for (auto iter = countedBlocks.begin(); iter != countedBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
counted = true;
break;
}
}
if (!counted)
{
// not counted
remainingBlocks.push_back({adjBlock, distance});
}
}
}
countedBlocks.push_back(temp);
}
blockVector.clear();
for (const auto &vertex : qAsConst(countedBlocks))
{
if (vertex.distance >= rangeLow)
{
blockVector.append(vertex.block);
}
}
}
void Map::getAllBlocks(QVector<Block *> &blockVector, int side) const
{
blockVector.clear();
int rows = m_size.height();
int cols = m_size.width();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Block *block = getBlock(i, j);
if (block != nullptr && block->getUnit() != nullptr && block->getUnit()->getSide() == side)
{
blockVector.push_back(block);
}
}
}
}
void Map::adjustOffset(QPoint deltaPos)
{
m_pOffset += deltaPos;
updateAllBlocks();
}
void Map::adjustScale(int deltaScale, QPointF center)
{
if ((m_nScale <= 30 && deltaScale < 0) || (m_nScale >= 150 && deltaScale > 0))
{
return;
}
center -= m_pOffset; // relative position
QPointF deltaOffset = (deltaScale * 1.0 / m_nScale) * center;
m_pOffset -= deltaOffset.toPoint();
m_nScale += deltaScale;
updateAllBlocks();
}
void Map::updateAllBlocks() const
{
int rows = m_size.height();
int cols = m_size.width();
int newBlockSize = m_nBlockSize * m_nScale / 100;
int deltaX = newBlockSize * 2;
int deltaY = newBlockSize * 1.8;
QPoint pos = m_pOffset;
for (int i = 0; i < rows; i++)
{
pos.setX(m_pOffset.x() + (i % 2 ? newBlockSize : 0));
for (int j = 0; j < cols; j++)
{
Block *block = getBlock(i, j);
if (block != nullptr)
{
block->updateArea(pos, newBlockSize);
}
pos.setX(pos.x() + deltaX);
}
pos.setY(pos.y() + deltaY);
}
}
void Map::paint(QPainter *painter, int part) const
{
int rows = m_size.height();
int cols = m_size.width();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Block *block = getBlock(i, j);
if (block != nullptr)
{
block->paint(painter, part, m_nDynamicsId);
}
}
}
}
void Map::updateDynamics()
{
m_nDynamicsId = 1 - m_nDynamicsId;
}
<file_sep>#include "unitselectionwidget.h"
#include "ui_unitselectionwidget.h"
#include <QPushButton>
#include <QDebug>
UnitSelectionWidget::UnitSelectionWidget(GameInfo *gameInfo, QWidget *parent) :
QWidget(parent),
ui(new Ui::UnitSelectionWidget),
m_listWidgetItems(),
m_gameInfo(gameInfo),
m_nKind(0)
{
ui->setupUi(this);
m_descriptionWidget = new DescriptionWidget(m_gameInfo, this, true);
ui->horizontalLayout->addWidget(m_descriptionWidget);
m_descriptionWidget->setUnit(nullptr, 0);
m_descriptionWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Preferred);
m_listWidget = ui->listWidget;
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
setAttribute(Qt::WA_StyledBackground, true);
hide();
connect(m_listWidget, &QListWidget::currentItemChanged, this, &UnitSelectionWidget::updateButtonValidity);
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &UnitSelectionWidget::selected);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &UnitSelectionWidget::cancel);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &UnitSelectionWidget::hide);
}
UnitSelectionWidget::~UnitSelectionWidget()
{
delete ui;
}
void UnitSelectionWidget::loadUnits(const QStringList &unitNames, float **unitInfo)
{
for (int i = 0; i < 18; i++)
{
QListWidgetItem *item = new QListWidgetItem(m_listWidget, unitInfo[i][10]);
item->setSizeHint(QSize(100, 80));
ItemWidget *w = new ItemWidget(unitNames[i], unitInfo[i][9],
QPixmap(":/image/unit/" + QString::number(i)).copy(0, 0, 64, 64),
m_listWidget);
m_listWidget->setItemWidget(item, w);
m_listWidgetItems.push_back(item);
}
}
void UnitSelectionWidget::showUnits(int unitKind, int coins)
{
// Set kind
static int kindList[3] = {1, 0, 7};
m_nKind = kindList[unitKind];
m_descriptionWidget->setUnit(nullptr, m_nKind);
// Set coins
ui->currentCoinsLabel->setText(QString::number(coins));
// Hide other items
for (const auto &item : qAsConst(m_listWidgetItems))
{
if (item->type() == unitKind)
{
item->setHidden(false);
ItemWidget *w = static_cast<ItemWidget *>(m_listWidget->itemWidget(item));
if (w->m_cost <= coins)
{
w->setValidity(true);
item->setFlags(item->flags() | Qt::ItemIsEnabled);
}
else
{
w->setValidity(false);
item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
}
}
else
{
item->setHidden(true);
}
}
// Adjust screen size
adjustSize();
// Reset selection
m_listWidget->setCurrentItem(nullptr);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
show();
m_descriptionWidget->show();
m_descriptionWidget->adjustBackground();
}
void UnitSelectionWidget::adjustSize()
{
int parentWidth = static_cast<QWidget *>(parent())->width();
int parentHeight = static_cast<QWidget *>(parent())->height();
setGeometry(parentWidth / 2 - 625, parentHeight / 2 - 350, 1250, 700);
m_descriptionWidget->show();
m_descriptionWidget->adjustBackground();
m_descriptionWidget->setFixedWidth(800);
}
void UnitSelectionWidget::selected()
{
if (m_listWidget->currentItem() == nullptr)
{
return;
}
int selectedId = m_listWidgetItems.indexOf(m_listWidget->currentItem());
emit confirm(selectedId);
hide();
}
void UnitSelectionWidget::updateButtonValidity()
{
QListWidgetItem *item = m_listWidget->currentItem();
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(item != nullptr);
if (item == nullptr)
{
m_descriptionWidget->setUnit(nullptr, m_nKind);
}
else
{
int selectedId = m_listWidgetItems.indexOf(item);
Unit unit(selectedId, 0, m_gameInfo->getUnitInfo()[selectedId][6], this);
m_descriptionWidget->setUnit(&unit, m_nKind);
}
m_descriptionWidget->adjustBackground();
}
UnitSelectionWidget::ItemWidget::ItemWidget(const QString &name, int cost,
const QPixmap &image, QWidget *parent) : QWidget(parent), m_cost(cost)
{
QHBoxLayout *widgetLayout = new QHBoxLayout(this);
widgetLayout->setContentsMargins(20, 0, 20, 0);
QLabel *pic = new QLabel(this);
pic->setPixmap(image);
widgetLayout->addWidget(pic);
QLabel *nameLabel = new QLabel(name, this);
nameLabel->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Preferred);
widgetLayout->addWidget(nameLabel);
QLabel *icon = new QLabel(this);
icon->setPixmap(QPixmap(":/image/icon/coin"));
widgetLayout->addWidget(icon);
m_costLabel = new QLabel(QString("%1").arg(cost, 4), this);
widgetLayout->addWidget(m_costLabel);
this->setLayout(widgetLayout);
}
void UnitSelectionWidget::ItemWidget::setValidity(bool valid)
{
if (!valid)
{
m_costLabel->setStyleSheet("color: #b34446");
}
else
{
m_costLabel->setStyleSheet("color: #3d4265");
}
}
<file_sep>#include "building.h"
#include <QDebug>
Building::Building(int unitId, int side, int maxHP, QObject *parent, int innerType)
: Unit(unitId, side, maxHP, parent, innerType)
{
// Reload images
for (int i = 0; i < 3; i++)
{
m_images[i] = QImage(QString(":/image/building/%1_%2_%3").arg(unitId).arg(innerType).arg(i - 1));
}
// Uncaptured buildings
if (m_nSide < 0)
{
m_nHealthPoint = 0;
}
// Base
if (m_nInnerType == 0)
{
m_nHealthPoint *= 2;
m_nMaxHealthPoint *= 2;
}
}
void Building::paint(QPainter *painter, const QRect &rect, int dynamicsId, int side) const
{
Q_UNUSED(dynamicsId);
if (side >= -1)
{
// special request
painter->drawImage(rect, grayImage(m_images + side + 1));
return;
}
if (m_bActive)
{
painter->drawImage(rect, m_images[m_nSide + 1]);
}
else
{
painter->drawImage(rect, grayImage(m_images + m_nSide + 1));
}
if (m_nHealthPoint < m_nMaxHealthPoint && m_nHealthPoint > 0)
{
painter->drawRect(rect.center().x() - 3, rect.center().y() - 17, 15, 20);
painter->drawText(rect.center(), QString::number(m_nHealthPoint * 10 / m_nMaxHealthPoint));
}
}
void Building::setSide(int side)
{
m_nSide = side;
}
void Building::getImages(QVector<QImage> *images) const
{
images->clear();
if (m_nId <= 18)
{
Unit::getImages(images);
}
else
{
images->push_back(m_images[m_nSide + 1]);
images->push_back(m_images[m_nSide + 1]);
}
}
bool Building::isOperable() const
{
return Unit::isOperable() || (m_nId == 19 && m_nInnerType >= 1 && m_nInnerType <= 3);
}
<file_sep>#ifndef SETTINGSWIDGET_H
#define SETTINGSWIDGET_H
#include "settings.h"
#include <QWidget>
namespace Ui
{
class SettingsWidget;
}
class SettingsWidget : public QWidget
{
Q_OBJECT
public:
explicit SettingsWidget(Settings *settings, QWidget *parent = nullptr);
~SettingsWidget();
virtual void closeEvent(QCloseEvent *event);
public slots:
void changeMap(int);
private:
Ui::SettingsWidget *ui;
Settings *m_settings;
signals:
void windowClosed();
};
#endif // SETTINGSWIDGET_H
<file_sep>#include "gameprocessor.h"
#include "building.h"
#include <QPainterPath>
#include <QDebug>
GameProcessor::GameProcessor(Settings *settings,
GameInfo *gameInfo,
Map *map,
GameStats *stats,
QMediaPlayer *SEplayer,
TipsLabel *tipsLabel,
QWidget *moveWidget,
UnitSelectionWidget *unitSelectionWidget,
DescriptionWidget *descriptionWidget,
QMenu *actionContextMenu,
QMenu *mainContextMenu,
QObject *parent,
int movingSide,
int totalSides)
: QObject(parent),
m_settings(settings),
m_gameInfo(gameInfo),
m_map(map),
m_stats(stats),
m_SEplayer(SEplayer),
m_tipsLabel(tipsLabel),
m_moveWidget(moveWidget),
m_unitSelectionWidget(unitSelectionWidget),
m_descriptionWidget(descriptionWidget),
m_battleWidget(nullptr),
m_actionContextMenu(actionContextMenu),
m_mainContextMenu(mainContextMenu),
m_nMovingSide(movingSide),
m_nTotalSides(totalSides),
m_nStage(0),
m_nRound(1),
m_selectedBlock(nullptr),
m_cursorBlock(nullptr),
m_nMovesLeft(0),
m_movingRoute(),
m_accessibleBlocks(),
m_attackableBlocks(),
m_capturableBlocks(),
m_carrierBlocks(),
m_tempUnit(nullptr)
{
// Initialize unit selection widgets
m_unitSelectionWidget->loadUnits(m_gameInfo->getUnitNames(), m_gameInfo->getUnitInfo());
// Initialize context menu actions
m_actions[0] = new QAction(QPixmap(":/image/icon/damage").scaledToHeight(30), tr("Get in"), this);
m_actions[1] = new QAction(QPixmap(":/image/icon/damage").scaledToHeight(30), tr("Get out"), this);
m_actions[2] = new QAction(QPixmap(":/image/icon/commander").scaledToHeight(30), tr("Capture"), this);
m_actions[3] = new QAction(QPixmap(":/image/icon/sword").scaledToHeight(30), tr("Attack"), this);
m_actions[4] = new QAction(QPixmap(":/image/icon/unit").scaledToHeight(30), tr("Wait"), this);
m_actions[5] = new QAction(tr("Cancel"), this);
m_mainActions[0] = new QAction(QPixmap(":/image/icon/groove").scaledToHeight(30), tr("End turn"), this);
m_mainActions[1] = new QAction(QPixmap(":/image/icon/control").scaledToHeight(30), tr("Exit game"), this);
m_mainActions[2] = new QAction(tr("Cancel"), this);
// Initialize pointer images
for (int i = 0; i < 6; i++)
{
m_pointerImage[i] = QImage(":/hightlight_pointer/" + QString::number(i));
}
// Initialize unit mover
m_unitMover = new UnitMover(m_settings, m_map, this);
// Connect signals and slots
connect(this, &GameProcessor::enterStage, this, &GameProcessor::processStage);
connect(this, &GameProcessor::endOfTurn, this, &GameProcessor::changeSide);
connect(m_unitMover, &UnitMover::movementFinished, this, [ = ]()
{
// Movement (stage 4) completes
emit enterStage(5);
});
connect(this, &GameProcessor::gameClosed, this, [ = ]()
{
// Game exit
static_cast<QWidget *>(parent)->close();
});
connect(m_unitSelectionWidget, &UnitSelectionWidget::confirm, this, [ = ](int unitId)
{
// Unit selection: unitId
createUnit(unitId, m_nMovingSide);
emit enterStage(12);
});
connect(m_unitSelectionWidget, &UnitSelectionWidget::cancel, this, [ = ]()
{
// Unit selection: cancel
emit enterStage(0);
});
// Action context menu
connect(m_actions[0], &QAction::triggered, this, [ = ]()
{
m_capturableBlocks.clear();
m_attackableBlocks.clear();
emit enterStage(3); // Action: get in
});
connect(m_actions[1], &QAction::triggered, this, [ = ]()
{
m_capturableBlocks.clear();
m_attackableBlocks.clear();
emit enterStage(3); // Action: get out
});
connect(m_actions[2], &QAction::triggered, this, [ = ]()
{
m_carrierBlocks.clear();
m_attackableBlocks.clear();
emit enterStage(3); // Action: capture
});
connect(m_actions[3], &QAction::triggered, this, [ = ]()
{
m_carrierBlocks.clear();
m_capturableBlocks.clear();
emit enterStage(3); // Action: attack
});
connect(m_actions[4], &QAction::triggered, this, [ = ]()
{
m_selectedBlock = nullptr;
emit enterStage(4); // Action: wait
});
connect(m_actions[5], &QAction::triggered, this, [ = ]()
{
emit enterStage(0); // Action: cancel
});
// Main context menu
connect(m_mainActions[0], &QAction::triggered, this, [ = ]()
{
emit enterStage(16); // Action: End turn
});
connect(m_mainActions[1], &QAction::triggered, this, [ = ]()
{
emit gameClosed(); // Action: Exit game
});
}
void GameProcessor::paint(QPainter *painter)
{
m_unitMover->paint(painter);
if (m_nMovingSide == 0 || m_nMovingSide == 1) // TODO: write it in settings to decide human
{
switch (m_nStage)
{
case -1: // Show selected enemy unit movement range
{
// Paint enemy unit accessible blocks
for (const auto &block : qAsConst(m_accessibleBlocks))
{
block->paintPointer(painter, m_pointerImage[4]);
}
break;
}
case 1: // Selecting moving route: show movement range and attack zone
{
// Paint accessible blocks
for (const auto &block : qAsConst(m_accessibleBlocks))
{
block->paintPointer(painter, m_pointerImage[2]);
}
// Paint attack zone
for (const auto &block : qAsConst(m_attackableBlocks))
{
block->paintPointer(painter, m_pointerImage[3]);
}
// Paint capturable blocks
for (const auto &block : qAsConst(m_capturableBlocks))
{
block->paintPointer(painter, m_pointerImage[3]);
}
// Paint carrier-related blocks
for (const auto &block : qAsConst(m_carrierBlocks))
{
block->paintPointer(painter, m_pointerImage[5]);
}
// Paint the moving route
QPainterPath path;
path.moveTo(m_movingRoute.first()->getCenter());
for (auto iter = m_movingRoute.begin() + 1; iter != m_movingRoute.end(); iter++)
{
path.lineTo((*iter)->getCenter());
}
QPen pen(QColor(255, 180, 35, 180), m_map->getBlockSize());
pen.setJoinStyle(Qt::PenJoinStyle::RoundJoin);
painter->setPen(pen);
painter->drawPath(path);
break;
}
case 2: // Choose whether to attack: show attack zone
case 3: // Selecting a unit to attack: show attack zone
{
// Paint attack zone and unit generating zone
for (const auto &block : qAsConst(m_attackableBlocks))
{
Unit *unit = block->getUnit();
if (unit != nullptr && unit->getSide() != m_nMovingSide)
{
block->paintPointer(painter, m_pointerImage[3]);
}
else if (unit == nullptr)
{
block->paintPointer(painter, m_pointerImage[5]);
}
}
// Paint capturable blocks
for (const auto &block : qAsConst(m_capturableBlocks))
{
block->paintPointer(painter, m_pointerImage[3]);
}
// Paint carrier-related blocks
for (const auto &block : qAsConst(m_carrierBlocks))
{
block->paintPointer(painter, m_pointerImage[5]);
}
// Paint the moving route
QPainterPath path;
path.moveTo(m_movingRoute.first()->getCenter());
for (auto iter = m_movingRoute.begin() + 1; iter != m_movingRoute.end(); iter++)
{
path.lineTo((*iter)->getCenter());
}
QPen pen(QColor(255, 180, 35, 180), m_map->getBlockSize());
pen.setJoinStyle(Qt::PenJoinStyle::RoundJoin);
painter->setPen(pen);
painter->drawPath(path);
break;
}
}
if (m_cursorBlock != nullptr)
{
// Paint the block with the cursor on
m_cursorBlock->paintPointer(painter, m_pointerImage[0]);
}
if (m_selectedBlock != nullptr)
{
// Paint the selected block
m_selectedBlock->paintPointer(painter, m_pointerImage[1]);
}
}
}
void GameProcessor::updateAccessibleBlocks(Block *block, int unitType, int movement)
{
int **terrainInfo = m_gameInfo->getTerrainInfo(); // move cost: terrainInfo[terrainId][unitType]
m_accessibleBlocks.clear();
struct Vertex
{
Block *block;
int distance;
};
QVector<Vertex> remainingBlocks;
remainingBlocks.push_back({block, 0}); // the vector only has the origin at first
while (!remainingBlocks.isEmpty())
{
// sort by distance, get the one with the shortest distance
std::sort(remainingBlocks.begin(), remainingBlocks.end(), [](const Vertex & v1, const Vertex & v2)
{
return v1.distance > v2.distance;
});
const Vertex temp = remainingBlocks.last();
remainingBlocks.pop_back();
if (temp.distance > movement) // other blocks are all out of reach
{
break;
}
QVector<Block *> adjacentBlocks;
m_map->getAdjacentBlocks(adjacentBlocks, temp.block);
for (const auto &adjBlock : qAsConst(adjacentBlocks))
{
if (adjBlock->getUnit() != nullptr)
{
continue;
}
int distance = temp.distance + terrainInfo[adjBlock->getTerrain()][unitType];
bool counted = false;
// find out whether the block is counted
for (auto iter = remainingBlocks.begin(); iter != remainingBlocks.end(); iter++)
{
if (iter->block == adjBlock)
{
// yes
if (iter->distance > distance)
{
// update distance
iter->distance = distance;
}
counted = true;
break;
}
}
if (!counted)
{
counted = m_accessibleBlocks.contains(adjBlock);
if (!counted)
{
// not counted
remainingBlocks.push_back({adjBlock, distance});
}
}
}
m_accessibleBlocks.push_back(temp.block);
}
}
void GameProcessor::updateOperatableBlocks(Block *block, int rangeLow, int rangeHigh, bool capture)
{
m_attackableBlocks.clear();
m_capturableBlocks.clear();
// Attackable
QVector<Block *> blocksInRange;
m_map->getAdjacentBlocks(blocksInRange, block, rangeHigh, rangeLow);
for (const auto &block : qAsConst(blocksInRange))
{
// submit blocks with enemy units for attackable blocks
Unit *unit = block->getUnit();
if (unit != nullptr && unit->getSide() != m_nMovingSide && unit->getSide() >= 0)
{
m_attackableBlocks.push_back(block);
}
}
if (!capture)
{
return;
}
// Capturable
QVector<Block *> nearbyBlocks;
m_map->getAdjacentBlocks(nearbyBlocks, block);
for (const auto &block : qAsConst(nearbyBlocks))
{
// remove blocks far away or captured buildings for capturable blocks
Unit *unit = block->getUnit();
if (unit != nullptr && unit->getSide() < 0)
{
m_capturableBlocks.push_back(block);
}
}
}
void GameProcessor::updateCarrierBlocks(Block *block, Unit *unit)
{
m_carrierBlocks.clear();
if ((!unit->isCarrier() && !m_gameInfo->getUnitInfo()[unit->getId()][8]) ||
(unit->isCarrier() && unit->getCarrier() == nullptr))
{
// not related or nothing in the carrier
return;
}
QVector<Block *> nearbyBlocks;
m_map->getAdjacentBlocks(nearbyBlocks, block);
if (!unit->isCarrier())
{
// can be carried: search for nearby empty carriers
for (const auto &adjBlock : qAsConst(nearbyBlocks))
{
if (adjBlock->getUnit() != nullptr &&
adjBlock->getUnit()->getSide() == m_nMovingSide &&
adjBlock->getUnit()->isCarrier() &&
adjBlock->getUnit()->getCarrier() == nullptr)
{
m_carrierBlocks.push_back(adjBlock);
}
}
}
else
{
// occupied carrier: search for nearby empty blocks to drop
int **terrainInfo = m_gameInfo->getTerrainInfo();
int unitType = m_gameInfo->getUnitInfo()[unit->getCarrier()->getId()][0];
for (const auto &adjBlock : qAsConst(nearbyBlocks))
{
if (adjBlock->getUnit() == nullptr && terrainInfo[adjBlock->getTerrain()][unitType] < 10)
{
m_carrierBlocks.push_back(adjBlock);
}
}
}
}
void GameProcessor::updateVisibleBlocks()
{
// Reset visibility
int mapRows = m_map->getSize().height();
int mapCols = m_map->getSize().width();
for (int i = 0; i < mapRows; i++)
{
for (int j = 0; j < mapCols; j++)
{
Block *block = m_map->getBlock(i, j);
if (block != nullptr)
{
block->setVisible(false);
}
}
}
// Set own visibility
float **unitInfo = m_gameInfo->getUnitInfo();
QVector<Block *> ownBlocks;
m_map->getAllBlocks(ownBlocks, m_nMovingSide);
QVector<Block *> visibleBlocks;
for (const auto &ownBlock : qAsConst(ownBlocks))
{
int unitId = ownBlock->getUnit()->getId();
m_map->getAdjacentBlocks(visibleBlocks, ownBlock, unitInfo[unitId][4]);
for (const auto &block : qAsConst(visibleBlocks))
{
block->setVisible(true);
}
}
}
void GameProcessor::createUnit(int unitId, int side)
{
if (m_tempUnit != nullptr)
{
delete m_tempUnit;
}
int maxHP = m_gameInfo->getUnitInfo()[unitId][6];
m_tempUnit = new Unit(unitId, side, maxHP, m_map);
}
void GameProcessor::confrontUnit()
{
// check whether there is a battle
bool battle = false;
Unit *activeUnit = m_movingRoute.last()->getUnit();
if (m_selectedBlock != nullptr)
{
Unit *passiveUnit = m_selectedBlock->getUnit();
if (passiveUnit != nullptr)
{
if (passiveUnit->isCarrier() && passiveUnit->getSide() == m_nMovingSide)
{
// Get in the carrier
passiveUnit->setCarrier(activeUnit);
m_movingRoute.last()->setUnit(nullptr);
}
else
{
m_battleWidget = new BattleWidget(m_movingRoute.last(), m_selectedBlock,
m_gameInfo, static_cast<QWidget *>(parent()));
battle = true;
connect(m_battleWidget, &BattleWidget::end, this, [ = ]()
{
// Battle animation ends
emit enterStage(8);
});
m_battleWidget->begin();
// Attack/Capture
int **terrainInfo = m_gameInfo->getTerrainInfo();
float **unitInfo = m_gameInfo->getUnitInfo();
float **damageMatrix = m_gameInfo->getDamageMatrix();
int activeId = activeUnit->getId();
int passiveId = passiveUnit->getId();
int activeAttack = unitInfo[activeId][5];
int passiveAttack = unitInfo[passiveId][5];
// Check critical hit
bool critical = activeUnit->checkCritical();
double multiplier = (critical ? unitInfo[activeId][11] : 1.0);
// Check terrain shields
if (passiveId < 10 || passiveId > 13)
{
// Enemy not an air unit
int shields = terrainInfo[m_selectedBlock->getTerrain()][5];
multiplier *= ((10.0 - shields) / 10.0);
}
// Calculate damage
bool killed = false;
double activeRandom = (std::rand() % 10 + 95) / 100.0;
int activeDamage = damageMatrix[activeId][passiveId] * multiplier * activeAttack * activeRandom;
killed = passiveUnit->injured(activeDamage);
m_battleWidget->setActiveAttack(activeDamage, killed, critical);
if (killed)
{
// killed
if (passiveUnit->getId() <= 18)
{
// not a building
if (passiveUnit->getCarrier() != nullptr)
{
// is a carrier and with a unit in it
m_stats->removeUnit(passiveUnit->getCarrier());
delete passiveUnit->getCarrier();
}
m_stats->removeUnit(passiveUnit);
delete passiveUnit;
m_selectedBlock->setUnit(nullptr);
}
else
{
// building
Building *building = static_cast<Building *>(passiveUnit);
if (building->getSide() >= 0)
{
m_stats->removeUnit(building);
building->setSide(-1);
}
else
{
building->regenerate(0.5);
building->setSide(m_nMovingSide);
building->setActivity(false);
m_stats->addUnit(building);
}
}
}
if (!killed)
{
// Find out if they are adjacent blocks
QVector<Block *> v;
m_map->getAdjacentBlocks(v, m_movingRoute.last());
if (v.contains(m_selectedBlock))
{
double passiveRandom = (std::rand() % 10 + 95) / 100.0;
int passiveDamage = damageMatrix[passiveId][activeId] * passiveAttack * passiveRandom / 2;
killed = activeUnit->injured(passiveDamage);
m_battleWidget->setPassiveAttack(passiveDamage, killed);
if (killed)
{
m_stats->removeUnit(activeUnit);
delete activeUnit;
m_movingRoute.last()->setUnit(nullptr);
activeUnit = nullptr;
}
}
}
}
}
else
{
if (activeUnit->isCarrier())
{
// Get out of the carrier
m_selectedBlock->setUnit(activeUnit->getCarrier());
activeUnit->setCarrier(nullptr);
}
else
{
// A building generating a unit
m_tempUnit->setActivity(false);
m_selectedBlock->setUnit(m_tempUnit);
m_stats->addUnit(m_tempUnit);
m_stats->addCoins(-m_gameInfo->getUnitInfo()[m_tempUnit->getId()][9], m_nMovingSide);
m_tempUnit = nullptr;
}
}
// Battle ends (if there is a battle)
m_selectedBlock = nullptr;
}
// Invalidate the unit (if it exists)
if (activeUnit != nullptr)
{
activeUnit->setActivity(false);
}
if (!battle)
{
// no battles, no need to wait
emit enterStage(0);
}
}
void GameProcessor::checkWin()
{
qDebug() << "side 1" << m_stats->getUnits(0).size() << "side 2" << m_stats->getUnits(1).size();
// Check commanders and strongholds
bool foundCommander = false;
bool foundStronghold = false;
for (const auto &unit : qAsConst(m_stats->getUnits(1)))
{
if (unit->getId() == 18)
{
foundCommander = true;
}
if (unit->getId() == 19 && unit->getInnerType() == 0)
{
foundStronghold = true;
}
}
if (!foundCommander && !foundStronghold)
{
// Check win
parent()->findChild<QLabel *>("gameOverLabel")->setText(tr("Game over! Side 1 win! "));
emit enterStage(99);
return;
}
foundCommander = false;
foundStronghold = false;
for (const auto &unit : qAsConst(m_stats->getUnits(0)))
{
if (unit->getId() == 18)
{
foundCommander = true;
}
if (unit->getId() == 19 && unit->getInnerType() == 0)
{
foundStronghold = true;
}
}
if (!foundCommander && !foundStronghold)
{
// Check lose
parent()->findChild<QLabel *>("gameOverLabel")->setText(tr("Game over! Side 2 win! "));
emit enterStage(99);
return;
}
}
void GameProcessor::processStage(int stage)
{
m_nStage = stage;
qDebug() << "Enter stage" << m_nStage;
switch (m_nStage)
{
// stage -1: no necessary operations
case 0:
{
if (m_settings->m_bFogMode)
{
updateVisibleBlocks();
}
m_selectedBlock = nullptr;
m_movingRoute.clear();
m_accessibleBlocks.clear();
m_attackableBlocks.clear();
m_capturableBlocks.clear();
m_carrierBlocks.clear();
checkWin();
break;
}
case 1:
{
// Update accessible blocks
int unitId = m_selectedBlock->getUnit()->getId();
if (m_selectedBlock->getUnit()->getSide() == m_nMovingSide && unitId > 18)
{
// Select an own building
emit enterStage(11);
break;
}
int unitType = m_gameInfo->getUnitInfo()[unitId][0];
m_nMovesLeft = m_gameInfo->getUnitInfo()[unitId][1];
updateAccessibleBlocks(m_selectedBlock, unitType, m_nMovesLeft);
if (m_selectedBlock->getUnit()->getSide() != m_nMovingSide)
{
// Select an enemy unit
emit enterStage(-1);
break;
}
m_movingRoute.push_back(m_selectedBlock);
updateOperatableBlocks(m_selectedBlock,
m_gameInfo->getUnitInfo()[unitId][2],
m_gameInfo->getUnitInfo()[unitId][3],
m_gameInfo->getUnitInfo()[unitId][7]);
updateCarrierBlocks(m_selectedBlock, m_selectedBlock->getUnit());
// Show move widget
QVector<QImage> unitImages;
m_selectedBlock->getUnit()->getImages(&unitImages);
m_moveWidget->findChild<QLabel *>("unitPicLabel")->setPixmap(QPixmap::fromImage(unitImages[0]));
m_moveWidget->findChild<QLabel *>("unitMoveLabel")->setText(QString::number(m_nMovesLeft));
m_moveWidget->show();
break;
}
case 2:
{
// Hide move widget
m_moveWidget->hide();
// Show context menu
m_actionContextMenu->clear();
if (!m_carrierBlocks.isEmpty())
{
if (m_movingRoute.first()->getUnit()->isCarrier())
{
m_actionContextMenu->addAction(m_actions[1]);
}
else
{
m_actionContextMenu->addAction(m_actions[0]);
}
}
if (!m_capturableBlocks.isEmpty())
{
m_actionContextMenu->addAction(m_actions[2]);
}
if (!m_attackableBlocks.isEmpty())
{
m_actionContextMenu->addAction(m_actions[3]);
}
m_actionContextMenu->addAction(m_actions[4]);
m_actionContextMenu->addAction(m_actions[5]);
m_actionContextMenu->exec(QCursor::pos());
break;
}
// stage 3: no necessary operations
case 4:
{
// Hide move widget
m_moveWidget->hide();
// Begin moving
m_unitMover->moveUnit(m_movingRoute);
break;
}
case 5:
{
// Battle field or other operation
confrontUnit();
break;
}
case 8:
{
// Battle ends
delete m_battleWidget;
emit enterStage(0);
break;
}
case 11:
{
// Show unit selection widget
m_unitSelectionWidget->showUnits(m_selectedBlock->getUnit()->getInnerType() - 1,
m_stats->getCoins(m_nMovingSide));
break;
}
case 12:
{
// Update area that can be selected to generate a unit
m_attackableBlocks.clear();
QVector<Block *> blocks;
m_map->getAdjacentBlocks(blocks, m_selectedBlock);
int **terrainInfo = m_gameInfo->getTerrainInfo();
int unitType = m_gameInfo->getUnitInfo()[m_tempUnit->getId()][0];
for (const auto &adjBlock : qAsConst(blocks))
{
if (adjBlock->getUnit() == nullptr &&
terrainInfo[adjBlock->getTerrain()][unitType] < 10)
{
m_attackableBlocks.push_back(adjBlock);
}
}
// Clear other block vectors (for stage 3)
m_capturableBlocks.clear();
m_carrierBlocks.clear();
// Define move route (for stage 5)
m_movingRoute.push_back(m_selectedBlock);
emit enterStage(3);
break;
}
case 16:
{
// End turn
// Refresh all units, regenerate buildings, add coins
for (const auto &unit : m_stats->getUnits(m_nMovingSide))
{
// Refresh
unit->setActivity(true);
if (unit->getCarrier() != nullptr)
{
unit->getCarrier()->setActivity(true);
}
// Regenerate buildings
if (unit->getId() > 18)
{
unit->regenerate(0.1);
if (unit->getInnerType() >= 4 || unit->getInnerType() == 0)
{
// Village/Base: coins + 100
m_stats->addCoins(100, m_nMovingSide);
}
}
}
emit endOfTurn();
break;
}
// stage 20: no neccessary operations
case 99:
{
// Game over
parent()->findChild<QLabel *>("gameOverLabel")->show();
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, &QTimer::timeout, this, &GameProcessor::gameClosed);
timer->start(3000);
}
}
}
void GameProcessor::changeSide()
{
qDebug() << "=============Round" << m_nRound << "Side" << m_nMovingSide + 1 << "finished===============";
m_nMovingSide++;
if (m_nMovingSide >= m_nTotalSides)
{
m_nMovingSide = 0;
m_nRound++;
}
m_tipsLabel->popup(tr("Round ") + QString::number(m_nRound) +
tr(": Side ") + QString::number(m_nMovingSide + 1));
emit roundForSide(m_nMovingSide);
}
void GameProcessor::activate()
{
emit enterStage(0);
}
void GameProcessor::moveMap(QPoint deltaPos)
{
if (m_nStage == 11)
{
return;
}
m_map->adjustOffset(deltaPos);
}
void GameProcessor::zoomMap(int direction, QPointF point)
{
if (m_nStage == 11)
{
return;
}
m_map->adjustScale(direction * m_settings->m_nZoomScale, point);
m_tipsLabel->popup(tr("Map Scale: ") + QString::number(m_map->getScale()) + "\%");
}
void GameProcessor::selectPosition(QPoint position)
{
m_SEplayer->play();
switch (m_nStage) // Check stage first
{
case 0: // Select unit
{
Block *newBlock = m_map->getBlock(position);
if (newBlock == nullptr)
{
// Cannot select a "no" block
break;
}
if (!newBlock->isVisible())
{
// Cannot select an invisible block
break;
}
if (newBlock->getUnit() == nullptr)
{
// Select an empty block: pop up main context menu
m_mainContextMenu->clear();
m_mainContextMenu->addAction(m_mainActions[0]);
m_mainContextMenu->addAction(m_mainActions[1]);
m_mainContextMenu->addAction(m_mainActions[2]);
m_mainContextMenu->exec(QCursor::pos());
break;
}
if (!newBlock->getUnit()->isOperable())
{
// Cannot operate this unit
break;
}
if (!newBlock->getUnit()->getActivity())
{
// Cannot operate an inactive unit
break;
}
m_selectedBlock = newBlock;
emit enterStage(1);
break;
}
case 1: // Select moving route
{
Block *newBlock = m_map->getBlock(position);
if (newBlock == nullptr)
{
// Cannot select an empty block
break;
}
if (m_unitMover->isBusy())
{
// Cannot move now
break;
}
if (m_movingRoute.last() != newBlock)
{
// cannot go there
if (m_attackableBlocks.contains(newBlock) ||
m_capturableBlocks.contains(newBlock) ||
m_carrierBlocks.contains(newBlock))
{
// skip stage 2 & 3, move directly
m_selectedBlock = newBlock;
emit enterStage(4);
break;
}
break;
}
m_selectedBlock = m_movingRoute.last();
emit enterStage(2);
break;
}
case 2: // Cancel selection
{
emit enterStage(0);
break;
}
case 3: // Select a unit to continue
{
Block *newBlock = m_map->getBlock(position);
if (!m_attackableBlocks.contains(newBlock) &&
!m_capturableBlocks.contains(newBlock) &&
!m_carrierBlocks.contains(newBlock))
{
// Cannot operate the block
break;
}
m_selectedBlock = newBlock;
emit enterStage(4);
break;
}
case 20: // Back to game
{
m_descriptionWidget->closeWindow();
emit enterStage(0);
break;
}
// Wait: stage 2, 4, 5, 8, 11, 16, 25
}
}
void GameProcessor::mouseToPosition(QPoint position)
{
switch (m_nStage) // Check stage first
{
case 0:
{
Block *newBlock = m_map->getBlock(position);
m_cursorBlock = newBlock;
break;
}
case 1: // Select moving route
{
Block *newBlock = m_map->getBlock(position);
if (newBlock == m_cursorBlock)
{
// Cannot move to the same block
break;
}
m_cursorBlock = newBlock;
if (m_cursorBlock == nullptr)
{
// Cannot move to a "no" block
break;
}
if (m_cursorBlock->getUnit() != nullptr &&
m_cursorBlock->getUnit() != m_selectedBlock->getUnit())
{
// destination isn't empty and isn't the starting point
break;
}
int idx = m_movingRoute.indexOf(m_cursorBlock);
if (idx >= 0)
{
// block reselected: undo selection
while (m_movingRoute.size() > idx + 1)
{
int terrainId = m_movingRoute.last()->getTerrain();
int unitType = m_gameInfo->getUnitInfo()[m_selectedBlock->getUnit()->getId()][0];
int moveCost = m_gameInfo->getTerrainInfo()[terrainId][unitType];
m_nMovesLeft += moveCost;
m_movingRoute.pop_back();
}
int unitId = m_selectedBlock->getUnit()->getId();
updateOperatableBlocks(m_cursorBlock,
m_gameInfo->getUnitInfo()[unitId][2],
m_gameInfo->getUnitInfo()[unitId][3],
m_gameInfo->getUnitInfo()[unitId][7]);
updateCarrierBlocks(m_cursorBlock, m_selectedBlock->getUnit());
m_moveWidget->findChild<QLabel *>("unitMoveLabel")->setText(QString::number(m_nMovesLeft));
break;
}
QVector<Block *> v;
m_map->getAdjacentBlocks(v, m_cursorBlock);
if (!v.contains(m_movingRoute.last()))
{
// not adjacent
break;
}
int terrainId = m_cursorBlock->getTerrain();
int unitId = m_selectedBlock->getUnit()->getId();
int unitType = m_gameInfo->getUnitInfo()[unitId][0];
int moveCost = m_gameInfo->getTerrainInfo()[terrainId][unitType];
if (moveCost > m_nMovesLeft)
{
break;
}
m_nMovesLeft -= moveCost;
m_movingRoute.push_back(m_cursorBlock);
updateOperatableBlocks(m_cursorBlock,
m_gameInfo->getUnitInfo()[unitId][2],
m_gameInfo->getUnitInfo()[unitId][3],
m_gameInfo->getUnitInfo()[unitId][7]);
updateCarrierBlocks(m_cursorBlock, m_selectedBlock->getUnit());
m_moveWidget->findChild<QLabel *>("unitMoveLabel")->setText(QString::number(m_nMovesLeft));
break;
}
case 3: // Select a unit to continue
{
Block *newBlock = m_map->getBlock(position);
m_cursorBlock = newBlock;
break;
}
// Wait: stage 2, 4, 5, 8, 11, 16, 20, 25
}
}
void GameProcessor::unselectPosition(QPoint position)
{
Q_UNUSED(position);
if (m_nStage == -1)
{
emit enterStage(0);
}
}
void GameProcessor::escapeMenu(QPoint position)
{
m_SEplayer->play();
Q_UNUSED(position);
switch (m_nStage)
{
case 0:
{
// Show description
Block *newBlock = m_map->getBlock(position);
if (newBlock == nullptr)
{
// Cannot select a "no" block
break;
}
if (!newBlock->isVisible())
{
// Cannot select an invisible block
break;
}
m_descriptionWidget->setBlock(m_map->getBlock(position));
emit enterStage(20);
break;
}
case 1:
{
// Hide move widget
m_moveWidget->hide();
// Cancel selection
emit enterStage(0);
break;
}
case 2:
case 3:
{
// Cancel selection
emit enterStage(0);
break;
}
// Wait: stage 4, 5, 8, 11, 12, 16, 20, 25
}
}
<file_sep>#ifndef BLOCK_H
#define BLOCK_H
#include "unit.h"
#include <QObject>
#include <QPainter>
#include <QImage>
class Block : public QObject
{
Q_OBJECT
public:
explicit Block(int terrain, int row, int col, QObject *parent = nullptr, bool fogMode = false);
void updateArea(QPoint center, int size);
// Paint block
// @param center: the absolute position of the center
// @param size: the distance between the center and a side
void paint(QPainter *painter, int part = 0, int dynamicsId = 0) const;
void paintPointer(QPainter *painter, QImage &image) const;
// Getter and setter
void setUnit(int unit, int side, int maxHP, int innerType = 0);
void setUnit(Unit *newUnit);
void setTerrain(int terrain);
void setVisible(bool visible);
Unit *getUnit() const;
QPoint getCenter() const;
const QPolygon *getArea() const;
int getTerrain() const;
int getRow() const;
int getColumn() const;
bool isVisible() const;
// Convert Image color to gray
static QImage grayImage(const QImage *image);
private:
static QVector<QPointF> sm_pbasePoints;
// Graphics related
QPolygon m_area; // area of the block (coordinates)
QPoint m_pCenter; // center position
int m_nBlockSize; // size of the block
// Properties
int m_nTerrain; // map terrain (1~9)
QImage m_terrainImage[2]; // depict terrain
Unit *m_unit; // army unit (nullptr - nothing)
// Fog mode
bool m_bVisible; // Whether a block can be seen
int m_row;
int m_col;
};
#endif // BLOCK_H
<file_sep>#ifndef BATTLEWIDGET_H
#define BATTLEWIDGET_H
#include "block.h"
#include "gameinfo.h"
#include <QWidget>
#include <QLabel>
#include <QTimer>
namespace Ui
{
class BattleWidget;
}
class BattleWidget : public QWidget
{
Q_OBJECT
public:
explicit BattleWidget(Block *activeBlock, Block *passiveBlock,
GameInfo *gameInfo, QWidget *parent = nullptr);
~BattleWidget();
void setActiveAttack(int damage, bool killed, bool critical);
void setPassiveAttack(int damage, bool killed);
void adjustScreen();
void begin();
public slots:
void updateDynamics();
void goOnStage();
void activeAttack();
void passiveAttack();
void ending();
private:
Ui::BattleWidget *ui;
// Data
GameInfo *m_gameInfo;
// Widgets
QLabel *m_activeLabel;
QLabel *m_passiveLabel;
QLabel *m_damageLabel;
// Images
QVector<QPixmap> m_activeImages;
QVector<QPixmap> m_passiveImages;
int m_nDynamicsId = 0;
// Timer
QTimer *m_dynamicsTimer;
// Data
Block *m_activeBlock;
Block *m_passiveBlock;
int m_nActiveDamage;
int m_nPassiveDamage;
bool m_bActiveCritical;
bool m_bActiveKilled;
bool m_bPassiveKilled;
signals:
void end();
};
#endif // BATTLEWIDGET_H
<file_sep>#ifndef DESCRIPTIONWIDGET_H
#define DESCRIPTIONWIDGET_H
#include "block.h"
#include "gameinfo.h"
#include <QWidget>
#include <QLabel>
#include <QTimer>
namespace Ui
{
class DescriptionWidget;
}
class DescriptionWidget : public QWidget
{
Q_OBJECT
public:
explicit DescriptionWidget(GameInfo *gameInfo, QWidget *parent = nullptr, bool selectUnits = false);
~DescriptionWidget();
void setUnit(const Unit *unit, int terrain);
void setBlock(const Block *block);
void adjustBackground();
void updateScreen();
void closeWindow();
public slots:
void updateUnitPicture();
private:
Ui::DescriptionWidget *ui;
GameInfo *m_gameInfo;
Block *m_displayingBlock;
bool m_bSelectUnits;
QTimer *m_refreshTimer;
QLabel ***m_interunitLabels;
QLabel *m_unitPictureLabel;
QImage *m_unitImages;
int m_nDynamicsId;
};
#endif // DESCRIPTIONWIDGET_H
<file_sep>#ifndef AIPROCESSOR_H
#define AIPROCESSOR_H
#include "settings.h"
#include "gameinfo.h"
#include "map.h"
#include "gamestats.h"
#include "unitmover.h"
#include "battlewidget.h"
#include <QObject>
#include <QMediaPlayer>
class AIProcessor : public QObject
{
Q_OBJECT
public:
explicit AIProcessor(Settings *settings,
GameInfo *gameInfo,
Map *map,
GameStats *stats,
QMediaPlayer *SEplayer,
QObject *parent = nullptr,
int side = 1);
void paint(QPainter *painter);
// Inner struct, used in choosing blocks
struct BlockValue
{
Block *block;
Block *lastBlock;
Block *confrontingBlock;
int distance;
int value;
};
// Get accessible blocks from the given block
void getAccessibleBlocks(QVector<BlockValue> &accessibleBlocks, Block *block, int unitType, int movement);
// Add attack points to each accessible block
// Detail: Point is given according to the opponent unit which offers the greatest point
// (because you can only attack once in a round)
void updateAttackPoints(QVector<BlockValue> &accessibleBlocks, Unit *unit);
// Add defence points to each accessible block
// Detail: Point is given according to the terrain defence and how many enemy units around
void updateDefencePoints(QVector<BlockValue> &accessibleBlocks, Unit *unit);
// If the unit isn't able to attack, find the shortest path to an enemy unit, save it in accessible blocks
// The block with the most distance lower than movement is given a value 1000 to stand out
void updateNearbyBlocks(QVector<BlockValue> &accessibleBlocks, Block *block, int unitType, int movement);
void moveSingleUnit(Block *block);
void operateBuilding(Block *block);
void createUnit(int unitId, int side);
public slots:
void activate();
void nextMove();
void confrontUnit();
void finishRound();
private:
// Game stats
Settings *m_settings; // Game settings
GameInfo *m_gameInfo; // Game info
Map *m_map; // Game map
GameStats *m_stats; // Game stats
// Sound Effect
QMediaPlayer *m_SEplayer; // Sound effect
// Widgets
BattleWidget *m_battleWidget; // Battle Widget
// Game processers
UnitMover *m_unitMover; // Army unit mover
// AI processing related
QVector<Block *> m_remainingBlocks; // Blocks that can be moved
QVector<Block *> m_movingRoute; // Moving route
Block *m_confrontingBlock; // Confronting units
Unit *m_tempUnit; // Temporary unit used for generating units
// Other members
int m_nSide; // Side in the game
int m_nStage; // Stage of a round
signals:
void finished();
void operationFinished();
};
#endif // AIPROCESSOR_H
<file_sep>#ifndef UNITSELECTIONWIDGET_H
#define UNITSELECTIONWIDGET_H
#include "descriptionwidget.h"
#include <QWidget>
#include <QLabel>
#include <QListWidget>
namespace Ui
{
class UnitSelectionWidget;
}
class UnitSelectionWidget : public QWidget
{
Q_OBJECT
public:
explicit UnitSelectionWidget(GameInfo *gameInfo, QWidget *parent = nullptr);
~UnitSelectionWidget();
// The widget used in each list widget item
class ItemWidget : public QWidget
{
public:
explicit ItemWidget(const QString &name, int cost,
const QPixmap &image, QWidget *parent = nullptr);
public:
int m_cost;
QLabel *m_costLabel;
void setValidity(bool valid);
};
// Load all units
void loadUnits(const QStringList &unitNames, float **unitInfo);
// Show the widget to select from units of the given kind
void showUnits(int unitKind, int coins);
public slots:
void selected();
void updateButtonValidity();
void adjustSize();
private:
Ui::UnitSelectionWidget *ui;
DescriptionWidget *m_descriptionWidget;
QListWidget *m_listWidget;
QList<QListWidgetItem *> m_listWidgetItems;
GameInfo *m_gameInfo;
int m_nKind;
signals:
void confirm(int);
void cancel();
};
#endif // UNITSELECTIONWIDGET_H
<file_sep>#include "gamestats.h"
GameStats::GameStats(QObject *parent, int totalSides, int coins) :
QObject(parent), m_nTotalSides(totalSides)
{
m_nCoins = new int[m_nTotalSides]();
m_units = new QVector<Unit *>[m_nTotalSides]();
for (int i = 0; i < m_nTotalSides; i++)
{
m_nCoins[i] = coins;
}
}
int GameStats::getCoins(int side) const
{
return m_nCoins[side];
}
void GameStats::addCoins(int deltaCoins, int side)
{
m_nCoins[side] += deltaCoins;
}
const QVector<Unit *> &GameStats::getUnits(int side) const
{
return m_units[side];
}
void GameStats::addUnit(Unit *unit)
{
if (unit != nullptr)
{
m_units[unit->getSide()].push_back(unit);
}
}
void GameStats::removeUnit(Unit *unit)
{
if (unit != nullptr)
{
m_units[unit->getSide()].removeOne(unit);
}
}
<file_sep>#ifndef SETTINGS_H
#define SETTINGS_H
#include <QObject>
#include <QSize>
class Settings : public QObject
{
Q_OBJECT
public:
explicit Settings(QObject *parent = nullptr);
public:
int m_nRefreshTime; // milliseconds
int m_nMoveSteps;
QStringList m_mapNames;
QList<QSize> m_mapSizes;
int m_nCurrentMap;
int m_nBlockSize;
int m_nZoomScale;
bool m_bFogMode;
bool m_bAI;
QString m_backgroundMusic;
int m_nVolume;
int m_nSEVolume;
};
#endif // SETTINGS_H
<file_sep>#ifndef UNITMOVER_H
#define UNITMOVER_H
#include "settings.h"
#include "map.h"
#include "block.h"
#include "unit.h"
#include <QObject>
#include <QPainter>
class UnitMover : public QObject
{
Q_OBJECT
public:
explicit UnitMover(Settings *settings, Map *map, QObject *parent = nullptr);
// Paint graphics
void paint(QPainter *painter) const;
// Moving operation
void moveUnit(Block *fromBlock, Block *toBlock); // shouldn't be used
void moveUnit(QVector<Block *> &blocks); // use this
// Check state
bool isBusy() const;
public slots:
void updateSingleMovement(); // updated when screen is refreshed
void updateRouteMovement(); // updated when single step is finished
private:
// Game stats
Settings *m_settings; // Game settings
Map *m_map; // Game map
// Moving related
// Single movement (step)
int m_nTotalMoves;
int m_nCurrentMove;
bool m_bVisible;
Block *m_movingBlock[2];
// Route movement
bool m_bMoving;
Unit *m_movingUnit;
QVector<Block *> m_movingRoute;
QVector<Block *>::Iterator m_currentStep;
// Update timer
QTimer *m_refreshTimer; // WARNING: REFRESH OVERLAPPING, or add mover->updatesingle in updateall
signals:
void stepFinished();
void movementFinished(Unit *);
};
#endif // UNITMOVER_H
<file_sep>#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QFontDatabase>
#include <QIcon>
#include <QDebug>
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent),
ui(new Ui::MainWidget),
m_gameWidget(nullptr),
m_settingsWidget(nullptr),
m_gameModeWidget(nullptr),
m_nTranslatorId(1),
m_bStopped(false)
{
// Initialize translators
const QStringList uiLanguages = QLocale::system().uiLanguages();
for (const QString &locale : uiLanguages)
{
const QString baseName = "Wargroove_" + QLocale(locale).name();
if (m_translators[m_nTranslatorId].load(":/i18n/" + baseName))
{
m_nTranslatorId++;
}
}
m_nTranslatorNumber = m_nTranslatorId;
m_nTranslatorId = 0;
// Initialize theme font
int id = QFontDatabase::addApplicationFont(":/fonts/zpix.ttf");
QFont font(QFontDatabase::applicationFontFamilies(id).at(0), 14, QFont::Bold);
QApplication::setFont(font);
qDebug() << "Font initialize:" << id << QFontDatabase::applicationFontFamilies(id).at(0);
// Initialize cursor
QPixmap pixmap(":/pointer");
QCursor cursor(pixmap);
setCursor(cursor);
// Initialize ui
ui->setupUi(this);
setWindowIcon(QIcon(":/Wargroove.png"));
// Initialize background
setAttribute(Qt::WA_StyledBackground, true);
QPalette palette;
palette.setBrush(backgroundRole(), QBrush(QImage(":/wargroove-bg.png").scaled(size(),
Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)));
setPalette(palette);
// Initialize game settings
m_settings = new Settings(this);
// Initialize background music
m_bgMusic = new QMediaPlayer(this);
m_bgMusic->setMedia(QUrl("./music/bgm01.mp3"));
m_bgMusic->setVolume(m_settings->m_nVolume);
m_bgMusic->play();
// Connect signals to slots
connect(ui->playButton, &QPushButton::clicked, this, &MainWidget::showGameMode);
connect(ui->settingsButton, &QPushButton::clicked, this, &MainWidget::showSettings);
connect(ui->languageButton, &QPushButton::clicked, this, &MainWidget::retranslate);
connect(ui->exitButton, &QPushButton::clicked, this, &MainWidget::close);
connect(m_bgMusic, &QMediaPlayer::stateChanged, this, &MainWidget::resetMedia);
}
MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
// Initialize background
setAttribute(Qt::WA_StyledBackground, true);
QPalette palette;
palette.setBrush(backgroundRole(), QBrush(QImage(":/wargroove-bg.png").scaled(size(),
Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)));
setPalette(palette);
}
void MainWidget::retranslate()
{
m_nTranslatorId++;
if (m_nTranslatorId >= m_nTranslatorNumber)
{
m_nTranslatorId = 0;
}
if (m_nTranslatorId == 0)
{
QApplication::removeTranslator(m_translators + m_nTranslatorNumber - 1);
}
else
{
QApplication::installTranslator(m_translators + m_nTranslatorId);
}
ui->retranslateUi(this);
}
void MainWidget::showGame()
{
qDebug() << m_settings->m_bAI;
m_gameWidget = new GameWidget(m_settings, this);
connect(m_gameWidget, &GameWidget::windowClosed, this, &MainWidget::returnToMenu);
ui->menuWidget->hide();
ui->mainLayout->addWidget(m_gameWidget);
m_gameWidget->show();
m_bStopped = true;
m_bgMusic->stop();
}
void MainWidget::showGameMode()
{
m_gameModeWidget = new GameModeWidget(m_settings, this);
m_gameModeWidget->setAttribute(Qt::WA_DeleteOnClose, true);
connect(m_gameModeWidget, &GameModeWidget::windowClosed, this, &MainWidget::returnToMenu);
connect(m_gameModeWidget, &GameModeWidget::startGame, this, &MainWidget::showGame);
ui->menuWidget->hide();
ui->mainLayout->addWidget(m_gameModeWidget);
m_gameModeWidget->show();
}
void MainWidget::showSettings()
{
m_settingsWidget = new SettingsWidget(m_settings, this);
m_settingsWidget->setAttribute(Qt::WA_DeleteOnClose, true);
connect(m_settingsWidget, &SettingsWidget::windowClosed, this, &MainWidget::returnToMenu);
ui->menuWidget->hide();
ui->mainLayout->addWidget(m_settingsWidget);
m_settingsWidget->show();
}
void MainWidget::returnToMenu()
{
m_bStopped = false;
if (m_bgMusic->state() == QMediaPlayer::StoppedState)
{
m_bgMusic->play();
}
ui->menuWidget->show();
}
void MainWidget::resetMedia(QMediaPlayer::State newState)
{
if (!m_bStopped && newState == QMediaPlayer::StoppedState)
{
m_bgMusic->play();
}
}
void MainWidget::setMediaVolume(int volume)
{
m_bgMusic->setVolume(volume);
}
<file_sep>#include "settingswidget.h"
#include "ui_settingswidget.h"
#include "mainwidget.h"
#include <QPushButton>
SettingsWidget::SettingsWidget(Settings *settings, QWidget *parent) :
QWidget(parent),
ui(new Ui::SettingsWidget),
m_settings(settings)
{
// Initialize ui
ui->setupUi(this);
// Connect signals and slots
connect(ui->backButton, &QPushButton::clicked, this, &SettingsWidget::close);
connect(ui->volumeSlider, &QSlider::valueChanged, this, [ = ](int value)
{
ui->volumeLabel->setText(QString::number(value));
});
connect(ui->volumeSlider, &QSlider::valueChanged, this, [ = ](int value)
{
m_settings->m_nVolume = value;
});
connect(ui->volumeSlider, &QSlider::valueChanged, this, [ = ](int value)
{
static_cast<MainWidget *>(parent)->setMediaVolume(value);
});
connect(ui->SEvolumeSlider, &QSlider::valueChanged, this, [ = ](int value)
{
ui->SEvolumeLabel->setText(QString::number(value));
});
connect(ui->SEvolumeSlider, &QSlider::valueChanged, this, [ = ](int value)
{
m_settings->m_nSEVolume = value;
});
connect(ui->refreshSlider, &QSlider::valueChanged, this, [ = ](int value)
{
ui->refreshLabel->setText(QString::number(value));
});
connect(ui->refreshSlider, &QSlider::valueChanged, this, [ = ](int value)
{
m_settings->m_nRefreshTime = value;
});
connect(ui->blockSlider, &QSlider::valueChanged, this, [ = ](int value)
{
ui->blockLabel->setText(QString::number(value));
});
connect(ui->blockSlider, &QSlider::valueChanged, this, [ = ](int value)
{
m_settings->m_nBlockSize = value;
});
// Initial values
ui->volumeSlider->setValue(m_settings->m_nVolume);
ui->SEvolumeSlider->setValue(m_settings->m_nSEVolume);
ui->refreshSlider->setValue(m_settings->m_nRefreshTime);
ui->blockSlider->setValue(m_settings->m_nBlockSize);
}
SettingsWidget::~SettingsWidget()
{
delete ui;
}
void SettingsWidget::closeEvent(QCloseEvent *event)
{
emit windowClosed();
QWidget::closeEvent(event);
}
void SettingsWidget::changeMap(int index)
{
m_settings->m_nCurrentMap = index;
}
<file_sep>#ifndef MAINWIDGET_H
#define MAINWIDGET_H
#include "gamewidget.h"
#include "settingswidget.h"
#include "gamemodewidget.h"
#include <QWidget>
#include <QPushButton>
#include <QTranslator>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWidget; }
QT_END_NAMESPACE
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget(QWidget *parent = nullptr);
~MainWidget();
virtual void resizeEvent(QResizeEvent *event);
public slots:
void retranslate();
void showGame();
void showGameMode();
void showSettings();
void returnToMenu();
void resetMedia(QMediaPlayer::State);
void setMediaVolume(int);
private:
Ui::MainWidget *ui;
GameWidget *m_gameWidget;
SettingsWidget *m_settingsWidget;
GameModeWidget *m_gameModeWidget;
QPushButton *m_pushButton_1;
QPushButton *m_pushButton_2;
QTranslator m_translators[5];
int m_nTranslatorId;
int m_nTranslatorNumber;
QMediaPlayer *m_bgMusic;
bool m_bStopped;
// Game settings
Settings *m_settings;
};
#endif // MAINWIDGET_H
<file_sep>#include "gamemodewidget.h"
#include "ui_gamemodewidget.h"
GameModeWidget::GameModeWidget(Settings *settings, QWidget *parent) :
QWidget(parent),
ui(new Ui::GameModeWidget),
m_settings(settings)
{
// Initialize ui
ui->setupUi(this);
// Initialize checkbox
ui->fogCheckBox->setChecked(m_settings->m_bFogMode);
// Initialize menu
for (const auto &mapName : qAsConst(m_settings->m_mapNames))
{
ui->mapComboBox->addItem(mapName);
}
ui->mapComboBox->setCurrentIndex(m_settings->m_nCurrentMap);
// Connect signals and slots
connect(ui->fogCheckBox, &QCheckBox::stateChanged, this, [ = ]()
{
m_settings->m_bFogMode = ui->fogCheckBox->isChecked();
});
connect(ui->singlePlayerButton, &QPushButton::clicked, this, [ = ]()
{
m_settings->m_bAI = true;
emit startGame();
close();
});
connect(ui->multiplayerButton, &QPushButton::clicked, this, [ = ]()
{
m_settings->m_bAI = false;
emit startGame();
close();
});
connect(ui->backButton, &QPushButton::clicked, this, [ = ]()
{
emit windowClosed();
close();
});
connect(ui->mapComboBox, SIGNAL(currentIndexChanged(int)), SLOT(changeMap(int)));
}
GameModeWidget::~GameModeWidget()
{
delete ui;
}
void GameModeWidget::changeMap(int index)
{
m_settings->m_nCurrentMap = index;
}
<file_sep>#include "gameinfo.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
GameInfo::GameInfo(QObject *parent)
: QObject(parent),
m_nTerrainNumber(9),
m_nUnitType(5),
m_nUnitNumber(21)
{
// Initialize names
m_sUnitNames = QStringList
{
tr("Soldier"), // 0
tr("Dog"), // 1
tr("Spearman"), // 2
tr("Mage"), // 3
tr("Archer"), // 4
tr("Giant"), // 5
tr("Cavalry"), // 6
tr("Wagon"), // 7
tr("Ballista"), // 8
tr("Trebuchet"), // 9
tr("Balloon"), // 10
tr("Aeronaut"), // 11
tr("Sky Rider"), // 12
tr("Dragon"), // 13
tr("Barge"), // 14
tr("Turtle"), // 15
tr("Harpoon Ship"), // 16
tr("Warship") // 17
};
m_sCommanderNames = QStringList
{
tr("Mercia"), // 18_1
tr("Emeric"), // 18_2
tr("Caesar"), // 18_3
tr("Sigrid"), // 18_1
tr("Valder"), // 18_2
tr("Ragna") // 18_3
};
m_sBuildingNames = QStringList
{
tr("Stronghold"), // 19_0
tr("Barrack"), // 19_1
tr("Tower"), // 19_2
tr("Port"), // 19_3
tr("Village"), // 19_4
tr("Water Village") // 19_5
};
m_sTerrainNames = QStringList
{
tr("Air"), // 0
tr("Road"), // 1
tr("Plain"), // 2
tr("Forest"), // 3
tr("Mountain"), // 4
tr("Beach"), // 5
tr("Shallow Sea"), // 6
tr("Deep Sea"), // 7
tr("Bridge"), // 8
tr("Reef") // 9
};
// Initialize descriptions
m_sUnitDescription = QStringList
{
tr("Basic infantry, useful for capturing structures."),
tr("A quick unit."),
tr("Slower, more powerful infantry."),
tr("A powerful unit built to combat air threats."),
tr("Ranged ground units able to move and attack in the same turn."),
tr("An immensely powerful unit, especially during critical hits."),
tr("Powerful, mobile ground unit."),
tr("Capable of quickly transporting units that would otherwise travel by foot."),
tr("Ranged ground to air unit, unable to move and attack in the same turn."),
tr("Powerful long range unit, unable to move and attack in the same turn."),
tr("Aircraft able to transport all ground units."),
tr("Immensely mobile units, useful for crossing enemy lines."),
tr("Air-to-air unit, able to create huge damage during critical hits."),
tr("Incredibly powerful air-to-ground unit, especially during critical hits."),
tr("Boats able to transport all ground units across water."),
tr("Powerful naval unit, built to conquer the water."),
tr("Ranged water unit, able to attack air and sea."),
tr("An immensely powerful long range unit.")
};
m_sCommanderDescription = QStringList
{
tr("Most powerful ground unit type. Having no commanders may result in a loss.")
};
m_sBuildingDescription = QStringList
{
tr("Special buildings which cannot be captured. Losing it may result in a loss."),
tr("Produces Land Units."),
tr("Produces Air Units."),
tr("Produces Naval Units."),
tr("The primary building type, able to generate income for players."),
tr("Functionally identical to Villages, but are positioned within water tiles.")
};
// Initialize terrain info
m_terrainInfo = new int *[m_nTerrainNumber + 1];
for (int i = 0; i <= m_nTerrainNumber; i++)
{
m_terrainInfo[i] = new int[m_nUnitType + 2];
}
// Initialize unit info
m_unitInfo = new float *[m_nUnitNumber];
for (int i = 0; i < m_nUnitNumber; i++)
{
m_unitInfo[i] = new float[12];
}
// Initialize unit info
m_damageMatrix = new float *[m_nUnitNumber];
for (int i = 0; i < m_nUnitNumber; i++)
{
m_damageMatrix[i] = new float[m_nUnitNumber];
}
loadFile();
}
GameInfo::~GameInfo()
{
for (int i = 0; i <= m_nTerrainNumber; i++)
{
delete m_terrainInfo[i];
}
for (int i = 0; i < m_nUnitNumber; i++)
{
delete m_unitInfo[i];
delete m_damageMatrix[i];
}
delete m_terrainInfo;
delete m_unitInfo;
delete m_damageMatrix;
}
void GameInfo::loadFile()
{
// Terrain info
QFile data(":/gameinfo/gameinfo/terrain_info.txt");
if (!data.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&data);
QStringList sizeStr = in.readLine().split(" ");
if (sizeStr[0].toInt() != m_nTerrainNumber || sizeStr[1].toInt() != m_nUnitType)
{
qDebug() << "Size doesn't match";
return;
}
for (int i = 1; i <= m_nTerrainNumber; i++)
{
QStringList rowStr = in.readLine().simplified().split(" ");
for (int j = 1; j <= m_nUnitType + 2; j++)
{
if (j >= rowStr.size())
{
qDebug() << "Map incomplete";
break;
}
m_terrainInfo[i][j - 1] = rowStr[j].toInt();
}
}
data.close();
// Unit info
data.setFileName(":/gameinfo/gameinfo/unit_info.txt");
if (!data.open(QIODevice::ReadOnly | QIODevice::Text))
return;
in.setDevice(&data);
sizeStr = in.readLine().split(" ");
if (sizeStr[0].toInt() != m_nUnitNumber)
{
qDebug() << "Size doesn't match";
return;
}
for (int i = 0; i < m_nUnitNumber; i++)
{
QStringList rowStr = in.readLine().simplified().split(" ");
for (int j = 1; j <= 12; j++)
{
if (j >= rowStr.size())
{
qDebug() << "Map incomplete";
break;
}
m_unitInfo[i][j - 1] = rowStr[j].toFloat();
}
}
data.close();
// Damage matrix
data.setFileName(":/gameinfo/gameinfo/damage_matrix.txt");
if (!data.open(QIODevice::ReadOnly | QIODevice::Text))
return;
in.setDevice(&data);
sizeStr = in.readLine().split(" ");
if (sizeStr[0].toInt() != m_nUnitNumber)
{
qDebug() << "Size doesn't match";
return;
}
for (int i = 0; i < m_nUnitNumber; i++)
{
QStringList rowStr = in.readLine().simplified().split(" ");
for (int j = 1; j <= m_nUnitNumber; j++)
{
if (j >= rowStr.size())
{
qDebug() << "Map incomplete";
break;
}
m_damageMatrix[i][j - 1] = rowStr[j].toFloat();
}
}
data.close();
qDebug() << "Game Info loaded";
}
int **GameInfo::getTerrainInfo() const
{
return m_terrainInfo;
}
float **GameInfo::getUnitInfo() const
{
return m_unitInfo;
}
float **GameInfo::getDamageMatrix() const
{
return m_damageMatrix;
}
const QStringList &GameInfo::getUnitNames() const
{
return m_sUnitNames;
}
const QStringList &GameInfo::getCommanderNames() const
{
return m_sCommanderNames;
}
const QStringList &GameInfo::getBuildingNames() const
{
return m_sBuildingNames;
}
const QStringList &GameInfo::getTerrainNames() const
{
return m_sTerrainNames;
}
const QStringList &GameInfo::getUnitDescription() const
{
return m_sUnitDescription;
}
const QStringList &GameInfo::getCommanderDescription() const
{
return m_sCommanderDescription;
}
const QStringList &GameInfo::getBuildingDescription() const
{
return m_sBuildingDescription;
}
<file_sep>#include "descriptionwidget.h"
#include "ui_descriptionwidget.h"
#include <QDebug>
DescriptionWidget::DescriptionWidget(GameInfo *gameInfo, QWidget *parent, bool selectUnits)
: QWidget(parent),
ui(new Ui::DescriptionWidget),
m_gameInfo(gameInfo),
m_bSelectUnits(selectUnits),
m_nDynamicsId(0)
{
ui->setupUi(this);
setAttribute(Qt::WA_StyledBackground, true);
ui->widget->setAttribute(Qt::WA_StyledBackground, true);
if (m_bSelectUnits)
{
ui->terrainMainWidget->hide();
}
hide();
m_displayingBlock = new Block(1, 0, 0, this);
m_unitPictureLabel = ui->unitPictureLabel;
m_unitImages = new QImage[2]();
ui->interunitsLayout->setColumnStretch(0, 2);
m_interunitLabels = new QLabel **[3];
for (int i = 0; i < 3; i++)
{
m_interunitLabels[i] = new QLabel *[7];
for (int j = 0; j < 7; j++)
{
m_interunitLabels[i][j] = new QLabel(this);
m_interunitLabels[i][j]->setFixedSize(33, 33);
m_interunitLabels[i][j]->setPixmap(QPixmap());
ui->interunitsLayout->addWidget(m_interunitLabels[i][j], i + 1, j + 1);
ui->interunitsLayout->setColumnStretch(j + 1, 1);
}
}
// Initialize timers
m_refreshTimer = new QTimer(this);
connect(m_refreshTimer, &QTimer::timeout, this, &DescriptionWidget::updateUnitPicture);
}
DescriptionWidget::~DescriptionWidget()
{
delete ui;
}
void DescriptionWidget::setUnit(const Unit *unit, int terrain)
{
m_displayingBlock->setTerrain(terrain);
if (m_displayingBlock->getUnit() != nullptr)
{
delete m_displayingBlock->getUnit();
}
if (unit != nullptr)
{
// Copy a unit
m_displayingBlock->setUnit(unit->getId(), unit->getSide(),
m_gameInfo->getUnitInfo()[unit->getId()][6],
unit->getInnerType());
m_nDynamicsId = 0;
}
else
{
m_displayingBlock->setUnit(nullptr);
}
updateScreen();
adjustBackground();
show();
m_refreshTimer->start(300);
}
void DescriptionWidget::setBlock(const Block *block)
{
setUnit(block->getUnit(), block->getTerrain());
}
void DescriptionWidget::adjustBackground()
{
// Initial visible condition
bool visible = isVisible();
if (!m_bSelectUnits)
{
// Reset size
int parentWidth = static_cast<QWidget *>(parent())->width();
int parentHeight = static_cast<QWidget *>(parent())->height();
setGeometry(parentWidth / 2 - 500, parentHeight / 2 - 350, 1000, 700);
}
if (m_displayingBlock->getUnit() != nullptr)
{
m_unitPictureLabel->setPixmap(QPixmap::fromImage(m_unitImages[m_nDynamicsId].scaledToHeight(ui->widget->height() / 3)));
}
// show() has to be before loading background ?
show();
// Reload background picture
QImage img;
Unit *unit = m_displayingBlock->getUnit();
if (unit != nullptr)
{
int unitId = unit->getId();
if (unitId >= 10 && unitId <= 13)
{
// Air unit
img = QImage(":/image/background/0");
}
else
{
img = QImage(":/image/background/" + QString::number(m_displayingBlock->getTerrain()));
}
}
else
{
img = QImage(":/image/background/" + QString::number(m_displayingBlock->getTerrain()));
}
// Set background picture
QWidget *displayWidget = ui->widget;
QPalette palette = displayWidget->palette();
palette.setBrush(displayWidget->backgroundRole(),
QBrush(img.scaled(displayWidget->size(),
Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)));
displayWidget->setPalette(palette);
// Return to initial condition
setVisible(visible);
}
void DescriptionWidget::updateScreen()
{
if (!m_bSelectUnits)
{
// Terrain info
int **terrainInfo = m_gameInfo->getTerrainInfo();
int terrain = m_displayingBlock->getTerrain();
ui->moveLabel1->setText(terrainInfo[terrain][0] < 10 ? QString::number(terrainInfo[terrain][0]) : "-");
ui->moveLabel2->setText(terrainInfo[terrain][1] < 10 ? QString::number(terrainInfo[terrain][1]) : "-");
ui->moveLabel3->setText(terrainInfo[terrain][2] < 10 ? QString::number(terrainInfo[terrain][2]) : "-");
ui->moveLabel4->setText(terrainInfo[terrain][3] < 10 ? QString::number(terrainInfo[terrain][3]) : "-");
ui->moveLabel5->setText(terrainInfo[terrain][4] < 10 ? QString::number(terrainInfo[terrain][4]) : "-");
ui->defenceLabel->setText(QString::number(terrainInfo[terrain][5]));
ui->terrainLabel->setText(m_gameInfo->getTerrainNames()[terrain]);
}
// Unit info
Unit *unit = m_displayingBlock->getUnit();
if (unit != nullptr)
{
// Relative game data
int unitId = unit->getId();
float **unitInfo = m_gameInfo->getUnitInfo();
// Set unit names
ui->unitNameLabel->show();
if (unitId < 18)
{
// ordinary units
ui->unitNameLabel->setText(m_gameInfo->getUnitNames()[unitId]);
}
else if (unitId == 18)
{
// commander
ui->unitNameLabel->setText(m_gameInfo->getCommanderNames()[3 * unit->getSide() + unit->getInnerType()]);
}
else
{
// building
ui->unitNameLabel->setText(m_gameInfo->getBuildingNames()[unit->getInnerType()]);
}
// Set unit icon
ui->unitIconLabel->show();
ui->unitIconLabel->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(unitId)));
// Set unit picture
QVector<QImage> v;
unit->getImages(&v);
for (int i = 0; i < 2; i++)
{
m_unitImages[i] = v[i];
}
m_unitPictureLabel->show();
m_unitPictureLabel->setPixmap(QPixmap::fromImage(m_unitImages[m_nDynamicsId].scaledToHeight(ui->widget->height() / 3)));
// Set battle data
ui->unitBattleDataWidget->show();
ui->attackLabel->setText(QString::number(unitInfo[unitId][5]));
ui->maxHPLabel->setText(QString::number(unit->getMaxHP()));
// Set unit data widget
ui->unitDataWidget->show();
// Set moving type and costs
ui->moveTypeLabel->setPixmap(QPixmap(":/image/move_icon/" + QString::number(unitInfo[unitId][0])));
ui->moveLabel->setText(QString::number(unitInfo[unitId][1]));
// Set range
int rangeLow = unitInfo[unitId][2];
int rangeHigh = unitInfo[unitId][3];
if (rangeLow == rangeHigh)
{
ui->rangeLabel->setText(QString::number(rangeLow));
}
else
{
ui->rangeLabel->setText(QString("%1-%2").arg(rangeLow).arg(rangeHigh));
}
// Set sight
ui->sightLabel->setText(QString::number(unitInfo[unitId][4]));
// Set description
ui->descriptionLabel->show();
if (unitId < 18)
{
// ordinary units
ui->descriptionLabel->setText(m_gameInfo->getUnitDescription()[unitId]);
}
else if (unitId == 18)
{
// commander
ui->descriptionLabel->setText(m_gameInfo->getCommanderDescription()[0]);
}
else
{
// building
ui->descriptionLabel->setText(m_gameInfo->getBuildingDescription()[unit->getInnerType()]);
}
// Set effective and vulnerable box
float **damageMatrix = m_gameInfo->getDamageMatrix();
// Effective units
int effIndex = 0;
for (int i = 0; i < 20; i++)
{
if (effIndex >= 7)
{
break;
}
if (damageMatrix[unitId][i] > 1.4)
{
m_interunitLabels[0][effIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[0][effIndex]->setStyleSheet("background-color: #20918b;");
effIndex++;
}
}
for (int i = 0; i < 20; i++)
{
if (effIndex >= 7)
{
break;
}
if (damageMatrix[unitId][i] < 1.4 && damageMatrix[unitId][i] > 1.0)
{
m_interunitLabels[0][effIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[0][effIndex]->setStyleSheet("background-color: #335eb0;");
effIndex++;
}
}
for (; effIndex < 7; effIndex++)
{
m_interunitLabels[0][effIndex]->setPixmap(QPixmap());
m_interunitLabels[0][effIndex]->setStyleSheet("");
}
// Void units
int voidIndex = 0;
for (int i = 0; i < 20; i++)
{
if (voidIndex >= 7)
{
break;
}
if (damageMatrix[unitId][i] < 0.4)
{
m_interunitLabels[1][voidIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[1][voidIndex]->setStyleSheet("background-color: #a4802b;");
voidIndex++;
}
}
for (int i = 0; i < 20; i++)
{
if (voidIndex >= 7)
{
break;
}
if (damageMatrix[unitId][i] > 0.4 && damageMatrix[unitId][i] < 0.7)
{
m_interunitLabels[1][voidIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[1][voidIndex]->setStyleSheet("background-color: #eac282;");
voidIndex++;
}
}
for (; voidIndex < 7; voidIndex++)
{
m_interunitLabels[1][voidIndex]->setPixmap(QPixmap());
m_interunitLabels[1][voidIndex]->setStyleSheet("");
}
// Vulnerable units
int vulIndex = 0;
for (int i = 0; i < 20; i++)
{
if (vulIndex >= 7)
{
break;
}
if (damageMatrix[i][unitId] > 1.4)
{
m_interunitLabels[2][vulIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[2][vulIndex]->setStyleSheet("background-color: #aa003f;");
vulIndex++;
}
}
for (int i = 0; i < 20; i++)
{
if (vulIndex >= 7)
{
break;
}
if (damageMatrix[i][unitId] < 1.4 && damageMatrix[i][unitId] > 1.0)
{
m_interunitLabels[2][vulIndex]->setPixmap(QPixmap(":/image/unit_icon/" + QString::number(i)));
m_interunitLabels[2][vulIndex]->setStyleSheet("background-color: #cd4c18;");
vulIndex++;
}
}
for (; vulIndex < 7; vulIndex++)
{
m_interunitLabels[2][vulIndex]->setPixmap(QPixmap());
m_interunitLabels[2][vulIndex]->setStyleSheet("");
}
ui->interunitsWidget->show();
}
else
{
ui->unitNameLabel->hide();
ui->unitIconLabel->hide();
ui->unitBattleDataWidget->hide();
ui->unitDataWidget->hide();
ui->descriptionLabel->hide();
m_unitPictureLabel->hide();
ui->interunitsWidget->hide();
}
}
void DescriptionWidget::closeWindow()
{
hide();
m_refreshTimer->stop();
}
void DescriptionWidget::updateUnitPicture()
{
if (m_displayingBlock->getUnit() != nullptr)
{
m_nDynamicsId = 1 - m_nDynamicsId;
m_unitPictureLabel->setPixmap(QPixmap::fromImage(m_unitImages[m_nDynamicsId].scaledToHeight(ui->widget->height() / 3)));
}
}
<file_sep>#ifndef GAMEWIDGET_H
#define GAMEWIDGET_H
#include "map.h"
#include "settings.h"
#include "gameinfo.h"
#include "gamestats.h"
#include "unitmover.h"
#include "gameprocessor.h"
#include "aiprocessor.h"
#include "tipslabel.h"
#include "unitselectionwidget.h"
#include "descriptionwidget.h"
#include <QWidget>
#include <QTimer>
#include <QtMultimedia/QMediaPlayer>
namespace Ui
{
class GameWidget;
}
class GameWidget : public QWidget
{
Q_OBJECT
public:
explicit GameWidget(Settings *settings, QWidget *parent = nullptr);
~GameWidget();
virtual void paintEvent(QPaintEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
virtual void wheelEvent(QWheelEvent *event);
virtual void resizeEvent(QResizeEvent *event);
virtual void closeEvent(QCloseEvent *event);
public slots:
void updateAll();
void resetMedia(QMediaPlayer::State);
void initializeSide(int);
private:
Ui::GameWidget *ui;
// Game data objects
Settings *m_settings; // Game settings
GameInfo *m_gameInfo; // Game info
Map *m_map; // Game map
GameStats *m_stats; // Game stats
// Game widgets
TipsLabel *m_tipsLabel; // Label at the bottom of the screen
UnitSelectionWidget *m_unitSelectionWidget; // Unit selection widget
DescriptionWidget *m_descriptionWidget; // Block discription widget
QMenu *m_actionContextMenu; // Action context menu
QMenu *m_mainContextMenu; // Main context menu
// Game engine
GameProcessor *m_processor; // Game processor
AIProcessor **m_ai; // Game AI Processors
// Sound effects
QMediaPlayer *m_mediaPlayer; // bgm player
QMediaPlayer *m_SEPlayer; // sound effect player
bool m_bClosing; // closing the widget
// Mouse events related
QPoint m_pDragBeginPoint; // Start point of dragging
bool m_bMouseEventConnected; // Whether mouse events are received
// Timer
QTimer *m_graphicsTimer; // Timer: update screen graphics
QTimer *m_dynamicsTimer; // Timer: update unit dynamics
signals:
void mouseLeftButtonClicked(QPoint);
void mouseLeftButtonReleased(QPoint);
void mouseRightButtonClicked(QPoint);
void mouseMiddleButtonClicked(QPoint);
void mouseMiddleButtonMoved(QPoint);
void mouseMoved(QPoint);
void mouseScrolled(int, QPointF);
void AIFinished();
void windowClosed();
};
#endif // GAMEWIDGET_H
<file_sep># Wargroove
An extension for wargroove game.
<file_sep>#ifndef GAMEMODEWIDGET_H
#define GAMEMODEWIDGET_H
#include "settings.h"
#include <QWidget>
namespace Ui
{
class GameModeWidget;
}
class GameModeWidget : public QWidget
{
Q_OBJECT
public:
explicit GameModeWidget(Settings *settings, QWidget *parent = nullptr);
~GameModeWidget();
public slots:
void changeMap(int index);
private:
Ui::GameModeWidget *ui;
Settings *m_settings;
signals:
void windowClosed();
void startGame();
};
#endif // GAMEMODEWIDGET_H
<file_sep>#include "unit.h"
#include <QRandomGenerator>
#include <QDebug>
QImage Unit::grayImage(const QImage *image)
{
QImage img(*image);
for (int i = 0; i < img.width(); ++i)
{
for (int j = 0; j < img.height(); ++j)
{
QColor color = img.pixelColor(i, j);
int gray = qGray(color.rgb());
int alpha = color.alpha();
img.setPixelColor(i, j, QColor(gray, gray, gray, alpha));
}
}
return img;
}
Unit::Unit(int unitId, int side, int maxHP, QObject *parent, int innerType, float HPPercentage)
: QObject(parent),
m_nId(unitId),
m_nInnerType(innerType),
m_nSide(side),
m_nDirection(0),
m_bActive(true),
m_carryingUnit(nullptr),
m_nMaxHealthPoint(maxHP)
{
m_nHealthPoint = m_nMaxHealthPoint * HPPercentage;
if (m_nId <= 18)
{
QString imgFileName(":/image/");
if (side == 0)
{
imgFileName += "unit/";
}
else if (side == 1)
{
imgFileName += "enemy_unit/";
}
imgFileName += QString::number(m_nId);
if (unitId == 18)
{
imgFileName += ("_" + QString::number(m_nInnerType));
}
QImage img(imgFileName);
int w = img.width();
int h = img.height() / 2;
m_images[0] = img.copy(0, 0, w, h);
m_images[1] = img.copy(0, h, w, img.height() / 2);
m_images[2] = m_images[0].mirrored(true, false);
m_images[3] = m_images[1].mirrored(true, false);
}
}
void Unit::paint(QPainter *painter, const QRect &rect, int dynamicsId, int side) const
{
Q_UNUSED(side);
if (m_bActive)
{
painter->drawImage(rect, m_images[2 * m_nDirection + dynamicsId]);
}
else
{
painter->drawImage(rect, grayImage(m_images + 2 * m_nDirection + dynamicsId));
}
if (m_nHealthPoint < m_nMaxHealthPoint)
{
painter->drawRect(rect.center().x() - 3, rect.center().y() - 17, 15, 20);
painter->drawText(rect.center(), QString::number(m_nHealthPoint * 10 / m_nMaxHealthPoint));
}
}
int Unit::getId() const
{
return m_nId;
}
int Unit::getInnerType() const
{
return m_nInnerType;
}
int Unit::getSide() const
{
return m_nSide;
}
bool Unit::getActivity() const
{
return m_bActive;
}
int Unit::getHP() const
{
return m_nHealthPoint;
}
int Unit::getMaxHP() const
{
return m_nMaxHealthPoint;
}
float Unit::getHPPercentage() const
{
return m_nHealthPoint * 1.0 / m_nMaxHealthPoint;
}
Unit *Unit::getCarrier() const
{
return m_carryingUnit;
}
void Unit::getImages(QVector<QImage> *images) const
{
images->clear();
images->push_back(m_images[0]);
images->push_back(m_images[1]);
}
bool Unit::isOperable() const
{
return m_nId <= 18 && m_nId >= 0;
}
bool Unit::isCarrier() const
{
return m_nId == 7 || m_nId == 10 || m_nId == 14;
}
void Unit::setDirection(int direction)
{
if (direction > 0)
{
m_nDirection = 1;
}
else
{
m_nDirection = 0;
}
}
void Unit::setActivity(bool active)
{
m_bActive = active;
}
void Unit::setCarrier(Unit *unit)
{
m_carryingUnit = unit;
}
bool Unit::injured(int damage)
{
m_nHealthPoint -= damage;
if (m_nHealthPoint <= 0)
{
m_nHealthPoint = 0;
}
qDebug() << m_nId << "injured" << damage << "remaining" << m_nHealthPoint;
return m_nHealthPoint <= 0;
}
bool Unit::checkCritical() const
{
int randomN = std::rand() % 10;
return randomN < 2;
}
void Unit::regenerate(double ratio)
{
m_nHealthPoint += (ratio * m_nMaxHealthPoint);
if (m_nHealthPoint > m_nMaxHealthPoint)
{
m_nHealthPoint = m_nMaxHealthPoint;
}
}
<file_sep>#include "block.h"
#include "building.h"
QVector<QPointF> Block::sm_pbasePoints =
{
QPointF(-1, -0.6),
QPointF(0, -1.2),
QPointF(1, -0.6),
QPointF(1, 0.6),
QPointF(0, 1.2),
QPointF(-1, 0.6)
};
QImage Block::grayImage(const QImage *image)
{
QImage img(*image);
for (int i = 0; i < img.width(); ++i)
{
for (int j = 0; j < img.height(); ++j)
{
QColor color = img.pixelColor(i, j);
int gray = qGray(color.rgb());
int alpha = color.alpha();
img.setPixelColor(i, j, QColor(gray, gray, gray, alpha));
}
}
return img;
}
Block::Block(int terrain, int row, int col, QObject *parent, bool fogMode)
: QObject(parent),
m_area(),
m_pCenter(),
m_nBlockSize(0),
m_nTerrain(terrain),
m_unit(nullptr),
m_bVisible(!fogMode),
m_row(row),
m_col(col)
{
m_terrainImage[0] = QImage(":/image/terrain/" + QString::number(m_nTerrain));
m_terrainImage[1] = grayImage(m_terrainImage);
}
void Block::updateArea(QPoint center, int size)
{
m_pCenter = center;
m_nBlockSize = size;
QVector<QPoint> points;
for (QPointF &point : sm_pbasePoints)
{
points.push_back((point * size + center).toPoint());
}
m_area = QPolygon(points);
}
void Block::paint(QPainter *painter, int part, int dynamicsId) const
{
if (part != 2)
{
if (m_bVisible)
{
painter->drawImage(QRect(m_pCenter - QPoint(m_nBlockSize, 1.25 * m_nBlockSize),
m_pCenter + QPoint(m_nBlockSize, 1.25 * m_nBlockSize)),
m_terrainImage[0]);
}
else
{
painter->drawImage(QRect(m_pCenter - QPoint(m_nBlockSize, 1.25 * m_nBlockSize),
m_pCenter + QPoint(m_nBlockSize, 1.25 * m_nBlockSize)),
m_terrainImage[1]);
}
painter->setPen(QPen(QColor(0, 0, 0, 20), 3));
painter->drawConvexPolygon(m_area);
}
if (part != 1 && m_unit != nullptr)
{
painter->setPen(Qt::white);
painter->setBrush(Qt::black);
if (m_unit->getId() == 19 && !m_bVisible)
{
// draw nobody-owned building
m_unit->paint(painter,
QRect(m_pCenter - QPoint(m_nBlockSize, 1.5 * m_nBlockSize),
m_pCenter + QPoint(m_nBlockSize, 0.5 * m_nBlockSize)),
dynamicsId, -1);
}
else if (m_bVisible)
{
m_unit->paint(painter,
QRect(m_pCenter - QPoint(m_nBlockSize, 1.5 * m_nBlockSize),
m_pCenter + QPoint(m_nBlockSize, 0.5 * m_nBlockSize)),
dynamicsId);
}
}
}
void Block::paintPointer(QPainter *painter, QImage &image) const
{
painter->drawImage(QRect(m_pCenter - QPoint(m_nBlockSize, 1.2 * m_nBlockSize),
m_pCenter + QPoint(m_nBlockSize, 1.2 * m_nBlockSize)), image);
}
void Block::setUnit(int unit, int side, int maxHP, int innerType)
{
if (unit <= 18)
{
m_unit = new Unit(unit, side, maxHP, parent(), innerType);
}
else
{
m_unit = new Building(unit, side, maxHP, parent(), innerType);
}
}
void Block::setUnit(Unit *newUnit)
{
m_unit = newUnit;
}
void Block::setTerrain(int terrain)
{
m_nTerrain = terrain;
m_terrainImage[0] = QImage(":/image/terrain/" + QString::number(m_nTerrain));
m_terrainImage[1] = grayImage(m_terrainImage);
}
void Block::setVisible(bool visible)
{
m_bVisible = visible;
}
Unit *Block::getUnit() const
{
return m_unit;
}
QPoint Block::getCenter() const
{
return m_pCenter;
}
const QPolygon *Block::getArea() const
{
return &m_area;
}
int Block::getTerrain() const
{
return m_nTerrain;
}
int Block::getRow() const
{
return m_row;
}
int Block::getColumn() const
{
return m_col;
}
bool Block::isVisible() const
{
return m_bVisible;
}
<file_sep>#ifndef GAMEPROCESSOR_H
#define GAMEPROCESSOR_H
#include "tipslabel.h"
#include "settings.h"
#include "gameinfo.h"
#include "map.h"
#include "gamestats.h"
#include "unitmover.h"
#include "unitselectionwidget.h"
#include "descriptionwidget.h"
#include "battlewidget.h"
#include <QObject>
#include <QMediaPlayer>
#include <QMenu>
class GameProcessor : public QObject
{
Q_OBJECT
public:
explicit GameProcessor(Settings *settings,
GameInfo *gameInfo,
Map *map,
GameStats *stats,
QMediaPlayer *SEplayer,
TipsLabel *tipsLabel,
QWidget *moveWidget,
UnitSelectionWidget *unitSelectionWidget,
DescriptionWidget *descriptionWidget,
QMenu *actionContextMenu,
QMenu *mainContextMenu,
QObject *parent = nullptr,
int movingSide = 0,
int totalSides = 2);
void paint(QPainter *painter);
// accessible blocks
void updateAccessibleBlocks(Block *block, int unitType, int movement);
// attackable or capturable blocks
void updateOperatableBlocks(Block *block, int rangeLow, int rangeHigh,
bool capture = false);
// carrier-related blocks
void updateCarrierBlocks(Block *block, Unit *unit);
// visible blocks in fog mode
void updateVisibleBlocks();
// create a unit
void createUnit(int unitId, int side);
// the interaction of two units (battle/get in/get out)
void confrontUnit();
// Check game over conditions
void checkWin();
public slots:
void processStage(int);
void changeSide();
void activate();
void moveMap(QPoint);
void zoomMap(int, QPointF);
void selectPosition(QPoint);
void mouseToPosition(QPoint);
void unselectPosition(QPoint);
void escapeMenu(QPoint);
private:
// Game stats
Settings *m_settings; // Game settings
GameInfo *m_gameInfo; // Game info
Map *m_map; // Game map
GameStats *m_stats; // Game stats
// Sound Effect
QMediaPlayer *m_SEplayer; // Sound effect
// Widgets
TipsLabel *m_tipsLabel; // Tips label at the bottom of the screen
QWidget *m_moveWidget; // Move widget at the top-left of the screen
UnitSelectionWidget *m_unitSelectionWidget; // Unit selection widget
DescriptionWidget *m_descriptionWidget; // Unit Description Widget
BattleWidget *m_battleWidget; // Battle Widget
QMenu *m_actionContextMenu; // Action context menu
QMenu *m_mainContextMenu; // Main context menu
// Menu actions
QAction *m_actions[6]; // Get in, Get out, Capture, Attack, Wait, Cancel
QAction *m_mainActions[3]; // End turn, exit, cancel
// Pointer images
QImage m_pointerImage[6]; // Block highlights
// Game processers
UnitMover *m_unitMover; // Army unit mover
// Moving side
int m_nMovingSide; // Moving side: 0-player, 1-opponent
int m_nTotalSides; // Number of sides
// Other members
int m_nStage; // Stage of a round
int m_nRound; // Round of the battle
Block *m_selectedBlock; // Selected block
Block *m_cursorBlock; // The block with the pointer
int m_nMovesLeft; // Move costs left
QVector<Block *> m_movingRoute; // Route saved
QVector<const Block *> m_accessibleBlocks;// Accessible blocks highlighted when choosing the route
QVector<const Block *> m_attackableBlocks;// Attackable blocks highlighted when choosing the route
QVector<const Block *> m_capturableBlocks;// Capturable blocks highlighted when choosing the route
QVector<const Block *> m_carrierBlocks; // Blocks highlighted that are related to carriers
Unit *m_tempUnit; // Used when creating a unit
signals:
void enterStage(int);
void endOfTurn();
void roundForSide(int);
void gameClosed();
};
#endif // GAMEPROCESSOR_H
|
d0ed215723b098cda9951a527829d2adcb265a42
|
[
"Markdown",
"C++"
] | 37
|
C++
|
ferv3455/Wargroove
|
604a8a8cb2af3ec367ca64999bd4341b09ae7686
|
0416aa3877b4a0b40ac33c581587815a0adadc1e
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include "interface.h"
#include "dominion.h"
int main(int argc, char *argv[]){
printf("random testing outpost\n");
int i, passed =0, failed =0;
srand(time(NULL));
for(i=0; i<1000; i++){
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
int num_players = rand() % 3 + 2;
int Seed = rand() % 2000;
int test, choice1, choice2, choice3;
initializeGame(num_players, k, Seed, &G);
G.hand[0][0] = outpost;
G.outpostPlayed = 0;
initializeGame(num_players, k, 2, &G);
G.hand[0][0] = outpost;
G.outpostPlayed = 0;
if(numHandCards(&G)!=5){
failed++;
}else{
passed++;
}
cardEffect(outpost, 1, 0, 0, &G, 0, 0);
if(G.outpostPlayed != 1){
failed++;
}else{
passed++;
}
if(numHandCards(&G)!=4){
failed++;
}else{
passed++;
}
test = cardEffect(outpost, choice1,choice2,choice3, &G,1);
if(test == 0){
passed++;
}else{
failed++;
}
}
printf("Tests passed: %i\n", passed);
printf("Tests failed: %i\n", failed);
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
int main(){
printf("tesing smithy_function()\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 3, &G);
G.hand[0][0] = smithy;
assertTrue(numHandCards(&G) == 5, "Should have five cards in hand");
cardEffect(smithy,0,0,&G,0,0);
assertTrue(numHandCards(&G) == 7, "Should have seven cards in hand");
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
int main(){
printf("testing outpost\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 2, &G);
G.hand[0][0] = outpost;
G.outpostPlayed = 0;
assertTrue(numHandCards(&G)==5, "Should have five cards");
cardEffect(outpost, 1, 0, 0, &G, 0, 0);
assertTrue(G.outpostPlayed = 1, "outpostPlayed should be one");
assertTrue(numHandCards(&G)==5, "Should have four cards");
}<file_sep>CFLAGS = -Wall -fpic -coverage -lm
rngs.o: rngs.h rngs.c
gcc -c rngs.c -g $(CFLAGS)
dominion.o: dominion.h dominion.c rngs.o
gcc -c dominion.c -g $(CFLAGS)
playdom: dominion.o playdom.c
gcc -o playdom playdom.c -g dominion.o rngs.o $(CFLAGS)
testdominion: testdominion.c dominion.o
gcc -o testdominion testdominion.c -g dominion.o rngs.o $(CFLAGS)
unittest1: unittest1.c dominion.o
gcc -o unittest1 unittest1.c -g dominion.o rngs.o $(CFLAGS)
unittest2: unittest2.c dominion.o
gcc -o unittest2 unittest2.c -g dominion.o rngs.o $(CFLAGS)
unittest3: unittest3.c dominion.o
gcc -o unittest3 unittest3.c -g dominion.o rngs.o $(CFLAGS)
unittest4: unittest4.c dominion.o
gcc -o unittest4 unittest4.c -g dominion.o rngs.o $(CFLAGS)
cardtest1: cardtest1.c dominion.o
gcc -o cardtest1 cardtest1.c -g dominion.o rngs.o $(CFLAGS)
cardtest2: cardtest2.c dominion.o
gcc -o cardtest2 cardtest2.c -g dominion.o rngs.o $(CFLAGS)
cardtest3: cardtest3.c dominion.o
gcc -o cardtest3 cardtest3.c -g dominion.o rngs.o $(CFLAGS)
cardtest4: cardtest4.c dominion.o
gcc -o cardtest4 cardtest4.c -g dominion.o rngs.o $(CFLAGS)
randomtestcard1: randomtestcard1.c dominion.o
gcc -o randomtestcard1 randomtestcard1.c -g dominion.o rngs.o $(CFLAGS)
randomtestcard2: randomtestcard2.c dominion.o
gcc -o randomtestcard2 randomtestcard2.c -g dominion.o rngs.o $(CFLAGS)
randomtestadventurer: randomtestadventurer.c dominion.o
gcc -o randomtestadventurer randomtestadventurer.c -g dominion.o rngs.o $(CFLAGS)
unittestresults.out: unittest1 unittest2 unittest3 unittest4 cardtest1 cardtest2 cardtest3 cardtest4 playdom
./unittest1 >> unittestresults.out
echo "GCOV AFTER UNITTEST 1" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./unittest2 >> unittestresults.out
echo "GCOV AFTER UNITTEST 2" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./unittest3 >> unittestresults.out
echo "GCOV AFTER UNITTEST 3" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./unittest4 >> unittestresults.out
echo "GCOV AFTER UNITTEST 4" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./cardtest1 >> unittestresults.out
echo "GCOV AFTER CARDTEST 1 " >> unittestresults.out
gcov dominion.c >> unittestresults.out
./cardtest2 >> unittestresults.out
echo "GCOV AFTER CARDTEST 2" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./cardtest3 >> unittestresults.out
echo "GCOV AFTER CARDTEST 3" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./cardtest4 >> unittestresults.out
echo "GCOV AFTER CARDTEST 4" >> unittestresults.out
gcov dominion.c >> unittestresults.out
./playdom 3 >> unittestresults.out
echo "GCOV AFTER PLAYING A GAME" >> unittestresults.out
gcov dominion.c >> unittestresults.out
randomtestcard1.out: randomtestcard1 playdom
./randomtestcard1 >> randomtestcard1.out
echo "GCOV AFTER randomtestcard1" >> randomtestcard1.out
gcov dominion.c >> randomtestcard1.out
randomtestcard2.out: randomtestcard2 playdom
./randomtestcard2 >> randomtestcard2.out
echo "GCOV AFTER randomtestcard2” >> randomtestcard2.out
gcov dominion.c >> randomtestcard2.out
randomtestadventurer.out: randomtestadventurer playdom
./randomtestadventurer >> randomtestadventurer.out
echo "GCOV AFTER randomtestadventurer" >> randomtestadventurer.out
gcov dominion.c >> randomtestadventurer.out
testdominion.out: testdominion playdom
./testdominion >> testdominion.out
gcov dominion.c >> testdominion.out
unittest1.out: unittest1 playdom
./unittest1 >> unittest1.out
gcov dominion.c >> unittest1.out
interface.o: interface.h interface.c
gcc -c interface.c -g $(CFLAGS)
player: player.c interface.o
gcc -o player player.c -g dominion.o rngs.o interface.o $(CFLAGS)
all: playdom player
clean:
rm -f *.o playdom.exe playdom test.exe test player testdominion unittest1 unittest2 unittest3 unittest4 cardtest1 cardtest2 cardtest3 cardtest4 player.exe testInit testInit.exe *.gcov *.gcda *.gcno *.so *.a *.dSYM
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include "interface.h"
#include "dominion.h"
int main(int argc, char *argv[]){
printf("Random testing adventurer\n");
srand(time(NULL));
int i, passed =0, failed =0, test;
for(i=0; i<1000;i++){
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
int num_players = rand() % 3 + 2;
int Seed = rand() % 5000;
int choice1, choice2;
test = initializeGame(num_players, k, Seed, &G);
if(test != 0){
failed++;
printf("Initialize failure\n");
}
int current_player = rand() % num_players;
G.whoseTurn = current_player;
choice1 = rand() % 26;
choice2 = rand() % 26;
test = cardEffect(adventurer, choice1,choice2,1, &G);
if(test == 0){
passed++;
}else{
failed++;
}
}
printf("Tests passed: %i\n", passed);
printf("Tests failed: %i\n", failed);
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
int main(){
printf("testing village_function()\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 3, &G);
G.hand[0][0] = village;
G.numActions = 1;
printf("Number of actions left: %i\n", G.numActions);
printf("Playing village card\n");
cardEffect(village, 1, 0, 0, &G, 0, 0);
assertTrue(G.numActions == 2, "Should have two additional actions");
printf("Number of actions left: %i\n", G.numActions);
/*
assertTrue(numHandCards(&G)==5, "Should have five cards");
cardEffect(steward, 1, 0, 0, &G, 0, 0);
assertTrue(G.numActions == 4, "Should have added 3 actions");
assertTrue(numHandCards(&G)==5, "Should have five cards after adding and discarding");
*/
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TEST PASSED\n");
return 0;
}
}
int main(){
printf("Testing initialize\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
int result;
result = initializeGame(5, k, 3, &G);
assertTrue(result == -1, "Added five players, should return error");
result = initializeGame(0, k, 3, &G);
assertTrue(result == -1, "Added zero players, should return error");
result = initializeGame(3, k, 3, &G);
assertTrue(result == 0, "Initialize error");
assertTrue(G.numPlayers = 3, "Number of players not set");
assertTrue(G.supplyCount[silver] == 40, "Silver supply count should be 40");
assertTrue(G.supplyCount[gold] == 30, "Silver supply count should be 40");
int k2[10] = {gardens, gardens, embargo, village, village, mine, cutpurse,
sea_hag, tribute, smithy};
result = initializeGame(3, k2, 3, &G);
assertTrue(result == -1, "Two kingdom cards are the same, should return error");
initializeGame(2, k, 3, &G);
assertTrue(G.supplyCount[curse] == 10, "Curse supply count should be 10"); //
initializeGame(2, k, 3, &G);
assertTrue(G.supplyCount[estate] == 8, "Estate supply count should be 8"); //
assertTrue(G.supplyCount[duchy] == 8, "Duchy supply count should be 8");
assertTrue(G.supplyCount[province] == 8, "Province supply count should be 8"); //
initializeGame(4, k, 3, &G);
assertTrue(G.supplyCount[curse] == 30, "Curse supply count should be 30"); //
assertTrue(G.supplyCount[estate] == 12, "Estate supply count should be 12"); //
assertTrue(G.supplyCount[duchy] == 12, "Duchy supply count should be 12");
assertTrue(G.supplyCount[province] == 12, "Province supply count should be 12");
printf("All initialize tests completed\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "interface.h"
#include "dominion.h"
int main(){
printf("random testing steward\n");
int i, passed =0, failed = 0, test;
srand(time(NULL));
for(i=0; i<1000; i++){
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
int num_players = rand() % 3 + 2;
int Seed = rand() % 2000;
int choice1, choice2, choice3, handPos;
test = initializeGame(num_players, k, Seed, &G);
if(test != 0){
failed++;
printf("Initialize failure\n");
}
int current_player = rand() % num_players;
G.whoseTurn = current_player;
choice1 = rand() % 5;
choice2 = rand() % 5;
handPos = rand() % 5;
G.hand[0][0] = steward;
G.coins = rand() % 20;
test = cardEffect(steward, choice1,choice2,choice3, &G, handPos, 1);
if(test == 0){
passed++;
}else{
failed++;
}
}
printf("Tests passed: %i\n", passed);
printf("Tests failed: %i\n", failed);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
int main(){
printf("testing steward\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 2, &G);
G.hand[0][0] = steward;
G.coins = 0;
assertTrue(numHandCards(&G)==5, "Should have five cards");
cardEffect(steward, 1, 0, 0, &G, 0, 0);
assertTrue(numHandCards(&G)==6, "Should have six cards if choice is 1");
cardEffect(steward, 2, 0, 0, &G, 0, 0);
assertTrue(G.coins==2, "Should have two coins if choice is 2");
cardEffect(steward, 0, 0, 0, &G, 0, 0);
assertTrue(numHandCards(&G)==2, "Should have two cards if choice not 1 or 2");
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include "interface.h"
#include "dominion.h"
#include <time.h>
void shuffleDeck(int *array, size_t n){
if (n > 1){
size_t i;
for (i = 0; i < n - 1; i++){
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
int main(int argc, char *argv[] ){
srand(time(NULL));
struct gameState G;
int k[10] = {adventurer, gardens, duchy, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
//int mySeed = atoi(argv[1]);
int randomSeed = rand() % 100;
int num_players = rand() % 3 + 2;
int currentPlayer, i, turnsPlayed = 0;
int smithyPos = -1, adventurerPos = -1, minePos = -1, villagePos = -1;
int winner = 0;
shuffleDeck(k, 10);
printf("Starting Dominion Game\n");
initializeGame(num_players, k, randomSeed, &G);
while(!isGameOver(&G)){
smithyPos = -1, adventurerPos = -1, minePos = -1, villagePos = -1;
int money 0;
currentPlayer = whoseTurn(&G);
printf("Player %i turn\n", currentPlayer);
for (i = 0; i < numHandCards(&G); i++) {
if(handCard(i, &G) == copper){
money++;
}else if(handCard(i, &G) == silver){
money += 2;
}else if(handCard(i, &G) == gold){
money += 3;
}else if(handCard(i, &G) == adventurer){
adventurerPos = i;
}else if(handCard(i, &G) == smithy){
smithyPos = i;
}else if(handCard(i, &G) == village){
villagePos = i;
}else if(handCard(i, &G) == mine){
minePos = i;
}
}
if(villagePos != -1){
playCard(villagePos, -1, -1, -1, &G);
printf("Played village\n");
int played = 0;
while(i<numHandCards(&G)){
if (handCard(i, &G) == copper){
playCard(i, -1, -1, -1, &G);
money++;
}
if (handCard(i, &G) == silver){
playCard(i, -1, -1, -1, &G);
money += 2;
}
if (handCard(i, &G) == gold){
playCard(i, -1, -1, -1, &G);
money += 3;
}
if (handCard(i, &G) == smithy && played < 2){
played++;
playCard(i, -1, -1, -1, &G);
printf("Played Smithy\n");
while(i<numHandCards(&G)){
if (handCard(i, &G) == copper){
playCard(i, -1, -1, -1, &G);
money++;
}
else if (handCard(i, &G) == silver){
playCard(i, -1, -1, -1, &G);
money += 2;
}
else if (handCard(i, &G) == gold){
playCard(i, -1, -1, -1, &G);
money += 3;
}
i++;
}
}
i++;
}
}else if(smithyPos != -1){
playCard(smithyPos, -1, -1, -1, &G);
printf("Played Smithy\n");
while(i<numHandCards(&G)){
if (handCard(i, &G) == copper){
playCard(i, -1, -1, -1, &G);
money++;
}
else if (handCard(i, &G) == silver){
playCard(i, -1, -1, -1, &G);
money += 2;
}
else if (handCard(i, &G) == gold){
playCard(i, -1, -1, -1, &G);
money += 3;
}
i++;
}
}else if(adventurerPos != -1){
playCard(i, -1, -1, -1, &G);
printf("Played adventurer");
}
printf("Player %i money count: %i\n", currentPlayer, G.coins);
if(turnsPlayed > 4){
if(money >= 8){
buyCard(province, &G);
printf("Province purchased\n");
}else if(money >= 5){
buyCard(duchy, &G);
printf("Duchy purchased\n");
}
}
if(money >=3){
buyCard(gold, &G);
printf("Gold purchased\n");
}else if(money >=2){
buyCard(silver, &G);
printf("Silver purchased\n");
}
endTurn(&G);
turnsPlayed++;
printf ("Player %i Score: %i\n", currentPlayer, scoreFor(currentPlayer, &G));
if(scoreFor(currentPlayer, &G) > winner){
winner = currentPlayer;
}
shuffleDeck(k, 10);
}
printf("Player %i wins\n", winner);
}
<file_sep>#include "dominion.h"
#include <stdio.h>
#include "rngs.h"
#include <stdlib.h>
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
//isGameOver()
int main(int argc, char **argv){
printf("Testing isGameOver()\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 5, &G);
assertTrue(isGameOver(&G)== 0, "isGameOver() should return 0");
//Province cards are out
initializeGame(2, k, 5, &G);
G.supplyCount[province] = 0;
assertTrue(isGameOver(&G)== 1, "Province cards empty, isGameOver() should return 1");
//Three empty supply piles
initializeGame(2, k, 5, &G);
G.supplyCount[1] = 0;
G.supplyCount[2] = 0;
G.supplyCount[3] = 0;
assertTrue(isGameOver(&G)== 1, "Three empty supply piles, isGameOver() should return 1");
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "dominion.h"
#include "rngs.h"
#include "assert.h"
#include "dominion_helpers.h"
int assertTrue(int test, char* message){
if(test != 1){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
//getCost()
int main(int argc, char **argv){
printf("Testing getCost()\n");
struct gameState G;
int result;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 5, &G);
result = getCost(curse);
assertTrue(result == 0 , "curse cost error");
result = getCost(estate);
assertTrue(result == 2, "estate cost error");
result = getCost(duchy);
assertTrue(result == 5, "duchy cost error");
result = getCost(province);
assertTrue(result == 8, "province cost error");
result = getCost(copper);
assertTrue(result == 0, "copper cost error");
result = getCost(silver);
assertTrue(result == 3, "silver cost error");
result = getCost(gold);
assertTrue(result == 6, "gold cost error");
result = getCost(adventurer);
assertTrue(result == 6, "adventurur cost error");
result = getCost(council_room);
assertTrue(result == 5, "council_room cost error");
result = getCost(feast);
assertTrue(result == 4, "feast cost error");
result = getCost(gardens);
assertTrue(result == 4, "gardens cost error");
result = getCost(mine);
assertTrue(result == 5, "mine cost error");
result = getCost(remodel);
assertTrue(result == 4, "remodel cost error");
result = getCost(smithy);
assertTrue(result == 4, "smithy cost error");
result = getCost(village);
assertTrue(result == 3, "village cost error");
result = getCost(baron);
assertTrue(result == 4, "baron cost error");
result = getCost(great_hall);
assertTrue(result == 3, "great_hall cost error");
result = getCost(minion);
assertTrue(result == 5, "minion cost error");
result = getCost(steward);
assertTrue(result == 3, "steward cost error");
result = getCost(tribute);
assertTrue(result == 5, "tribute cost error");
result = getCost(ambassador);
assertTrue(result == 3, "ambassador cost error");
result = getCost(cutpurse);
assertTrue(result == 4, "cutpurse cost error");
result = getCost(embargo);
assertTrue(result == 2, "embargo cost error");
result = getCost(outpost);
assertTrue(result == 5, "outpost cost error");
result = getCost(salvager);
assertTrue(result == 4, "salvager cost error");
result = getCost(sea_hag);
assertTrue(result == 4, "sea_hag cost error");
result = getCost(treasure_map);
assertTrue(result == 4, "treasure_map cost error");
}
<file_sep>#include "dominion.h"
#include <stdio.h>
#include "rngs.h"
#include <stdlib.h>
//My assertTrue function
int assertTrue(int test, char* message){
if(test == 0){
printf("TEST FAILED: %s\n", message);
return 1;
}else{
printf("TESTS SUCCESSFULLY COMPLETED\n");
return 0;
}
}
//buyCard()
int main(int argc, char **argv){
printf("Testing buyCard()\n");
struct gameState G;
int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
initializeGame(2, k, 2, &G);
G.numBuys = 0;
G.coins = 5;
assertTrue(buyCard(1, &G) == -1, "Should not be able to buy card");
G.coins = 2;
G.numBuys = 2;
assertTrue(buyCard(1,&G)==0, "Should be able to buy card");
}
|
2a36c0d5ad9f3993a2506503e3f2699cd7dd3379
|
[
"C",
"Makefile"
] | 13
|
C
|
cs362sp16/cs362sp16_grejucv
|
4ba8b1c89892a2b46103c6d7b41eadd1b9f9a707
|
ec7bd9b5c42d79717f8c32df6fe3a2cf99611e0d
|
refs/heads/main
|
<file_sep>SECRET_KEY =
DEBUG = True
ALLOWED_HOSTS =127.0.0.1
# DB Connection
DB_ENGINE = django.db.backends.sqlite3
DB_NAME = db.sqlite3
DB_USER =
DB_PASSWORD =
DB_HOST =
DB_PORT =
#EMAIL Connection
EMAIL_HOST =
EMAIL_PORT =
TIME_ZONE = UTC
|
933fa54b1a049079e6c208fc6e3f66d300a21fda
|
[
"Shell"
] | 1
|
Shell
|
Padma-Ramanathan/django-polling
|
2f2a788a60b3841aad258172e4ec541a657f062a
|
a6f65adec8141ba2b9dd6a10ae6eed34f97594c7
|
refs/heads/main
|
<file_sep>module.exports = (router) => {
const routers = router();
routers.get('/', (req, res) => {
res.send('All articles');
});
routers.get('/:id', (req, res) => {
res.send(`Article ${req.params.id}`);
});
return routers;
};
<file_sep>module.exports = (router) => {
const routers = router();
routers.get('/', (req, res) => {
res.send('All category');
});
routers.get('/:id', (req, res) => {
res.send(`Category ${req.params.id}`);
});
return routers;
};
|
c8ac0e742103b92032efcab5026bb4a2676bd43e
|
[
"JavaScript"
] | 2
|
JavaScript
|
MrAlexandder/lil_project
|
6c72b2ed279b7b97eb5528f157cefce9115fe89c
|
3e09bbea8a9680c5c9697db0f2754470da46fb6f
|
refs/heads/main
|
<repo_name>jdeng/gosilk<file_sep>/README.md
# gosilk
Skype Silk decoder transpiled using modernc.org/ccgo so it is CGO free.
Silk source code is from https://github.com/collects/silk and under the Skype license.
Check out https://github.com/jdeng/silk2wav for more info.
<file_sep>/example/main.go
package main
import (
"encoding/binary"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"bytes"
"github.com/jdeng/gosilk"
"log"
)
type wavHeader struct {
ChunkID [4]byte
ChunkSize uint32
Format [4]byte
Subchunk1ID [4]byte
Subchunk1Size uint32
AudioFormat uint16
NumChannels uint16
SampleRate uint32
ByteRate uint32
BlockAlign uint16
BitsPerSample uint16
Subchunk2ID [4]byte
Subchunk2Size uint32
}
const SAMPLE_RATE = 24000
func convert(buf []byte) ([]byte, error) {
out, err := gosilk.Decode(buf, SAMPLE_RATE, true)
if err != nil {
return nil, err
}
datalen := uint32(len(out))
hdr := wavHeader{
ChunkID: [4]byte{'R', 'I', 'F', 'F'},
ChunkSize: 36 + datalen,
Format: [4]byte{'W', 'A', 'V', 'E'},
Subchunk1ID: [4]byte{'f', 'm', 't', ' '},
Subchunk1Size: 16,
AudioFormat: 1, //1 = PCM not compressed
NumChannels: 1,
SampleRate: SAMPLE_RATE,
ByteRate: 2 * SAMPLE_RATE,
BlockAlign: 2,
BitsPerSample: 16,
Subchunk2ID: [4]byte{'d', 'a', 't', 'a'},
Subchunk2Size: datalen,
}
var b bytes.Buffer
binary.Write(&b, binary.LittleEndian, hdr)
b.Write(out)
return b.Bytes(), nil
}
func main() {
fname := os.Args[1]
data, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatal(err)
}
out, err := convert(data)
if err != nil {
log.Fatal(err)
}
oname := filepath.Base(fname)
oname = strings.TrimSuffix(oname, path.Ext(oname)) + ".wav"
ioutil.WriteFile(oname, out, 0644)
}
<file_sep>/decode.go
package gosilk
import (
"bytes"
"errors"
lib "github.com/jdeng/gosilk/lib"
"log"
"modernc.org/libc"
"unsafe"
)
type decoder struct {
dec uintptr
tls *libc.TLS
}
func newDecoder() *decoder {
tls := libc.NewTLS()
var size int32
lib.XSKP_Silk_SDK_Get_Decoder_Size(tls, uintptr(unsafe.Pointer(&size)))
dec := libc.Xmalloc(tls, uint64(size))
ret := lib.XSKP_Silk_SDK_InitDecoder(tls, dec)
if ret < 0 {
libc.Xfree(tls, dec)
return nil
}
return &decoder{tls: tls, dec: dec}
}
func freeDecoder(d *decoder) {
libc.Xfree(d.tls, d.dec)
}
func (d *decoder) decodeFrame(sampleRate int32, payload []byte, buf []byte) (int, error) {
c := &lib.SKP_SILK_SDK_DecControlStruct{FframesPerPacket: 1, FAPI_sampleRate: sampleRate}
var used int16
ret := lib.XSKP_Silk_SDK_Decode(d.tls, d.dec, uintptr(unsafe.Pointer(c)), 0, uintptr(unsafe.Pointer(&payload[0])), int32(len(payload)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&used)))
if ret < 0 {
return 0, errors.New("decode error")
}
return int(used) * 2, nil
}
func Decode(buf []byte, sampleRate int32, withHeader bool) ([]byte, error) {
const MAXSIZE = 20 * 48 * 5 * 2 * 2
var b bytes.Buffer
out := make([]byte, MAXSIZE)
if withHeader {
const TAG = "#!SILK_V3"
if len(buf) < 1+len(TAG) || buf[0] != 0x02 || bytes.Compare(buf[1:1+len(TAG)], []byte(TAG)) != 0 {
return nil, errors.New("invalid header")
}
buf = buf[1+len(TAG):]
}
d := newDecoder()
defer freeDecoder(d)
for {
if len(buf) < 2 {
break
}
plen := int(uint16(buf[0]) + (uint16(buf[1]) << 8))
if len(buf) < 2+plen {
log.Printf("%d bytes expected but only %d available\n", int(plen), len(buf))
break
}
payload := buf[2 : 2+plen]
buf = buf[2+plen:]
olen, _ := d.decodeFrame(sampleRate, payload, out)
if olen < 0 {
log.Printf("Failed to decode %d bytes\n", plen)
break
}
b.Write(out[:olen])
}
return b.Bytes(), nil
}
<file_sep>/go.mod
module github.com/jdeng/gosilk
go 1.16
require modernc.org/libc v1.9.5
|
894ab9a55f094e0e85107dcd8233356ef9ac6611
|
[
"Markdown",
"Go Module",
"Go"
] | 4
|
Markdown
|
jdeng/gosilk
|
b75505eb6562e4f3821cc4f240e4320ddffe1001
|
d4d9dd1b9fd4c3ba9cb8a48e341d4a357c598030
|
refs/heads/master
|
<repo_name>bpavle/PetitionWebsite<file_sep>/get_locations.php
<?php
if (!isset($_SESSION["status"])) {
echo "Немате право приступа!";
} else {
require_once("config.php");
$id = $_SESSION["id"];
$upit = "SELECT * FROM location;";
$rez = mysqli_query($link, $upit);
while ($podaci = mysqli_fetch_assoc($rez)) {
$id = $podaci['location_id'];
$naziv = $podaci['name'];
$grad = $podaci['city'];
$opstina = $podaci['municipality'];
$ulica = $podaci['street'];
$x = $podaci['x_coordinate'];
$y = $podaci['y_coordinate'];
echo <<<EOT
<tr>
<td>$naziv</td>
<td>$grad</td>
<td>$opstina</td>
<td>$ulica</td>
<td>$x; $y</td>
</tr>
EOT;
}
echo <<<EOT
<tr>
<td colspan="2"> <button class = "btn" type="submit" name="posalji"><a href="choose_locations.html">Одабери локације </a></button></td>
<td colspan="3"> <button class = "btn" type="submit" name="posalji"><a href="update_location.html">Измени </a></button></td>
</tr>
EOT;
mysqli_close($link);
}<file_sep>/insert_location.php
<?php
session_start();
if (isset($_SESSION["status"])) {
require_once("config.php");
if (isset($_POST["posalji"])) {
$ime = $_POST["naziv"];
$grad = $_POST["grad"];
$opstina = $_POST["opstina"];
$ulica = $_POST["ulica"];
$x = $_POST["x_koordinata"];
$y = $_POST["y_koordinata"];
}
$id = $_SESSION['id'];
$sql = "INSERT INTO location SET
name='$ime',
city='$grad',
municipality='$opstina',
street='$ulica',
organizer_id_chose='$id',
organizer_administrator_id='$id',
x_coordinate='$x',
y_coordinate='$y'
";
mysqli_query($link, $sql);
mysqli_close($link);
//vracanje na sign.html
$newURL = "location_entry.html";
header('Location: ' . $newURL);
die();
}<file_sep>/save_choose_locations.php
<?php
session_start();
if (isset($_SESSION["id"]) && isset($_POST["update"])) {
require_once("config.php");
$organizer_id = $_SESSION["id"];
$i = 1;
$sql = "SELECT location_id FROM location where organizer_id_chose=0 or organizer_id_chose=$organizer_id;";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "Usao u while organizator " . $organizer_id . " location_id= " . $row["location_id"] . "<br>";
$location_id = $row["location_id"];
if (isset($_POST["odaberi$i"])) {
$sql = "UPDATE location SET organizer_id_chose='$organizer_id' WHERE location_id=$location_id;";
mysqli_query($link, $sql);
echo $sql . "<br>";
} else {
//organizator moze i da ancekira lokaciju koja je bila njegova i time je oslobodi da moze da je uzme drugi organizator
$sql = "UPDATE location SET organizer_id_chose=0 WHERE location_id=$location_id;";
mysqli_query($link, $sql);
}
$i++;
}
}
mysqli_close($link);
//vracanje na sign.html
$newURL = "locations.html";
header('Location: ' . $newURL);
die();<file_sep>/registration.php
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$mail_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validacija email adrese-
//Proveravamo da li je polje mozda ostalo prazno
if(empty(trim($_POST["mail"]))){
$mail_err = "Молимо Вас да унесете адресу е поште";
echo $mail_err;
} else{
//ako polje nije prazno proveravamo da li se adresa vec nalazi u bazi
$mail = $_POST["mail"];
$sql = "SELECT email FROM organizer_administrator WHERE email = '$mail' ";
$result= mysqli_query($link,$sql);
$temp = mysqli_fetch_array($result);//mysqli_fetch_array smesta rezultat upita u numericki ili asocijativni niz kada god
//kada god se pozove predje se u sledeci red, ali ja ovde ocekujem jedan ili ne jedan niz podataka.
if($temp["email"]==$mail){
$mail_err="Мејл адреса већ постоји";
//Ovde bi mogao da uleti javascript sa nekim alertom npr. Mozda i da boji html polje u kojem je mejl adresa(to moze i bez javascript-a)
}else{
// Validate password
if(empty(trim($_POST["sifra"]))){
$password_err = "Поље за шифру не сме бити празно";
echo $password_err;
} else{
$password = trim($_POST["sifra"]);
}
$name=$_POST["ime"];
$surname=$_POST["prezime"];
$phone_number=$_POST["telefon"];
$address=$_POST["adresa"];
$recommended_by=$_POST["predlagac"];
// Check input errors before inserting in database
if(empty($mail_err) && empty($password_err)){
/* nije dodata adresa jer je nema u postavci novog dela zadatka:( */
$sql = "INSERT INTO organizer_administrator (email, password,name,surname,recommended_by_organizer_id,phone_number) VALUES ('".$mail."','".$password."','".$name."','".$surname."',".$recommended_by.",'".$phone_number."')";
$result=mysqli_query($link,$sql);
echo "upit ".$sql." izvrsen";
}
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/png" href="assets/favicon.png" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>Регистрација</title>
</head>
<body>
<!-- <div class="head">
<div id="head-content">
<a href="index.html">
<div id="logo-container"><img src="assets/favicon.png" style="width: 100px; height: 100px;"
/></a></div>
<div id="naslov">Добродошли на Потпиши.ме!</div></div>
</div>
<div class="navigation">
<div id="nav-container">
<a href="index.html">Насловна</a>
<a href="petition.html">Петиција</a>
<a href="news.html">Вести</a>
<a href="sign.html">Потпиши</a>
<div class="dropdown">
<button class="dropbtn">Организација</button>
<div class="dropdown-content">
<a href="login.html">Улогуј се</a>
<a href="registration.html">Регистрација</a>
</div>
</div>
<a href="contact.html">Контакт</a>
</div>
</div>
<script src="inactive.js"></script>
-->
<?php include("fixed.php")?>
<div class="content">
<div class="form-container">
<h1>Регистрација</h1>
<div class="form">
<table>
<form method="POST" action="registration.php">
<tr>
<td> Име:</td>
<td> <input type="text" name="ime" required></td>
</tr>
<tr>
<td> Презиме:</td>
<td> <input type="text" name="prezime" required></td>
</tr>
<tr>
<td> е-mail:</td>
<td> <input type="text" name="mail" required></td>
</tr>
<tr>
<td> Адреса:</td>
<td> <input type="text" name="adresa" required></td>
</tr>
<tr>
<td> Предлагач:</td>
<td> <input type="text" name="predlagac" required></td>
</tr>
<tr>
<td> Телефон:</td>
<td> <input type="number" name="telefon" required></td>
</tr>
<tr>
<td> Шифра:</td>
<td> <input type="password" name="<PASSWORD>" required></td>
</tr>
<tr >
<td colspan="2"> <button class = "btn" name="register"> <a href="index.html">Региструј се </a></button></td>
</tr>
</form>
</table>
</div>
</div>
</div>
</body>
</html><file_sep>/insert_sign.php
<?php
require_once("config.php");
if (isset($_POST["posalji"])){
$x=1;
$termini="";
if(isset($_POST["termin1"])){
$termini = $termini.$_POST["termin1"].";";
}
if(isset($_POST["termin2"])){
$termini = $termini.$_POST["termin2"].";";
}
if(isset($_POST["termin3"])){
$termini = $termini.$_POST["termin3"].";";
}
if(isset($_POST["termin4"])){
$termini = $termini.$_POST["termin4"].";";
}
if(isset($_POST["termin5"])){
$termini = $termini.$_POST["termin5"].";";
}
if(isset($_POST["termin6"])){
$termini = $termini.$_POST["termin6"].";";
}
if(isset($_POST["termin7"])){
$termini = $termini.$_POST["termin7"].";";
}
if(isset($_POST["termin8"])){
$termini = $termini.$_POST["termin8"].";";
}
$ime = $_POST["ime"];
echo $ime.'<br>';
$prezime = $_POST["prezime"];
echo $prezime.'<br>';
$email=$_POST["email"];
echo $email.'<br>';
$tel = $_POST["tel"];
echo $tel.'<br>';
$broj_lk = $_POST["broj_lk"];
echo $broj_lk.'<br>';
$lokacija=$_POST["lokacije"];
$komentar=$_POST["message"];
$preuzet=0;
$javno=$_POST["javno"];
$obavestenja=$_POST["obavestenja"];
$x_coordinate=$_POST["x_coordinate"];
$y_coordinate=$_POST["y_coordinate"];
}
$sql = "INSERT INTO sign SET
name='$ime',
surname='$prezime',
phone_number='$tel',
email='$email',
id_number='$broj_lk',
comment='$komentar',
location_id='$lokacija',
appointments='$termini',
email_notification='$obavestenja[0]',
publish='$javno[0]',
taken_over='$preuzet',
number=1,
x_coordinate='$x_coordinate',
y_coordinate='$y_coordinate'
";
echo $sql;
mysqli_query($link,$sql);
mysqli_close($link);
//vracanje na sign.html
$newURL = "sign.html";
header('Location: '.$newURL);
die();
?><file_sep>/get_organizers.php
<?php
//session_start();
$disqualified_organizers = [];
$all_organizers = [];
if (isset($_SESSION["status"])) {
require_once("config.php");
if (basename($_SERVER["PHP_SELF"]) == "organizer.html") {
$upit = "SELECT * FROM `organizer_administrator` WHERE `approved`<>2;";
$rez = mysqli_query($link, $upit);
while ($podaci = mysqli_fetch_assoc($rez)) {
$ime = $podaci['name'];
$prezime = $podaci['surname'];
$mail = $podaci['email'];
$telefon = $podaci['phone_number'];
$predlagac = $podaci['recommended_by_organizer_id'];
echo <<<EOT
<tr>
<td>$ime</td>
<td>$prezime</td>
<td><a href="mailto:$mail">$mail</a></td>
<td>$predlagac</td>
<td>$telefon</td>
</tr>
EOT;
}
if ($_SESSION["status"] == "admin") {
echo <<<EOT
<tr>
<td></td>
<td></td>
<td></td>
<td><td colspan="2"> <button class = "btn" type="submit" name="posalji"><a href="update_organizer.html">Измени </a></button></td></td></tr>
EOT;
}
} else {
$sql = "SELECT * FROM organizer_administrator WHERE approved<>2;";
// echo $sql . "<br>";
$rezult = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($rezult)) {
array_push($GLOBALS["all_organizers"], $row);
$organizer_id_chose = $row["organizer_administrator_id"];
$sql = "SELECT COUNT(*) AS total_signatures_by_organizator FROM `sign` S, location L where S.location_id=L.location_id AND organizer_id_chose=$organizer_id_chose;";
//echo $sql . "<br>";
$total_signatures_by_organizator = mysqli_query($link, $sql);
$total_signatures_by_organizator = mysqli_fetch_assoc($total_signatures_by_organizator);
$total_signatures_by_organizator = $total_signatures_by_organizator["total_signatures_by_organizator"];
if ($total_signatures_by_organizator == 0 || $row["invalid_signature_count"] / $total_signatures_by_organizator <= 0.05) {
// echo "desio se continue<br>";
continue;
}
$sql = "SELECT * FROM `organizer_administrator` WHERE `invalid_signature_count`/$total_signatures_by_organizator>0.05 AND
organizer_administrator_id=$organizer_id_chose;";
//echo $sql . "<br>";
$organizer = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($organizer);
array_push($GLOBALS["disqualified_organizers"], $row);
$ime = $row['name'];
$prezime = $row['surname'];
$mail = $row['email'];
$telefon = $row['phone_number'];
$predlagac = $row['recommended_by_organizer_id'];
/*
echo <<<EOT
<tr>
<td>$ime</td>
<td>$prezime</td>
<td><a href="mailto:$mail">$mail</a></td>
<td>$predlagac</td>
<td>$telefon</td>
</tr>
EOT; */
}
foreach ($GLOBALS["all_organizers"] as $value) {
if ($value["bad_recommendation_count"] >= 2) {
array_push($GLOBALS["disqualified_organizers"], $value);
}
}
while ($row = array_pop($GLOBALS["disqualified_organizers"])) {
$ime = $row['name'];
$prezime = $row['surname'];
$mail = $row['email'];
$telefon = $row['phone_number'];
$predlagac = $row['recommended_by_organizer_id'];
echo <<<EOT
<tr>
<td>$ime</td>
<td>$prezime</td>
<td><a href="mailto:$mail">$mail</a></td>
<td>$predlagac</td>
<td>$telefon</td>
</tr>
EOT;
}
}
mysqli_close($link);
}<file_sep>/insert_organizer.php
<?php
session_start();
if (isset($_SESSION["status"])) {
require_once("config.php");
$id = $_SESSION["id"];
if (isset($_POST["posalji"])) {
$ime = $_POST["ime"];
$prezime = $_POST["prezime"];
$email = $_POST["email"];
/* $predlagac= $_POST["predlagac"]; */
$sifra = $_POST["sifra"];
$telefon = $_POST["telefon"];
$broj_lk = $_POST["broj_lk"];
}
$sql = "INSERT INTO organizer_administrator SET
name='$ime',
surname='$prezime',
email='$email',
phone_number='$telefon',
id_number='$broj_lk',
password = <PASSWORD>',
recommended_by_organizer_id=$id;
";
mysqli_query($link, $sql);
mysqli_close($link);
//vracanje na sign.html
$newURL = "organizer.html";
header('Location: ' . $newURL);
//die();
}<file_sep>/update_organizers.php
<?php
require_once("config.php");
if (!(isset($_SESSION["status"]) && $_SESSION["status"] == "admin")) {
echo "<h2>МОРАТЕ СЕ УЛОГОВАТИ КАО АДМИН ДА БИСТЕ МЕЊАЛИ ПОДАТКЕ О ОРГАНИЗАТОРИМА</h2>";
//sleep(10);
/* header("Location: ", "login.php"); */
die();
} else {
echo "<script src='validator.js'></script>";
$upit = "SELECT * FROM organizer_administrator;";
$rez = mysqli_query($link, $upit);
echo <<<EOT
<form method="POST" action="save_update_organizers.php" onsubmit="return validateForm()">
EOT;
$i = 0;
while ($podaci = mysqli_fetch_assoc($rez)) {
$i++;
$id = $podaci['organizer_administrator_id'];
$ime = $podaci['name'];
$prezime = $podaci['surname'];
$sifra = $podaci['password'];
$telefon = $podaci['phone_number'];
$email = $podaci['email'];
$br_lk = $podaci['id_number'];
$odobren = $podaci['approved'];
$checked; //cekiramo kolonu odobren za vec odobrene organizatore. OStavlima ostavljamo necekiran cekbox
if ($odobren == '2') {
$checked = "checked onclick='return false;'";
} else if ($odobren != '0') {
$checked = "checked";
} else {
$checked = "";
}
$predlagac = $podaci['recommended_by_organizer_id'];
$nevazeci = $podaci['invalid_signature_count'];
$lose_preporuke = $podaci['bad_recommendation_count'];
echo <<<EOT
<tr>
<td><input type="text" name="id$i" value=$id></td>
<td><input type="text" name="ime$i" value=$ime></td>
<td><input type="text" name="prezime$i" value=$prezime></td>
<td><input type="text" name="email$i" value=$email></td>
<td><input type="text" name="predlagac$i" value=$predlagac></td>
<td><input type="text" name="telefon$i" value=$telefon></td>
<td><input type="text" name="sifra$i" value=$sifra></td>
<td><input type="text" name="br_lk$i" value=$br_lk></td>
<td><input type="checkbox" name="odobren$i" value=$odobren $checked></td>
<td><input type="text" name="nevazeci$i" value=$nevazeci></td>
<td><input type="text" name="lose_preporuke$i" value=$lose_preporuke></td>
<td><input id="checkbox$i" type="checkbox" name="brisi$i" value="brisi"></td>
</tr>
EOT;
}
echo <<<EOT
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td><td colspan="2"> <button class = "btn" type="submit" name="update"> Сачувај </button></td></td></tr>
EOT;
//echo "<br><br><br>POSLEDNJE i=$i";
mysqli_close($link);
}<file_sep>/fixed.php
<?php
if(!isset($_SESSION["id"]))
session_start();
if (
basename($_SERVER["PHP_SELF"]) == "locations.html" ||
basename($_SERVER["PHP_SELF"]) == "organizer.html" ||
basename($_SERVER["PHP_SELF"]) == "complete_signatures.html" ||
basename($_SERVER["PHP_SELF"]) == "news_entry.html" ||
basename($_SERVER["PHP_SELF"]) == "organizer_entry.html" ||
basename($_SERVER["PHP_SELF"]) == "location_entry.html"
)
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
if (!isset($_SESSION["email"])) {
echo <<<EOT
<div class="head">
<div id="head-content">
<a href="index.html">
<div id="logo-container"><img src="assets/favicon.png" style="width: 100px; height: 100px;"
/></a></div>
<div id="naslov">Добродошли на Потпиши.ме!</div></div>
</div>
<div class="navigation">
<div id="nav-container">
<a href="index.html">Насловна</a>
<a href="petition.html">Петиција</a>
<a href="news.html">Вести</a>
<a href="sign.html">Потпиши</a>
<div class="dropdown">
<button class="dropbtn">Организација</button>
<div class="dropdown-content">
<a href="login.php">Улогуј се</a>
<a href="registration.php">Регистрација</a>
</div>
</div>
<a href="contact.html">Контакт</a>
</div>
</div>
EOT;
} else {
$status = $_SESSION['status'];
$id = $_SESSION['id'];
echo <<<EOT
<div class="head">
<div id="head-content">
<a href="index.html">
<div id="logo-container"><img src="assets/favicon.png" style="width: 100px; height: 100px;"
/></a></div>
<div id="naslov">Добродошли на Потпиши.ме!</div></div>
</div>
<div class="navigation">
<div id = "nav-container">
<a href="index.html">Насловна</a>
<a href="petition.html">Петиција</a>
<a href="news.html">Вести</a>
<a href="sign.html">Потпиши</a>
<div class="dropdown">
<button class="dropbtn">Организација</button>
<div class="dropdown-content">
<a href="locations.html">Локације</a>
<a href="organizer.html">Организатори</a>
EOT;
if ($_SESSION["status"] == "admin") {
echo <<<EOT
<a href="disqualified_organizers.html">Искључени организатори</a>
EOT;
}
echo <<<EOT
<a href="choose_appointments.html"style="background-color: #5cff017d;">Почни са радом</a>
<a href="complete_signatures.html">Комплетни потписи</a>
<a href="logout.php">Излогујте се</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Унос</button>
<div class="dropdown-content">
<a href="news_entry.html">Унос вести</a>
<a href="organizer_entry.html">Унос организатора</a>
<a href="location_entry.html">Унос локације</a>
</div>
</div>
<a href="contact.html">Контакт</a>
<p> Улоговани сте као $status id=$id</p>
</div>
</div>
EOT;
}<file_sep>/get_news.php
<?php
require_once("config.php");
$upit="SELECT * FROM news;";
$rez=mysqli_query($link,$upit);
while($podaci=mysqli_fetch_assoc($rez)){
$naslov=$podaci['title'];
$vest=$podaci['content'];
echo<<<EOT
<dt>
<a href="#" ; class="links"
><b
>$naslov
>
</a>
</dt>
<br />
<dd>
$vest
</dd>
<hr />
EOT;
}
mysqli_close($link);
?>
<file_sep>/get_comments.php
<?php
require_once("config.php");
$upit = "SELECT * FROM sign;";
$rez = mysqli_query($link, $upit);
while ($podaci = mysqli_fetch_assoc($rez)) {
$ime = $podaci['name'];
$komentar = $podaci['comment'];
echo <<<EOT
<div class="comment">
<h4>$ime</h4>
$komentar
</div>
<hr />
EOT;
}
mysqli_close($link);
<file_sep>/choose_locations_form.php
<?php
if (!isset($_SESSION["status"])) {
echo "Немате право приступа!";
} elseif($_SESSION["status"]=="admin"){
echo"<h1>АДМИН НЕ МОЖЕ БИРАТИ ЛОКАЦИЈЕ!</h1>";
}else {
if ($_SESSION["status"] == "organizer") {
$id = $_SESSION["id"];
//echo "ORGANIZER";
$upit = "SELECT * FROM location where organizer_id_chose=0 or organizer_id_chose=$id;";
}
require_once("config.php");
$rez = mysqli_query($link, $upit);
echo <<<EOT
<form method="POST" action="save_choose_locations.php">
EOT;
$i = 1;
while ($podaci = mysqli_fetch_assoc($rez)) {
$id = $podaci['location_id'];
$naziv = $podaci['name'];
$grad = $podaci['city'];
$opstina = $podaci['municipality'];
$ulica = $podaci['street'];
$x = $podaci['x_coordinate'];
$y = $podaci['y_coordinate'];
$chosen_by = $podaci["organizer_id_chose"];
if ($chosen_by == $_SESSION["id"]) {
$checked = "checked";
} else {
$checked = "";
}
echo <<<EOT
<tr>
<td>$id</td>
<td>$naziv</td>
<td>$grad</td>
<td>$opstina</td>
<td>$ulica</td>
<td>$x</td>
<td>$y</td>
<td><input type="checkbox" name="odaberi$i" value="odaberi" $checked></td>
</tr>
EOT;
$i++;
}
echo <<<EOT
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td><td colspan="2"> <button class = "btn" type="submit" name="update"> Сачувај </button></td></td></tr>
EOT;
mysqli_close($link);
}
<file_sep>/update_complete_signatures.php
<?php
require_once("config.php");
echo "<script src='validator.js'></script>";
$upit="SELECT * FROM sign;";
$rez=mysqli_query($link,$upit);
echo<<<EOT
<form method="POST" action="save_update_complete_signatures.php" onsubmit="return validateForm()">
EOT;
$i=1;
while($podaci=mysqli_fetch_assoc($rez)){
$id=$podaci['sign_id'];
$ime=$podaci['name'];
$prezime=$podaci['surname'];
$email=$podaci['email'];
$telefon=$podaci['phone_number'];
$br_lk=$podaci['id_number'];
$lokacija=$podaci['location_id'];
$javniPotpis=$podaci['publish'];
$email_obavestenje=$podaci['email_notification'];
$preuzet=$podaci['taken_over'];
$komentar=$podaci['comment'];
echo<<<EOT
<tr>
<td><input type="text" name="id$i" value=$id></td>
<td><input type="text" name="ime$i" value=$ime></td>
<td><input type="text" name="prezime$i" value=$prezime></td>
<td><input type="text" name="email$i" value=$email></td>
<td><input type="text" name="telefon$i" value=$telefon></td>
<td><input type="text" name="br_lk$i" value=$br_lk></td>
<td><input type="text" name="lokacija$i" value=$lokacija></td>
<td><input type="text" name="javniPotpis$i" value=$javniPotpis></td>
<td><input type="text" name="email_obavestenje$i" value=$email_obavestenje></td>
<td><input type="text" name="preuzet$i" value=$preuzet></td>
<td><input type="text" name="komentar$i" value=$komentar></td>
<td><input type="checkbox" id="checkbox$i" name="brisi$i" value="brisi"></td>
</tr>
EOT;
$i++;
}
echo<<<EOT
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td><td colspan="2"> <button class = "btn" type="submit" name="update"> Сачувај </button></td></td></tr>
EOT;
mysqli_close($link);
?><file_sep>/update_locations.php
<?php
if (!isset($_SESSION["status"])) {
echo "Немате право приступа!";
} else {
echo "<script src='validator.js'></script>";
if ($_SESSION["status"] == "organizer") {
$id = $_SESSION["id"];
//echo "ORGANIZER";
$upit = "SELECT * FROM location WHERE organizer_administrator_id=$id";
} else {
$upit = "SELECT * FROM location;";
}
require_once("config.php");
$rez = mysqli_query($link, $upit);
echo <<<EOT
<form onSubmit="return validateForm()" method="POST" action="save_update_locations.php">
EOT;
$i = 1;
while ($podaci = mysqli_fetch_assoc($rez)) {
$id = $podaci['location_id'];
$naziv = $podaci['name'];
$grad = $podaci['city'];
$opstina = $podaci['municipality'];
$ulica = $podaci['street'];
$x = $podaci['x_coordinate'];
$y = $podaci['y_coordinate'];
echo <<<EOT
<tr>
<td><input type="text" name="id$i" value=$id></td>
<td><input type="text" name="naziv$i" value=$naziv></td>
<td><input type="text" name="grad$i" value=$grad></td>
<td><input type="text" name="opstina$i" value=$opstina></td>
<td><input type="text" name="ulica$i" value=$ulica></td>
<td><input type="text" name="x$i" value=$x></td>
<td><input type="text" name="y$i" value=$y></td>
<td><input type="checkbox" name="brisi$i" id="checkbox$i" value="brisi"></td>
</tr>
EOT;
$i++;
}
echo <<<EOT
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td><td colspan="2"> <button class = "btn" type="submit" name="update" > Сачувај </button></td></td></tr>
EOT;
mysqli_close($link);
}
?>
<!--
<script>
function validateForm() {
var br=0;
var i = 1;
//alert(document.get);
while(document.getElementById("checkbox"+i)) {
//alert("USAO");
//document.getElementsByName("brisi"+i);
var checkboxes = document.getElementById("checkbox"+i);
if (checkboxes.checked) {
br++;
}
i++;
}
if(br==1){
return confirm("Пажња! Да ли сте сигурни да желите да обришете "+br +" ред?");
}
else if(br<5){
return confirm("Пажња! Да ли сте сигурни да желите да обришете "+br +" реда?");
}
else {return confirm("Пажња! Да ли сте сигурни да желите да обришете "+br +" редова?");}
}
</script> --><file_sep>/work.php
<?php
/*
Organizator izabere lokacije, tim lokacijama
>> odgovaraju određeni potpisnici. Onda izabere termine. Onda program
>> nadje
>> u
>> svakom terminu koliko ima potpisnika kojima odgovaraju ti termini, i
>> onda
>> bira termine prema broju potpisnika, prvo najgušći termin. Onda program
>> krene od jednog potpisnika slučajno izabranog iz tog termina, pa nadje
>> sledećeg najbližeg, pa sledećeg i tako dalje sve dok mogu da stanu u
>> taj
>> termin. Onda izbaci te potpisnike, i bira sledeći najgušći termin, pa
>> tu
>> izabere raspored potpisnika. Na kraju posle proračuna organizatoru
>> izbaci
>> listu termina i redosleda potpisnika koje treba da obidje u tom terminu
>> sa
>> adresama. */
session_start();
//echo $_SESSION["status"];
if(isset($_SESSION["status"])&&$_SESSION["status"]=="admin"){
echo "АДМИН САМО КОНТРОЛИШЕ! НЕ РАДИ!";
}else{
//funkcija koja vraca distancu izmedju dve tacke zadatih koordinata
function distance($X1, $X2, $Y1, $Y2)
{
return sqrt(($X1 - $X2) ** 2 + ($Y1 - $Y2) ** 2);
}
if (isset($_SESSION["status"]) && isset($_POST["posalji"])) {
$organizer_speed = 4 / 60; //brzina organizatora po minutu
echo <<<EOT
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="shortcut icon" type="image/png" href="assets/favicon.png" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Рад</title>
</head>
<body>
EOT;
include("fixed.php");
echo <<<EOT
<div class="content">
<h1>Почетак рада</h1>
EOT;
require_once("config.php");
//prvo cemo da dohvatimo sve termine koji odgovaraju organizatoru iz forme koja je pozvala ovaj fajl
//promenljiva koja sadrzi niz termina koje je organizator odabrao
$chosen_appointments = $_POST["appointments"];
/* foreach ($chosen_appointments as $appointment) {
//echo $appointment . " ";
} */
//lokacije koje je organizator koji je ulogovan izabrao
$id = $_SESSION["id"];
$sql = "SELECT Location_id FROM location WHERE organizer_id_chose=$id";
$result = mysqli_query($link, $sql);
$chosen_locations = [];
while ($location = mysqli_fetch_assoc($result)) {
array_push($chosen_locations, $location);
} //napravili smo niz id-jeva lokacija koje je organizator odabrao
//sada nam trebaju potpisnici sa tih lokacija i njihovi termini
$signatories_by_appointment_count = [];
$signatories_by_appointment = [];
//za svaki termin koji je izabrao organizator uzimamo koliko je ljudi u njemu
foreach ($chosen_appointments as $appointment) {
//uzimamo sve potpisnike kojima odgovara taj termin
$sql = "SELECT * FROM sign WHERE taken_over=0 AND appointments LIKE '%$appointment%' AND location_id IN (
SELECT location_id FROM location WHERE organizer_id_chose=$id
)";
//echo $sql . "<br>";
$result = mysqli_query($link, $sql);
//brojimo koliko u kom terminu ima potpisnika
$signatories_by_appointment_count[$appointment] = mysqli_num_rows($result);
// echo "Broj potpisnika kojima odgovara termin: " . $appointment . " je " . $signatories_by_appointment_count[$appointment] . "<br>";
}
//sortiramo niz broja potpisnika po terminima opadajuce jer krecemo od najgusceg termina
array_multisort($signatories_by_appointment_count, SORT_DESC);
//termini sortirani po gustini(prvo najgusci)
$sorted_appointments = array_keys($signatories_by_appointment_count);
$last_signatory = [];
//u svakom terminu sortiramo ljude po blizini pocevsi od prvog coveka
foreach ($sorted_appointments as $appointment) {
$sql = "SELECT * FROM sign WHERE taken_over=0 AND appointments LIKE '%$appointment%' AND location_id IN (
SELECT location_id FROM location WHERE organizer_id_chose=$id
)";
//echo $sql . "<br>";
$result = mysqli_query($link, $sql);
$signatories_by_appointment[$appointment] = [];
while ($signatory = mysqli_fetch_assoc($result)) {
//ako je neko vec rasporedjen(taken_over=2) njega ne ubacujemo u termin
//ubacujemo samo one koji nisu rasporedjeni taken_over=0;
if ($signatory["taken_over"] == 0)
array_push($signatories_by_appointment[$appointment], $signatory);
//echo $signatory["sign_id"] . " ide u niz<br>";
}
/* echo "<br>za ".$appointment;
foreach($signatories_by_appointment[$appointment] as $s){
echo "<br>".$s["sign_id"];
}*/
//sortiramo ljude po blizini
$arr = $signatories_by_appointment[$appointment];
for ($i = 0; $i < count($signatories_by_appointment[$appointment]); $i++) {
$min = 1000000;
for ($j = 1; $j < count($signatories_by_appointment[$appointment]); $j++) {
//mala optimizacija... Preskacemo slucajeve kada poredimo potpisnika sa samim sobom
if ($arr[$i]["sign_id"] == $arr[$j]["sign_id"]) continue;
//echo "Distanca izmedju " . $arr[$i]["sign_id"] . "(" . $arr[$i]['x_coordinate'] . "," . $arr[$i]['y_coordinate'] . ")" . " i " . $arr[$j]["sign_id"] . "(" . $arr[$j]['x_coordinate'] . "," . $arr[$j]['y_coordinate'] . ")" . " je " . distance($arr[$i]["x_coordinate"], $arr[$j]["x_coordinate"], $arr[$i]["y_coordinate"], $arr[$j]["y_coordinate"]) . "<br>";
//echo "Trenutna najmanja distanca u nizu je " . $min . "<br>";
if (distance($arr[$i]["x_coordinate"], $arr[$j]["x_coordinate"], $arr[$i]["y_coordinate"], $arr[$j]["y_coordinate"]) < $min) {
$min = distance($arr[$i]["x_coordinate"], $arr[$j]["x_coordinate"], $arr[$i]["y_coordinate"], $arr[$j]["y_coordinate"]);
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
//echo "USAO" . "<br>";
}
}
//belezimo koje smo ljude vec rasporedili
/* $sid=$arr[$i]['sign_id'];
$sql="UPDATE sign SET
taken_over=2
WHERE sign_id=$sid;
";
echo $sql;
mysqli_query($link,$sql); */
} //zavrseno sortiranje po blizini
$signatories_by_appointment[$appointment] = $arr;
/* echo "sortirani u terminu ".$appointment;
foreach ($arr as $key) {
echo '<br>'.$key["sign_id"];
} */
//proverimo da li je termin prazan, ako jeste ne pravimo tabelu
if (empty($signatories_by_appointment[$appointment])) {
echo "Термин " . $appointment . " је празан<BR>";
continue;
};
echo <<<EOT
<form method="POST" action = "finish.php">
<table id="table" class="table_cs">
<tr >
<th colspan="7">Термин $appointment</th>
</tr>
<tr>
<th>Име</th>
<th>Презиме</th>
<th>e-mail</th>
<th>Број телефона</th>
<th>Број личне карте</th>
<th>Локација</th>
<th>Потпис преузет</th>
</tr>
EOT;
$last_signatory[$appointment] = 1; //poslednji potpisnik do kojeg stizemo
$time_left = 12000000000;//postavljena je velika vrednost da se pokaze da algoritam radi lepo...
//echo"broj ljudi je ".count($signatories_by_appointment[$appointment]);
for ($i = 0; $i < count($signatories_by_appointment[$appointment]) - 1; $i++) {
//echo $signatories_by_appointment[$appointment][$i]["sign_id"] . "<br>";
$time_left -= 15; //oduzimamo petnaest minuta za potpis od potpisnika kod kojeg je organizator trenutno
$time_left -=
distance(
$signatories_by_appointment[$appointment][$i]["x_coordinate"],
$signatories_by_appointment[$appointment][$i + 1]["x_coordinate"],
$signatories_by_appointment[$appointment][$i]["y_coordinate"],
$signatories_by_appointment[$appointment][$i + 1]["y_coordinate"]
) / $organizer_speed;
//za svakog korisnika u ovom terminu do kojeg mozemo da stignemo, upisujemo u bazu taken_over=2
//belezimo koga smo rasporedili
$sql = "UPDATE sign SET taken_over=2 WHERE sign_id=" . $signatories_by_appointment[$appointment][$i]["sign_id"];
// echo $sql;
mysqli_query($link, $sql);
/* //za coveka koji je rasporedjen u ovaj termin, gledamo da li je bio i u drugim terminima i ako jeste, skidamo ga iz njih
foreach ($sorted_appointments as $other_appointment) {
if ($other_appointment != $appointment && in_array($signatories_by_appointment[$appointment][$i], $signatories_by_appointment[$appointment2])) {
}
} */
//echo"<br>$time_left<br>";
if ($time_left == 15) {
//kada vreme padne na 15 stizemo da uzmemo potpis od potpisnika kod kog smo dosli
$last_signatory[$appointment] = $i + 1;
$sql = "UPDATE sign SET taken_over=2 WHERE sign_id=" . $signatories_by_appointment[$appointment][$i + 1]["sign_id"];
// echo $sql;
mysqli_query($link, $sql);
break;
}
if ($time_left < 15) {
//ako je manje, ne stizemo, pa cemo tog potisnika izbaciti
$last_signatory[$appointment] = $i;
break;
} else {
$sql = "UPDATE sign SET taken_over=2 WHERE sign_id=" . $signatories_by_appointment[$appointment][$i + 1]["sign_id"];
// echo $sql;
mysqli_query($link, $sql);
$last_signatory[$appointment] = $i + 1;
}
}
//echo "<br>Posledji koji staje je ".$last_signatory[$appointment];
for ($i = 0; $i < count($signatories_by_appointment[$appointment]) ; $i++) {
// echo "<br>usao u petlju i=".$i."<br>";
$sign_id = $signatories_by_appointment[$appointment][$i]["sign_id"];
$name = $signatories_by_appointment[$appointment][$i]["name"];
$surname = $signatories_by_appointment[$appointment][$i]["surname"];
$email = $signatories_by_appointment[$appointment][$i]["email"];
$phone_number = $signatories_by_appointment[$appointment][$i]["phone_number"];
$id_number = $signatories_by_appointment[$appointment][$i]["id_number"];
$location_id = $signatories_by_appointment[$appointment][$i]["location_id"];
$taken_over = $signatories_by_appointment[$appointment][$i]["taken_over"];
$checked = "";
if ($taken_over != 0) {
$checked = "checked";
}
echo <<<EOT
<tr>
<td>$name</td>
<td>$surname</td>
<td><a href="mailto:$email">$email</a></td>
<td>$phone_number</td>
<td>$id_number</td>
<td>$location_id</td>
<td><input type="checkbox" name="taken_over[]" value="$sign_id" $checked></td>
</tr>
EOT;
}
} //za svaki termin
//niz u koji cemo za svaki termin staviti posledjeg potpinika do kojeg mozemo stici
echo <<<EOT
<tr><td colspan="7"><button class = "btn" type="submit" name="finish"> Сачувај </button></td></tr>
EOT;
mysqli_close($link);
}
}<file_sep>/insert_news.php
<?php
session_start();
if (isset($_SESSION["status"])) {
$id = $_SESSION["id"];
require_once("config.php");
if (isset($_POST["posalji"])) {
$naslov = $_POST["naslov"];
$datum = $_POST["datum"];
$vest = $_POST["message"];
}
$sql = "INSERT INTO news SET
title='$naslov',
date='$datum',
content='$vest',
organizer_administrator_id=$id; # -mora da postoji id organizatora da bi radilo
";
mysqli_query($link, $sql);
mysqli_close($link);
//vracanje na sign.html
$newURL = "news.html";
header('Location: ' . $newURL);
//die();
}<file_sep>/admin.html
<!DOCTYPE html>
<html>
<head>
<title>Администратор</title>
<meta charset="UTF-8" />
<link rel="shortcut icon" type="image/png" href="assets/favicon.png" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="head">
<div id="head-content">
<a href="index.html">
<div id="logo-container"><img src="assets/favicon.png" style="width: 100px; height: 100px;"
/></a></div>
<div id="naslov">Добродошли на Потпиши.ме!</div></div>
</div>
<div class="navigation">
<div id = "nav-container">
<a href="index.html">Насловна</a>
<a href="petition.html">Петиција</a>
<a href="news.html">Вести</a>
<a href="sign.html">Потпиши</a>
<div class="dropdown">
<button class="dropbtn">Организација</button>
<div class="dropdown-content">
<a href="locations.html">Локације</a>
<a href="organizer.html">Организатори</a>
<a href="complete_signatures.html">Комплетни потписи</a>
<a href="index.html">Излогујте се</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Унос</button>
<div class="dropdown-content">
<a href="news_entry.html">Унос вести</a>
<a href="organizer_entry.html">Унос организатора</a>
<a href="location_entry.html">Унос локације</a>
</div>
</div>
<a href="contact.html">Контакт</a>
</div>
</div>
<div class="content">
<div class="comments-container">
<h1>Коментари потписника</h1>
<?php include("get_comments.php")?>
<!--
<div class="comment">
<h4>Димитрије</h4>
Много ми се допада петици! Потписујем одмах. Надам се да ћемо успети заједно да променимо свет!
Много ми се допада петици! Потписујем одмах. Надам се да ћемо успети заједно да променимо свет!
Много ми се допада петици! Потписујем одмах. Надам се да ћемо успети заједно да променимо свет!
</div>
<hr />
<div class="comment">
<h4>Јелисавета</h4>
Појава нових вируса је увек изненађујућа, али не и неочекивана.
Број од преко 100.000 заражених на светском нивоу свакако захтева одређене додатне превентивне мере и поступања, посебно у односу на просторе које користе деца предшколског узраста и старе особе.
</div>
<hr />
<div class="comment">
<h4>Светислав</h4>
Здравствена служба у Србији почиње да се уводи и организује тек од Хатишерифа из 1830. године. У почетку је била у саставу Министарства унутрашњих послова (1835), потом Министарства просвете,
</div>
<hr />
<div class="comment">
<h4>Јоргованка</h4>
У овим најтежим тре је да је тужан што су је да је тужан што сунуцима у Србији је показана велика солидарност. Међу првима су у помоћ кренули врхунски спортисти, али и велики број клу
</div>
<hr />
<div class="comment">
<h4>Србољуб</h4>
Српски фудбалер Душко Тошић је да је тужан што су је да је тужан што су, члан Гванџуа, испричао је како је крајем јануара скоро последњим авионом напустио Кину.
</div>
<hr />
<div class="comment">
<h4>Будимирка</h4>
Крушевац - Председник ФК Напредак из Крушевца Марко Мишковић поднео је оставку после осам година на тој функцији. Мишковић, син власника компаније Делта Миросл
</div>
<hr />
<div class="comment">
<h4>Вукосава</h4>
Председник Европске фудбалске уније (Уефа) Александар Чеферин рекао је да ће ова сезона „вероватно бити изгубљена” ако се такмичења не настав
</div>
<hr />
<div class="comment">
<h4>Милојица</h4>
Млади српски фудбалер, је да је тужан што су је да је тужан што су је да је тужан што су је да је тужан што суиграч Реал Мадрида Лука Јовић пок је да је тужан што су је да је тужан што су је да је тужан што сулонио је 50.000 евра за куповину респиратора неопходних у
</div>
<hr />
<div class="comment">
<h4>Радашин</h4>
Најбољи тенисер света Новак Ђоковић рекао је д је да је тужан што су је да је тужан што су је да је тужан што суа је тужан што су Олимпијске игре одложене, али да је то права одлука због здравља
</div>
<hr />
-->
</div>
<div class="petition">
<h1>Петиција</h1>
<p>
СЛОБОДА ЗА САШКА-ПРАВДА ЗА СВЕ!
<NAME>, коме је 23.05. одређен притвор од 30 дана, бранећи своју зену и дете, ранио је човека, који је недуго након тога преминуо.
Инцидент се десио у уторак, 21.05. око поноћи, када је провалник <NAME> ушао кроз прозор стана породице Богески, дрзећи у руци шрафцигер.
По нашем закону, самоодбрана је у Србији тешко доказива.
Зато морамо да се организујемо и прузимо подршку овом цовеку!
</p>
<p>
Немојте да дозволите да овај човек заврши у затвору!
</p>
<p>
<NAME> је познати филантроп, који се годинама залаже за права маргинализованих група. Председник је НВО за промоцију етичких вредности у приватном и јавном животу, а годинама је радио у Библијској сколи где је помагао избеглицама из Хрватске, БиХ, Косова.
Такође је помагао и особама са инвалидитетом. Један је од оних који су довели Ника Вујичића у Београд.
Иза себе нема ниједно кривично дело, ни прекршај.
</p>
<p>
Потпишите ову петицију као знак ваше сагласности да овај човек МОРА да буде
пуштен из притвора и да му се не суди за класично убиство.
Желимо да се изборимо за промену закона који самоодбрану третира као убиство.
</p>
<p>
Ускоро ћемо у више градова организовати скупове подршке Саску.
Све нове информације имате на ФБ групи: хттпс://њњњ.фацебоок.цом/гроупс/подрска.саску/
</p>
<p>
Ми искрено жалимо због губитка једног људског живота, без обзира на све.
</p>
</div>
</div>
</div>
</body>
</html><file_sep>/login.php
<?php
// Initialize the session
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$email = $password = "";
$email_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["email"]))){
$email_err = "<NAME>а унесете мејл";
} else{
$email = trim($_POST["email"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "<PASSWORD>";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($email_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT organizer_administrator_id, email, password, approved FROM organizer_administrator WHERE email='".$email."'";
$result = mysqli_query($link,$sql);
echo $sql;
$temp = mysqli_fetch_array($result);
$id = $temp["organizer_administrator_id"];
$status = $temp["approved"];
if($status==2){
$status="admin";
}
else {
$status = "organizer";
}
if($temp["email"]==$_POST["email"]){
if($temp["password"]==$_POST["password"]){
session_id("idadminsesije");
session_start();
$_SESSION["loggedin"]=true;
$_SESSION["email"] = $email;
$_SESSION["id"] = $id;
$_SESSION["status"] = $status;
header("Location: index.html");
echo"Uspesno logovanje email:".$_SESSION["email"];
}else{
//ovde ce stajati kod za pogresan password
echo "Pogresan pass";
}
}else{
//ovde stoji kod koji se izvrsi ako ne postoji user sa datim mejlom... npr. prebacivanje na registration.php
echo "Ne postoji user sa datim mejlom";
}
// Close connection
mysqli_close($link);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/png" href="assets/favicon.png" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>Логовање</title>
</head>
<body>
<!-- <div class="head">
<div id="head-content">
<a href="index.html">
<div id="logo-container"><img src="assets/favicon.png" style="width: 100px; height: 100px;"
/></a></div>
<div id="naslov">Добродошли на Потпиши.ме!</div></div>
</div>
<div class="navigation">
<div id="nav-container">
<a href="index.html">Насловна</a>
<a href="petition.html">Петиција</a>
<a href="news.html">Вести</a>
<a href="sign.html">Потпиши</a>
<div class="dropdown">
<button class="dropbtn">Организација</button>
<div class="dropdown-content">
<a href="login.html">Улогуј се</a>
<a href="registration.html">Регистрација</a>
</div>
</div>
<a href="contact.html">Контакт</a>
</div>
</div> -->
<?php include("fixed.php")?>
<script src="inactive.js"></script>
<div class="content">
<div class="form-container">
<h1>Логовање</h1>
<div class="form" id="login">
<table>
<form method = "POST" action ="login.php">
<tr>
<td>е-mail: <input type="text" name="email"></td>
</tr>
<tr>
<td>Шифра: <input type="password" name="password"></td>
</tr>
<tr >
<td> <button class = "btn" style="margin-top: 10%;"><a href="admin.html";> Улогуј се</a></button></td>
</tr>
</form>
</table>
</div>
</div>
</body>
</html><file_sep>/save_update_organizers.php
<?php
session_start();
if (isset($_SESSION["status"]) && $_SESSION["status"] == "admin") {
require_once("config.php");
if (isset($_POST["update"])) {
$i = 1;
$data_set = [];
while (isset($_POST["id$i"])) {
$id = $_POST["id$i"];
$ime = $_POST["ime$i"];
$prezime = $_POST["prezime$i"];
$email = $_POST["email$i"];
$predlagac = $_POST["predlagac$i"];
$telefon = $_POST["telefon$i"];
$sifra = $_POST["sifra$i"];
$br_lk = $_POST["br_lk$i"];
$odobren = $_POST["odobren$i"];
//echo "<br>" . "Odobren $i :" . $odobren . "<br>";
$nevazeci = $_POST["nevazeci$i"];
$lose_preporuke = $_POST["lose_preporuke$i"];
$not_null_fields = array(
"id" => $id,
"ime" => $ime,
"prezime" => $prezime,
"email" => $email,
"predlagac" => $predlagac,
"telefon" => $telefon,
"sifra" => $sifra,
"br_lk" => $br_lk,
"odobren" => $odobren,
"nevazeci" => $nevazeci,
"lose_preporuke" => $lose_preporuke
);
array_push($data_set, $not_null_fields);
if (isset($_POST["brisi$i"])) {
$sql = "SELECT COUNT(*) AS broj FROM organizer_administrator
WHERE recommended_by_organizer_id =$id
";
$result = mysqli_query($link, $sql);
$arr=mysqli_fetch_assoc($result);
if($arr["broj"]!=0){
//ne moze se brisati
}else{
$sql = "DELETE FROM sign
WHERE location_id IN (
SELECT location_id FROM location WHERE organizer_id_chose=$id)
";
mysqli_query($link, $sql);
$sql = "DELETE FROM location
WHERE organizer_id_chose=$id;
";
mysqli_query($link, $sql);
$sql = "DELETE FROM organizer_administrator
WHERE organizer_administrator_id=$id;
";
mysqli_query($link, $sql);
}
}
$sql = "UPDATE organizer_administrator SET ";
if (!empty($ime))
$sql = $sql . "name='" . $ime . "',";
if (!empty($prezime))
$sql = $sql . "surname='" . $prezime . "',";
if (!empty($email))
$sql = $sql . "email='" . $email . "',";
if (!empty($predlagac))
$sql = $sql . "recommended_by_organizer_id='" . $predlagac . "',";
if (!empty($telefon))
$sql = $sql . "phone_number='" . $telefon . "',";
if (!empty($sifra))
$sql = $sql . "password='" . $<PASSWORD> . "',";
if (!empty($br_lk))
$sql = $sql . "id_number='" . $br_lk . "',";
// echo "<br>" . "Odobren $i :" . $odobren . "<br>";
//menjamo approved samo za one koji nisu admini. admin je uvek 2
if ($odobren != '2') {
if (isset($_POST["odobren$i"])) {
$sql = $sql . "approved='" . "1" . "',";
// echo "JESTE SETOVANO!!!!!!!!!!!!!!!!!!! $odobren";
} else {
$sql = $sql . "approved='" . "0" . "',";
// echo "NIJE SETOVANO!!!!!!!!!!!!!!!";
}
}
if (!empty($nevazeci))
$sql = $sql . "invalid_signature_count='" . $nevazeci . "',";
if (!empty($lose_preporuke))
$sql = $sql . "bad_recommendation_count='" . $lose_preporuke . "',";
$sql = substr($sql, 0, -1); //sklanjamo poslednji zarez iz sql stringa
$sql = $sql . "WHERE organizer_administrator_id=$id;";
//echo $sql;
//echo "\n";
/* $sql = "UPDATE organizer_administrator SET
name='$ime',
surname='$prezime',
email='$email',
recommended_by_organizer_id='$predlagac',
phone_number='$telefon',
password='<PASSWORD>',
id_number='$br_lk',
approved='$odobren',
invalid_signature_count='$nevazeci',
bad_recommendation_count='$lose_preporuke'
WHERE organizer_administrator_id=$id;
"; */
mysqli_query($link, $sql);
$i++;
}
}
mysqli_close($link);
//vracanje na sign.html
$newURL = "organizer.html";
header('Location: ' . $newURL);
//die();
} else {
echo "НЕМАТЕ ПРИСТУП, УЛОГУЈТЕ СЕ КАО АДМИН!";
sleep(5);
$newURL = "login.php";
header('Location: ' . $newURL);
die();
}<file_sep>/create_database.php
<?php
$link=mysqli_connect("localhost:3308", "root","","petition");
$sql="CREATE SCHEMA IF NOT EXISTS `Petition` DEFAULT CHARACTER SET utf8 ;
USE `Petition` ;
CREATE TABLE IF NOT EXISTS `Petition`.`Location` (
`Location_id` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NOT NULL,
`Address` VARCHAR(45) NULL,
`municipality` VARCHAR(45) NULL,
`xcoordinate` DOUBLE NOT NULL,
`ycoordinate` DOUBLE NOT NULL,
PRIMARY KEY (`Location_id`),
)
CREATE TABLE IF NOT EXISTS `Petition`.`Sign` (
`Sign_id` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NOT NULL,
`Surname` VARCHAR(45) NOT NULL,
`Phone_Number` VARCHAR(45) NULL,
`Email` VARCHAR(45) NULL,
`personal_id_number` VARCHAR(45) NULL,
`Location_id` INT NOT NULL,
`Number_Of_Appointments` INT NOT NULL,
`Appointments` VARCHAR(100) NOT NULL,
`Email_Info` TINYINT NULL,
`Public_Signature` TINYINT NULL,
PRIMARY KEY (`Sign_id`),
CONSTRAINT `Location_id`
FOREIGN KEY (`Location_id`)
REFERENCES `Petition`.`Location` (`Location_id`)
)
";
mysqli_query($link,$sql);
mysqli_close($link);
?><file_sep>/save_update_locations.php
<?php
if (isset($_POST["update"])){
require_once("config.php");
$i=1;
while($_POST["id$i"]){
$id=$_POST["id$i"];
$naziv= $_POST["naziv$i"];
$grad= $_POST["grad$i"];
$opstina= $_POST["opstina$i"];
$ulica= $_POST["ulica$i"];
$x= $_POST["x$i"];
$y= $_POST["y$i"];
if (isset($_POST["brisi$i"])) {
$sql = "DELETE FROM sign
WHERE location_id=$id;
";
mysqli_query($link,$sql);
$sql = "DELETE FROM location
WHERE location_id=$id;
";
mysqli_query($link,$sql);
}
$sql = "UPDATE location SET
name='$naziv',
city='$grad',
municipality='$opstina',
street='$ulica',
x_coordinate='$x',
y_coordinate='$y'
WHERE location_id=$id;
";
mysqli_query($link,$sql);
$i++;
}
}
mysqli_close($link);
//vracanje na sign.html
$newURL = "locations.html";
header('Location: '.$newURL);
die();
?>
<file_sep>/get_complete_signatures.php
<?php
require_once("config.php");
$upit = "SELECT * FROM sign;";
$rez = mysqli_query($link, $upit);
while ($podaci = mysqli_fetch_assoc($rez)) {
$ime = $podaci['name'];
$prezime = $podaci['surname'];
$mail = $podaci['email'];
$licna = $podaci['id_number'];
$javniPotpis = $podaci['publish'];
$telefon = $podaci['phone_number'];
$komentar = $podaci['comment'];
$lokacija = $podaci['location_id'];
$broj_termina = $podaci['appointment_count'];
$termini = $podaci['appointments'];
$preuzet = $podaci['taken_over'];
$email_obavestenje = $podaci['email_notification'];
if ($javniPotpis == 1) {
$javniPotpis = 'ДА';
} else $javniPotpis = 'НЕ';
if ($preuzet == 1) {
$preuzet = 'ДА';
} else $preuzet = 'НЕ';
if ($email_obavestenje == 1) {
$email_obavestenje = 'ДА';
} else $email_obavestenje = 'НЕ';
echo <<<EOT
<tr>
<td>$ime</td>
<td>$prezime</td>
<td><a href="mailto:$mail">$mail</a></td>
<td>$telefon</td>
<td>$licna</td>
<td>$lokacija</td>
<td>$javniPotpis</td>
<td>$email_obavestenje</td>
<td>$preuzet</td>
<td>$komentar</td>
</tr>
EOT;
}
if ($_SESSION["status"] == "admin") {
echo <<<EOT
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td><td colspan="2"> <button class = "btn" type="submit" name="posalji"><a href="update_complete_signature.html">Измени </a></button></td></td></tr>
EOT;
}
mysqli_close($link);<file_sep>/get_locations_sign.php
<?php
require_once("config.php");
$upit="SELECT * FROM location;";
$rez=mysqli_query($link,$upit);
$i=1;
while($podaci=mysqli_fetch_assoc($rez)){
$grad=$podaci['city'];
$ulica=$podaci['street'];
echo<<<EOT
<option value="$i">$grad, $ulica</option>
EOT;
$i++;
}
mysqli_close($link);
?><file_sep>/dynamic_appointments.js
function myFunction(val) {
var container = document.getElementById("div_termin");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for(i=1; i<=val;i++){
var input = document.createElement("input");
input.type = "text";
input.name = "termin" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
<file_sep>/finish.php
<?php
session_start();
require_once("config.php");
if(isset($_SESSION["status"]) && isset($_POST["finish"])){
for ($i=0; $i < count($_POST["taken_over"]); $i++) {
if(isset($_POST["taken_over"]))
echo " potpis prikupljen ".$_POST["taken_over"][$i]."<br>";
$id=$_POST["taken_over"][$i];
$sql="UPDATE sign set taken_over=1 where sign_id=$id ";
mysqli_query($link,$sql);
}
}
$sql="UPDATE sign set taken_over=0 where taken_over=2";
mysqli_query($link,$sql);
//vracanje na sign.html
$newURL = "complete_signatures.html";
header('Location: '.$newURL);
die();
<file_sep>/save_update_complete_signatures.php
<?php
session_start();
if (isset($_POST["update"]) && isset($_SESSION["status"]) && $_SESSION["status"] == "admin") {
echo "pocelo je";
require_once("config.php");
$i = 1;
while (isset($_POST["id$i"])) {
$id = $_POST["id$i"];
$ime = $_POST["ime$i"];
$prezime = $_POST["prezime$i"];
$email = $_POST["email$i"];
$telefon = $_POST["telefon$i"];
$br_lk = $_POST["br_lk$i"];
$lokacija = $_POST["lokacija$i"];
$javniPotpis = $_POST["javniPotpis$i"];
$email_obavestenje = $_POST["email_obavestenje$i"];
$preuzet = $_POST["preuzet$i"];
$komentar = $_POST["komentar$i"];
if (isset($_POST["brisi$i"])) {
$sql = "DELETE FROM sign
WHERE sign_id=$id;
";
mysqli_query($link, $sql);
}
$sql = "UPDATE sign SET
name='$ime',
surname='$prezime',
email='$email',
phone_number='$telefon',
id_number='$br_lk',
location_id='$lokacija',
publish='$javniPotpis',
email_notification='$email_obavestenje',
taken_over='$preuzet',
comment='$komentar'
WHERE sign_id=$id;
";
echo $sql;
mysqli_query($link, $sql);
$i++;
}
mysqli_close($link);
}
//vracanje na sign.html
$newURL = "complete_signatures.html";
header('Location: ' . $newURL);
die();
|
09926cfed590c3aa5beb07c79ce6fc915c1a9051
|
[
"JavaScript",
"HTML",
"PHP"
] | 26
|
PHP
|
bpavle/PetitionWebsite
|
fa73eeb6b7e06375857dd4ca604d289c75dd3404
|
878a960687296073cf993ff56296189b1f93b56b
|
refs/heads/master
|
<repo_name>jinternals/spring-boot-s2i<file_sep>/Dockerfile
# spring-boot
FROM openshift/base-centos7
MAINTAINER <NAME> <<EMAIL>>
ENV JAVA_VERSON 1.8.0
ENV MAVEN_VERSION 3.3.9
LABEL io.k8s.description="Platform for building Spring boot application" \
io.k8s.display-name="Spring boot maven builder" \
io.openshift.expose-services="8080:http" \
io.openshift.tags="builder,springboot,maven-3,java-8"
RUN yum update -y && \
yum install -y curl && \
yum install -y java-$JAVA_VERSON-openjdk java-$JAVA_VERSON-openjdk-devel && \
yum clean all
RUN curl -fsSL https://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xzf - -C /usr/share \
&& mv /usr/share/apache-maven-$MAVEN_VERSION /usr/share/maven \
&& ln -s /usr/share/maven/bin/mvn /usr/bin/mvn
ENV JAVA_HOME /usr/lib/jvm/java
ENV MAVEN_HOME /usr/share/maven
RUN mkdir -p /opt/app-root/src && chmod -R a+rwX /opt/app-root/src
# TODO (optional): Copy the builder files into /opt/app-root
# COPY ./<builder_folder>/ /opt/app-root/
COPY ./s2i/bin/ /usr/libexec/s2i
RUN chown -R 1001:1001 /opt/app-root
USER 1001
# TODO: Set the default port for applications built using this image
EXPOSE 8080
# TODO: Set the default CMD for the image
CMD ["/usr/libexec/s2i/usage"]
<file_sep>/s2i/bin/assemble
#!/bin/bash -e
#
# S2I assemble script for the 'spring-boot' image.
# The 'assemble' script builds your application source so that it is ready to run.
#
# For more information refer to the documentation:
# https://github.com/openshift/source-to-image/blob/master/docs/builder_image.md
#
# If the 'spring-boot' assemble script is executed with the '-h' flag, print the usage.
if [[ "$1" == "-h" ]]; then
exec /usr/libexec/s2i/usage
fi
# Restore artifacts from the previous build (if they exist).
#
if [ "$(ls /tmp/artifacts/ 2>/dev/null)" ]; then
echo "---> Restoring build artifacts..."
mv /tmp/artifacts/. ./
fi
echo "---> Installing application source..."
cp -Rf /tmp/src/. ./src
echo "---> Building spring boot application from source..."
echo "---> MVN_ARGS = '$MVN_ARGS'"
cd ./src
if [ -f "mvnw" ]; then
./mvnw clean install $MVN_ARGS
else
mvn clean install $MVN_ARGS
fi
cp -Rf ./target/*.jar ../
echo "---> Removing source code..."
rm -r ./src
|
892cb6fcd6a0324be622170fc65099e6bc1e09a4
|
[
"Dockerfile",
"Shell"
] | 2
|
Dockerfile
|
jinternals/spring-boot-s2i
|
e77a76ee4ce540dda934f33421e2d27d83cb8c1a
|
eeac99de53bd550e7c0943e7ef991ec9bbc36699
|
refs/heads/master
|
<repo_name>aganesh5663/Deep3D_TF<file_sep>/README.md
# Tensorflow Deep3D
This is a Tensorflow implemention of Deep3D (The original MXNet implementation can be found in the github repository: <a href="https://github.com/piiswrong/deep3d">Deep3D-MXNet</a>. The <a href="https://arxiv.org/abs/1604.03650">published paper</a> describes the development and performance of the original network. There is a lot of work to be done for this ported model!
* Refactor and port over NumPy weights to Tensorflow loading methods
* Add training persistance
* Train WAY longer on hollywood Dataset
* Explore TensorServe API for web hosting + experiment with Ruby API
**Presentation Slides:** https://goo.gl/iijL3X
<img src="https://github.com/JustinTTL/Deep3D_TF/blob/master/viz/graph_run.png" width="700">
The backbone of this network is built from the github repository of an <a href="https://github.com/machrisaa/tensorflow-vgg">implementation of VGG19</a>.
## Some Results
<img src="https://github.com/JustinTTL/Deep3D_TF/blob/master/viz/dancegirl.gif" width="700">
<img src="https://github.com/JustinTTL/Deep3D_TF/blob/master/viz/horse.png" width="700">
<img src="https://github.com/JustinTTL/Deep3D_TF/blob/master/viz/depth.gif" width="700">
<img src="https://github.com/JustinTTL/Deep3D_TF/blob/master/viz/frodo.gif" width="700">
<file_sep>/data/README.md
# Data Pull
This folder contains scripts to pull and pre-process data. Beware, some scripts will take a very long time to run
## To run
python get_inria3D.py
## Dependencies needed
skimage, h5py
Simply install via pip
## Output of scripts
The output X,Y files will be written to disk
in h5py numpy arrays files. It is advised to
load local copies instead of re-downloading and processing.
__To Extract__
```python
h5f = h5py.File('filename.h5','r')
X = h5f['X'][:]
Y = h5f['Y'][:]
h5f.close()
```
<file_sep>/data/get_inria3D.py
# Script to download, untar and extract the inria dataset
import sys
import shutil
import skimage
import skimage.io
import skimage.transform
import numpy as np
import os, tarfile
import h5py
def resize_scale_img(path, dims = (180, 320), scale = False):
img = skimage.io.imread(path)
# Scale down color channels
if scale:
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# Resize
resized_img = skimage.transform.resize(img, dims, mode = "reflect")
return resized_img
def download_inria():
import urllib2
urls = ["http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_segmentation.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_video_segmentation.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_persondetection_train.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_persondetection_test.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_poseestimation_train.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_poseestimation_test.tar",
"http://www.di.ens.fr/willow/research/stereoseg/dataset/inria_stereo_dataset_negatives.tar"]
for url in urls:
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
def extract_tar():
dir_name = os.getcwd()
extension = ".tar"
print "Extracting all .tar directories ..."
for item in os.listdir(dir_name):
if item.endswith(extension):
file_name = os.path.abspath(item)
tar_ref = tarfile.open(file_name)
tar_ref.extractall()
tar_ref.close()
os.remove(file_name)
print "Untarred: " + item
#Remove Viz Folders with only generic jpg frames
print "Removing Viz Folders"
dir_name = os.getcwd()
try:
viz1_path = dir_name+"/inria_stereo_dataset/poseestimation_test/visualization"
viz2_path = dir_name+"/inria_stereo_dataset/poseestimation_train/visualization"
shutil.rmtree(viz1_path)
shutil.rmtree(viz2_path)
except:
pass
def load_inria_frame(dims = (180,320), terminate = None, prob = 0.2):
print "Collecting Inria Dataset Frames"
# Recursively walk down directorie and collect Frames and concat to X and Y
cur_dir = os.getcwd()
l_ext = ".jpg"
r_ext = ".right"
out_ext = ".jpeg"
# Add directories
if not os.path.exists(os.path.join(cur_dir, "frames")):
print "Creating Frames Folder... "
os.makedirs(os.path.join(cur_dir, "frames", "train", "left"))
os.makedirs(os.path.join(cur_dir, "frames", "train", "right"))
os.makedirs(os.path.join(cur_dir, "frames", "test", "left"))
os.makedirs(os.path.join(cur_dir, "frames", "test", "right"))
# Calculate Total Frames
count = 0
tot_count = 0
for root, dirs, files in os.walk(cur_dir, topdown=False):
for file in files:
if file.endswith(l_ext):
tot_count = tot_count + 2
terminate_count = tot_count
if terminate is not None:
if terminate * 2 > tot_count:
print "Error: Requested number of pairs larger than total number of pairs avail"
return
terminate_count = terminate * 2
print "Collecting " + str(terminate_count) + " frames and downsampling them."
print "This will take awhile, be patient =D."
# Create seeded mask for determining Test/Train Split
np.random.seed(100)
test_mask = np.random.choice([0,1], size =(terminate_count/2,), p = [1-prob, prob])
# The actual walk
for root, dirs, files in os.walk(cur_dir, topdown = True):
for file in files:
if file.endswith(l_ext):
path = os.path.join(root, file)
try:
l_frame = resize_scale_img(path, dims)
r_frame = resize_scale_img(path+r_ext, dims)
# Write back to disk in designated Folder
if test_mask[count/2] == 0:
folder = "train"
else:
folder = "test"
l_path = os.path.join(cur_dir, "frames", folder, "left", str(count/2)+out_ext)
r_path = os.path.join(cur_dir, "frames", folder, "right", str(count/2)+out_ext)
skimage.io.imsave(l_path, l_frame)
skimage.io.imsave(r_path, r_frame)
count = count + 2
except IOError:
print "IO Error (Missing Right Frame/Mem Limit/etc) , Ignoring Entry"
if count % 250 == 0 and count != 0:
print "(" + str(count) + "/" + str(terminate_count) + ")"
if count == terminate_count:
break
if count == terminate_count:
break
return
# H5 Writing to Disk Function
def write_to_disk(X, Y, f_name, ds_ext):
print "Writing " + "X_/Y_" + ds_ext + " to " + f_name
h5f = h5py.File(f_name, 'a')
h5f.create_dataset('X_'+ds_ext, data=X)
h5f.create_dataset('Y_'+ds_ext, data=Y)
h5f.close()
print "Write Complete"
# -------------------------------------------------------------- #
def main():
import time
start = time.time()
if os.path.exists('inria_stereo_dataset/'):
print "Inria data already downloaded. Using cached files"
else:
download_inria()
extract_tar()
load_inria_frame()
end = time.time()
print "Extraction Completed... Took " + str((end - start)/60) + " minutes"
if __name__ == "__main__":
main()
<file_sep>/hyperparam_search.py
import tensorflow as tf
import Deep3D_branched as deep3d
import utils
import numpy as np
import os
import os.path
import h5py
from collections import defaultdict
import pickle
def main():
#importing data
inria_file = '/a/data/deep3d_data/inria_data.h5'
# inria_file = 'data/inria_data.h5'
h5f = h5py.File(inria_file,'r')
X_train_0 = h5f['X_0'][:,10:170,16:304,:]
Y_train_0 = h5f['Y_0'][:,10:170,16:304,:]
X_train_1 = h5f['X_1'][:,10:170,16:304,:]
Y_train_1 = h5f['Y_1'][:,10:170,16:304,:]
X_train_2 = h5f['X_2'][:,10:170,16:304,:]
Y_train_2 = h5f['Y_2'][:,10:170,16:304,:]
X_train_3 = h5f['X_3'][:,10:170,16:304,:]
Y_train_3 = h5f['Y_3'][:,10:170,16:304,:]
X_train_4 = h5f['X_4'][:,10:170,16:304,:]
Y_train_4 = h5f['Y_4'][:,10:170,16:304,:]
X_train_5 = h5f['X_5'][:,10:170,16:304,:]
Y_train_5 = h5f['Y_5'][:,10:170,16:304,:]
X_train_6 = h5f['X_6'][:,10:170,16:304,:]
Y_train_6 = h5f['Y_6'][:,10:170,16:304,:]
h5f.close()
X_train = np.concatenate([X_train_0,X_train_1,X_train_2,X_train_3,X_train_4,X_train_5,X_train_6])
Y_train = np.concatenate([Y_train_0,Y_train_1,Y_train_2,Y_train_3,Y_train_4,Y_train_5,Y_train_6])
batchsize = 50
num_epochs = 5
num_batches = (X_train.shape[0]/batchsize)*num_epochs
save_step = 10
cost_dict = defaultdict()
powers = np.linspace(-5,-2,8)
learning_rates = [np.power(10,power) for power in powers]
optimizers = ['adam','momentum']
momentums = np.linspace(0,1,4)
momentums = (0.98-0.14*momentums)
count = 0
search_count = len(optimizers) * len(learning_rates) + 2 * len(learning_rates) * (len(momentums)-1)
for optimizer in optimizers:
for momentum in momentums:
for lr in learning_rates:
print 'optimizer: ' + optimizer + ' momentum: ' + str(momentum) + ' learning rate: ' + str(lr)
#initialize list to store outputs of run
out_list = []
# Define config for GPU memory debugging
config = tf.ConfigProto()
config.gpu_options.allow_growth=True # Switch to True for dynamic memory allocation instead of TF hogging BS
config.gpu_options.per_process_gpu_memory_fraction= 1 # Cap TF mem usage
config.allow_soft_placement=True
with tf.device('/gpu:0'):
# Session
sess = tf.Session(config=config)
# Placeholders
images = tf.placeholder(tf.float32, [None, 160, 288, 3], name='input_batch')
true_out = tf.placeholder(tf.float32, [None, 160, 288, 3] , name='ground_truth')
train_mode = tf.placeholder(tf.bool, name='train_mode')
# Building Net based on VGG weights
net = deep3d.Deep3Dnet('./vgg19.npy', dropout = 0.5)
net.build(images, train_mode)
# Define Training Objectives
with tf.variable_scope("Loss"):
#reg_factor = 1e-5
cost = tf.reduce_sum(tf.abs(net.prob - true_out))/batchsize
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
if optimizer == 'adam':
train = tf.train.AdamOptimizer(learning_rate=lr,beta1=momentum).minimize(cost)
if optimizer == 'momentum':
train = tf.train.MomentumOptimizer(learning_rate=lr, momentum=momentum).minimize(cost)
# Run initializer
sess.run(tf.global_variables_initializer())
# Track Cost
tf.summary.scalar('cost', cost)
# Training Loop
for i in xrange(num_batches):
# Creating Batch
image_mask = np.random.choice(X_train.shape[0],batchsize)
images_in = X_train[image_mask,:,:,:]
labels_in = Y_train[image_mask,:,:,:]
# Traing Step
_, cost_val = sess.run([train, cost], feed_dict={images: images_in, true_out: labels_in, train_mode: True})
#storing in cost_dict
out_list.append(cost_val)
#saves cost outputs and clears graph for next iteration
cost_dict[optimizer,lr,momentum] = out_list
tf.reset_default_graph()
#closing out search iteration
count += 1
print "finished hyperparam: " + str(count) + ' of ' + str(search_count)
print ""
# Save a cost outputs into a pickle file.
pickle.dump(cost_dict, open( "cost_outputs.p", "wb" ) )
return 0
if __name__ == "__main__":
main()<file_sep>/selection.py
import numpy as np
import tensorflow as tf
import skimage
import skimage.io
import skimage.transform
import numpy as np
def select(masks, left_image, left_shift=16, name="select"):
'''
assumes inputs:
masks, shape N, H, W, S
left_image, shape N, H, W, C
returns
right_image, shape N, H, W, C
'''
_, H, W, S = masks.get_shape().as_list()
with tf.variable_scope(name):
padded = tf.pad(left_image, [[0,0],[0,0],[left_shift, left_shift],[0,0]], mode='REFLECT')
# padded is the image padded whatever the left_shift variable is on either side
layers = []
for s in np.arange(S):
layers.append(tf.slice(padded, [0,0,s,0], [-1,H,W,-1]))
slices = tf.stack(layers, axis=4)
disparity_image = tf.multiply(slices, tf.expand_dims(masks, axis=3))
return tf.reduce_sum(disparity_image, axis=4)
#layers = tf.zeros_like(left_image)
#for s in np.arange(S):
# mask_slice = tf.slice(masks, [0,0,0,s], [-1, H, W, 1])
# pad_slice = tf.slice(padded, [0,0,s,0], [-1,H,W,-1])
# layers = tf.add(layers, tf.multiply(mask_slice, pad_slice))
#return layers
# YOU CAN IGNORE THE FOLLOWING:
def compose(masks, left_image, left_shift=16):
'''
THIS FUNCTION IS ASSUMING WIDTH IS ON AXIS 1, MASK AXIS IS 3
Takes disparity masks and applies pixel selection to generate a right frame
Inputs:
masks: narray of shape (N, W, H, S)
left_images: narray of shape (N, W, H, C)
left_shift: maximum pixel left shift
Outputs:
right_images: narray of shape (N, W, H)
'''
N, H, W, C = masks.get_shape().as_list()
C = left_image.shape[3]
shift_images = np.zeros([N,W,H,C,S])
for s in np.arange(S):
shift_images[:,:,:,:,s] = np.roll(left_image, s-left_shift, axis=1) #width is axis 1
right_image = np.sum(shift_images * masks, axis=4) #mask axis is 4
return right_image
if __name__ == '__main__':
sess = tf.InteractiveSession()
image_contents = tf.read_file('./test_data/tiger.jpeg')
image = tf.image.decode_jpeg(image_contents,channels=3)
print image.eval().shape
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# print "Original Image Shape: ", img.shape
# resize to 224, 224
resized_img = skimage.transform.resize(img, (180, 320))
return resized_img
<file_sep>/train_D3D.py
import tensorflow as tf
import Deep3D_Final as deep3d
import utils
import numpy as np
import os
import os.path
from collections import defaultdict
import pickle
import sys
def train(in_path, out_path):
print "-- Training Deep3D --"
# Calculate number of iterations
batchsize = 30
num_epochs = 5
left_dir = "/a/data/deep3d_data/frames2/left/"
right_dir = "/a/data/deep3d_data/frames2/right/"
iter_per_epoch = (len(os.listdir(left_dir))/batchsize)
num_iter = iter_per_epoch * num_epochs
print "Number of Training Iterations : " + str(num_iter)
validation_size = 2000
# Learning Rates
lr = 0.00005
# b1 = 0.9
# b2 = 0.99
# Define CPU operations for filename queue and random shuffle batch queue
with tf.device('/cpu:0'):
left_image_queue = tf.train.string_input_producer(
left_dir + tf.convert_to_tensor(os.listdir(left_dir)[:-validation_size:]),
shuffle=False, num_epochs=num_epochs)
right_image_queue = tf.train.string_input_producer(
right_dir + tf.convert_to_tensor(os.listdir(right_dir)[:-validation_size:]),
shuffle=False, num_epochs=num_epochs)
# use reader to read file
image_reader = tf.WholeFileReader()
_, left_image_raw = image_reader.read(left_image_queue)
left_image = tf.image.decode_jpeg(left_image_raw)
left_image = tf.cast(left_image, tf.float32)/255.0
_, right_image_raw = image_reader.read(right_image_queue)
right_image = tf.image.decode_jpeg(right_image_raw)
right_image = tf.cast(right_image, tf.float32)/255.0
left_image.set_shape([160,288,3])
right_image.set_shape([160,288,3])
# preprocess image
batch = tf.train.shuffle_batch([left_image, right_image],
batch_size = batchsize,
capacity = 12*batchsize,
num_threads = 1,
min_after_dequeue = 4*batchsize)
# ------ GPU Operations ---------- #
# Define config for GPU memory debugging
config = tf.ConfigProto()
config.gpu_options.allow_growth=True # Switch to True for dynamic memory allocation instead of TF hogging BS
config.gpu_options.per_process_gpu_memory_fraction= 1 # Cap TF mem usage
config.allow_soft_placement=True
# Session
sess = tf.Session(config=config)
# Placeholders
images = tf.placeholder(tf.float32, [None, 160, 288, 3], name='input_batch')
true_out = tf.placeholder(tf.float32, [None, 160, 288, 3] , name='ground_truth')
train_mode = tf.placeholder(tf.bool, name='train_mode')
# Building Net based on VGG weights
net = deep3d.Deep3Dnet(in_path, dropout = 0.5)
net.build(images, train_mode)
# Print number of variables used
print 'Variable count:'
print(net.get_var_count())
# Define Training Objectives
with tf.variable_scope("Loss"):
cost = tf.reduce_sum(tf.abs(net.prob - true_out))/batchsize
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train = tf.train.AdamOptimizer(learning_rate=lr).minimize(cost)
# Run initializer
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
queue_threads = tf.train.start_queue_runners(coord=coord, sess=sess)
# Track Cost
tf.summary.scalar('cost', cost)
# Tensorboard operations to compile summary and then write into logs
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('./final_trainlog/', graph = sess.graph)
# ---------- Training Loop --------------- #
print ""
print ">> Start training <<"
print_step = 1
save_step = 25
print "saving every " + str(save_step) + " iterations"
# Base case data fetch
next_batch = sess.run(batch)
count = 0
try:
while not coord.should_stop():
# Traing Step
_, cost_val, next_batch, summary,up_conv = sess.run([train, cost, batch, merged,net.up_conv],
feed_dict={images: next_batch[0],
true_out: next_batch[1],
train_mode: True})
writer.add_summary(summary, count)
if count%print_step == 0:
print str(count).ljust(10) + ' | Cost: ' + str(cost_val).ljust(10) + ' | UpConv Max: ' + str(np.mean(up_conv, axis =(0,1,2)).max())
if count%save_step == 0:
print "Checkpoint Save"
net.save_npy(sess, npy_path = out_path)
count = count + 1
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
# When done, ask the threads to stop.
coord.request_stop()
# Store Final Traing Output
print ""
print "Training Completed, storing weights"
net.save_npy(sess, npy_path = out_path)
# Terminate session
coord.join(queue_threads)
sess.close()
if __name__ == "__main__":
if len(sys.argv) != 3:
print "Invalid Arguements. Give 1) input weights file 2) output weight file"
else:
train(sys.argv[1], sys.argv[2])
|
787d752f3b9d61ca8eb886e7609487a06e66a96b
|
[
"Markdown",
"Python"
] | 6
|
Markdown
|
aganesh5663/Deep3D_TF
|
00abeff58b9f5b4c03ffaf3bb64696c015c52fab
|
6b5534743450513a29d76e2517e68be73c09e035
|
refs/heads/master
|
<file_sep>[](https://travis-ci.org/santosfrancisco/gatsby-starter-cv)
[](https://badge.fury.io/gh/santosfrancisco%2Fgatsby-starter-cv)
[](http://commitizen.github.io/cz-cli/)
<p align="center">
<a href="https://www.gatsbyjs.org">
<img alt="Gatsby" src="https://www.gatsbyjs.org/monogram.svg" width="60" />
</a>
</p>
<h1 align="center">
Gatsby's CV starter
</h1>
Create your resume in a few minutes with this totally responsive starter using React. Show off your skills, work experiences and activities in github.
### Sections
- About
- Skills
- Job experiences
- Github repositories
- Portifolio
### Features
- Responsive Design, optimized for Mobile devices
- Google Analytics
- SEO
- PWA
- Dark mode
- Animations
## 📷 Preview
### Mobile

### Desktop

## 🚀 Quick start
1. **Create a Gatsby site.**
Use the Gatsby CLI to create a new site, specifying the default starter.
```sh
# create a new Gatsby site using the default starter
npx gatsby new my-default-starter https://github.com/santosfrancisco/gatsby-starter-cv
```
2. **Start developing.**
Navigate into your new site’s directory and start it up.
```sh
cd my-default-starter/
npm run develop
```
3. **Open the source code and start editing!**
Your site is now running at `http://localhost:8000`!
\_Note: You'll also see a second link: `http://localhost:8000/___graphql`. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.org/tutorial/part-five/#introducing-graphiql).\_
Open the `my-default-starter` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes and the browser will update in real time!
4. **Generate production build**
That command will generate a production build on _public_ folder
```sh
npm run build
```
5. **Deploy to Github pages**
That command will deploy the production build to gh-pages branch of your repository
> ⚠️ don't forget to check `pathPrefix` in the configuration file.
```sh
npm run deploy
```
## Configuration
Update the configuration file with your data. The configuration file is in `data/siteConfig.js`
:warning: NOTE: Please change googleAnalyticsId to your ID. See https://analytics.google.com for details.
> **Skills** is a set of your personal skills and their respective levels ranging from > 0 to 100.
> **jobs** is a set of your work experiences
```js
module.exports = {
siteTitle: '',
siteDescription: `Create your online curriculum in just a few minutes with this starter`,
keyWords: ['gatsbyjs', 'react', 'curriculum'],
authorName: '<NAME>',
twitterUsername: '_franciscodf',
githubUsername: 'santosfrancisco',
authorAvatar: '/images/avatar.jpeg',
authorDescription: `Developer, passionate about what I do. Always interested in how the sites were made, I started to study HTML by hobby. <br />
In 2012 I started working as a support technician and I approached the developers.
In 2015, I started to study C # and started to contribute with the team giving maintenance in an application in C # and .NET. <br />
I currently work as a frontend developer and mainly work with <strong>Javascript, NodeJS e React.</strong>`,
skills: [
{
name: 'HTML',
level: 70,
},
{
name: 'CSS',
level: 60,
},
{
name: 'Javascript',
level: 50,
},
{
name: 'NodeJs',
level: 40,
},
{
name: 'React',
level: 60,
},
{
name: 'Git',
level: 70,
},
/* more skills here */
],
jobs: [
/* more jobs here */
{
company: 'Gympass',
begin: {
month: 'sep',
year: '2019',
},
duration: null,
occupation: 'Frontend developer',
description:
'I am part of the Corporate team, responsible for the development and maintenance of the employee management platform, giving more and more autonomy to partner companies.',
},
{
company: 'Lendico',
begin: {
month: 'apr',
year: '2018',
},
duration: null,
occupation: 'Frontend developer',
description:
'I integrate the Frontend team responsible for developing and maintaining the online lending platform.',
},
{
company: 'Anapro',
begin: {
month: 'dec',
year: '2016',
},
duration: '1 yr e 5 mos',
occupation: 'Fullstack developer',
description:
'Development and maintenance, corrective and preventive, of web applications for the real estate market.',
},
{
company: 'Anapro',
begin: {
month: 'set',
year: '2012',
},
duration: '4 yrs e 3 mos',
occupation: 'Support Technician',
description:
'Responsible for the implementation and parameterization of the system, training and customer support. Acting also in person in real estate launches guaranteeing the success and good use of the tool.',
},
],
portifolio: [
{
image: '/images/gatsby-starter-cv.png',
description: 'Gatsby starter CV template',
url:
'https://www.gatsbyjs.org/starters/santosfrancisco/gatsby-starter-cv/',
},
{
image: '/images/awesome-grid.png',
description: 'Responsive grid for ReactJS',
url: 'https://github.com/santosfrancisco/react-awesome-styled-grid',
},
/* more portifolio items here */
],
social: {
twitter: 'https://twitter.com/_franciscodf',
linkedin: 'https://www.linkedin.com/in/santos-francisco',
github: 'https://github.com/santosfrancisco',
email: '<EMAIL>',
},
siteUrl: 'https://santosfrancisco.github.io/gatsbystarter-cv',
pathPrefix: '/gatsby-starter-cv', // Note: it must *not* have a trailing slash.
siteCover: '/images/cover.jpeg',
googleAnalyticsId: 'UA-000000000-1',
background_color: '#ffffff',
theme_color: '#25303B',
fontColor: '#000000cc',
enableDarkmode: true, // If true, enables dark mode switch
display: 'minimal-ui',
icon: 'src/assets/gatsby-icon.png',
headerLinks: [
{
label: 'Home',
url: '/',
},
{
label: 'Portifolio',
url: '/portifolio',
},
],
}
```
## It was useful?
<a href="https://www.buymeacoffee.com/santosfrancisco" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-blue.png" alt="Buy Me A Coffee" width="180px" ></a>
<file_sep>module.exports = {
siteTitle: 'Harshith Venkatesh',
siteDescription: `Create your online curriculum in just a few minutes with this starter`,
keyWords: ['gatsbyjs', 'react', 'curriculum'],
authorName: '<NAME>',
twitterUsername: 'Harshith_V007',
githubUsername: 'harshith-venkatesh',
authorAvatar: '/images/avatar.jpeg',
authorDescription: `Experienced Coordinator with a demonstrated history of working on UI Development. Skilled in <strong>React.js, JavaScript, Angular, NodeJS, CSS, HTML</strong>.
Actively involved in product discussion, development of three projects on Angular and React in Lumen Technologies. Apart from office work, I am an active member, App Owner(Events Page) of an open-source community - Real Dev Squad where I involve in building unique features, interact with students on web development from various parts of the world, code reviews, etc`,
jobs: [
/* more jobs here */
{
company: 'Lumen India',
begin: {
month: 'aug',
year: '2018',
},
duration: null,
occupation: 'Software Development Consultant I',
description:
`
- Developed Responsive SPA Enterprise Dashboard, assets display for 1M+ transactions using Angular 8, NodeJS, GitLab, Material UI.
- Devoted special emphasis to display relevant data based on criteria and implemented features to ease data visualization.
- Awarded for initiating and leading a team of 3 people for devising a tracking tool, Enterprise Dashboard project which automates PASE team's performance by 40%.
- Improved project performance by 60% by caching, lazy loading,optimization of code.
- Created an SPA using ReactJS, Ag-Grid,D3.js consisting of multiple dashboards for invoice portal.
- Involved in migrating the application from manual deployment to CI/CD pipeline using Jenkins and GitHub actions.
`,
},
{
company: 'Real Dev Squad',
begin: {
month: 'aug',
year: '2020',
},
duration: null,
occupation: 'Open Source Contributor',
description:
`
- Managing open source web development community having 100+ members
- App Owner of Events App which contains the role of TechLead, Project Manager.
- Moderated and coordinated in building multiple projects built on React, NextJS, NodeJS at Real Dev Squad.
- Proactively involved in setting up repositories, reviewing codes, and overseeing PRs.
`,
},
,
],
portifolio: [
{
image:'/images/project_techkart.png',
description:'Tech Kart',
url: 'https://techcart-app.herokuapp.com/'
},
{
image:'/images/project_shankha.PNG',
description:'Shankha CSS',
url: 'http://shankhacss.netlify.app/'
},
{
image: '/images/project1.png',
description: 'Where in the World!',
url: 'https://whereintheworldismycountry.netlify.app/',
},
{
image: '/images/project6.png',
description: 'Farm2Home MERN Project',
url: 'https://farm2wohome.herokuapp.com/',
},
{
image: '/images/project2.png',
description: 'Expense Tracker using Angular',
url: 'https://kharchapaani.netlify.app/',
},
{
image: '/images/project3.png',
description: 'Covid Tracker using React',
url: 'https://covid19trackerdemo.netlify.app/',
},
{
image: '/images/project4.png',
description: 'Weather Progressive Web App',
url: 'https://progressiveweatherapp.netlify.app/',
},
{
image: '/images/project5.png',
description: 'Breaking Bad',
url: 'https://iamtheonewhoknocks.netlify.app/',
},
/* more portifolio items here */
],
social: {
twitter: 'https://twitter.com/Harshith_V007',
linkedin: 'https://www.linkedin.com/in/harshithvenkatesh/',
github: 'https://github.com/harshith-venkatesh',
email: '<EMAIL>',
},
siteUrl: 'https://harshith-venkatesh.github.io',
// pathPrefix: '/gatsby-starter-cv', // Note: it must *not* have a trailing slash.
siteCover: '/images/cover.jpeg',
googleAnalyticsId: 'UA-171686543-1',
background_color: '#ffffff',
theme_color: '#25303B',
fontColor: '#000000cc',
enableDarkmode: true, // If true, enables dark mode switch
display: 'minimal-ui',
icon: 'src/assets/gatsby-icon.png',
headerLinks: [
{
label: 'Home',
url: '/',
},
{
label: 'Portifolio',
url: '/portifolio',
},
],
}
|
f64d030dc8d9dd734ef1e593f3ed581754ee86c5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Harshi7016/HarshithPortfolio
|
f4c5bda1fecdea45e6d0ca3c8ae8a901fd1feb35
|
8e221f33e2dcc65f9cbbf99f3796b80b6535a685
|
refs/heads/master
|
<repo_name>11o9/NG<file_sep>/Panel.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using NG.Class;
using Rhino.Geometry;
using System.Threading.Tasks;
using System.Threading;
namespace NG
{
/// <summary>
/// Panel.xaml에 대한 상호 작용 논리
/// </summary>
public partial class Panel : UserControl
{
Curve tempSelectedBoundary = null;
PlotSetting setting = new PlotSetting();
Brush[] brushes = new Brush[] { Brushes.Gold, Brushes.Aqua, Brushes.Beige, Brushes.Magenta };
Previewer preview = new Previewer();
UnitSettings unitSettings = new UnitSettings();
List<UnitSetting> units = new List<UnitSetting>();
public Panel()
{
InitializeComponent();
preview.Enabled = true;
UnitSelection.ItemsSource = unitSettings.TypeName;
//Units.ItemsSource = units;
}
private void Generate_Click(object sender, RoutedEventArgs e)
{
if (PlotTypeCombo.SelectedIndex == -1)
return;
if (tempSelectedBoundary == null)
return;
if (Width_Combo.SelectedIndex == -1)
return;
Graph.Children.Clear();
Angle_Combo.Items.Clear();
AddPlotAngle();
Generate_SelectedType();
//Generate_Graph();
}
private void AddPlotAngle()
{
var segments = tempSelectedBoundary.DuplicateSegments();
var vectors = segments.Select(n => n.TangentAtStart);
var acos = vectors.Select(n => n.Y / Math.Abs(n.Y == 0 ? 1 : n.Y) * Math.Acos(n.X));
var angles = acos.Select(n => n * 180 / Math.PI);
angles.ToList().ForEach(n => Angle_Combo.Items.Add(n));
}
private async void Generate_SelectedType()
{
Generate.IsEnabled = false;
//GenerateOne.IsEnabled = false;
int selected = PlotTypeCombo.SelectedIndex;
double aptwidth = (double)Width_Combo.SelectedItem;
double canvasy = Graph.Height;
double canvasx = Graph.Width;
var task1 = Task<List<System.Windows.Point>>.Run(() => CalcAsync(selected, aptwidth));
List<System.Windows.Point> points = await task1;
int maxindex = 0;
List<System.Windows.Shapes.Ellipse> els = new List<System.Windows.Shapes.Ellipse>();
for (int p = 0; p < points.Count; p++)
{
double width = 2;
double height = 2;
double newyvalue = canvasy - points[p].Y;
//newyvalue *= ;
var ne = new System.Windows.Shapes.Ellipse();
ne.Margin = new Thickness((points[p].X * 2) - width / 2, newyvalue - height / 2, 0, 0);
ne.Width = width;
ne.Height = height;
ne.Fill = brushes[selected];
els.Add(ne);
if (points[p].Y > points[maxindex].Y)
maxindex = p;
}
List<int> items = new List<int>();
for (int j = 1; j < points.Count-1; j++)
{
int i = j - 1;
int k = j + 1;
//가운데가제일크면
if (points[j].Y > points[i].Y && points[j].Y > points[k].Y)
{
els[j].Fill = Brushes.HotPink;
items.Add(j);
}
}
els.ForEach(n => Graph.Children.Add(n));
items.ForEach(n => Angle_Combo.Items.Add((double)n));
//Angle_Combo.ItemsSource = items;
Generate.IsEnabled = true;
//GenerateOne.IsEnabled = true;
}
private async void Generate_Graph()
{
Generate.IsEnabled = false;
//GenerateOne.IsEnabled = false;
double aptwidth = (double)Width_Combo.SelectedItem;
double canvasy = Graph.Height;
double canvasx = Graph.Width;
//int i = PlotTypeCombo.SelectedIndex;
int selected = PlotTypeCombo.SelectedIndex;
var task1 = Task<List<List<System.Windows.Point>>>.Run(() => CalcAsyncEachFloor(selected, aptwidth));
List<List<System.Windows.Point>> points = await task1;
//var task1 = Task<List<System.Windows.Point>>.Run(() => CalcAsync(i, aptwidth));
//List<System.Windows.Point> points = await task1;
int maxindex = 0;
//Rhino.RhinoApp.WriteLine(((PlotTypes)sum).ToString() + "완료");
//ResultMax.Text = "최대각 : " + maxindex.ToString() + ", 값 : " + points[maxindex].Y.ToString();
for (int p = 0; p < points.Count; p++)
{
for (int i = 0; i < 4; i++)
{
double width = 2;
double height = 2;
double newyvalue = canvasy - points[p][i].Y;
//newyvalue *= ;
var ne = new System.Windows.Shapes.Ellipse();
ne.Margin = new Thickness((points[p][i].X * 2) - width / 2, newyvalue - height / 2, 0, 0);
ne.Width = width;
ne.Height = height;
ne.Fill = brushes[i];
Graph.Children.Add(ne);
if (points[p][i].Y > points[maxindex][i].Y)
maxindex = p;
}
}
Generate.IsEnabled = true;
//GenerateOne.IsEnabled = true;
}
private List<System.Windows.Point> CalcAsync(int i,double width)
{
List<System.Windows.Point> points = new List<System.Windows.Point>();
Plot plot = new Plot() { Boundary = tempSelectedBoundary, BuildingType = BuildingTypes.다세대, LegalCVR = setting.LegalCVR[i], LegalFAR = setting.LegalFAR[i], LegalMaxF = setting.LegalMaxF[i], PlotType = (PlotTypes)i, RoadWidths = new List<double>() { 4 } };
//test
var roadCenter = Regulation.RoadCenterLines(plot);
var north = Regulation.North(roadCenter, plot);
var clearance = Regulation.Clearance(plot);
int minimum = north.Count > clearance.Count ? clearance.Count : north.Count;
List<Curve> nc = new List<Curve>();
for (int j = 0; j < minimum; j++)
{
var a = Curve.CreateBooleanIntersection(north[j], clearance[j]);
nc.Add(a[0]);
}
//List<List<Curve>> curvesCollection = new List<List<Curve>>();
List<double> valuesCollection = new List<double>();
var start = DateTime.Now;
for (int r = 0; r < 180; r++)
{
int maxfloor;
var reg = Regulation.MergedRegulation_TopOnly(nc, plot, (double)r / 180 * Math.PI, out maxfloor);
List<Curve> trash;
List<Rhino.Geometry.Line> trash2;
var length = Calculate.AngleMax_Simple(reg.Last(), maxfloor, width, (double)r / 180 * Math.PI, out trash, out trash2);
valuesCollection.Add(length);
points.Add(new System.Windows.Point(r, length * maxfloor / 10));
}
var end = DateTime.Now;
int endsec = end.Second;
int startsec = start.Second;
if (startsec > endsec)
endsec += 60;
double endtime = endsec * 1000 + end.Millisecond;
double starttime = startsec * 1000 + start.Millisecond;
double x = (endtime - starttime) / 1000;
Rhino.RhinoApp.WriteLine("180회 소요시간 " + x.ToString() + "초, 회당 " + (x / 180).ToString() + "초");
double lengthmax = points.Select(n => n.Y).Max();
return points;
}
private List<List<System.Windows.Point>> CalcAsyncEachFloor(int i, double width)
{
List<List<System.Windows.Point>> result = new List<List<System.Windows.Point>>();
Plot plot = new Plot() { Boundary = tempSelectedBoundary, BuildingType = BuildingTypes.다세대, LegalCVR = setting.LegalCVR[i], LegalFAR = setting.LegalFAR[i], LegalMaxF = setting.LegalMaxF[i], PlotType = (PlotTypes)i, RoadWidths = new List<double>() { 4 } };
//test
var roadCenter = Regulation.RoadCenterLines(plot);
var north = Regulation.North(roadCenter, plot);
var clearance = Regulation.Clearance(plot);
int minimum = north.Count > clearance.Count ? clearance.Count : north.Count;
List<Curve> nc = new List<Curve>();
for (int j = 0; j < minimum; j++)
{
var a = Curve.CreateBooleanIntersection(north[j], clearance[j]);
nc.Add(a[0]);
}
//List<List<Curve>> curvesCollection = new List<List<Curve>>();
//List<double> valuesCollection = new List<double>();
var start = DateTime.Now;
for (int r = 0; r < 180; r++)
{
List<System.Windows.Point> points = new List<System.Windows.Point>();
var reg = Regulation.MergedRegulation(nc, plot, (double)r / 180 * Math.PI);
List<Curve> trash;
List<Rhino.Geometry.Line> trash2;
for (int f = reg.Count-4; f < reg.Count; f++)
{
var length = Calculate.AngleMax_Simple(reg[f], f, width, (double)r / 180 * Math.PI, out trash,out trash2);
//valuesCollection.Add(length);
points.Add(new System.Windows.Point(r, length * f / 10));
}
result.Add(points);
}
var end = DateTime.Now;
int endsec = end.Second;
int startsec = start.Second;
if (startsec > endsec)
endsec += 60;
double endtime = endsec * 1000 + end.Millisecond;
double starttime = startsec * 1000 + start.Millisecond;
double x = (endtime - starttime) / 1000;
Rhino.RhinoApp.WriteLine("소요시간 " + x.ToString() + "초");
//double lengthmax = points.Select(n => n.Y).Max();
return result;
}
private void SelCurve_Click(object sender, RoutedEventArgs e)
{
// Rhino.Geometry.Polyline result;
// var r = Rhino.Input.RhinoGet.GetPolyline(out result);
// if (r == Rhino.Commands.Result.Success)
// {
// Curve temp = result.ToNurbsCurve();
// if (result.ToNurbsCurve().ClosedCurveOrientation(Plane.WorldXY) != CurveOrientation.CounterClockwise)
// temp.Reverse();
// tempSelectedBoundary = temp;
// }
Rhino.DocObjects.ObjRef result;
var r = Rhino.Input.RhinoGet.GetOneObject("커브 선택", true, Rhino.DocObjects.ObjectType.Curve, out result);
if (r == Rhino.Commands.Result.Success)
{
Curve temp = result.Curve();
if (temp.ClosedCurveOrientation(Plane.WorldXY) != CurveOrientation.CounterClockwise)
temp.Reverse();
tempSelectedBoundary = temp;
}
}
//private void GenerateOne_Click(object sender, RoutedEventArgs e)
//{
// if (PlotTypeCombo.SelectedIndex == -1)
// return;
// if (tempSelectedBoundary == null)
// return;
// int i = PlotTypeCombo.SelectedIndex;
// Plot plot = new Plot() { Boundary = tempSelectedBoundary, BuildingType = BuildingTypes.다세대, LegalCVR = setting.LegalCVR[i], LegalFAR = setting.LegalFAR[i], LegalMaxF = setting.LegalMaxF[i], PlotType = (PlotTypes)i, RoadWidths = new List<double>() { 4 } };
// //test
// var roadCenter = Regulation.RoadCenterLines(plot);
// var north = Regulation.North(roadCenter, plot);
// var clearance = Regulation.Clearance(plot);
// int minimum = north.Count > clearance.Count ? clearance.Count : north.Count;
// List<Curve> nc = new List<Curve>();
// for (int j = 0; j < minimum; j++)
// {
// var a = Curve.CreateBooleanIntersection(north[j], clearance[j]);
// nc.Add(a[0]);
// }
// int r = (int)Angle.Value;
// var start = DateTime.Now;
// var reg = Regulation.MergedRegulation(nc, plot, (double)r / 180 * Math.PI);
// var end = DateTime.Now;
// //Rhino.RhinoApp.WriteLine("법규선계산 : " + (end.Second - start.Second) + "초" + (end.Millisecond - start.Millisecond) + "ms");
// start = DateTime.Now;
// List<Curve> temp1;
// List<Curve> temp2;
// var val1 = Calculate.AngleMax_Josh(reg.Last(), plot.LegalMaxF, 9, (double)r / 180 * Math.PI,out temp1);
// end = DateTime.Now;
// //Rhino.RhinoApp.WriteLine("최대길이계산 : " + (end.Second - start.Second) + "초" + (end.Millisecond - start.Millisecond) + "ms yvalue = " + Math.Round(length, 1).ToString());
// var val2 = Calculate.AngleMax(reg.Last(), plot.LegalMaxF, 9, (double)r / 180 * Math.PI, out temp2);
// //points.Add(new System.Windows.Point(r, length));
// //double lengthmax = points.Select(n => n.Y).Max();
// preview.reg = reg;
// preview.model1 = temp1;
// preview.model2 = temp2;
// preview.value1 = val1;
// preview.value2 = val2;
// Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();
//}
/// <summary>
/// asdfasfdfdassfdasfda
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Angle_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Angle_Combo.SelectedIndex == -1)
return;
if (PlotTypeCombo.SelectedIndex == -1)
return;
if (tempSelectedBoundary == null)
return;
if (Width_Combo.SelectedIndex == -1)
return;
int i = PlotTypeCombo.SelectedIndex;
//폭
double width = (double)Width_Combo.SelectedItem;
double canvasy = Graph.Height;
double canvasx = Graph.Width;
List<System.Windows.Point> points = new List<System.Windows.Point>();
Plot plot = new Plot() { Boundary = tempSelectedBoundary, BuildingType = BuildingTypes.다세대, LegalCVR = setting.LegalCVR[i], LegalFAR = setting.LegalFAR[i], LegalMaxF = setting.LegalMaxF[i], PlotType = (PlotTypes)i, RoadWidths = new List<double>() { 4 } };
//test
var roadCenter = Regulation.RoadCenterLines(plot);
var north = Regulation.North(roadCenter, plot);
var clearance = Regulation.Clearance(plot);
int minimum = north.Count > clearance.Count ? clearance.Count : north.Count;
List<Curve> nc = new List<Curve>();
for (int j = 0; j < minimum; j++)
{
var a = Curve.CreateBooleanIntersection(north[j], clearance[j]);
nc.Add(a[0]);
}
double r = (double)Angle_Combo.SelectedValue;
var start = DateTime.Now;
var reg = Regulation.MergedRegulation(nc, plot, (double)r / 180 * Math.PI);
var end = DateTime.Now;
//Rhino.RhinoApp.WriteLine("법규선계산 : " + (end.Second - start.Second) + "초" + (end.Millisecond - start.Millisecond) + "ms");
start = DateTime.Now;
//List<Curve> temp1;
List<Curve> temp2;
//var val1 = Calculate.AngleMax_Josh(reg.Last(), plot.LegalMaxF, 9, (double)r / 180 * Math.PI, out temp1);
end = DateTime.Now;
List<Rhino.Geometry.Line> parkingBaseLine;
//Rhino.RhinoApp.WriteLine("최대길이계산 : " + (end.Second - start.Second) + "초" + (end.Millisecond - start.Millisecond) + "ms yvalue = " + Math.Round(length, 1).ToString());
var val2 = Calculate.AngleMax_Simple(reg.Last(), plot.LegalMaxF, width, (double)r / 180 * Math.PI, out temp2, out parkingBaseLine);
double aptDistance = (reg.Last().PointAtStart.Z - 3.3) * 0.8;
double linedistance = width + aptDistance;
var far = Math.Round(val2 * width * plot.LegalMaxF / plot.Area,4) * 100;
//points.Add(new System.Windows.Point(r, length));
//유닛분배........................................................................................
//유닛정보,라인..음..
List<Point3d> aptSeparatePoints = new List<Point3d>();
List<Point3d> balancedPoints = new List<Point3d>();
for (int j = 0; j < temp2.Count; j++)
{
var tempcurve = temp2[j];
var templength = tempcurve.GetLength();
var unitset = (UnitSetting)Units.Items[0];
var unitlength = unitset.Area / width;
var p1 = tempcurve.PointAtLength(templength);
aptSeparatePoints.Add(p1);
int aptcount = 0;
while (templength > 2*unitlength)
{
var p2 = tempcurve.PointAtLength(templength - unitlength);
var p3 = tempcurve.PointAtLength(templength - unitlength * 2);
aptcount += 2;
aptSeparatePoints.Add(p2);
aptSeparatePoints.Add(p3);
templength -= 2 * unitlength;
}
double lengthleftperapt = templength / aptcount;
double balancedaptlength = unitlength + lengthleftperapt;
for (int k = 0; k <= aptcount; k++)
{
var temppoint = tempcurve.PointAtLength(k * balancedaptlength);
balancedPoints.Add(temppoint);
}
}
preview.points = aptSeparatePoints;
preview.balancedpoints = balancedPoints;
List<Curve> parkingLinesCollection = new List<Curve>();
List<Curve> baseCurves = parkingBaseLine.Select(n => n.ToNurbsCurve() as Curve).ToList();
ParkingMaster master = new ParkingMaster(tempSelectedBoundary, baseCurves, linedistance);
int parkingCount = master.CalculateParkingScore();
parkingLinesCollection = master.parkingCells;
//for (int p = 0; p < parkingBaseLine.Count; p++)
//{
// bool addfirst = p == 0 ? true : false;
// List<Curve> parkingLines = ParkingPrediction.Calculate(linedistance, parkingBaseLine[p].ToNurbsCurve(), addfirst);
// parkingLinesCollection.AddRange(parkingLines);
//}
//주차는.?
//for()
//plot, aptline, width, distance
//distance 와 set
//double lengthmax = points.Select(n => n.Y).Max();
preview.reg = reg;
preview.model1 = parkingLinesCollection;
preview.model2 = temp2;
preview.value1 = parkingCount;
preview.value2 = far;
Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();
}
//add
private void UnitSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (UnitSelection.SelectedIndex == -1)
return;
int i = UnitSelection.SelectedIndex;
UnitSetting tempsetting = new UnitSetting() { Area = unitSettings.Area[i], TypeName = unitSettings.TypeName[i], ExclusiveArea = unitSettings.ExclusiveArea[i], MinWidth = unitSettings.MinWidth[i], MaxWidth = unitSettings.MaxWidth[i] };
UnitSetting[] temp = new UnitSetting[Units.Items.Count];
Units.Items.CopyTo(temp, 0);
if (temp.Where(n => n.TypeName == tempsetting.TypeName).ToList().Count != 0)
return;
int index = temp.Where(n => n.Area < tempsetting.Area).Count();
Units.Items.Insert(index, tempsetting);
UnitSelection.SelectedIndex = -1;
UnitSetup();
}
//remove
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn.DataContext is UnitSetting)
{
UnitSetting deleteme = (UnitSetting)btn.DataContext;
Units.Items.Remove(deleteme);
}
UnitSetup();
}
//set
private void UnitSetup()
{
Width_Combo.Items.Clear();
UnitSetting[] temp = new UnitSetting[Units.Items.Count];
Units.Items.CopyTo(temp, 0);
if (temp.Length == 0)
{
//선택 x ?
return;
}
//최대값의최소값
double widthMax = temp.Select(n => n.MaxWidth).Min();
//최소값의최대값
double widthMin = temp.Select(n => n.MinWidth).Max();
//최대값의 최소값, 최소값의 최대값 의 평균
double widthAvrg = (widthMax + widthMin) / 2;
Width_Combo.Items.Add(widthMin);
Width_Combo.Items.Add(widthAvrg);
Width_Combo.Items.Add(widthMax);
}
}
}
<file_sep>/PeterParker.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rhino.Geometry;
namespace NG
{
public class ParkingMaster
{
Curve Boundary;
List<Curve> aptLines;
double TotalLength;
public List<Curve> parkingCells;
public ParkingMaster(Curve boundary, List<Curve> aptLines, double Length)
{
Boundary = InnerLoop(boundary);
this.aptLines = aptLines;
TotalLength = Length;
//ParkingResult result = ParkingPrediction.Calculate()
}
public Curve InnerLoop(Curve boundary)
{
CurveOrientation ot = boundary.ClosedCurveOrientation(Plane.WorldXY);
double offsetDistance = 6;
var segments = boundary.DuplicateSegments();
for (int i = 0; i < segments.Length; i++)
{
Vector3d v = segments[i].TangentAtStart;
v.Rotate(-Math.PI / 2, Vector3d.ZAxis);
Curve temp = segments[i].DuplicateCurve();
temp.Translate(v * offsetDistance);
segments[i] = temp;
}
List<Point3d> toPoly = new List<Point3d>();
for (int i = 0; i < segments.Length; i++)
{
int j = (i + 1) % segments.Length;
Line l1 = new Line(segments[i].PointAtStart, segments[i].PointAtEnd);
Line l2 = new Line(segments[j].PointAtStart, segments[j].PointAtEnd);
double p1;
double p2;
Rhino.Geometry.Intersect.Intersection.LineLine(l1, l2, out p1, out p2);
toPoly.Add(l1.PointAt(p1));
}
toPoly.Add(toPoly[0]);
Curve merged = new Polyline(toPoly).ToNurbsCurve();
var intersection = Rhino.Geometry.Intersect.Intersection.CurveSelf(merged, 0);
var parameters = intersection.Select(n => n.ParameterA).ToList();
parameters.AddRange(intersection.Select(n => n.ParameterB));
var spltd = merged.Split(parameters);
var joined = Regulation.NewJoin(spltd);
return joined.Where(n => n.ClosedCurveOrientation(Plane.WorldXY) == ot).ToList()[0];
}
public int CalculateParkingScore()
{
if (aptLines.Count == 0)
return 0;
Vector3d dir0 = aptLines[0].TangentAtStart;
List<Curve> origins = new List<Curve>(aptLines);
dir0.Rotate(-Math.PI / 2, Vector3d.ZAxis);
//List<Point3d> starts = x.Select(n => n.PointAtStart).ToList();
if (origins.Count > 0)
{
Curve temp = origins[0].DuplicateCurve();
temp.Translate(dir0 * TotalLength);
origins.Insert(0, temp);
}
var parkingResult = ParkingPrediction.Calculate(TotalLength);
List<Curve> result = new List<Curve>();
List<Curve> partitions = new List<Curve>();
for (int i = 0; i < origins.Count; i++)
{
result.AddRange(parkingResult.GetCurves(origins[i]));
partitions.AddRange(parkingResult.GetParkingLines(origins[i]));
}
var widths = parkingResult.widths();
var heights = parkingResult.heights();
var innerParkings = partitions.Where(n => IsInside(Boundary, n)).ToList();
string log = innerParkings.Count.ToString() + " / " + partitions.Count.ToString()
+ " ( " + (double)innerParkings.Count / partitions.Count * 100 + " %)";
//to debug
parkingCells = innerParkings;
return innerParkings.Count;
}
public bool IsInside(Curve c, Curve d)
{
var endPoints = d.DuplicateSegments().Select(n => n.PointAtStart).ToList();
int outCount = 0;
for (int i = 0; i < endPoints.Count; i++)
{
if (c.Contains(endPoints[i]) == PointContainment.Outside)
outCount++;
}
if (outCount > 0)
return false;
else
return true;
}
}
//단위 거리 분할 결과.
public class ParkingResult
{
PeterParkerCollection resultCollection;
public ParkingResult(PeterParkerCollection result)
{
resultCollection = result;
}
public List<Curve> GetCurves(Curve origin)
{
List<double> offsets = resultCollection.collection.Last().OffsetDistances();
List<Curve> results = new List<Curve>();
for (int i = 0; i < offsets.Count; i++)
{
Curve temp = origin.DuplicateCurve();
Vector3d v = temp.TangentAtStart;
v.Rotate(Math.PI / 2, Vector3d.ZAxis);
temp.Translate(v * offsets[i]);
results.Add(temp);
}
return results;
}
public List<Curve> GetParkingLines(Curve origin)
{
List<double> offsets = resultCollection.collection.Last().OffsetDistances();
List<double[]> widths = resultCollection.collection.Last().GetWidths();
List<double> heights = resultCollection.collection.Last().GetHeights();
List<Curve> results = new List<Curve>();
double originCurveRotation = Vector3d.VectorAngle(Vector3d.XAxis, origin.TangentAtEnd, Plane.WorldXY);
for (int i = 0; i < widths.Count; i++)
{
Parking parking = resultCollection.collection.Last().parkings[i];
//도로면 패스
if (widths[i][0] == 0)
continue;
Curve temp = origin.DuplicateCurve();
Vector3d v = origin.TangentAtStart;
v.Rotate(Math.PI / 2, Vector3d.ZAxis);
temp.Translate(v * offsets[i]);
var divided = origin.DivideByLength(widths[i][1], true);
//하나도 안나오면 패스
if (divided == null)
continue;
var partitions = divided.Select(n => new LineCurve(temp.PointAt(n), temp.PointAt(n) - v * heights[i])).ToList();
List<Curve> pLines = new List<Curve>();
for (int j = 0; j < partitions.Count; j++)
{
List<Curve> lines = parking.DrawLine(partitions[j].PointAtStart).ToList();
lines.ForEach(n => n.Transform(Transform.Rotation(originCurveRotation, Vector3d.ZAxis, partitions[j].PointAtStart)));
pLines.AddRange(lines);
}
pLines.ForEach(n => results.Add(n));
}
return results;
}
public bool IsInside(Curve c, Curve d)
{
var endPoints = d.DuplicateSegments().Select(n => n.PointAtStart).ToList();
int outCount = 0;
for (int i = 0; i < endPoints.Count; i++)
{
if (c.Contains(endPoints[i]) == PointContainment.Outside)
outCount++;
}
if (outCount > 0)
return false;
else
return true;
}
//test//
public List<string> widths()
{
List<string> result = new List<string>();
List<double[]> widths = resultCollection.collection.Last().GetWidths();
for (int i = 0; i < widths.Count; i++)
{
result.Add(widths[i][0].ToString() + " , " + widths[i][1].ToString());
}
return result;
}
public List<string> heights()
{
List<string> result = new List<string>();
List<double> heights = resultCollection.collection.Last().GetHeights();
for (int i = 0; i < heights.Count; i++)
{
result.Add(heights[i].ToString());
}
return result;
}
}
public class ParkingPrediction
{
public static ParkingResult Calculate(double initialLength/*, Curve initialCurve*/)
{
PeterParker origin = new PeterParker(initialLength/*, initialCurve*/);
Queue<PeterParker> wait = new Queue<PeterParker>();
PeterParkerCollection fit = new PeterParkerCollection();
wait.Enqueue(origin);
while (wait.Count > 0)
{
PeterParker current = wait.Dequeue();
for (int i = 0; i < (int)ParkingType.Max; i++)
{
PeterParker temp = new PeterParker(current, (ParkingType)i);
if (temp.LeftLength() < 0)
{
//cull
}
else if (temp.LeftLength() > 0)
{
if (temp.LeftLength() < 5)
{
//fit
fit.Add(temp);
}
else
{
//re enqueue
wait.Enqueue(temp);
}
}
}
}
//
fit.collection.ForEach(n => n.FillRoads());
var result = new ParkingResult(fit);
return result;
}
}
public class PeterParkerCollection
{
public List<PeterParker> collection;
public int Count { get { return collection.Count; } }
public PeterParkerCollection()
{
collection = new List<PeterParker>();
}
public void Add(PeterParker parker)
{
if (collection.Count < 10)
{
collection.Add(parker);
Sort();
}
else
{
if (collection[0].ParkingUnitCount().Sum() < parker.ParkingUnitCount().Sum())
{
collection.RemoveAt(0);
collection.Add(parker);
Sort();
}
}
}
void Sort()
{
PeterParkerComparer comp = new PeterParkerComparer();
collection.Sort(comp);
}
}
public enum ParkingType
{
P0Single,
P0Double,
P45Single,
P45Double,
P60Single,
P60Double,
P90Single,
P90Double,
Max,
Road
}
public class Parking
{
public double height;
public double width;
public double widthOffset;
public double necessaryRoad;
public bool isDouble;
public ParkingType type;
public Parking(double distance)
{
height = distance;
necessaryRoad = 0;
width = 0;
widthOffset = 0;
isDouble = false;
type = ParkingType.Road;
}
public Parking(ParkingType type)
{
this.type = type;
switch (type)
{
case ParkingType.P0Single:
{
height = 2;
width = 6;
widthOffset = 6;
necessaryRoad = 3.5;
isDouble = false;
break;
}
case ParkingType.P0Double:
{
height = 4;
width = 6;
widthOffset = 6;
necessaryRoad = 3.5;
isDouble = true;
break;
}
case ParkingType.P45Single:
{
height = 5.162;
width = 5.162;
widthOffset = 3.253;
necessaryRoad = 3.5;
isDouble = false;
break;
}
case ParkingType.P45Double:
{
height = 8.697;
width = 5.162;
widthOffset = 3.253;
necessaryRoad = 3.5;
isDouble = true;
break;
}
case ParkingType.P60Single:
{
height = 5.48;
width = 4.492;
widthOffset = 2.656;
necessaryRoad = 4.5;
isDouble = false;
break;
}
case ParkingType.P60Double:
{
height = 9.810;
width = 4.492;
widthOffset = 2.656;
necessaryRoad = 4.5;
isDouble = true;
break;
}
case ParkingType.P90Single:
{
height = 5;
width = 2.3;
widthOffset = 2.3;
necessaryRoad = 6;
isDouble = false;
break;
}
case ParkingType.P90Double:
{
height = 10;
width = 2.3;
widthOffset = 2.3;
necessaryRoad = 6;
isDouble = true;
break;
}
}
}
public List<Curve> DrawLine(Point3d origin)
{
switch (type)
{
case ParkingType.P0Single:
return DrawRect(origin, -1, false);
case ParkingType.P0Double:
return DrawRect(origin, -1, true);
case ParkingType.P45Single:
return DrawRect(origin, Math.PI / 2 - Math.PI / 4, false);
case ParkingType.P45Double:
return DrawRect(origin, Math.PI / 2 - Math.PI / 4, true);
case ParkingType.P60Single:
return DrawRect(origin, Math.PI / 2 - Math.PI / 3, false);
case ParkingType.P60Double:
return DrawRect(origin, Math.PI / 2 - Math.PI / 3, true);
case ParkingType.P90Single:
return DrawRect(origin, Math.PI / 2 - Math.PI / 2, false);
case ParkingType.P90Double:
return DrawRect(origin, Math.PI / 2 - Math.PI / 2, true);
}
return null;
}
public List<Curve> DrawRect(Point3d origin, double rad, bool isdouble)
{
List<Curve> result = new List<Curve>();
//평행주차 시, [6,2]
if (rad == -1)
{
Polyline p = new Polyline(new Point3d[]{
origin,
origin - Vector3d.YAxis * 2,
origin - Vector3d.YAxis * 2 + Vector3d.XAxis * 6,
origin + Vector3d.XAxis * 6,
origin});
result.Add(p.ToNurbsCurve());
if (isdouble)
{
Polyline p2 = new Polyline(new Point3d[]{
p[1],
p[1] - Vector3d.YAxis * 2,
p[1] - Vector3d.YAxis * 2 + Vector3d.XAxis * 6,
p[1] + Vector3d.XAxis * 6,
p[1]});
result.Add(p2.ToNurbsCurve());
}
}
//나머지 [2.3,5]
else
{
Polyline p = new Polyline(new Point3d[]{
origin,
origin - Vector3d.YAxis * 5,
origin - Vector3d.YAxis * 5 + Vector3d.XAxis * 2.3,
origin + Vector3d.XAxis * 2.3,
origin});
if (isdouble)
{
Polyline p2 = new Polyline(new Point3d[]{
p[1],
p[1] - Vector3d.YAxis * 5,
p[1] - Vector3d.YAxis * 5 + Vector3d.XAxis * 2.3,
p[1] + Vector3d.XAxis * 2.3,
p[1]});
p2.Transform(Transform.Rotation(-rad, origin));
result.Add(p2.ToNurbsCurve());
}
p.Transform(Transform.Rotation(-rad, origin));
result.Add(p.ToNurbsCurve());
}
return result;
}
}
public class PeterParkerComparer : IComparer<PeterParker>
{
public int Compare(PeterParker a, PeterParker b)
{
return a.ParkingUnitCount().Sum().CompareTo(b.ParkingUnitCount().Sum());
}
}
public class PeterParker
{
public List<Parking> parkings;
public double totalLength;
//public Curve baseCurve;
public PeterParker(double length/*, Curve baseCurve*/)
{
parkings = new List<Parking>();
totalLength = length;
//this.baseCurve = baseCurve.DuplicateCurve();
}
public PeterParker(PeterParker parent, ParkingType type)
{
parkings = new List<Parking>(parent.parkings);
parkings.Add(new Parking(type));
totalLength = parent.totalLength;
//baseCurve = parent.baseCurve;
}
//call when fit
public void FillRoads()
{
List<int> inserts = new List<int>();
List<Parking> roads = new List<Parking>();
for (int i = 0; i < parkings.Count; i++)
{
int j = (i + 1) % parkings.Count;
double roadi = parkings[i].necessaryRoad;
double roadj = parkings[j].necessaryRoad;
double roadLonger = roadi > roadj ? roadi : roadj;
inserts.Add(i);
roads.Add(new Parking(roadLonger));
}
//음.... +1 해줘야 맞음
for (int i = inserts.Count - 1; i >= 0; i--)
{
parkings.Insert(inserts[i] + 1, roads[i]);
}
}
//zero - back
public List<double> OffsetDistances()
{
List<double> Lengths = new List<double>();
double sum = 0;
for (int i = 0; i < parkings.Count; i++)
{
sum += parkings[i].height;
Lengths.Add(sum);
}
return Lengths;
}
//front - back
public List<double> GetHeights()
{
List<double> Heights = new List<double>();
Heights = parkings.Select(n => n.height).ToList();
return Heights;
}
//left - right
public List<double[]> GetWidths()
{
List<double[]> Widths = new List<double[]>();
//double sum = 0;
for (int i = 0; i < parkings.Count; i++)
{
Widths.Add(new double[] { parkings[i].width, parkings[i].widthOffset });
}
return Widths;
}
public double LeftLength()
{
List<double> Lengths = new List<double>();
for (int i = 0; i < parkings.Count; i++)
{
int j = (i + 1) % parkings.Count;
double roadi = parkings[i].necessaryRoad;
double roadj = parkings[j].necessaryRoad;
double roadLonger = roadi > roadj ? roadi : roadj;
Lengths.Add(parkings[i].height);
Lengths.Add(roadLonger);
}
return totalLength - Lengths.Sum();
}
//카운트를 여기서?...
public List<int> ParkingUnitCount()
{
List<int> Counts = new List<int>();
for (int i = 0; i < parkings.Count; i++)
{
double totalWidth = 100;
int count = 0;
while (true)
{
double offset = i == 0 ? parkings[i].width : parkings[i].widthOffset;
totalWidth -= offset;
if (totalWidth > 0)
{
if (parkings[i].isDouble)
count += 2;
else
count++;
}
else
{
Counts.Add(count);
break;
}
}
}
return Counts;
}
}
}
<file_sep>/Previewer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhino;
using Rhino.Display;
using Rhino.Geometry;
namespace NG
{
class Previewer : Rhino.Display.DisplayConduit
{
public List<Curve> reg = new List<Curve>();
public List<Curve> model1 = new List<Curve>();
public List<Curve> model2 = new List<Curve>();
public List<Point3d> points = new List<Point3d>();
public List<Point3d> balancedpoints = new List<Point3d>();
public double value1 = 0;
public double value2 = 0;
protected override void PostDrawObjects(DrawEventArgs e)
{
foreach (var m in balancedpoints)
{
e.Display.DrawPoint(m, PointStyle.X, 5, System.Drawing.Color.Red);
}
foreach (var m in points)
{
e.Display.DrawPoint(m, PointStyle.X,5, System.Drawing.Color.Green);
}
foreach (var m in reg)
{
e.Display.DrawCurve(m, System.Drawing.Color.Red);
}
foreach (var m in model1)
{
e.Display.DrawCurve(m,System.Drawing.Color.Blue);
}
foreach (var m in model2)
{
e.Display.DrawCurve(m, System.Drawing.Color.Gold);
}
Point3d point1 = new BoundingBox(model2.Select(n => n.PointAtNormalizedLength(0.5))).Center;
e.Display.DrawDot(point1, value1.ToString(),System.Drawing.Color.Blue,System.Drawing.Color.White);
if (model2.Count != 0)
{
Point3d point2 = new BoundingBox(model2.Select(n => n.PointAtNormalizedLength(0.5))).Max;
e.Display.DrawDot(point2, value2.ToString(), System.Drawing.Color.Gold, System.Drawing.Color.Black);
}
}
}
}
<file_sep>/NGCommand.cs
using System;
using System.Collections.Generic;
using Rhino;
using Rhino.Commands;
using Rhino.Geometry;
using Rhino.Input;
using Rhino.Input.Custom;
using Rhino.UI;
namespace NG
{
[System.Runtime.InteropServices.Guid("116d72b5-0b7a-4f6c-bea2-a4b6f9123520")]
public class NGCommand : Command
{
public NGCommand()
{
// Rhino only creates one instance of each command class defined in a
// plug-in, so it is safe to store a refence in a static property.
Instance = this;
}
///<summary>The only instance of this command.</summary>
public static NGCommand Instance
{
get; private set;
}
///<returns>The command name as it appears on the Rhino command line.</returns>
public override string EnglishName
{
get { return "NGCommand"; }
}
protected override Result RunCommand(RhinoDoc doc, RunMode mode)
{
// TODO: start here modifying the behaviour of your command.
// ---
Guid panelID = PanelHost.PanelId;
bool visible = Panels.IsPanelVisible(panelID);
if (visible)
Rhino.UI.Panels.ClosePanel(panelID);
else
Rhino.UI.Panels.OpenPanel(panelID);
return Result.Success;
// ---
}
}
}
<file_sep>/DataStructure.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rhino.Geometry;
namespace NG.DataStructure
{
interface ILine
{
Point3d Start { get; set; }
Point3d End { get; set; }
}
interface IControlLineCollection
{
IEnumerator<IControlLine> lines { get; set; }
}
interface IControlLine
{
}
interface IProject
{
}
class DataStructure
{
}
}
<file_sep>/Calculate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhino.Geometry;
namespace NG
{
class Calculate
{
//일정 거리 떨어진 예비 선들을 뽑아 값 비교
public static double AngleMax_Simple(Curve regCurve, double floor, double width, double angleRadian, out List<Curve> results, out List<Line> parkingBase)
{
double height = regCurve.PointAtStart.Z;
double aptDistance = (height - 3.3) * 0.8;
Curve regulationCurve = regCurve.DuplicateCurve();
Curve regZero = regCurve.DuplicateCurve();
List<Curve> output = new List<Curve>();
//List<Curve> wholeLines = new List<Curve>();
List<Curve> outputUp = new List<Curve>();
List<Curve> outputDown = new List<Curve>();
List<Curve> outputRegions = new List<Curve>();
regZero.Translate(Vector3d.ZAxis * -regZero.PointAt(0).Z);
Point3d rotatecenter = AreaMassProperties.Compute(regCurve).Centroid;
regulationCurve.Rotate(-angleRadian, Vector3d.ZAxis, rotatecenter);
var boundingbox = regulationCurve.GetBoundingBox(false);
//y범위
double ygap = boundingbox.Max.Y - boundingbox.Min.Y;
List<double> param = new List<double>();
double linecount = 1;
double unitlength = width;
double z = width;
double y = aptDistance;
//y채우기
param.Add(0);
while (unitlength < ygap)
{
linecount++;
unitlength = z * linecount + y * (linecount - 1);
if (unitlength < ygap)
param.Add(unitlength);
}
if (unitlength > ygap)
unitlength -= z + y;
param[0] += z;
//채우고 남은 y
double lengthremain = ygap - unitlength;
List<double> wholeLengths = new List<double>();
double MaxLength = double.MinValue;
List<Line> result = new List<Line>();
List<Line> parkingBaseline = new List<Line>();
//남은 길이의 0.1단위마다,,? ===> 2라인,3라인 이 1,2보다 안나오는 경우 있음. 모든 y 검토
double step = 1;
for (int k = 0; k < ygap / step; k++)
{
List<Line> tempResult = new List<Line>();
double[] tempParam = param.ToArray();
//parameter[i] + 단위길이 - width/2 위치에 라인 생성
for (int i = 0; i < param.Count; i++)
{
tempParam[i] = param[i] + k * step - z / 2;
Line templine = new Line(new Point3d(boundingbox.Min.X, boundingbox.Min.Y + tempParam[i], 0), new Point3d(boundingbox.Max.X, boundingbox.Min.Y + tempParam[i], 0));
tempResult.Add(templine);
}
//생성된 라인을 역회전 하여 기존 상태로 되돌림.
for (int i = 0; i < tempResult.Count; i++)
{
Line tempr = tempResult[i];
tempr.Transform(Transform.Rotation(angleRadian, Vector3d.ZAxis, rotatecenter));
tempResult[i] = tempr;
}
List<Curve> aptlines = new List<Curve>();
//offset한 라인마다 충돌체크,길이조정
for (int i = 0; i < tempResult.Count; i++)
{
Curve[] inner = InnerRegion(regZero, tempResult[i].ToNurbsCurve(), z);
aptlines.AddRange(inner);
}
//결과 값의 길이 확인
var AvailableLength = GetAvailableLength(aptlines);
//wholeLines.AddRange(aptlines);
wholeLengths.Add(AvailableLength);
if (MaxLength < AvailableLength)
{
MaxLength = AvailableLength;
output = aptlines;
parkingBaseline = tempResult;
}
}
if (output.Count == 0)
{
results = new List<Curve>();
parkingBase = new List<Line>();
return 0;
}
//outputUp = output.Select(n => n.DuplicateCurve()).Where(n => n.GetLength() >= 8).ToList();
//outputDown = output.Select(n => n.DuplicateCurve()).Where(n => n.GetLength() >= 8).ToList();
//Vector3d tv = output[0].TangentAtStart;
//tv.Rotate(Math.PI / 2, Vector3d.ZAxis);
//tv.Unitize();
//for (int i = 0; i < outputUp.Count; i++)
//{
// outputUp[i].Transform(Transform.Translation(tv * z / 2));
// outputDown[i].Transform(Transform.Translation(-tv * z / 2));
// Polyline p = new Polyline(new Point3d[] { outputUp[i].PointAtStart, outputUp[i].PointAtEnd, outputDown[i].PointAtEnd, outputDown[i].PointAtStart, outputUp[i].PointAtStart });
// outputRegions.Add(p.ToNurbsCurve());
//}
results = output;
parkingBase = parkingBaseline;
return MaxLength;
}
public static double AngleMax(Curve regCurve, double floor, double width, double angleRadian, out List<Curve> results)
{
double height = regCurve.PointAtStart.Z;
double aptDistance = (height - 3.3) * 0.8;
Curve regulationCurve = regCurve.DuplicateCurve();
Curve regZero = regCurve.DuplicateCurve();
//double[] parameters = { a, b, c, d, f };
//double storiesHigh = Math.Max((int)parameters[0], (int)parameters[1]);
//double storiesLow = Math.Min((int)parameters[0], (int)parameters[1]);
//double width = parameters[2];
//double angleRadian = -parameters[3];
List<Curve> output = new List<Curve>();
//List<Curve> wholeLines = new List<Curve>();
List<Curve> outputUp = new List<Curve>();
List<Curve> outputDown = new List<Curve>();
List<Curve> outputRegions = new List<Curve>();
regZero.Translate(Vector3d.ZAxis * -regZero.PointAt(0).Z);
Point3d rotatecenter = AreaMassProperties.Compute(regCurve).Centroid;
regulationCurve.Rotate(-angleRadian, Vector3d.ZAxis, rotatecenter);
var boundingbox = regulationCurve.GetBoundingBox(false);
//y범위
double ygap = boundingbox.Max.Y - boundingbox.Min.Y;
List<double> param = new List<double>();
double linecount = 1;
double unitlength = width;
double z = width;
double y = aptDistance;
//y채우기
param.Add(0);
while (unitlength < ygap)
{
linecount++;
unitlength = z * linecount + y * (linecount - 1);
if (unitlength < ygap)
param.Add(unitlength);
}
if (unitlength > ygap)
unitlength -= z + y;
param[0] += z;
//채우고 남은 y
double lengthremain = ygap - unitlength;
List<double> wholeLengths = new List<double>();
double MaxLength = double.MinValue;
List<Line> result = new List<Line>();
//남은 길이의 0.1단위마다,,? ===> 2라인,3라인 이 1,2보다 안나오는 경우 있음. 모든 y 검토
double step = 1;
for (int k = 0; k < ygap / step; k++)
{
List<Line> tempResult = new List<Line>();
double[] tempParam = param.ToArray();
//parameter[i] + 단위길이 - width/2 위치에 라인 생성
for (int i = 0; i < param.Count; i++)
{
tempParam[i] = param[i] + k * step - z / 2;
Line templine = new Line(new Point3d(boundingbox.Min.X, boundingbox.Min.Y + tempParam[i], 0), new Point3d(boundingbox.Max.X, boundingbox.Min.Y + tempParam[i], 0));
tempResult.Add(templine);
}
//생성된 라인을 역회전 하여 기존 상태로 되돌림.
for (int i = 0; i < tempResult.Count; i++)
{
Line tempr = tempResult[i];
tempr.Transform(Transform.Rotation(angleRadian, Vector3d.ZAxis, rotatecenter));
tempResult[i] = tempr;
}
List<Curve> aptlines = new List<Curve>();
//offset한 라인마다 충돌체크,길이조정
for (int i = 0; i < tempResult.Count; i++)
{
Curve[] inner = InnerRegion(regZero, tempResult[i].ToNurbsCurve(), z);
aptlines.AddRange(inner);
}
//결과 값의 길이 확인
var AvailableLength = GetAvailableLength(aptlines);
//wholeLines.AddRange(aptlines);
wholeLengths.Add(AvailableLength);
if (MaxLength < AvailableLength)
{
MaxLength = AvailableLength;
output = aptlines;
}
}
if (output.Count == 0)
{
results = new List<Curve>();
return 0;
}
outputUp = output.Select(n => n.DuplicateCurve()).Where(n => n.GetLength() >= 8).ToList();
outputDown = output.Select(n => n.DuplicateCurve()).Where(n => n.GetLength() >= 8).ToList();
Vector3d tv = output[0].TangentAtStart;
tv.Rotate(Math.PI / 2, Vector3d.ZAxis);
tv.Unitize();
for (int i = 0; i < outputUp.Count; i++)
{
outputUp[i].Transform(Transform.Translation(tv * z / 2));
outputDown[i].Transform(Transform.Translation(-tv * z / 2));
Polyline p = new Polyline(new Point3d[] { outputUp[i].PointAtStart, outputUp[i].PointAtEnd, outputDown[i].PointAtEnd, outputDown[i].PointAtStart, outputUp[i].PointAtStart });
outputRegions.Add(p.ToNurbsCurve());
}
results = outputRegions;
return MaxLength;
}
public static double GetAvailableLength(IEnumerable<Curve> curves)
{
double minlength = 8;
var list = curves.ToList();
double result = 0;
for (int i = 0; i < list.Count; i++)
{
var d = list[i].GetLength() >= minlength ? list[i].GetLength() : 0;
result += d;
}
return result;
}
public static Curve[] InnerRegion(Curve outside, Curve baseCurve, double regionWidth)
{
//check upper, lower bound
int underzero = 5;
Curve up = baseCurve.DuplicateCurve();
Curve down = baseCurve.DuplicateCurve();
Vector3d vu = up.TangentAtStart * regionWidth / 2;
vu.Rotate(Math.PI / 2, Vector3d.ZAxis);
Vector3d vd = -vu;
up.Translate(vu);
down.Translate(vd);
var iu = Rhino.Geometry.Intersect.Intersection.CurveCurve(up, outside, 0, 0);
var id = Rhino.Geometry.Intersect.Intersection.CurveCurve(down, outside, 0, 0);
List<double> parameters = new List<double>();
parameters.AddRange(iu.Select(n => Math.Round(n.ParameterA, underzero)));
parameters.AddRange(id.Select(n => Math.Round(n.ParameterA, underzero)));
var su = up.Split(parameters);
var sd = down.Split(parameters);
bool[] inu = su.Select(n => outside.Contains(n.PointAtNormalizedLength(0.5)) == PointContainment.Inside).ToArray();
bool[] ind = sd.Select(n => outside.Contains(n.PointAtNormalizedLength(0.5)) == PointContainment.Inside).ToArray();
if (inu.Length != ind.Length)
//why?
{
return new Curve[0];
}
var sb = baseCurve.Split(parameters);
List<Curve> result = new List<Curve>();
List<Curve> boxes = new List<Curve>();
for (int i = 0; i < inu.Length; i++)
{
if (inu[i] && ind[i])
{
//1번,3번 segments 가 사이드선
boxes.Add(new Polyline(
new Point3d[] { su[i].PointAtStart, su[i].PointAtEnd, sd[i].PointAtEnd, sd[i].PointAtStart, su[i].PointAtStart }
).ToNurbsCurve());
result.Add(sb[i]);
}
}
// check side
Vector3d testv = -baseCurve.TangentAtStart;
//makebox
for (int i = 0; i < boxes.Count; i++)
{
//외곽 기준선의 vertex들
var outps = outside.DuplicateSegments().Select(n => n.PointAtStart).ToList();
List<double> lefts = new List<double>();
List<double> rights = new List<double>();
for (int j = 0; j < outps.Count; j++)
{
//박스 i 가 점 j 를 포함하면?
if (boxes[i].Contains(outps[j]) == PointContainment.Inside)
{
var boxsegments = boxes[i].DuplicateSegments();
Point3d testleft = outps[j] - testv;
double param;
result[i].ClosestPoint(outps[j], out param);
//외곽 기준선이 testpoint 를 포함하면?
if (outside.Contains(testleft) == PointContainment.Inside)
{
//왼쪽 선 수정
lefts.Add(param);
}
else
{
//오른쪽 선 수정
rights.Add(param);
}
}
}
//lefts 중 max, rights 중 min 으로 선 조정....
var newstart = lefts.Count > 0 ? result[i].PointAt(lefts.Max()) : result[i].PointAtStart;
var newend = rights.Count > 0 ? result[i].PointAt(rights.Min()) : result[i].PointAtEnd;
result[i] = new LineCurve(newstart, newend);
}
return result.ToArray();
}
//예비 선을 모두 뽑아 일정 거리 이상 의 선들을 조합.
//느림. 정교화..?
public static double AngleMax_Josh(Curve regCurve, double floor, double width, double angleRadian, out List<Curve> resultCurves)
{
double height = regCurve.PointAtStart.Z;
double aptDistance = (height - 3.3) * 0.8;
Curve regulationCurve = regCurve.DuplicateCurve();
Curve regZero = regCurve.DuplicateCurve();
double minlength = 8;
List<Curve> output = new List<Curve>();
List<Curve> wholeLines = new List<Curve>();
List<Curve> outputUp = new List<Curve>();
List<Curve> outputDown = new List<Curve>();
List<Curve> outputRegions = new List<Curve>();
regZero.Translate(Vector3d.ZAxis * -regZero.PointAt(0).Z);
Point3d rotatecenter = AreaMassProperties.Compute(regCurve).Centroid;
regulationCurve.Rotate(angleRadian, Vector3d.ZAxis, rotatecenter);
regulationCurve.Translate(Vector3d.ZAxis * -regulationCurve.PointAt(0).Z);
var boundingbox = regulationCurve.GetBoundingBox(false);
//y범위
double ygap = boundingbox.Max.Y - boundingbox.Min.Y;
List<double> wholeLengths = new List<double>();
//같은 라인에서 쪼개진녀석들 있을수 있으므로..
List<List<Curve>> result = new List<List<Curve>>();
double step = 0.5;
for (int k = 0; k < ygap / step; k++)
{
Curve tempLine = new LineCurve(new Point3d(boundingbox.Min.X, boundingbox.Min.Y + k * step, 0), new Point3d(boundingbox.Max.X, boundingbox.Min.Y + k * step, 0));
var survivor = InnerRegion(regulationCurve, tempLine , width);
//result.Add(tempLine);
result.Add(survivor.Where(n=>n.GetLength() > minlength).ToList());
}
//var lengths = result.Select(n => n.GetLength()).ToList();
var offsetindex = (int)Math.Round((aptDistance + width) / step);
double maxlength = 0;
List<int> indexes = new List<int>();
Wornl(new List<int>(), 0, offsetindex, result, ref maxlength, ref indexes);
#region asdf
//for (int i = 0; i < result.Count; i++)
//{
// List<int> baselist = new List<int>();
// baselist.Add(i);
// if (i + offsetindex >= result.Count)
// {
// List<int> cindexes = baselist;
// double tempmvalue = cindexes.Sum(n=>result[n].Sum(m=>m.GetLength()));
// if (maxlength < tempmvalue)
// {
// maxlength = tempmvalue;
// indexes = cindexes;
// }
// }
// else
// {
// for (int j = i + offsetindex; j < result.Count; j++)
// {
// if (j + offsetindex >= result.Count)
// {
// double tempmvalue = result[i].Sum(n => n.GetLength()) + result[j].Sum(n => n.GetLength());
// if (maxlength < tempmvalue)
// {
// maxlength = tempmvalue;
// indexes = new List<int>() { i , j};
// }
// }
// else
// {
// for (int k = j + offsetindex; k < result.Count; k++)
// {
// if (k + offsetindex >= result.Count)
// {
// double tempmvalue = result[i].Sum(n => n.GetLength()) + result[j].Sum(n => n.GetLength()) + result[k].Sum(n => n.GetLength());
// if (maxlength < tempmvalue)
// {
// maxlength = tempmvalue;
// indexes = new List<int>() { i ,j ,k };
// }
// }
// else
// {
// for (int l = k + offsetindex; l < result.Count; l++)
// {
// double tempmvalue = result[i].Sum(n => n.GetLength()) + result[j].Sum(n => n.GetLength()) + result[k].Sum(n => n.GetLength()) + result[l].Sum(n => n.GetLength());
// if (maxlength < tempmvalue)
// {
// maxlength = tempmvalue;
// indexes = new List<int>() { i , j , k , l};
// }
// }
// }
// }
// }
// }
// }
//next = i + offset
//}
#endregion
for (int k = 0; k < result.Count; k++)
{
result[k].ForEach(n=>n.Rotate(-angleRadian, Vector3d.ZAxis, rotatecenter));
}
List<Curve> outcurve = new List<Curve>();
indexes.ForEach(n => outcurve.AddRange(result[n]));
resultCurves = outcurve;
return maxlength;
}
public static void Wornl(List<int> baselist, int start, int offsetindex, List<List<Curve>> result, ref double maxlength, ref List<int> indexes)
{
for (int i = start; i < result.Count; i++)
{
List<int> cindexes = new List<int>(baselist);
cindexes.Add(i);
if (i + offsetindex >= result.Count)
{
double tempmvalue = cindexes.Sum(n => result[n].Sum(m => m.GetLength()));
if (maxlength < tempmvalue)
{
maxlength = tempmvalue;
indexes = cindexes;
}
}
else
{
Wornl(cindexes, i + offsetindex,offsetindex,result,ref maxlength, ref indexes);
}
}
}
}
}
<file_sep>/Regulation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhino;
using Rhino.Geometry;
using NG.Class;
namespace NG
{
public enum PlotTypes
{
제1종일반주거지역,
제2종일반주거지역,
제3종일반주거지역,
상업지역
}
public enum BuildingTypes
{
단독다가구,
다세대
}
class Regulation
{
//도로 중심선
public static Curve RoadCenterLines(Plot plot)
{
//plot 의 boundary 와 roads 를 사용.
var segments = plot.Boundary.DuplicateSegments();
var roadwidths = plot.RoadWidths.Select(n=>n*0.5).ToList();
for (int i = 0; i < segments.Length; i++)
{
int j = i % roadwidths.Count;
Curve temp = segments[i];
var v = temp.TangentAtStart;
v.Rotate(Math.PI / 2, Vector3d.ZAxis);
temp.Translate(v * roadwidths[j]);
segments[i] = temp;
}
List<Point3d> topoly = new List<Point3d>();
for (int k = 0; k < segments.Length; k++)
{
int j = (k + 1) % segments.Length;
Line li = new Line(segments[k].PointAtStart, segments[k].PointAtEnd);
Line lj = new Line(segments[j].PointAtStart, segments[j].PointAtEnd);
double paramA;
double paramB;
var intersect = Rhino.Geometry.Intersect.Intersection.LineLine(li, lj, out paramA, out paramB, 0, false);
topoly.Add(li.PointAt(paramA));
}
topoly.Add(topoly[0]);
return new Polyline(topoly).ToNurbsCurve();
}
//정북방향
public static List<Curve> North(Curve roadCenter, Plot plot)
{
List<Curve[]> copy = new List<Curve[]>();
double t = -1;
if (UseNorth(plot))
{
//move
}
else
{
t = 0;
}
for (int i = 0; i < plot.LegalMaxF; i++)
{
double tempHeight = 3.3 + i * 2.8;//숫자 -> 나중에 변수로
var tempRoadLine = roadCenter.DuplicateCurve();
if (tempHeight < 9)//숫자 -> 나중에 변수로
tempRoadLine.Translate(Vector3d.YAxis * t * 1.5);//숫자 -> 나중에 변수로
else
tempRoadLine.Translate(Vector3d.YAxis * t * tempHeight / 2);//숫자 -> 나중에 변수로
var newCurve = Curve.CreateBooleanIntersection(tempRoadLine, plot.Boundary);
for (int j = 0; j < newCurve.Length; j++)
newCurve[j].Translate(Vector3d.ZAxis * tempHeight);
copy.Add(newCurve);
}
return copy.Select(n => n[0]).ToList();
//plot의 boundary, maxfloor, roadwidths, plottype 사용 , 도로중심선
}
public static bool UseNorth(Plot plot)
{
List<double> roadwidths = plot.RoadWidths;
PlotTypes plotinfo = plot.PlotType;
if (roadwidths.Max() >= 20)
return false;
else if ((int)plotinfo == 3)
return false;
else
return true;
}
//대지안의공지
public static List<Curve> Clearance(Plot plot)
{
//plot의 boundary, maxfloor, roadwidth, buildingtype 사용
var segments = plot.Boundary.DuplicateSegments();
var roadwidths = plot.RoadWidths;
double plotoffset = plot.BuildingType == BuildingTypes.다세대 ? 1.5 : 1;
double roadoffset = plot.BuildingType == BuildingTypes.단독다가구 ? 1.5 : 0.75;
for (int i = 0; i < segments.Length; i++)
{
int j = i % roadwidths.Count;
Curve temp = segments[i];
var v = temp.TangentAtStart;
v.Rotate(Math.PI / 2, Vector3d.ZAxis);
if (roadwidths[j] == 0)
temp.Translate(-v * plotoffset);
else
temp.Translate(-v * roadoffset);
segments[i] = temp;
}
List<Point3d> topoly = new List<Point3d>();
for (int k = 0; k < segments.Length; k++)
{
int j = (k + 1) % segments.Length;
Line li = new Line(segments[k].PointAtStart, segments[k].PointAtEnd);
Line lj = new Line(segments[j].PointAtStart, segments[j].PointAtEnd);
double paramA;
double paramB;
var intersect = Rhino.Geometry.Intersect.Intersection.LineLine(li, lj, out paramA, out paramB, 0, false);
topoly.Add(li.PointAt(paramA));
}
topoly.Add(topoly[0]);
List<Curve> result = new List<Curve>();
for (int i = 0; i < plot.LegalMaxF; i++)
{
double height = 3.3 + 2.8 * i;
Polyline poly = new Polyline(topoly);
poly.Transform(Transform.Translation(Vector3d.ZAxis * height));
result.Add(poly.ToNurbsCurve());
}
return result;
}
//채광방향
public static List<Curve> Lighting(Curve roadCenter, Plot plot, double aptAngle)
{
double d = 0;
if (plot.PlotType != PlotTypes.상업지역)
{
if (plot.LegalMaxF <= 7)
d = 0.25;
else
d = 0.5;
}
else
d = 0.25;
Curve basecurve = null;
var cp = AreaMassProperties.Compute(plot.Boundary).Centroid;
var basev = Vector3d.XAxis;
basev.Rotate(aptAngle, Vector3d.ZAxis);
var bounding = plot.Boundary.GetBoundingBox(false);
basecurve = new LineCurve(cp - basev * bounding.Diagonal.Length / 2, cp + basev * bounding.Diagonal.Length / 2);
List<Curve> result = new List<Curve>();
Curve last = roadCenter.DuplicateCurve();
double pheight = 3.3;
double fheight = 2.8;
int floor = plot.LegalMaxF;
List<Curve> debug = new List<Curve>();
for (int i = 0; i < floor; i++)
{
var height = pheight + fheight * i;
var distance = d * (height - pheight);
var segments = roadCenter.DuplicateSegments();
for (int j = 0; j < segments.Length; j++)
{
var ps = segments[j].PointAtStart;
var pe = segments[j].PointAtEnd;
double ds = 0;
double de = 0;
basecurve.ClosestPoint(ps, out ds);
basecurve.ClosestPoint(pe, out de);
Vector3d vs = basecurve.PointAt(ds) - ps;
Vector3d ve = basecurve.PointAt(de) - pe;
vs.Unitize();
ve.Unitize();
var mp = segments[j].PointAtNormalizedLength(0.5);
var ts = mp + vs;
var te = mp + ve;
if (roadCenter.Contains(ts) == PointContainment.Inside)
{
segments[j].Translate(vs * distance);
}
else if (roadCenter.Contains(te) == PointContainment.Inside)
{
segments[j].Translate(ve * distance);
}
segments[j].Translate(Vector3d.ZAxis * height);
}
List<Point3d> topoly = new List<Point3d>();
for (int k = 0; k < segments.Length; k++)
{
int j = (k + 1) % segments.Length;
Line li = new Line(segments[k].PointAtStart, segments[k].PointAtEnd);
Line lj = new Line(segments[j].PointAtStart, segments[j].PointAtEnd);
double paramA;
double paramB;
var intersect = Rhino.Geometry.Intersect.Intersection.LineLine(li, lj, out paramA, out paramB, 0, false);
topoly.Add(li.PointAt(paramA));
}
topoly.Add(topoly[0]);
var tempcurve = new PolylineCurve(topoly);
var rotation = tempcurve.ClosedCurveOrientation(Vector3d.ZAxis);
var selfintersection = Rhino.Geometry.Intersect.Intersection.CurveSelf(tempcurve, 0);
var parameters = selfintersection.Select(n => n.ParameterA).ToList();
parameters.AddRange(selfintersection.Select(n => n.ParameterB));
var spl = tempcurve.Split(parameters);
var f = NewJoin(spl);
var merged = f.Where(n => n.ClosedCurveOrientation(Vector3d.ZAxis) == rotation).ToList();
debug.AddRange(merged);
for (int j = merged.Count - 1; j >= 0; j--)
{
var tc = merged[j].DuplicateCurve();
tc.Translate(Vector3d.ZAxis * -tc.PointAtStart.Z);
if (Curve.CreateBooleanDifference(tc, last).Length == 0)
{
last = tc;
result.Add(merged[j]);
}
}
}
return result;
}
public static List<Curve> NewJoin(IEnumerable<Curve> spl)
{
Queue<Curve> q = new Queue<Curve>(spl);
Stack<Curve> s = new Stack<Curve>();
List<Curve> f = new List<Curve>();
while (q.Count > 0)
{
Curve temp = q.Dequeue();
if (temp.IsClosable(0))
{
temp.MakeClosed(0);
f.Add(temp);
}
else
{
if (s.Count > 0)
{
Curve pop = s.Pop();
var joined = Curve.JoinCurves(new Curve[] { pop, temp });
if (joined[0].IsClosable(0))
{
joined[0].MakeClosed(0);
f.Add(joined[0]);
}
else
{
s.Push(pop);
s.Push(temp);
}
}
else
{
s.Push(temp);
}
}
}
if (s.Count > 0)
{
var last = Curve.JoinCurves(s);
f.AddRange(last);
}
return f;
}
//합체!
public static List<Curve> MergedRegulation(Plot plot, double angle)
{
var roadCenter = RoadCenterLines(plot);
var north = North(roadCenter, plot);
var clearance = Clearance(plot);
var lighting = Lighting(roadCenter, plot, angle);
List<Curve> result = new List<Curve>();
int minimum = north.Count < clearance.Count ? north.Count : clearance.Count;
minimum = minimum < lighting.Count ? minimum : lighting.Count;
for (int i = 0; i < minimum; i++)
{
var a = Curve.CreateBooleanIntersection(north[i], clearance[i]);
var b = Curve.CreateBooleanIntersection(a[0], lighting[i]);
if (b.Length > 0)
result.Add(b[0]);
}
return result;
}
public static List<Curve> MergedRegulation(List<Curve> a, Plot plot, double angle)
{
var roadCenter = RoadCenterLines(plot);
var lighting = Lighting(roadCenter, plot, angle);
List<Curve> result = new List<Curve>();
int minimum = a.Count < lighting.Count ? a.Count : lighting.Count;
for (int i = 0; i < minimum; i++)
{
var b = Curve.CreateBooleanIntersection(a[i], lighting[i]);
if (b.Length > 0)
result.Add(b[0]);
}
return result;
}
public static List<Curve> MergedRegulation_TopOnly(List<Curve> a, Plot plot, double angle, out int maxfloor)
{
var roadCenter = RoadCenterLines(plot);
var lighting = Lighting(roadCenter, plot, angle);
List<Curve> result = new List<Curve>();
int minimum = a.Count < lighting.Count ? a.Count : lighting.Count;
int temporary = 0;
for (int i = minimum - 1; i >= 0; i--)
{
var b = Curve.CreateBooleanIntersection(a[i], lighting[i]);
if (b.Length > 0)
{
result.Add(b[0]);
temporary = i+1;
break;
}
}
maxfloor = temporary;
return result;
}
}
}
<file_sep>/BindingClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rhino.Geometry;
namespace NG.Class
{
public class BindingClass
{
public List<string> omg { get; set; } = new List<string>() { "1종 일반", "2종 일반", "3종 일반", "상업" };
}
public class PlotSetting
{
//plottype = 용도지역
public List<PlotTypes> PlotType { get; set; } = new List<PlotTypes>() { PlotTypes.제1종일반주거지역,PlotTypes.제2종일반주거지역,PlotTypes.제3종일반주거지역,PlotTypes.상업지역};
public List<double> LegalFAR { get; set; } = new List<double>() { 150, 200, 250, 1300 };
public List<double> LegalCVR { get; set; } = new List<double>() { 60, 60, 50, 80 };
public List<int> LegalMaxF { get; set; } = new List<int>() { 4, 7, 10, 30 };
public List<double> Roads { get; set; } = new List<double> { 4 };
}
public class BuildingSetting
{
//buildingtype = 건물유형
//........
public List<string> BuildingType { get; set; } = new List<string>() { "단독/다가구", "다세대" };
public List<double> Near_Plot { get; set; } = new List<double>() { 1, 1.5 };
public List<double> Near_Road { get; set; } = new List<double>() { 0.75, 1.5 };
}
public class UnitSettings
{
public List<string> TypeName { get; set; } = new List<string>() { "30m2형", "45m2형", "59m2형", "76m2형", "84m2형", "103m2형" };
public List<double> ExclusiveArea { get; set; } = new List<double>() { 30, 45, 59, 76, 84, 103 };
public List<double> Area { get; set; }
public List<double> MinWidth { get; set; }
public List<double> MaxWidth { get; set; }
public UnitSettings()
{
Area = ExclusiveArea.Select(n => n * 1.5).ToList();
MinWidth = new List<double>() { 3, 4, 5, 6, 7, 8 };
MaxWidth = new List<double>() { 8, 9, 10, 11, 12, 13 };
}
}
public class UnitSetting
{
public string TypeName { get; set; }
public double ExclusiveArea { get; set; }
public double Area { get; set; }
public double MinWidth { get; set; }
public double MaxWidth { get; set; }
public double Rate { get; set; }
public double CoreArea { get; set; }
public double CorridorArea { get; set; }
//simple ver
}
public class Plot
{
public PlotTypes PlotType { get; set; }
public List<double> RoadWidths { get; set; }
public double LegalFAR { get; set; }
public double LegalCVR { get; set; }
public int LegalMaxF { get; set; }
public Curve Boundary { get; set; }
public BuildingTypes BuildingType {get;set;}
public double Area { get { if (Boundary == null) return 0; else return AreaMassProperties.Compute(Boundary).Area; } }
}
}
<file_sep>/NGPlugIn.cs
using Rhino.PlugIns;
using Rhino.UI;
namespace NG
{
///<summary>
/// <para>Every RhinoCommon .rhp assembly must have one and only one PlugIn-derived
/// class. DO NOT create instances of this class yourself. It is the
/// responsibility of Rhino to create an instance of this class.</para>
/// <para>To complete plug-in information, please also see all PlugInDescription
/// attributes in AssemblyInfo.cs (you might need to click "Project" ->
/// "Show All Files" to see it in the "Solution Explorer" window).</para>
///</summary>
public class NGPlugIn : Rhino.PlugIns.PlugIn
{
public NGPlugIn()
{
Instance = this;
}
///<summary>Gets the only instance of the NGPlugIn plug-in.</summary>
public static NGPlugIn Instance
{
get; private set;
}
protected override LoadReturnCode OnLoad(ref string errorMessage)
{
System.Type panel_type = typeof(PanelHost);
var b = panel_type.IsPublic;
try
{
Panels.RegisterPanel(this, panel_type, "SampleWpf", Properties.Resources.Icon1);
}
catch (System.Exception e)
{
throw e;
}
return LoadReturnCode.Success;
}
// You can override methods here to change the plug-in behavior on
// loading and shut down, add options pages to the Rhino _Option command
// and mantain plug-in wide options in a document.
}
[System.Runtime.InteropServices.Guid("4FF5E249-AEE3-4F7B-8EFB-78CE8B358156")]
public class PanelHost : RhinoWindows.Controls.WpfElementHost
{
public PanelHost()
: base(new Panel(), null) // No view model (for this example)
{
}
/// <summary>
/// Returns the ID of this panel.
/// </summary>
public static System.Guid PanelId
{
get
{
return typeof(PanelHost).GUID;
}
}
}
}
|
1f105216ae0c9cc05a4b6b4891710802836634a9
|
[
"C#"
] | 9
|
C#
|
11o9/NG
|
12d07439ed497ed3de3254c5432cd9eb7f78ebad
|
b5f78e9f0f71d22c4c43148eecbb9f536222d560
|
refs/heads/master
|
<file_sep>#!/bin/bash
# (1)判断参数个数
if [ $# -le 1 ]; then
echo "参数个数必须大于1..."
exit 0
fi
# (2)设置常量参数
target=./
work_dir=work
uncompress_dir=uncompress
library_dir=BOOT-INF/lib
# (3)设置输入文件和输出文件参数
# (3.1)the name of the library that should be uncompressed
#library_name="spring-boot-starter-web-2.1.4.RELEASE.jar"
# (3.2)the obfuscated artifact
original_jar='springboot-kafka-storm-0.0.1-SNAPSHOT.jar'
# (3.3)the new obfuscated artifact (can be the same)
repacked_jar='springboot-kafka-storm-repack-0.0.1-SNAPSHOT.jar'
# (4)build the obfuscated library
mvn clean package -Dobfuscation
# (5)create working directory and copy obfuscated artifact
mkdir target/$work_dir
cp target/$original_jar target/$work_dir
cd target/$work_dir
# (6)extract contents of obfuscated artifact
jar xvf $original_jar
# (6.1)do not delete original file
#rm $original_jar
# (7)uncompress the target library and jar again without compression (c0)
##########Begin##########
# 若传入多个参数,将各个包进行解压即可
# 循环获取相应的参数,并对其进行解压
for param in $@
do
########Action########
echo "创建目录"$uncompress_dir
mkdir $uncompress_dir
#(7.1)将library_name赋值为参数,并将其移动到解压目录
library_name=$param
mv $library_dir/$library_name $uncompress_dir
#(7.2)进入解压目录,将Jar包进行解压;并删除原Jar包
cd $uncompress_dir
jar xvf $library_name
rm $library_name
#(7.3)将解压的内容重新打包,并将新Jar包拷贝到Lib目录
jar c0mf ./META-INF/MANIFEST.MF $library_name *
mv $library_name ../$library_dir
cd ..
#(7.4)删除加压的临时目录
rm -r $uncompress_dir
echo "删除目录"$uncompress_dir
echo "解压成功..."$library_name
########Action########
done
#删除servlet-api
rm -f $library_dir/servlet-api-2.5.jar
##########End ##########
#(8) jar the complete obfuscated artifact again
#(8.1) it is important here to copy the manifest as otherwise the library would not be executeable any more by spring-boot
jar c0mf ./META-INF/MANIFEST.MF ../$repacked_jar *
#(9) cleanup work dir
cd ..
rm -r $work_dir
#(10)End
echo "解压成功......\n"
|
7e64a190839189feaa932fb59eadfd46d5b30d98
|
[
"Shell"
] | 1
|
Shell
|
wanglg007/MySetup
|
e78b67a65396586ce2dae7c3048fad9866337147
|
2569140d30ca0279f97971eadef63e9a4dd469d7
|
refs/heads/master
|
<file_sep>
text = input("input the text\n")
shift = input("input the shift\n")
cypherString = ""
for c in text:
if c.isalpha():
#check limites
num = ord(c)
cipherValue = num + int(shift)
if c.isupper():
li = "A"
ls = "Z"
else:
li = "a"
ls = "z"
#check upper and lower bounds
if cipherValue < ord(li):
cipherValue = ord(ls) - (ord(li) - cipherValue -1)
# print(chr(cipherValue))
if cipherValue > ord(ls):
cipherValue = ord(li) + (cipherValue - ord(ls) ) -1
# print(chr(cipherValue))
cipherValue = chr(cipherValue)
else:
cipherValue = c
cypherString += cipherValue
print(cypherString)<file_sep>import re
def checkpasswort(password):
if re.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$",password):
return True
else:
return False
def __main__():
passw = input("informe a senha\n")
if checkpasswort(passw):
print("senha valida")
else:
print("senha invalida")
__main__()
<file_sep>
OptimizerValues = {}
def isPerfectNum(num, OptimizerPD = False):
listDiv = [1]
div = 2
opNum = num
while (opNum != 1):
if OptimizerPD and opNum in OptimizerValues:
listDiv = listDiv + [x*y for x in OptimizerValues[opNum] for y in listDiv ]
# listDiv.append(num)
break
if opNum%div == 0:
listDiv = listDiv + [div*x for x in listDiv]
opNum = opNum / div
else:
div+=1
# print(listDiv)
if OptimizerPD:
OptimizerValues[num] = listDiv.copy()
if num != 1:
listDiv.remove(num)
listDiv = set(listDiv)
return listDiv, (sum(listDiv) == num)
#The optimizer, uses PD to calculate faster, in the end of the output files pfnumberoutputNormal.txt and
#pfnumberoutputOptimizer.txt has a time comparison
def __main__():
print("perfect numbers 1-10000")
for x in range(1,10001):
# print(x)
r1, r2 = isPerfectNum(x, OptimizerPD=True)
# print(r1,r2)
if r2:
print(x)
__main__()<file_sep>
def isPalindromeRecursive(word,start=-1,end=-1):
if start == -1 and end ==-1:
start = 0
end = len(word) -1
return isPalindromeRecursive(word,start,end)
if start >= end:
return True
elif word[end] == word[start]:
return isPalindromeRecursive(word,start+1,end-1)
else:
return False
def __main__():
x = input("type the word\n")
if isPalindromeRecursive(x):
print("the word is a palindrome")
else:
print("the word is not a palindrome")
__main__()
|
3e819a340ceed1151c6481e0eb34613c060223c2
|
[
"Python"
] | 4
|
Python
|
the-last-question/CodeTask-1-Rafael-Bessa
|
5e8a3acbebaffd8402191b603da7dbe01baebb76
|
4f520193b7a1cf558e9706632f386d15dbfadcba
|
refs/heads/master
|
<repo_name>Kyutatsu/practice<file_sep>/cms/mul3.py
#!/Users/kyutatsu/Documents/web_development/webenv/bin/python
import sys
num = sys.argv[-1]
num = int(num) * 3
print(num)<file_sep>/api/views.py
import json
from collections import OrderedDict
from django.http import HttpResponse
from cms.models import Book, Impression
def render_json_response(request, data, status=None):
json_str = json.dumps(data, ensure_ascii=False, indent=2)
callback = request.GET.get('callback')
if not callback:
callback = request.POST.get('callback')
if callback:
# これ何が起こるんや...??? url(json)ってなんや...??-->> これがjsのAjaxで使うやつらしい。
json_str = "%s(%s)" % (callback, json_str)
response = HttpResponse(json_str, content_type='application/javascript; charset=UTF-8', status=status)
# こっちはわかる。
else:
response = HttpResponse(json_str, content_type='application/json; charset=UTF-8', status=status)
return response
def book_list(request):
books = []
for book in Book.objects.all().order_by('id'):
impressions = []
# ↓でQuerySet取れる。Impression.objects.filter(book_id=book.id)とせんでええんやな。
for impression in book.impressions.order_by('id'):
temp_impression_info_dict = OrderedDict([
('id', impression.id),
('comment', impression.comment),
])
impressions.append(temp_impression_info_dict)
temp_book_info_dict = OrderedDict([
('id', book.id),
('name', book.name),
('publisher', book.publisher),
('page', book.page),
('impressions', impressions),
])
books.append(temp_book_info_dict)
data = OrderedDict([('books', books)])
return render_json_response(request, data)
|
25c6e67c0cffc074174ffd5b5a4e9ed73adcec62
|
[
"Python"
] | 2
|
Python
|
Kyutatsu/practice
|
00305883d15f19cddfa95e213f8db4c9828d312b
|
0863693a065d0a3c375343a28dc694b31d009ae9
|
refs/heads/main
|
<file_sep>const gameState = {
score: 0,
starRating: 5,
currentWaveCount: 1,
customersServedCount: 0,
customerIsReady: false,
cam: {},
readyForNextOrder: true,
gameSpeed: 3,
serviceCountdown: {},
currentMusic: {},
totalWaveCount: 3,
countdownTimer: 1500
}
// Gameplay scene
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' })
}
preload() {
// Preload images
const baseURL = 'https://content.codecademy.com/courses/learn-phaser/fastfoodie/';
this.load.image('Chef', `${baseURL}art/Chef.png`);
this.load.image('Customer-1', `${baseURL}art/Customer-1.png`);
this.load.image('Customer-2', `${baseURL}art/Customer-2.png`);
this.load.image('Customer-3', `${baseURL}art/Customer-3.png`);
this.load.image('Customer-4', `${baseURL}art/Customer-4.png`);
this.load.image('Customer-5', `${baseURL}art/Customer-5.png`);
this.load.image('Floor-Server', `${baseURL}art/Floor-Server.png`);
this.load.image('Floor-Customer', `${baseURL}art/Floor-Customer.png`);
this.load.image('Tray', `${baseURL}art/Tray.png`);
this.load.image('Barrier', `${baseURL}art/Barrier.png`);
this.load.image('Star-full', `${baseURL}art/Star-full.png`);
this.load.image('Star-half', `${baseURL}art/Star-half.png`);
this.load.image('Star-empty', `${baseURL}art/Star-empty.png`);
// Preload song
this.load.audio('gameplayTheme', [
`${baseURL}audio/music/2-gameplayTheme.ogg`,
`${baseURL}audio/music/2-gameplayTheme.mp3`
]); // Credit: "Pixel Song #18" by hmmm101: https://freesound.org/people/hmmm101
// Preload SFX
this.load.audio('placeFoodSFX', [
`${baseURL}audio/sfx/placeFood.ogg`,
`${baseURL}audio/sfx/placeFood.mp3`
]); // Credit: "action_02.wav" by dermotte: https://freesound.org/people/dermotte
this.load.audio('servingCorrectSFX', [
`${baseURL}audio/sfx/servingCorrect.ogg`,
`${baseURL}audio/sfx/servingCorrect.mp3`
]); // Credit: "Video Game SFX Positive Action Long Tail" by rhodesmas: https://freesound.org/people/djlprojects
this.load.audio('servingIncorrectSFX', [
`${baseURL}audio/sfx/servingIncorrect.ogg`,
`${baseURL}audio/sfx/servingIncorrect.mp3`
]); // Credit: "Incorrect 01" by rhodesmas: https://freesound.org/people/rhodesmas
this.load.audio('servingEmptySFX', [
`${baseURL}audio/sfx/servingEmpty.ogg`,
`${baseURL}audio/sfx/servingEmpty.mp3`
]); // Credit: "Computer Error Noise [variants of KevinVG207's Freesound#331912].wav" by Timbre: https://freesound.org/people/Timbre
this.load.audio('fiveStarsSFX', [
`${baseURL}audio/sfx/fiveStars.ogg`,
`${baseURL}audio/sfx/fiveStars.mp3`
]); // Credit: "Success 01" by rhodesmas: https://freesound.org/people/rhodesmas
this.load.audio('nextWaveSFX', [
`${baseURL}audio/sfx/nextWave.ogg`,
`${baseURL}audio/sfx/nextWave.mp3`
]); // Credit: "old fashion radio jingle 2.wav" by rhodesmas: https://freesound.org/people/chimerical
}
create() {
// Stop, reassign, and play the new music
gameState.currentMusic.stop();
gameState.currentMusic = this.sound.add('gameplayTheme');
gameState.currentMusic.play({ loop: true });
// Assign SFX
gameState.sfx = {};
gameState.sfx.placeFood = this.sound.add('placeFoodSFX');
gameState.sfx.servingCorrect = this.sound.add('servingCorrectSFX');
gameState.sfx.servingIncorrect = this.sound.add('servingIncorrectSFX');
gameState.sfx.servingEmpty = this.sound.add('servingEmptySFX');
gameState.sfx.fiveStars = this.sound.add('fiveStarsSFX');
gameState.sfx.nextWave = this.sound.add('nextWaveSFX');
// Create environment sprites
gameState.floorServer = this.add.sprite(gameState.cam.midPoint.x, 0, 'Floor-Server').setScale(0.5).setOrigin(0.5, 0);
gameState.floorCustomer = this.add.sprite(gameState.cam.midPoint.x, gameState.cam.worldView.bottom, 'Floor-Customer').setScale(0.5).setOrigin(0.5, 1);
gameState.table = this.add.sprite(gameState.cam.midPoint.x, gameState.cam.midPoint.y, 'Barrier').setScale(0.5);
// Create player and tray sprites
gameState.tray = this.add.sprite(gameState.cam.midPoint.x, gameState.cam.midPoint.y, 'Tray').setScale(0.5);
gameState.player = this.add.sprite(gameState.cam.midPoint.x, 200, 'Chef').setScale(0.5);
// Display the score
gameState.scoreTitleText = this.add.text(gameState.cam.midPoint.x, 30, 'Score', { fontSize: '15px', fill: '#666666' }).setOrigin(0.5);
gameState.scoreText = this.add.text(gameState.cam.midPoint.x, gameState.scoreTitleText.y + gameState.scoreTitleText.height + 20, gameState.score, { fontSize: '30px', fill: '#000000' }).setOrigin(0.5);
// Display the wave count
gameState.waveTitleText = this.add.text(gameState.cam.worldView.right - 20, 30, 'Wave', { fontSize: '64px', fill: '#000000' }).setOrigin(1, 1).setScale(0.25);
gameState.waveCountText = this.add.text(gameState.cam.worldView.right - 20, 30, gameState.currentWaveCount + '/' + gameState.totalWaveCount, { fontSize: '120px', fill: '#000000' }).setOrigin(1, 0).setScale(0.25);
// Display number of customers left
gameState.customerCountText = this.add.text(gameState.cam.worldView.right - 20, 80, `Customers left: ${gameState.customersLeftCount}`, { fontSize: '15px', fill: '#000000' }).setOrigin(1);
// Generate wave group
gameState.customers = this.add.group();
this.generateWave();
// Generate meals feed to customers
gameState.currentMeal = this.add.group();
gameState.currentMeal.fullnessValue = 0;
// Push keyboards to serve food
gameState.keys = {};
gameState.keys.Enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
gameState.keys.A = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A);
gameState.keys.S = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S);
gameState.keys.D = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
// Stars ratings System
gameState.starGroup = this.add.group();
this.drawStars();
}
update() {
if (gameState.readyForNextOrder === true) {
gameState.readyForNextOrder = false;
gameState.customerIsReady = false;
if (gameState.customersServedCount > 0) {
gameState.currentCustomer.meterContainer.visible = false;
// Move each customer before current one
for (let i = 0; i < gameState.customersServedCount; i++) {
gameState.previousCustomer = gameState.customers.children.entries[i];
this.tweens.add({
targets: gameState.previousCustomer,
duration: 750,
x: '-=300',
angle: 0,
ease: 'Power2',
});
}
};
// Move the new current customer
gameState.currentCustomer = gameState.customers.children.entries[gameState.customersServedCount];
this.tweens.add({
targets: gameState.currentCustomer,
duration: 1000,
delay: 100,
angle: 90,
x: gameState.player.x,
ease: 'Power2',
onComplete: () => {
gameState.customerIsReady = true;
gameState.currentCustomer.meterContainer.visible = true;
// If player is too slow, go to next order
gameState.serviceCountdown = this.time.delayedCall(gameState.countdownTimer * gameState.gameSpeed, function () {
this.moveCustomerLine();
}, [], this);
}
});
// Move the upcoming customers
for (let j = 0; j < gameState.customersLeftCount; j++) {
let nextCustomer = gameState.customers.children.entries[gameState.customersServedCount + 1 + j];
let nextCustomerPositionX = 1024 + (200 * j);
this.tweens.add({
targets: nextCustomer,
x: '-=200',
delay: 200,
duration: 1500,
ease: 'Power2'
});
}
}
// When customers infront of the chef
if (gameState.customerIsReady) {
// Count time
gameState.currentCustomer.timerMeterBody.width = gameState.currentCustomer.meterBase.width - (gameState.serviceCountdown.getProgress() * gameState.currentCustomer.meterBase.width);
// Based on the ratio of the time, change color of the timer bar
if (gameState.serviceCountdown.getProgress() > .75) {
gameState.currentCustomer.timerMeterBody.setFillStyle(0xDB533A);
} else if (gameState.serviceCountdown.getProgress() > .25) {
gameState.currentCustomer.timerMeterBody.setFillStyle(0xFF9D00);
} else {
gameState.currentCustomer.timerMeterBody.setFillStyle(0x3ADB40);
}
}
//check if the user pressed any key :3
if (Phaser.Input.Keyboard.JustDown(gameState.keys.A)) {
this.placeFood('Burger', 5);
gameState.sfx.placeFood.play();
} else if (Phaser.Input.Keyboard.JustDown(gameState.keys.S)){
this.placeFood('Fries', 3);
gameState.sfx.placeFood.play();
} else if (Phaser.Input.Keyboard.JustDown(gameState.keys.D)){
this.placeFood('Shake', 1);
gameState.sfx.placeFood.play();
} else if (Phaser.Input.Keyboard.JustDown(gameState.keys.Enter)) {
if (gameState.readyForNextOrder === false && gameState.customerIsReady === true) {
gameState.serviceCountdown.remove();
this.moveCustomerLine();
this.updateCustomerCountText();
}
}
}
/* WAVES */
// Generate wave
generateWave() {
// Add the total number of customers per wave here:
gameState.totalCustomerCount = Math.ceil(Math.random() * 10);
gameState.customersServedCount = 0;
this.updateCustomerCountText();
for (let i = 0; i < gameState.totalCustomerCount; i++) {
// Create your container below and add your customers to it below:
const customerContainer = this.add.container(gameState.cam.worldView.right + (200 * i), gameState.cam.worldView.bottom - 140);
gameState.customers.add(customerContainer);
// Customer sprite randomizer
let customerImageKey = Math.ceil(Math.random() * 5);
// Draw customers here!
let customer = this.add.sprite(0, 0, `Customer-${customerImageKey}`).setScale(0.5);
customerContainer.add(customer);
// Fullness meter container
customerContainer.fullnessMeter = this.add.group();
// Define capacity
customerContainer.fullnessCapacity = Math.ceil(Math.random() * 5 * gameState.totalWaveCount);
// If capacity is an impossible number, reshuffle it until it isn't
while (customerContainer.fullnessCapacity === 12 || customerContainer.fullnessCapacity === 14) {
customerContainer.fullnessCapacity = Math.ceil(Math.random() * 5) * gameState.totalWaveCount;
}
// Edit the meterWidth
let meterWidth = customerContainer.fullnessCapacity * 10;
customerContainer.meterContainer = this.add.container(0, customer.y + (meterWidth / 2));
// Add the customerContainer.meterContainer to customerContainer
customerContainer.add(customerContainer.meterContainer);
// Add meter base
customerContainer.meterBase = this.add.rectangle(-130, customer.y, meterWidth, 33, 0x707070).setOrigin(0);
customerContainer.meterBase.setStrokeStyle(6, 0x707070);
customerContainer.meterBase.angle = -90;
customerContainer.meterContainer.add(customerContainer.meterBase);
// Add timer countdown meter body
customerContainer.timerMeterBody = this.add.rectangle(customerContainer.meterBase.x + 22, customer.y + 1, meterWidth + 4, 12, 0x3ADB40).setOrigin(0);
customerContainer.timerMeterBody.angle = -90;
customerContainer.meterContainer.add(customerContainer.timerMeterBody);
// Create container for individual fullness blocks
customerContainer.fullnessMeterBlocks = [];
// Create fullness meter blocks
for (let j = 0; j < customerContainer.fullnessCapacity; j++) {
customerContainer.fullnessMeterBlocks[j] = this.add.rectangle(customerContainer.meterBase.x, customer.y - (10 * j), 10, 20, 0xDBD53A).setOrigin(0);
customerContainer.fullnessMeterBlocks[j].setStrokeStyle(2, 0xB9B42E);
customerContainer.fullnessMeterBlocks[j].angle = -90;
customerContainer.fullnessMeter.add(customerContainer.fullnessMeterBlocks[j]);
customerContainer.meterContainer.add(customerContainer.fullnessMeterBlocks[j]);
}
// Hide meters
customerContainer.meterContainer.visible = false;
}
}
// Update customer count
updateCustomerCountText() {
gameState.customersLeftCount = gameState.totalCustomerCount - gameState.customersServedCount;
gameState.customerCountText.setText(`Customers left: ${gameState.customersLeftCount}`);
gameState.waveCountText.setText(gameState.currentWaveCount + '/' + gameState.totalWaveCount);
}
// Place food with diff keys
placeFood(food, fullnessValue) {
if (gameState.currentMeal.children.entries.length < 3 && gameState.customerIsReady === true) {
gameState.sfx.placeFood.play();
let Xposition = (gameState.cam.midPoint.x - 90) + gameState.currentMeal.children.entries.length * 90;
if (food === 'Burger') {
gameState.currentMeal.create(Xposition, gameState.cam.midPoint.y, 'Burger').setScale(0.5);
} else if (food === 'Fries') {
gameState.currentMeal.create(Xposition, gameState.cam.midPoint.y, 'Fries').setScale(0.5);
} else if (food === 'Shake') {
gameState.currentMeal.create(Xposition, gameState.cam.midPoint.y, 'Shake').setScale(0.5);
}
gameState.currentMeal.fullnessValue += fullnessValue;
for (let i = 0; i < gameState.currentMeal.fullnessValue; i++) {
if (i < gameState.currentCustomer.fullnessCapacity) {
if (gameState.currentMeal.fullnessValue < gameState.currentCustomer.fullnessCapacity) {
gameState.currentCustomer.fullnessMeterBlocks[i].setFillStyle(0xFFFA81);
} else if (gameState.currentMeal.fullnessValue === gameState.currentCustomer.fullnessCapacity) {
gameState.currentCustomer.fullnessMeterBlocks[i].setFillStyle(0x3ADB40);
gameState.currentCustomer.fullnessMeterBlocks[i].setStrokeStyle(2, 0x2EB94E);
} else {
gameState.currentCustomer.fullnessMeterBlocks[i].setFillStyle(0xDB533A);
gameState.currentCustomer.fullnessMeterBlocks[i].setStrokeStyle(2, 0xB92E2E);
}
}
}
}
}
// Make customers move forward
moveCustomerLine() {
gameState.currentCustomer.fullnessValue = gameState.currentMeal.fullnessValue;
this.updateStars(game, gameState.currentCustomer.fullnessValue, gameState.currentCustomer.fullnessCapacity)
gameState.currentMeal.clear(true);
gameState.currentMeal.fullnessValue = 0;
gameState.customersServedCount++;
// If no more customers
if (gameState.customersServedCount === gameState.totalCustomerCount) {
gameState.currentWaveCount += 1;
if (gameState.currentWaveCount > gameState.totalWaveCount) {
this.scene.stop('GameScene');
this.scene.start('WinScene');
} else {
this.destroyWave();
gameState.gameSpeed -= 1;
}
} else {
gameState.readyForNextOrder = true;
}
}
// Generate rating stars on the left corner of the screen
drawStars() {
gameState.starGroup.clear(true);
for (let i = 0; i < gameState.starRating; i++) {
let spacebetween = i * 50;
gameState.starGroup.create(50 + spacebetween, 50, "Star-full").setScale(0.5);
}
}
// Updating the star rating during the game process
updateStars() {
if (gameState.currentMeal.fullnessValue === gameState.currentCustomer.fullnessCapacity) {
gameState.currentCustomer.list[0].setTint(0x3ADB40);
gameState.sfx.servingCorrect.play();
gameState.score += 100;
gameState.scoreText.setText(gameState.score);
if (gameState.starRating < 5) {
gameState.starRating += 1;
}
if (gameState.starRating === 5) {
gameState.sfx.fiveStars.play();
}
} else if (gameState.starRating > 1) {
if (gameState.fullnessValue > 0) {
gameState.starRating -= 1;
gameState.currentCustomer.list[0].setTint(0xDBD53A);
gameState.sfx.servingIncorrect.play();
} else {
gameState.currentCustomer.list[0].setTint(0xDB533A);
gameState.sfx.servingEmpty.play();
gameState.starRating -= 2;
}
if (gameState.starRating < 1) {
this.scene.stop('GameScene');
this.scene.start('LoseScene');
}
} else {
this.scene.stop('GameScene');
this.scene.start('LoseScene');
}
this.drawStars();
}
// Destroy wave
destroyWave() {
gameState.sfx.nextWave.play();
gameState.currentCustomer.meterContainer.visible = false;
// Change text origin after short pause so it's not noticeable to players
this.time.delayedCall(750, function () {
gameState.waveTitleText.setOrigin(.5, 1);
gameState.waveCountText.setOrigin(.5, 0);
}, [], game);
// Center the wave count text
this.tweens.add({
targets: [gameState.waveTitleText, gameState.waveCountText],
x: gameState.cam.midPoint.x,
y: gameState.cam.midPoint.y,
scaleX: 1,
scaleY: 1,
duration: 500,
delay: 750,
ease: 'Power2',
onComplete: () => {
// Change text origin again after pause
this.time.delayedCall(750, function () {
gameState.waveTitleText.setOrigin(1, 1);
gameState.waveCountText.setOrigin(1, 0);
}, [], game);
// Decenter the wave count text
this.tweens.add({
targets: [gameState.waveTitleText, gameState.waveCountText],
x: gameState.cam.worldView.right - 20,
y: 30,
scaleX: .25,
scaleY: .25,
duration: 500,
delay: 750,
ease: 'Power2'
});
}
});
for (let i = 0; i < gameState.customersServedCount; i++) {
// Move each customer forward and rotate them
this.tweens.add({
targets: gameState.customers.children.entries[i],
x: '-=300',
angle: 0,
duration: 750,
ease: 'Power2',
onComplete: () => {
// Move the customers offscreen
this.tweens.add({
targets: gameState.customers.children.entries[i],
x: '-=900',
duration: 1200,
ease: 'Power2',
onComplete: () => {
// Remove customers from the group
gameState.customers.clear(true);
this.generateWave();
gameState.readyForNextOrder = true;
}
});
}
});
}
this.drawStars();
}
// Restart the game
restartGame() {
gameState.score = 0;
gameState.starRating = 5;
gameState.currentWaveCount = 1;
gameState.customersServedCount = 0;
gameState.readyForNextOrder = true;
gameState.gameSpeed = 3;
}
}
<file_sep># FastFoodie
### JavaScript, Phaser.js
Players play as the server and have three choices to meet customers' requirements(burger, fries, and milkshake). According to whether or not players meet each customer's requirement, they will get reward and penalty.

|
ed15152139120c6f20518acacd190aedca31ed6f
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
tqc1120/FastFoodie
|
cee9c7dd1310e431229775447d4391378365a5ca
|
bf70a1a4a0bdcca4085d8b9ed30452c309a153c4
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
# 1、发送普通邮件 2、发送带附件邮件
def mail(receiver, subject, content, cc_list):
my_sender = 'xxxx' # 发件人邮箱账号
my_pass = '<PASSWORD>' # 发件人邮箱密码
msg = MIMEMultipart()
msg['From'] = Header(my_sender, 'utf-8') # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = ','.join(receiver) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Cc'] = ",".join(cc_list) #抄送
msg['Subject'] = Header(subject, 'utf-8') # 邮件的主题,也可以说是标题,'utf-8'
text = MIMEText(content, 'plain', 'utf-8')
msg.attach(text)
server = smtplib.SMTP_SSL("smtp.chinatelecom.cn", 465, timeout=10)
server.login(my_sender, my_pass)
server.sendmail(my_sender, receiver, msg.as_string())
def mail_file(receiver, subject, content, address, cc_list):
rename = address.split('\\')[-1]
my_sender = 'xxxx' # 发件人邮箱账号
my_pass = '<PASSWORD>' # 发件人邮箱密码
msg = MIMEMultipart()
msg['From'] = my_sender # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] =','.join(receiver) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Cc'] = ",".join(cc_list)
msg['Subject'] = Header(subject, 'utf-8') # 邮件的主题,也可以说是标题,'utf-8'
text = MIMEText(content, 'plain', 'utf-8')
msg.attach(text)
# 可以多个附件 for循环
f = open(address, 'rb')
att1 = MIMEApplication(f.read())
att1.add_header('Content-Disposition', 'attachment', filename=rename)
msg.attach(att1)
·
server = smtplib.SMTP_SSL("smtp.chinatelecom.cn", 465, timeout=30)
server.login(my_sender, my_pass)
server.sendmail(my_sender, receiver + cc_list, msg.as_string()) # cc_list 抄送
if __name__ == "__main__":
# mail(['<EMAIL>'], u'步test', u'请查收', ["<EMAIL>"])
try:
mail_file(['<EMAIL>'], u'主题', u'内容', u'C:\\余额对应.xlsx', ["<EMAIL>"])
print 'done!'
except Exception as e:
print 'fail'
<file_sep>#coding:utf-8
import poplib
import cStringIO
import email
import base64
import chardet
import time
#pop3 get email
'''
1. 连接pop3服务器 (poplib.POP3.__init__)
2. 发送用户名和密码进行验证 (poplib.POP3.user poplib.POP3.pass_)
3. 获取邮箱中信件信息 (poplib.POP3.stat)
4. 收取邮件 (poplib.POP3.retr)
5. 删除邮件 (poplib.POP3.dele)
6. 退出 (poplib.POP3.quit)
'''
for t in range(1,100):
print t
M=poplib.POP3('pop3.163.com')
M.user('<EMAIL>')
M.pass_('xxx')
print M.stat()
numMessages=len(M.list()[1])
print 'num of messages',numMessages
for i in range(1,numMessages+1):
print u"正在读取第%s封邮件"%i
m = M.retr(i)
buf = cStringIO.StringIO()
for j in m[1]:
print >>buf,j
buf.seek(0)
#
msg = email.message_from_file(buf)
for part in msg.walk():
contenttype = part.get_content_type()
filename = part.get_filename()
mycode=part.get_content_charset()
if filename:
data = part.get_payload(decode=True)
h = email.Header.Header(filename)
dh = email.Header.decode_header(h)
fname = dh[0][0]
encodeStr = dh[0][1]
if encodeStr != None:
fname = fname.decode(encodeStr, mycode)
print fname
#end if
f = open("mail%s%s"%(i,fname), 'wb')
f.write(data)
f.close()
time.sleep(0.1)
|
376d59c729fafe938c40ad2bcf98217d0d370567
|
[
"Python"
] | 2
|
Python
|
caoqinan/python-demo
|
1728fceb08d39425ba8321dbd40ef6a0a28bbc5d
|
06211f91874280b8e355034b19d6989262b3b567
|
refs/heads/master
|
<repo_name>SAM-AI-Intro/hw2_sammy<file_sep>/hw2_grace.py
# ----------------------------------------------------------------------
# Name: homework2
# Purpose: Practice writing Python functions
#
# Author(s): SAM
# ----------------------------------------------------------------------
"""
Implement functions to track Sammy's consumption of carrots.
Sammy is an eco-friendly intelligent agent powered by carrots.
His task is to collect medals at various positions in a grid.
Sammy can only move North, South, West or East.
The carrot consumption per step for each direction is given by a
dictionary that is passed to the various functions.
The functions must work with any dictionary specifying the carrot
consumption.
"""
# Constants
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
def get_distance(sammy, medal):
"""
Compute the distance from sammy to the given medal
:param sammy: (tuple) representing the position of Sammy in the grid
:param medal: (tuple) representing the position of a given medal
:return: (tuple) the distance unit horizontally and vertically
"""
x, y = sammy[0] - medal[0], sammy[1] - medal[1]
return x, y
def cost_distance(distance, carrot_cost):
"""
Compute the number of carrots from the given distance
:param distance: (tuple) the distance unit horizontally and vertically
:param carrot_cost: (dictionary) representing the carrot consumption
per step for each direction
:return: (tuple) the number of carrots horizontally and vertically
"""
horizon, vertical = 0, 0
if distance[0] >= 0:
horizon = distance[0] * carrot_cost[WEST]
elif distance[0] < 0:
horizon = distance[0] * carrot_cost[EAST]
if distance[1] >= 0:
vertical = distance[1] * carrot_cost[NORTH]
elif distance[1] < 0:
vertical = distance[1] * carrot_cost[SOUTH]
return abs(horizon), abs(vertical)
def carrots_to_medal(sammy, medal, carrot_cost):
"""
Compute the number of carrots that Sammy consumes to reach the
given medal.
:param sammy (tuple) representing the position of Sammy in the grid
:param medal (tuple) representing the position of a given medal
:param carrot_cost (dictionary) representing the carrot consumption
per step for each direction
:return: (integer) the number of carrots.
"""
distance = get_distance(sammy, medal)
horizon, vertical = cost_distance(distance, carrot_cost)
return horizon + vertical
def min_carrots(sammy, medals, carrot_cost):
"""
Compute the minimum number of carrots that Sammy consumes to reach a
medal.
:param sammy (tuple) representing the position of Sammy in the grid
:param medals (set of tuples) containing the positions of all medals
:param carrot_cost (dictionary) representing the carrot consumption
per step for each direction
:return: (integer) the number of carrots.
"""
if not medals:
return None
cost_list = [carrots_to_medal(sammy, m, carrot_cost) for m in medals]
return min(cost_list)
def most_carrots_medal(sammy, medals, carrot_cost):
"""
Find the medal that Sammy consumes the most carrots to reach.
:param sammy (tuple) representing the position of Sammy in the grid
:param medals (set of tuples) containing the positions of all medals
:param carrot_cost (dictionary) representing the carrot consumption
per step for each direction
:return: (tuple) the position of the medal
"""
if not medals:
return None
return max(medals, key=lambda m: carrots_to_medal(sammy, m, carrot_cost))
def main():
# The main function is used to test the 3 functions.
carrot_cost1 = {WEST: 1, EAST: 2, SOUTH: 3, NORTH: 4}
sammy1 = (10, 3)
print('----------Testing the carrots_to_medal function----------')
print(carrots_to_medal(sammy1, (3, 1), carrot_cost1)) # 15
print(carrots_to_medal(sammy1, (0, 8), carrot_cost1)) # 25
print(carrots_to_medal(sammy1, (10, 6), carrot_cost1)) # 9
print(carrots_to_medal(sammy1, (14, 3), carrot_cost1)) # 8
print(carrots_to_medal(sammy1, (13, 7), carrot_cost1)) # 18
print(carrots_to_medal(sammy1, (10, 3), carrot_cost1)) # 0
print('----------')
sammy2 = (2, 2)
carrot_cost2 = {NORTH: 1, EAST: 2, WEST: 3, SOUTH: 4}
print(carrots_to_medal(sammy2, (3, 1), carrot_cost2)) # 3
print(carrots_to_medal(sammy2, (0, 8), carrot_cost2)) # 30
print(carrots_to_medal(sammy2, (10, 6), carrot_cost2)) # 32
print(carrots_to_medal(sammy2, (14, 3), carrot_cost2)) # 28
print(carrots_to_medal(sammy2, (13, 7), carrot_cost2)) # 42
print(carrots_to_medal(sammy2, (10, 3), carrot_cost2)) # 20
print('----------Testing the min_carrots function----------')
medals1 = {(3, 1), (0, 8), (13, 7), (1, 4), (10, 6), (14, 3)}
medals2 = {(10, 3), (14, 3), (13, 7)}
print(min_carrots(sammy1, medals1, carrot_cost1)) # 8
print(min_carrots(sammy1, {}, carrot_cost1)) # None
print(min_carrots(sammy1, medals2, carrot_cost1)) # 0
print(min_carrots(sammy2, medals1, carrot_cost2)) # 3
print(min_carrots(sammy2, {}, carrot_cost2)) # None
print(min_carrots(sammy2, medals2, carrot_cost2)) # 20
print('-------Testing the most_carrots_medal function-------')
print(most_carrots_medal(sammy1, medals1, carrot_cost1)) # (0, 8)
print(most_carrots_medal(sammy1, {}, carrot_cost1)) # None
print(most_carrots_medal(sammy1, medals2, carrot_cost1)) # (13, 7)
print(most_carrots_medal(sammy1, medals2, carrot_cost2)) # (13, 7)
if __name__ == '__main__':
main()
|
8798c89d246f7967569810371023a667aa91a622
|
[
"Python"
] | 1
|
Python
|
SAM-AI-Intro/hw2_sammy
|
835432001f4ca6178d0b4bca98331e65590488c6
|
de0a83d2a93fdb05aa7c3f89037b838381e80e7c
|
refs/heads/master
|
<file_sep>require 's3'
require 'digest/md5'
require 'mime/types'
YUI_COMPRESSOR_JAR = "~/lib/yuicompressor.jar"
AWS_ACCESS_KEY_ID = ENV['AWS_ACCESS_KEY']
AWS_SECRET_ACCESS_KEY = ENV['AWS_SECRET_KEY']
AWS_BUCKET = "static.whotouse.co"
task :deploy => [:prepare, :static, :css, :img, :s3upload, :s3ify_html,
:set_meta, :www_upload, :clean] do
end
desc "Prepare for deploy"
task :prepare do
sh "mkdir -p tmp/public/"
sh "mkdir -p tmp/assets/img/"
sh "mkdir -p tmp/assets/css/"
end
desc "Move all static files to tmp pubblic"
task :static do
sh "cp public/*.html tmp/public/"
sh "cp public/*.txt tmp/public/"
sh "cp public/*.ico tmp/public/"
end
desc 'Pack stylesheets to assets folder"'
task :css do
sh "java -jar #{YUI_COMPRESSOR_JAR} public/css/style.css > tmp/assets/css/style.min.css"
end
desc "Copy image assets folder"
task :img do
sh "cp public/img/* tmp/assets/img/"
end
desc "Make all html assets point to s3"
task :s3ify_html do
Dir.glob("tmp/public/*.html").each do |file|
if File.file?(file)
text = File.read(file)
text = text.gsub(/href="css\//, "href=\"http://static.whotouse.co/css/")
text = text.gsub(/\.css"/, ".min.css\"")
text = text.gsub(/<img src="img\//, "<img src=\"http://static.whotouse.co/img/")
File.open(file, "w") {|file| file.puts text }
end
end
end
desc "Set meta content"
task :set_meta do
Dir.glob("tmp/public/*.html").each do |file|
if File.file?(file)
text = File.read(file)
text = text.gsub('<meta name="description" content="">',
'<meta name="description" content="Who to use"/>')
text = text.gsub('<meta name="author" content="">',
'<meta name="author" content="Who to use - <NAME>, <NAME>"/>')
File.open(file, "w") {|file| file.puts text }
end
end
end
desc "Upload all changed assets in assts/**/* to S3"
task :s3upload do
puts "== Uploading assets to S3/Cloudfront"
service = S3::Service.new(
:access_key_id => AWS_ACCESS_KEY_ID,
:secret_access_key => AWS_SECRET_ACCESS_KEY)
bucket = service.buckets.find(AWS_BUCKET)
STDOUT.sync = true
Dir.glob("tmp/assets/**/*").each do |file|
if File.file?(file)
remote_file = file.gsub("tmp/assets/", "")
begin
obj = bucket.objects.find_first(remote_file)
rescue
obj = nil
end
if !obj || (obj.etag != Digest::MD5.hexdigest(File.read(file)))
print "U"
obj = bucket.objects.build(remote_file)
obj.content = open(file)
obj.content_type = MIME::Types.type_for(file).first.to_s
obj.save
else
print "."
end
end
end
STDOUT.sync = false
puts
puts "== Done syncing assets"
end
desc "Upload to the www server"
task :www_upload do
sh "cd tmp && tar -zcvf public.tar.gz public/*"
sh 'cat tmp/public.tar.gz | ssh whotouse.co "cd /data/apps/whotouse.co ; tar zxvf - "'
end
desc "Clean up"
task :clean do
sh "rm -rf tmp/"
end
<file_sep># Who to use
This is whotouse.co's launch page.
|
2776ec36d15ea134db2458869292faa1050e9552
|
[
"Markdown",
"Ruby"
] | 2
|
Ruby
|
nerdyworm/launchy
|
aef2d4532748c3042883ed41230e05176282d0e0
|
34b5b2f88fb974a6ee9992b9d43dfd4e7e53761e
|
refs/heads/master
|
<file_sep>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { NavbarComponent } from './navbar/navbar.component';
import { LoginComponent } from './login/login.component';
import { SidenavComponent } from './sidenav/sidenav.component';
import { RightscreenComponent } from './rightscreen/rightscreen.component';
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { HttpClientModule } from '@angular/common/http';
import { BoardlistComponent } from './boardlist/boardlist.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
NavbarComponent,
LoginComponent,
SidenavComponent,
RightscreenComponent,
BoardlistComponent,
AppComponent
],
imports: [
FormsModule,
HttpClientModule,
NgZorroAntdModule.forRoot()
]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should create the navbar', async(() => {
const fixture = TestBed.createComponent(NavbarComponent);
const navbar = fixture.debugElement.componentInstance;
expect(navbar).toBeTruthy();
}));
it('should create the login', async(() => {
const fixture = TestBed.createComponent(LoginComponent);
const login = fixture.debugElement.componentInstance;
expect(login).toBeTruthy();
}));
it('should create the boardlist', async(() => {
const fixture = TestBed.createComponent(BoardlistComponent);
const boardlist = fixture.debugElement.componentInstance;
expect(boardlist).toBeTruthy();
}));
});
<file_sep>import { Component, OnInit, Injectable, EventEmitter, Output } from '@angular/core';
import { LoginService, ILoginForm } from './login.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
providers: [LoginService],
styleUrls: ['./login.component.css']
})
@Injectable()
export class LoginComponent implements OnInit {
loginData: ILoginForm = {
userName: '',
password: ''
};
@Output() notify: EventEmitter<string> = new EventEmitter();
constructor(private loginService: LoginService) { }
ngOnInit() {
}
loginClicked(loginData: ILoginForm): void {
this.loginService.loginIn(loginData)
.subscribe(data => console.log(data),
error => {
console.log(`login error with: ${error}`);
},
() => {
// console.log(`login finished`);
this.notify.emit('LOGIN_SUCCESSFUL');
}
);
}
}
<file_sep>kdtwz
=====================
Powered by [KeystoneJS](http://keystonejs.com).
目录结构:
/ 根目录
/dist 通过tsc编译后的keystone 生成文件目录
/front angular2前端目录
/src 后台源代码目录
/templates 模板目录
Run steps:
1. 进入front目录,运行 grunt
2. 进入根目录, 运行 grunt
3. 进入根目录, 运行npm start
前后组合思路:
在keystone项目根目录中建立前端框架目录front, 分别编译前端目录和后端目录。
编译前端目录后,利用copyStaticAssets.js拷贝前端编译后的文件到后台dist目录中的keystone静态目录文件:public文件夹中。
利用grunt自动运行ng的编译,以及keystone的ts编译,然后启动keystone。<file_sep>import { Component, OnInit, Injectable, EventEmitter, Output } from '@angular/core';
interface IButtonName {
ButtonName: string;
}
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
@Injectable()
export class NavbarComponent implements OnInit {
@Output() notify: EventEmitter<string> = new EventEmitter<string>();
menuItems: IButtonName [] = [
{ ButtonName: '物资采购管理'},
{ ButtonName: 'Contact'},
{ ButtonName: 'Blog' },
{ ButtonName: 'Email' },
{ ButtonName: 'Login'}
];
constructor() { }
ngOnInit() {
}
navClicked(item: IButtonName) {
// console.log(`item clicked: ${item.ButtonName}`);
this.notify.emit(`${item.ButtonName}`);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IManufacturer } from '../IBoardList';
@Injectable()
export class BoardlistService {
private listUrl = '/boards';
constructor(private http: HttpClient) { }
getBoardList() {
return this.http.get<IManufacturer[]>(this.listUrl);
}
}
<file_sep>export enum FilterType {
Manufacturer,
BoardType,
None
}
export interface IFilter {
filterName: string;
filterType: FilterType;
filterValues?: string [];
}
export interface IApplyFilter {
filterType: FilterType;
filterValue: string;
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HandleError } from '../http-error-handler.service';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
export interface ILoginForm {
userName: string;
password: string;
}
export interface ILoginResult {
loginSatus: string;
}
@Injectable()
export class LoginService {
private handleError: HandleError;
constructor(private http: HttpClient) { }
loginIn(loginData: ILoginForm): Observable<ILoginResult> {
return this.http.post<ILoginResult>('/login', loginData, {
headers: httpOptions.headers
});
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { SidenavComponent } from './sidenav.component';
describe('SidenavComponent', () => {
let component: SidenavComponent;
let fixture: ComponentFixture<SidenavComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SidenavComponent ],
imports: [NgZorroAntdModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SidenavComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
// 测试组件类中的方法:closeNav 是否被调用
it('should spyOn function closeNav', () => {
const classInstance = new SidenavComponent();
const testcloseNavSpy = spyOn(classInstance, 'closeNav');
classInstance.closeNav();
expect(testcloseNavSpy).toHaveBeenCalled();
});
// 测试组件类中的方法:showNav 是否被调用
it('should spyOn function showNav', () => {
const classInstance = new SidenavComponent();
const testcloseNavSpy = spyOn(classInstance, 'showNav');
classInstance.showNav();
expect(testcloseNavSpy).toHaveBeenCalled();
});
});
<file_sep>import { Component, OnInit, Injectable, EventEmitter, Output } from '@angular/core';
import { IBoardListItem, IManufacturer } from '../IBoardList';
import { BoardlistService } from './boardlist.service';
import { IApplyFilter, FilterType } from '../IFilters';
@Component({
selector: 'app-boardlist',
providers: [BoardlistService],
templateUrl: './boardlist.component.html',
styleUrls: ['./boardlist.component.css']
})
@Injectable()
export class BoardlistComponent implements OnInit {
manufacturerList: IManufacturer [];
currentList: IManufacturer [];
jsonResponse: IManufacturer;
@Output() notify: EventEmitter<IBoardListItem> = new EventEmitter<IBoardListItem>();
boardClicked(board: IBoardListItem) {
// console.log(`board: ${board.name}`);
this.notify.emit(board);
}
applyFilter( filter: IApplyFilter) {
this.currentList = new Array();
if (filter.filterType === FilterType.Manufacturer) {
for (const manuf of this.manufacturerList) {
if (manuf.manufacturer === filter.filterValue) {
this.currentList.push(manuf);
}
}
}
if (filter.filterType === FilterType.BoardType) {
for (const manuf of this.manufacturerList) {
const currentManuf: IManufacturer = {
manufacturer: manuf.manufacturer,
manufacturer_logo: manuf.manufacturer_logo
};
currentManuf.boards = new Array();
let boardFound = false;
for (const board of manuf.boards) {
for (const boardtype of board.board_types ) {
// console.log(`boardtype: ${boardtype.board_type} filtervalue: ${filter.filterValue}`);
if (boardtype.board_type === filter.filterValue) {
boardFound = true;
currentManuf.boards.push(board);
}
}
}
if (boardFound) {
this.currentList.push(currentManuf);
}
}
}
if (filter.filterType === FilterType.None) {
this.currentList = this.manufacturerList;
}
}
constructor(private boardListService: BoardlistService) {
// console.log(`BordListCompnent constructor`);
this.boardListService.getBoardList().subscribe(
(data: IManufacturer[]) => {
this.manufacturerList = this.currentList = data;
// console.log(this.manufacturerList);
},
error => {
console.log(`error: ${error}`);
},
() => {
console.log(`success`);
}
);
}
ngOnInit() {
}
}
<file_sep>import { TestBed, inject } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { BoardlistService } from './boardlist.service';
import { IManufacturer } from '../IBoardList';
describe('HttpClient testing', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [BoardlistService],
imports: [HttpClientTestingModule]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
/// Tests begin ///
it('boardlistService should get data', inject([BoardlistService], (service: BoardlistService) => {
const testData: IManufacturer = { manufacturer: 'Test Data', manufacturer_logo: 'Test Logo' };
// Make an HTTP GET request
httpClient.get<IManufacturer>('/boards')
.subscribe(data =>
// When observable resolves, result should match test data
expect(data).toEqual(testData)
);
}));
});
|
9c7a80bf275d8415774efa2e153322c1e5719385
|
[
"Markdown",
"TypeScript"
] | 10
|
TypeScript
|
Tangcuyu/KDTWZ
|
688e5fa7f8c003e57ee539b1d0829ee1685165d3
|
e12d8c422c3216c820897e6591271345273ce857
|
refs/heads/master
|
<repo_name>adeleinesantos/warmup.july26<file_sep>/app.warmup.js
var arr = ['Carmel', 'Oscar','Adeleine'];
var obj = {
FirstName: 'Diego',
LastName: 'Fierro',
grade: 10
}
|
e18a1da5583f21d6a203241d0af8ffab68036567
|
[
"JavaScript"
] | 1
|
JavaScript
|
adeleinesantos/warmup.july26
|
49298367000ee7d0e9510fe6b15bbabdf19c4fdf
|
8bdcefad711c8418880b5fb3aa44da88930fd53f
|
refs/heads/master
|
<file_sep>#include <QCoreApplication>
#include <iostream>
#include "jordanelmannet.h"
using namespace std;
void main(){
JordanElmanNet net;
net.StartLearning();
net.GeneratePredictedSequence();
// int p = 2;
// int m = 6;
// vec input(p);
// mat X(m, p);
// for (int i = 0; i < m; i++)
// {
// for (int j = 0; j < p; j++)
// {
// X(i, j) = i + j + 1;
// cout << X(i, j) << " ";
// }
// cout << endl;
// }
// input = conv_to<vec>::from(X.row(0));
// cout << input;
return;
}
<file_sep>/**
* Автор: <NAME>
*/
#ifndef JORDANELMANNET_H
#define JORDANELMANNET_H
#include <iostream>
#include <armadillo>
/**
* Armadillo - библиотека линейной алгебры
* Авторы: Dr <NAME>
* Dr <NAME>
*/
using namespace std;
using namespace arma;
class JordanElmanNet
{
public:
JordanElmanNet();
void StartLearning();
void GeneratePredictedSequence();
private:
vector<double> sequence; //исходная последовательность
vector<double> resSequence; //выходная последовательность
vector<double> expSequence; //ожидаемая выходная последовательность
int k; //размерность обучаемой последовательности
int p; //количество столбцов в матрице обучения - размер окна
int m; //количество образов или количество нейронов скрытого слоя
double e; //максимально допустимая ошибка
double alfa; //коэффициент альфа
int N; //максимальное количество шагов обучения
int r; //количество предсказываемых элементов
vec input; //входной вектор (p)
vec hidden; //выходной вектор из скрытого слоя (m)
double output; //выходной вектор из выходного слоя (1)
vec context_hidden; //контекстный слой для скрытого слоя (m)
double context_output; //контекстный слой для выходного слоя (1)
mat X; //матрица обучения m x p
mat W; //матрица весов W на скрытом слое p x m
mat Wch_h; //матрица весов между контекстным с предыдущими значениями скрытого и скрытым слоем m x m
mat W_; //матрица весов W_ на выходном слое m x 1
mat Wco_h; //матрица весов между контекстным с предыдущим значением выходного и скрытым слоем 1 x m
vec T; //пороговые значения для скрытого слоя
double T_; //пороговые значения для выходного слоя
vector<double> expValues; //значения, которые необходимо получить при обучении для каждого входного вектора
void EnterInputParameters();
void ShowInputParameters();
bool CheckInputParameters();
void PrintSequence();
void CreateMatrixes();
double GetRandom();
double ActFunc(double x);
double DerOfActFunc(double x);
void DirectErrorProp();
void BackErrorProp(double val);
vector<double> CalcFibonacciSeries(int num);
vector<double> CalcFactorialFunction(int num);
vector<double> CalcPeriodicFunction(int num);
vector<double> CalcPowerFunction(int num);
vector<double> CalcSequenceOfNaturalNumbers(int num);
};
#endif // JORDANELMANNET_H
<file_sep># MRZvIS_Lab_2
Вариант 12
Модель сети Джордана-Элмана с функцией активации гиперболического тангенса
Model of the Jordan-Elman network with the hyperbolic tangent activation function
|
db1316529e55df6fbe65779904fb006573e7c9c7
|
[
"Markdown",
"C++"
] | 3
|
C++
|
NastyaArt/MRZvIS_Lab_2
|
a0072e337d4c10e68b2c7d01023882d73628c929
|
60d854bdc682c46ef3ac7ad217b5e24921d7b099
|
refs/heads/master
|
<file_sep>## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ---- eval = FALSE------------------------------------------------------------
# glm(formula, family, data)
## ---- eval = FALSE------------------------------------------------------------
# for(m in model){
# glm(m$formula, family, data)
# }
## -----------------------------------------------------------------------------
N <- 800
set.seed(0)
sex <- sample(c('F', 'M'), N, TRUE, c(.4, .6))
snp <- rbinom(N, 2, c(.4, .3, .3))
age <- runif(N, 20, 60)
pr <- plogis(.1 + .5 * I(sex == 'F') + .5 * I(age > 40) - .2 * snp)
cancer <- rbinom(N, 1, pr)
ext <- data.frame(cancer, sex, snp, age, stringsAsFactors = FALSE)
## -----------------------------------------------------------------------------
m1 <- glm(cancer ~ sex, data = ext, family = "binomial")
m2 <- glm(cancer ~ I(age < 30) + I(age > 50), data = ext, family = "binomial")
m3 <- glm(cancer ~ I(snp == 0), data = ext, family = "binomial")
## -----------------------------------------------------------------------------
summary(m2)$coef
## -----------------------------------------------------------------------------
model1 <- list(formula = 'cancer ~sex',
info = data.frame(var = names(coef(m1))[-1],
bet = coef(m1)[-1], stringsAsFactors = FALSE))
model2 <- list(formula = 'cancer~I(age< 30) + I(age > 50)',
info = data.frame(var = names(coef(m2))[3],
bet = coef(m2)[3], stringsAsFactors = FALSE))
model3 <- list(formula = 'cancer ~ I(snp == 0)',
info = data.frame(var = names(coef(m3))[-1],
bet = coef(m3)[-1], stringsAsFactors = FALSE))
model <- list(model1, model2, model3)
model2
## -----------------------------------------------------------------------------
nsample <- matrix(N, 3, 3)
## -----------------------------------------------------------------------------
ncase <- matrix(sum(cancer), 3, 3)
nctrl <- matrix(sum(!cancer), 3, 3)
## -----------------------------------------------------------------------------
n <- 300
set.seed(1)
sex <- sample(c('F', 'M'), n, TRUE, c(.4, .6))
snp <- rbinom(n, 2, c(.4, .3, .3))
age <- runif(n, 20, 60)
pr <- plogis(.3 + .5 * I(sex == 'F') + .5 * I(age > 40) - .2 * snp)
cancer <- rbinom(n, 1, pr)
smoking <- sample(c(TRUE, FALSE), n, TRUE, c(.3, .7))
int <- data.frame(cancer, sex, snp, age, smoking, stringsAsFactors = FALSE)
## -----------------------------------------------------------------------------
library(gim)
fit1 <- gim(cancer ~ I(sex == "F") + I(age > 40) + snp + smoking,
"case-control", int, model,
ncase = ncase, nctrl = nctrl)
summary(fit1)
## -----------------------------------------------------------------------------
fit0 <- glm(cancer ~ I(sex =="F") + I(age>40) +snp + smoking,
"binomial", int)
summary(fit0)$coef
## -----------------------------------------------------------------------------
int$sex_F <- ifelse(int$sex == "F", 1, 0)
int$age_gt_40 <- ifelse(int$age > 40, 1, 0)
fit2 <- gim(cancer ~ sex_F + age_gt_40 + snp + smoking,
"case-control", int, model,
ncase = ncase, nctrl = nctrl)
summary(fit2)
## -----------------------------------------------------------------------------
model[[1]]
## -----------------------------------------------------------------------------
int$dummy_sex <- ifelse(int$sex == "M", 1, 0)
model1 <- list(formula = 'cancer ~ dummy_sex',
info = data.frame(var = 'dummy_sex',
bet = coef(m1)[-1], stringsAsFactors = FALSE))
model1
model <- list(model1, model2, model3)
fit3 <- gim(cancer ~ I(sex == "F") + I(age > 40) + snp + smoking,
"case-control", int, model,
ncase = ncase, nctrl = nctrl)
summary(fit3)
## -----------------------------------------------------------------------------
coef(fit1)
confint(fit1, level = 0.9)
all(diag(vcov(fit1))^.5 == summary(fit1)$coef[, 2])
<file_sep>
hess.lo <- function(para, map, data, ref, inv.V, bet0, outcome){
h <- numDeriv::jacobian(score.lo, para, map = map, data = data, ref = ref, inv.V = inv.V, bet0 = bet0, outcome = outcome)
colnames(h) <- names(para)
rownames(h) <- names(para)
h
}
|
3ab4931dd17eef3f0ba3153e86e06a00e147809a
|
[
"R"
] | 2
|
R
|
cran/gim
|
2182d9a6cee5dd3455f36ad743018ec5f840fbc5
|
a5a8ffddbb5b59ed1bb152ec24845227bf9ff390
|
refs/heads/master
|
<repo_name>nemidebyalep/Parcial_01<file_sep>/app/src/main/java/com/example/parcial_01/Materias.java
package com.example.parcial_01;
import android.app.Activity;
public class Materias extends Activity {
}
|
342b68a0c64601126707897c982a8802e4fb9cd5
|
[
"Java"
] | 1
|
Java
|
nemidebyalep/Parcial_01
|
757ec02d2c1bc22a52fc2d48206bc50603a93e59
|
f6ce6f7f258ed838611a37f61a16193499ed1be0
|
refs/heads/master
|
<repo_name>andresmachado/djangogirlstutorial<file_sep>/blog/utils.py
from django.core.exceptions import PermissionDenied
def can_view_post(request, post):
if request.user.is_authenticated and post.author.id == request.user.id:
request.can_edit = True
return request
def can_edit_post(request, post):
if request.user.is_authenticated and post.author.id == request.user.id:
request.can_edit = True
return request
raise PermissionDenied<file_sep>/blog/urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='home'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
url(r'^post/new/$', views.post_new, name='post_new'),
url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),
url(r'^login/$', views.login_user, name='login_user'),
url(r'^logout/$', views.logout_user, name='logout_user'),
url(r'^accounts/register/$', views.register, name='register'),
url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'),
url(r'^myaccount/home/(?P<pk>[0-9]+)/$', views.user_profile, name='user_profile'),
url(r'^myaccount/home/(?P<pk>[0-9]+)/myposts/$', views.user_posts, name='user_posts'),
]
<file_sep>/blog/views.py
from django.http import *
from django.shortcuts import render, get_object_or_404, redirect, render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.utils import timezone
from django.views.generic import DeleteView
from django.core.urlresolvers import reverse
from .forms import PostForm, UserCreateForm
from .utils import can_edit_post, can_view_post
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts':posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
request = can_view_post(request, post)
return render(request, 'blog/post_detail.html', {'post': post})
@login_required
def post_new(request):
if request.user.is_authenticated():
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
else:
return redirect('login_user')
@login_required
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
request = can_edit_post(request, post)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
def login_user(request):
# logout(request)
username = password = ''
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('home'))
return render_to_response('blog/login.html', context_instance=RequestContext(request))
def logout_user(request):
if request.user.is_authenticated():
logout(request)
return render(request, 'blog/login.html')
else:
return redirect('home')
def register(request):
if request.method == 'POST':
form = UserCreateForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('registration_complete'))
else:
form = UserCreateForm()
token = {}
token.update(csrf(request))
token['form'] = UserCreateForm()
return render_to_response('blog/signup.html', token)
def registration_complete(request):
return render_to_response('blog/registration_complete.html')
@login_required
def user_profile(request, pk):
user = get_object_or_404(User, pk=pk)
if request.user.id == pk:
return render(request, 'blog/user_profile.html', {'user': user})
else:
return render(request, 'blog/user_profile.html')
@login_required
def user_posts(request, pk):
posts = Post.objects.filter(author=pk).order_by('-published_date')
return render(request, 'blog/user_posts.html', {'posts': posts})<file_sep>/blog/templates/blog/user_posts.html
{% extends 'blog/base.html' %}
{% block title %}Your posts{% endblock %}
{% block content %}
{% include 'blog/personal_posts.html' %}
{% endblock %}
|
5d83d908f9c1dde3930ae02556230eff703fdc9c
|
[
"Python",
"HTML"
] | 4
|
Python
|
andresmachado/djangogirlstutorial
|
09d95753ec3f2985a0f040ab3924b1041f1c8974
|
8cec76aa79dff6126625615d4927b9d80a0f7d76
|
refs/heads/master
|
<file_sep># -*-coding: utf-8-*-
import urllib.request
url = 'http://www.gsxt.gov.cn/index.html'
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11')
proxy = '172.16.58.3:83'
proxy_support = urllib.request.ProxyHandler({'http':proxy})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read()
print(html)
<file_sep>import turtle
#turtle.color("white")
turtle.goto(-300,100)
turtle.color("black")
turtle.speed(5)
turtle.pensize(10)
turtle.forward(60)
turtle.right(90)
turtle.forward(60)
turtle.right(90)
turtle.forward(60)
turtle.left(90)
turtle.forward(60)
turtle.left(90)
turtle.forward(60)
turtle.color("white")
turtle.forward(30)
turtle.color("black")
turtle.forward(60)
turtle.left(90)
turtle.forward(120)
turtle.left(90)
turtle.forward(60)
<file_sep>import requests
from bs4 import BeautifulSoup
res = requests.get('http://www.dytt8.net/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
print(soup)
<file_sep>import jieba.analyse
def keyword_dict():
# 读取存放用户邮件内容的 email_info.txt 文件
text_from_file_with_apath = open('email_info.txt', encoding='utf-8').read()
# 精确分词,返回列表
wordlist_after_jieba = jieba.lcut(text_from_file_with_apath, cut_all=False)
TextBayes = open('TextBayes.txt', encoding='utf-8').read().splitlines()
key = []
num = []
for i in range(0, len(wordlist_after_jieba)):
if len(wordlist_after_jieba[i]) > 0:
if wordlist_after_jieba[i] not in key and wordlist_after_jieba[i] not in TextBayes:
key.append(wordlist_after_jieba[i])
num.append(wordlist_after_jieba.count(wordlist_after_jieba[i]))
word_cloud = dict(zip(key, num))
print(word_cloud)
return word_cloud
keyword_dict()<file_sep># -*- coding: utf-8 -*-
import scrapy
import requests
from lxml import etree
from scrapy.http import Request
from scrapy.selector import Selector
from keti.items import InformationItem
import time
class KETI(scrapy.Spider):
name = "keti"
redis_key = 'keti:start_urls'
start_urls = ['http://xa.58.com/chuzu/0/', 'http://xa.58.com/chuzu/1/']
def parse(self, response):
item = InformationItem()
selector = Selector(response)
sites = selector.xpath('//ul[@class="listUl"]')
def clean_spaces(s):
s = s.replace(' ', '')
s = s.replace('\n', '')
s = s.replace('\r', '')
s = s.replace('\t', ' ')
s = s.replace('\f', ' ')
return s
for site in sites:
titles = [a.strip() for a in site.xpath('li/div[2]/h2/a/text()').extract() if len(clean_spaces(a)) > 0] # 标题:此写法无需调用其它函数
areas = site.xpath('li/div[2]/p[1]/text()').extract() # 面积
address = site.xpath('li/div[2]/p[2]/a[1]/text()').extract() # 地址
moneys = site.xpath('li/div[3]/div[2]/b/text()').extract() # 价钱
for (title, area, add, money) in zip(titles, areas, address, moneys):
item['title'] = title
item['area'] = clean_spaces(area)
item['address'] = add
item['money'] = money
yield item
next_page = selector.xpath('//a[@class="next"]/@href').extract()
time.sleep(1)
if next_page:
next_page = next_page[0]
yield Request(next_page, callback=self.parse)
new_url = 'http://xa.58.com/pinpaigongyu/'
yield Request(new_url, callback=self.pingpai)
def pingpai(self, response):
selector = Selector(response)
sites = selector.xpath('//ul[@class="list"]')
def clean_spaces(s):
s = s.replace(' ', '')
s = s.replace('\n', '')
s = s.replace('\r', '')
s = s.replace('\t', ' ')
s = s.replace('\f', ' ')
return s
def open_url(url):
headers = {
'Server': 'Tengine',
'Content-Type': 'text/html; charset=UTF-8',
'Connection': 'keep-alive',
'Vary': 'Accept-Encoding',
'X-Powered-By': 'PHP/5.6.20',
'Content-Encoding': 'gzip',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
req = requests.get(url, headers=headers)
req.encoding = 'utf-8'
new_selector = etree.HTML(req.text)
return new_selector
def new_address(url):
address = []
for i in url:
new_selector = open_url('http://xa.58.com' + i)
address_1 = ''.join(new_selector.xpath('//ul[@class="house-info-list"]/li[4]/span/text()'))
address_2 = ''.join(new_selector.xpath('//div[@class="detail detailAddress"]/span/text()'))
if len(address_1) > 0:
address.append(address_1)
elif len(address_2) > 0:
address.append(address_2)
else:
address.append('http://xa.58.com' + i)
return address
def str_address(str_title):
num = 0
for i in str_title:
if i == ' ':
ss = num
break
num += 1
return ss
for site in sites:
item = InformationItem()
titles = site.xpath('li/a/div[2]/h2/text()').extract() # 标题
areas = [a.strip() for a in site.xpath('li/a//div[2]/p[1]/text()').extract() if len(clean_spaces(a)) > 0] # 面积
moneys = site.xpath('li/a/div[3]/span/b/text()').extract() # 价格
#address_url = site.xpath('li/a/@href').extract() # 目标页面url
#time.sleep(1)
#address = new_address(address_url)
#time.sleep(1)
'''
for (title, area, add, money) in zip(titles, areas, address, moneys):
item['title'] = title
item['area'] = clean_spaces(area)
item['address'] = add
item['money'] = money
time.sleep(0.5)
yield item
'''
for (title, area, money) in zip(titles, areas, moneys):
item['title'] = title
item['area'] = clean_spaces(area)
item['address'] = title[4:str_address(title)]
item['money'] = money
yield item
next_page = selector.xpath('//a[@class="next"]/@href').extract()
next_page = 'http://xa.58.com' + next_page[0]
next_pages = []
next_pages.append(next_page)
time.sleep(1)
if next_pages:
next_pages = next_pages[0]
yield Request(next_pages, callback=self.pingpai)
<file_sep># -*- coding: utf-8 -*-
import pymongo
# 以下三行命令是创建python到数据库mongodb的连接
connection = pymongo.MongoClient() # 在本机运行括号里不需要写内容
tdb = connection.jikexueyuan #jikexueyuan是命名的名称,可更改
post_info = tdb.test # 同jikexueyuan一样
jike = {'name':'jike', 'age':'5', 'skill':'Python'}
god = {'name':'我爱的人', 'age':'21', 'skill':'love me', 'other':'我也是哈'}
godslaver = {'name':'月老', 'age':'unknow', 'other':'管我什么事'}
#以下三条是添加
post_info.insert(jike)
post_info.insert(god)
post_info.insert(godslaver)
# 这一条是删除
post_info.remove({'name':'极客'})
# 测试使用, 无关紧要
print('操作数据库成功')
<file_sep>import pandas as pd
# Reading data locally
df = pd.read_csv(r'D:\\Scrapy\keti\keti\keti.csv')
print(df.describe())
<file_sep>from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import string
import operator
def clean_input(in_put):
in_put = re.sub('\n+', " ", in_put).lower()
in_put = re.sub('\[[0-9]*\]]', "", in_put)
in_put = re.sub(' +', " ", in_put)
in_put = bytes(in_put, 'utf-8')
in_put = in_put.decode('ascii', 'ignore')
result = []
in_put = in_put.split()
for item in in_put:
item = item.strip(string.punctuation)
if len(item) > 1 or (item.lower()) == 'a' or item.lower() == 'i':
result.append(item)
return result
def nagrams(in_put, n):
in_put = clean_input(in_put)
output = {}
for i in range(len(in_put)-n+1):
ngramtemp = ''.join(in_put[i:i+n])
if ngramtemp not in output:
output[ngramtemp] = 0
output[ngramtemp] += 1
return output
content = str(urlopen("http://pythonsctaping.com/files/inaugurationSpeech.txt").read(), 'utf-8')
ngrams = nagrams(content, 2)
sortedNGrams = sorted(ngrams.items(), key=operator.itemgetter(1), reverse=True)
print(sortedNGrams)<file_sep># -*- coding: utf-8 -*-
import json
from urllib.request import urlopen, quote
import requests,csv
#import pandas as pd #导入这些库后边都要用到
import time
def getlnglat(address, ak):
url = 'http://api.map.baidu.com/geocoder/v2/'
output = 'json'
#ak = '<KEY>' # 自己申请的ak
#ak = '<KEY>'
add = quote(address) #由于地址变量为中文,为防止乱码,先用quote进行编码
uri = url + '?' + 'address=' + add + '&output=' + output + '&ak=' + ak
req = urlopen(uri)
res = req.read().decode() #将其他编码的字符串解码成unicode
temp = json.loads(res) #对json数据进行解析
return temp
file = open(r'D:\\Scrapy\keti\keti\point.json','w') #建立json数据文件
with open(r'D:\\Scrapy\keti\keti\keti.csv', 'r', encoding='utf-8') as csvfile: #打开csv
reader = csv.reader(csvfile)
ak1 = '<KEY>'
ak2 = '<KEY>'
num = 1
for line in reader: #读取csv里的数据
# 忽略第一行
if reader.line_num == 1: #由于第一行为变量名称,故忽略掉
continue # line是个list,取得所有需要的值
b = line[2].strip() #将第一列address读取出来并清除不需要字符
c= line[3].strip() #将第二列money读取出来并清除不需要字符
lng = getlnglat("西安市" + b, ak2)['result']['location']['lng'] #采用构造的函数来获取经度
lat = getlnglat("西安市" + b, ak2)['result']['location']['lat'] #获取纬度
str_temp = '{"lat":' + str(lat) + ',"lng":' + str(lng) + ',"count":' + str(c) +'},'
print(num, str_temp) #也可以通过打印出来,把数据copy到百度热力地图api的相应位置上
num += 1
file.write(str_temp) #写入文档
if num%100 == 0:
time.sleep(10)
file.close() #保存
<file_sep>import urllib.request
response = urllib.request.urlopen("http://placekitten.com/g/500/600")
cat = response.read()
with open('E:\car.jpg', 'wb') as f:
f.write(cat)
<file_sep>import json
import requests
import logging
import os
import re
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(filename='lqq_qzone.log', level=logging.DEBUG)
url = 'https://user.qzone.qq.com/proxy/domain/m.qzone.qq.com/cgi-bin/new/get_msgb?'
with open('data.json', encoding='utf-8') as f:
for num, i in enumerate(reversed(list(f))):
logging.info(f'这是第{num}页留言')
datas = eval(i)
for data in reversed(datas['data']['commentList']):
try:
name = data['nickname']
time = data['pubtime']
info = data['htmlContent']
info_2 = data['ubbContent'].strip()
logging.info(f'{time}: {name} say: {info_2}')
replyList = data['replyList']
if replyList:
logging.info(f'{"="*10}以下为回复内容:')
for reply in replyList:
content = reply['content']
contenter = reply['nick']
logging.info(f'\t\t{contenter},Reply:{content}')
except KeyError:
logging.warning('这是一条私密评论')
headers = {
# ':authority':'user.qzone.qq.com',
# ':method':'GET',
# ':path':'/proxy/domain/m.qzone.qq.com/cgi-bin/new/get_msgb?uin=583829693&hostUin=610098967&num=10&start=50&hostword=0&essence=1&r=0.024324804308030412&iNotice=0&inCharset=utf-8&outCharset=utf-8&format=jsonp&ref=qzone&g_tk=213132643&qzonetoken=<KEY>',
# ':scheme':'https',
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'cookie': '',
'referer': 'https://user.qzone.qq.com/123456789?ptlang=2052',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
# a = s.get(url, params=params)
for i in range(90):
params = {
'uin': '583829693',
'hostUin': '303067975',
'num': '10',
'start': i*10,
'hostword': '0',
'essence': '1',
# 'r':'0.024324804308030412',
'iNotice': '0',
'inCharset': 'utf-8',
'outCharset': 'utf-8',
'format': 'jsonp',
'ref': 'qzone',
'g_tk': '1995018497',
'qzonetoken': '49d9abc22e253773ae35dd1fff98105bd317f3787390fs827e6csa82332b06854bf80f0d6985d8c2'
}
a = requests.get(url, headers=headers, params=params)
data = json.loads(a.text[10:-2])
print('第{}页数据'.format(i), data)
# os.chdir(r'E:\新建文件夹 (2)')
# m_list = os.listdir(r'E:\新建文件夹 (2)')
# all_m = []
# for i in m_list:
# name_t = re.findall('(.*?)\.(mp3|flac|MP3|wav|ape)', i)[0]
# name, _t = name_t
# if name in all_m:
# print(name, _t)
# # try:
# # os.remove(name + '.mp3')
# # except FileExistsError:
# # os.remove(name + '.MP3')
# else:
# all_m.append(name)<file_sep># twoci fangcheng
import math
def main():
print("This program find the real solutions to a quadratic\n")
a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
delta = b * b - 4 * a * c
# discRoot = math.sqrt(delta)
if a == 0:
root = (-c) / b
print("\nThe solution is yiyuan question anwser is :", root)
elif delta > 0:
discRoot = math.sqrt(delta)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("\nThe solutions are: ", root1, root2)
elif delta == 0:
discRoot = math.sqrt(delta)
root = (-b) / (2 * a)
print("\nThe solution only one is: ", root)
else:
print("Not the solution a quadratic.")
main()
<file_sep># -*- coding: utf-8 -*-
import urllib.request
import re
import os
def url_open(url):
req = urllib.request.Request(url)
req.add_header('user-agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')# 或者等会解码
print(html)
return html
def get_imgs(url):
html = url_open(url)
p = r'<img width="190" height="190" data-img="1" src="([^"]+\.jpg)"'
imlist = re.findall(p, html)
print(imlist)
return imlist
def save_imgs(folder, img_addrs):
for each in img_addrs:
filename = each.split('/')[-1]
with open(filename, 'wb') as f:
img = url_open(each)
f.write(img)
def main(folder='jingdong'):
url = 'https://list.jd.com/list.html?cat=1315,1342,12003'
img_addrs = get_imgs(url)
save_imgs(folder, img_addrs)
if __name__ == '__main__':
main()
<file_sep>"""
去 Gmail 收件箱获取所有邮件内容
链接:'https://www.googleapis.com/auth/gmail.modify'
此外,client_secret.json应该保存在与此文件相同的目录中
"""
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import jieba.analyse
def read_all_email(GMAIL, label_id):
# SENT 发件箱、
# 获取收件箱信息字典
user_id = 'me' # 用户id
unread_msgs = GMAIL.users().messages().list(userId='me', labelIds=[label_id]).execute()
print(unread_msgs)
if 'messages' in unread_msgs:
# 获取一个字典,现在读取关键“消息”的值
mssg_list = unread_msgs['messages']
print("读取邮件数量: ", str(len(mssg_list)))
all_email_info = []
num = 1
for mssg in mssg_list:
m_id = mssg['id'] # 获取个人消息的ID
message = GMAIL.users().messages().get(userId=user_id, id=m_id).execute() # 使用API获取消息
print('正在读取第 %s 封邮件,请稍后...' % num)
# print(message['snippet'])
all_email_info.append(message['snippet'])
num += 1
# with open('email_info.txt', 'wb') as f:
# f.write(''.join(all_email_info).encode('utf-8'))
else:
print('没有数据')
def read_email_info():
# 创建具有身份验证详细信息的storage.JSON文件, 此为Google Gmail API
# 连接地址
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
store = file.Storage('storage.json')
creds = store.get()
print(creds)
if not creds.access_token_expired:
creds = creds.refresh(Http())
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
GMAIL = discovery.build('gmail', 'v1', http=creds.authorize(Http()))
label_id = 'INBOX'
read_all_email(GMAIL, label_id)
def keyword_dict():
# 读取存放用户邮件内容的 email_info.txt 文件
text_from_file_with_apath = open('email_info.txt', encoding='utf-8').read()
# 精确分词,返回列表
wordlist_after_jieba = jieba.lcut(text_from_file_with_apath, cut_all=False)
# 读取存放中文停用词表的 TextBayes.txt 文件
TextBayes = open('TextBayes.txt', encoding='utf-8').read().splitlines()
key = []
num = []
# 将分词结果对照中文停用词表剔除
for i in range(0, len(wordlist_after_jieba)):
if len(wordlist_after_jieba[i].strip()) > 2:
if wordlist_after_jieba[i] not in key and wordlist_after_jieba[i] not in TextBayes:
key.append(wordlist_after_jieba[i])
num.append(wordlist_after_jieba.count(wordlist_after_jieba[i]))
# 关键词和出现频率存放在字典中
word_cloud = dict(zip(key, num))
print(word_cloud)
return word_cloud
read_email_info()
# print(keyword_dict())
# a = open('word_cloud.json')
<file_sep># PM2.5.py
def main():
PM = eval (input("What is today a PM2.5?: "))
if PM > 250:
print("Zhongduwuran!")
elif PM > 150:
print("Yanzhongwuran!")
elif PM > 115:
print("Qingduwuran!")
elif PM > 75:
print("kongqihuanjingShizhong!")
elif PM > 35:
print("kongqizhilianglianghao!")
else:
print("Youxiu!")
main()
<file_sep>from scrapy import cmdline
cmdline.execute("scrapy crawl keti".split())
#cmdline.execute("scrapy crawl keti -o keti.csv".split())
<file_sep># # -*-coding: utf-8 -*-
# import requests
# import json
# from bs4 import BeautifulSoup
# from time import time
#
# def submit(url, content):
# params = {
# 'type': 'AUTO',
# 'i': content,
# 'doctype': 'json',
# 'xmlVersion': '1.8',
# 'keyfrom': 'fanyi.web',
# 'ue': 'UTF-8',
# 'action': 'FY_BY_ENTER',
# 'typoResult': 'true'
# }
# headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
#
# html = requests.post(url, data=params, headers=headers)
# html.encoding = 'utf-8'
# soup = BeautifulSoup(html.text, 'html.parser').decode('utf-8')
# return soup
#
# def input_results(soup):
# try:
# target = json.loads(soup)
# except:
# print("该词无法识别,请重新输入其他词汇")
# else:
# if "smartResult" in target:
# if len(target['smartResult']['entries']) > 3:
# print("翻译结果:%s" % (''.join(target['translateResult'][0][0]['tgt'])),
# '\n\t',
# (''.join(target['smartResult']['entries'][1])),
# '\n\t',
# (''.join(target['smartResult']['entries'][2])),
# '\n\t',
# (''.join(target['smartResult']['entries'][3])))
# elif len(target['smartResult']['entries']) > 2:
# print("翻译结果:%s" % (''.join(target['translateResult'][0][0]['tgt'])),
# '\n\t',
# (''.join(target['smartResult']['entries'][1])),
# '\n\t',
# (''.join(target['smartResult']['entries'][2])))
# elif len(target['smartResult']['entries']) > 1:
# print("翻译结果:%s" % (''.join(target['translateResult'][0][0]['tgt'])),
# '\n\t',
# (''.join(target['smartResult']['entries'][1])))
# else:
# print("请再试一次")
# else:
# print("翻译结果:%s" % (target['translateResult'][0][0]['tgt']))
#
# def main():
# url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rul'
# while True:
# content = input("请输入需要翻译的内容: ")
# if content == 'exit':
# break
# start = time()
# try:
# soup = submit(url, content)
# except:
# print('网络连接错误,请检查您的网络设置')
# else:
# input_results(soup)
# end = time()
# print ('用时 {}秒'.format(end - start))
#
# if __name__ == '__main__':
# main()
#
#
import os
import re
import shutil
from concurrent.futures import ThreadPoolExecutor
os.chdir('E:/BaiduYunDownload/李杰的分享/老男孩python全栈3期')
print(os.listdir())
for i in os.listdir():
if os.path.isfile(i):
pass
# reg = re.compile('python.*?\.mp4|python.*?\.avi')
# name = reg.findall(i)[0]
# os.renames(i, name)
if os.path.isdir(i):
# print('is dir', i)
os.chdir(i)
for n in os.listdir():
reg = re.compile('day\d+')
name = reg.findall(i)[0] + '-' + n
print(name)
# os.renames(n, name)
os.chdir('..')
<file_sep># BMI.py
height, weight = eval(input("请输入你的身高体重:例如(1.75, 80.5) "))
BMI = weight / (height**2)
if BMI < 18.5:
print("过轻")
elif BMI < 25:
print("正常")
elif BMI < 28:
print("过重")
elif BMI < 32:
print("肥胖")
else:
print("严重肥胖")
<file_sep>import csv
import pymysql
import you_get
# def canshu():
# position_info = []
# with open('me.csv', 'r', encoding='utf-8') as f:
# reader = csv.reader(f)
# for line in reader:
# if reader.line_num == 1:
# continue
# a = line[0], line[1], line[2], line[3], line[4], line[5]
# position_info.append(a)
# # print(type(a))
# return position_info
# test
db = pymysql.connect(host="127.0.0.1", user="root", password="<PASSWORD>", db="meituan", charset="utf8")
cursor = db.cursor()
sql = "SELECT * FROM shangjia_info"
cursor.execute(sql)
is_del = cursor.fetchall()
for i in is_del:
sql_cai = "SELECT * FROM caiping_info WHERE n_id=%s"
cursor.execute(sql_cai, i[0])
cai_info = cursor.fetchall()
print(cai_info)
<file_sep># Simple-gadget
Some less mature little things
> jd.py: 京东、天猫selenium抓取
> 12306.py: 模拟登陆抢票
> qzone.py: 获取某个qq用户留言板信息
<file_sep># -*-coding : utf-8 -*-
import time
from lxml import etree
from bs4 import BeautifulSoup
from selenium import webdriver
def moni(url, content):
browser = webdriver.PhantomJS()
#browser = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])
browser.get(url)
browser.implicitly_wait(30) # 智能等待页面加载完成
browser.find_element_by_id("live-search").send_keys(content+'\n') # 输入信息跳转
browser.find_element_by_partial_link_text(content).click() # 匹配输入内容的公司名称,进入
browser.implicitly_wait(30)
browser.switch_to_window(browser.window_handles[-1]) # 捕获最新窗口
browser.implicitly_wait(30)
# 获取数据
soup = BeautifulSoup(browser.page_source, 'lxml')
company = soup.select('div[class="in-block ml10 f18 mb5 ng-binding"]')[0].text
tag_shareholders = soup.select('th[width="22%"]')[0].text
tag_percent = soup.select('th[width="12%"]')[0].text
tag_money = soup.select('th[width="33%"]')[0].text
name = soup.select('a[event-name="company-detail-investment"]')
percent = soup.select('span[class="c-money-y ng-binding"]')
money = soup.select('''span[ng-class="item.amomon?'':'c-none'"]''')
print(company)
print(tag_shareholders, tag_percent, tag_money)
for names, percents, moneys in zip(name, percent, money):
print(names.text, percents.text, moneys.text)
browser.implicitly_wait(30)
browser.quit()
def main():
url = "http://www.tianyancha.com/search"
content = input("请输入需要查询公司的名称: ")
moni(url, content)
if __name__ == "__main__":
main()
<file_sep># -*-coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from lxml import etree
def open_url(url): #打开url,获取网页代码
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
html = requests.get(url, headers=headers)
html.encoding = 'utf-8'
selector = etree.HTML(html.text)
return selector
def introduce(selector): #定位标题位置并获取标题地址url
sites = selector.xpath('//div[@class="maincon"]/div/dl')
address = []
for site in sites:
title = ''.join(site.xpath('dt/a/text()'))
new_url = site.xpath('dt/a/@href')
address.append(''.join(new_url))
#print(title)
return address
def content(url): #进入标题地址抓取页面内容
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
title = soup.select('.headConLeft')[0].text
name = soup.select('.posSumLeft')[0].text
money = soup.select('.posinfo')[0].text
print(title, name, money)
def perform(url): #执行函数
selector = open_url(url)
url_list = introduce(selector)
for url in url_list:
content(url)
def main(): #主函数
url = 'http://xa.58.com/renli/?key=%E6%96%87%E5%91%98&cmcskey=%E6%96%87%E5%91%98&final=1&jump=1&specialtype=gls'
try:
perform(url)
except:
print("网络连接错误,请检查您的网络设置")
else:
content = input("如需查看下一页请按:y,否则请按任意键退出 ")
if content == 'y':
for page in range(2, 20):
new_url = 'http://xa.58.com/renli/pn' + str(page) + '/?key=%E6%96%87%E5%91%98&cmcskey=%E6%96%87%E5%91%98&final=1&jump=1&specialtype=gls&PGTID=0d303652-001e-322f-0a03-3f8664226838&ClickID=3'
perform(new_url)
content = input("如需查看下一页请按:y,否则请按任意键退出 ")
if content != 'y':
break
if __name__ == '__main__':
main()
<file_sep># day.py
day = "星期一星期二星期三星期四星期五星期六星期天"
n = input("请输入星期数(1-7): ")
pos = (int(n)-1) * 3
days = day[pos:pos+3]
print("今天是:"+days+".")
<file_sep>import jieba.analyse
import matplotlib.pyplot as plt
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
def keyword_dict():
# 读取存放用户邮件内容的 email_info.txt 文件
text_from_file_with_apath = open('email_info.txt', encoding='utf-8').read()
# 精确分词,返回列表
wordlist_after_jieba = jieba.lcut(text_from_file_with_apath, cut_all=False)
TextBayes = open('TextBayes.txt', encoding='utf-8').read().splitlines()
key = []
num = []
for i in wordlist_after_jieba:
if len(i) > 0:
if i not in key and i not in TextBayes:
key.append(i)
num.append(wordlist_after_jieba.count(i))
word_cloud = dict(zip(key, num))
name_list = []
num_list = []
for k, v in word_cloud.items():
if v > 100 and k.split():
name_list.append(k)
num_list.append(v)
rects = plt.bar(range(len(num_list)), num_list, color='rgby')
# X轴标题
index = range(len(name_list))
index = [float(c) + 0.4 for c in index]
plt.ylim(ymax=1000, ymin=0)
plt.xticks(index, name_list)
plt.ylabel("arrucay(%)") # X轴标签
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height, str(height) + '%', ha='center', va='bottom')
plt.show()
return word_cloud
keyword_dict()
<file_sep>import urllib.request
import os
import re
def open_url(url):
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')
page = urllib.request.urlopen(req)
html = page.read()
return html
def get_img(html):
html = open_url(url).decode('utf-8')
p = r'<img class="BDE_Image" src="([^"]+\.jpg)"'
imglist = re.findall(p, html)
for each in imglist:
filename = each.split('/')[-1]
with open(filename, 'wb') as f:
img = open_url(each)
f.write(img)
if __name__ == '__main__':
url = "http://tieba.baidu.com/p/3563409202/"
get_img(open_url(url))
<file_sep>'''
This script does the following:
- Go to Gmal inbox
- Find and read all the unread messages
- Extract details (Date, Sender, Subject, Snippet, Body) and export them to a .csv file / DB
- Mark the messages as Read - so that they are not read again
此脚本执行以下操作:
- 去Gmal收件箱
- 查找并读取所有未读消息
- 提取详细信息(日期,发件人,主题,代码段,正文)并将其导出到.csv文件/数据库
- 将邮件标记为已读 - 以使其不再读取
'''
'''
Before running this script, the user should get the authentication by following
the link: https://developers.google.com/gmail/api/quickstart/python
Also, client_secret.json should be saved in the same directory as this file
在运行此脚本之前,用户应该通过以下方式获取身份验证
链接:https://developers.google.com/gmail/api/quickstart/python
此外,client_secret.json应该保存在与此文件相同的目录中
'''
# Importing required libraries
from apiclient import discovery
from apiclient import errors
from httplib2 import Http
from oauth2client import file, client, tools
import base64
from bs4 import BeautifulSoup
import re
import time
import dateutil.parser as parser
import requests
from datetime import datetime
import datetime
import csv
# 创建具有身份验证详细信息的storage.JSON文件
# 我们正在使用修改而不是只读,因为我们将标记消息Read
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
GMAIL = discovery.build('gmail', 'v1', http=creds.authorize(Http()))
print(GMAIL)
user_id = 'me'
label_id_one = 'INBOX'
label_id_two = 'UNREAD'
# 从Inbox获取所有未读邮件
# labelIds可以相应更改
unread_msgs = GMAIL.users().messages().list(userId='me', labelIds=[label_id_one]).execute()
# 我们得到一个字典,现在读取关键“消息”的值
mssg_list = unread_msgs['messages']
print(mssg_list)
print(len(mssg_list))
print("收件箱中所有邮件数量: ", str(len(mssg_list)))
final_list = []
for mssg in mssg_list:
temp_dict = {}
m_id = mssg['id'] # 获取个人消息的ID
message = GMAIL.users().messages().get(userId=user_id, id=m_id).execute() # 使用API获取消息
print('Message snippet: %s' % message['snippet'])
# payld = message['threadId'] # 获取消息的有效载荷
# headr = payld['headers'] # 获取有效载荷的标题
#
# # print(m_id)
# # print(payld)
# # print(message)
# for one in headr: # 获取主题
# if one['name'] == 'Subject':
# msg_subject = one['value']
# temp_dict['Subject'] = msg_subject
# else:
# pass
#
# for two in headr: # 获取时间
# if two['name'] == 'Date':
# msg_date = two['value']
# date_parse = (parser.parse(msg_date))
# m_date = (date_parse.date())
# temp_dict['Date'] = str(m_date)
# else:
# pass
#
# for three in headr: # 获取发件人
# if three['name'] == 'From':
# msg_from = three['value']
# temp_dict['Sender'] = msg_from
# else:
# pass
#
# temp_dict['Snippet'] = message['snippet'] # fetching message snippet
#
# try:
#
# # Fetching message body
# mssg_parts = payld['parts'] # fetching the message parts
# part_one = mssg_parts[0] # fetching first element of the part
# part_body = part_one['body'] # fetching body of the message
# part_data = part_body['data'] # fetching data from the body
# clean_one = part_data.replace("-", "+") # decoding from Base64 to UTF-8
# clean_one = clean_one.replace("_", "/") # decoding from Base64 to UTF-8
# clean_two = base64.b64decode(bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8
# soup = BeautifulSoup(clean_two, "lxml")
# mssg_body = soup.body()
# # mssg_body is a readible form of message body
# # depending on the end user's requirements, it can be further cleaned
# # using regex, beautiful soup, or any other method
# temp_dict['Message_body'] = mssg_body
#
# except:
# pass
#
# print(temp_dict)
# final_list.append(temp_dict) # This will create a dictonary item in the final list
#
# # This will mark the messagea as read
# GMAIL.users().messages().modify(userId=user_id, id=m_id, body={'removeLabelIds': ['UNREAD']}).execute()
#
# print("Total messaged retrived: ", str(len(final_list)))
#
# '''
# The final_list will have dictionary in the following format:
# { 'Sender': '"email.com" <<EMAIL>>',
# 'Subject': 'Lorem ipsum dolor sit ametLorem ipsum dolor sit amet',
# 'Date': 'yyyy-mm-dd',
# 'Snippet': 'Lorem ipsum dolor sit amet'
# 'Message_body': 'Lorem ipsum dolor sit amet'}
# The dictionary can be exported as a .csv or into a databse
# '''
#
# # exporting the values as .csv
# with open('CSV_NAME.csv', 'w', encoding='utf-8', newline='') as csvfile:
# fieldnames = ['Sender', 'Subject', 'Date', 'Snippet', 'Message_body']
# writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',')
# writer.writeheader()
# for val in final_list:
# writer.writerow(val)
<file_sep>import math
a = 2
if a > 4:
print("dasdadsa")
print()
<file_sep>import urllib.request
import random
url = 'http://www.whatismyip.com.tw'
iplist = ['172.16.31.10:80', '192.168.3.11:80', '192.168.3.11:81', '172.16.58.3:80']
proxy_support = urllib.request.ProxyHandler({'http':random.choice(iplist)})
opener = urllib.request.build_opener(proxy_support)
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')]
urllib.request.install_opener(opener)
respone = urllib.request.urlopen(url)
html = respone.read().decode('utf-8')
print(html)
<file_sep># -*- coding : utf-8 -*-
import requests
import json
from time import time
def open_url(url, **params):
req = requests.get(url, **params)
js = req.json(encoding='utf-8')
return js
def jixi(js_1):
name = js_1['data']['result']
for i in name:
print(i['name'])
for a in i['capital']:
print(a['percent'])
print(a['amomon'])
def main():
keywords = input("请输入需要查询公司的名称: ")
start = time()
url = 'http://www.tianyancha.com/search/' + keywords + '.json?'
url_1 = 'http://www.tianyancha.com/expanse/holder.json'
js = open_url(url)
company_id = js['data'][0]['id']
param = {
'id' : company_id,
'ps' : 20,
'pn' : 1
}
js_1 = open_url(url_1, params=param)
jixi(js_1)
end = time()
print(end - start)
if __name__ == "__main__":
main()
<file_sep>import requests
from bs4 import BeautifulSoup
from datetime import datetime
res = requests.get('http://news.sina.com.cn/o/2016-11-22/doc-ifxxwsix4389213.shtml')
res.encoding = 'utf-8'
# print(res.text)
soup = BeautifulSoup(res.text, 'html.parser')
title = soup.select('#artibodyTitle')[0].text # 获取标题
# time = soup.select('.time-source, #navtimeSource')[0].text #这是自己的方法,获取时间和来源,类型为字符串
timesource = soup.select('.time-source')[0].contents[0].strip() # 老师方法获取时间
dt = datetime.strptime(timesource, '%Y年%m月%d日%H:%M') # 将获取的时间的字符串转为时间表示类型
t = dt.strftime('%Y年%m月%d日') #可以自己设置时间显示方式
laiyuan = soup.select('.time-source span a')[0].text # 获取来源
'''
此为第一种方法:
neirong = soup.select('#artibody p')[:-1] # 获取正文部分,[:-1]表示不要最后的一个标签中的内容
artlist = []
for p in neirong:
artlist.append(p.text.strip())
wenzhang = '\n '.join(artlist)
'''
# 这是第二种方法,用一行代码实现,更为简洁
wenzhang = '\n '.join([p.text.strip() for p in soup.select('#artibody p')[:-1]])
bianji = soup.select('.article-editor')[0].text.lstrip('李鹏') # lstrip('责任编辑:')是从左边将其移除
print(title)
# print(time)
print(timesource)
print(dt)
print(t)
print(laiyuan)
print(wenzhang)
print(bianji)
<file_sep>import requests
from lxml import etree
import re
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import csv
def jd():
browser = webdriver.Chrome()
url = 'https://search.jd.com/Search?keyword=%E7%99%BD%E9%85%92&enc=utf-8&wq=%E7%99%BD%E9%85%92&pvid=91cc689c20be4ae79df9e94ebe6adc60'
browser.get(url)
for i in range(100):
html = browser.page_source
selector = etree.HTML(html)
moneys = [''.join(i.xpath('div/div[2]/strong/i/text()')) for i in
selector.xpath('//*[@id="J_goodsList"]/ul/li')]
names = [''.join(i.xpath('div/div[3]/a/em/text()')) for i in selector.xpath('//*[@id="J_goodsList"]/ul/li')]
pintjias = [''.join(i.xpath('div/div[4]/strong/a/text()')) for i in
selector.xpath('//*[@id="J_goodsList"]/ul/li')]
time.sleep(1)
browser.find_element_by_xpath('//*[@id="J_bottomPage"]/span[1]/a[9]/em').click()
header = ['name', 'money', 'pinjia']
html = browser.page_source
header = ['name', 'money', 'pinjia']
if i % 2 != 0:
print(moneys)
print(names)
print(pintjias)
print(len(moneys))
print(len(names))
print(len(pintjias))
# for name, money, pintjia in zip(names, moneys, pintjias):
# rows = [name, money, pintjia]
# with open('dog.csv', 'a', encoding='utf-8') as f:
# f_csv = csv.writer(f, delimiter=',', lineterminator='\n')
# f_csv.writerow(rows)
browser.quit()
def taobao():
browser = webdriver.Chrome()
url = 'https://s.taobao.com/search?q=%E7%99%BD%E9%85%92&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306'
browser.get(url)
for i in range(50):
html = browser.page_source
# with open('das.html', encoding='utf-8') as f:
# html = f.read()
selector = etree.HTML(html)
price = selector.xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[1]/div[1]/strong/text()')
name = [''.join(i.xpath('div[2]/a/text()')) for i in selector.xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]')]
month_c = selector.xpath('//*[@id="mainsrp-itemlist"]/div/div/div[1]/div/div[2]/div[1]/div[2]/text()')
# comment = selector.xpath('//*[@id="J_ItemList"]/div/div/p[3]/span[2]/a/text()')
print(price)
print(name)
print(month_c)
# print(comment)
print(len(price))
print(len(name))
print(len(month_c))
# # print(len(comment))
# print(selector.xpath('//b[@class="ui-page-num"]/a[last()]/text()'))
# time.sleep(1)
for money, name, pintjia in zip(price, name, month_c):
# print(i, ''.join(j.split()), k)
rows = [''.join(name.split()), money, pintjia]
with open('taobao.csv', 'a', encoding='utf-8') as f:
f_csv = csv.writer(f, delimiter=',', lineterminator='\n')
f_csv.writerow(rows)
try:
browser.find_element_by_xpath('//*[@id="mainsrp-pager"]/div/div/div/ul/li[last()]/a/span[1]').click()
WebDriverWait(browser, 2).until(
EC.presence_of_element_located((By.CLASS_NAME, "J_Ajax num icon-tag"))
)
except Exception as e:
print(e)
browser.quit()
def tianmao():
browser = webdriver.Chrome()
url = 'https://list.tmall.com/search_product.htm?q=%B0%D7%BE%C6&type=p&vmarket=&spm=875.7931836%2FB.a2227oh.d100&from=mallfp..pc_1_searchbutton'
browser.get(url)
for i in range(100):
html = browser.page_source
# with open('das.html', encoding='utf-8') as f:
# html = f.read()
selector = etree.HTML(html)
price = selector.xpath('//*[@id="J_ItemList"]/div/div/p[1]/em/text()')
name = [''.join(i.xpath('a/text()')) for i in selector.xpath('//*[@id="J_ItemList"]/div/div/p[2]')]
month_c = selector.xpath('//*[@id="J_ItemList"]/div/div/p[3]/span[1]/em/text()')
comment = selector.xpath('//*[@id="J_ItemList"]/div/div/p[3]/span[2]/a/text()')
try:
browser.find_element_by_xpath('//*[@id="content"]/div/div[8]/div/b[1]/a[last()]').click()
WebDriverWait(browser, 3).until(
EC.presence_of_element_located((By.CLASS_NAME, "ui-page-next"))
)
except Exception as e:
print(e)
if i % 2 != 0:
print(price)
print(name)
print(month_c)
print(comment)
print(len(price))
print(len(name))
print(len(month_c))
print(len(comment))
for p, j, k, l in zip(price, name, month_c, comment):
# print(i, ''.join(j.split()), k, l)
rows = [''.join(j.split()), p, k, l]
with open('cat.csv', 'a', encoding='utf-8') as f:
f_csv = csv.writer(f, delimiter=',', lineterminator='\n')
f_csv.writerow(rows)
browser.quit()
<file_sep>import requests
import pprint
import json
import pymysql
import csv
import time
# db = pymysql.connect(host="127.0.0.1", user="root", password="<PASSWORD>", db="meituan", charset="utf8")
# cursor = db.cursor()
def all_cai(sj_id):
# test_url = 'https://takeaway.dianping.com/waimai/ajax/wxwallet/menu?actualLat=&actualLng=&initialLat=34.259458&initialLng=108.947001&geoType=2&mtWmPoiId=2094805&dpShopId=80966797&source=shoplist&_token=<KEY> <PASSWORD>%2<PASSWORD>qN0csb%2BKLmX8Cx4Iv%2B12GkvyciFQBHKQexNAzJ6pJN7HVRcNYNvKsWed8aE%2BMt48Z0mVjTlNJoy268KYbk2A9R4XuQOI5LXK2VV4IgsTxoa6IfT3npC0UbLqTGOy45a2ImfWwtkE0s2%2FsDu8o3obcglguhqbFcju%2FJ31btgf5%2Fj97kfVH66tx5H20JIpuVvId4SJTvQvMTQW%2B804RksvRNhDWgCmn3qhCl9VXZVeVVBa86sATl7WWf1NN4l2LqpbUQh8eQnj8nWXFI1n00e5XwUjTJcD3vZjrJufiapMYuvKtkkj3hlJ7pazJHx8f%2BsiPRhcapSeNyvX6gaBscn52GZ21QsS071Y2V1cGH52aVWxONN1CEm%2FnAz7uY27f77GkMhrGoPw55v3oIXI%2FXFfjxE64XtLU%3D&_=1506522773260'
url = 'https://takeaway.dianping.com/waimai/ajax/wxwallet/menu?'
headers = {
'Host': 'takeaway.dianping.com',
'Connection': 'keep-alive',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; PLK-AL10 Build/HONORPLK-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043508 Safari/537.36 MicroMessenger/6.5.13.1100 NetType/WIFI Language/zh_CN',
'Referer': 'https://takeaway.dianping.com/waimai/wxwallet?code=001vTIG929EAtO03pSG92nD1H92vTIGn&state=123&',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,en-US;q=0.8',
'Cookie': '_hc.v=018814d1-2b04-7113-b352-0c224b5591af.1501688076; m_cookie_issues_uuid=yVsMhGQlPx; _lxsdk=15da39597c12b-0aab3e0fc398e5-20206876-38400-15da39597c321; mter=O-ejUyOTKzBe79Tw378C7V5HIaoAAAAAdAQAAGpwOQCHCVleHrEs8O9ZgaRiH_aN5Cpy58YM53HeT5szkCqQt_zAZG3Gw6WYPAZS6A; ta.uuid=901405955860766817; waimai_cityname=%E5%9F%8E%E5%B8%82%E5%90%8D%E5%B7%B2%E5%88%A0%E9%99%A4; __mta=146757131.1501688076530.1506521098321.1506521252533.10; isUuidUnion=false; dpUserId=""; mtUserId=142481724; _lxsdk_s=6bf8e2bf672f78bb0f481f9542ec%7C%7C80',
}
from_data = {
# 'actualLat': '31.063480025949268',
# 'actualLng': '121.4983591662249',
# 'initialLat': '34.259458',
# 'initialLng': '108.947001',
'geoType': '2',
'mtWmPoiId': sj_id['mtWmPoiId'],
'dpShopId': sj_id['dpShopId'],
'source': 'shoplist',
'_token': '<KEY>',
'_': '1506521305060'
}
req = requests.post(url, headers=headers, data=from_data, verify=False)
req.encoding = 'utf-8'
# pprint.pprint(req.json())
a = json.loads(req.text)
zhonglei = a['data']['categoryList']
for i in range(len(zhonglei)):
b = zhonglei[i]['spuList']
for m in range(len(b)):
cai_name = str(b[m]['spuName']).strip() # 商品名称
short_price = b[m]['currentPrice'] # 小份
big_price = b[m]['originPrice'] # 大份
sales = b[m]['saleVolume'] # 月销售
like_num = b[m]['praiseNum'] # 点赞数
# print(cai_name, short_price, big_price, sales, like_num)
# sql = "INSERT INTO caiping_info(n_id, c_name, big_price, short_price, sales, like_num)\
# VALUE (%s, %s, %s, %s, %s, %s)"
# cursor.execute(sql, (sj_id['n_id'], cai_name, big_price, short_price, sales, like_num))
# db.commit()
def all_shangjia(datas):
url = 'https://takeaway.dianping.com/waimai/ajax/wxwallet/newIndex?'
headers = {
'Host': 'takeaway.dianping.com',
'Connection': 'keep-alive',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; PLK-AL10 Build/HONORPLK-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043508 Safari/537.36 MicroMessenger/6.5.13.1100 NetType/WIFI Language/zh_CN',
'Referer': 'https://takeaway.dianping.com/waimai/wxwallet?code=001vTIG929EAtO03pSG92nD1H92vTIGn&state=123&',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,en-US;q=0.8',
'Cookie': '_hc.v=018814d1-2b04-7113-b352-0c224b5591af.1501688076; m_cookie_issues_uuid=yVsMhGQlPx; _lxsdk=15da39597c12b-0aab3e0fc398e5-20206876-38400-15da39597c321; mter=O-ejUyOTKzBe79Tw378C7V5HIaoAAAAAdAQAAGpwOQCHCVleHrEs8O9ZgaRiH_aN5Cpy58YM53HeT5szkCqQt_zAZG3Gw6WYPAZS6A; ta.uuid=901405955860766817; waimai_cityname=%E5%9F%8E%E5%B8%82%E5%90%8D%E5%B7%B2%E5%88%A0%E9%99%A4; __mta=146757131.1501688076530.1506521098321.1506521252533.10; isUuidUnion=false; dpUserId=""; mtUserId=142481724; _lxsdk_s=6bf8e2bf672f78bb0f481f9542ec%7C%7C80',
}
try:
for data in datas:
from_data = {
'startIndex': '0',
'sortId': '',
'secondcategoryid': '0',
'rankTraceId': '',
'multifilterids': '',
'lng': data[5],
'lat': data[4],
'initialLng': data[5],
'initialLat': data[4],
'geoType': '2',
'firstcategoryid': '0',
'channel': '24',
'cateId': '',
'address': data[1],
'actualLng': '',
'actualLat': '',
'_token': '<KEY>',
'_': '1506521305060'
}
req = requests.post(url, headers=headers, data=from_data, verify=False)
a = json.loads(req.text)
try:
mtPoiNumber = a['data']['mtPoiNumber']
number = int(mtPoiNumber) // 25 * 25 + 1
# print(mtPoiNumber)
# print('*' * 200)
for num in range(0, number, 25):
# startIndex 字段是显示商家的数量,以[0, 25, 50, 75, 100.....]这样递增
from_data = {
'startIndex': num,
'sortId': '',
'secondcategoryid': '0',
'rankTraceId': '',
'multifilterids': '',
'lng': data[5],
'lat': data[4],
'initialLng': data[5],
'initialLat': data[4],
'geoType': '2',
'firstcategoryid': '0',
'channel': '24',
'cateId': '',
'address': data[1],
'actualLng': '',
'actualLat': '',
'_token': '<KEY>',
'_': '1506521305060'
}
req = requests.post(url, headers=headers, data=from_data, verify=False)
a = json.loads(req.text)
print('*' * 100)
# pprint.pprint(a)
a_list = a['data']['shopList']
for i in range(0, len(a_list)):
try:
huodong = ','.join([x['actDesc'] for x in a_list[i]['activityList']])
except:
huodong = None
name = a_list[i]['name']
qisongjia = a_list[i]['minFee']
peisongfei = a_list[i]['minDeliverFee']
mtWmPoiId = a_list[i]['mtWmPoiId']
dpShopId = a_list[i]['id']
sold = a_list[i]['sold'] # 月销售
# print(huodong, name, qisongjia, peisongfei, mtWmPoiId, dpShopId, sold)
# sql_insert = "INSERT INTO shangjia_info(d_name, qisong_pice, peisong_pice, mtwmpoi_id,\
# dpShop_id, sold, huodong, address_type, address_name, quyu, address)\
# VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
# cursor.execute(sql_insert, (name, qisongjia, peisongfei, mtWmPoiId, dpShopId, sold, huodong,
# data[0], data[1], data[2], data[3]))
# n_id = cursor.lastrowid
# db.commit()
sj_id = {'mtWmPoiId': mtWmPoiId,
'dpShopId': dpShopId,
'n_id': n_id}
all_cai(sj_id)
except Exception as e:
print('@'*100, str(e))
# print('变更商家, 等待10s')
# time.sleep(10)
# print('变更商家列表, 等待10s')
# time.sleep(10)
# print('变更地址, 等待30s')
# time.sleep(30)
except Exception as e:
print('!'*100, str(e))
def canshu():
position_info = []
with open('me.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for line in reader:
if reader.line_num == 1:
continue
a = line[0], line[1], line[2], line[3], line[4], line[5]
position_info.append(a)
# print(type(a))
return position_info
all_shangjia(canshu())
<file_sep># -*-conding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from lxml import etree
import os
# 输出所在网址的内容
def introduce(url):
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
title = soup.select('h1')[0].text
content = '\n '.join([p.text.strip() for p in soup.select('.section')])
#print(title)
#print(content)
with open('python.doc', 'a+', encoding='utf-8') as f:
f.write(content)
# 返回目录所对应的地址
def get_url(selector):
sites = selector.xpath('//div[@class="toctree-wrapper compound"]/ul/li')
address = []
for site in sites:
directory = ''.join(site.xpath('a/text()'))
new_url = site.xpath('a/@href')
address.append('http://www.pythondoc.com/pythontutorial3/' + ''.join(new_url))
return address
def main():
url = 'http://www.pythondoc.com/pythontutorial3/index.html#'
html = requests.get(url)
html.encoding = 'utf-8'
selector = etree.HTML(html.text)
introduce(url)
url_list = get_url(selector)
for url in url_list:
introduce(url)
if __name__ == '__main__':
main()
|
820989741288d692565718280617a43eabc0675d
|
[
"Markdown",
"Python"
] | 33
|
Python
|
wananoner/translation-spider
|
f05182a6f948417b59547c28293614657d6e37db
|
f9360da166edb7e581987fd9a46cca922997289d
|
refs/heads/master
|
<repo_name>Priyanka-M96/Scientific-Project-based-on-GPU<file_sep>/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.5) #cmake_minimum_required(VERSION 3.10)
PROJECT(openCLDispatcher)
SET(CMAKE_CXX_STANDARD 11) #set(CMAKE_CXX_STANDARD 98)
#set(OpenCL_INCLUDE_DIR /opt/intel/OpenCL)
FIND_PACKAGE(OpenCL)
ADD_EXECUTABLE(openCLDispatcher
Main.h
Main.cpp
Query6.h
include/kernel_class/logical.h
include/kernel_class/selection.h
include/kernel_generator/selection.h
include/kernel_generator/selection_generator.h
include/headers.h
include/globals.h
include/Environment.h
include/data_api.h
include/kernel_api.h
include/runtime_api.h
include/base_kernel.h
include/DAG_query.h
include/ImportKernelSource.h
include/primitives/header/BitonicSorting.h
#include/primitives/source/BitonicSorting.cpp
include/primitives/header/Merging.h
#include/primitives/header/Merging.cpp
include/primitives/header/Aggregating.h
#include/primitives/source/Aggregation.cpp
include/primitives/header/Aggregation.h
include/distribution.h
#include/primitives/VariantTest/AggregateVariantTest.h
#include/primitives/VariantTest/BitonicVariantTest.h
include/primitives/VariantTest/MergeVariantTest.h
include/primitives/VariantTest/VariantTesting.h)
#INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
INCLUDE_DIRECTORIES( ${OpenCL_INCLUDE_DIR} )
#LINK_DIRECTORIES(/opt/intel/OpenCL)
TARGET_LINK_LIBRARIES( openCLDispatcher LINK_PUBLIC ${OpenCL_LIBRARIES})
#-----------------------------------------------------------------------------------------------------------
#cmake_minimum_required(VERSION 2.0)
#project(openCLDispatcher)
#set(CMAKE_CXX_STANDARD 11)
#add_executable(openCLDispatcher
# main.cpp
# Query6.h
# include/headers.h
# include/globals.h
# include/Environment.h
# include/data_api.h
# include/kernel_api.h
# include/runtime_api.h
# include/DAG_query.h
# include/base_kernel.h
# include/kernel_generator/selection.h
# include/kernel_class/selection.h
# include/kernel_generator/selection_generator.h
# include/kernel_class/logical.h)
#FIND_PACKAGE(Boost 1.58 COMPONENTS system chrono)
#FIND_PACKAGE(OpenCL)
#INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
#INCLUDE_DIRECTORIES( ${OpenCL_INCLUDE_DIR} )
#LINK_DIRECTORIES(/usr/local/cuda-8.0/include)
#TARGET_LINK_LIBRARIES( openCLDispatcher LINK_PUBLIC ${Boost_LIBRARIES} ${OpenCL_LIBRARIES})<file_sep>/Main.cpp
//
// Created by gurumurt on 3/19/18.
//
#include "include/Environment.h"
#include "include/primitives/header/BitonicSorting.h"
#include "include/primitives/header/Aggregating.h"
#include "include/distribution.h"
#include "include/primitives/VariantTest/MergeVariantTest.h"
#include "include/primitives/VariantTest/VariantTesting.h"
#include "include/primitives/header/Merging.h"
void call();
void call_BitonicSort(cl_device_id _DEVICE, uint m_arr[], int m_size);
void call_Merge(cl_device_id _DEVICE);
void call_Aggregation(cl_device_id _DEVICE, uint m_arr[], int m_size);
int main(int argc, char *argv[]) {
bs_evaluation(9); // loop for executing the bitonic sort in
evaluate_Merge(15,256,5); //(Power of max element size allowed, max_work_group_size, loop_size)
agg_evaluation(4);
//call();
return 0;
}
void call() {
// Generate random numbers
int m_size = pow(2, 8);
cout << "ELEMENT SIZE :: " << m_size << endl;
// Set the Generate Size in distribution.h file
setGen(m_size);
// Create an array of _size
uint m_rand_arr[m_size];
for (int i = 0; i < m_size; i++) {
m_rand_arr[i] = UniformRandom();
}
setup_environment();
print_environment();
// Get Device ID
//cl_device_id CPU, GPU;
cl_device_id DEVICE;
DEVICE = device[0][0]; // GPU
//DEVICE = device[0][1]; // CPU
cl_ulong DEV_SIZE;
//clGetDeviceInfo(DEVICE, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(cl_ulong), &DEV_SIZE, NULL);
clGetDeviceInfo(DEVICE, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &DEV_SIZE, NULL); //CL_DEVICE_MAX_COMPUTE_UNITS //CL_DEVICE_GLOBAL_MEM_SIZE //CL_DEVICE_LOCAL_MEM_SIZE
cout << "DEV_SIZE :: " << DEV_SIZE << "\tDEV SIZE :: " << log(DEV_SIZE)/log(2) << endl;
// Initialize the events required
//evt = new cl_event[3];
//Main().call_BitonicSort(GPU, evt[0]);
/*Main().*/ call_BitonicSort(DEVICE, m_rand_arr, m_size);
cout << "EXECUTION TIME :: " << execution_time_ns / 1000000.0 << endl;
/*Main().*/ //call_Merge(DEVICE);
/* Main().*/ call_Aggregation(DEVICE, m_rand_arr, m_size);
cout << "EXECUTION TIME :: " << execution_time_ns / 1000000.0 << endl;
}
void /*Main::*/call_BitonicSort(cl_device_id _DEVICE, uint m_arr[], int m_size) {
// Call the Bitonic Sorting
/*BitonicSorting().*/BitonicSort(_DEVICE, m_arr, m_size);
}
void /*Main::*/call_Merge(cl_device_id _DEVICE) {
//Creating 2 sorted arrays
uint _m_size_left = 8;
uint _m_size_right = 8;
uint _m_size_chunk = 4;
uint _m_arr_left[_m_size_left] = {1, 1, 2, 3, 4, 8, 8, 9};
uint _m_arr_right[_m_size_right] = {1, 3, 5, 8, 11, 12, 13, 14};
int *_m_arr_result = (int *) calloc((int)_m_size_left, sizeof(int));
//int _m_arr_result[_m_size_left];
// Call merge function
Merge(_DEVICE, _m_arr_left, _m_arr_right, _m_arr_result, _m_size_left, _m_size_right,_m_size_chunk);
}
void /*Main::*/call_Aggregation(cl_device_id _DEVICE, uint m_arr[], int m_size) {
// Call the Aggregation
/*Aggregating().*/ //Aggregate(_DEVICE, _m_arr, _m_size);
/*Aggregation().*/ Aggregate(_DEVICE, m_arr, m_size, 16, 16);
//print_execution_time(evt);
}<file_sep>/Main.h
//
// Created by tompi on 6/6/18.
//
/*#ifndef OPENCLDISPATCHER_MAIN_H
#define OPENCLDISPATCHER_MAIN_H
#pragma once
#include "include/Environment.h"
//#include "include/primitives/header/BitonicSorting.h"
//#include "include/primitives/header/Aggregation.h"
class Main {
public:
void call_BitonicSort(cl_device_id _DEVICE, cl_event _event);
void call_Merge(cl_device_id _DEVICE);
//void call_Aggregation(cl_device_id _DEVICE);
};
#endif //OPENCLDISPATCHER_MAIN_H/**/
|
a05389e2fd7176ca330b626b60696846c2bde927
|
[
"CMake",
"C++"
] | 3
|
CMake
|
Priyanka-M96/Scientific-Project-based-on-GPU
|
21b6e27b34a124e2b08b12da6a400ff64f26dc3e
|
d1e26c7e656ec5e506d3b39cfa1b135b3fb2608b
|
refs/heads/master
|
<repo_name>dorofiykolya/ModuleLR<file_sep>/ModuleManager/Spells/SpellModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class SpellModule : ModuleManager, ITick
{
public override void Initialize()
{
}
public SpellModule Add<T>() where T : Spell
{
AddModule<T>();
return this;
}
public void PreTick(float time)
{
foreach (var spell in GetModules<Spell>())
{
if (spell.RemainingTime > 0f && !spell.Added)
{
spell.Added = true;
spell.Process();
}
}
}
public void Tick(float time)
{
foreach (var spell in GetModules<Spell>())
{
spell.Tick(time);
}
}
public void PostTick(float time)
{
foreach (var spell in GetModules<Spell>())
{
if (spell.RemainingTime <= 0f && spell.Added)
{
spell.Added = false;
spell.PostProcess();
}
}
}
public void FinalTick(float time)
{
}
}
public abstract class Spell : Module
{
public override void Initialize()
{
}
public void Set(float time)
{
RemainingTime = time;
}
public bool Added { get; set; }
public float RemainingTime { get; set; }
public abstract void Process();
public abstract void PostProcess();
public virtual void Tick(float time)
{
RemainingTime = Math.Max(0f, RemainingTime - time);
}
}
}
<file_sep>/ModuleManager/InputModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class InputModule : Module
{
private PlayerModule _playerModule;
private readonly Dictionary<InputType, Queue<Input>> _dictionary = new Dictionary<InputType, Queue<Input>>();
public override void Initialize()
{
_playerModule = GetModule<PlayerModule>();
_dictionary[InputType.Move] = new Queue<Input>();
_dictionary[InputType.Skill] = new Queue<Input>();
}
public Input Dequeue(InputType type)
{
return _dictionary[type].Count != 0? _dictionary[type].Dequeue() : null;
}
public void Input(Input input)
{
_dictionary[input.Type].Enqueue(input);
}
}
public enum InputType
{
Move,
Skill
}
public enum InputAction
{
MoveLeft,
MoveRight,
MoveUp,
MoveDown,
DigLeft,
DigRight
}
public class Input
{
public InputType Type;
public InputAction Action;
public int SkillId;
}
}
<file_sep>/ModuleManager/Characters/CharacterProperty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public enum CharacterProperty
{
None,
Speed,
Life,
DiggingSpeed,
XMove,
YMove
}
}
<file_sep>/ModuleManager/Interfaces.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Point
{
public int X;
public int Y;
public static bool operator ==(Point p1, Point p2)
{
if (ReferenceEquals(p1, p2)) return true;
if (ReferenceEquals(p1, null)) return false;
if (ReferenceEquals(p2, null)) return false;
return p1.Equals(p2);
}
public static bool operator !=(Point p1, Point p2)
{
if (ReferenceEquals(p1, p2)) return false;
if (ReferenceEquals(p1, null)) return true;
if (ReferenceEquals(p2, null)) return true;
return !p1.Equals(p2);
}
public override bool Equals(object obj)
{
var other = obj as Point;
if (other != null)
{
return other.X == X && other.Y == Y;
}
return base.Equals(obj);
}
protected bool Equals(Point other)
{
return X == other.X && Y == other.Y;
}
public override int GetHashCode()
{
unchecked
{
return (X * 397) ^ Y;
}
}
}
public class TeleportRecord
{
public bool IsTwoWay;
public Point From;
public Point To;
}
public enum AiType
{
}
public class GuardRecord
{
public int Id;
public Point Spawn;
public AiType AiType;
}
public enum CellType
{
Empty,
Block,
Solid,
Ladder,
RopeBar,
Trap,
HLadr,
Teleport
}
public enum CharacterAction
{
Unknown = -1,
Stop = 0,
Left = 1,
Right = 2,
Up = 3,
Down = 4,
Fall = 5,
FallBar = 6,
DigLeft = 7,
DigRight = 8,
Digging = 9,
InHole = 10,
ClimpOut = 11,
Reborn = 12
}
public class CellRecord
{
public Point Point;
public CellType CellType;
}
public class GameLevelRecord
{
public int Time; // Длительность уровня
public int GuardRespawnTime;
public int CellRespawnTime;
public Point Size;
public CellRecord[] Cells; // Непустые клеточки
public GuardRecord[] Guards; // Описание охранников
public TeleportRecord[] Teleports;
public Point[] GoldGhests;
public Point[] GuardRespawn;
public Point RunnerSpawn;
}
/*
Gold = 0x07,
Guard = 0x08,
Runner = 0x09,
Reborn = 0x10
*/
}
<file_sep>/ModuleManager/Characters/GuardModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class GuardModule : CharacterModule
{
public override void AddModifier(Modifier modifier)
{
foreach (var module in GetModules<Guard>())
{
module.AddModifier(modifier);
}
}
public override void RemoveModifier(Modifier modifier)
{
foreach (var module in GetModules<Guard>())
{
module.RemoveModifier(modifier);
}
}
public override void PreTick(float time)
{
}
public override void Tick(float time)
{
}
public override void PostTick(float time)
{
}
public override void FinalTick(float time)
{
}
public void Set(GuardRecord[] guards, Point[] guardRespawn, int guardRespawnTime)
{
throw new NotImplementedException();
}
public Guard GetGuardAt(int x, int y)
{
foreach (var guard in GetModules<Guard>())
{
if (guard.X == x && guard.Y == y)
{
return guard;
}
}
return null;
}
public bool IsGuardAt(int x, int y)
{
return GetGuardAt(x, y) != null;
}
public bool IsGuardAlive(int x, int y)
{
return IsGuardAt(x, y);
}
}
}
<file_sep>/ModuleManager/CoinModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class CoinModule : Module
{
public override void Initialize()
{
}
public void Set(Point[] coins)
{
}
public bool IsCoin(int x, int y)
{
return false;
}
public bool IsEmpty
{
get { return false; }
}
public bool IsCompleted
{
get { return false; }
}
public void RemoveAt(int x, int y)
{
}
}
}
<file_sep>/ModuleManager/LevelModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class LevelModule : TickModule
{
public bool IsPause { get; set; }
public void Pause()
{
IsPause = true;
}
public void Resume()
{
IsPause = false;
}
public override void Tick()
{
AdvanceTime();
if (!IsPause)
{
AdvanceTick();
}
}
}
}
<file_sep>/ModuleManager/Characters/PlayerModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class PlayerModule : CharacterModule
{
private Player _player;
private InputModule _inputModule;
public bool IsDigging
{
get { return GetModule<Player>().IsDigging; }
}
public bool GodMode
{
get { return GetModule<Player>().GodMode; }
set { GetModule<Player>().GodMode = value; }
}
public Player SetPlayer<T>() where T : Player
{
_player = AddModule<T>();
return _player;
}
public override void AddModifier(Modifier modifier)
{
_player.AddModifier(modifier);
}
public override void RemoveModifier(Modifier modifier)
{
_player.RemoveModifier(modifier);
}
public override void Initialize()
{
base.Initialize();
_inputModule = GetModule<InputModule>();
}
public override void PreTick(float time)
{
}
public override void Tick(float time)
{
_player.Move();
Input input;
while ((input = _inputModule.Dequeue(InputType.Skill)) != null)
{
_player.NextInput(input);
}
while ((input = _inputModule.Dequeue(InputType.Move)) != null)
{
_player.NextInput(input);
}
}
public override void PostTick(float time)
{
}
public override void FinalTick(float time)
{
}
}
}
<file_sep>/ModuleManager/Spells/SpeedDownSpell.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager.Spells
{
public class SpeedDownSpell : Spell
{
private readonly SpeedModifier _modifier;
public SpeedDownSpell()
{
_modifier = new SpeedModifier(0.5f);
}
public override void Process()
{
GetModule<GuardModule>().AddModifier(_modifier);
}
public override void PostProcess()
{
GetModule<GuardModule>().RemoveModifier(_modifier);
}
}
}
<file_sep>/ModuleManager/StateModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class StateModule : Module
{
private State _state;
public State Previous { get; private set; }
public State State
{
get { return _state; }
set
{
if (value != _state)
{
Previous = _state;
_state = value;
}
}
}
public void Pause()
{
if (IsRunning)
{
State = State.Pause;
}
}
public void Resume()
{
if (IsPause)
{
State = State.Running;
}
}
public bool IsRunning { get { return _state == State.Running; } }
public bool IsPause { get { return _state == State.Pause; } }
public override void Initialize()
{
}
}
public enum State
{
Unknown,
Pause,
Start,
Running,
Stop,
Dead
}
}
<file_sep>/ModuleManager/TimeModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class TimeModule : Module, ITick
{
private float _remainigTime = float.NaN;
public bool IsTimeout
{
get { return !float.IsNaN(_remainigTime) && _remainigTime <= 0f; }
}
public float RemainigTime
{
get { return _remainigTime; }
set { _remainigTime = value; }
}
public override void Initialize()
{
_remainigTime = float.NaN;
}
public void PreTick(float time)
{
}
public void Tick(float time)
{
}
public void PostTick(float time)
{
}
public void FinalTick(float time)
{
}
}
}
<file_sep>/ModuleManager/Cells/Cell.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Cell
{
public CellType Type;
public Point Point;
public bool IsHide;
public Cell(Point point)
{
Point = point;
}
public bool IsEmpty
{
get { return Type == CellType.Empty; }
}
public bool IsBlock
{
get { return Type == CellType.Block; }
}
public bool IsNotHiddenBlock
{
get { return IsBlock && !IsHide; }
}
public bool Any(params CellType[] types)
{
foreach (var type in types)
{
if (type == Type) return true;
}
return false;
}
}
}
<file_sep>/ModuleManager/Characters/Character.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Character : Module
{
public int X;
public int Y;
public float XOffset;
public float YOffset;
public CharacterAction Action;
private readonly float[] _properties;
private readonly List<Modifier> _modifiers;
protected Character()
{
_properties = new float[Enum.GetValues(typeof(CharacterProperty)).Length];
_modifiers = new List<Modifier>();
}
protected void SetPosition(int x, int y, float xOffset, float yOffset)
{
X = x;
Y = y;
XOffset = xOffset;
YOffset = yOffset;
}
public override void Initialize()
{
}
public void AddModifier(Modifier modifier)
{
_modifiers.Add(modifier);
}
public void RemoveModifier(Modifier modifier)
{
_modifiers.Remove(modifier);
}
public float GetModifiedValue(CharacterProperty property)
{
var value = GetValue(property);
foreach (var modifier in _modifiers)
{
value = modifier.GetValue(value);
}
return value;
}
public float GetValue(CharacterProperty property)
{
return _properties[(int)property];
}
public Character SetValue(CharacterProperty property, float value)
{
_properties[(int)property] = value;
return this;
}
public float this[CharacterProperty property]
{
get { return GetValue(property); }
set { SetValue(property, value); }
}
}
}
<file_sep>/ModuleManager/Module.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public abstract class Module
{
public abstract void Initialize();
public ModuleManager ModuleManager { get; protected internal set; }
public virtual T GetModule<T>() where T : Module
{
return ModuleManager.GetModule<T>();
}
public virtual void GetModules<T>(List<T> result = null) where T : class
{
ModuleManager.GetModules<T>(result);
}
public virtual T[] GetModules<T>() where T : class
{
return ModuleManager.GetModules<T>();
}
}
}
<file_sep>/ModuleManager/SoundModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class SoundModule : Module
{
public override void Initialize()
{
}
public void StopFall()
{
}
public void PlayDown()
{
}
public void PlayFall()
{
}
public void PlayGetGold()
{
}
public void PlayDig()
{
}
}
}
<file_sep>/ModuleManager/Spells/DiggingModifier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager.Spells
{
public class DiggingModifier : Modifier
{
private readonly float _percent;
public DiggingModifier(float percent) : base(CharacterProperty.DiggingSpeed)
{
_percent = percent;
}
public override float GetValue(float value)
{
return value*_percent;
}
}
}
<file_sep>/ModuleManager/TeleportModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class TeleportModule : Module
{
private TeleportRecord[] _teleports;
public override void Initialize()
{
}
public TeleportRecord Get(int x, int y)
{
var point = new Point { X = x, Y = y };
var result = _teleports.FirstOrDefault(t => t.From == point);
if (result == null)
{
result = _teleports.FirstOrDefault(t => t.To == point);
}
return result;
}
public void Set(TeleportRecord[] teleports)
{
_teleports = teleports;
}
}
}
<file_sep>/ModuleManager/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ModuleManager.Spells;
namespace ModuleManager
{
class Program
{
private static readonly object Sync = new object();
static void Main(string[] args)
{
var module = new LevelModule();
module.AddModule<TimeModule>();
module.AddModule<InputModule>();
module.AddModule<PlayerModule>()
.SetPlayer<Player>()
.SetValue(CharacterProperty.Speed, 1f)
.SetValue(CharacterProperty.Life, 1)
.SetValue(CharacterProperty.DiggingSpeed, 1f);
module.AddModule<CellModule>();
module.AddModule<EventDispatcherModule>().EVENT += OnEvent;
module.AddModule<GuardModule>();
module.AddModule<StateModule>();
module.AddModule<CoinModule>();
module.AddModule<SpellModule>()
.Add<SpeedUpSpell>()
.Add<SpeedDownSpell>()
.Add<DiggingSpell>();
module.Initialize();
ThreadPool.QueueUserWorkItem((s) =>
{
while (true)
{
lock (Sync)
{
module.Tick();
}
Thread.Sleep(100);
}
});
while (true)
{
var key = Console.ReadKey(true);
lock (Sync)
{
switch (key.Key)
{
case ConsoleKey.LeftArrow:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.MoveLeft });
break;
case ConsoleKey.RightArrow:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.MoveRight });
break;
case ConsoleKey.UpArrow:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.MoveUp });
break;
case ConsoleKey.DownArrow:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.MoveDown });
break;
case ConsoleKey.Z:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.DigLeft });
break;
case ConsoleKey.X:
module.GetModule<InputModule>().Input(new Input { Type = InputType.Move, Action = InputAction.DigRight });
break;
case ConsoleKey.Escape:
var state = module.GetModule<StateModule>();
if (state.IsPause) state.Resume();
else state.Pause();
break;
}
}
}
}
private static void OnEvent(Event evt)
{
}
}
}
<file_sep>/ModuleManager/Spells/SpeedModifier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
class SpeedModifier : Modifier
{
private readonly float _percent;
public SpeedModifier(float percent) : base(CharacterProperty.Speed)
{
_percent = percent;
}
public override float GetValue(float value)
{
return value * _percent;
}
}
}
<file_sep>/ModuleManager/Characters/CharacterModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public abstract class CharacterModule : ModuleManager, ITick
{
public abstract void PreTick(float time);
public abstract void Tick(float time);
public abstract void PostTick(float time);
public abstract void FinalTick(float time);
public abstract void AddModifier(Modifier modifier);
public abstract void RemoveModifier(Modifier modifier);
}
}
<file_sep>/ModuleManager/Cells/CellModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class CellModule : Module, ITick
{
private Cell[,] _map;
private TeleportModule _teleport;
private Point Size;
public CellModule()
{
}
public int Left { get { return 0; } }
public int Top { get { return 0; } }
public int Right { get { return Size.X; } }
public int Bottom { get { return Size.Y; } }
public override void Initialize()
{
_teleport = GetModule<TeleportModule>();
}
public Cell Get(int x, int y)
{
return _map[x, y];
}
public bool IsEmpty(int x, int y)
{
return Get(x, y).IsEmpty;
}
public Cell this[int x, int y] { get { return Get(x, y); } }
public int SizeX { get { return Size.X; } }
public int SizeY { get { return Size.Y; } }
public float TileW { get { return 1; } }
public float TileH { get { return 1; } }
public float W2 { get { return (1f / 2f); } }
public float H2 { get { return (1f / 2f); } }
public float W4 { get { return (1f / 4f); } }
public float H4 { get { return (1f / 4f); } }
public int MaxTileX { get { return SizeX - 1; } }
public int MaxTileY { get { return SizeY - 1; } }
public float TileScale { get { return 1; } }
public void Set(Point size, CellRecord[] cells)
{
Size = size;
_map = new Cell[size.X, size.Y];
for (int x = 0; x < size.X; x++)
{
for (int y = 0; y < size.Y; y++)
{
_map[x, y] = new Cell(new Point { X = x, Y = y }) { Type = CellType.Empty };
}
}
foreach (var cell in cells)
{
_map[cell.Point.X, cell.Point.Y] = new Cell(cell.Point)
{
Type = cell.CellType
};
}
}
public void ShowHiddenLadder()
{
}
public void PreTick(float time)
{
}
public void Tick(float time)
{
}
public void PostTick(float time)
{
}
public void FinalTick(float time)
{
}
}
}
<file_sep>/ModuleManager/EventDispatcherModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class EventDispatcherModule : Module
{
public event Action<Event> EVENT;
public override void Initialize()
{
}
public void DispatchEvent(Event evt)
{
if (EVENT != null)
{
EVENT(evt);
}
}
public void DispatchEvent<T>() where T : Event
{
DispatchEvent(Event.Instantiate<T>());
}
}
public abstract class Event : IDisposable
{
private static readonly Dictionary<int, Stack<Event>> _pool = new Dictionary<int, Stack<Event>>();
private bool _disposed;
private readonly int _id;
protected Event()
{
_id = GetType().FullName.GetHashCode();
}
public static T Instantiate<T>() where T : Event
{
var id = typeof (T).FullName.GetHashCode();
Stack<Event> result;
if (_pool.TryGetValue(id, out result))
{
if (result.Count != 0)
{
var evt = (T) result.Pop();
evt._disposed = false;
return evt;
}
}
return Activator.CreateInstance<T>();
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Stack<Event> stack;
if (!_pool.TryGetValue(_id, out stack))
{
_pool[_id] = stack = new Stack<Event>();
}
stack.Push(this);
}
}
}
}
<file_sep>/ModuleManager/TickModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class TickModule : ModuleManager
{
private ITick[] _ticks;
private int _lastTime = 0;
private float _deltaTime;
public override void Initialize()
{
_ticks = GetModules<ITick>();
}
public int Ticks { get; private set; }
public virtual void Tick()
{
AdvanceTime();
AdvanceTick();
}
private void CalculateDeltaTime()
{
float deltaTime = 0f;
var time = Environment.TickCount;
if (_lastTime == 0)
{
_lastTime = time;
}
else
{
deltaTime = (time - _lastTime) / 1000f;
}
_deltaTime = deltaTime;
}
protected virtual void AdvanceTime()
{
CalculateDeltaTime();
}
protected virtual void AdvanceTick()
{
Ticks++;
PreTick(_deltaTime);
Tick(_deltaTime);
PostTick(_deltaTime);
FinalTick(_deltaTime);
}
protected float DeltaTime { get { return _deltaTime; } }
private void PreTick(float time)
{
foreach (var tick in _ticks)
{
tick.PreTick(time);
}
}
private void Tick(float time)
{
foreach (var tick in _ticks)
{
tick.Tick(time);
}
}
private void PostTick(float time)
{
foreach (var tick in _ticks)
{
tick.PostTick(time);
}
}
private void FinalTick(float time)
{
foreach (var tick in _ticks)
{
tick.FinalTick(time);
}
}
}
}
<file_sep>/ModuleManager/ModuleManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class ModuleManager : Module
{
private readonly List<Module> _modules;
public ModuleManager()
{
_modules = new List<Module>();
}
public Module AddModule(Module module)
{
_modules.Add(module);
module.ModuleManager = this;
return module;
}
public T AddModule<T>() where T : Module
{
return (T)AddModule(Activator.CreateInstance<T>());
}
public override T GetModule<T>()
{
var result = (T)_modules.FirstOrDefault(m => m is T);
if (result == null && ModuleManager != null)
{
result = (T)ModuleManager.GetModule<T>();
}
return result;
}
public override void GetModules<T>(List<T> result = null)
{
if (result == null) result = new List<T>();
if (ModuleManager != null)
{
ModuleManager.GetModules<T>(result);
}
result.AddRange(_modules.OfType<T>());
}
public override T[] GetModules<T>()
{
var result = new List<T>();
GetModules<T>(result);
return result.ToArray();
}
public override void Initialize()
{
foreach (var module in _modules)
{
module.Initialize();
}
}
}
}
<file_sep>/ModuleManager/Characters/Player.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Player : Character
{
private CellModule _cellModule;
private GuardModule _guardModule;
private TeleportModule _teleportModule;
private EventDispatcherModule _eventDispatcher;
private SoundModule _soundModule;
private CoinModule _coinModule;
private StateModule _stateModule;
private DiggingModule _diggingModule;
public bool IsDigging { get; private set; }
public CharacterAction LastMoveAction { get; set; }
public bool GodMode { get; set; }
public override void Initialize()
{
_cellModule = GetModule<CellModule>();
_guardModule = GetModule<GuardModule>();
_teleportModule = GetModule<TeleportModule>();
_eventDispatcher = GetModule<EventDispatcherModule>();
_soundModule = GetModule<SoundModule>();
_coinModule = GetModule<CoinModule>();
_stateModule = GetModule<StateModule>();
_diggingModule = GetModule<DiggingModule>();
}
public virtual void Move()
{
if (!IsDigging)
{
var stayCurrPos = true;
var curToken = _cellModule.Get(X, Y).Type;
bool curState;
Cell nextToken;
if (curToken == CellType.Ladder || (curToken == CellType.RopeBar && YOffset == 0f))
{ //ladder & bar
curState = true; //ok to move (on ladder or bar)
}
else if (YOffset < 0)
{ //no ladder && yOffset < 0 ==> falling
curState = false;
}
else if (Y < _cellModule.Bottom)
{ //no laddr && y < maxTileY && yOffset >= 0
nextToken = _cellModule[X, Y + 1];
if (nextToken.IsEmpty)
{
curState = false;
}
else if (nextToken.Any(CellType.Block, CellType.Ladder, CellType.Solid))
{
curState = true;
}
else if (_guardModule.IsGuardAt(X, Y + 1))
{
curState = true;
}
else
{
curState = false;
}
}
else
{ // no laddr && y == maxTileY
curState = true;
}
if (!curState)
{
stayCurrPos = (Y >= _cellModule.Bottom ||
_cellModule[X, Y + 1].Any(CellType.Block, CellType.Solid) ||
_guardModule.IsGuardAt(X, Y + 1));
MoveStep(CharacterAction.Fall, stayCurrPos);
return;
}
}
}
public void MoveStep(CharacterAction action, bool stayCurrPos)
{
var x = X;
var xOffset = XOffset;
var y = Y;
var yOffset = YOffset;
//var curShape = _runner.shape;
//var newShape = curShape;
var centerX = CharacterAction.Stop;
var centerY = centerX;
switch (action)
{
case CharacterAction.DigLeft:
case CharacterAction.DigRight:
xOffset = 0;
yOffset = 0;
break;
case CharacterAction.Up:
case CharacterAction.Down:
case CharacterAction.Fall:
if (xOffset > 0) centerX = CharacterAction.Left;
else if (xOffset < 0) centerX = CharacterAction.Right;
break;
case CharacterAction.Left:
case CharacterAction.Right:
if (yOffset > 0) centerY = CharacterAction.Up;
else if (yOffset < 0) centerY = CharacterAction.Down;
break;
}
var curToken = _cellModule[x, y].Type;
if (action == CharacterAction.Up)
{
yOffset -= GetModifiedValue(CharacterProperty.YMove);//_runner.yMove;
if (stayCurrPos && yOffset < 0) yOffset = 0; //stay on current position
else if (yOffset < -_cellModule.H2)
{ //move to y-1 position
//if (curToken == CellType.Block || curToken == CellType.HLadr) curToken = CellType.Empty; //in hole or hide laddr
//map[x, y].Act = curToken; //runner move to [x][y-1], so set [x][y].act to previous state
y--;
yOffset = _cellModule.TileH + yOffset;
//if (map[x, y].Act == CubePlatformType.Guard && AI.Guard.guardAlive(x, y)) setRunnerDead(); //collision
if (_guardModule.IsGuardAlive(x, y)) Dead();
}
//newShape = "RunUpDn";
}
if (centerY == CharacterAction.Up)
{
yOffset -= GetModifiedValue(CharacterProperty.YMove);
if (yOffset < 0) yOffset = 0; //move to center Y
}
if (action == CharacterAction.Down || action == CharacterAction.Fall)
{
var holdOnBar = 0;
if (curToken == CellType.RopeBar)
{
if (yOffset < 0) holdOnBar = 1;
else if (action == CharacterAction.Down && y < _cellModule.Bottom && _cellModule[x, y + 1].Type != CellType.Ladder)
{
action = CharacterAction.Fall; //shape fixed: 2014/03/27
}
}
yOffset += GetModifiedValue(CharacterProperty.YMove);
if (holdOnBar == 1 && yOffset >= 0)
{
yOffset = 0; //fall and hold on bar
action = CharacterAction.FallBar;
}
if (stayCurrPos && yOffset > 0) yOffset = 0; //stay on current position
else if (yOffset > _cellModule.H2)
{ //move to y+1 position
//if (curToken == CubePlatformType.Block || curToken == CubePlatformType.HLadr) curToken = CubePlatformType.Empty; //in hole or hide laddr
//map[x][y].Act = curToken; //runner move to [x][y+1], so set [x][y].act to previous state
y++;
yOffset = yOffset - _cellModule.TileH;
if (_guardModule.IsGuardAlive(x, y)) Dead(); //collision
}
if (action == CharacterAction.Down)
{
//newShape = "RunUpDn";
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.RunUpDn));
}
else
{ //ACT_FALL or ACT_FALL_BAR
if (y < _cellModule.Bottom && _guardModule.IsGuardAt(x, y + 1))
{ //over guard
//don't collision
var guard = _guardModule.GetGuardAt(x, y + 1);//AI.Guard.getGuardId(x, y + 1);
if (yOffset > guard.YOffset) yOffset = guard.YOffset;
}
if (action == CharacterAction.FallBar)
{
if (LastMoveAction == CharacterAction.Left)
{
_eventDispatcher.DispatchEvent(
new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.BarLeft));
//newShape = "BarLeft");
}
else
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.BarRight));
//newShape = "BarRight";
}
}
else
{
if (LastMoveAction == CharacterAction.Left)
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.FallLeft));
//newShape = "FallLeft";
}
else
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.FallRight));
}
//else newShape = "FallRight";
}
}
}
if (centerY == CharacterAction.Down)
{
yOffset += GetModifiedValue(CharacterProperty.YMove);
if (yOffset > 0) yOffset = 0; //move to center Y
}
if (action == CharacterAction.Left)
{
xOffset -= GetModifiedValue(CharacterProperty.XMove);
if (stayCurrPos && xOffset < 0) xOffset = 0; //stay on current position
else if (xOffset < -_cellModule.W2)
{ //move to x-1 position
//if (curToken == CubePlatformType.Block || curToken == CubePlatformType.HLadr) curToken = CubePlatformType.Empty; //in hole or hide laddr
//map[x][y].Act = curToken; //runner move to [x-1][y], so set [x][y].act to previous state
x--;
xOffset = _cellModule.TileW + xOffset;
if (_guardModule.IsGuardAlive(x, y)) Dead(); //collision
}
if (curToken == CellType.RopeBar)
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.BarLeft));
//newShape = "BarLeft";
}
else
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.RunLeft));
//else newShape = "RunLeft";
}
}
if (centerX == CharacterAction.Left)
{
xOffset -= GetModifiedValue(CharacterProperty.XMove);
if (xOffset < 0) xOffset = 0; //move to center X
}
if (action == CharacterAction.Right)
{
xOffset += GetModifiedValue(CharacterProperty.XMove);
if (stayCurrPos && xOffset > 0) xOffset = 0; //stay on current position
else if (xOffset > _cellModule.W2)
{ //move to x+1 position
//if (curToken == CubePlatformType.Block || curToken == CubePlatformType.HLadr) curToken = CubePlatformType.Empty; //in hole or hide laddr
//map[x][y].Act = curToken; //runner move to [x+1][y], so set [x][y].act to previous state
x++;
xOffset = xOffset - _cellModule.TileW;
if (_guardModule.IsGuardAlive(x, y)) Dead(); //collision
}
if (curToken == CellType.RopeBar)
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.BarRight));
//newShape = "BarRight";
}
else
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.RunRight));
//else newShape = "runRight";
}
}
if (centerX == CharacterAction.Right)
{
xOffset += GetModifiedValue(CharacterProperty.XMove);
if (xOffset > 0) xOffset = 0; //move to center X
}
if (action == CharacterAction.Stop)
{
if (Action == CharacterAction.Fall)
{
_soundModule.StopFall();
_soundModule.PlayDown();
}
if (Action != CharacterAction.Stop)
{
//_runner.sprite.stop();
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.Stop));
Action = CharacterAction.Stop;
}
}
else
{
//_runner.sprite.x = (x + xOffset);
//_runner.sprite.y = (y + yOffset);
SetPosition(x, y, xOffset, yOffset);
//if (curShape != newShape)
//{
//_runner.sprite.gotoAndPlay(newShape);
//_runner.shape = newShape;
//}
if (action != Action)
{
if (Action == CharacterAction.Fall)
{
_soundModule.StopFall();
_soundModule.PlayDown();
}
else if (action == CharacterAction.Fall)
{
_soundModule.PlayFall();
}
//_runner.sprite.play();
}
if (action == CharacterAction.Left || action == CharacterAction.Right) LastMoveAction = action;
Action = action;
}
//map[x][y].Act = CubePlatformType.Runner;
// Check runner to get gold (MAX MOVE MUST < H4 & W4)
if (_coinModule.IsCoin(x, y) &&
((xOffset == 0f && yOffset >= 0 && yOffset < _cellModule.H4) ||
(yOffset == 0f && xOffset >= 0 && xOffset < _cellModule.W4) ||
(y < _cellModule.Bottom && _cellModule.Get(x, y + 1).Type == CellType.Ladder && yOffset < _cellModule.H4) // gold above laddr
)
)
{
_coinModule.RemoveAt(x, y);
_soundModule.PlayGetGold();
//debug("gold = " + goldCount);
//if (playMode == PLAY_CLASSIC || playMode == PLAY_AUTO || playMode == PLAY_DEMO)
//{
// drawScore(SCORE_GET_GOLD);
//}
//else
//{
//for modern mode , edit mode
//AI.drawGold(1); //get gold
//}
}
if (_coinModule.IsEmpty && !_coinModule.IsCompleted) _cellModule.ShowHiddenLadder();
//check collision with guard !
СheckCollision(x, y);
}
public void СheckCollision(int runnerX, int runnerY)
{
var x = -1;
var y = -1;
//var dbg = "NO";
if (runnerY > 0 && _guardModule.IsGuardAlive(runnerX, runnerY - 1))
{
x = runnerX;
y = runnerY - 1;
//dbg = "UP";
}
else if (runnerY < _cellModule.Bottom && _guardModule.IsGuardAlive(runnerX, runnerY + 1))
{
x = runnerX;
y = runnerY + 1;
//dbg = "DN";
}
else if (runnerX > 0 && _guardModule.IsGuardAlive(runnerX - 1, runnerY))
{
x = runnerX - 1;
y = runnerY;
//dbg = "LF";
}
else if (runnerX < _cellModule.Right && _guardModule.IsGuardAlive(runnerX + 1, runnerY))
{
x = runnerX + 1;
y = runnerY;
//dbg = "RT";
}
//if( dbg != "NO") debug(dbg);
if (x >= 0)
{
var guard = _guardModule.GetGuardAt(x, y);
if (guard.Action != CharacterAction.Reborn)
{ //only guard alive need check collection
//var dw = Math.abs(runner.sprite.x - guard[i].sprite.x);
//var dh = Math.abs(runner.sprite.y - guard[i].sprite.y);
//change detect method ==> don't depend on scale
var runnerPosX = X * _cellModule.TileW + XOffset;
var runnerPosY = Y * _cellModule.TileH + YOffset;
var guardPosX = guard.X * _cellModule.TileW + guard.XOffset;
var guardPosY = guard.Y * _cellModule.TileH + guard.YOffset;
var dw = Math.Abs(runnerPosX - guardPosX);
var dh = Math.Abs(runnerPosY - guardPosY);
if (dw <= _cellModule.W4 * 3 && dh <= _cellModule.H4 * 3)
{
Dead(); //07/04/2014
//debug("runner dead!");
}
}
}
}
private void Dead()
{
if (!GodMode)
{
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.Dead));
_stateModule.State = State.Dead;
}
}
public virtual void NextInput(Input input)
{
switch (input.Type)
{
case InputType.Move:
InputMove(input.Action);
break;
case InputType.Skill:
break;
}
}
protected virtual void InputMove(InputAction action)
{
var moveStep = CharacterAction.Stop;
var stayCurrPos = true;
var keyAction = action;
Cell nextToken;
switch (keyAction)
{
case InputAction.MoveUp:
stayCurrPos = Y <= 0 || (nextToken = _cellModule.Get(X, Y - 1)).IsNotHiddenBlock || nextToken.Any(CellType.Solid, CellType.Trap);
if (Y > 0 &&
_cellModule.Get(X, Y).Type != CellType.Ladder &&
YOffset < _cellModule.H4 &&
YOffset > 0 &&
_cellModule.Get(X, Y + 1).Type == CellType.Ladder)
{
stayCurrPos = true;
moveStep = CharacterAction.Up;
}
else if (!(_cellModule.Get(X, Y).Type != CellType.Ladder &&
(YOffset <= 0 || _cellModule.Get(X, Y + 1).Type != CellType.Ladder) ||
(YOffset <= 0 && stayCurrPos))
)
{
moveStep = CharacterAction.Up;
}
break;
case InputAction.MoveDown:
stayCurrPos = Y >= _cellModule.Bottom ||
(nextToken = _cellModule.Get(X, Y + 1)).IsNotHiddenBlock ||
nextToken.Type == CellType.Solid;
if (!(YOffset >= 0 && stayCurrPos))
{
moveStep = CharacterAction.Down;
}
break;
case InputAction.MoveLeft:
stayCurrPos = X <= 0 ||
(nextToken = _cellModule.Get(X - 1, Y)).IsNotHiddenBlock ||
nextToken.Any(CellType.Solid, CellType.Trap);
if (!(XOffset <= 0 && stayCurrPos))
{
moveStep = CharacterAction.Left;
}
break;
case InputAction.MoveRight:
stayCurrPos = X >= _cellModule.Right ||
(nextToken = _cellModule.Get(X + 1, Y)).IsNotHiddenBlock ||
nextToken.Any(CellType.Solid, CellType.Trap);
if (!(XOffset >= 0 && stayCurrPos))
moveStep = CharacterAction.Right;
break;
case InputAction.DigLeft:
case InputAction.DigRight:
CharacterAction characterAction;
if(keyAction == InputAction.DigLeft) characterAction = CharacterAction.Left;
else characterAction = CharacterAction.Right;
if (_diggingModule.AvailableToDigg(characterAction))
{
MoveStep(characterAction, stayCurrPos);
Digging(characterAction);
}
else
{
MoveStep(CharacterAction.Stop, stayCurrPos);
}
return;
}
MoveStep(moveStep, stayCurrPos);
}
protected virtual void Digging(CharacterAction action)
{
int x;
int y;
//string holeShape;
if (action == CharacterAction.DigLeft)
{
x = X - 1;
y = Y;
//_runner.shape = CubeAction.DigLeft;
//holeShape = "digHoleLeft";
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.DigLeft));
}
else
{ //DIG RIGHT
x = X + 1;
y = Y;
//_runner.shape = CubeAction.DigRight;
//holeShape = "digHoleRight";
_eventDispatcher.DispatchEvent(new PlayerAnimationEvent(PlayerAnimationEvent.AnimationEvent.DigRight));
}
_soundModule.PlayDig();
_eventDispatcher.DispatchEvent(new DiggingCellEvent(x, y + 1));
//AI.Map[x, y + 1].HideBlock(); //hide block (replace with digging image)
//_runner.sprite.gotoAndPlay(_runner.shape);
/*var holeObj = AI.HoleObj;
holeObj.action = CubeAction.Digging;
holeObj.pos.Set(x, y);
holeObj.sprite.setTransform(x, y);
holeObj.StartDigging(AI.Map[x, y + 1]);
holeObj.DigEnd += digComplete;
//digTimeStart = recordCount; //for debug
holeObj.sprite.gotoAndPlay(_runner.shape);
holeObj.sprite.onComplete(digComplete);
holeObj.AddToScene();*/
}
}
}
<file_sep>/ModuleManager/Spells/DiggingSpell.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModuleManager.Spells;
namespace ModuleManager
{
public class DiggingSpell : Spell
{
private readonly DiggingModifier _modifier = new DiggingModifier(1.5f);
public override void Process()
{
GetModule<PlayerModule>().AddModifier(_modifier);
}
public override void PostProcess()
{
GetModule<PlayerModule>().RemoveModifier(_modifier);
}
}
}
<file_sep>/ModuleManager/LevelFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModuleManager.Spells;
namespace ModuleManager
{
public class LevelFactory
{
public LevelModule Instantiate(GameLevelRecord record)
{
var module = new LevelModule();
module.AddModule<TimeModule>();
module.AddModule<InputModule>();
module.AddModule<PlayerModule>()
.SetPlayer<Player>()
.SetValue(CharacterProperty.Speed, 1f)
.SetValue(CharacterProperty.Life, 1)
.SetValue(CharacterProperty.DiggingSpeed, 1f);
module.AddModule<DiggingModule>();
module.AddModule<TeleportModule>().Set(record.Teleports);
module.AddModule<CellModule>().Set(record.Size, record.Cells);
module.AddModule<GuardModule>().Set(record.Guards, record.GuardRespawn, record.GuardRespawnTime);
module.AddModule<StateModule>();
module.AddModule<CoinModule>().Set(record.GoldGhests);
module.AddModule<SpellModule>()
.Add<SpeedUpSpell>()
.Add<SpeedDownSpell>()
.Add<DiggingSpell>();
return module;
}
}
}
<file_sep>/ModuleManager/Spells/SpeedUpSpell.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class SpeedUpSpell : Spell
{
private readonly SpeedModifier _modifier;
public SpeedUpSpell()
{
_modifier = new SpeedModifier(1.1f);
}
public override void Process()
{
GetModule<PlayerModule>().AddModifier(_modifier);
}
public override void PostProcess()
{
GetModule<PlayerModule>().RemoveModifier(_modifier);
}
}
}
<file_sep>/ModuleManager/DiggingModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class DiggingModule : Module, ITick
{
public class DiggInfo
{
public Cell Cell;
public float RemainingTime;
}
private readonly List<DiggInfo> _list = new List<DiggInfo>();
private CellModule _cellModule;
private PlayerModule _playerModule;
private CoinModule _coinModule;
public override void Initialize()
{
_cellModule = GetModule<CellModule>();
_playerModule = GetModule<PlayerModule>();
_coinModule = GetModule<CoinModule>();
}
public void Digg(Point point)
{
var cell = _cellModule.Get(point.X, point.Y);
_list.Add(new DiggInfo
{
Cell = cell,
RemainingTime = 1f
});
}
public bool IsDigg(Point point)
{
return _list.Exists(c => c.RemainingTime > 0f && c.Cell.Point == point);
}
public bool AvailableToDigg(CharacterAction nextMove)
{
var player = _playerModule.GetModule<Player>();
var x = player.X;
var y = player.Y;
switch (nextMove)
{
case CharacterAction.DigLeft:
if (y < _cellModule.Bottom &&
x > 0 &&
_cellModule.Get(x - 1, y + 1).IsNotHiddenBlock &&
_cellModule.Get(x - 1, y).IsEmpty &&
!_coinModule.IsCoin(x - 1, y))
{
return true;
}
break;
case CharacterAction.DigRight:
if (y < _cellModule.Bottom &&
x < _cellModule.Right &&
_cellModule.Get(x + 1, y + 1).IsNotHiddenBlock &&
_cellModule.Get(x + 1, y).IsEmpty &&
!_coinModule.IsCoin(x + 1, y))
{
return true;
}
break;
}
return false;
}
public void PreTick(float time)
{
foreach (var diggInfo in _list)
{
diggInfo.RemainingTime -= time;
}
DiggInfo info;
while ((info = _list.FirstOrDefault(m => m.RemainingTime <= 0f)) != null)
{
_list.Remove(info);
}
}
public void Tick(float time)
{
}
public void PostTick(float time)
{
}
public void FinalTick(float time)
{
}
}
}
<file_sep>/ModuleManager/Events.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Events
{
}
public class DiggingCellEvent : Event
{
public int X;
public int Y;
public DiggingCellEvent(int x, int y)
{
X = x;
Y = y;
}
}
public class PlayerAnimationEvent : Event
{
public enum AnimationEvent
{
RunLeft,
RunRight,
RunUpDn,
BarLeft,
BarRight,
FallLeft,
FallRight,
Stop,
Dead,
DigLeft,
DigRight
}
public PlayerAnimationEvent(AnimationEvent evt)
{
Event = evt;
}
public AnimationEvent Event;
}
}
<file_sep>/ModuleManager/Cells/CellType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//namespace ModuleManager
//{
// public enum CellType
// {
// Empty = 0x00,
// Block = 0x01,
// Solid = 0x02,
// Ladder = 0x03,
// RopeBar = 0x04,
// Trap = 0x05,
// HLadr = 0x06,
// Gold = 0x07,
// Guard = 0x08,
// Runner = 0x09,
// Reborn = 0x10,
// Player = 0x20
// }
//}
//value | Character | Type
//------+-----------+-----------
// 0x0 | <space> | Empty space
// 0x1 | # | Normal Brick
// 0x2 | @ | Solid Brick
// 0x3 | H | Ladder
// 0x4 | - | Hand-to-hand bar (Line of rope)
// 0x5 | X | False brick
// 0x6 | S | Ladder appears at end of level
// 0x7 | $ | Gold chest
// 0x8 | 0 | Guard
// 0x9 | & | Player
<file_sep>/ModuleManager/Characters/Guard.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Guard : Character
{
public override void Initialize()
{
}
}
}
<file_sep>/ModuleManager/Spells/Modifier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public class Modifier
{
public Modifier(CharacterProperty property)
{
Property = property;
}
public CharacterProperty Property { get; private set; }
public virtual float GetValue(float value)
{
return value;
}
}
}
<file_sep>/ModuleManager/ITick.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModuleManager
{
public interface ITick
{
void PreTick(float time);
void Tick(float time);
void PostTick(float time);
void FinalTick(float time);
}
}
|
bb7c0168233f8873a0f84eec09e5a5fe25e6e21f
|
[
"C#"
] | 34
|
C#
|
dorofiykolya/ModuleLR
|
91bb94b0d1f80415d844636377e06653c11f3615
|
d7a5b5b88036a3d99fc54c7e74c26c467a83f37f
|
refs/heads/master
|
<file_sep>/**
* Created by hu on 2016/9/26.
*/
$(function () {
$("#imagegallery img").fadeTo("slow", 0.5);
$("#imagegallery img").hover(function(){
$(this).fadeTo("slow", 1.0); // 设置透明度为100%
},function(){
$(this).fadeTo("slow", 0.5); // 设置不透明度mouseout回到50%
});
});
function showPic(whichpic) {
if(!document.getElementById("placeholder"))return false;
var source=whichpic.getAttribute("href");
var placeholder=document.getElementById("placeholder");
placeholder.setAttribute("src",source);
if(document.getElementById("description")){
var text=whichpic.getAttribute("title")?whichpic.getAttribute("title"):"";
var description=document.getElementById("description");
if (description.firstChild.nodeType==3){
description.firstChild.nodeValue=text;
}
}
return true;
}
function preparePlaceholder() {
var placeholder=document.createElement("img");
placeholder.setAttribute("id","placeholder");
placeholder.setAttribute("src","images/placeholder.png");
placeholder.setAttribute("alt","my image gallery");
var description=document.createElement("p");
description.setAttribute("id","description");
var desctext=document.createTextNode("choose an image");
description.appendChild(desctext);
var gallery=document.getElementById("imagegallery");
insertAfter(placeholder,gallery);
insertAfter(description,placeholder);
}
function prepareGallery() {
if(!document.getElementById("imagegallery"))return false;
var gallery=document.getElementById("imagegallery");
var links=gallery.getElementsByTagName("a");
for (var i=0;i<links.length;i++){
links[i].onclick=function () {
return !showPic(this);
}
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(preparePlaceholder);
window.onload=prepareGallery;
<file_sep>/**
* Created by hu on 2016/9/26.
*/
function addClass(element,value) {
if (!element.className){
element.className=value;
}else {
newClassName=element.className;
newClassName+=" ";
newClassName+=value;
element.className=newClassName;
}
}
function stripeTable() {
var tables=document.getElementsByTagName("table");
var odd,rows;
for(var i=0;i<tables.length;i++){
odd=false;
rows=tables[i].getElementsByTagName("tr");
for(var j=0;j<rows.length;j++){
if(odd==true){
rows[j].style.backgroundColor="#699";
odd=false;
}else {
odd=true;
}
}
}
}
function highlightRows() {
var rows=document.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++){
rows[i].onmouseover=function () {
this.style.fontWeight="bold";
}
rows[i].onmouseout=function () {
this.style.fontWeight="normal";
}
}
}
function displayAbbreviations() {
var abbreviations=document.getElementsByTagName("abbr");
if(abbreviations.length<1)return false;
var defs=new Array();
for (var i=0;i<abbreviations.length;i++){
var current_abbr=abbreviations[i];
if(current_abbr.childNodes.length<1)continue;
var definition=current_abbr.getAttribute("title");
var key=current_abbr.lastChild.nodeValue;
defs[key]=definition;
}
var dlist=document.createElement("dl");
for(key in defs){
var definition=defs[key];
var dtitle=document.createElement("dt");
var dtitle_text=document.createTextNode(key);
dtitle.appendChild(dtitle_text);
var ddesc=document.createElement("dd");
var ddesc_text=document.createTextNode(definition);
ddesc.appendChild(ddesc_text);
dlist.appendChild(dtitle);
dlist.appendChild(ddesc);
}
if(dlist.childNodes.length<1)return false;
var header=document.createElement("h3");
var header_text=document.createTextNode("Abbreviations");
header.appendChild(header_text);
var articles=document.getElementsByTagName("article");
var container=articles[0];
container.appendChild(header);
container.appendChild(dlist);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(stripeTable);
addLoadEvent(highlightRows);
addLoadEvent(displayAbbreviations);
|
2e27f33df75ab623875d8c0a4e84574a0102845f
|
[
"JavaScript"
] | 2
|
JavaScript
|
reborn33/huxia3
|
a7dbd7bb49de49eead682af0a4c203ac41b3e2c1
|
6c70c80ce7a9d8c5bf4d1d13da99b7b528cb01b6
|
refs/heads/master
|
<file_sep>package com.project.pages;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import com.project.base.BasePageObject;
public class LoginPage extends BasePageObject<LoginPage>{
private By emailfield=By.xpath("//input[@id='username']");
private By passwordfield=By.xpath("//input[@id='password']");
private By loginButton= By.xpath("//button[text()='LOGIN']");
Logger log;
public LoginPage(WebDriver driver, Logger log) {
super(driver);
this.log=log;
// TODO Auto-generated constructor stub
}
public void openLoginPage(String url) {
log.info("opening loginpage--");
getPage(url);
}
public void fillupEmailAndPassword(String email,String pswd) {
log.info("fill up email and password--");
type(email,emailfield);
type(pswd,passwordfield);
}
public WelcomePage pushSigninButton() {
log.info("clicking on SignInButton--");
click(loginButton);
return new WelcomePage(driver);
}
}
<file_sep>package com.project;
import org.testng.annotations.Test;
public class WelcomePageTest {
}
<file_sep>package com.project.pages;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.project.base.BasePageObject;
public class WelcomePage extends BasePageObject<WelcomePage>{
private By enterNewItem=By.xpath("//*[text()='Enter a New Item']");
private By titleField=By.xpath("");
private By descriptionField=By.xpath("");
private By addToDoField=By.xpath("");
private By deleteLink=By.xpath("");
private By logoutlink=By.xpath("");
private By addedElement=By.xpath("");
private By LinkPanel=By.xpath("");
public By All=By.linkText("");
public WelcomePage(WebDriver driver) {
// TODO Auto-generated constructor stub
super(driver);
}
public void waitForWelcomePageToLoad() {
waitForVisibilityOf(enterNewItem, 20);
}
public void addNewItem(String newItemTxt,String descriptionText) {
click(enterNewItem);
type(newItemTxt, titleField);
type(descriptionText,descriptionField);
}
public void deleteItem(String newItemTxt,String descriptionText) {
addNewItem(newItemTxt, descriptionText);
click(deleteLink);
}
public boolean findLogout() {
return isElementPresent(logoutlink);
}
public String getActualTextOfaddedElement() {
return getText(addedElement);
}
/* public List<WebElement> getLinksHeader(){
return getElements(LinkPanel);
}*/
public boolean IsLinkDisplayed(By element) {
return isElementPresent(element);
}
}
<file_sep>package com.project.base;
import java.util.List;
import java.util.function.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BasePageObject<T> {
protected WebDriver driver;
protected WebDriverWait wait;
// constructor
protected BasePageObject(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 40);
}
protected T getPage(String URL) {
driver.get(URL);
return (T) this;
}
protected void type(String text, By element) {
find(element).sendKeys(text);
}
private WebElement find(By element) {
return driver.findElement(element);
}
public void get(By element) {
driver.findElement(element);
}
public boolean isElementPresent(By element) {
return find(element).isDisplayed();
}
protected void click(By element) {
find(element).click();
}
protected void waitForVisibilityOf(By locator,Integer...timeOutinSeconds) {
int attempts=0;
while (attempts<2) {
try {
waitfor(ExpectedConditions.visibilityOfElementLocated(locator), (timeOutinSeconds.length>0?timeOutinSeconds[0]:null));
break;
} catch (StaleElementReferenceException e) {
// TODO: handle exception
}
attempts++;
}
}
private void waitfor(ExpectedCondition<WebElement> condition,Integer timeOutInSeconds) {
timeOutInSeconds=timeOutInSeconds!=null?timeOutInSeconds:30;
WebDriverWait wait=new WebDriverWait(driver,timeOutInSeconds);
wait.until(condition);
}
public String getTitle() {
return driver.getTitle();
}
public String getText(By element) {
return driver.findElement(element).getText();
}
public List<WebElement> getElements(By element){
WebElement ele=driver.findElement(element);
return ele.findElements(By.tagName("a"));
}
}
<file_sep>package com.project;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
WebDriver driver;
Logger log;
@BeforeMethod
public void setUp() {
log=Logger.getLogger(".\\src\\main\\resources\\log4j.properties");
log.info("Opening browser --");
driver = new ChromeDriver();
}
@AfterMethod
public void teardown() {
log.info("Closing browser--");
driver.quit();
}
}
|
0bd7f68607d3c32c81adc0d7127e2442323b763e
|
[
"Java"
] | 5
|
Java
|
sanjayvp/Auto3
|
0ed76757e0b12dbc11d461cf0bd8e912c31d3d42
|
90d407a76f8b0344a8e2b694f658fcce70d3ffe9
|
refs/heads/master
|
<repo_name>edwinsamodra/operating-system<file_sep>/so4/main_condition_var.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
// Write numbers 1-3 and 8-10 as permitted by functionCount ()
void * functionCount1() {
for (;;) {
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( & count_mutex);
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( & condition_var, & count_mutex);
count++;
printf("Counter value functionCount1: %d\n", count);
pthread_mutex_unlock( & count_mutex);
if (count >= 10)
return (NULL);
}
}
// Write numbers 4-7
void * functionCount2() {
for (;;) {
pthread_mutex_lock( & count_mutex);
if (count < 3 || count > 6) {
// Condition of if statement has been met.
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".
pthread_cond_signal( & condition_var);
} else {
count++;
printf("Counter value functionCount2: %d\n", count);
}
pthread_mutex_unlock( & count_mutex);
if (count >= 10)
return (NULL);
}
}
void main() {
pthread_t thread1, thread2;
pthread_create( & thread1, NULL, & functionCount1, NULL);
pthread_create( & thread2, NULL, & functionCount2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Final count: %d\n", count);
exit(EXIT_SUCCESS);
}
|
b28274c77db988773df9f2b20a7794e8949fbcb1
|
[
"C"
] | 1
|
C
|
edwinsamodra/operating-system
|
0f9b8900ffbd66738a17189327348e9dcdffc7f2
|
f171645bf33e6660a8ba30fda9b8ddc4db6b92fb
|
refs/heads/master
|
<repo_name>zbanks/livid<file_sep>/Cargo.toml
[package]
name = "livid"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
dlopen = "0.1.5"
dlopen_derive = "0.1.3"
inotify = "0.6.1"
nix = "0.12.0"
libc = "0.2"
structopt = "0.2"
<file_sep>/src/main.rs
#![allow(dead_code)]
extern crate dlopen;
#[macro_use]
extern crate dlopen_derive;
use dlopen::wrapper::{Container, WrapperApi};
extern crate inotify;
extern crate libc;
extern crate structopt;
use structopt::StructOpt;
use std::ffi::{CStr, CString};
use std::fmt;
use std::fs;
use std::fs::File;
use std::io;
use std::io::{BufRead, Seek, SeekFrom, Write};
use std::path;
use std::process::{Command, Stdio};
use std::slice;
use std::str::FromStr;
use std::thread;
use std::default::Default;
use std::marker::PhantomData;
use std::os::raw::c_char;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::RawFd;
use std::time::{Duration, Instant};
// TODO: non-zero default values for numerics
// TODO: parse time, time fns
// TODO: serialize stdin back out to workspace?
type Result<T> = std::result::Result<T, Box<std::error::Error>>;
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum CellType {
Text = 0,
Long = 1,
Time = 2,
Double = 3,
}
impl CellType {
fn upper_str(self: &Self) -> &'static str {
match *self {
CellType::Text => "TEXT",
CellType::Long => "LONG",
CellType::Time => "TIME",
CellType::Double => "DOUBLE",
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
struct CStrPtr<'v> {
ptr: *const i8,
phantom: PhantomData<&'v i8>,
}
impl<'a> CStrPtr<'a> {
fn from(s: &'a CString) -> CStrPtr<'a> {
CStrPtr {
ptr: s.as_ptr(),
phantom: PhantomData,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
union CellValue<'v> {
text: CStrPtr<'v>,
long: i64,
time: i64,
double: f64,
}
#[derive(Debug)]
struct Column {
name: CString,
index: usize,
cell_type: CellType,
grid_width: i16,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct CColumn {
name: *const c_char,
cell_type: CellType,
grid_width: i16,
}
impl<'v> CellValue<'v> {
fn to_string(&self, t: CellType, empty: bool) -> String {
if empty {
String::from("")
} else {
unsafe {
match t {
CellType::Text => self.text.to_string(),
CellType::Long => self.long.to_string(),
CellType::Time => self.time.to_string(), // TODO
CellType::Double => self.double.to_string(),
}
}
}
}
}
impl Column {
fn from_c(c: CColumn, index: usize) -> Self {
Column {
name: CString::from(unsafe { const_char_cstr(c.name) }),
index: index,
cell_type: c.cell_type,
grid_width: c.grid_width,
}
}
fn empty_value<'c>(&'c self) -> Cell<'c, 'c> {
Cell {
column: self,
empty: true,
value: CellValue { long: 0 },
}
}
fn parse_value<'v, 'c: 'v>(&'c self, v: &'v CString) -> Cell<'c, 'v> {
let op_value = match self.cell_type {
CellType::Text => Some(CellValue {
text: CStrPtr::from(v),
}),
CellType::Long => v
.to_str()
.ok()
.and_then(|x| i64::from_str(x).ok())
.map(|x| CellValue { long: x }),
CellType::Time => v
.to_str()
.ok()
.and_then(|x| i64::from_str(x).ok())
.map(|x| CellValue { time: x }),
CellType::Double => v
.to_str()
.ok()
.and_then(|x| f64::from_str(x).ok())
.map(|x| CellValue { double: x }),
};
if let Some(value) = op_value {
Cell {
column: self,
empty: false,
value: value,
}
} else {
self.empty_value()
}
}
}
struct Cell<'col, 'val> {
column: &'col Column,
empty: bool,
value: CellValue<'val>,
}
type Row<'col, 'val> = Vec<Cell<'col, 'val>>;
impl<'val> fmt::Debug for CStrPtr<'val> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", unsafe { const_char_cstr(self.ptr) })
}
}
unsafe fn const_char_cstr<'a>(ptr: *const c_char) -> &'a CStr {
if ptr == std::ptr::null() {
Default::default()
} else {
CStr::from_ptr(ptr)
}
}
impl<'val> CStrPtr<'val> {
fn to_string(&'val self) -> String {
unsafe { const_char_cstr(self.ptr) }
.to_str()
.unwrap()
.to_string()
}
}
impl<'col, 'val> fmt::Debug for Cell<'col, 'val> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.empty {
write!(f, "Empty")
} else {
unsafe {
match self.column.cell_type {
CellType::Text => write!(f, "Text {:?}", self.value.text),
CellType::Long => write!(f, "Long {:?}", self.value.long),
CellType::Time => write!(f, "Time {:?}", self.value.time),
CellType::Double => write!(f, "Double {:?}", self.value.double),
}
}
}
}
}
trait InputTable<'a> {
fn input_columns(&'a self) -> &'a Vec<Column>;
fn output_columns(&'a self) -> &'a Vec<Column>;
fn set_output_columns(&'a mut self, output_columns: Vec<Column>);
fn next(&'a mut self) -> Option<Vec<Cell<'a, 'a>>>;
fn reset(&'a mut self);
}
#[derive(Debug)]
struct CsvInputFile {
delimiter: char,
header: String,
line: String,
reader: io::BufReader<File>,
input_columns: Vec<Column>,
output_columns: Vec<Column>,
output_input_map: Vec<Option<usize>>,
row_index: usize,
raw_cells: Vec<Vec<CString>>,
}
impl CsvInputFile {
fn new(input_path: &path::Path, delimiter: char) -> Result<Self> {
let input_file = File::open(&input_path)?;
let mut input_reader = io::BufReader::new(input_file);
let mut header = String::new();
input_reader.read_line(&mut header)?;
let columns = header
.trim()
.split(delimiter)
.enumerate()
.map(|(i, h)| Column {
name: CString::new(h).unwrap(),
index: i,
cell_type: CellType::Text,
grid_width: 0,
}).collect();
return Ok(CsvInputFile {
delimiter: delimiter,
header: header.trim().to_string(),
line: String::new(),
reader: input_reader,
input_columns: columns,
output_input_map: vec![],
output_columns: vec![],
row_index: 0,
raw_cells: vec![],
});
}
}
impl<'a> InputTable<'a> for CsvInputFile {
fn input_columns(&'a self) -> &'a Vec<Column> {
&self.input_columns
}
fn output_columns(&'a self) -> &'a Vec<Column> {
&self.output_columns
}
fn set_output_columns(&'a mut self, output_columns: Vec<Column>) {
self.output_columns = output_columns;
self.output_input_map = self
.output_columns
.iter()
.map(|oc| {
self.input_columns
.iter()
.find(|ic| ic.name == oc.name)
.map(|ic| ic.index)
}).collect();
}
fn next(&'a mut self) -> Option<Vec<Cell<'a, 'a>>> {
let raw_cells = &mut self.raw_cells;
let line_buf = &mut self.line;
let delimiter = self.delimiter;
let reader = &mut self.reader;
let input_len = self.input_columns.len();
let output_input_map: &Vec<_> = &self.output_input_map;
let output_columns = &self.output_columns;
let raw_row = if raw_cells.len() > self.row_index {
raw_cells.get(self.row_index)
} else {
line_buf.clear();
reader.read_line(line_buf).ok().and_then(move |rc| {
if rc <= 0 {
return None;
}
let mut l: Vec<CString> = line_buf
.trim()
.split(delimiter)
.map(|s| CString::new(s).unwrap())
.collect();
l.resize(input_len, CString::default());
raw_cells.push(l);
raw_cells.last()
})
}?;
self.row_index += 1;
Some(
output_input_map
.iter()
.zip(output_columns.iter())
.map(|(opt_idx, col)| {
opt_idx
.and_then(|x| raw_row.get(x))
.map(|x| col.parse_value(x))
.unwrap_or(col.empty_value())
}).collect(),
)
}
fn reset(&'a mut self) {
self.row_index = 0;
}
}
#[repr(C)]
struct LividApi<'a> {
next: extern "C" fn(api: *mut LividApi<'a>, row_out: *mut CellValue<'a>, empty_out: *mut i8) -> i8,
grid: extern "C" fn(api: *mut LividApi<'a>, row: *const CellValue<'a>, empty: *const i8) -> i8,
write: extern "C" fn(api: *mut LividApi<'a>, string: *const c_char) -> (),
input: &'a mut CsvInputFile,
editor: &'a mut Editor,
}
extern "C" fn livid_api_raw_next<'a>(api: *mut LividApi<'a>, row_out: *mut CellValue<'a>, empty_out: *mut i8) -> i8 {
unsafe {
if let Some(row) = (*api).input.next() {
for (i, cell) in row.iter().enumerate() {
row_out.add(i).write(cell.value.clone());
empty_out.add(i).write(cell.empty as i8);
}
1
} else {
0
}
}
}
extern "C" fn livid_api_raw_grid<'a>(api: *mut LividApi<'a>, row: *const CellValue<'a>, empty: *const i8) -> i8 {
unsafe {
let api = &mut (*api);
let columns = &api.input.output_columns();
let row_slice = slice::from_raw_parts(row, columns.len());
let empty_slice = slice::from_raw_parts(empty, columns.len());
api.editor
.grid(columns, row_slice, empty_slice)
.map(|x| x as i8)
.unwrap_or(-1)
}
}
extern "C" fn livid_api_raw_write<'a>(api: *mut LividApi<'a>, string: *const i8) -> () {
unsafe {
(*api)
.editor
.write(const_char_cstr(string).to_str().unwrap())
.unwrap()
}
}
impl<'a> LividApi<'a> {
fn new(input: &'a mut CsvInputFile, editor: &'a mut Editor) -> Self {
LividApi {
next: livid_api_raw_next,
grid: livid_api_raw_grid,
write: livid_api_raw_write,
input: input,
editor: editor,
}
}
}
#[derive(WrapperApi, Debug)]
struct LividLib<'a> {
columns: *const CColumn,
columns_count: &'a usize,
grid_rows_limit: &'a usize,
run: extern "C" fn(api: &'a LividApi<'a>) -> (),
}
struct StdioRedirector {
stdout_fd: RawFd,
stderr_fd: RawFd,
}
impl StdioRedirector {
fn new(target_fd: RawFd) -> Self{
unsafe {
let stdout_fd = libc::dup(1);
let stderr_fd = libc::dup(2);
libc::close(1);
libc::dup(target_fd);
libc::close(2);
libc::dup(target_fd);
StdioRedirector {
stdout_fd: stdout_fd,
stderr_fd: stderr_fd,
}
}
}
}
impl Drop for StdioRedirector {
fn drop(&mut self) {
unsafe {
libc::close(1);
libc::dup(self.stdout_fd);
libc::close(self.stdout_fd);
libc::close(2);
libc::dup(self.stderr_fd);
libc::close(self.stderr_fd);
}
}
}
struct Editor {
workspace: path::PathBuf,
vimrc_path: path::PathBuf,
script_file: File,
log_file: File,
output_file: File,
script_notify: inotify::Inotify,
grid_rows: usize,
grid_rows_limit: usize,
auto_widths: Vec<usize>,
redirector: StdioRedirector,
last_reload: Instant,
}
impl Editor {
fn new() -> Result<Self> {
let workspace = path::PathBuf::from("./wkspace");
fs::create_dir_all(&workspace)?;
let header_file_path = workspace.join("livid.h");
let mut header_file = File::create(&header_file_path)?;
header_file.write_all(include_str!("../c_src/livid.h").as_bytes())?;
let script_file_path = workspace.join("script.c");
let script_file = File::create(&script_file_path)?;
let mut script_notify = inotify::Inotify::init()?;
script_notify.add_watch(script_file_path.clone(), inotify::WatchMask::CLOSE_WRITE)?;
let log_file_path = workspace.join("log");
let log_file = File::create(&log_file_path)?;
let output_file_path = workspace.join("output");
let output_file = File::create(&output_file_path)?;
let vimrc_path = workspace.join("vimrc");
{
let mut vimrc = File::create(&vimrc_path)?;
write!(vimrc, "set backupcopy=yes\n")?;
write!(vimrc, "set autoread\n")?;
write!(vimrc, "set splitbelow\n")?;
write!(vimrc, "edit {}\n", output_file_path.to_str().unwrap())?;
write!(vimrc, "split {}\n", log_file_path.to_str().unwrap())?;
write!(vimrc, "vsplit {}\n", script_file_path.to_str().unwrap())?;
}
let log_fd = log_file.as_raw_fd();
Ok(Editor {
workspace: workspace,
vimrc_path: vimrc_path,
script_file: script_file,
script_notify: script_notify,
log_file: log_file,
output_file: output_file,
grid_rows: 0,
grid_rows_limit: 20,
auto_widths: vec![],
redirector: StdioRedirector::new(log_fd),
last_reload: Instant::now(),
})
}
fn launch(&mut self) -> Result<thread::JoinHandle<()>> {
let vim_stdin = File::open("/dev/tty")?;
let vim_stdout = File::create("/dev/tty")?;
let vim_stderr = self.log_file.try_clone()?;
let vimrc_path = self.vimrc_path.clone();
Ok(thread::spawn(move || {
Command::new("vim")
.arg("--servername")
.arg("livid")
.arg("-S")
.arg(vimrc_path.as_os_str())
.stdin(Stdio::from(vim_stdin))
.stdout(Stdio::from(vim_stdout))
.stderr(Stdio::from(vim_stderr))
.status()
.unwrap();
}))
}
fn reload(&mut self, force: bool) -> Result<()> {
let now = Instant::now();
if force || now > self.last_reload + Duration::from_millis(100) {
self.last_reload = now;
self.output_file.sync_all()?;
Command::new("vim")
.arg("--servername")
.arg("livid")
.arg("--remote-send")
.arg("<Esc>:checktime<CR>")
.status()?;
}
Ok(())
}
fn compile(&mut self) -> std::io::Result<path::PathBuf> {
let lib_path = self.workspace.join("liblivid.so").to_path_buf();
Command::new("/usr/bin/gcc")
.arg("-std=c99")
.arg("-Wall")
.arg("-Wextra")
.arg("-Wconversion")
.arg("-Werror")
.arg("-O0")
.arg("-ggdb3")
.arg("-D_POSIX_C_SOURCE=201704L")
.arg("-fPIC")
.arg("-shared")
.arg("-o")
.arg(&lib_path)
.arg(self.workspace.join("script.c"))
.stderr(self.log_file.try_clone()?)
.status()?;
Ok(lib_path)
}
fn grid<'a>(&mut self, columns: &Vec<Column>, values: &[CellValue<'a>], emptys: &[i8]) -> Result<bool> {
assert!(columns.len() == values.len());
assert!(columns.len() == emptys.len());
if self.auto_widths.len() < columns.len() {
self.auto_widths.resize(columns.len(), 0);
}
if self.grid_rows == 0 {
for (column, auto_width) in columns.iter()
.zip(self.auto_widths.iter_mut()) {
let grid_width = column.grid_width;
let width = if grid_width < 0 {
continue;
} else if grid_width == 0 {
*auto_width
} else {
grid_width as usize
};
let string_value = column.name.to_str().unwrap();
write!(
self.output_file,
"| {val:>width$} ",
width = width,
val = string_value
)?;
*auto_width = std::cmp::max(*auto_width, string_value.len());
}
write!(self.output_file, "|\n")?;
for (column, auto_width) in columns.iter()
.zip(self.auto_widths.iter_mut()) {
let grid_width = column.grid_width;
let width = if grid_width < 0 {
continue;
} else if grid_width == 0 {
*auto_width
} else {
grid_width as usize
};
let dashes = "-".repeat(width + 2);
write!(self.output_file, "+{}", dashes)?;
}
write!(self.output_file, "+\n")?;
}
if self.grid_rows >= self.grid_rows_limit {
if self.grid_rows == self.grid_rows_limit {
write!(self.output_file, "------\nHit limit of {} rows\n", self.grid_rows_limit)?;
self.reload(true)?;
}
return Ok(true);
}
self.grid_rows += 1;
for (((column, value), empty), auto_width) in columns.iter()
.zip(values.iter())
.zip(emptys.iter().map(|x| *x != 0))
.zip(self.auto_widths.iter_mut()) {
let grid_width = column.grid_width;
let width = if grid_width < 0 {
continue;
} else if grid_width == 0 {
*auto_width
} else {
grid_width as usize
};
let string_value = value.to_string(column.cell_type, empty);
write!(
self.output_file,
"| {val:>width$} ",
width = width,
val = string_value
)?;
*auto_width = std::cmp::max(*auto_width, string_value.len());
}
write!(self.output_file, "|\n")?;
self.reload(false)?;
Ok(false)
}
fn write(&mut self, string: &str) -> Result<()> {
write!(self.output_file, "{}", string)?;
Ok(())
}
fn reset_output(&mut self) -> std::io::Result<()> {
self.output_file.set_len(0)?;
self.output_file.seek(SeekFrom::Start(0))?;
self.log_file.set_len(0)?;
self.log_file.seek(SeekFrom::Start(0))?;
self.grid_rows = 0;
Ok(())
}
fn set_grid_rows_limit(&mut self, limit: usize) -> () {
self.grid_rows_limit = limit;
}
}
fn run_livid(mut editor: Editor, mut input: CsvInputFile) -> Result<()> {
generate_script(&mut editor.script_file, input.input_columns())?;
let _editor_jh = editor.launch()?;
loop {
editor.reset_output()?;
let lib_path = editor.compile()?;
println!("Compiled: {:?}", lib_path);
{
let api = LividApi::new(&mut input, &mut editor);
let container: Container<LividLib> = unsafe { Container::load(lib_path) }.unwrap();
println!(
"Loaded container: {:?} {:?}",
container.columns, container.columns_count
);
api.editor.set_grid_rows_limit(*container.grid_rows_limit);
let output_columns =
unsafe { slice::from_raw_parts(container.columns, *container.columns_count) }
.iter()
.enumerate()
.map(|(i, c)| { Column::from_c(*c, i) })
.collect();
println!("Columns: {:?}", output_columns);
api.input.set_output_columns(output_columns);
api.input.reset();
container.run(&api);
}
editor.reload(true).unwrap();
let mut buffer = [0; 1024];
let _events = editor.script_notify.read_events_blocking(&mut buffer);
}
}
fn generate_script(file: &mut File, columns: &Vec<Column>) -> Result<()> {
file.set_len(0)?;
write!(file, "#define COLUMN_LIST \\\n")?;
write!(
file,
" /* {:16} {:10} {:10} */\\\n",
"column name", "type", "grid width"
)?;
for column in columns {
write!(
file,
" COLUMN({:16}, {:10}, {:10}) \\\n",
column.name.to_str().unwrap(),
column.cell_type.upper_str(),
"GRID_AUTO"
)?;
}
write!(file, "\n")?;
file.write_all(include_str!("../c_src/template.c").as_bytes())?;
file.sync_all()?;
Ok(())
}
fn main() -> Result<()> {
let opt = Opt::from_args();
let editor = Editor::new()?;
let input = CsvInputFile::new(&opt.input, opt.delimiter)?;
println!("Header: {:#?}", input.input_columns());
run_livid(editor, input)
}
#[derive(StructOpt, Debug)]
#[structopt(name = "livid")]
struct Opt {
/// Input CSV file
#[structopt(name = "file", default_value = "/dev/stdin", parse(from_os_str))]
input: path::PathBuf,
#[structopt(short = "d", long = "delimiter", default_value = ",")]
delimiter: char,
}
<file_sep>/c_src/Makefile
#CC=gcc
#CC=clang
#CC=afl-clang-fast
CFLAGS = -std=c11 -Wall -Wextra -Wconversion -Werror -D_POSIX_C_SOURCE=201804L -I.
CFLAGS += -ggdb3 -O0
#CFLAGS += -O3
liblivid.so: livid.c | livid.h
$(CC) $(CFLAGS) $^ -shared -fPIC -ldl -o $@
.PHONY: clean
clean:
-rm -f *.o *.so
.PHONY: all
all: liblivid.so
.DEFAULT_GOAL = all
<file_sep>/c_src/template.c
// TEXT, LONG, TIME, DOUBLE
// GRID_AUTO, GRID_HIDDEN, GRID_WIDTH(12)
#include "livid.h"
const size_t grid_rows_limit = 20;
void run(struct api * api) {
printf("hello\n");
struct row row[1];
while (api_next(api, row)) {
//row->b *= 2;
//row->_empty.c = row->a & 1;
if (api_grid(api, row)) return;
}
}
<file_sep>/c_src/livid.h
#ifndef __LIVID_H__
#define __LIVID_H__
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#define PASTE(x, y) PASTE2(x, y)
#define PASTE2(x, y) x ## y
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x
// Types
#define TYPE_LIST \
TYPE(TEXT, 0) \
TYPE(LONG, 1) \
TYPE(TIME, 2) \
TYPE(DOUBLE, 3) \
#define _TYPE_CTYPE_TEXT const char *
#define _TYPE_CTYPE_TIME long
#define _TYPE_CTYPE_LONG long
#define _TYPE_CTYPE_DOUBLE double
#define _TYPE_CTYPE(t) PASTE(_TYPE_CTYPE_, t)
enum cell_type {
#define TYPE(t, n) PASTE(TYPE_, t) = n,
TYPE_LIST
#undef TYPE
};
#define TYPE(t, _n) _Static_assert(sizeof(_TYPE_CTYPE(t)) <= sizeof(uint64_t), "Each value type must be less than 8 bytes: " t " with type " STRINGIFY(_TYPE_CTYPE(t)) " is too big");
TYPE_LIST
#undef TYPE
static inline const char * strtype(enum cell_type type) {
switch (type) {
#define TYPE(t, n) case PASTE(TYPE_, t): return STRINGIFY(t);
TYPE_LIST
#undef TYPE
}
return "(unknown)";
}
struct column {
const char * const name;
enum cell_type cell_type;
int16_t grid_width;
};
#define GRID_WIDTH(n) (n)
#define GRID_HIDDEN -1
#define GRID_AUTO 0
struct row {
#define COLUMN(_NAME, _TYPE, _GRID_WIDTH) union { _TYPE_CTYPE(_TYPE) _NAME; uint64_t PASTE(_placeholder_, _NAME); };
COLUMN_LIST
#undef COLUMN
struct {
#define COLUMN(_NAME, _TYPE, _GRID_WIDTH) bool _NAME;
COLUMN_LIST
#undef COLUMN
} _empty;
};
struct api;
struct api {
int8_t (* const next)(struct api * api, void * row_out, bool * empty_out);
int8_t (* const grid)(struct api * api, const void * row, const bool * empty);
void (* const write)(struct api * api, const char * str);
char _rust_owned_data[];
};
// Exports
void run(struct api * api);
#define COLUMN(_NAME, _TYPE, _GRID_WIDTH) (struct column) { .name = STRINGIFY(_NAME), .cell_type = PASTE(TYPE_, _TYPE), .grid_width = _GRID_WIDTH},
const struct column columns[] = {
COLUMN_LIST
};
#undef COLUMN
const size_t columns_count = sizeof(columns) / sizeof(columns[0]);
// Functions to use inside script
static bool
api_next(struct api * const api, struct row * const row) {
return api->next(api, row, (bool *) &row->_empty);
}
static bool
api_grid(struct api * const api, struct row const * const row) {
return api->grid(api, row, (bool *) &row->_empty);
}
#define printf(...) api_printf(api, ## __VA_ARGS__)
static void
api_printf(struct api * const api, const char * const fmt, ...) {
va_list vargs;
va_start(vargs, fmt);
int len = vsnprintf(NULL, 0, fmt, vargs) + 1;
if (len < 0) return;
static char * buf = NULL;
static size_t buflen = 0;
if (buflen < (size_t) len) {
size_t new_buflen = (size_t) len * 2;
char * new_buf = realloc(buf, new_buflen);
if(!new_buf) {
fprintf(stderr, "Unable to realloc %zu bytes for api_printf", new_buflen);
return;
}
buf = new_buf;
buflen = new_buflen;
}
va_end(vargs);
va_start(vargs, fmt);
vsnprintf(buf, buflen, fmt, vargs);
va_end(vargs);
buf[buflen-1] = '\0';
api->write(api, buf);
}
#endif
<file_sep>/README.md
# livid
Rust tool to process text in vim
|
65ed7f8d3ce0a4c30a24f93275be2e4008cb1a20
|
[
"TOML",
"Markdown",
"Makefile",
"Rust",
"C"
] | 6
|
TOML
|
zbanks/livid
|
7a061e9987ac4c2dfac195de43776e6f0f90d56b
|
f2ef48413174a39a46ef519a8755e0e405b42111
|
refs/heads/master
|
<file_sep>// @flow
import { extractFiles } from 'extract-files';
import type { ErrorValues } from './Errors';
import Errors from './Errors';
import type { Method } from './flow';
import http from './http';
import { arrayToObject, clone, containsFile, emptyValue, hasOwn, isArr, isFile, isNil, isObj, isStr, isFunc } from './utils';
type PrimitiveFormValue = string | number | boolean | null | typeof undefined;
type ScalarFormValue = PrimitiveFormValue | Blob | File;
type FormValue = ScalarFormValue | Array<?FormValue> | { [string]: ?FormValue };
export type Data = { [string]: FormValue };
type DataCb = () => Data;
type Options = {
method: Method,
baseUrl: string,
url: string,
graphql: string,
sendWith: (method: Method, url: string, data: FormData | Data, options: Options) => Promise<any>,
useJson: boolean,
strictMode: boolean,
isValidationError: ({ status: number }) => boolean,
formatData: (Data) => Data,
formatErrorResponse: (any) => ErrorValues,
timeout: false | number,
autoRemoveError: boolean,
clear: boolean,
quiet: boolean,
clone: boolean,
addAppendToDataCallback: boolean,
}
type PartialOptions = $Shape<Options>;
function set(obj: FormValue, keys: number|string|string[], value: FormValue) {
if (isStr(keys) || (typeof keys === 'number')) {
keys = (''+keys).split('.');
}
let key = keys.shift();
if (!isObj(obj) || isFile(obj)) {
return;
}
if (!keys.length) {
if (isArr(obj)) {
obj[+key] = value;
} else {
obj[key] = value;
}
} else {
if (!hasOwn(obj, key)) {
if (isArr(obj)) {
obj[+key] = key === '0' ? [] : {};
} else {
obj[key] = key === '0' ? [] : {};
}
}
if (isArr(obj)) {
set(obj[+key], keys, value);
} else {
set(obj[key], keys, value);
}
}
}
function get(obj: FormValue, keys: string|string[]): FormValue {
if (isStr(keys)) {
keys = keys.split('.');
}
let key = keys.shift();
if (!isObj(obj) || isFile(obj) || !hasOwn(obj, key)) {
return undefined;
}
let result: FormValue;
if (isArr(obj)) {
result = obj[+key];
} else if (isObj(obj) && !isFile(obj)) {
result = obj[key];
} else {
result = undefined;
}
if (!keys.length) {
return result;
}
get(result, keys);
}
function parseOptions(method: ?(Method | PartialOptions), url: ?(string | PartialOptions), options: ?PartialOptions): PartialOptions {
method = method ? (isObj(method) ? method : { method }) : {};
url = url ? (isObj(url) ? url : { url }) : {};
options = options || {};
return {
...options,
...url,
...method,
}
}
function flattenToQueryParams(data: Data | Array<FormValue>, prefix: string = ''): Array<[ string, string | Blob | File ]> {
let params = [];
if (isArr(data)) {
data.forEach(item => {
let paramKey = `${prefix}[]`;
if (isObj(item) && !isFile(item)) {
params = params.concat(flattenToQueryParams(item, paramKey));
return;
}
params.push([paramKey, isFile(item) ? item : formValueToString(item)]);
})
} else {
Object.keys(data).forEach(key => {
let item = data[key];
let paramKey = prefix ? `${prefix}[${key}]` : '' + key;
if (isObj(item) && !isFile(item)) {
params = params.concat(flattenToQueryParams(item, paramKey));
return;
}
params.push([paramKey, isFile(item) ? item : formValueToString(item)]);
});
}
return params;
}
function formValueToString(value: PrimitiveFormValue): string {
if (typeof value === 'boolean') {
return ''+(+value);
}
if (typeof value === 'number') {
return value.toString();
}
return value || '';
}
function bubbleError(error: Error | Object): Promise<Object> {
if (error instanceof Error) {
throw error;
}
return Promise.reject(error);
}
function isValidErrorObject(errors) {
return !errors ||
typeof errors !== 'object' ||
!Object.keys(errors).length ||
Object.values(errors).some(error => {
if (isArr(error)) {
return error.some(message => !isStr(message));
}
return !isStr(error);
});
}
class Form {
_errors: Errors;
_data: Data;
_dataCb: ?DataCb;
_originalData: Data;
_originalConstantData: Data;
_options: Options;
static defaultOptions: Options = {
// The default method type used by the submit method
method: 'post',
// If set any relative urls will be appended to the baseUrl
baseUrl: '',
// The url to submit the form
url: '',
// The endpoint to use for all graphql queries
graphql: 'graphql',
// A callback to implement custom HTTP logic.
// It is recommended to use this option so the form can utilise your HTTP library.
// The callback should return a promise that the form can use to handle the response.
sendWith: http,
// Set to true if you want the form to submit the data as a json object.
// This will pass the data as a JavaScript object to the sendWith callback so it is up to you to stringify it for your HTTP library.
// If the data contains a File or Blob object the data will be a FormData object regardless of this option (unless strictMode is true).
useJson: false,
// If set to true the form will use follow the `useJson` option even if the data contains non JSONable values (including files).
strictMode: false,
// The status code for which the form should handle validation errors.
isValidationError: ({ status }) => status === 422,
// A callback to format the data before sending it.
formatData: (data) => data,
// A callback that should turn the error response into an object of field names and their validation errors.
formatErrorResponse: (response) => {
let data = response.data || response.response;
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
throw new Error('Unable to find errors in the response');
}
}
let errors: ErrorValues = data.errors;
if (isValidErrorObject(errors)) {
throw new Error('Unable to find errors in the response');
}
return errors;
},
// The number of milliseconds to wait before clearing the error messages.
// When timeout is false the error messages will stay indefinitely.
timeout: false,
// When set to true the errors for a field will be cleared when that field's value is updated.
autoRemoveError: true,
// When set to true, the data will be reverted to it's original values after a successful request.
clear: true,
// When set to true, no errors will be recorded.
quiet: false,
// If clone is set to false any nested objects and arrays will be stored in the form by reference.
clone: true,
// If the form is called with a callback constructor then any data added
// later will be included when the form is reset. Set this to false to
// have the form reset using just the callback.
addAppendToDataCallback: true,
};
static setOptions = function (options: Options) {
Form.defaultOptions = {
...Form.defaultOptions,
...options
};
};
constructor(data: Data|DataCb, options: ?Options) {
this.setOptions(options);
if (isFunc(data)) {
this._dataCb = data;
data = data();
}
this._originalData = {};
this._originalConstantData = {};
this._data = {};
// $FlowFixMe
this.append(data, undefined, false, false);
this._errors = new Errors();
}
setOptions(options: ?Options) {
this._options = this._options || Form.defaultOptions;
if (options) {
this._options = {
...this._options,
...options,
}
}
}
append(key: string | Data, value: FormValue, constant: ?boolean = false, addToDataCallback: ?boolean = true): Form {
if (this._dataCb && !constant && this._options.addAppendToDataCallback && addToDataCallback) {
const originalCb = this._dataCb;
this._dataCb = () => {
const data = originalCb();
if (isObj(key)) {
return {
...data,
...key
};
}
return {
...data,
[key]: value,
};
}
}
if (isObj(key)) {
Object.keys(key).forEach(field => {
this.append(field, key[field], constant, false);
});
return this;
}
value = this.parseData(value);
if (constant) {
set(this._originalConstantData, key, value);
} else {
set(this._originalData, key, this.parseData(value));
}
if (!constant) {
set(this._data, key, value);
this.defineProperty(key);
} else {
Object.defineProperty(
this,
key,
{
get: () => undefined,
set: () => {
throw new Error(`The "${key}" value has been set as constant and cannot be modified`);
}
}
);
}
return this;
}
defineProperty(key: string) {
Object.defineProperty(
this,
key,
{
configurable: true,
enumerable: true,
get: () => get(this._data, key),
set: (newValue: FormValue) => {
this.setData(key, newValue);
}
}
);
}
constantData(key: string | Data, value: FormValue): Form {
return this.append(key, value, true, false);
}
getData(): Data {
return {
...this._data,
...this._originalConstantData,
}
}
setData(key: string, value: FormValue) {
set(this._data, key, value);
if (this._options.autoRemoveError) {
this._errors.clear(key);
}
}
errors(): Errors {
return this._errors;
}
reset(): Form {
const originalData = this._dataCb ? this._dataCb() : this._originalData;
for (let field in this._data) {
// $FlowFixMe
delete this[field];
}
this._originalData = {};
this._data = {};
this.append(originalData, undefined, false, false);
this._errors.clear();
return this;
}
clear(field: string): Form {
if (hasOwn(this, field)) {
set(this._data, field, emptyValue(get(this._data, field)));
}
return this;
}
parseData(data: FormValue): FormValue {
return this._options.clone ? clone(data) : data;
}
addFileFromEvent(event: Event | DragEvent, key: ?string): Form {
let node = event.target;
if (!(node instanceof HTMLInputElement)) {
throw new Error('Incompatible event target, must be of type HTMLInputElement');
}
if (!key) {
key = node.name;
}
if (key in this && (node.value !== '')) {
if (event instanceof DragEvent) {
this.setData(key, event.dataTransfer && event.dataTransfer.files.length && event.dataTransfer.files[0]);
} else {
this.setData(key, node.files && node.files.length && node.files[0]);
}
node.value = '';
}
return this;
}
post(url: string | Options, options: ?Options): Promise<any> {
return this.submit('post', url, options);
}
put(url: string | Options, options: ?Options): Promise<any> {
return this.submit('put', url, options);
}
patch(url: string | Options, options: ?Options): Promise<any> {
return this.submit('patch', url, options);
}
delete(url: string | Options, options: ?Options): Promise<any> {
return this.submit('delete', url, options);
}
get(url: string | Options, options: ?Options): Promise<any> {
return this.submit('get', url, options);
}
graphql(query: string, options: ?Options): Promise<any> {
options = options || {};
const originalFormatDataCallback = options.formatData || this._options.formatData;
options.url = options.graphql || this._options.graphql;
options.useJson = !this.hasFile();
options.formatData = (data) => {
data = originalFormatDataCallback ? originalFormatDataCallback(data) : data;
const operations = {
query,
variables: data,
};
if (!this.hasFile()) {
return operations;
}
const { clone, files } = extractFiles(data);
operations.variables = clone;
return {
operations: JSON.stringify(operations),
map: JSON.stringify(arrayToObject(Array.from(files.values()))),
...arrayToObject(Array.from(files.keys())),
};
};
return this.post(options);
}
submit(method: Method | Options, url: ?string | Options, options: ?Options): Promise<any> {
options = parseOptions(method, url, options);
const requestOptions = {
...this._options,
...options,
};
let formData, data = requestOptions.formatData(this.getData());
if (this.shouldConvertToFormData(requestOptions)) {
formData = new FormData();
let params = flattenToQueryParams(data);
params.forEach(([key, param]) => {
formData.append(key, param);
});
data = formData;
}
let httpAdapter = requestOptions.sendWith;
return httpAdapter(requestOptions.method, this.buildBaseUrl(requestOptions), data, requestOptions).then(response => {
if (requestOptions.isValidationError(response)) {
this.onFail(response, requestOptions);
} else {
this.onSuccess(requestOptions);
}
return response;
}).catch(error => {
if (requestOptions.isValidationError(error)) {
this.onFail(error, requestOptions);
}
return bubbleError(error);
});
}
shouldConvertToFormData(options: ?Options) {
options = options || this._options;
if (options.strictMode) {
return !options.useJson;
}
return !options.useJson || this.hasFile();
}
hasFile(): boolean {
return containsFile(this.getData());
}
onSuccess(options: ?Options) {
options = options || this._options;
if (options.clear) {
this.reset();
}
}
onFail(error: XMLHttpRequest, options: ?Options) {
options = options || this._options;
if (!options.quiet) {
let errors = options.formatErrorResponse(error);
this._errors.record(errors, options.timeout);
if (this._errors.hasElements()) {
this._errors.scrollToFirst();
}
}
}
buildBaseUrl(options: ?Options) {
options = options || this._options;
if (options.url.includes('://')) {
return options.url;
}
let baseUrl = options.baseUrl;
let relativeUrl = options.url;
baseUrl = baseUrl.replace(/\/+$/g, '');
relativeUrl = relativeUrl.replace(/^\/+/g, '');
return `${baseUrl}/${relativeUrl}`;
}
makeUrl(options: ?Options): string {
let url = this.buildBaseUrl(options);
let queryStart = url.includes('?') ? '&' : '?';
let fullUrl = url + queryStart;
let properties = [];
let data = this.getData();
let params = flattenToQueryParams(data);
params.forEach(([key, item]) => {
if (isFile(item)) {
throw new Error('Cannot convert file to a string');
}
properties.push(key + (isNil(item) ? '' : `=${item}`));
});
return fullUrl + properties.join('&');
}
addElement(key: string, el: HTMLElement) {
this._errors.addElement(key, el);
}
removeElement(el: HTMLElement) {
this._errors.removeElement(el);
}
removeElementKey(key: string) {
this._errors.removeElementKey(key);
}
}
export default Form;
<file_sep>// @flow
const hasOwnProperty = Object.prototype.hasOwnProperty;
export function hasOwn (obj: Object, key: string): boolean %checks {
return hasOwnProperty.call(obj, key)
}
export function isFile(val: mixed): boolean %checks {
return !!val && (val instanceof Blob);
}
export function clone(obj: any): any {
if (isArr(obj)) {
return obj.map(clone);
}
if (obj === null || obj === undefined) {
return null;
}
if (isFile(obj) || ['number', 'string', 'boolean'].includes(typeof obj)) {
return obj;
}
if (isObj(obj)) {
let target = {};
Object.keys(obj).forEach((key) => target[key] = clone(obj[key]));
return target;
}
}
export function emptyValue(original: mixed): Array<any> | {} | '' | null {
if (original instanceof Array) {
return [];
}
if (typeof original === 'object') {
return {};
}
if (typeof original === 'string') {
return '';
}
return null;
}
export function isObj(value: mixed): boolean %checks {
return value !== null && typeof value === 'object';
}
export function isArr(value: mixed): %checks {
return value instanceof Array;
}
export function isNil(value: mixed): %checks {
return value == null;
}
export function isFunc(value: mixed): %checks {
return value instanceof Function;
}
export function isStr(value: mixed): %checks {
return typeof value === 'string';
}
export function escapeRegExp(string: string) {
return string.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
}
export function containsFile(obj: any): boolean {
if (isArr(obj)) {
for (let i = 0; i < obj.length; i++) {
if (obj[i] instanceof File) {
return true;
}
if (isObj(obj[i])) {
return containsFile(obj[i]);
}
}
} else {
for (let key in obj) {
if (obj[key] instanceof File) {
return true;
}
if (isObj(obj[key])) {
return containsFile(obj[key]);
}
}
}
return false;
}
export function arrayToObject(array: any[]): { [string]: any } {
let target = {};
array.forEach((item, index) => {
target[index] = item;
});
return target;
}
export function isInViewport(el: Element) {
const boundingBox = el.getBoundingClientRect();
// $FlowFixMe
return boundingBox.top >= 0 && boundingBox.bottom <= (window.innerHeight || window.document.documentElement.clientHeight);
}
<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
test('Accessing properties passed to the form', () => {
const form = new Form({ name: 'Bob' });
expect(form.name).toBe('Bob');
expect(form.getData()).toEqual({ name: 'Bob' });
});
test('Properties passed to the form with a callback', () => {
let name = 'Bob';
let secondName;
const form = new Form(() => {
const data = { name };
if (secondName) {
data.secondName = secondName;
} else {
secondName = 'Ted';
}
return data;
});
expect(form.name).toBe('Bob');
expect(form.secondName).toBeUndefined();
expect(form.getData()).toEqual({ name: 'Bob' });
name = 'Bill';
form.reset();
expect(form.name).toBe('Bill');
expect(form.secondName).toBe('Ted');
expect(form.getData()).toEqual({ name: 'Bill', secondName: 'Ted' });
});
test('Modifying data on the form', () => {
const form = new Form({ name: 'Bob' });
form.name = 'Bill';
expect(form.name).toBe('Bill');
expect(form.getData()).toEqual({ name: 'Bill' });
});
test('Modifying data on the form with a callback', () => {
const form = new Form(() => ({ name: 'Bob' }));
form.name = 'Bill';
expect(form.name).toBe('Bill');
expect(form.getData()).toEqual({ name: 'Bill' });
});
test('Cloning data', () => {
let email = { label: 'private', address: '<EMAIL>' };
const form = new Form({
email
});
form.email.label = 'work';
expect(form.email.label).toBe('work');
expect(email.label).toBe('private');
});
test('Cloning data with callback', () => {
let email = { label: 'private', address: '<EMAIL>' };
const form = new Form(() => ({
email
}));
form.email.label = 'work';
expect(form.email.label).toBe('work');
expect(email.label).toBe('private');
});
test('Disabling cloning data', () => {
let email = { label: 'private', address: '<EMAIL>' };
const form = new Form({
email
}, {
clone: false,
});
form.email.label = 'work';
expect(form.email.label).toBe('work');
expect(email.label).toBe('work');
});
test('Disabling cloning data with callback', () => {
let email = { label: 'private', address: '<EMAIL>' };
const form = new Form(() => ({
email
}), {
clone: false,
});
form.email.label = 'work';
expect(form.email.label).toBe('work');
expect(email.label).toBe('work');
});
<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
let mockXHR;
beforeEach(() => {
mockXHR = {
open: jest.fn(),
send: jest.fn(),
readyState: 4,
response: JSON.stringify(
[
{ title: 'test post' },
{ tile: 'second test post' }
]
),
status: 200,
setRequestHeader: jest.fn(),
};
const oldXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = jest.fn(() => mockXHR);
});
test('Submitting a request', () => {
const form = new Form({
name: 'Bob',
});
form.submit('post', 'https://api.com');
expect(mockXHR.setRequestHeader).toBeCalledWith('Content-Type', 'multipart/form-data');
expect(mockXHR.open).toBeCalledWith('post', 'https://api.com');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData instanceof FormData).toBe(true);
expect(submittedData.get('name')).toBe('Bob');
});
test('Submitting with different methods', () => {
const form = new Form({
name: 'Bob',
});
form.get('https://api.com');
expect(mockXHR.open).toBeCalledWith('get', 'https://api.com');
form.post('https://api.com');
expect(mockXHR.open).toBeCalledWith('post', 'https://api.com');
form.put('https://api.com');
expect(mockXHR.open).toBeCalledWith('put', 'https://api.com');
form.patch('https://api.com');
expect(mockXHR.open).toBeCalledWith('patch', 'https://api.com');
form.delete('https://api.com');
expect(mockXHR.open).toBeCalledWith('delete', 'https://api.com');
});
test('Submitting with different methods overrides request options', () => {
const form = new Form({
name: 'Bob',
});
form.get('https://api.com', { method: 'post' });
expect(mockXHR.open).toBeCalledWith('get', 'https://api.com');
});
test('Submitting with a custom callback', () => {
const form = new Form({
name: 'Bob',
}, {
sendWith(method, url, data) {
expect(method).toBe('post');
expect(url).toBe('https://api.com');
expect(data.get('name')).toBe('Bob');
return Promise.resolve({});
}
});
form.post('https://api.com').catch();
});
test('Submitting json data', () => {
const form = new Form({
name: 'Bob',
}, {
useJson: true,
});
form.submit('post', 'https://api.com');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData).toBe(JSON.stringify({
name: 'Bob',
}));
});
test('Submitting FormData', () => {
const file = new File(['foo'], 'foo.txt', {
type: 'text/plain',
});
const form = new Form({
file,
arr: [1, 2, 3],
key: 'value',
obj: {
key: 'value',
},
}, {
useJson: false,
});
form.submit('post', 'https://api.com');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData instanceof FormData).toBe(true);
const entries = Array.from(submittedData.entries());
expect(entries).toEqual([
['file', file],
['arr[]', '1'],
['arr[]', '2'],
['arr[]', '3'],
['key', 'value'],
['obj[key]', 'value'],
]);
});
test('Submitting a form with useJson reverts to FormData', () => {
const file = new File(['foo'], 'foo.txt', {
type: 'text/plain',
});
const form = new Form({
file,
}, {
useJson: true,
});
form.submit('post', 'https://api.com');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData instanceof FormData).toBe(true);
expect(submittedData.get('file')).toBe(file);
});
test('Submitting a file with useJson in strict mode will still use JSON', () => {
const file = new File(['foo'], 'foo.txt', {
type: 'text/plain',
});
const form = new Form({
file,
}, {
useJson: true,
strictMode: true,
sendWith(method, url, data) {
expect(data instanceof FormData).toBe(false);
return Promise.resolve(true);
}
});
form.submit('post', 'https://api.com');
});
test('Submitting a request with a base url', () => {
const form = new Form({
name: 'Bob',
}, {
baseUrl: 'https://api.com',
});
form.submit('post', 'posts');
expect(mockXHR.open).toBeCalledWith('post', 'https://api.com/posts');
});
test('Submitting a request with a base url trims excess slashes', () => {
const form = new Form({
name: 'Bob',
}, {
baseUrl: 'https://api.com/',
});
form.submit('post', '/posts');
expect(mockXHR.open).toBeCalledWith('post', 'https://api.com/posts');
});
test('Fields are reverted to their original value after a successful request', (done) => {
const form = new Form({
name: 'Bob',
});
form.name = 'Bill';
form.submit('post', '/posts').then(() => {
expect(form.name).toBe('Bob');
done();
});
mockXHR.onload();
});
test('Disabling field clearance after a successful request', (done) => {
const form = new Form({
name: 'Bob',
}, {
clear: false,
});
form.name = 'Bill';
form.submit('post', '/posts').then(() => {
expect(form.name).toBe('Bill');
done();
});
mockXHR.onload();
});
test('Data can be modified before a request is sent', () => {
const form = new Form({
name: 'Bob',
}, {
formatData(data) {
data.name = data.name.toUpperCase();
return data;
}
});
form.submit('post', 'https://api.com');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData.get('name')).toBe('BOB');
});<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
test('Append constant data to the form', () => {
const form = new Form({});
form.constantData('name', 'Bob');
expect(form.name).not.toBe('Bob');
expect(form.getData()).toEqual({ name: 'Bob' });
});
test('Append constant data object to the form', () => {
const form = new Form({});
form.constantData({
name: 'Bob',
job: 'Builder',
});
expect(form.name).not.toBe('Bob');
expect(form.job).not.toBe('Builder');
expect(form.getData()).toEqual({
name: 'Bob',
job: 'Builder',
});
});
test('Attempting to modify constant data', () => {
const form = new Form({});
form.constantData('name', 'Bob');
const t = () => {
form.name = 'Bill';
};
expect(t).toThrow(Error);
expect(form.getData()).toEqual({ name: 'Bob' });
});
test('Cloning constant data', () => {
const form = new Form({});
const email = { label: 'private', address: '<EMAIL>' };
form.constantData('email', email);
email.label = 'work';
expect(form.getData()).toEqual({
email: { label: 'private', address: '<EMAIL>' }
});
});
test('Disabling cloning constant data', () => {
const form = new Form({}, { clone: false });
const email = { label: 'private', address: '<EMAIL>' };
form.constantData('email', email);
email.label = 'work';
expect(form.getData()).toEqual({
email: { label: 'work', address: '<EMAIL>' }
});
});
<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
let mockXHR;
beforeEach(() => {
mockXHR = {
open: jest.fn(),
send: jest.fn(),
readyState: 4,
response: JSON.stringify({
errors: {
username: 'That username has already been taken',
password: [
'The password cannot <PASSWORD> <PASSWORD>',
'The password must contain letters and numbers',
],
}
}),
status: 422,
setRequestHeader: jest.fn(),
};
const oldXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = jest.fn(() => mockXHR);
});
test('The form has errors after an invalid request', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.any()).toBe(true);
done();
});
mockXHR.onload();
});
test('The status code for validation errors can be changed', (done) => {
mockXHR.status = 419;
const wrongCodeForm = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
let wrongCodeRequest = wrongCodeForm.submit('post', 'https://api.com')
.catch((e) => {
expect(wrongCodeForm._errors.any()).toBe(false);
});
mockXHR.onload();
const rightCodeForm = new Form({
username: 'Bob',
password: '<PASSWORD>!',
}, {
isValidationError: ({ status }) => status === 419
});
let rightCodeRequest = rightCodeForm.submit('post', 'https://api.com')
.catch((e) => {
expect(rightCodeForm._errors.any()).toBe(true);
});
mockXHR.onload();
Promise.all([wrongCodeRequest, rightCodeRequest]).then(() => done());
});
test('The response can be modified to the correct response', (done) => {
mockXHR.response = {
messages: [
{ username: 'The username was taken' },
{ password: '<PASSWORD>' },
{ password: '<PASSWORD> and <PASSWORD>' },
]
};
const wrongErrorForm = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
let wrongErrorRequest = wrongErrorForm.submit('post', 'https://api.com')
.catch((e) => {
expect(wrongErrorForm._errors.any()).toBe(false);
expect(e instanceof Error).toBe(true)
});
mockXHR.onload();
const rightErrorForm = new Form({
username: 'Bob',
password: '<PASSWORD>!',
}, {
formatErrorResponse: (xhr) => {
let errors = {};
xhr.response.messages.forEach(message => {
Object.keys(message).forEach(key => {
if (!errors[key]) {
errors[key] = [];
}
errors[key].push(message[key]);
});
});
return errors;
}
});
let rightErrorRequest = rightErrorForm.submit('post', 'https://api.com')
.catch((e) => {
expect(rightErrorForm._errors.any()).toBe(true);
});
mockXHR.onload();
Promise.all([wrongErrorRequest, rightErrorRequest]).then(() => done());
});
test('The form errors can be silenced in options', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
}, {
quiet: true,
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.any()).toBe(false);
done();
});
mockXHR.onload();
});
test('Checking if the form has a certain error', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.has('username')).toBe(true);
expect(form._errors.has('nothing')).toBe(false);
done();
});
mockXHR.onload();
});
test('Getting a certain error', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.get('username')).toBe('That username has already been taken');
expect(form._errors.get('password')).toEqual([
'The password cannot be less than 6 characters',
'The password must contain letters and numbers',
]);
expect(form._errors.get('nothing')).toBe(undefined);
done();
});
mockXHR.onload();
});
test('Getting the first error', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.getFirst('username')).toBe('That username has already been taken');
expect(form._errors.getFirst('password')).toBe('The password cannot be less than 6 characters');
expect(form._errors.getFirst('nothing')).toBe(undefined);
done();
});
mockXHR.onload();
});
test('Getting the first error with a wildcard', (done) => {
mockXHR.response = {
errors: {
key1: 'Invalid key',
key2: ['Invalid other key', 'Bad request'],
}
};
const form = new Form({
key1: 'Bob',
key2: 'Passw0rd!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.getFirst('key*')).toBe('Invalid key');
expect(form._errors.get('key*')).toEqual([
'Invalid key',
'Invalid other key',
'Bad request',
]);
done();
});
mockXHR.onload();
});
test('Clearing the errors', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.any()).toBe(true);
form._errors.clear();
expect(form._errors.any()).toBe(false);
done();
});
mockXHR.onload();
});
test('Clearing the errors after timeout', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
}, {
timeout: 100,
});
form.submit('post', 'https://api.com')
.catch(() => {
setTimeout(() => {
expect(form._errors.any()).toBe(true);
}, 90);
setTimeout(() => {
expect(form._errors.any()).toBe(false);
done();
}, 101);
});
mockXHR.onload();
});
test('Clearing errors when a field is updated', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.has('username')).toBe(true);
expect(form._errors.has('password')).toBe(true);
form.username = 'Bill';
expect(form._errors.has('username')).toBe(false);
expect(form._errors.has('password')).toBe(true);
done();
});
mockXHR.onload();
});
test('Clearing errors when a field is updated can be disabled', (done) => {
const form = new Form({
username: 'Bob',
password: '<PASSWORD>!',
}, {
autoRemoveError: false,
});
form.submit('post', 'https://api.com')
.catch(() => {
expect(form._errors.has('username')).toBe(true);
form.username = 'Bill';
expect(form._errors.has('username')).toBe(true);
done();
});
mockXHR.onload();
});
<file_sep># Formla
An easy to use, highly configurable, object oriented ajax form package.
## Installation
Using npm:
```
npm install formla --save
```
Using yarn:
```
yarn add formla --save
```
## Usage
To use the form, first import it into your project and instantiate a new instance with the form fields and initial
values.
```js
import Form from 'formla';
const form = new Form({
username: '',
password: '',
});
```
Alternately you can pass a callback that will get resolved and will be used when resetting the form.
```js
import Form from 'formla';
const form = new Form(() => ({
username: '',
password: '',
}));
```
### Append data
You can add fields to the form after instantiation using the `append` method.
You can pass the field name and initial value as arguments or you can pass an object of key value pairs.
```js
form.append('email', '');
form.append({
firstName: '',
lastName: '',
});
```
The values supplied to the form can be accessed and updated directly on the form object.
```js
let name = form.firstName + ' ' + form.lastName;
form.username = 'cheesy123';
```
### Constant data
Sometimes you may want to use data that shouldn't be changed, for example an api key or a CSRF token.
For these fields you can use the `constantData` method.
As with the `append` method you can either send a single key and value or an object.
```js
const form = new Form({
username: '',
password: '',
}).constantData('_token', csrfToken);
```
Any fields added using the `constantData` method cannot be accessed on the form object but will be sent in the body of
the request when the form is submitted.
### Dealing with files
You can add a file as a value to any key in the form data but it can be quite annoying to do so.
Instead you can use the `addFileFromEvent` method which accepts an input event from a file `<input>` element and adds
the file to the form.
```js
const form = new Form({
file: null,
});
document.querySelector('input[name="file"]')
.addEventListener('input', (event) => form.addFileFromEvent(event));
```
By default the file will use the name of the input field to find the key, however you can override this by passing the
key as the second argument.
### Submitting the form
The `submit` method accepts 3 arguments. The request method, the url, and some optional configuration.
Alternatively you could just pass the options as the first argument, so long as the options includes the method and the
url.
```js
form.submit('post', 'https://api.com');
```
The form object also exposes a function for each request method.
```js
form.get('https://api.com');
form.post('https://api.com');
form.put('https://api.com');
form.patch('https://api.com');
form.delete('https://api.com');
```
By default the form uses a basic implementation to submit the data however it is recommended to use a different library
like `jQuery` or `axios` to send the request.
You can do this by passing a callback function to the `sendWith` options which accepts the method, url, and data as
parameters.
```js
import axios from 'axios';
Form.setOptions({
sendWith(method, url, data) {
axios({
method,
url,
data,
});
},
});
```
The data argument will be a `FormData` object constructed from the data provided to the form. You can set this to a json
object by setting the `useJson` option to `true`.
>Note, you cannot have a `File` or `Blob` object in JSON so if a file is detected in the form data the form will be
>sent as a `FormData` object, even if `useJson` is `true`. Unless the `strictMode` option is `true` in which case an
>error will be thrown.
>
>All options can either be set globally using the static `setOptions` method, on a per form instance basis by passing
>them as the second argument to the constructor, or on a per request basis by passing them as the last parameter of the
>request method.
### GraphQL
The form class has a `graphql` method that allows you to submit the data as a GraphQL request.
The method accepts a query string and an optional second argument of options.
The data held by the form will be submitted in the `variables` key of the request data.
```js
// Here is an example of how to submit the mutation described in the GraphQL
// docs: https://graphql.org/learn/queries/#mutation
const form = new Form({
ep: 'JEDI',
review: {
stars: 5,
commentary: 'This is a great movie!',
},
});
form.graphql(`
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
`);
```
You can use the `formatData` option to manipulate the data before it is sent. This is great for dealing with input
types and some of the variables are constant.
```js
const form = new Form({
stars: 5,
commentary: 'This is a great movie!',
}, {
formatData(data) {
return {
ep: 'JEDI',
review: data,
}
}
});
form.graphql(`
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
`);
```
#### File uploads
Files are extracted from GraphQL requests according to the multipart request specs:
https://github.com/jaydenseric/graphql-multipart-request-spec#multipart-form-field-structure
### Handling validation errors
An important feature of the form is handling validation errors.
If the form is submitted with invalid data, the server typically sends back error messages with information on why the
data was invalid.
The form object will automatically store these errors and allow you to display them however you like.
By default the form will check for a 422 status code and a json response of the format:
```json
{
"errors": {
"username": [
"The username was already taken",
"The username was too long"
],
"password": [
"<PASSWORD>"
]
}
}
```
You can change the logic for discerning validation errors by overriding the
`isValidationError` callback in the config.
If you're server doesn't return validation errors in this format, you can pass a callback to the `formatErrorResponse`
option which should return an object of the form data keys with their corresponding error messages as a string or an
array of strings:
```js
Form.setOptions({
formatErrorResponse(response) {
return response.error.details;
}
})
```
Once an error response has been caught by the form you can access the errors class with the `errors` property on the
form.
```js
if (form.errors.any()) {
alert('There was an issue');
}
```
The `has` method accepts a string or a regular expression and tells you if the first field matching that string or
expression has an error.
The `get` method will return all the errors for the field provided as the argument.
The `getFirst` method will return the first error if there is an array of errors, otherwise it will just return the
error.
The `clear` method will remove the error messages for the specified field, or all messages if no field is specified.
If you want all the errors to clear after a certain interval you can use the `timeout` option on the form with the
number of milliseconds to wait before clearing the errors.
When the value for a field with errors is updated the error messages for that field are automatically cleared.
This behaviour can be prevented by setting the `autoRemoveError` option to `false`.
Typically you will want to display an error message by the input element with the invalid data.
However sometimes this element could be off the page, especially when the user is on a mobile device.
The form object can automatically scroll to any elements that have errors if you tell it where to go:
```js
const form = new Form({
username: '',
password: '',
});
const usernameInput = document.querySelector('input[name="username"]');
const passwordInput = document.querySelector('input[name="password"]');
form.addElement('username', usernameInput);
form.addElement('password', passwordInput);
```
Make sure you add the elements in the order they appear in the page as the form will use the order they are added to
determine which is the first element with an error and scroll to that one.
If you have a group of inputs inside a container and you just want to scroll to that element for all of the fields
within it, you can pass an array of fields as the first argument, or a regular expression, or even just a string with
`*` wildcards.
### Configuration
The form class has many options for customising the plugin to your needs.
You can set the options globally using the `setOptions` static method:
```js
import Form from 'formla';
Form.setOptions({
baseUrl: 'https://api.com',
});
```
You can set the options for a specific form instance by passing them as a second argument to the constructor or using
the `setOptions` instance method.
These options will override any global options and any options set before them.
```js
const form = new Form({
username: '',
}, {
autoRemoveError: false,
});
form.setOptions({
quiet: true,
});
```
Finally you can set additional options when sending a request.
These options are only used for the request and not saved once the request is finished.
```js
form.post('https://api.com/comments', {
timeout: 5000,
});
```
**All available options and their defaults**
```js
Form.setOptions({
// The default method type used by the submit method
method: 'post',
// If set any relative urls will be appended to the baseUrl
baseUrl: '',
// The url to submit the form
url: '',
// The url of the GraphQL endpoint which will be used by all GraphQL
// requests.
graphql: 'graphql',
// A callback to implement custom HTTP logic.
// It is recommended to use this option so the form can utilise your HTTP
// library.
// The callback should return a promise that the form can use to handle the
// response.
sendWith: null,
// Set to true if you want the form to submit the data as a json object.
// This will pass the data as a JavaScript object to the sendWith callback
// so it is up to you to stringify it for your HTTP library.
// If the data contains a File or Blob object the data will be a FormData
// object regardless of this option (unless strictMode is true).
useJson: false,
// If set to true the form will use follow the `useJson` option even if the
// data contains non JSONable values (including files).
strictMode: false,
// The status code for which the form should handle validation errors.
isValidationError: ({ status }) => status === 422,
// A callback to format the data before sending it.
formatData: (data) => data,
// A callback that should turn the error response into an object of field
// names and their validation errors.
formatErrorResponse: ({ errors }) => errors,
// The number of milliseconds to wait before clearing the error messages.
// When timeout is false the error messages will stay indefinitely.
timeout: false,
// When set to true the errors for a field will be cleared when that field's
// value is updated.
autoRemoveError: true,
// When set to true, the data will be reverted to it's original values after
// a successful request.
clear: true,
// When set to true, no errors will be recorded.
quiet: false,
// When instantiating the form with a callback any fields appended to the
// form after construction are included in the form after reset. Set this
// field to false to reset the form only using the callback supplied.
addAppendToDataCallback: true,
});
```
<file_sep>// @flow
import type { Method } from './flow';
import type { Data } from "./Form";
type Options = {
method: Method,
url: string,
}
export default function http(method: Method, url: string, data: FormData | Data, options: Options) {
let xhr = new XMLHttpRequest();
let response = new Promise<XMLHttpRequest>((resolve, reject) => {
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr);
} else {
reject(xhr);
}
};
xhr.onerror = () => reject(xhr);
});
xhr.open(method, url);
if (data instanceof FormData) {
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(data);
} else {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
}
return response;
}<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
let mockXHR;
beforeEach(() => {
mockXHR = {
open: jest.fn(),
send: jest.fn(),
readyState: 4,
response: '',
setRequestHeader: jest.fn(),
};
window.XMLHttpRequest = jest.fn(() => mockXHR);
});
test('Setting options globally', () => {
Form.setOptions({
method: 'delete',
url: 'https://api.com',
});
const form = new Form({
name: 'Bob',
});
form.submit();
expect(mockXHR.open).toBeCalledWith('delete', 'https://api.com');
});
test('Setting options on the instance overrides global options', () => {
Form.setOptions({
method: 'delete',
url: 'https://api.com',
});
const form = new Form({
name: 'Bob',
}, {
method: 'put',
url: 'https://json.com',
});
form.submit();
expect(mockXHR.open).toBeCalledWith('put', 'https://json.com');
});
test('Setting options on the request overrides instance options', () => {
Form.setOptions({
method: 'delete',
url: 'https://api.com',
});
const form = new Form({
name: 'Bob',
}, {
method: 'put',
url: 'https://json.com',
});
form.submit({
method: 'get',
url: 'https://server.com'
});
expect(mockXHR.open).toBeCalledWith('get', 'https://server.com');
});
<file_sep>/**
* @jest-environment jsdom
*/
import Form from '../src/Form';
let mockXHR;
beforeEach(() => {
mockXHR = {
open: jest.fn(),
send: jest.fn(),
readyState: 4,
response: JSON.stringify(
[
{ title: 'test post' },
{ tile: 'second test post' }
]
),
status: 200,
setRequestHeader: jest.fn(),
};
const oldXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = jest.fn(() => mockXHR);
});
test('Submitting a graphql request', () => {
const form = new Form({
title: 'Blog',
body: 'The body',
});
const query = `
mutation CreateBlog($title: String!, $body: String!) {
createBlog(title: $title, body: $body) {
body
title
}
}
`;
form.graphql(query);
expect(mockXHR.setRequestHeader).toBeCalledWith('Content-Type', 'application/json');
expect(mockXHR.open).toBeCalledWith('post', '/graphql');
const submittedData = JSON.parse(mockXHR.send.mock.calls[0][0]);
expect(submittedData.query).toBe(query);
expect(submittedData.variables).toEqual({
title: 'Blog',
body: 'The body',
});
});
test('Submitting a graphql request with a different endpoint', () => {
const form = new Form({
title: 'Blog',
body: 'The body',
}, {
graphql: 'api',
});
const query = `
mutation CreateBlog($title: String!, $body: String!) {
createBlog(title: $title, body: $body) {
body
title
}
}
`;
form.graphql(query);
expect(mockXHR.open).toBeCalledWith('post', '/api');
});
test('Submitting a graphql request with files', () => {
const file = new File([1], 'a.txt', { type: 'text/plain' });
const form = new Form({
title: 'Blog',
doc: file,
});
const query = `
mutation CreateBlog($title: String!, $file: Upload) {
createBlog(title: $title, file: $file) {
title
}
}
`;
form.graphql(query);
expect(mockXHR.setRequestHeader).toBeCalledWith('Content-Type', 'multipart/form-data');
expect(mockXHR.open).toBeCalledWith('post', '/graphql');
const submittedData = mockXHR.send.mock.calls[0][0];
expect(submittedData instanceof FormData).toBe(true);
expect(submittedData.get('operations')).toBe(JSON.stringify({
query,
variables: {
title: 'Blog',
doc: null,
}
}));
expect(submittedData.get('map')).toBe(JSON.stringify({0: ['doc']}));
expect(submittedData.get('0')).toBe(file);
});
<file_sep>const webpack = require('webpack');
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
function generateConfig(name) {
const uglify = name.indexOf('min') > -1;
const config = {
entry: './src/Form.js',
output: {
path: path.resolve(__dirname, 'lib'),
filename: name + '.js',
sourceMapFilename: name + '.map',
library: 'formla',
libraryTarget: 'umd',
},
mode: 'production',
optimization: {
minimize: uglify,
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
plugins: [
'@babel/plugin-proposal-class-properties',
],
presets: [
'@babel/preset-flow',
],
}
}
}
]
}
};
if (uglify) {
config.optimization.minimizer = [new TerserPlugin()];
}
return config;
}
module.exports = ['Form', 'Form.min'].map(function (key) {
return generateConfig(key);
});
|
c9eb18167d2f24fafb353f1b90ff7183ea9af2cf
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
Codeatron5000/formla
|
7e29e333e594ec604e5e5d5e21f209037d8f18b2
|
b39f1b837b6578bd0c03a5e39bd1c61b16d90deb
|
refs/heads/master
|
<file_sep>######################################################
# ****************************************
# MRAA Test on Minnowboard Max \
# Using Yocto /
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Minnowboard MAX with Calamari LURE
# Turns on an LED corresponding to the button pressed
# LEDs
# R = GPIO_S5_0 : MRAA 21 : Linux Sysfs GPIO = gpio338
# G = GPIO_S5_0 : MRAA 23 : Linux Sysfs GPIO = gpio339
# B = ILB_8254_SPKR : MRAA 26 : Linux Sysfs GPIO = gpio464
# Push Buttons
# R = I2S_CLK : MRAA 14 : Linux Sysfs GPIO = gpio270
# G = UART1_CTS : MRAA 10 : Linux Sysfs GPIO = gpio266
# B = UART1_RTS : MRAA 12 : Linux Sysfs GPIO = gpio268
import mraa
# Declare GPIOS
# LEDs
rl = mraa.Gpio(21)
gl = mraa.Gpio(23)
bl = mraa.Gpio(26)
leds = [rl,gl,bl]
# Buttons
rb = mraa.Gpio(14)
gb = mraa.Gpio(10)
bb = mraa.Gpio(12)
pushbtns = [rb,gb,bb]
# Initialize resources
for led in leds:
led.dir(0) # 0 = MRAA_GPIO_OUT see http://iotdk.intel.com/docs/master/mraa/gpio_8h.html#afcfd0cb57b9f605239767c4d18ed7304
for btn in pushbtns:
btn.dir(1) # 1 = MRAA_GPIO_IN
def turnOn(index):
leds[index].write(1)
def turnOff(index):
leds[index].write(0)
while (True):
index = 0
for btn in pushbtns:
if (btn.read()==0):
turnOn(index)
if (btn.read()==1):
turnOff(index)
index += 1
<file_sep>/*
######################################################
# ****************************************
# MRAA Test on C \
# Read Analog values using Yocto & MRAA /
# Compilation inside Galileo Gen 2 \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
Circuit:
Galileo Gen 2
Photoresistor ADC0
Pass libMRAA to the linker:
gcc-lmraa mraa_galileo_adc.c -o mraa_adc
*/
#include <mraa/aio.h>
#include <time.h>
int main(){
/* Delay to sleep for human sight*/
struct timespec a,b;
a.tv_sec = 0;
a.tv_nsec = 500000000L;
/* Golden Rule */
mraa_aio_context adc_a0;
uint16_t adc_value = 0;
float adc_value_float = 0.0;
/* Initialize Pin */
adc_a0 = mraa_aio_init(0);
if (adc_a0 ==NULL){
return 1;
}
/* Read and print values Loopy-Loop */
for(;;){
adc_value = mraa_aio_read(adc_a0);
adc_value_float = mraa_aio_read_float(adc_a0);
fprintf(stdout, "ADC A0: %d\n", adc_value, adc_value);
fprintf(stdout, "ADC A0 float: %.3f\n", adc_value_float);
if(nanosleep(&a,&b)<0){
return 1;
}
}
mraa_aio_close(adc_a0);
return MRAA_SUCCESS;
}
<file_sep>#!/usr/bin/python
######################################################
# ****************************************
# Neural Network Color Classification \
# Using Yocto & Numpy /
# Running KnNN Network \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Red: Connected to Pin 2 : Linux GPIO = gpio13 : Mux gpio34 = 0
# Green: Connected to Pin 3 : Linux GPIO = gpio14 : Mux gpio16 = 0
# Blue: Connected to Pin 4 : Linux GPIO = gpio6 : Mux gpio36 = 0
# Photoresistor: Connected to ADC0 : iio:device0/in_voltage0_raw
# Classes
# Red = 1
# Green = 2
# Blue = 3
# Nothing = 4
# Imports
import sys
import time
from neural_nets import knnn
# Specify number of neighbors
k=5
# Declare GPIOs
iored = "13"
iogreen = "14"
ioblue = "6"
muxred = "34"
muxgreen = "16"
muxblue = "36"
iolist = []
iolist.append(iored)
iolist.append(iogreen)
iolist.append(ioblue)
muxlist = []
muxlist.append(muxred)
muxlist.append(muxgreen)
muxlist.append(muxblue)
alllist = iolist + muxlist
# Make sure GPIOs are unexported
for i in alllist:
with open("/sys/class/gpio/unexport", "w") as exportfile:
exportfile.write(i)
# Export
for i in alllist:
with open("/sys/class/gpio/export", "w") as exportfile:
exportfile.write(i)
# I/O Direction
for i in alllist:
with open("/sys/class/gpio/gpio" + str(i) + "/direction", "w+") as dirfile:
dirfile.write("out")
# Muxes
for i in muxlist:
with open("/sys/class/gpio/gpio" + str(i) + "/value", "w+") as muxfile:
muxfile.write("0")
# Turn Off Everything
for i in iolist:
with open("/sys/class/gpio/gpio" + str(i) + "/value", "w+") as iofile:
iofile.write("1")
def turnOn(value):
if (value == 1):
io = iored
elif(value == 2):
io = iogreen
elif(value == 3):
io = ioblue
elif(value == 4):
return
with open("/sys/class/gpio/gpio" + str(io) + "/value", "w+") as iofile:
iofile.write("0")
def turnOff(value):
if (value == 1):
io = iored
elif(value == 2):
io = iogreen
elif(value == 3):
io = ioblue
elif(value == 4):
return
with open("/sys/class/gpio/gpio" + str(io) + "/value", "w+") as iofile:
iofile.write("1")
# Create class object
knn_net = knnn("/opt/neural_training", k)
print("Ready")
while True:
# Read analog value
A0file = open("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r")
measurement = A0file.readline()
A0file.close()
measurement = int(measurement.rstrip())
# Get probabilities for classes (Call KNN)
result = knn_net.classify(measurement)
# Assign Class / Turn on RGB LED accordingly
turnOn(result)
# Print some info to make sure we're still alive
# print 'Measurement:{} Class:{}'.format(measurement,result)
print 'Class:{}'.format(result)
# Noop for a while
time.sleep(2)
# Turn Off RGB LED
turnOff(result)
<file_sep>######################################################
# ****************************************
# Cloud server on Minnowboard Max \
# Using Yocto /
# \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Classify an input obtained from a client over the network
# using the K-Nearest-Neighbors algorithm
import socket
import sys
import mraa
from thread import *
import numpy as np
from StringIO import StringIO
# Specify number of neighbors
k=3
n=0
traindata=''
# LEDs on the Calamari Lure
rl = mraa.Gpio(21)
gl = mraa.Gpio(23)
bl = mraa.Gpio(26)
leds = [rl,gl,bl]
def turnOn(index):
leds[index].write(1)
def turnOff(index):
leds[index].write(0)
def train(trainfile,k):
global traindata
global n
# Read Input Files (Training) and assign variables
trainstr = open(trainfile, "r").read()
traindata = np.genfromtxt(StringIO(trainstr), delimiter = ",")
n = traindata.shape[0]
# Initialize resources
for led in leds:
led.dir(MRAA_GPIO_OUT) # 0 = MRAA_GPIO_OUT see http://iotdk.intel.com/docs/master/mraa/gpio_8h.html#afcfd0cb57b9f605239767c4d18ed7304
def knn(invals):
# Initialize class counters
c1 = 0
c2 = 0
c3 = 0
# Calculate Euclidean Distance for Train Data and sort
eucD = np.empty((n,),dtype='f32,i4')
for i in range(n):
eucD[i][0] = np.linalg.norm(traindata[i,1:3]-invals)
eucD[i][1] = traindata[i,0]
eucD = np.sort(eucD)
# Sum k's for closest samples
for i in range(k):
# Red
if(eucD[i][1] == 1):
c1 += 1
# Green
elif(eucD[i][1] == 2):
c2 += 1
# Blue
elif(eucD[i][1] == 3):
c3 += 1
# Assign a class
classarray = np.array([c1,c2,c3])
return(np.argmax(classarray)+1)
# Function for handling connections. This will be used to create threads
def clientthread(conn,addr):
print 'New thread created for new connection'
# Sending message to connected client
conn.send('Connected\n')
# Infinite loop for every thread
while True:
# Receive data from client
data = conn.recv(1024)
if (data == 'exit'):
break
if not data:
break
# Get probabilities for classes (Call KNN)
# Assume data comes like [1,2]
# Asuume train data was [0,1,2], where class is 0
data_list=data.split(',')
# Avoid network errors
if (len(data_list)!=2):
continue
print 'Received %s' % data
# Make NumPy "understand" the data
try:
data=np.array(map(float,data_list))
except:
print "Error"
sys.exit()
# Run the algorithm
result=knn(data)
reply = 'Classified as %s' % result
print '%s for %s' % (reply,addr)
# Turn on and off an LED for every request successfully handled
turnOn(1)
conn.sendall(reply)
turnOff(1)
conn.close()
# Create socket
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
# Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print "Socket bind complete"
# Start listening on socket, handle at most (10) connections
s.listen(10)
print 'Socket now listening'
# Create class object and train the algorithm
print("Reading Training Values")
knn_net = train("/home/root/train", k)
print("KNN Ready")
# Loop
while True:
# Start a new thread for every new connection
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,addr))
s.close()
<file_sep>######################################################
# ****************************************
# Edison Bluetooth Client Using Python \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
#! /usr/bin/python
import sys
import bluetooth as bt
# Get the MAC Address from cmdline
# This should be checked for format errors #ToDo
server_addr = str(sys.argv[1])
#bd_addr = "AA:BB:CC:DD:EE:FF"
# Connect to server
port = 29
sock=bt.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((server_addr, port))
# Get new value and send it, otherwise exit
line = ""
print "Please input a PWM value:"
while("exit" not in line):
line = sys.stdin.readline()
sock.send(line)
sock.close()
<file_sep>/*
#######################################################
****************************************
Neural Network Color Classification \
Using Yocto & Numpy /
Training Network Using Arduino IDE \
/
<NAME> \
<EMAIL> /
<EMAIL> \
<EMAIL> /
****************************************
######################################################
*/
char category;
char * filename = "/opt/neural_training";
char TrainFlag = '0';
char TestFlag = '0';
void setup() {
// Initialize serial communication at 9600 bits per second:
Serial.begin(9600);
analogReadResolution(12);
}
void loop() {
/* Check for serial command and react accordingly */
if (Serial.available()){
char cmd;
cmd = Serial.read();
if (TrainFlag == '1' || TestFlag == '1') {
if (cmd == 's'){
// Stop Training
TrainFlag = '0';
TestFlag = '0';
Serial.println("Stopping Training");
}
}
else {
switch (cmd){
case 'r':
//Train for Red
Serial.println("Training for Red");
TrainFlag = '1';
category='1';
break;
case 'g':
//Train for Green
Serial.println("Training for Green");
TrainFlag = '1';
category='2';
break;
case 'b':
//Train for Blue
Serial.println("Training for Blue");
TrainFlag = '1';
category='3';
break;
case 'n':
//Train for Nothing
Serial.println("Training for Nothing");
TrainFlag = '1';
category='4';
break;
case 't':
//Testing Measurement
Serial.println("Testing Measurement");
TestFlag = '1';
break;
}
}
}
if (TrainFlag == '1'){
// Read the input on analog pin 0
int sensorValue = analogRead(A0);
String output = String(sensorValue) + "," + category + "\n";
char output_array [50];
output.toCharArray(output_array,sizeof(output));
FILE *fp;
fp = fopen(filename, "a+");
fputs(output_array,fp);
fclose(fp);
// Print out the value
Serial.println(sensorValue);
delay(50); // delay in between reads for stability
}
if (TestFlag == '1'){
// Read the input on analog pin 0
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
}
}
<file_sep><!--
######################################################
# ****************************************
# Nginx + PHP Home Automation Server \
# Using Yocto /
# Reading sensors, using outputs \
# & using a weather API (Yahoo) /
# \
# <NAME> /
# <EMAIL> \
# <EMAIL> /
# <EMAIL> \
# ****************************************
######################################################
Circuit
Galileo Gen 2
LED Pin 2 (GPIO)
Photoresistor ADC 0
Temperature Sensor ADC 1
-->
<html>
<head>
</head>
<body>
<!-- Display query results -->
<script>
var callbackFunction = function(data) {
var loc = data.query.results.channel.location;
var astronomy= data.query.results.channel.astronomy;
var item = data.query.results.channel.item;
document.write("<h2>Clima para: " + loc.city + " " + loc.country +"");
document.write("<p> Sunrise: " + astronomy.sunrise + "</p>");
document.write("<p> Sunset: " + astronomy.sunset + "</p>");
document.write("<p> Temperatura: " + item.condition.temp + " °C </p>");
};
</script>
<!--Request to get weather from Yahoo's RESTful API -->
<script src="https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='zapopan,jal')&format=json&callback=callbackFunction"></script>
<?php
// Turn On/Off LED
function turnOn() {
$gpioval = "/sys/class/gpio/gpio12/value";
file_put_contents($gpioval,"1");
}
function turnOff() {
$gpioval = "/sys/class/gpio/gpio12/value";
file_put_contents($gpioval,"0");
}
// Call function according to POST value
if ($_POST['on'] == 'On') {
turnOn();
}
else{
turnOff();
}
// Variables
$A0file = "/sys/bus/iio/devices/iio:device0/in_voltage0_raw";
$A1file = "/sys/bus/iio/devices/iio:device0/in_voltage1_raw";
$uptimefile = "/proc/uptime";
$gpioval = "/sys/class/gpio/gpio12/value";
// Read Voltage from ADC's
$A0 = file_get_contents($A0file);
$A1 = file_get_contents($A1file);
$ledstate = file_get_contents($gpioval);
// Restore LED value
$gpiodirection = "/sys/class/gpio/gpio12/direction";
$gpiomuxerdir = "/sys/class/gpio/gpio28/direction";
$gpiomuxer = "/sys/class/gpio/gpio28/value";
file_put_contents($gpiodirection,"out");
file_put_contents($gpiomuxerdir,"out");
file_put_contents($gpiomuxer,"0");
file_put_contents($gpioval,$ledstate);
// Get system's uptime
$uptime = file_get_contents($uptimefile);
$uptmarray = explode(" ",$uptime);
// Display results
echo "Iluminacion: " . $A0 . "<p>";
echo "Temperatura Cocina: " . $A1*.1220 . " °C; <p>";
echo "Uptime: " . $uptmarray[0] . " segundos <p>";
echo "Actuador (LED): " . $ledstate . "<p>";
?>
<!-- Forms to use the actuator -->
<form action="index.php" method="post"><input type="submit" name="on" value="On" style="height:50px; width:350px"/></>
<form action="index.php" method="post"><input type="submit" name="on" value="Off" style="height:50px; width:350px"/></>
</body>
</html>
<file_sep>######################################################
# ****************************************
# MRAA Testing PWM & GPIOs Using Python \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Circuit on Galileo Gen 2
# Red: Connected to Pin 2 : Linux GPIO = gpio13 : Mux gpio34 = 0
# Green: Connected to Pin 3 : Linux GPIO = gpio14 : Mux gpio16 = 0
# Blue: Connected to Pin 4 : Linux GPIO = gpio6 : Mux gpio36 = 0
# PWM LED: Connected to Pin 5
import mraa
import time
# Delcare GPIOs
r=mraa.Gpio(2)
g=mraa.Gpio(3)
b=mraa.Gpio(4)
r.dir(mraa.DIR_OUT)
g.dir(mraa.DIR_OUT)
b.dir(mraa.DIR_OUT)
# Delcare PWM
z = mraa.Pwm(5)
z.enable(True)
# Binary counter for Loop
# There are better ways of doing this
i=1
print "Starting Loop"
while(i<8):
if (i==0):
r.write(1)
g.write(1)
b.write(1)
if (i==1):
r.write(1)
g.write(1)
b.write(0)
elif(i==2):
r.write(1)
g.write(0)
b.write(1)
elif(i==3):
r.write(1)
g.write(0)
b.write(0)
elif(i==4):
r.write(0)
g.write(1)
b.write(1)
elif(i==5):
r.write(0)
g.write(1)
b.write(0)
elif(i==6):
r.write(0)
g.write(0)
b.write(1)
elif(i==7):
r.write(0)
g.write(0)
b.write(0)
# Print actual Loop
print "Loop %s" % i
for j in range(50):
# Increment PWM
z.write(j*0.001*i)
# Sleep for the sake of human sight
time.sleep(0.03)
# Print values every now and then
if(j%10==0):
print "Pwm %s" % z.read()
i+=1
# Restart
z.write(0.0)
print "Sleeping"
time.sleep(0.5)
if(i==8):
i=1
<file_sep>#!/usr/bin/python
######################################################
# ****************************************
# Neural Network Color Classification \
# Using Yocto & Numpy /
# Neural Networks Classes \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Classes
# Red = 1
# Green = 2
# Blue = 3
# Black / Nothing = 4
# Imports
from math import *
import numpy as np
from StringIO import StringIO
import random
class knnn:
# Constructor
def __init__(self, trainfile, k):
# Read Input Files (Training) and assign variables
trainstr = open(trainfile, "r").read()
self.traindata = np.genfromtxt(StringIO(trainstr), delimiter = ",")
self.n = self.traindata.shape[0]
self.k = k
def classify(self,value):
reds = 0
greens = 0
blues = 0
blacks = 0
n = self.n
# Calculate Euclidean Distance for Train Data and sort
eucD = np.empty((n,),dtype='f32,i4')
for i in range(n):
eucD[i][0] = np.linalg.norm(self.traindata[i,0]-value)
eucD[i][1] = self.traindata[i,1]
eucD = np.sort(eucD)
# Sum k's for closest samples
for i in range(self.k):
# Red
if(eucD[i][1] == 1):
reds += 1
# Green
elif(eucD[i][1] == 2):
greens += 1
# Blue
elif(eucD[i][1] == 3):
blues += 1
# Black / Nothing
elif(eucD[i][1] == 4):
blacks += 1
# Assign a class
classarray = np.array([reds,greens,blues,blacks])
return(np.argmax(classarray)+1)
class perceptron:
def __init__(self, trainfile, eta = 0.5, threshold = 0):
# Read Input Files (Training) and assign variables
trainstr = open(trainfile, "r").read()
self.traindata = np.genfromtxt(StringIO(trainstr), delimiter = ",")
self.eta = eta
self.thres = threshold
self.rmse = 0
self.n = traindata.shape[0]
# Declare & Initialize Weights
self.numw = traindata.shape[1] + 1
self.w = np.random.rand(self.numw)
# Randomize Data
np.random.shuffle(self.traindata)
# Train Network
self.train(self.traindata)
def epoch(self):
sse = 0
for i in range(self.n):
# Green is food
if(self.traindata[i][0] == 3):
desired = 1
else:
desired = -1
output = self.output(self.traindata[i])
error = desired - output
self.adjust_weights(error,traindata[i])
sse += math.pow(error,2)
rmse = math.sqrt(sse/self.n)
def output(self, measurement):
v = 0
# Multiply Input by Weight
for i in range(self.numw - 1):
v += self.w[i]*measurement[i+1]
# Bias
v += self.w[i+1]
# Map output for perceptron
if(v>0):
return 1
else:
return -1
def adjust_weights(self, error, measurement):
for i in range(self.numw - 1):
self.w[i] += self.eta*error*measurement[i+1]
self.w[i+1] += self.eta*error
def classify(self, measurement):
# Input for train had a desired value so create a dummy one
dummy = np.empty(self.numw) + 1
dummy[0] = 0
for i in range(self.numw):
dummy[i+1] = measurement[i]
return self.output(dummy)
def train(self):
rmse = self.rmse
while (rmse > self.thres):
rmse = self.epoch()
<file_sep>######################################################
# ****************************************
# IoT Client on Galileo \
# Using Yocto & Machine Learning /
# \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Python Imports
import socket
import sys
from time import sleep
import random
import pyupm_i2clcd as lcd
import mraa
# Set up network
server='192.168.1.100'
port=8888
# Get Client IP Address
try:
ip=[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
except socket.error as msg:
print msg
# Set up MRAA
btn=mraa.Gpio(5)
btn.dir(mraa.DIR_IN)
temp=mraa.Aio(1)
light=mraa.Aio(0)
# Set up LCD Screen using both upm and MRAA
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
x = mraa.I2c(0)
x.address(0x62)
# Init LCD using MRAA
x.writeReg(0, 0)
x.writeReg(1, 0)
# Send RGB color data
x.writeReg(0x08, 0xAA)
# Red
x.writeReg(0x04, 159)
# Green
x.writeReg(0x03, 0)
# Blue
x.writeReg(0x02, 255)
# Use UPM to manipulate LCD
myLcd.setCursor(0,0)
myLcd.write('%s' % ip)
myLcd.setCursor(1,0)
myLcd.write('Waiting for server')
scrollFlag = False
scrollCount = 0
# Wait for button
while btn.read()==0:
myLcd.setCursor(0,0)
myLcd.write('%s' % ip)
myLcd.setCursor(1,0)
myLcd.write('Waiting for server')
myLcd.scroll(scrollFlag)
sleep(1)
scrollCount+=1
if(scrollCount==4):
scrollFlag = not scrollFlag
scrollCount=0
# Create socket and connect to server
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
s.connect((server , port))
print 'Socket Connected to ' + server
# Loop
while True:
sleep(1)
lightval=light.read()
tempval=temp.read()
message = '%s,%s' % (lightval,tempval)
try :
# Send the whole string
s.sendall(message)
except socket.error:
# Send failed
print 'Send failed'
sys.exit()
# Server replied
reply = s.recv(4096)
print reply
# Write result obtained from server and values read from sensors
myLcd.clear()
myLcd.setCursor(0,0)
myLcd.write(message)
myLcd.setCursor(1,0)
myLcd.write(reply)
<file_sep>######################################################
# ****************************************
# Testing GPIOS on Minnowboard Max \
# Using Yocto /
# \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
# Minnowboard MAX with Calamari LURE
# Good read:
# http://elinux.org/Calamari_Lure
# LEDs
# GPIOS changed on Linux 3.18 + 256
# R = GPIO_S5_0 : MRAA 21 : Linux Sysfs GPIO = gpio338
# G = GPIO_S5_0 : MRAA 23 : Linux Sysfs GPIO = gpio339
# B = ILB_8254_SPKR : MRAA 26 : Linux Sysfs GPIO = gpio464
# Assumes root permissions & proper kernel modules loaded
# Export GPIOS on SysFS
echo "338" > /sys/class/gpio/export
echo "339" > /sys/class/gpio/export
echo "464" > /sys/class/gpio/export
# Set GPIOS as outputs
echo "out" > /sys/class/gpio/gpio338/direction
echo "out" > /sys/class/gpio/gpio339/direction
echo "out" > /sys/class/gpio/gpio464/direction
# Turn on specific color
echo 1 > /sys/class/gpio/gpio338/value
#echo 1 > /sys/class/gpio/gpio339/value
#echo 1 > /sys/class/gpio/gpio464/value
# Turn off specific color
echo 0 > /sys/class/gpio/gpio338/value
#echo 0 > /sys/class/gpio/gpio339/value
#echo 0 > /sys/class/gpio/gpio464/value
<file_sep># yocto-examples
Materials related to a workshop to build an embedded linux distribution using the Yocto Project
<file_sep>######################################################
# ****************************************
# Bluetooth Server on Edison Using Python \
# /
# <NAME> \
# <EMAIL> /
# <EMAIL> \
# <EMAIL> /
# ****************************************
######################################################
#! /usr/bin/python
import bluetooth as bt
import mraa
# Set up Bluetooth Server
server=bt.BluetoothSocket(bluetooth.RFCOMM)
port = 29
server.bind(("",port))
# Start Listening for New Connections (1)
# Should potentially use several tasks #ToDo
server.listen(1)
print "Listening for new connections on port %s" % port
client,addr = server.accept()
print "Accepted connection from %s " % addr
print "Waiting for new PWM value..."
# Set up MRAA
pwm_pin = mraa.Pwm(9)
pwm_pin.enable(True)
data=0
# Wait for Data (Loop)
while(data!="exit"):
data = client.recv(1024)
print "[Debug] Received [%s]" % data
try:
value = float(data)
except ValueError:
break
# Use received value for PWM
pwm_pin.write(float(data))
# Close Socket
print "Server is exiting..."
client.close()
server.close()
|
d18ecd57884a62ac3d9a32a28a2f3664cbb7cf10
|
[
"Markdown",
"Python",
"PHP",
"C",
"C++",
"Shell"
] | 13
|
Python
|
aehs29/yocto-workshop
|
237ec6dbdb206b9c42d70bb925500dd69b863fa9
|
c93a10e0c72227129a9fc3bd3070d5515892d74f
|
refs/heads/main
|
<repo_name>GNVageesh/spaceremoverjs<file_sep>/README.md
# spaceremoverjs

# Installation
`npm install spaceremoverjs`
# Usage
```js
const srjs = require("spaceremoverjs");
srjs("This is a string with spaces");
```
`Output => Thisisastringwithspaces`
<file_sep>/index.js
module.exports = function srjs(string) {
if (typeof string !== "string")
throw new TypeError("srJs require a string as an input");
return string.replace(/\s/g, "");
};
|
4d2b3868e27c4f7f493fef0772c262c4d24ab063
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
GNVageesh/spaceremoverjs
|
2ec0cf320cfe03cf03d6cddd3501d5792fb13969
|
78a48d3c2e2b37e2d6f605db8f0f555a291c9f0b
|
refs/heads/master
|
<repo_name>jjsalinas/estadisticas_liga<file_sep>/graficos_liga.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 10:33:37 2016
@author: jjsalinas
Script para generar las gráficas asociadas a las estadisticas y datos contenidos en la clase info_liga
"""
import recoleccion_info
import matplotlib.pyplot as plt
import numpy as np
import os
#******************************************************************************************************#
#************************************** CLASE GRAFICOS_LIGA **************************************** #
#******************************************************************************************************#
"""
CLASE graficos_liga
@info_liga : Objeto de la clase info_liga para almacenar todos los datos
@graficos_ratios : map tipo {equipo: matplotlib fig} : grafico continuo con los ratios de goles anotados-encajados en cada intervalo de 10 min
@graficos_resultados : map tipo {equipo: matplotlib fig} : grafico de barras con numero de partidos ganados, empatados, perdidos
@graficos_primero: map tipo {equipo: matplotlib fig} : grafico de barras con % de partidos (como local-visitante) en los que el equipo anota primero
@vmax: variable interna - el valor maximo a representar en graficos_resultados
"""
class graficos_liga:
#Constructor que toma un objeto info_liga basico (jornada ya establecido), procesa todo la info para ese objeto y establece el valor de vmax
def __init__(self, info_liga_obj):
self.info_liga=info_liga_obj
self.info_liga.procesar_todo()
self.graficos_ratios={}
self.graficos_resultados={}
self.graficos_primero={}
vmax=0
clasif=self.info_liga.get_clasif()
for i in clasif:
if int(clasif[i][3])>vmax:
vmax=int(clasif[i][3])
if int(clasif[i][4])>vmax:
vmax=int(clasif[i][4])
if int(clasif[i][5])>vmax:
vmax=int(clasif[i][5])
self.vmax=vmax
#Metodo __str__ llamado cuando se realice una llamada a imprimir por pantalla a la variable con la instancia de la clase
def __str__(self):
mensaje="Instancia de GRAFICAS para la jornada"+ str(self.info_liga.get_jornada())
return mensaje
#******************************************************************************************************#
def get_instancia_info_liga(self):
return self.info_liga
#******************************************************************************************************#
def get_graficosRatios(self):
return self.graficos_ratios
#******************************************************************************************************#
#Metodo que para cada equipo genera y guarda el archivo de imagen de su grafica de ratios de goles anotados en intervalos de 10 min
def set_graficos_ratios_todos_guarda(self, directorio):
if not os.path.isdir(directorio):
os.makedirs(directorio)
r=self.info_liga.get_ratios()
#t=self.info_liga.get_timing()
maxi=self.info_liga.get_maximoR()
mini=self.info_liga.get_minimoR()
tiempos=['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '81-90']
for i in r:
aux=r[i][0:9]
if len(aux)==9:
x=range(9)
#plt.plot(x, aux, 'bs') #Cuadros Azules
plt.plot(x, aux, color='black') #Linea continua negra
plt.grid(True)
plt.title(i)
plt.ylabel("Ratio")
plt.xlabel("Tramo")
plt.xticks(x, tiempos, rotation=15)
plt.ylim(mini, maxi)
"""
#Flecha Señalando el máximo
plt.annotate(max(aux), xy=(aux.index(max(aux)), max(aux)), xytext=(aux.index(max(aux))+1, max(aux)+0.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
"""
#plt.show()
if 'Bilbao' in i:
plt.savefig(directorio+"/ratio"+i[1:-1])
else:
plt.savefig(directorio+"/ratio"+i[:-1])
self.graficos_ratios[i]=plt
plt.clf()
#******************************************************************************************************#
"""
#Metodo que para cada equipo genera y guarda en la instancia su grafica de resultados
# ahora mismo solo las muestra
def set_graficos_resultados_partidos_todos(self):
for i in self.info_liga.get_equipos():
valores=self.info_liga.get_clasif()[i][3:6]
assert(len(valores)==3)
ind=np.arange(3)
r=[int(i) for i in valores]
t=['Victorias', 'Empates', 'Derrotas']
plt.bar(ind, r, 0.45, color='g')
plt.title("Resultados Partidos"+i)
plt.xticks(ind, t, rotation=-45)
plt.ylim(0, self.vmax)
plt.xlim(-0.1, 2.5)
#aux=plt.figure()
#plt.show()
self.graficos_resultados[i]=plt
#plt.close()
plt.clf()
"""
#******************************************************************************************************#
#Metodo que para cada equipo genera y guarda el archivo de imagen su grafica de resultados en el directorio dado
def set_graficos_resultados_todos_guarda(self, directorio):
if not os.path.isdir(directorio):
os.makedirs(directorio)
for i in self.info_liga.get_equipos():
valores=self.info_liga.get_clasif()[i][3:6]
assert(len(valores)==3)
ind=np.arange(3)
r=[int(i) for i in valores]
t=['Victorias', 'Empates', 'Derrotas']
plt.bar(ind, r, 0.45, color='g')
plt.title("Resultados Partidos"+i)
plt.xticks(ind, t, rotation=-45)
plt.ylim(0, self.vmax)
plt.xlim(-0.1, 2.5)
#aux=plt.figure()
plt.savefig(directorio+"/resultados"+i[:-2])
#self.graficos_resultados[i]=plt
#plt.close()
plt.clf()
#******************************************************************************************************#
"""
#Metodo que para un equipo genera y guarda en la instancia su grafica de resultados
def set_grafico_resultados_equipo(self, equipo):
valores=self.info_liga.get_clasif()[equipo][3:6]
assert(len(valores)==3)
ind=np.arange(3)
r=[int(i) for i in valores]
t=['Victorias', 'Empates', 'Derrotas']
plt.bar(ind, r, 0.45, color='g')
plt.title("Resultados Partidos"+equipo)
plt.xticks(ind, t, rotation=-45)
plt.ylim(0, self.vmax)
plt.xlim(-0.1, 2.5)
self.graficos_resultados[equipo]=plt
#plt.close()
plt.clf()
"""
#******************************************************************************************************#
#Metodo que para cada equipo genera y guarda el archivo de imagen de su grafica de porcentajes de partidos en que marca-encaja primero como local y visitante
def set_grafico_marca_encaja_primero_todos_guarda(self, directorio):
if not os.path.isdir(directorio):
os.makedirs(directorio)
c=self.info_liga.get_casa()
f=self.info_liga.get_fuera()
for i in self.info_liga.get_equipos():
valores=[int(c[i[1:-1]][0][3][:-2]), int(c[i[1:-1]][0][4][:-2]), int(f[i[1:-1]][3][:-2]), int(f[i[1:-1]][4][:-2])]
assert(len(valores)==4)
ind=np.arange(4)
r=[int(i) for i in valores]
t=['Marca 1º\n como Local', 'Encaja 1º\n como Local', 'Marca 1º\n como Visitante', 'Encaja 1º\n como Visitante']
plt.bar(ind[0:2], r[0:2], 0.35, color='y')
plt.bar(ind[2:4], r[2:4], 0.35, color='orange')
plt.xticks(ind, t, rotation=0)
plt.grid(True)
plt.title("Marca/Encaja Primero "+i[:-2])
plt.ylabel("% Partidos")
plt.ylim(0, 100)
plt.xlim(-0.2, 3.5)
plt.savefig(directorio+"/marcaencaja"+i[:-2])
#self.graficos_resultados[i]=plt
plt.clf()
#******************************************************************************************************#
#** FIN CLASE GRAFICOS_LIGA **#
#******************************************************************************************************#
#** main para testear **#
if __name__ == "__main__":
j=21
il=recoleccion_info.info_liga(j)
graficas=graficos_liga(il)
"""
dire="test"
graficas.set_graficos_ratios_todos_guarda(dire)
graficas.set_graficos_resultados_todos_guarda(dire)
graficas.set_grafico_marca_encaja_primero_todos_guarda(dire)
"""
#print(graficas.get_instancia_info_liga().get_fuera())
#print(graficas.info_liga.get_fuera())<file_sep>/README.md
# Estadísticas Liga BBVA
Script python (python 3) para visualizar estadísticas de fútbol de la primera división española.
A partir de los datos existentes en los archivos .txt se obtienen distintas estadísticas via python.
La información se vuelca directamente a una web con nombre jornadaX.html
#####Toda la información se ha obtenido de la web:
> http://www.soccerstats.com/
##Para cada equipo:
- Información clasificación actual en liga.
- Goles a favor/en contra (general, como local y como visitante)
- Promedio goles por partido total/como local/como visitante.
- Promedio partidos con más de 0.5 goles, más de 1.5, más de 2.5, más de 3.5 y más de 4.5 en general/como local/como visitante.
- Ratio goles marcados/encajados para cada intervalo de 10 minutos.
- Porcentaje partidos anota primero como Local y como Visitante.
- Partidos Ganados - Empatados - Perdidos según Anota o Encaja primero.
- Puntos por partido.
- Partidos con mas de 2.5 goles (a favor + en contra).
- Partidos sin encajar.
- Partidos sin marcar.
- Partidos ambos equipos marcan.
- Porcentaje puntos ganados en casa.
- Porcentaje puntos ganadas fuera.
- Porcentaje goles a favor/en contra en casa.
- Porcentaje goles a favor/en contra fuera.
##Volcado a página HTML
En la web resultante se muestran el conjunto de los datos para cada equipo actualizados al cierre de la jornada indicada.
Para la jornada siguiente se muestra una comparación directa entre los equipos que jugarán entre si.
##Ejecución
Para obtener la info de la jornada actual de repositorio basta con ejecutar el script volcado_info:
> python3 volcado_info.py
<file_sep>/volcado_info.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 10:38:47 2016
@author: jjsalinas
Script para volcar en archivos html la información contenida en una instancia de la clase info_liga
"""
import recoleccion_info
import graficos_liga
import os
import sys
#******************************************************************************************************#
#************************************* CLASE VOLCADO INFO ****************************************** #
#******************************************************************************************************#
"""
CLASE volcado_info
@graficas: objeto de la clase grafico_liga para generar los archivos de imagen de las distintas graficas de datos
@index: string con el nombre del fichero html que sera index para la info de la jornada de la instancia
@optimos: string con el nombre del fichero html que contendra la info de los emparejamientos optimos de la siguiente jornada
@dir_imgs: string con el directorio en el que se almacenaran las imagenes de las graficas
"""
class volcado_info:
#Constructor que toma un objeto de clase info_liga basico (solo contiene info en el campo jornada)
#Se establece como salida estandar el fichero que seria index para la info de jornada en instancia_info_liga
def __init__(self, instancia_info_liga):
self.graficas=graficos_liga.graficos_liga(instancia_info_liga)
self.index="jornada"+str(instancia_info_liga.get_jornada())+".html"
self.optimos="optimosj"+str(instancia_info_liga.get_jornada())+".html"
self.dir_imgs="imgs"
try:
os.remove(self.index)
#os.remove(self.optimos)
except:
print("No se puede borrar index")
self.fsalida=open(self.index, 'a+')
sys.stdout=self.fsalida
#******************************************************************************************************#
#Metodo que genera todos los archivos de imagen de las graficas en un directorio dado
def genera_graficas(self):
self.graficas.set_graficos_ratios_todos_guarda(self.dir_imgs)
self.graficas.set_graficos_resultados_todos_guarda(self.dir_imgs)
self.graficas.set_grafico_marca_encaja_primero_todos_guarda(self.dir_imgs)
#******************************************************************************************************#
#Metodo que genera la lineas de estilo tocadas manualmente
def estilo_manual(self):
print("<STYLE type=text/css>")
#print("h2{ font-family: calibri; font-weight: bold; }")
#print("h3{ font-family: calibri; font-weight: bold; }")
#print("p{ font-family: consolas; }")
#print("footer{ font-family: calibri; border: solid black 2px; padding: 5px; }")
print(".pstrong{ font-weight: bold; }")
print(".pgrande{ font-size:18; }")
print(".lider{ color: blue; font-weight: bold; font-size:18; }")
print(".champions{ color: grey; font-weight: bold; font-size:18; }")
print(".uefa{ color: orange; font-weight: bold; font-size:18; }")
print(".descenso{ color: red; font-weight: bold; font-size:18; }")
print(".img-grafica{ display: inline; float: right; -webkit-column-span: in-column; -moz-column-span: in-column;} ")
print(".img-ratios{ display: inline; float: left; -webkit-column-span: in-column; -moz-column-span: in-column;} ")
print(".navbar{ background: black; text-align:center; padding: 3 0;}")
print(".link-github{ color: #363636; font-weight: bold; font-size:14; }")
print(".link-inicio{ color: #363636; font-weight: bold; }")
#print(".row{ background-color:#fed136; border:solid 2px #fed136; }")
#print(".caja { border: 1px solid background: #fed136 }")
print("</STYLE>")
#******************************************************************************************************#
#Metodo que vuelca en el archivo la deficion del estilo
def estilo(self):
print("<link href='css/bootstrap.min.css' rel='stylesheet'>")
#print("<link href='css/main.css' rel='stylesheet'>")
print("<link href='css/agency.css' rel='stylesheet'>")
print("<link href='css/backtotop.css' rel='stylesheet'>")
#print("<link href='css/font-awesome.css' rel='stylesheet'>")
self.estilo_manual()
#******************************************************************************************************#
#Metodo que vuelca en el archivo la deficion del estilo para los html de enfrentamientos
def estilo_partidos(self):
print("<link href='../css/bootstrap.min.css' rel='stylesheet'>")
#print("<link href='../css/main.css' rel='stylesheet'>")
print("<link href='../css/agency.css' rel='stylesheet'>")
self.estilo_manual()
#******************************************************************************************************#
#Metodo que vuelva en el archivo la cabecera al completo
def cabecera(self):
print("<html>")
print("<head>")
print("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>")
print("<title>Información Jornada "+ str(self.graficas.get_instancia_info_liga().get_jornada())+"</title>")
self.estilo()
print("</head>")
#******************************************************************************************************#
def back_to_top(self):
print("<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js'></script> <script>$(document).ready(function(){ // hide #back-top first $('#back-top').hide(); // fade in #back-top $(function () { $(window).scroll(function () { if ($(this).scrollTop() > 100) { $('#back-top').fadeIn(); } else { $('#back-top').fadeOut(); } }); // scroll body to 0px on click $('#back-top a').click(function () { $('body,html').animate({ scrollTop: 0 }, 800); return false; }); });});</script>")
#******************************************************************************************************#
#Metodo que vuelva la info de un equipo dado
def info_equipo(self, e):
if e in self.graficas.get_instancia_info_liga().get_equipos():
#print("<p>#*****************************************************************************#</p>")
print("<div class='container' id='%s'>" % e[1:-2].replace(' ', ''))
print("<div class='row'>")
#print("<div class='col-lg-12'>")
print("<br>")
print("<h2 class='section-heading'>")
print(e, ":")
print("</h2>")
print("</div>")
#print("<a href=%s>Inicio</a>" % self.index)
#Ratios y resultados
#Grafica de ratios
print("<div class='row'>")
g=self.dir_imgs+"/ratio"+e[:-2]+".png"
print("<img src='%s' class='img-ratios img-responsive' width=600 />" % g)
#print("</div>")
#print("<div class='col-md-4'>")
#Grafica de resultados
g=self.dir_imgs+"/resultados"+e[:-2]+".png"
print("<img src='%s' class='img-grafica img-responsive' width=450/>" % g)
c=self.graficas.get_instancia_info_liga().get_clasif()[e]
posicion=int(c[0][:])
print("</div>")
print("<div class='row'>")
print("<br><p class='pgrande'>Ha jugado ", c[1], "partidos; ", c[3], "victorias, ", c[4], "empates,", c[5], "derrotas; => ", c[2], "puntos.</p>")
#Posicion | Color segun que posicion
if posicion==1:
print("<p class='posicion lider'> \tPosicion: ", c[0], " .Lider</p>")
elif posicion==18 or posicion==19 or posicion==20:
print("<p class='posicion descenso'> Posicion: ", c[0], " .En Descenso.</p>")
elif posicion ==2 or posicion==3 or posicion==4:
print("<p class='posicion champions'> \tPosicion: ", c[0], " .Chempions</p>")
elif posicion==5 or posicion==6:
print("<p class='posicion uefa'> \tPosicion: ", c[0], " .UEFA</p>")
else:
print("<p class='posicion pgrande'> \tPosicion: ", c[0], "</p>")
#print("<br>")
print("<p class='pgrande'>LLeva: ", c[6], "goles a favor. |", c[7], "goles en contra. | ", c[8],"</p>")
print("</div>")
print("<br>")
#Goles Total
gall=self.graficas.get_instancia_info_liga().get_golesTotal()[e[1:]]
print("<div class='col-md-4'>") # Para posicionamiento en varias columnas!
print("<h3>GOLES:</h3>")
#print("<br>")
print("<p class='pstrong' >Media goles por partido: ", gall[1], "</p>")
#print("<br>")
print("<p>Partidos con: <br>más de <strong>0.5</strong> goles: ", gall[2], "<br>más de <strong>1.5</strong>: ", gall[3], "<br>más de <strong>2.5</strong>: ", gall[4], "<br>más de <strong>3.5</strong>: ", gall[5], "<br>más de <strong>4.5</strong>: ", gall[6], "</p>")
#Goles e info Casa
gcasa=self.graficas.get_instancia_info_liga().get_golesLocal()[e[1:]]
pcasa=self.graficas.get_instancia_info_liga().get_partidosCasa()[e]
print("<p class='pstrong'>Como LOCAL: </p><p>", gcasa[0], "partidos: ", pcasa[0], "victorias, ", pcasa[1], " empates, ", pcasa[2], "derrotas. <br>", pcasa[3], "goles a favor. |", pcasa[4], "goles en contra.</p>" )
#print("<br>")
print("<p>Media goles por partido en casa: ", gcasa[1], "</p>")
#print("<br>")
print("<p>En casa. Partidos con: <br>más de <strong>0.5</strong> goles: ", gcasa[2], "<br>más de <strong>1.5</strong>: ", gcasa[3], "<br>más de <strong>2.5</strong>: ", gcasa[4], "<br>más de <strong>3.5</strong>: ", gcasa[5], "<br>más de <strong>4.5</strong>: ", gcasa[6], "</p>")
#Goles e info fuera
gfuera=self.graficas.get_instancia_info_liga().get_golesVisitante()[e[1:]]
pfuera=self.graficas.get_instancia_info_liga().get_partidosFuera()[e]
print("<p class='pstrong'>Como VISITANTE: </p><p>", gfuera[0], "partidos: ",pfuera[0], "victorias, ", pfuera[1], " empates, ", pfuera[2], "derrotas. ", pfuera[3], "goles a favor. |", pfuera[4], "goles en contra.</p>" )
#print("<br>")
print("<p>Media goles por partido en fuera: ", gfuera[1], "</p>")
#print("<br>")
print("<p>Fuera. Partidos con: <br>más de <strong>0.5</strong> goles: ", gfuera[2], "<br>más de <strong>1.5</strong>: ", gfuera[3], "<br>más de <strong>2.5</strong>: ", gfuera[4], "<br>más de <strong>3.5</strong>: ", gfuera[5], "<br>más de <strong>4.5</strong>: ", gfuera[6], "</p>")
print("</div>")
print("<div class='col-md-4'>")
#Resultados casa+fuera
casa=self.graficas.get_instancia_info_liga().get_casa()[e[1:-1]]
fuera=self.graficas.get_instancia_info_liga().get_fuera()[e[1:-1]]
print("<h3>Partidos Marca - Encaja primero</h3>")
#Grafica de Marca-Encaja primero
g=self.dir_imgs+"/marcaencaja"+e[:-2]+".png"
print("<img src='%s' width=400/>" % g)
print("<p>")
print("Ha marcado primero como LOCAL en", casa[0][0], "partidos; un ", casa[0][3], "<br>")
print("Ha encajado primero como LOCAL en", casa[0][2], "partidos; un ", casa[0][4], "</p>")
print("<p>Ha marcado primero como VISITANTE en", fuera[0], "partidos; un ", fuera[3], "<br>")
print("Ha encajado primero como VISITANTE en", fuera[2], "partidos; un ", fuera[4], "</p>")
#Anotacion
mp=self.graficas.get_instancia_info_liga().get_marcaPrimero()[e[1:-1]]
ep=self.graficas.get_instancia_info_liga().get_encajaPrimero()[e[1:-1]]
n_marca=int(mp[0])+int(mp[1])+int(mp[2])
n_encaja=int(ep[0])+int(ep[1])+int(ep[2])
print("<p class='pstrong'>Marca primero:</p>")
if n_marca!=0:
print("<p>De los", n_marca , "partidos en que ha marcado primero <br>Ha ganado:",mp[0],"(", (int(mp[0])/n_marca)*100,"%) ha empatado:", mp[1], "(", (int(mp[1])/n_marca)*100,"%) y ha perdido:", mp[2],"(", (int(mp[2])/n_marca)*100,"%)</p>" )
else:
print("<p>De los", n_marca , "partidos en que ha marcado primero <br>Ha ganado:",mp[0]," ha empatado:", mp[1]," y ha perdido:", mp[2], "</p>")
#print("<br>")
print("<p class='pstrong'>Encaja primero:</p>")
if n_encaja!=0:
print("<p>De los", n_encaja ,"partidos en que ha encajado primero <br>Ha ganado:",ep[0],"(", (int(ep[0])/n_encaja)*100,"%) ha empatado:", ep[1], "(", (int(ep[1])/n_encaja)*100,"%) y ha perdido:", ep[2],"(", (int(ep[2])/n_encaja)*100,"%)</p>" )
else:
print("<p>De los", n_encaja ,"partidos en que ha encajado primero <br>Ha ganado:",ep[0]," ha empatado:", ep[1], " y ha perdido:", ep[2], "</p>")
#print("<br>")
#print("<p>Ha tenido <strong>",self.graficas.get_instancia_info_liga().get_empates0()[e[:-1]] , "partidos con 0-0.</strong></p>")
print("</div>")
print("<div class='col-md-4'>")
#Cantidad de goles por partido
#Info partidos no esta siendo obtenido ahora mismo
"""
ip=self.graficas.get_instancia_info_liga().get_infopartidos()[e]
print("<h3>Ratio de puntos - goles</h3>")
print("<p>")
print("Puntos por partido: <strong>", ip[0], "</strong><br>")
print("Partidos con mas de <strong>2.5</strong> goles(a favor+en contra): <strong>", ip[1], "</strong><br>")
print("Partidos <strong>sin encajar: ", ip[2], "</strong><br>")
print("Partidos <strong>sin marcar: ", ip[3], "</strong><br>")
print("Partidos <strong>ambos equipos marcan: ", ip[4], "</strong>")
print("</p>")
"""
partidoscasa=self.graficas.get_instancia_info_liga().get_partidosCasa()[e]
partidosfuera=self.graficas.get_instancia_info_liga().get_partidosFuera()[e]
#Porcentaje puntos casa-fuera
ppcasa=(int(partidoscasa[0])*3+int(partidoscasa[1]))/int(c[2])
ppfuera=(int(partidosfuera[0])*3+int(partidosfuera[1]))/int(c[2])
print("<p>% puntos ganados en Casa: <strong>", ppcasa*100, '%</strong></p>')
#print("<br>")
print("<p>% puntos ganados Fuera: <strong>", ppfuera*100, '%</strong></p>')
#Porcentajes goles a favor-en contra en casa-fuera
pgfavorcasa=int(partidoscasa[3])/int(c[6])
pgfavorfuera=int(partidosfuera[3])/int(c[6])
pgcontracasa=int(partidoscasa[4])/int(c[7])
pgcontrafuera=int(partidosfuera[4])/int(c[7])
print("<p>")
print("% goles a favor como local:<strong>", pgfavorcasa*100, '%</strong> <br>| ', partidoscasa[3], "de", c[6], " anotados<br>")
#print("<br>")
print("% goles en contra como local:<strong>", pgcontracasa*100, '%</strong> <br>| ', partidoscasa[4], "de", c[7], " encajados<br>")
#print("<br>")
print("% goles a favor como visitante:<strong>", pgfavorfuera*100, '%</strong> <br>| ', partidosfuera[3], "de", c[6], " anotados<br>")
#print("<br>")
print("% goles en contra como visitante:<strong>", pgcontrafuera*100, '%</strong> <br>| ', partidosfuera[4], "de", c[7], " encajados<br>")
print("</p>")
print("</div>")
#print("</div>")
print("</div>")
#******************************************************************************************************#
# Metodo que crea el html con la info dedicada a un partido de la siguiente jornada
def info_enfrentamiento(self, partido):
loc=partido[0]
vis=partido[1]
#self.cabecera()
print("<html>")
print("<head>")
print("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>")
print("<title>Jorná ", self.graficas.get_instancia_info_liga().get_jornada(), ": ", loc, "-", vis, "</title>")
self.estilo_partidos()
print("</head>")
print("<body>")
print("<div class='container'>")
#print("<a href=''../%s'>Inicio</a>" % (self.index))
#print(" <script src='../css/backtotop.js'></script>")
#print("<i><a href='javascript:' id='return-to-top'><i class='icon-chevron-up'></i></a>")
print("<div class='intro-text'>")
print("<h2 class='section-heading'>Info siguiente jornada partido ", loc, "-", vis, ":</h2>")
print("</div>")
#Nav con los nombres de cada equipo. Pinchando en un equipo te lleva a su info
print("<nav class='navbar navbar-default navbar-fixed-top'>")
for e in sorted(self.graficas.get_instancia_info_liga().get_equipos()):
print("<a class='page-scroll' href=%s#%s>%s</a>" % ('../'+self.index, e[1:-2].replace(' ', ''), e) )
print(" | ")
print("</nav>")
#Barra con los enlaces a los partidos de la proxima jornada
print("<h5><a class='link-inicio' href='../%s'>Inicio</a></h5>" % (str(self.index)))
print("<h4>Partidos siguiente jornada:</h4>")
for p in self.graficas.get_instancia_info_liga().get_siguiente_jornada():
enlace=p[0][1:-1].replace(' ', '')+"-"+p[1][1:-1].replace(' ', '')+".html"
print("<span><a class='navbar navbar-default' href=%s >%s</a><span>" % (str(enlace), p[0]+"-"+p[1]))
#print(" | ")
print("</nav>")
#print("<div class='container'><h1>Información partido", loc, "-", vis, ":</h1></div>")
#** VOLCADO DE LA INFO DEL PARTIDO CONCRETO **#
#AQUI ES LA PARTE A MODIFICAR
print("<div class='row'>")
print("<h2 class='section-heading'>")
print(loc, "-", vis, " : Jornada ", str(self.graficas.get_instancia_info_liga().get_jornada()+1))
print("</h2>")
print("</div>")
#Grafica de ratios
print("<div class='row'>")
gl='../'+self.dir_imgs+"/ratio"+loc[:-1]+".png"
gv='../'+self.dir_imgs+"/ratio"+vis[:-1]+".png"
print("<img src='%s' class='img-ratios img-responsive' width=550 />" % gl)
print("<img src='%s' class='img-ratios img-responsive' width=550 />" % gv)
print("</div>")
#Grafica de resultados
print("<br><br>")
print("<div class='row'>")
gl='../'+self.dir_imgs+"/resultados"+loc[:-1]+".png"
gv='../'+self.dir_imgs+"/resultados"+vis[:-1]+".png"
print("<img src='%s' class='img-ratios img-responsive' width=400/>" % gl)
print("<img src='%s' class='img-ratios img-responsive' width=400/>" % gv)
print("</div>")
#GOLES
#Goles e info Casa
loc2=loc
if loc[0]!=' ':
loc2=' '+loc
gcasaL=self.graficas.get_instancia_info_liga().get_golesLocal()[loc2[1:]+' ']
gcasaV=self.graficas.get_instancia_info_liga().get_golesLocal()[vis[1:]+' ']
pcasaL=self.graficas.get_instancia_info_liga().get_partidosCasa()[loc[:]+' ']
pcasaV=self.graficas.get_instancia_info_liga().get_partidosCasa()[vis[:]+' ']
#print("<div class='row'>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (loc))
print("<p class='pstrong'>Como LOCAL: </p><p>", gcasaL[0], "partidos: ", pcasaL[0], "victorias, ", pcasaL[1], " empates, ", pcasaL[2], "derrotas. <br>", pcasaL[3], "goles a favor. |", pcasaL[4], "goles en contra.</p>" )
print("<p>Media goles por partido en casa: ", gcasaL[1], "</p>")
print("<p>En casa. Partidos con: <br>más de <strong>0.5</strong> goles: ", gcasaL[2], "<br>más de <strong>1.5</strong>: ", gcasaL[3], "<br>más de <strong>2.5</strong>: ", gcasaL[4], "<br>más de <strong>3.5</strong>: ", gcasaL[5], "<br>más de <strong>4.5</strong>: ", gcasaL[6], "</p>")
print("</div>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (vis))
print("<p class='pstrong'>Como LOCAL: </p><p>", gcasaV[0], "partidos: ", pcasaV[0], "victorias, ", pcasaV[1], " empates, ", pcasaV[2], "derrotas. <br>", pcasaV[3], "goles a favor. |", pcasaV[4], "goles en contra.</p>" )
print("<p>Media goles por partido en casa: ", gcasaV[1], "</p>")
print("<p>En casa. Partidos con: <br>más de <strong>0.5</strong> goles: ", gcasaV[2], "<br>más de <strong>1.5</strong>: ", gcasaV[3], "<br>más de <strong>2.5</strong>: ", gcasaV[4], "<br>más de <strong>3.5</strong>: ", gcasaV[5], "<br>más de <strong>4.5</strong>: ", gcasaV[6], "</p>")
print("</div>")
#print("</div>")
#Goles e info fuera
gfueraL=self.graficas.get_instancia_info_liga().get_golesVisitante()[loc[1:]+' ']
gfueraV=self.graficas.get_instancia_info_liga().get_golesVisitante()[vis[1:]+' ']
pfueraL=self.graficas.get_instancia_info_liga().get_partidosFuera()[loc[:]+' ']
pfueraV=self.graficas.get_instancia_info_liga().get_partidosFuera()[vis[:]+' ']
#print("<div class='row'>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (loc))
print("<p class='pstrong'>Como VISITANTE: </p><p>", gfueraL[0], "partidos: ",pfueraL[0], "victorias, ", pfueraL[1], " empates, ", pfueraL[2], "derrotas. ", pfueraL[3], "goles a favor. |", pfueraL[4], "goles en contra.</p>" )
print("<p>Media goles por partido en fuera: ", gfueraL[1], "</p>")
print("<p>Fuera. Partidos con: <br>más de <strong>0.5</strong> goles: ", gfueraL[2], "<br>más de <strong>1.5</strong>: ", gfueraL[3], "<br>más de <strong>2.5</strong>: ", gfueraL[4], "<br>más de <strong>3.5</strong>: ", gfueraL[5], "<br>más de <strong>4.5</strong>: ", gfueraL[6], "</p>")
print("</div>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (vis))
print("<p class='pstrong'>Como VISITANTE: </p><p>", gfueraV[0], "partidos: ",pfueraV[0], "victorias, ", pfueraV[1], " empates, ", pfueraV[2], "derrotas. ", pfueraV[3], "goles a favor. |", pfueraV[4], "goles en contra.</p>" )
print("<p>Media goles por partido en fuera: ", gfueraV[1], "</p>")
print("<p>Fuera. Partidos con: <br>más de <strong>0.5</strong> goles: ", gfueraV[2], "<br>más de <strong>1.5</strong>: ", gfueraV[3], "<br>más de <strong>2.5</strong>: ", gfueraV[4], "<br>más de <strong>3.5</strong>: ", gfueraV[5], "<br>más de <strong>4.5</strong>: ", gfueraV[6], "</p>")
print("</div>")
#print("</div>")
#Resultados casa+fuera
casaC=self.graficas.get_instancia_info_liga().get_casa()[loc[1:]]
fueraC=self.graficas.get_instancia_info_liga().get_fuera()[loc[1:]]
casaV=self.graficas.get_instancia_info_liga().get_casa()[vis[1:]]
fueraV=self.graficas.get_instancia_info_liga().get_fuera()[vis[1:]]
#Grafica de Marca-Encaja primero
print("<div class='row'>")
g='../'+self.dir_imgs+"/marcaencaja"+loc[:-1]+".png"
print("<img src='%s' width=400/>" % g)
g='../'+self.dir_imgs+"/marcaencaja"+vis[:-1]+".png"
print("<img src='%s' width=400/>" % g)
print("</div>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (loc))
print("<p>")
print("Ha marcado primero como LOCAL en", casaC[0][0], "partidos; un ", casaC[0][3], "<br>")
print("Ha encajado primero como LOCAL en", casaC[0][2], "partidos; un ", casaC[0][4], "</p>")
print("<p>Ha marcado primero como VISITANTE en", fueraC[0], "partidos; un ", fueraC[3], "<br>")
print("Ha encajado primero como VISITANTE en", fueraC[2], "partidos; un ", fueraC[4], "</p>")
print("</div>")
print("<div class='col-md-3'>")
print("<h4>%s</h4>" % (vis))
print("<p>")
print("Ha marcado primero como LOCAL en", casaV[0][0], "partidos; un ", casaV[0][3], "<br>")
print("Ha encajado primero como LOCAL en", casaV[0][2], "partidos; un ", casaV[0][4], "</p>")
print("<p>Ha marcado primero como VISITANTE en", fueraV[0], "partidos; un ", fueraV[3], "<br>")
print("Ha encajado primero como VISITANTE en", fueraV[2], "partidos; un ", fueraV[4], "</p>")
print("</div>")
print("</div>")
#** FIN VOLCADO **#
print("</body>")
print("<br><br>")
self.pie()
#******************************************************************************************************#
#Metodo que vuelva la info de todos los equipos
def info_equipos(self):
for i in sorted(self.graficas.get_instancia_info_liga().get_equipos()):
self.info_equipo(i)
#******************************************************************************************************#
#Metodo que incluye el body, la info global
def cuerpo(self):
print("<body>")
print("<div class='container'>")
#print(" <script src='css/backtotop.js'></script>")
#print("<i><a href='javascript:' id='return-to-top'><i class='icon-chevron-up'></i></a>")
print("<div class='intro-text'>")
print("<h2 class='section-heading'>Info actualizada tras final de jornada ", self.graficas.get_instancia_info_liga().get_jornada(), ":</h2>")
print("</div>")
self.back_to_top()
print("<p id='back-top'><a href=%s ><span>Vuerta parriba</span></a></p>" % (self.index))
#Nav con los nombres de cada equipo. Pinchando en un equipo te lleva a su info
print("<nav class='navbar navbar-default navbar-fixed-top'>")
#print("<div class='row'>")
for e in sorted(self.graficas.get_instancia_info_liga().get_equipos()):
print("<a class='page-scroll' href=#%s>%s</a>" % (e[1:-2].replace(' ', ''), e) )
print(" | ")
print("</nav>")
#print("</div>")
print("<nav>")
#Lista con la info para cada par de equipos correspondientes a los partidos de la siguiente jornada
print("<h4>Partidos siguiente jornada:</h4>")
for p in self.graficas.get_instancia_info_liga().get_siguiente_jornada():
enlace='partidos/'+p[0][1:-1].replace(' ', '')+"-"+p[1][1:-1].replace(' ', '')+".html"
print("<a class='navbar navbar-default' href=%s >%s</a>" % (str(enlace), p[0]+"-"+p[1]))
#print(" | ")
print("</nav>")
print("<div class='container'><h1>Info de todos los equipos: Jornada "+str(self.graficas.get_instancia_info_liga().get_jornada())+"</h1></div>")
#print("<section>")
#Llamada a volcado info equipos
self.info_equipos()
#print("</section>")
print("</div>") #Fin container
print("</body>")
#******************************************************************************************************#
#Metodo que incluye el footer
def pie(self):
print("<footer>")
print("<div class='container'>")
print("<p>Web creada por <NAME> | <EMAIL> </p>")
print("<p>Toda la información expuesta se ha logrado vía código en python <br> Repositorio en <a class='link-github' href='https://github.com/jjsalinas/estadisticas_liga.git'>GitHub</a></p>")
print("</div>")
print("</footer>")
print("</html>")
#******************************************************************************************************#
#Metodo que vuelca la información completa de todos los equipos en un html
def todo_index(self):
self.genera_graficas()
self.cabecera()
self.cuerpo()
self.pie()
try:
sys.stdout=sys.__stdout__
self.fsalida.close()
except:
print("No se ha podido cerrar", str(self.fsalida))
#******************************************************************************************************#
#Metodo que genera cada html correspondiente a cada partido de la siguiente jornada
def todo_enfrentamientos(self):
directorio='partidos/'
if not os.path.isdir(directorio):
os.makedirs(directorio)
for p in self.graficas.get_instancia_info_liga().get_siguiente_jornada():
enlace=directorio+p[0][1:-1].replace(' ', '')+"-"+p[1][1:-1].replace(' ', '')+".html"
if os.path.exists(enlace):
os.remove(enlace)
fenlace=open(enlace, 'a+')
sys.stdout=fenlace
#try:
self.info_enfrentamiento(p)
#except:
sys.stdout=sys.__stdout__
# print("Error en tiempo de ejecucion")
fenlace.close()
try:
sys.stdout=sys.__stdout__
except:
print("No se ha podido cerrar", str(self.fsalida))
#******************************************************************************************************#
#Metodo que actualiza el html de index (solo ejecutar si ya existen las graficas)
def actualiza_index(self):
self.cabecera()
self.cuerpo()
self.pie()
try:
sys.stdout=sys.__stdout__
self.fsalida.close()
except:
print("No se ha podido cerrar", str(self.fsalida))
#******************************************************************************************************#
#******************************************************************************************************#
#** FIN CLASE VOLCADO INFO **#
#******************************************************************************************************#
#** main para testear **#
if __name__ == "__main__":
j=38
info_jornada=recoleccion_info.info_liga(j)
#JORNADA SIGUIENTE: 31
""" DEFINICION DE LA SIGUIENTE JORNADA """
siguiente_jornada=[[' <NAME> ', ' Getafe ']] #0
siguiente_jornada.append([' Atletico Madrid ', ' Real Betis ']) #1
siguiente_jornada.append([' Las Palmas ', ' Valencia ']) #2
siguiente_jornada.append([' FC Barcelona ', ' Real Madrid ']) #3
siguiente_jornada.append([' Celta Vigo ', ' Deportivo ']) #4
siguiente_jornada.append([' <NAME> ', ' Granada ']) #5
siguiente_jornada.append([' Malaga ', ' Espanyol ']) #6
siguiente_jornada.append([' Eibar ', ' Villarreal ']) #7
siguiente_jornada.append([' FC Sevilla ', ' Real Sociedad ']) #8
siguiente_jornada.append([' Levante ', ' Sporting Gijon ']) #9
info_jornada.set_siguiente_jornada(siguiente_jornada)
info=volcado_info(info_jornada)
info.todo_index()
#info.todo_enfrentamientos()
#info.actualiza_index()
print("Done!")
<file_sep>/recoleccion_info.py
# -*- coding: utf-8 -*-
"""
@author: jjsalinas
Script que contiene la clase info_liga para procesar y almacenar la información
sobre las estadísticas contenida en los distintos txt:
La pagina web desde la que saco toda la info:
web_stats='http://www.soccerstats.com/timing.asp?league=spain'
Archivos txt con la información usada:
general.txt
timing.txt
first.txt
marcaprimero.txt
encajaprimero.txt
goleslocal.txt
golesvisitante.txt
golestotal.txt
Estos txt estan contenidos en la carpeta info
"""
#import sys
#import os
#******************************************************************************************************#
#*************************************** CLASE INFO_LIGA ******************************************* #
#******************************************************************************************************#
"""
CLASE info_liga
@gdespues80 : % de goles que se anotan tras el minuto 80
@jornada : ultima jornada a la que está actualizada la información
@timing : map{equipo:'golesfavor-golescontra'} : goles a favor - en contra para cada equipo en cada intervalo de 10 minutos
@timing_partes : map{equipo:'golesfavor-golescontra'} : goles a favor - en contra para cada equipo en el total de cada parte
@ratios : map{equipo:'ratios'} : ratios anotados menos encajados para cada equipo en cada intervalo de 10 minutos
@ratios_partes : map{equipo:'ratios'} : ratios anotados menos encajados para cada equipo en el total de cada parte
@casa : map{equipo:info_anotaction_primero} : para cada equipo en cuantos partidos como local: ha anotado primero, empatado a 0, encajado primero
@fuera : map{equipo:info_anotaction_primero} : para cada equipo en cuantos partidos como visitante: ha anotado primero, empatado a 0, encajado primero
@clasif #equipo: posicion, jugados, puntos, ganados, empatados, perdidos, goles a favor, goles contra, golaverage
@partidosCasa #equipo: victorias, empates, derrotas en casa, goles favor, goles contra casa
@partidosFuera #equipo: victorias, empates, derrotas fuera, goles favor, goles contra fuera
@infopartidos #equipo: puntos por partido, % partidos mas de 2.5 goles, partidos sin encajar, partidos sin marcar, partidos ambos marcan
@goleslocal : {equipo: numero partidos en casa, media goles por partido, partidos mas de 0.5 goles, mas de 1.5, mas de 2.5, mas de 3.5, mas de 4.5}
@golesvisitante : {equipo: numero partidos fuera, media goles por partido, partidos mas de 0.5 goles, mas de 1.5, mas de 2.5, mas de 3.5, mas de 4.5}
@golestotal : {equipo: numero partidos, media goles por partido, partidos mas de 0.5 goles, mas de 1.5, mas de 2.5, mas de 3.5, mas de 4.5}
@empates0 : {equipos: numero partidos con empate a 0}
@marcaprimero: {equipo: num_partidos marca primero, cuantos ha ganado, empatado, perdido }
@encajaprimero: {equipo: num_partidos encaja primero, cuantos ha ganado, empatado, perdido }
@minimoR: valor del ratio minimo en el global de todos los equipos
@maximoR: valor del ratio maximo en el global de todos los equipos
@siguiente_jornada: List of list or pairs con los partidos de la siguiente jornada
"""
class info_liga:
#Constructor que solo toma por argumentos la jornada y % goles después minuto 80
def __init__(self, jornada):
self.jornada=jornada
self.timing=None
self.timing_partes=None
self.ratios=None
self.ratios_partes=None
self.casa=None
self.fuera=None
self.clasif=None
self.partidosCasa=None
self.partidosFuera=None
self.infopartidos=None
self.goleslocal=None
self.golesvisitante=None
self.empates0=None
self.golestotal=None
self.marcaprimero=None
self.encajaprimero=None
self.minimoR=0
self.maximoR=0
self.siguiente_jornada=None
#Metodo __str__ llamado cuando se realice una llamada a imprimir por pantalla a la variable con la instancia de la clase
def __str__(self):
mensaje="Instancia para la jornada"+ str(self.jornada)
return mensaje
#******************************************************************************************************#
#Metodos set get para el valor de jornada
def set_jornada(self, ultima_jornada):
self.jornada=ultima_jornada
def get_jornada(self):
return self.jornada
#******************************************************************************************************#
#Metodo que recoge la informacion contenida en general.txt para establecer los valores de
# - clasif, partidosCasa, partidosFuera, infopartidos
def procesar_clasificacion(self):
#Lectura de archivo
fi=open('infotxt/general.txt', 'r')
info = [i for i in fi]
fi.close()
#Remover los saltos de linea y tab+salto de linea
while '\n' in info:
info.remove('\n')
while '\t\n' in info:
info.remove('\t\n')
#Variables locales
todo={}
clasif={}
partidoscasa={}
partidosfuera={}
ipartidos={}
cont=0
while cont<len(info):
#Hay que unir 3 elementos consecutivos leidos del archivo para sacar una linea completa de la wide table de clasificacion
aux=[str(i) for i in info[cont:cont+2]]
#print(aux)
cont+=2 #Contador para juntar los siguiente 3
#Como aux es vector lo paso a string para poder aplicar split('\t') sobre todos sus elementos (que son del tipo '\t8')
temp=""
for e in aux:
temp+=e
temp=temp.split('\t') #Ahora temp es un vector de strings en claro
eq=temp[1]
#print(eq)
clasif[eq]=[temp[0], temp[2], temp[9], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]]
partidoscasa[eq]=[temp[13], temp[14], temp[15], temp[16], temp[17]]
partidosfuera[eq]=[temp[21], temp[22], temp[23], temp[24], temp[25][:-2]]
ipartidos[eq]=[temp[10]] #Con los cambios de la web en la wide table es imposible sacar la infopartidos desde general.txt
"""
@clasif #equipo: posicion, jugados, puntos, ganados, empatados, perdidos, goles a favor, goles contra, golaverage
@partidosCasa #equipo: victorias, empates, derrotas en casa, goles favor, goles contra casa
@partidosFuera #equipo: victorias, empates, derrotas fuera, goles favor, goles contra fuera
@infopartidos #equipo: puntos por partido, % partidos mas de 2.5 goles, partidos sin encajar, partidos sin marcar, partidos ambos marcan
"""
self.clasif=clasif
self.partidosCasa=partidoscasa
self.partidosFuera=partidosfuera
self.infopartidos=ipartidos
#******************************************************************************************************#
# Metodo que devuelve un array con todos los nombres de los equpipos (son keys de los maps)
def get_equipos(self):
return [i for i in self.clasif]
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion del metodo clasificacion
def get_clasif(self):
return self.clasif
def get_partidosCasa(self):
return self.partidosCasa
def get_partidosFuera(self):
return self.partidosFuera
def get_infopartidos(self):
return self.infopartidos
#******************************************************************************************************#
#Metodo que recoge la informacion en timing.txt para establecer los valores de
# - timing, timing_partes, ratios, ratios_partes
def procesar_timing(self):
fi=open('infotxt/timing.txt', 'r')
info = [i for i in fi]
fi.close()
timing={}
timing_partes={}
ratios={}
ratios_partes={}
for i in info:
temp=i.split('\t')
aux=temp[1:11]
timing[temp[0]]=aux
for i in info:
temp=i.split('\t')
aux=temp[10:13]
timing_partes[temp[0]]=[aux[-2], aux[-1]]
for i in timing:
aux=timing[i]
t=[]
for j in aux:
if j!='':
if j[1]!=' ':
a=int(j[0:2])
else:
a=int(j[0])
if j[5]!=' ':
b=int(j[4:6])
else:
b=int(j[4])
ratio=a-b
t.append(ratio)
ratios[i]=t[:]
t.clear()
for i in timing_partes:
aux=timing_partes[i]
t=[]
for j in aux:
if j!='':
if j[1]!=' ':
a=int(j[0:2])
else:
a=int(j[0])
if j[5]!='\\':
b=int(j[4:6])
else:
b=int(j[4])
ratio=a-b
t.append(ratio)
ratios_partes[i]=t[:]
t.clear()
self.timing=timing
self.timing_partes=timing_partes
self.ratios=ratios
self.ratios_partes=ratios_partes
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion del metodo timing
def get_timing(self):
return self.timing
def get_timing_partes(self):
return self.timing_partes
def get_ratios(self):
return self.ratios
def get_ratios_partes(self):
return self.ratios_partes
#******************************************************************************************************#
#Metodo que recoge la informacion ya almacenada en ratios para establecer los valores de
# - maximoR, minimoR
def procesar_ratiomaxmin(self):
if(self.ratios!=None):
max_temp = min_temp = 0
for i in self.ratios:
aux=self.ratios[i]
if max(aux)>max_temp:
max_temp=max(aux)
if min(aux)<min_temp:
min_temp=min(aux)
self.maximoR=max_temp
self.minimoR=min_temp
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion del metodo procesar_ratiomaxmin
def get_maximoR(self):
return self.maximoR
def get_minimoR(self):
return self.minimoR
#******************************************************************************************************#
#Metodo que recoge la informacion en goleslocal.txt, golesvisitante.txt, golestotal.txt para establecer los valores de
# - gcasa, gfuera, gall
def procesar_goles(self):
info=[]
gcasa={}
gfuera={}
gall={}
#Goles Local
fi=open('infotxt/goleslocal.txt', 'r')
info = [ i for i in fi]
for i in fi:
info.append(i)
fi.close()
cont=0
for i in info:
temp=i.split('\t')
if not cont:
eq=temp[0]
aux=[]
aux=[j for j in temp if j!=temp[0] and j!='\n' and j!=temp[2]]
cont=1
else:
for j in temp:
if j!='':
aux.append(j)
if cont==1:
gcasa[eq]=aux[:]
gcasa[eq][6]=gcasa[eq][6][:-1]
cont=0
aux.clear()
info.clear()
#Goles Visitante
fi=open('infotxt/golesvisitante.txt', 'r')
for i in fi:
info.append(i)
fi.close()
cont=0
for i in info:
temp=i.split('\t')
if not cont:
eq=temp[0]
aux=[]
aux=[j for j in temp if j!=temp[0] and j!='\n' and j!=temp[2]]
cont=1
else:
for j in temp:
if j!='':
aux.append(j)
if cont==1:
gfuera[eq]=aux[:]
gfuera[eq][6]=gfuera[eq][6][:-1]
cont=0
aux.clear()
info.clear()
#Goles Total
fi=open('infotxt/golestotal.txt', 'r')
for i in fi:
info.append(i)
fi.close()
cont=0
for i in info:
temp=i.split('\t')
if not cont:
eq=temp[0]
aux=[]
aux=[j for j in temp if j!=temp[0] and j!='\n' and j!=temp[2]]
cont=1
else:
for j in temp:
if j!='':
aux.append(j)
if cont == 1:
gall[eq]=aux[:]
gall[eq][6]=gall[eq][6][:-1]
cont=0
aux.clear()
self.goleslocal=gcasa
self.golesvisitante=gfuera
self.golestotal=gall
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion del metodo goles
def get_golesLocal(self):
return self.goleslocal
def get_golesVisitante(self):
return self.golesvisitante
def get_golesTotal(self):
return self.golestotal
#******************************************************************************************************#
#Metodo que recoge la informacion en first.txt para establecer los valores de
# - casa, fuera, empates0
def procesar_primero(self):
fi=open('infotxt/first.txt', 'r')
info = [i for i in fi]
fi.close()
casa={}
fuera={}
for i in info:
temp2=i.split("\t")
temp=[i for i in temp2 if i!=' ' and i!=' ' and i!='']
for i in temp:
casa[temp[0]]=[temp[1:6]]
fuera[temp[0]]=[temp[6], temp[7], temp[8], temp[9], temp[10]]
empates={}
for i in self.ratios:
k=i[1:]
if not k in casa:
k=i[2:]
empates[i]=int(casa[k][0][1])+int(fuera[k][1])
self.casa=casa
self.fuera=fuera
self.empates0=empates
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion del metodo primero
def get_casa(self):
return self.casa
def get_fuera(self):
return self.fuera
def get_empates0(self):
return self.empates0
#******************************************************************************************************#
#Metodo que recoge la informacion en marcaprimero.txt para establecer los valores de
# - marcaprimero
def procesar_marcaprimero(self):
info=[]
victoria_primero={}
fi=open('infotxt/marcaprimero.txt', 'r')
for i in fi:
info.append(i)
fi.close()
for i in info:
temp2=i.split("\t")
temp=[i for i in temp2 if i!=' ' and i!=' ' and i!='']
victoria_primero[temp[0][1:-1]]=[temp[3], temp[4], temp[5]]
self.marcaprimero=victoria_primero
#******************************************************************************************************#
#Metodo que recoge la informacion en encajaprimero.txt para establecer los valores de
# - encajaprimero
def procesar_encajaprimero(self):
encaja_primero={}
fi=open('infotxt/encajaprimero.txt', 'r')
info = [i for i in fi]
fi.close()
for i in info:
temp2=i.split("\t")
temp=[i for i in temp2 if i!=' ' and i!=' ' and i!='']
encaja_primero[temp[0][1:-1]]=[temp[3], temp[4], temp[5]]
self.encajaprimero=encaja_primero
#******************************************************************************************************#
# Metodos get para las variables asignadas tras la ejecucion de los metodos marcaprimero y encajaprimero
def get_marcaPrimero(self):
return self.marcaprimero
def get_encajaPrimero(self):
return self.encajaprimero
#******************************************************************************************************#
# Metodo que establece los valores de los partidos de la siguiente jornada
def set_siguiente_jornada(self, partidos):
self.siguiente_jornada=[]
for i in partidos:
self.siguiente_jornada.append(i)
#******************************************************************************************************#
# Metodo que devuelve la lista de listas de los partidos de la siguiente jornada
def get_siguiente_jornada(self):
return self.siguiente_jornada
#******************************************************************************************************#
# Metodo que compila la informacion al completo en la instancia actual
def procesar_todo(self):
self.procesar_clasificacion()
self.procesar_timing()
self.procesar_goles()
self.procesar_primero()
self.procesar_marcaprimero()
self.procesar_encajaprimero()
self.procesar_ratiomaxmin()
#******************************************************************************************************#
#** FIN CLASE INFO_LIGA **#
#******************************************************************************************************#
#** main para testear **#
if __name__ == "__main__":
j=30
test=info_liga(j)
test.procesar_todo()
#print(test.get_partidosCasa())
#print(test.get_equipos())
|
3aad1a4e3ba172721ea38d9654e6ca267784cfc5
|
[
"Markdown",
"Python"
] | 4
|
Python
|
jjsalinas/estadisticas_liga
|
26c14a8ca847d2027d773c7776789ed427085bab
|
691d4210817bd366d120f4b7463431e140f8358c
|
refs/heads/main
|
<repo_name>egomez3412/2-Player-Pong<file_sep>/README.md
# 2-Player-Pong :joystick:
Instructor: <NAME>
CPSC 362 - Foundation of Software Engineering
Team Members:
- <NAME>
- <NAME>
- <NAME>
## Project Description :memo:
This project is intended to be a 2-player game of ping pong that can be played on the same keyboard. This product serves the need to be entertained. Users from every age and/or any demographic can benefit from this product.
- Both users can control a paddle
- Both users can play at the same time
- Users can tell their score during the game
<file_sep>/old versions/pongv3.py
# Pong by <NAME>
# November 7 2019
import turtle
import time
import winsound
if_paused = False
running = True
game_state = "splash"
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
wn = turtle.Screen()
sn = turtle.Screen()
go = turtle.Screen()
paddle_a = turtle.Turtle()
paddle_b = turtle.Turtle()
ball = turtle.Turtle()
pen = turtle.Turtle()
timeCounter = turtle.Turtle()
quitText = turtle.Turtle()
def start_game():
global game_state
game_state = "game"
def start_game_ai():
global game_state
game_state = "game-with-ai"
def end_game():
global game_state
game_state = "gameover"
main_running = True
def quit():
global main_running
main_running = False
def gameover_window():
global go
wn.title("Pong by Team 1")
wn.bgcolor("black")
wn.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
wn.tracer(2)
time_limit = 5
start_time = time.time()
# Main game loop
while (time.time() - start_time) < time_limit:
elapsed_time = time.time() - start_time
start_time = time.time() - elapsed_time
wn.update()
return True
def splash_Screen():
global sn, running
sn.title("Pong by Team 1")
wn.bgcolor("black")
sn.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
sn.tracer(2)
sn.listen()
sn.onkeypress(start_game, " ")
sn.onkeypress(start_game_ai, "a")
sn.onkeypress(quit, "q")
while running:
sn.update()
if game_state == "splash":
sn.bgpic("splash_pong.gif")
elif game_state == "game":
sn.bgpic("game_background.gif")
done = main(0)
if done:
sn.bgpic("gameover.gif")
if gameover_window():
running = False
elif game_state == "game-with-ai":
sn.bgpic("game_background.gif")
done = main(1)
if done:
sn.bgpic("gameover.gif")
if gameover_window():
running = False
elif game_state == "gameover":
if gameover_window():
running = False
#Two timers means two threads?
def toggle_pause():
global if_paused
if if_paused == True:
if_paused = False
else:
if_paused = True
# Functions
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
def main(ifAI):
#global Turtles and Screen
global wn, paddle_a, paddle_b, ball, pen, timeCounter, quitText, main_running
# Score
score_a = 0
score_b = 0
# window creation
wn.title("Pong by Team 1")
wn.bgcolor("black")
wn.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
wn.tracer(2)
# Paddle A
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# can do an array of balls from user select...(how many balls? )
# Ball
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
#change so that the ball doesn't go as fast with tracer 2 on screen (for timer)
ball.dx = .4
ball.dy = .4
# Pen (Score)
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player A: 0 Player B: 0", align="center",
font=("Bit5x5", 24, "normal"))
# timeCounter (Timer)
timeCounter.speed(0)
timeCounter.color("white")
timeCounter.penup()
timeCounter.hideturtle()
timeCounter.goto(20 - SCREEN_WIDTH/2, 20 - SCREEN_HEIGHT/2)
timeCounter.write("TIME: ", align="left",
font=("Bit5x5", 24, "normal"))
# quit Text
quitText.speed(0)
quitText.color("white")
quitText.penup()
quitText.hideturtle()
quitText.goto(0, 220)
quitText.write("press Q to quit game...", align="center",
font=("Bit5x5", 16, "normal"))
# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
wn.onkeypress(toggle_pause, "p")
wn.onkeypress(quit, "q")
# added capslock buttons
wn.onkeypress(paddle_a_up, "W")
wn.onkeypress(paddle_a_down, "S")
wn.onkeypress(quit, "Q")
wn.onkeypress(toggle_pause, "P")
time_limit = 50
start_time = time.time()
# Main game loop
while (time.time() - start_time) < time_limit and main_running:
#timeCounter.clear()
if score_a == 4 or score_b == 4:
quitText.clear()
if if_paused:
start_time = time.time() - elapsed_time
wn.update()
else:
elapsed_time = time.time() - start_time
countDown = time_limit - int(elapsed_time)
timeCounter.clear()
timeCounter.goto(20 - SCREEN_WIDTH/2, 20 - SCREEN_HEIGHT/2)
timeCounter.write("TIME: {}".format(countDown), align="left", font=("Bit5x5", 24, "normal"))
if elapsed_time >= time_limit:
print("GAME OVER") #need to print on screen!
exit()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
# Paddle and ball collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (
ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):
ball.setx(340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball.xcor() < -340 and ball.xcor() > -350) and (
ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ifAI == 1:
#AI Player
if paddle_b.ycor() < ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_down()
wn.clear()
#wn.ontimer(main(True), 100)
return True
splash_Screen()<file_sep>/old versions/pongv2.py
# Pong by <NAME>
# November 7 2019
import turtle
import time
import winsound
if_paused = False
running = True
game_state = "splash"
def start_game():
global game_state
game_state = "game"
def toggle_pause():
global if_paused
if if_paused == True:
if_paused = False
else:
if_paused = True
def end_game():
global game_state
game_state = "gameover"
quit()
def quit():
global running
running = False
def main_menu():
#close_menu = True
ww = turtle.Screen()
ww.title("Main Menu")
ww.bgcolor("white")
ww.setup(width=800, height=600)
ww.tracer(5)
# Pen
temp = turtle.Turtle()
temp.speed(0)
temp.color("black")
temp.penup()
temp.hideturtle()
temp.goto(0, 0)
temp.write("2-Player Pong", align="center", font=("Bit5x3", 48, "bold"))
while True:
ww.update()
def press_space_write(pen):
pen.clear()
pen.goto(100, 200)
pen.write("PRESS SPACE TO PAUSE THE GAME", align="center",
font=("Bit5x5", 24, "normal"))
menuStart = True
def onMenu():
global menuStart
if menuStart == True:
menuStart = False
def splash_Screen(wn):
global running
wn = turtle.Screen()
wn.title("Pong by Team 1")
wn.bgcolor("black")
wn.bgpic("splash_pong.gif")
wn.setup(width=800, height=600)
wn.tracer(1)
wn.listen()
splash_timer = time.time()
time_limit = 30
while running:
elapsed_time = time.time() - splash_timer
print(time_limit - int(elapsed_time))
if elapsed_time > time_limit:
exit()
if game_state == "splash":
wn.onkeypress(start_game, "e")
elif game_state == "game":
running = False
elif game_state == "gameover":
quit()
exit()
def main():
wn = turtle.Screen()
splash_Screen(wn)
wn.clear()
wn.bgcolor("black")
# test
# Score
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# can do an array of balls from user select...(how many balls? )
# Ball
ball = turtle.Turtle()
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = 2
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player A: 0 Player B: 0", align="center",
font=("Bit5x5", 24, "normal"))
pen.goto(0, -260)
pen.write("PRESS SPACE TO PAUSE THE GAME", align="center",
font=("Bit5x5", 12, "normal"))
# Functions
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
#wn.onkeypress(toggle_pause, " ")
wn.onkeypress(quit, "q")
#wn.onkeypress(start_game, "s")
time_limit = 999
start_time = time.time()
# Main game loop
while running:
if if_paused:
start_time = time.time() - elapsed_time
wn.update()
else:
elapsed_time = time.time() - start_time
print(time_limit - int(elapsed_time))
if elapsed_time > time_limit:
print("GAME OVER") #need to print on screen!
exit()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
# Paddle and ball collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (
ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):
ball.setx(340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball.xcor() < -340 and ball.xcor() > -350) and (
ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
#press_space_write(pen)
#AI Player
if paddle_b.ycor() < ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_down()
def menu():
print("Would you like to play? [y/n]")
choice = input("> ")
if (choice.upper() == "Y"):
main()
elif (choice.upper() == "N"):
print("Exiting...")
else:
print("Error")
# =========#=========#=========#=========#=========#=========#=========#
if __name__ == "__main__":
#main_menu()
main()
# =========#=========#=========#=========#=========#=========#=========#<file_sep>/old versions/test.py
import turtle
import time
import math
import winsound
win = turtle.Screen()
win.bgcolor("black")
win.title("Timer")
pen = turtle.Turtle()
pen.hideturtle()
pen.color("white")
pen.penup()
pen.setx(-75)
box = turtle.Turtle()
box.hideturtle()
box.color("white")
box.pensize(5)
box.penup()
box.setx(-50)
box.sety(-50)
box.pendown()
box.forward(250)
box.left(90)
box.forward(150)
box.left(90)
box.forward(300)
box.left(90)
box.forward(150)
box.left(90)
box.forward(150)
num = math.floor(win.numinput("Timer", "Enter the seconds", minval=0, maxval=59))
minute = math.floor(win.numinput("Timer", "Enter the minutes number: ", minval=0, maxval=59))
hours = math.floor(win.numinput("Timer", "Enter the hours number: ", minval=0, maxval=59))
stop = False
while True:
pen.sety(0)
pen.write(str(hours)+":"+str(minute)+":"+str(num), font=("Arial", 50))
pen.sety(100)
pen.write("Time Left:", font=("Arial", 15))
num -= 1
time.sleep(1)
pen.clear()
if num <= 0 and minute <= 0 and hours <= 0:
pen.clear()
box.clear()
pen.setx(-100)
pen.write("Time Over", font=("Arial", 50))
winsound.PlaySound("E:\\Nirma\\ChillingMusic.wav", winsound.SND_ASYNC)
time.sleep(5)
pen.clear()
break
if num == 0 and minute >= 1 and stop is not True:
num = 60
minute -= 1
if num == 0 and minute == 0 and hours >= 1 and stop is not True:
minute = 60
hours -= 1
print(num)
win.update()
print("Time Has Ended!!")
import turtle
if_paused = False
game_state = "splash"
def start_game():
global game_state
game_state = "game"
#Reset the Game
def end_game():
global game_state
game_state = "gameover"
#Game Over Timer
def toggle_pause():
global if_paused
if if_paused == True:
if_paused = False
else:
if_paused = True
def test():
wn = turtle.Screen()
wn.title("test")
wn.bgcolor("black")
bob = turtle.Turtle()
bob.speed(0)
bob.color("yellow")
bob.shape("triangle")
bob.penup()
wn.listen()
wn.onkeypress(toggle_pause, "p")
wn.onkeypress(start_game, " ")
wn.onkeypress(end_game, "q")
if not if_paused:
bob.fd(1)
bob.lt(1)
while True:
bob.clear()
if game_state == "splash":
wn.bgpic("splash.gif")
elif game_state == "game":
wn.bgpic("main.gif")
elif game_state == "gameover":
wn.bgpic("game_over.gif")
wn.update()
test()
"""
import tkinter
root = tkinter.Tk()
#root.geometry("500x450")
root.title("Concatinate Strings!")
#Create Functions
def concatStr():
first = label_first_word.get()
second = label_second_word.get()
concat = first + second
label_result['text'] = f"Result: {concat}"
#Create GUI
#Create Labels
label_first_word = tkinter.Label(root, text="Field One: ")
label_first_word.grid(column=0, row=0)
#label_first_word.pack()
label_first_word = tkinter.Entry(root)
label_first_word.grid(column=1, row=0)
#label_first_word.pack()
label_second_word = tkinter.Label(root, text="Field Two: ")
label_second_word.grid(column=0, row=1)
#label_second_word.pack()
label_second_word = tkinter.Entry(root)
label_second_word.grid(column=1, row=1)
#label_second_word.pack()
button_concat = tkinter.Button(root, text="Concatinate!", command=concatStr)
button_concat.grid(column=0, row=2)
#button_concat.pack()
label_result = tkinter.Label(root, text = "Result: ")
label_result.grid(column=1, row=2)
#label_result.pack()
#Execute Form
root.mainloop()
"""
time_limit = 5
start_time = time.time()
while (time.time() - start_time) < time_limit:
# timeCounter.clear()
if if_paused:
start_time = time.time() - elapsed_time
wn.update()
else:
elapsed_time = time.time() - start_time
countDown = time_limit - int(elapsed_time)
timeCounter.clear()
timeCounter.goto(20 - SCREEN_WIDTH / 2, 20 - SCREEN_HEIGHT / 2)
timeCounter.write("TIME: {}".format(countDown), align="left", font=("Bit5x5", 24, "normal"))
if elapsed_time >= time_limit:
print("GAME OVER") # need to print on screen!
exit()<file_sep>/old versions/2pong01.py
import turtle
import time
# import winsound
time_limit = 45
score_limit = 10
score_a = 0
score_b = 0
ball_speed_x = .4
ball_speed_y = .4
ifTwoBalls = False
ifThreeBalls = False
if_paused = False
running = True
game_state = "splash"
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
wn = turtle.Screen() # window screen
sn = turtle.Screen() # start screen
go = turtle.Screen() # gameover screen
ss = turtle.Screen() # settings screen object
paddle_a = turtle.Turtle()
paddle_b = turtle.Turtle()
settings_select = turtle.Turtle()
settings_select2 = turtle.Turtle()
settings_select3 = turtle.Turtle()
settings_select4 = turtle.Turtle()
ball = turtle.Turtle()
ball2 = turtle.Turtle()
ball3 = turtle.Turtle()
pen = turtle.Turtle()
timeCounter = turtle.Turtle()
quitText = turtle.Turtle()
def start_game():
global game_state
game_state = "game"
def start_game_ai():
global game_state
game_state = "game-with-ai"
def end_game():
global game_state
game_state = "gameover"
main_running = True
def quit():
global main_running
main_running = False
def settings():
global game_state
game_state = "settings"
restart = False
def reset():
global restart
restart = True
def splash():
global game_state
game_state = "splash"
def gameover_window():
global go, score_a, score_b, pen,sn,wn,running,restart
go.title("Gameover")
go.bgcolor("black")
go.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
go.tracer(2)
go.listen()
go.onkeypress(reset, "r") # after gave over gives user option to play again.
time_limit = 10
start_time = time.time()
pen.goto(0, -50)
scores = 'Player A: ' + str(score_a) + ' Player B: ' + str(score_b)
pen.write(scores, align="center", font=("Bit5x5", 24, "normal"))
pen.goto(0, -200)
pen.color("yellow")
res = 'Press R to restart...'
pen.write(res, align="center", font=("Bit5x5", 18, "normal"))
pen.color("light green")
if (score_a > score_b):
pen.goto(0, -100)
scores = 'Player A is the winner!'
pen.write(scores, align="center", font=("Bit5x5", 32, "normal"))
elif (score_a < score_b):
pen.goto(0, -100)
scores = 'Player B is the winner!'
pen.write(scores, align="center", font=("Bit5x5", 32, "normal"))
else:
pen.goto(0, -100)
scores = 'Tie!'
pen.write(scores, align="center", font=("Bit5x5", 32, "normal"))
timeCounter.color("white")
timeCounter.goto(20 - SCREEN_WIDTH / 2, 20 - SCREEN_HEIGHT / 2)
timeCounter.write("TIME: ", align="left",
font=("Bit5x5", 24, "normal"))
go.update()
go.reset()
while (time.time() - start_time) < time_limit and not restart:
elapsed_time = time.time() - start_time
start_time = time.time() - elapsed_time
timeCounter.clear()
countDown = time_limit - int(elapsed_time)
timeCounter.write("TIME: {}".format(countDown), align="left",
font=("Bit5x5", 24, "normal"))
pen.clear()
timeCounter.clear()
sn.update()
splash()
splash_Screen()
return True
def settings_clicked(x, y):
global ss, sn
# while running:
while game_state == "splash":
if (x >= -14.0 and x <= 14.0 and y >= -255.0 and y <= -229.0): # gear icon / settings icon
# print("x = ",x,", y = ",y)
settings_screen()
# ss.bgpic("settings.gif")
else:
sn.update()
# print("x = ",x,", y = ",y)
def settings_screen():
def save_clicked(x, y):
global settings_select, settings_select2, settings_select3, settings_select4
# settings_select.shape("square")
# settings_select.color("light green")
# settings_select.shapesize(stretch_wid=0.5, stretch_len=0.5)
# settings_select.goto(SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1)
#
# settings_select.clear()
#
# settings_select2.shape("square")
# settings_select2.color("light green")
# settings_select2.shapesize(stretch_wid=0.5, stretch_len=0.5)
# settings_select2.goto(SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1)
# settings_select2.clear()
#
# settings_select3.shape("square")
# settings_select3.color("light green")
# settings_select3.shapesize(stretch_wid=0.5, stretch_len=0.5)
# settings_select3.goto(SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1)
# settings_select3.clear()
#
# settings_select4.shape("square")
# settings_select4.color("light green")
# settings_select4.shapesize(stretch_wid=0.5, stretch_len=0.5)
# settings_select4.goto(SCREEN_WIDTH-1,SCREEN_HEIGHT-1)
# settings_select4.clear()
settings_select.shape("square")
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.penup()
settings_select.clear()
settings_select2.shape("square")
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.penup()
settings_select2.clear()
settings_select3.shape("square")
settings_select3.color("light green")
settings_select3.shapesize(stretch_wid=2.7, stretch_len=5.5)
settings_select3.penup()
settings_select3.clear()
settings_select4.shape("square")
settings_select4.color("light green")
settings_select4.shapesize(stretch_wid=2.8, stretch_len=5.5)
settings_select4.penup()
settings_select4.clear()
global time_limit, score_limit, ball_speed_x, ball_speed_y #use this in a different func if needed
global ifTwoBalls, ifThreeBalls
"""
if game_state == "settings": #test coordinates
print("x = ",x,", y = ",y) #to check coordinates
#seconds
if (x >= 1.0 and x <= 56.0 and y >= 21.0 and y <= 76.0):
print("you selected 10 seconds.")
elif (x >= 57.0 and x <= 111.0 and y >= 21.0 and y <= 76.0):
print("you selected 20 seconds.")
elif (x >= 112.0 and x <= 168.0 and y >= 21.0 and y <= 76.0):
print("you selected 30 seconds.")
elif (x >= 169.0 and x <= 225.0 and y >= 21.0 and y <= 76.0):
print("you selected 40 seconds.")
elif (x >= 226.0 and x <= 281.0 and y >= 21.0 and y <= 76.0):
print("you selected 45 seconds.")
elif (x >= 282.0 and x <= 337.0 and y >= 21.0 and y <= 76.0):
print("you selected 60 seconds.")
#score limit
elif (x >= 1.0 and x <= 56.0 and y >= -39.0 and y <= 20.0):
print("you selected 5 point limit.")
elif (x >= 57.0 and x <= 111.0 and y >= -39.0 and y <= 20.0):
print("you selected 10 point limit.")
elif (x >= 112.0 and x <= 168.0 and y >= -39.0 and y <= 20.0):
print("you selected 25 point limit.")
elif (x >= 169.0 and x <= 225.0 and y >= -39.0 and y <= 20.0):
print("you selected 50 point limit.")
elif (x >= 226.0 and x <= 281.0 and y >= -39.0 and y <= 20.0):
print("you selected 75 point limit.")
elif (x >= 282.0 and x <= 337.0 and y >= -39.0 and y <= 20.0):
print("you selected 99 point limit.")
#Number of Balls
elif (x >= 1.0 and x <= 111.0 and y >= -94.0 and y <= -41.0):
print("you selected 1 ball.")
elif (x >= 112.0 and x <= 225.0 and y >= -94.0 and y <= -41.0):
print("you selected 2 balls.")
elif (x >= 226.0 and x <= 337.0 and y >= -94.0 and y <= -41.0):
print("you selected 3 balls.")
#Ball Speed
elif (x >= 1.0 and x <= 111.0 and y >= -153.0 and y <= -97.0):
print("you selected 1x speed.")
elif (x >= 112.0 and x <= 225.0 and y >= -153.0 and y <= -97.0):
print("you selected 2x speed.")
elif (x >= 226.0 and x <= 337.0 and y >= -153.0 and y <= -97.0):
print("you selected 3x speed.")
"""
if game_state == "settings": #settings logic
#seconds
if (x >= 1.0 and x <= 56.0 and y >= 21.0 and y <= 76.0):
print("you selected 10 seconds.")
# pen.goto(x,y)
# pen.color('red')
# pen.write(str(x)+","+str(y))
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
# settings_select2.reset()
# settings_select3.reset()
# settings_select4.reset()
settings_select.goto(28, 51)
time_limit = 10
elif (x >= 57.0 and x <= 111.0 and y >= 21.0 and y <= 76.0):
print("you selected 20 seconds.")
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.goto(84, 51)
time_limit = 20
elif (x >= 112.0 and x <= 168.0 and y >= 21.0 and y <= 76.0):
print("you selected 30 seconds.")
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.goto(140, 51)
time_limit = 30
elif (x >= 169.0 and x <= 225.0 and y >= 21.0 and y <= 76.0):
print("you selected 40 seconds.")
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.goto(196, 51)
time_limit = 40
elif (x >= 226.0 and x <= 281.0 and y >= 21.0 and y <= 76.0):
print("you selected 45 seconds.")
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.goto(252, 51)
time_limit = 45
elif (x >= 282.0 and x <= 337.0 and y >= 21.0 and y <= 76.0):
print("you selected 60 seconds.")
settings_select.clear()
settings_select.color("light green")
settings_select.shapesize(stretch_wid=2.7, stretch_len=2.7)
settings_select.goto(308, 51)
time_limit = 60
#score limit
if (x >= 1.0 and x <= 56.0 and y >= -39.0 and y <= 20.0):
print("you selected 5 point limit.")
# pen.goto(x,y)
# pen.color('red')
# pen.write(str(x)+","+str(y))
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(28, -7)
score_limit = 5
elif (x >= 57.0 and x <= 111.0 and y >= -39.0 and y <= 20.0):
print("you selected 10 point limit.")
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(84, -7)
score_limit = 10
elif (x >= 112.0 and x <= 168.0 and y >= -39.0 and y <= 20.0):
print("you selected 25 point limit.")
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(140, -7)
score_limit = 25
elif (x >= 169.0 and x <= 225.0 and y >= -39.0 and y <= 20.0):
print("you selected 50 point limit.")
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(196, -7)
score_limit = 50
elif (x >= 226.0 and x <= 281.0 and y >= -39.0 and y <= 20.0):
print("you selected 75 point limit.")
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(252, -7)
score_limit = 75
elif (x >= 282.0 and x <= 337.0 and y >= -39.0 and y <= 20.0):
print("you selected 99 point limit.")
settings_select2.clear()
settings_select2.color("light green")
settings_select2.shapesize(stretch_wid=2.9, stretch_len=2.7)
settings_select2.goto(308, -7)
score_limit = 99
#***NUMBER OF BALLS CODE HERE***
elif (x >= 1.0 and x <= 111.0 and y >= -94.0 and y <= -41.0):
print("you selected 1 ball.")
ifTwoBalls = False
ifThreeBalls = False
# pen.goto(x,y)
# pen.color('red')
# pen.write(str(x)+","+str(y))
settings_select3.clear()
settings_select3.color("light green")
settings_select3.shapesize(stretch_wid=2.7, stretch_len=5.5)
settings_select3.goto(56, -65)
elif (x >= 112.0 and x <= 225.0 and y >= -94.0 and y <= -41.0):
print("you selected 2 balls.")
settings_select3.clear()
settings_select3.color("light green")
settings_select3.shapesize(stretch_wid=2.7, stretch_len=5.5)
settings_select3.goto(168, -65)
ifTwoBalls = True
ifThreeBalls = False
elif (x >= 226.0 and x <= 337.0 and y >= -94.0 and y <= -41.0):
print("you selected 3 balls.")
settings_select3.clear()
settings_select3.color("light green")
settings_select3.shapesize(stretch_wid=2.7, stretch_len=5.5)
settings_select3.goto(280, -65)
ifTwoBalls = True
ifThreeBalls = True
#Ball Speed
if (x >= 1.0 and x <= 111.0 and y >= -153.0 and y <= -97.0):
print("you selected 1x speed.")
# pen.goto(x,y)
# pen.color('red')
# pen.write(str(x)+","+str(y))
settings_select4.clear()
settings_select4.color("light green")
settings_select4.shapesize(stretch_wid=2.8, stretch_len=5.5)
settings_select4.goto(56, -122)
ball_speed_x = .4
ball_speed_y = .4
elif (x >= 112.0 and x <= 225.0 and y >= -153.0 and y <= -97.0):
print("you selected 2x speed.")
settings_select4.clear()
settings_select4.color("light green")
settings_select4.shapesize(stretch_wid=2.8, stretch_len=5.5)
settings_select4.goto(168, -122)
ball_speed_x = .8
ball_speed_y = .8
elif (x >= 226.0 and x <= 337.0 and y >= -153.0 and y <= -97.0):
print("you selected 3x speed.")
settings_select4.clear()
settings_select4.color("light green")
settings_select4.shapesize(stretch_wid=2.8, stretch_len=5.5)
settings_select4.goto(280, -122)
ball_speed_x = 1.2 #real 3x = 1.2
ball_speed_y = 1.2 #real 3x = 1.2
if (x >= -47.0 and x <= 44.0 and y >= -237.0 and y <= -218.0): #save button (saves user's settings)
# game_state == "" #resert the game_state for splash?
settings_select.reset()
settings_select2.reset()
settings_select3.reset()
settings_select4.reset()
sn.update()
splash()
#time_limit = 10 #update time_limit if user presses this coordinates,,, function maybe...
#score_limit = 1 #update score_limit if user presses,,,
# ball_speed_x = .8 #update x ball speed if user presses,,,
# ball_speed_y = .8 #update y ball speed if user presses,,,
#ball_speed_x = 4.0 # update x ball speed if user presses,,,
#ball_speed_y = 4.0 # update y ball speed if user presses,,,
# game_state == "splash"
# print("x = ",x,", y = ",y) #used to see cordinates of clicked.
# gameover_window() #does update screen but for a second
# sn.bgpic("splash_pong.gif") #switches screen to splash but no other onkeypress works (disabled)
splash_Screen()
else:
sn.update()
global ss
game_state = "settings"
ss.title("Settings")
ss.bgcolor("black")
ss.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
ss.tracer(2)
sn.listen()
# while running: #needed?
ss.update()
ss.bgpic("settings.gif")
ss.onclick(save_clicked)
# mainloop() #needed to keep listening for clicks
# return splash() #is it needed?
def splash_Screen():
global sn, running, restart
sn.title("Pong by Team 1")
wn.bgcolor("black")
sn.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
sn.tracer(2)
sn.listen()
sn.onkeypress(start_game, " ")
sn.onkeypress(start_game_ai, "a")
sn.onkeypress(quit, "q")
# sn.onkeypress(settings, "s")
sn.onclick(settings_clicked)
while running:
sn.update()
if game_state == "splash":
sn.bgpic("splash_pong.gif")
elif game_state == "game":
sn.bgpic("game_background.gif")
done = main(0)
if done:
sn.bgpic("gameover.gif")
if gameover_window():
running = False
elif game_state == "game-with-ai":
sn.bgpic("game_background.gif")
done = main(1)
if done:
sn.bgpic("gameover.gif")
gameover_window()
if restart:
running = True
else:
running = False
# if not gameover_window():
# running = False
elif game_state == "gameover":
gameover_window()
if gameover_window():
running = False
elif game_state == "settings":
settings_screen()
def toggle_pause():
global if_paused
if if_paused == True:
if_paused = False
else:
if_paused = True
# Functions
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
def main(ifAI):
# global Turtles and Screen
global wn, paddle_a, paddle_b, ball, pen, timeCounter, quitText, main_running, time_limit, score_limit, ball2
global ball_speed_x, ball_speed_y, ifTwoBalls, ifThreeBalls, ball3
# Score
global score_a
score_a = 0
global score_b
socre_b = 0
# window creation
wn.title("Pong by Team 1")
wn.bgcolor("black")
wn.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
wn.tracer(2)
# Paddle A
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# can do an array of balls from user select...(how many balls? )
# if(ifTWoBalls):
# create the other ball
# ball2
# if(three):
# create two more balls
# Ball
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
if ifTwoBalls:
# Ball2
ball2.shape("circle")
ball2.color("red")
ball2.penup()
ball2.goto(0, 0)
if ifThreeBalls:
# Ball3
ball3.shape("circle")
ball3.color("yellow")
ball3.penup()
ball3.goto(0, 0)
# change so that the ball doesn't go as fast with tracer 2 on screen (for timer)
"""
ball.dx = .4
ball.dy = .4
ball2.dx = -.4
ball2.dy = -.4
"""
ball.dx = ball_speed_x
ball.dy = ball_speed_y
if ifTwoBalls:
ball2.dx = -ball_speed_x
ball2.dy = -ball_speed_y
if ifThreeBalls:
ball3.dx = ball_speed_x
ball3.dy = -ball_speed_y
# Pen (Score)
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player A: 0 Player B: 0", align="center",
font=("Bit5x5", 24, "normal"))
# timeCounter (Timer)
timeCounter.speed(0)
timeCounter.color("white")
timeCounter.penup()
timeCounter.hideturtle()
timeCounter.goto(20 - SCREEN_WIDTH / 2, 20 - SCREEN_HEIGHT / 2)
timeCounter.write("TIME: ", align="left",
font=("Bit5x5", 24, "normal"))
# quit Text
quitText.speed(0)
quitText.color("white")
quitText.penup()
quitText.hideturtle()
quitText.goto(0, 220)
quitText.write("press Q to quit game...", align="center",
font=("Bit5x5", 16, "normal"))
# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
wn.onkeypress(toggle_pause, "p")
wn.onkeypress(quit, "q")
# added capslock buttons
wn.onkeypress(paddle_a_up, "W")
wn.onkeypress(paddle_a_down, "S")
wn.onkeypress(quit, "Q")
wn.onkeypress(toggle_pause, "P")
# time_limit = 5
start_time = time.time()
# Main game loop
while (time.time() - start_time) < time_limit and main_running:
# timeCounter.clear()
if score_a == 4 or score_b == 4:
quitText.clear()
if if_paused:
start_time = time.time() - elapsed_time
wn.update()
else:
elapsed_time = time.time() - start_time
countDown = time_limit - int(elapsed_time)
timeCounter.clear()
timeCounter.goto(20 - SCREEN_WIDTH / 2, 20 - SCREEN_HEIGHT / 2)
timeCounter.write("TIME: {}".format(countDown), align="left", font=("Bit5x5", 24, "normal"))
if elapsed_time >= time_limit:
print("GAME OVER") # need to print on screen!
exit()
if score_a == score_limit or score_b == score_limit:
print("GAME OVER") # need to print on screen!
quit()
exit()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
if ifTwoBalls:
ball2.setx(ball2.xcor() + ball2.dx)
ball2.sety(ball2.ycor() + ball2.dy)
if ifThreeBalls:
ball3.setx(ball3.xcor() + ball3.dx)
ball3.sety(ball3.ycor() + ball3.dy)
# Border checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
# winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
# winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ifTwoBalls:
if ball2.ycor() > 290:
ball2.sety(290)
ball2.dy *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball2.ycor() < -290:
ball2.sety(-290)
ball2.dy *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball2.xcor() > 390:
ball2.goto(0, 0)
ball2.dx *= -1
score_a += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ball2.xcor() < -390:
ball2.goto(0, 0)
ball2.dx *= -1
score_b += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ifThreeBalls:
if ball3.ycor() > 290:
ball3.sety(290)
ball3.dy *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball3.ycor() < -290:
ball3.sety(-290)
ball3.dy *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball3.xcor() > 390:
ball3.goto(0, 0)
ball3.dx *= -1
score_a += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
if ball3.xcor() < -390:
ball3.goto(0, 0)
ball3.dx *= -1
score_b += 1
pen.clear()
pen.goto(0, 260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center",
font=("Bit5x5", 24, "normal"))
# Paddle and ball collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (
ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):
ball.setx(340)
ball.dx *= -1
# winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball.xcor() < -340 and ball.xcor() > -350) and (
ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
# winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ifTwoBalls:
if (ball2.xcor() > 340 and ball2.xcor() < 350) and (
ball2.ycor() < paddle_b.ycor() + 40 and ball2.ycor() > paddle_b.ycor() - 40):
ball2.setx(340)
ball2.dx *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball2.xcor() < -340 and ball2.xcor() > -350) and (
ball2.ycor() < paddle_a.ycor() + 40 and ball2.ycor() > paddle_a.ycor() - 40):
ball2.setx(-340)
ball2.dx *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ifThreeBalls:
if (ball3.xcor() > 340 and ball3.xcor() < 350) and (
ball3.ycor() < paddle_b.ycor() + 40 and ball3.ycor() > paddle_b.ycor() - 40):
ball3.setx(340)
ball3.dx *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball3.xcor() < -340 and ball3.xcor() > -350) and (
ball3.ycor() < paddle_a.ycor() + 40 and ball3.ycor() > paddle_a.ycor() - 40):
ball3.setx(-340)
ball3.dx *= -1
#winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ifAI == 1:
# AI Player
if paddle_b.ycor() < ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_down()
if ifTwoBalls:
if ball.xcor() > ball2.xcor():
if paddle_b.ycor() < ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball.ycor() and abs(paddle_b.ycor() - ball.ycor()) > 10:
paddle_b_down()
else:
if paddle_b.ycor() < ball2.ycor() and abs(paddle_b.ycor() - ball2.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball2.ycor() and abs(paddle_b.ycor() - ball2.ycor()) > 10:
paddle_b_down()
if ifThreeBalls:
if ball2.xcor() > ball3.xcor():
if paddle_b.ycor() < ball2.ycor() and abs(paddle_b.ycor() - ball2.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball2.ycor() and abs(paddle_b.ycor() - ball2.ycor()) > 10:
paddle_b_down()
else:
if paddle_b.ycor() < ball3.ycor() and abs(paddle_b.ycor() - ball3.ycor()) > 10:
paddle_b_up()
elif paddle_b.ycor() > ball3.ycor() and abs(paddle_b.ycor() - ball3.ycor()) > 10:
paddle_b_down()
# if(two balls then this)
wn.clear()
return True
splash_Screen()
# settings_screen()
|
aa026ba89219aa112cb2088ab7d8f7917fc6340f
|
[
"Markdown",
"Python"
] | 5
|
Markdown
|
egomez3412/2-Player-Pong
|
238ad5f21abf2a6f44f30c1e5ddaf85bbc217b08
|
20e4f479eb77a9e591163528cd965935f276b0b0
|
refs/heads/master
|
<repo_name>incad/relief4<file_sep>/relief4-client/build.gradle
gwt {
gwtVersion = '2.8.1'
modules 'cz.incad.relief4.Relief4'
minHeapSize = "512M";
maxHeapSize = "1024M";
superDev {
noPrecompile = true
}
}
dependencies {
gwt "org.aplikator:aplikator:0.5-SNAPSHOT"
compile "org.aplikator:aplikator:0.5-SNAPSHOT"
}
<file_sep>/src/main/resources/labels.properties
aplikator.brand=Relief4
Book.ABSTRACT=Abstract
Author.ACTIVE=Active
Book.AUTHOR_ID=Author
Author=Authors
Book=Books
Book.DATE_OF_PUBL=Date of publication
Author.FIRSTNAME=First name
Author.GENDER=Gender
Author.LASTNAME=Last name
Book.NAME=Title
Book.PICTURE=File
Book.PRICE=Price
female=Female
male=Male
increaseBookPrice=Increase price
increaseBookPrice_firstPage.firstField=First unused field
increaseBookPrice_firstPage.secondField=Second ignored
increaseBookPrice_secondPage.coefficient=Coefficient<file_sep>/build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.wisepersist:gwt-gradle-plugin:1.0.5'
}
}
allprojects {
repositories {
mavenLocal()
mavenCentral()
}
apply plugin: 'java'
compileJava {
options.encoding = 'UTF-8'
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
}
}
subprojects {
apply plugin: 'gwt'
}
apply plugin: 'war'
dependencies {
compile "org.aplikator:aplikator:0.5-SNAPSHOT"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
runtime "org.postgresql:postgresql:42.1.4",
"com.oracle.jdbc:ojdbc7:172.16.17.32"
}
war {
from project(':relief4-client').tasks.compileGwt.outputs
}<file_sep>/README.md
Aplikator test project
Build & run instructions:
- checkout the aplikator framework dependency from https://github.com/incad/aplikator
- install aplikator.jar to local gradle repository running ./gradlew install in aplikator root folder
- build relief4 test with ./gradlew build
- create local postgresql database relief4 (user relief4, password <PASSWORD>)
- copy relief4.war to tomcat/webapps, start tomcat. If postgresql and tomcat run both at localhost, no configuration is necessary
- open http://localhost:8080/relief4/ddl?update=true - it will generate and execute database ddl script
- test application is ready at http://localhost:8080/relief4
<file_sep>/src/main/java/cz/incad/relief4/IncreaseBookPrice.java
package cz.incad.relief4;
import static org.aplikator.server.descriptor.Panel.column;
import static org.aplikator.server.descriptor.Panel.row;
import java.math.BigDecimal;
import java.util.List;
import org.aplikator.client.shared.data.ClientContext;
import org.aplikator.client.shared.data.FunctionResult;
import org.aplikator.server.data.Context;
import org.aplikator.server.data.Executable;
import org.aplikator.server.data.Record;
import org.aplikator.server.descriptor.Application;
import org.aplikator.server.descriptor.Function;
import org.aplikator.server.descriptor.Property;
import org.aplikator.server.descriptor.SimpleLabel;
import org.aplikator.server.descriptor.WizardPage;
/**
*
*/
public class IncreaseBookPrice extends Function {
Property<String> status1;
Property<String> status2;
Property<BigDecimal> coefficient;
public IncreaseBookPrice() {
super("increaseBookPrice", "increaseBookPrice", new Executor());
WizardPage p1 = new WizardPage(this, "firstPage");
Property<String> p1input = p1.stringProperty("firstField");
status1 = p1.stringProperty("status1");
p1.form(row(
column(new SimpleLabel<String>(status1).setSize(12), p1input)
), false);
WizardPage p2 = new WizardPage(this, "secondPage");
status2 = p1.stringProperty("status2");
coefficient = p2.numericProperty("coefficient");
p2.form(row(
column(new SimpleLabel<String>(status2).setSize(12), coefficient)
), false);
}
private static class Executor extends Executable {
@Override
public FunctionResult execute(Record currentRecord, Record wizardParameters, ClientContext clientContext, Context ctx) {
IncreaseBookPrice func = (IncreaseBookPrice) function;
Structure struct = (Structure) Application.get();
try {
List<Record> coauthors = currentRecord.getCollectionRecords(struct.book.COAUTHORS, ctx);
Record newCoauthor = struct.book.COAUTHORS.createCollectionRecord(currentRecord);
Record author = currentRecord.getReferredRecord(struct.book.AUTHOR_ID, ctx);
BigDecimal coef = wizardParameters.getValue(func.coefficient);
BigDecimal currPrice = currentRecord.getValue(struct.book.PRICE);
currentRecord.setValue(struct.book.PRICE, currPrice.multiply(coef));
ctx.addUpdatedRecordToContainer(currentRecord, currentRecord);
ctx.processRecordContainer();
return new FunctionResult("Kniha " + currentRecord.getValue(struct.book.NAME) + " byla zdražena. ", true);
} catch (Throwable t) {
return new FunctionResult("Kniha " + currentRecord.getValue(struct.book.NAME) + " nebyla zdražena: " + t, false);
}
}
@Override
public WizardPage getWizardPage(String currentPageId, boolean forwardDirection, Record currentRecord, Record wizardParameters, ClientContext clientContext, Context context) {
WizardPage page = super.getWizardPage(currentPageId, forwardDirection, currentRecord, wizardParameters, clientContext, context);
IncreaseBookPrice func = (IncreaseBookPrice) function;
if ("firstPage".equals(page.getPageId())) {
String currentStatus = wizardParameters.getValue(func.status1);
if (currentStatus == null) {
wizardParameters.setValue(func.status1, "Wizard spusten - prvnistrana");
} else {
wizardParameters.setValue(func.status1, "Navrat na prvni stranu");
}
} else if ("secondPage".equals(page.getPageId())) {
BigDecimal coef = wizardParameters.getValue(func.coefficient);
if (coef == null) {
wizardParameters.setValue(func.status2, "Poprve na druhe strane");
wizardParameters.setValue(func.coefficient, new BigDecimal("10"));
} else {
wizardParameters.setValue(func.status2, "Znovu na druhe strane");
}
}
page.setClientRecord(wizardParameters);
return page;
}
}
}<file_sep>/src/main/resources/labels_cs.properties
aplikator.brand=Relief4
Book.ABSTRACT=Abstrakt
Author.ACTIVE=Aktivní
Book.AUTHOR_ID=Autor
Author=Autoři
Book=Knihy
Book.DATE_OF_PUBL=Datum vydání
Author.FIRSTNAME=Jméno
Author.GENDER=Pohlaví
Author.LASTNAME=Příjmení
Book.NAME=Název
Book.PICTURE=Soubor
Book.PRICE=Cena
female=Božena
male=Muž
increaseBookPrice=Zdražit
increaseBookPrice_firstPage.firstField=První zbytečné pole
increaseBookPrice_firstPage.secondField=Druhé zbytečné pole
increaseBookPrice_secondPage.coefficient=Koeficient
<file_sep>/settings.gradle
include 'relief4-client'
|
71ca0d76823a733d72257b05f6b4e3e6886d7021
|
[
"Markdown",
"Java",
"INI",
"Gradle"
] | 7
|
Gradle
|
incad/relief4
|
b15ef9877455dcf097981bd91537da5d067f2441
|
1fe5e0436210df290b2cec81c9456b16ccaac69e
|
refs/heads/master
|
<repo_name>ZejdKoco/Arduino-Home-Theater-IR-code<file_sep>/KucnoKinoIR.ino
/*
* IRremote: IRsendRawDemo - demonstrates sending IR codes with sendRaw
* An IR LED must be connected to Arduino PWM pin 3.
* Version 0.1 July, 2009
* Copyright 2009 <NAME>
* http://arcfn.com
*
* IRsendRawDemo - added by AnalysIR (via www.AnalysIR.com), 24 August 2015
*
* This example shows how to send a RAW signal using the IRremote library.
* The example signal is actually a 32 bit NEC signal.
* Remote Control button: LGTV Power On/Off.
* Hex Value: 0x20DF10EF, 32 bits
*
* It is more efficient to use the sendNEC function to send NEC signals.
* Use of sendRaw here, serves only as an example of using the function.
*
*/
#include <IRremote.h>
IRsend irsend;
bool radiPC = false;
bool radiHT = false;
bool DIMM = false;
int PCpin = 8;
int HTpin = 12;
int khz = 38; // 38kHz carrier frequency for the NEC protocol
unsigned int irSignal[] = {4420, 4420, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 520, 520, 520, 520, 1638, 520, 520, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 1638, 520, 520, 520, 1638, 520, 520, 520, 1638, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 520, 1638, 520, 1638, 520, 1638, 520, 1638, 520, 1638, 520, 1638, 520, 1638, 520, 45656};
unsigned int irSignal2[] = {4420, 4420, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 520, 520, 520, 520, 1638, 520, 520, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 1638, 520, 520, 520, 1638, 520, 520, 520, 520, 520, 520, 520, 520, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 520, 520, 1638, 520, 1638, 520, 1638, 520, 520, 520, 520, 520, 1638, 520, 1638, 520, 1638, 520, 45656};
void sendIR(){
irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
}
void sendIR2(){
irsend.sendRaw(irSignal2, sizeof(irSignal2) / sizeof(irSignal2[0]), khz);
}
volatile byte state = LOW;
void setup()
{
Serial.begin(115200);
pinMode(PCpin, INPUT);
pinMode(HTpin, INPUT);
}
void loop() {
radiPC = digitalRead(PCpin);
radiHT = digitalRead(HTpin);
if(radiPC && !radiHT){ sendIR(); digitalWrite(LED_BUILTIN, HIGH); DIM = false;}
if(!radiPC && radiHT){ sendIR(); digitalWrite(LED_BUILTIN, LOW);}
delay(5000);
if(radiPC && radiHT && !DIMM){sendIR2(); DIMM=true;}
}
<file_sep>/README.md
# Arduino-Home-Theater-IR-code
Small Arduino IR controller that sends raw ON / OFF IR codes to a Samsung HT-X30 Home theater system based on Digital input. Contains a raw Dimm IR code as well.
Need to add a schematic for wiring the arduino (nano).
|
4968f14ec4573fa4414756df81545eab64431708
|
[
"Markdown",
"C++"
] | 2
|
C++
|
ZejdKoco/Arduino-Home-Theater-IR-code
|
38dd0215c703152639df65326a60157c3e957756
|
97a7992acbfa8c13b2fb75de64f8ff7e20db15b4
|
refs/heads/master
|
<file_sep>class mainScene extends Scene {
constructor(game) {
super(game)
this.init()
}
init() {
var game = this.game
this.bird = Bird(game);
this.background = game.imageByName('background')
this.background.x = 0
this.background.y = 0
this.score = 0;
this.pipes = []
for (let index = 0; index < 6; index++) {
let x = window.SCREENWIDTH * (1 + parseInt(index / 2) / 2)
let y = 0
const pipe = Pipe(game, x, y);
this.pipes.push(pipe)
}
game.registerAction("w", () => {
this.bird.moveTop();
});
game.registerAction("s", () => {
this.bird.moveBottom();
});
}
draw() {
var game = this.game
// draw
game.drawImage(this.background);
game.drawImage(this.bird);
// draw pipes
for (let index = 0; index < this.pipes.length; index++) {
const pipe = this.pipes[index];
if (pipe.alive) {
game.drawImage(pipe)
}
}
// draw labels
game.context.fillText("分数: " + this.score, 350, 50);
}
update() {
if (window.paused) {
return;
}
const bird = this.bird
const game = this.game
// 判断游戏结束
for (let index = 0; index < this.pipes.length; index++) {
const pipe = this.pipes[index];
pipe.move()
// if (bird.collide(pipe)) {
// var endScene = SceneEnd.new(game)
// game.replaceScene(endScene)
// }
}
}
}
<file_sep>const enableDebugMode = function(enable = true) {
if (!enable) {
return;
}
window.paused = false;
window.addEventListener("keydown", function(event) {
let k = event.key;
if (k == "p") {
// 暂停功能
window.paused = !window.paused;
}
});
};
const testPathFinding = () => {
var graph = new Graph([
[1,1,1,1],
[0,1,1,0],
[0,0,1,1]
]);
var start = graph.grid[0][0];
var end = graph.grid[1][2];
var result = astar.search(graph, start, end);
log('path result => ', result)
}
const __main = function() {
const images = {
bird: "img/fly1.png",
background: "img/background.png",
ground: "img/ground.png",
pipe_bottom: "img/pipe_bottom.png",
b1: "img/b1.png",
b2: "img/b2.png",
b3: "img/b3.png",
b4: "img/b4.png",
b5: "img/b5.png",
// pipe_top: "img/pipe_top.png",
};
window.SCREENWIDTH = 600
window.SCREENHEIGHT = 400
const game = Game.instance(30, images, function(g) {
// const s = SceneMain.new(g);
const s = SceneMain.new(g)
g.runWithScene(s);
});
enableDebugMode(true)
testPathFinding()
};
__main();
<file_sep>class GuaTileMap {
constructor(game) {
this.game = game
this.tiles = [
1, 2, 3, 0, 4, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
3, 1, 4, 0, 2, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
2, 2, 2, 0, 3, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
//
1, 2, 3, 0, 4, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
3, 1, 4, 0, 2, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
2, 2, 2, 0, 3, 1, 0, 0, 0, 4, 1, 0, 0, 0, 4,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
// 一列5个
this.th = 15
// Todo: tw必须为整数
this.tw = this.tiles.length / this.th
this.tileImages = [
game.imageByName('b1'),
game.imageByName('b2'),
game.imageByName('b3'),
game.imageByName('b4'),
game.imageByName('b5'),
]
this.tileWidth = 32
}
static new(...args) {
return new this(...args)
}
onTheGround(i, j) {
let index = i * this.th + j
return this.tiles[index] != 0
}
draw() {
const game = this.game
for (let index = 0; index < this.tiles.length; index++) {
const indexOfImage = this.tiles[index] - 1;
if (indexOfImage === -1) {
continue
}
let x = Math.floor(index / this.th) * this.tileWidth
let y = (index % this.th) * this.tileWidth
let tileImage = this.tileImages[indexOfImage]
tileImage.x = x
tileImage.y = y
game.drawImage(tileImage)
}
}
update() {
}
}
class SceneEditor extends Scene {
constructor(game) {
super(game)
this.init()
}
init() {
var game = this.game
// this.bird = Bird(game);
this.sprite = NesSprite.new(game, window.bitesData)
// game.context.fillStyle = '#5080ff'
// game.context.fillRect(0, 0, 1000, 1000)
this.score = 0;
this.map = GuaTileMap.new(game)
this.sprite.addMap(this.map)
// this.pipes = []
// for (let index = 0; index < 6; index++) {
// let x = window.SCREENWIDTH * (1 + parseInt(index / 2) / 2)
// let y = 0
// const pipe = Pipe(game, x, y);
// this.pipes.push(pipe)
// }
this.registerAction()
}
registerAction() {
const game = this.game
game.registerAction("a", (keyStatus) => {
// log('move left => ', keyStatus)
this.sprite.move(-1, keyStatus)
})
game.registerAction("d", (keyStatus) => {
this.sprite.move(1, keyStatus)
})
game.registerAction("w", (keyStatus) => {
// log('move top => ', keyStatus)
this.sprite.jump(keyStatus)
})
}
draw() {
// log('scene draw')
var game = this.game
// draw
// game.drawImage(this.background);
// game.drawImage(this.bird);
this.map.draw()
// draw sprite
this.sprite.draw()
// draw pipes
// for (let index = 0; index < this.pipes.length; index++) {
// const pipe = this.pipes[index];
// if (pipe.alive) {
// game.drawImage(pipe)
// }
// }
// draw labels
// game.context.fillText("分数: " + this.score, 350, 50);
}
update() {
if (window.paused) {
return;
}
// const bird = this.bird
const game = this.game
const sprite = this.sprite
sprite.update()
// 判断游戏结束
// for (let index = 0; index < this.pipes.length; index++) {
// const pipe = this.pipes[index];
// pipe.move()
// // if (bird.collide(pipe)) {
// // var endScene = SceneEnd.new(game)
// // game.replaceScene(endScene)
// // }
// }
}
}
<file_sep>class SceneMain extends Scene {
constructor(game) {
super(game)
this.init()
}
init() {
let game = this.game
this.debugPath = []
// this.background = GuaImage.new(game, 'background')
// this.addElement(this.background)
this.setMap()
this.gun = GuaImage.new(game, 'b1', 500, 280)
this.addElement(this.gun)
this.enemys = []
this.towers = []
this.setEnemys()
this.setTowers()
this.registerAction()
this.registerMouse()
}
setMap() {
this.map = TDMap.new(this.game, 100)
}
setEnemys() {
this.addEnemy()
}
addEnemy() {
let y = 100
let x = 0
const enemy = Enemy.new(this.game, 'b3', x, y)
this.addElement(enemy)
this.enemys.push(enemy)
}
drawPath(path) {
let context = this.game.context
context.fillStyle = 'rgba(200, 200, 200, 0.2)'
for (const p of path) {
// log('position => ', p)
let [x, y] = p
context.fillRect(x, y, 100, 100)
}
}
findPathing(start, end) {
let [i1, j1] = start
let [i2, j2] = end
let grids = this.map.normalGrid()
let graph = new Graph(grids)
let start1 = graph.grid[i1][j1]
let end1 = graph.grid[i2][j2]
let result = astar.search(graph, start1, end1)
let path = []
for (const p of result) {
path.push([p.x * 100, p.y * 100])
}
return path
}
setTowers() {
this.addTowers(200, 100)
this.addTowers(200, 300)
}
addTowers(x, y) {
let game = this.game
let tileSize = this.map.tileSize
let [i, j] = this.map.computeRowAndColumn(x, y)
let tower = Tower.new(game, 'b1', i * tileSize, j * tileSize)
this.addElement(tower)
this.towers.push(tower)
this.map.addTower(x, y)
this.findPathForEnemies()
}
findPathForEnemies() {
for (const e of this.enemys) {
let start = this.map.computeRowAndColumn(e.x, e.y)
let path = this.findPathing(start, [5, 2])
e.setPath(path)
this.debugPath = path
}
}
registerAction() {
const game = this.game
game.registerAction("a", (keyStatus) => {
// log('move left => ', keyStatus)
this.sprite.moveLeft(keyStatus)
})
game.registerAction("d", (keyStatus) => {
this.sprite.moveRight(keyStatus)
})
game.registerAction("w", (keyStatus) => {
// log('move top => ', keyStatus)
this.sprite.jump(keyStatus)
})
}
positionInCanvas(event) {
const target = event.target
let rect = target.getBoundingClientRect()
let x = event.clientX - rect.left
let y = event.clientY - rect.top
return [x, y]
}
blockCoordsInCanvas(event, eWidth) {
let [x, y] = this.positionInCanvas(event)
let i = Math.floor(x / eWidth)
let j = Math.floor(y / eWidth)
return [i, j]
}
registerMouse() {
const { game, gun } = this
let isDragGun = false
let offset = 16
game.registerMouseAction("mousedown", (event) => {
let [x, y] = this.positionInCanvas(event)
if (gun.isContain(x, y)) {
this.tower = gun.copy()
this.addElement(this.tower)
isDragGun = true
}
})
game.registerMouseAction("mousemove", (event) => {
if (isDragGun) {
let [x, y] = this.positionInCanvas(event)
this.tower.x = x - offset
this.tower.y = y - offset
}
})
game.registerMouseAction("mouseup", (event) => {
isDragGun = false
this.removeElement(this.tower)
let [x, y] = this.positionInCanvas(event)
this.addTowers(x, y)
})
}
draw() {
super.draw()
// log('scene draw')
this.drawPath(this.debugPath)
}
checkEnemys() {
// to check with gua video
// 先删除elements中的
this.enemys.forEach((item) => {
if (item.isDead) {
this.removeElement(item)
}
})
this.enemys = this.enemys.filter((enemy) => !enemy.isDead)
let enemys = this.enemys
let towers = this.towers
for (let index = 0; index < enemys.length; index++) {
const enemy = enemys[index]
this.removeElement()
for (let i = 0; i < towers.length; i++) {
const tower = towers[i]
if (tower.target == null) {
tower.target = enemy
tower.canAttack()
}
}
}
}
update() {
if (window.paused) {
return;
}
this.checkEnemys()
super.update()
}
}
<file_sep>class Enemy extends GuaImage {
constructor(game, name, x, y) {
name = name || 'b3'
super(game, name, x, y)
this.setInputs()
}
setInputs() {
this.speed = 2
this.maxHP = 20
this.hp = this.maxHP
this.isDead = false
// 路径
this.stepIndex = 0
this.steps = []
this.destination = 500
}
static new(...args) {
return new this(...args)
}
damaged(atk) {
this.hp -= atk
if (this.hp <= 0) {
this.isDead = true
}
}
setPath(steps) {
this.steps = steps
this.stepIndex = 0
}
update() {
if (this.isDead) {
return
}
let [dx, dy] = this.steps[this.stepIndex]
let signX = dx - this.x > 0 ? 1 : -1
let signY = dy - this.y > 0 ? 1 : -1
if (dx == this.x) {
signX = 0
}
if (dy == this.y) {
signY = 0
}
this.x += this.speed * signX
this.y += this.speed * signY
if (this.x == dx && this.y == dy) {
this.stepIndex++
if (this.stepIndex == this.steps.length) {
this.getToEnd()
}
}
}
drawLifebar() {
const { context } = this.game
context.fillStyle = 'red'
context.fillRect(this.x, this.y - 10, this.w, 10)
context.fillStyle = 'green'
let w = this.w * (this.hp / this.maxHP)
context.fillRect(this.x, this.y - 10, w, 10)
}
draw() {
super.draw()
this.drawLifebar()
}
die() {
this.isDead = true
// todo: 加死亡动画,然后移出场景
}
getToEnd() {
this.die()
}
}<file_sep>var e = selector => document.querySelector(selector);
var log = console.log.bind(console);
var imageFromPath = function(path) {
var img = new Image();
img.src = path;
return img;
};
var rectIntersects = function(a, b) {
var o = a;
if (b.y > o.y && b.y < o.y + o.image.height) {
if (b.x > o.x && b.x < o.x + o.image.width) {
return true;
}
}
return false;
};
var randomInt = function(min, max) {
var range = max - min
return min + Math.floor(Math.random() * range)
};
<file_sep>class GuaImage {
constructor(game, name, x, y) {
this.game = game
this.name = name
this.texture = game.imageByName(name)
this.x = x || 0
this.y = y || 0
this.w = this.texture.w
this.h = this.texture.h
this.rotation = 0
}
static new(...args) {
return new this(...args)
}
copy() {
let { game, name, x, y } = this
let copy = GuaImage.new(game, name, x, y)
return copy
}
isContain(cx, cy) {
let dx = this.x <= cx && cx <= this.x + this.w
let dy = this.y <= cy && cy <= this.y + this.h
return dx && dy
}
draw() {
// if (this.name == 'b1') {
// log('tower draw')
// }
const context = this.game.context
context.save()
let w2 = this.w / 2
let h2 = this.h / 2
context.translate(this.x + w2, this.y + h2)
context.rotate(this.rotation * Math.PI / 180)
context.translate(-w2 - this.x, -this.y - h2)
this.game.drawTexture(this.texture.image, this.x, this.y)
context.restore()
}
update() {
}
center() {
let cx = this.x + this.w / 2
let cy = this.y + this.h / 2
return Vector.new(cx, cy)
}
}
class Vector {
constructor(x, y) {
this.x = x
this.y = y
}
static new(...args) {
return new this(...args)
}
distance(otherV) {
let v = otherV
let dx = this.x - v.x
let dy = this.y - v.y
return Math.sqrt(dx * dx + dy * dy)
}
}<file_sep>class SceneTitle extends Scene {
constructor(game) {
super(game)
game.registerAction('k', function(){
var s = mainScene(game)
game.replaceScene(s)
})
game.registerAction('e', function(){
var s = SceneEdit.new(game)
game.replaceScene(s)
})
}
draw() {
// draw backImg
// this.game.context.drawImage(this.backImg.image, this.backImg.x, this.backImg.y)
// draw labels
this.game.context.font="30px Verdana";
// 创建渐变
var gradient=this.game.context.createLinearGradient(0, 0, 400, 0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// 用渐变填色
this.game.context.fillStyle=gradient;
this.game.context.fillText('按 k 开始游戏', 70, 150)
this.game.context.fillText('按 e 开始关卡编辑', 70, 190)
}
}<file_sep>class TDMap {
constructor(game, tileSize) {
this.game = game
this.w = 6
this.h = 4
this.tileSize = tileSize
this.setInputs()
}
static new(...args) {
return new this(...args)
}
setInputs() {
let grids = []
for (let i = 0; i < this.w; i++) {
let column = []
for (let j = 0; j < this.h; j++) {
column[j] = 0
}
grids.push(column)
}
this.grids = grids
}
computeRowAndColumn(x, y) {
let i = Math.floor(x / this.tileSize)
let j = Math.floor(y / this.tileSize)
return [i, j]
}
addTower(x, y) {
// 0表示地图上无障碍物,可以行走
// 10表示地图上有tower,无法行走
let [row, col] = this.computeRowAndColumn(x, y)
this.grids[row][col] = 10
}
normalGrid() {
let grids = this.grids
let pathGraph = []
for (const column of grids) {
let colOfGraph = []
for (const t of column) {
if (t != 0) {
colOfGraph.push(0)
} else {
colOfGraph.push(1)
}
}
pathGraph.push(colOfGraph)
}
return pathGraph
}
}<file_sep>var Bird = function(game) {
var o = game.imageByName("bird")
o.x = 20
o.y = window.SCREENHEIGHT / 2
o.speed = 10
o.alive = true
o.move = function(y) {
if (y < 0) {
y = 0
} else if (y > window.SCREENHEIGHT - o.h) {
y = window.SCREENHEIGHT - o.h
} else {
}
o.y = y
}
o.moveTop = function() {
o.move(o.y - o.speed)
}
o.moveBottom = function() {
o.move(o.y + o.speed)
}
o.collide = function(pipe) {
return o.alive && (rectIntersects(o, pipe) || rectIntersects(pipe, o))
}
return o
}<file_sep>class SceneEdit extends Scene {
constructor(game) {
super(game)
this.blocks = loadLevel(game, 3)
this.curBlock = null
game.registerAction('b', () => {
this.saveLevel()
var s = SceneTitle.new(game)
game.replaceScene(s)
})
// game.registerAction('e', function(){
// var s = editScene(game)
// game.replaceScene(s)
// })
var enableDrag = false
var enableCreat = true
game.canvas.addEventListener('mousedown', (event) => {
var x = event.offsetX
var y = event.offsetY
log(x, y, event)
// 检查是否点中了 ball
if(this.hasBlockClick(x, y)) {
// 设置拖拽状态
enableDrag = true
} else {
if(enableCreat) {
var b = Block(game, [x, y,])
log(b)
this.blocks.push(b)
enableCreat = false
}
}
})
game.canvas.addEventListener('mousemove', (event) => {
var x = event.offsetX
var y = event.offsetY
// log(x, y, 'move')
if (enableDrag) {
log(x, y, 'drag')
this.curBlock.x = x
this.curBlock.y = y
}
})
game.canvas.addEventListener('mouseup', (event) => {
var x = event.offsetX
var y = event.offsetY
log(x, y, 'up')
enableDrag = false
enableCreat = true
})
}
saveLevel() {
var blocks = this.blocks
var level = []
for(var i = 0; i < blocks.length; i++) {
var block = blocks[i]
level.push([block.x, block.y])
}
levels.push(level)
}
draw() {
// draw 背景
this.game.context.fillStyle = "#554"
this.game.context.fillRect(0, 0, 400, 300)
// draw blocks
for (var i = 0; i < this.blocks.length; i++) {
var block = this.blocks[i]
if (block.alive) {
this.game.drawImage(block)
}
}
// draw labels
// this.game.context.fillText('分数: ' + score, 10, 290)
}
hasBlockClick(x, y) {
var blocks = this.blocks
for(var i = 0; i < blocks.length; i++) {
if(blocks[i].hasPoint(x, y)) {
this.curBlock = blocks[i]
return true
}
}
return false
}
}<file_sep>class SceneMain extends Scene {
constructor(game) {
super(game)
this.init()
}
init() {
var game = this.game
// this.bird = Bird(game);
this.sprite = NesSprite.new(game, window.bitesData)
this.background = game.imageByName('background')
this.background.x = 0
this.background.y = 0
// game.context.fillStyle = '#5080ff'
// game.context.fillRect(0, 0, 1000, 1000)
this.score = 0;
// this.pipes = []
// for (let index = 0; index < 6; index++) {
// let x = window.SCREENWIDTH * (1 + parseInt(index / 2) / 2)
// let y = 0
// const pipe = Pipe(game, x, y);
// this.pipes.push(pipe)
// }
this.registerAction()
}
registerAction() {
const game = this.game
game.registerAction("a", (keyStatus) => {
// log('move left => ', keyStatus)
this.sprite.moveLeft(keyStatus)
})
game.registerAction("d", (keyStatus) => {
this.sprite.moveRight(keyStatus)
})
game.registerAction("w", (keyStatus) => {
// log('move top => ', keyStatus)
this.sprite.jump(keyStatus)
})
}
draw() {
// log('scene draw')
var game = this.game
// draw
game.drawImage(this.background);
// game.drawImage(this.bird);
// draw sprite
this.sprite.draw()
// draw pipes
// for (let index = 0; index < this.pipes.length; index++) {
// const pipe = this.pipes[index];
// if (pipe.alive) {
// game.drawImage(pipe)
// }
// }
// draw labels
game.context.fillText("分数: " + this.score, 350, 50);
}
update() {
if (window.paused) {
return;
}
// const bird = this.bird
const game = this.game
const sprite = this.sprite
sprite.update()
// 判断游戏结束
// for (let index = 0; index < this.pipes.length; index++) {
// const pipe = this.pipes[index];
// pipe.move()
// // if (bird.collide(pipe)) {
// // var endScene = SceneEnd.new(game)
// // game.replaceScene(endScene)
// // }
// }
}
}
<file_sep># beatBlock
beatBlock guaGame
<file_sep>class Tower extends GuaImage {
constructor(game, name, x, y) {
name = name || 'b1'
super(game, name, x, y)
this.setInputs()
}
setInputs() {
this.target = null
this.atk = 1
this.range = 100
}
static new(...args) {
return new this(...args)
}
canAttack() {
let t = this.target
let exist = t !== null
let can = exist && !t.isDead && this.center().distance(t.center()) <= this.range
if (can) {
return can
} else {
this.target = null
return false
}
}
fire() {
this.target.damaged(this.atk)
}
update() {
let can = this.canAttack()
if (can) {
this.fire()
let dx = this.center().x - this.target.center().x
let dy = this.center().y - this.target.center().y
this.rotation = Math.atan2(-dx, -dy) * 180 / Math.PI - 45
// log('rotation => ', this.rotation)
}
}
drawRange() {
const { context } = this.game
let { x, y } = this.center()
context.fillStyle = 'rgba(200, 200, 200, 0.5)'
context.beginPath()
context.arc(x, y, this.range, 0, 2 * Math.PI)
context.fill()
}
draw() {
this.drawRange()
super.draw()
// log('tower draw')
}
}
|
2bce655a8a5ef58f6cd1ddc244b3da6b8917dc05
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
zprad/guagame-pratice
|
fb812f1972cc5695d5a48d186360657a784d0f32
|
0a563c82467208c1976cf01081040125a84f2c57
|
refs/heads/master
|
<file_sep>package com.example.demo.algorithm;
import java.util.Arrays;
/**
* @ClassName com.example.demo.algorithm.SameNumBetweenTwoOrderArray
* @Description 找出两个有序数组的相同元素
* 数组int[] a = {2,3,3,5,7,11}
* 数组int[] b = {3,5,5,7,9,17}
* @Author lzx
* @Date 2019-12-26 9:55
* @Version 1.0
*/
public class SameNumBetweenTwoOrderArray {
public static int[] method(int[] a, int[] b) {
int[] res = new int[Math.min(a.length, b.length)];
int count = 0, start = 0;
for (int num : a) {
for (int j = start; (j < b.length) && (num >= b[j]); j++) {
if (num == b[j]) {
res[count++] = num;
start = j + 1;
break;
}
}
}
return Arrays.copyOf(res, count);
}
public static void main(String[] args) {
int[] a = {2, 3, 3, 5, 7, 11};
int[] b = {3, 5, 5, 7, 9, 17};
System.out.println(Arrays.toString(method(a, b)));
}
}
<file_sep>package com.example.demo.algorithm;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
/**
* @ClassName com.example.demo.algorithm.Factorization
* @Description 产生一个不大于给定整数n的连续质数序列
* @Author lzx
* @Date 2019-12-25 11:41
* @Version 1.0
*/
@Slf4j
public class Factorization {
public static void main(String[] args) {
System.out.println(Arrays.toString(Factorization.methodOne(25)));
}
/**
* 埃拉托色尼筛选法
*/
public static int[] methodOne(int n) {
int[] array = new int[n + 1];
for (int i = 2; i < array.length; i++) {
array[i] = 1;
}
int length = array.length - 2;
for (int i = 2; i <= Math.sqrt(n); i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[j] == 1 && j % i == 0) {
array[j] = 0;
length--;
}
}
}
int[] res = new int[length];
int num = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 1) {
res[num++] = i;
}
}
return res;
}
}
|
ba73ba306c2a74602b6848ce2d65a0ac799460de
|
[
"Java"
] | 2
|
Java
|
liangzhixin/Data_Structures_And_Algorithms
|
a2afe82b58e49519837bf624c23a6ccd1bbf9da4
|
d22627989ad625efdb25f40faae26a999b8ea3be
|
refs/heads/master
|
<file_sep>/**
* Node server for serving website on Heroku
*/
var API_KEY = process.env.MAILGUN_API_KEY;
var DOMAIN = process.env.MAILGUN_DOMAIN;
const express = require('express');
const bodyParser = require('body-parser');
const serveStatic = require('serve-static');
const mailgun = require('mailgun-js')({
apiKey: API_KEY,
domain: DOMAIN
});
function sendEmail(user) {
var data = {
from: `${user.name} <mailgun@${DOMAIN}>`,
to: '<EMAIL>',
subject: user.company,
text: user.message
};
return mailgun.messages().send(data);
}
const app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log(`Server running on port ${port}.`)
});
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
extended: true
})); // support encoded bodies
app.post('/contact/message-data', (req, res) => {
sendEmail(req.body).then(r => res.send("SUCCESS")).catch(e => res.send("ERROR"));
});
|
485a2a4156f2af7450dc8025a71fc85b64b49400
|
[
"JavaScript"
] | 1
|
JavaScript
|
AgentMacklin/portfolio-website
|
b9b5a543238645d853d6fbb8b9002f121620ef13
|
bffcfa4fc3a5f74e8cde1646b66947fe3e8f0903
|
refs/heads/melodic
|
<repo_name>hans-robot/elfin_robot<file_sep>/elfin_ethercat_driver/src/elfin_ethercat_manager.cpp
/*
* Copyright (C) 2015, <NAME>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Tokyo Opensource Robotics Kyokai Association. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// copied from https://github.com/ros-industrial/robotiq/blob/jade-devel/robotiq_ethercat/src/ethercat_manager.cpp
#include "elfin_ethercat_driver/elfin_ethercat_manager.h"
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <boost/ref.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <soem/ethercattype.h>
#include <soem/nicdrv.h>
#include <soem/ethercatbase.h>
#include <soem/ethercatmain.h>
#include <soem/ethercatdc.h>
#include <soem/ethercatcoe.h>
#include <soem/ethercatfoe.h>
#include <soem/ethercatconfig.h>
#include <soem/ethercatprint.h>
namespace
{
static const unsigned THREAD_SLEEP_TIME = 1000; // 1 ms
static const unsigned EC_TIMEOUTMON = 500;
static const int NSEC_PER_SECOND = 1e+9;
void timespecInc(struct timespec &tick, int nsec)
{
tick.tv_nsec += nsec;
while (tick.tv_nsec >= NSEC_PER_SECOND)
{
tick.tv_nsec -= NSEC_PER_SECOND;
tick.tv_sec++;
}
}
void handleErrors()
{
/* one ore more slaves are not responding */
ec_group[0].docheckstate = FALSE;
ec_readstate();
for (int slave = 1; slave <= ec_slavecount; slave++)
{
if ((ec_slave[slave].group == 0) && (ec_slave[slave].state != EC_STATE_OPERATIONAL))
{
ec_group[0].docheckstate = TRUE;
if (ec_slave[slave].state == (EC_STATE_SAFE_OP + EC_STATE_ERROR))
{
fprintf(stderr, "ERROR : slave %d is in SAFE_OP + ERROR, attempting ack.\n", slave);
ec_slave[slave].state = (EC_STATE_SAFE_OP + EC_STATE_ACK);
ec_writestate(slave);
}
else if(ec_slave[slave].state == EC_STATE_SAFE_OP)
{
fprintf(stderr, "WARNING : slave %d is in SAFE_OP, change to OPERATIONAL.\n", slave);
ec_slave[slave].state = EC_STATE_OPERATIONAL;
ec_writestate(slave);
}
else if(ec_slave[slave].state > 0)
{
if (ec_reconfig_slave(slave, EC_TIMEOUTMON))
{
ec_slave[slave].islost = FALSE;
printf("MESSAGE : slave %d reconfigured\n",slave);
}
}
else if(!ec_slave[slave].islost)
{
/* re-check state */
ec_statecheck(slave, EC_STATE_OPERATIONAL, EC_TIMEOUTRET);
if (!ec_slave[slave].state)
{
ec_slave[slave].islost = TRUE;
fprintf(stderr, "ERROR : slave %d lost\n",slave);
}
}
}
if (ec_slave[slave].islost)
{
if(!ec_slave[slave].state)
{
if (ec_recover_slave(slave, EC_TIMEOUTMON))
{
ec_slave[slave].islost = FALSE;
printf("MESSAGE : slave %d recovered\n",slave);
}
}
else
{
ec_slave[slave].islost = FALSE;
printf("MESSAGE : slave %d found\n",slave);
}
}
}
}
void cycleWorker(boost::mutex& mutex, bool& stop_flag)
{
// 1ms in nanoseconds
double period = THREAD_SLEEP_TIME * 1000;
// get current time
struct timespec tick;
clock_gettime(CLOCK_REALTIME, &tick);
timespecInc(tick, period);
// time for checking overrun
struct timespec before;
double overrun_time;
while (!stop_flag)
{
int expected_wkc = (ec_group[0].outputsWKC * 2) + ec_group[0].inputsWKC;
int sent, wkc;
{
boost::mutex::scoped_lock lock(mutex);
sent = ec_send_processdata();
wkc = ec_receive_processdata(EC_TIMEOUTRET);
}
if (wkc < expected_wkc)
{
handleErrors();
}
// check overrun
clock_gettime(CLOCK_REALTIME, &before);
overrun_time = (before.tv_sec + double(before.tv_nsec)/NSEC_PER_SECOND) - (tick.tv_sec + double(tick.tv_nsec)/NSEC_PER_SECOND);
if (overrun_time > 0.0)
{
tick.tv_sec=before.tv_sec;
tick.tv_nsec=before.tv_nsec;
}
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, NULL);
timespecInc(tick, period);
}
}
} // end of anonymous namespace
namespace elfin_ethercat_driver {
EtherCatManager::EtherCatManager(const std::string& ifname)
: ifname_(ifname),
num_clients_(0),
stop_flag_(false)
{
// initialize iomap
for(int i=0; i<4096; i++)
{
iomap_[i]=0;
}
if (initSoem(ifname))
{
cycle_thread_ = boost::thread(cycleWorker,
boost::ref(iomap_mutex_),
boost::ref(stop_flag_));
}
else
{
// construction failed
throw EtherCatError("Could not initialize SOEM");
}
}
EtherCatManager::~EtherCatManager()
{
stop_flag_ = true;
// Request init operational state for all slaves
ec_slave[0].state = EC_STATE_INIT;
/* request init state for all slaves */
ec_writestate(0);
//stop SOEM, close socket
ec_close();
cycle_thread_.join();
}
bool EtherCatManager::initSoem(const std::string& ifname) {
// Copy string contents because SOEM library doesn't
// practice const correctness
const static unsigned MAX_BUFF_SIZE = 1024;
char buffer[MAX_BUFF_SIZE];
size_t name_size = ifname_.size();
if (name_size > sizeof(buffer) - 1)
{
fprintf(stderr, "Ifname %s exceeds maximum size of %u bytes\n", ifname_.c_str(), MAX_BUFF_SIZE);
return false;
}
std::strncpy(buffer, ifname_.c_str(), MAX_BUFF_SIZE);
printf("Initializing etherCAT master\n");
if (!ec_init(buffer))
{
fprintf(stderr, "Could not initialize ethercat driver\n");
return false;
}
/* find and auto-config slaves */
if (ec_config_init(FALSE) <= 0)
{
fprintf(stderr, "No slaves are found on %s\n", ifname_.c_str());
return false;
}
printf("SOEM found and configured %d slaves\n", ec_slavecount);
if (ec_statecheck(0, EC_STATE_PRE_OP, EC_TIMEOUTSTATE*4) != EC_STATE_PRE_OP)
{
fprintf(stderr, "Could not set EC_STATE_PRE_OP\n");
return false;
}
// configure IOMap
int iomap_size = ec_config_map(iomap_);
printf("SOEM IOMap size: %d\n", iomap_size);
// locates dc slaves - ???
ec_configdc();
// '0' here addresses all slaves
if (ec_statecheck(0, EC_STATE_SAFE_OP, EC_TIMEOUTSTATE*4) != EC_STATE_SAFE_OP)
{
fprintf(stderr, "Could not set EC_STATE_SAFE_OP\n");
return false;
}
/*
This section attempts to bring all slaves to operational status. It does so
by attempting to set the status of all slaves (ec_slave[0]) to operational,
then proceeding through 40 send/recieve cycles each waiting up to 50 ms for a
response about the status.
*/
ec_slave[0].state = EC_STATE_OPERATIONAL;
ec_send_processdata();
ec_receive_processdata(EC_TIMEOUTRET);
ec_writestate(0);
int chk = 40;
do {
ec_send_processdata();
ec_receive_processdata(EC_TIMEOUTRET);
ec_statecheck(0, EC_STATE_OPERATIONAL, 50000); // 50 ms wait for state check
} while (chk-- && (ec_slave[0].state != EC_STATE_OPERATIONAL));
if(ec_statecheck(0,EC_STATE_OPERATIONAL, EC_TIMEOUTSTATE) != EC_STATE_OPERATIONAL)
{
fprintf(stderr, "OPERATIONAL state not set, exiting\n");
return false;
}
ec_readstate();
printf("\nFinished configuration successfully\n");
return true;
}
int EtherCatManager::getNumClinets() const
{
return num_clients_;
}
void EtherCatManager::write(int slave_no, uint8_t channel, uint8_t value)
{
boost::mutex::scoped_lock lock(iomap_mutex_);
if (slave_no > ec_slavecount) {
fprintf(stderr, "ERROR : slave_no(%d) is larger than ec_slavecount(%d)\n", slave_no, ec_slavecount);
exit(1);
}
if (channel*8 >= ec_slave[slave_no].Obits) {
fprintf(stderr, "ERROR : slave_no(%d) : channel(%d) is larger than Output bits (%d), you may need to read elfin_robot/docs/Fix_ESI.md or elfin_robot/docs/Fix_ESI_english.md with a Markdown editor or on github.com\n", slave_no, channel*8, ec_slave[slave_no].Obits);
exit(1);
}
ec_slave[slave_no].outputs[channel] = value;
}
uint8_t EtherCatManager::readInput(int slave_no, uint8_t channel) const
{
boost::mutex::scoped_lock lock(iomap_mutex_);
if (slave_no > ec_slavecount) {
fprintf(stderr, "ERROR : slave_no(%d) is larger than ec_slavecount(%d)\n", slave_no, ec_slavecount);
exit(1);
}
if (channel*8 >= ec_slave[slave_no].Ibits) {
fprintf(stderr, "ERROR : slave_no(%d) : channel(%d) is larger than Input bits (%d), you may need to read elfin_robot/docs/Fix_ESI.md or elfin_robot/docs/Fix_ESI_english.md with a Markdown editor or on github.com\n", slave_no, channel*8, ec_slave[slave_no].Ibits);
exit(1);
}
return ec_slave[slave_no].inputs[channel];
}
uint8_t EtherCatManager::readOutput(int slave_no, uint8_t channel) const
{
boost::mutex::scoped_lock lock(iomap_mutex_);
if (slave_no > ec_slavecount) {
fprintf(stderr, "ERROR : slave_no(%d) is larger than ec_slavecount(%d)\n", slave_no, ec_slavecount);
exit(1);
}
if (channel*8 >= ec_slave[slave_no].Obits) {
fprintf(stderr, "ERROR : slave_no(%d) : channel(%d) is larger than Output bits (%d), you may need to read elfin_robot/docs/Fix_ESI.md or elfin_robot/docs/Fix_ESI_english.md with a Markdown editor or on github.com\n", slave_no, channel*8, ec_slave[slave_no].Obits);
exit(1);
}
return ec_slave[slave_no].outputs[channel];
}
template <typename T>
uint8_t EtherCatManager::writeSDO(int slave_no, uint16_t index, uint8_t subidx, T value) const
{
int ret;
ret = ec_SDOwrite(slave_no, index, subidx, FALSE, sizeof(value), &value, EC_TIMEOUTSAFE);
return ret;
}
template <typename T>
T EtherCatManager::readSDO(int slave_no, uint16_t index, uint8_t subidx) const
{
int ret, l;
T val;
l = sizeof(val);
ret = ec_SDOread(slave_no, index, subidx, FALSE, &l, &val, EC_TIMEOUTRXM);
if ( ret <= 0 ) { // ret = Workcounter from last slave response
fprintf(stderr, "Failed to read from ret:%d, slave_no:%d, index:0x%04x, subidx:0x%02x\n", ret, slave_no, index, subidx);
}
return val;
}
template uint8_t EtherCatManager::writeSDO<char> (int slave_no, uint16_t index, uint8_t subidx, char value) const;
template uint8_t EtherCatManager::writeSDO<int> (int slave_no, uint16_t index, uint8_t subidx, int value) const;
template uint8_t EtherCatManager::writeSDO<int8_t> (int slave_no, uint16_t index, uint8_t subidx, int8_t value) const;
template uint8_t EtherCatManager::writeSDO<short> (int slave_no, uint16_t index, uint8_t subidx, short value) const;
template uint8_t EtherCatManager::writeSDO<long> (int slave_no, uint16_t index, uint8_t subidx, long value) const;
template uint8_t EtherCatManager::writeSDO<unsigned char> (int slave_no, uint16_t index, uint8_t subidx, unsigned char value) const;
template uint8_t EtherCatManager::writeSDO<unsigned int> (int slave_no, uint16_t index, uint8_t subidx, unsigned int value) const;
template uint8_t EtherCatManager::writeSDO<unsigned short> (int slave_no, uint16_t index, uint8_t subidx, unsigned short value) const;
template uint8_t EtherCatManager::writeSDO<unsigned long> (int slave_no, uint16_t index, uint8_t subidx, unsigned long value) const;
template char EtherCatManager::readSDO<char> (int slave_no, uint16_t index, uint8_t subidx) const;
template int EtherCatManager::readSDO<int> (int slave_no, uint16_t index, uint8_t subidx) const;
template short EtherCatManager::readSDO<short> (int slave_no, uint16_t index, uint8_t subidx) const;
template long EtherCatManager::readSDO<long> (int slave_no, uint16_t index, uint8_t subidx) const;
template unsigned char EtherCatManager::readSDO<unsigned char> (int slave_no, uint16_t index, uint8_t subidx) const;
template unsigned int EtherCatManager::readSDO<unsigned int> (int slave_no, uint16_t index, uint8_t subidx) const;
template unsigned short EtherCatManager::readSDO<unsigned short> (int slave_no, uint16_t index, uint8_t subidx) const;
template unsigned long EtherCatManager::readSDO<unsigned long> (int slave_no, uint16_t index, uint8_t subidx) const;
}
<file_sep>/elfin_ethercat_driver/src/elfin_ethercat_io_client.cpp
/*
Created on Mon Sep 17 11:15 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include <elfin_ethercat_driver/elfin_ethercat_io_client.h>
namespace elfin_ethercat_driver {
ElfinEtherCATIOClient::ElfinEtherCATIOClient(EtherCatManager *manager, int slave_no, const ros::NodeHandle &nh, std::string io_port_name):
manager_(manager), slave_no_(slave_no), io_nh_(nh, io_port_name)
{
// init pdo_input and output
std::string name_pdo_input[5]={"Digital_Input", "Analog_Input_channel1", "Analog_Input_channel2",
"Smart_Camera_X", "Smart_Camera_Y"};
uint8_t channel_pdo_input[5]={0, 4, 8, 12, 16};
pdo_input.clear();
ElfinPDOunit unit_tmp;
for(unsigned i=0; i<5; ++i)
{
unit_tmp.name=name_pdo_input[i];
unit_tmp.channel=channel_pdo_input[i];
pdo_input.push_back(unit_tmp);
}
std::string name_pdo_output[1]={"Digital_Output"};
uint8_t channel_pdo_output[1]={0};
pdo_output.clear();
for(unsigned i=0; i<1; ++i)
{
unit_tmp.name=name_pdo_output[i];
unit_tmp.channel=channel_pdo_output[i];
pdo_output.push_back(unit_tmp);
}
// Initialize services
read_sdo_=io_nh_.advertiseService("read_di", &ElfinEtherCATIOClient::readSDO_cb, this); // 20201117: support for 485 end
read_do_=io_nh_.advertiseService("read_do", &ElfinEtherCATIOClient::readDO_cb, this); // 20201130: support for read DO
write_sdo_=io_nh_.advertiseService("write_do",&ElfinEtherCATIOClient::writeSDO_cb, this); // 20201117: support for 485 end
get_txsdo_server_=io_nh_.advertiseService("get_txpdo", &ElfinEtherCATIOClient::getTxSDO_cb, this); // 20201120: support for 485 end
get_rxsdo_server_=io_nh_.advertiseService("get_rxpdo", &ElfinEtherCATIOClient::getRxSDO_cb, this); // 20201120: support for 485 end
}
ElfinEtherCATIOClient::~ElfinEtherCATIOClient()
{
}
// 20201116: read the end SDO
int32_t ElfinEtherCATIOClient::readSDO_unit(int n)
{
if(n<0 || n>=pdo_input.size())
return 0x0000;
// 20201116: build the connection.
manager_->writeSDO<int>(3,0x3100,0x0,1); // Modbus DO command
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3101,0x0,0x010040); // 64 connect to Modbus
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3102,0x0,0x010001); // Modbus Addr & count
usleep(50000);
// 0x2126, L_4 is end DI, H_4 is button DI.
int32_t map;
map = (manager_->readSDO<int32_t>(3, 0x2126, 0x0)) << 16; // read the end DI
manager_->writeSDO<int>(3,0x3100,0x0,0); // Modbus DO command 0
usleep(50000);
return map;
}
// 20201130: read the end DO
int32_t ElfinEtherCATIOClient::readDO_unit(int n)
{
if(n<0 || n>=pdo_input.size())
return 0x0000;
// 20201130: build the connection.
manager_->writeSDO<int>(3,0x3100,0x0,1); // Modbus DO command
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3101,0x0,0x010040); // 64 connect to Modbus
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3102,0x0,0x010001); // Modbus Addr & count
usleep(50000);
// 0x310C, DO.
int32_t map;
map = (manager_->readSDO<int32_t>(3, 0x310C, 0x0)) << 12; // read the end DO
manager_->writeSDO<int>(3,0x3100,0x0,0); // Modbus DO command 0
usleep(50000);
return map;
}
// 20201117: write the end SDO LED and DO
int32_t ElfinEtherCATIOClient::writeSDO_unit(int32_t val)
{
// 20201119: high the LED and DO of the end
manager_->writeSDO<int>(3,0x3100,0x0,1); // Modbus DO command
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3101,0x0,0x010006); // Modbus SlaveID & Function
usleep(50000);
manager_->writeSDO<int32_t>(3,0x3102,0x0,0x010001); // Modbus Addr & count
usleep(50000);
manager_->writeSDO<int32_t>(3,0x310C,0x0, val >> 12); // Write the LED and DO
usleep(50000);
manager_->writeSDO<int>(3,0x3100,0x0,0); // Modbus DO command 0
usleep(50000);
return 0;
}
// 20201120: add the getTxSDO and getRxSDO for confirming the same as old IO
std::string ElfinEtherCATIOClient::getTxSDO()
{
int length=20;
uint8_t map[length];
char temp[8];
std::string result="slave";
result.reserve(160);
result.append("4_txpdo:\n");
for (unsigned i = 0; i < length; ++i)
{
map[i] = 0x00;
sprintf(temp,"0x%.2x",(uint8_t)map[i]);
result.append(temp, 4);
result.append(":");
}
result.append("\n");
return result;
}
std::string ElfinEtherCATIOClient::getRxSDO()
{
int length=4;
uint8_t map[length];
char temp[8];
std::string result="slave";
result.reserve(160);
result.append("4_rxpdo:\n");
for (unsigned i = 0; i < length; ++i)
{
map[i] = 0x00;
sprintf(temp,"0x%.2x",(uint8_t)map[i]);
result.append(temp, 4);
result.append(":");
}
result.append("\n");
return result;
}
// 20201116: read the end SDO
bool ElfinEtherCATIOClient::readSDO_cb(elfin_robot_msgs::ElfinIODRead::Request &req, elfin_robot_msgs::ElfinIODRead::Response &resp)
{
resp.digital_input=readSDO_unit(elfin_io_txpdo::DIGITAL_INPUT);
return true;
}
// 20201130: read the end DO
bool ElfinEtherCATIOClient::readDO_cb(elfin_robot_msgs::ElfinIODRead::Request &req, elfin_robot_msgs::ElfinIODRead::Response &resp)
{
resp.digital_input=readDO_unit(elfin_io_txpdo::DIGITAL_INPUT); // 20201130: digital_input for convenience
return true;
}
// 20201117: write the end SDO
bool ElfinEtherCATIOClient::writeSDO_cb(elfin_robot_msgs::ElfinIODWrite::Request &req, elfin_robot_msgs::ElfinIODWrite::Response &resp)
{
writeSDO_unit(req.digital_output);
resp.success=true;
return true;
}
// 20201120: add the getTxSDO and getRxSDO for confirming the same as old IO
bool ElfinEtherCATIOClient::getRxSDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
resp.success=true;
resp.message=getRxSDO();
return true;
}
bool ElfinEtherCATIOClient::getTxSDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
resp.success=true;
resp.message=getTxSDO();
return true;
}
}
<file_sep>/README_cn.md
Elfin Robot
======
If you don't speak chinese, please [click here](./README_english.md)
<p align="center">
<img src="docs/images/elfin.png" />
</p>
本文件夹中包含了多个为Elfin机器人提供ROS支持的软件包。推荐的运行环境为 Ubuntu 18.04 + ROS Melodic, 其他环境下的运行情况没有测试过。
### 安装软件包
#### Ubuntu 18.04 + ROS Melodic
**安装一些重要的依赖包**
```sh
$ sudo apt-get install ros-melodic-soem ros-melodic-gazebo-ros-control ros-melodic-ros-control ros-melodic-ros-controllers
```
**安装和升级MoveIt!,** 注意因为MoveIt!最新版进行了很多的优化,如果你已经安装了MoveIt!, 也请一定按照以下方法升级到最新版。
安装/升级MoveIt!:
```sh
$ sudo apt-get update
$ sudo apt-get install ros-melodic-moveit-*
```
安装 trac_ik 插件包
```sh
sudo apt-get install ros-melodic-trac-ik
```
**安装本软件包**
首先创建catkin工作空间 ([教程](http://wiki.ros.org/catkin/Tutorials))。 然后将本文件夹克隆到src/目录下,之后用catkin_make来编译。
假设你的工作空间是~/catkin_ws,你需要运行的命令如下:
```sh
$ cd ~/catkin_ws/src
$ git clone -b melodic-devel https://github.com/hans-robot/elfin_robot.git
$ cd ..
$ catkin_make
$ source devel/setup.bash
```
**安装本软件包**
首先创建catkin工作空间 ([教程](http://wiki.ros.org/catkin/Tutorials))。 然后将本文件夹克隆到src/目录下,之后用catkin_make来编译。
假设你的工作空间是~/catkin_ws,你需要运行的命令如下:
```sh
$ cd ~/catkin_ws/src
$ git clone -b melodic-devel https://github.com/hans-robot/elfin_robot.git
$ cd ..
$ catkin_make
$ source devel/setup.bash
```
---
### 使用仿真模型
***下面给出的是启动Elfin3的一系列命令。启动Elfin5和Elfin10的方法与之类似,只要在相应的地方替换掉相应的前缀即可。***
用Gazebo仿真请运行:
```sh
$ roslaunch elfin_gazebo elfin3_empty_world.launch
```
运行MoveIt!模块, RViz界面:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch
```
如果你此时不想运行RViz界面,请用以下命令:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch display:=false
```
运行后台程序及Elfin Control Panel界面:
```sh
$ roslaunch elfin_basic_api elfin_basic_api.launch
```
> 关于MoveIt!的使用方法可以参考[docs/moveit_plugin_tutorial.md](docs/moveit_plugin_tutorial.md)
Tips:
每次规划路径时,都要设置初始位置为当前位置。
---
### 使用真实的Elfin机器人
***下面给出的是启动Elfin3的一系列命令。启动Elfin5和Elfin10的方法与之类似,只要在相应的地方替换掉相应的前缀即可。***
先把购买机器人时得到的elfin_drivers.yaml放到elfin_robot_bringup/config/文件夹下。
将Elfin通过网线连接到电脑。先通过`ifconfig`指令来确定与Elfin连接的网卡名称。本软件包默认的名称是eth0 。假如当前名称不是eth0的话,请对elfin_robot_bringup/config/elfin_drivers.yaml的相应部分进行修改。
```
elfin_ethernet_name: eth0
```
加载Elfin机器人模型:
```sh
$ roslaunch elfin_robot_bringup elfin3_bringup.launch
```
启动Elfin硬件,Elfin的控制需要操作系统的实时性支持,运行下面的命令前请先为你的Linux系统内核打好实时补丁。打补丁的方法可以参考这个[教程](http://www.jianshu.com/p/8787e45a9e01)。Elfin机械臂有两种不同版本的EtherCAT从站,在启动硬件前,请先确认你的Elfin的从站版本。
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control.launch
```
或
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v2.launch
```
或如果购买的是RS485末端的机器人
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v3.launch
```
运行MoveIt!模块, RViz界面:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch
```
如果你此时不想运行RViz界面,请用以下命令:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch display:=false
```
运行后台程序及Elfin Control Panel界面:
```sh
$ roslaunch elfin_basic_api elfin_basic_api.launch
```
用Elfin Control Panel界面给Elfin使能指令,如果此时没有报错,直接按下"Servo On"即可使能。如果报错,需先按"Clear Fault"清错后再按下"Servo On"使能。
关于MoveIt!的使用方法可以参考[docs/moveit_plugin_tutorial.md](docs/moveit_plugin_tutorial.md)
Tips:
每次规划路径时,都要设置初始位置为当前位置。
在关闭机械臂电源前,需先按下Elfin Control Panel界面的"Servo Off"给Elfin去使能。
更多关于API的信息请看[docs/API_description.md](docs/API_description.md)
<file_sep>/elfin_ikfast_plugins/elfin10_ikfast_plugin/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
project(elfin10_ikfast_plugin)
add_compile_options(-std=c++11)
find_package(catkin REQUIRED COMPONENTS
moveit_core
pluginlib
roscpp
tf_conversions
tf2_kdl
tf2_eigen
eigen_conversions
)
include_directories(${catkin_INCLUDE_DIRS})
catkin_package(
LIBRARIES
CATKIN_DEPENDS
moveit_core
pluginlib
roscpp
tf_conversions
tf2_kdl
tf2_eigen
eigen_conversions
)
include_directories(include)
set(IKFAST_LIBRARY_NAME elfin10_elfin_arm_moveit_ikfast_plugin)
find_package(LAPACK REQUIRED)
add_library(${IKFAST_LIBRARY_NAME} src/elfin10_elfin_arm_ikfast_moveit_plugin.cpp)
target_link_libraries(${IKFAST_LIBRARY_NAME} ${catkin_LIBRARIES} ${Boost_LIBRARIES} ${LAPACK_LIBRARIES})
install(TARGETS ${IKFAST_LIBRARY_NAME} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
install(
FILES
elfin10_elfin_arm_moveit_ikfast_plugin_description.xml
DESTINATION
${CATKIN_PACKAGE_SHARE_DESTINATION}
)
<file_sep>/elfin_ros_control/include/elfin_ros_control/elfin_hardware_interface.h
/*
Created on Tue Sep 25 10:16 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_ROS_CONTROL_HW_INTERFACE
#define ELFIN_ROS_CONTROL_HW_INTERFACE
#include <ros/ros.h>
#include <urdf/model.h>
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <std_msgs/Float64.h>
#include <sensor_msgs/JointState.h>
#include <hardware_interface/joint_command_interface.h>
#include <hardware_interface/joint_state_interface.h>
#include <hardware_interface/posvel_command_interface.h>
#include <elfin_hardware_interface/postrq_command_interface.h>
#include <elfin_hardware_interface/posveltrq_command_interface.h>
#include <hardware_interface/robot_hw.h>
#include <controller_manager/controller_manager.h>
#include <controller_manager_msgs/ListControllers.h>
#include "elfin_ethercat_driver/elfin_ethercat_driver.h"
namespace elfin_ros_control {
typedef struct{
std::string name;
double reduction_ratio;
double count_rad_factor;
double count_rad_per_s_factor;
double count_Nm_factor;
int32_t count_zero;
double axis_position_factor;
double axis_torque_factor;
double position;
double velocity;
double effort;
double position_cmd;
double velocity_cmd;
double vel_ff_cmd;
double effort_cmd;
}AxisInfo;
typedef struct{
elfin_ethercat_driver::ElfinEtherCATClient* client_ptr;
AxisInfo axis1;
AxisInfo axis2;
}ModuleInfo;
class ElfinHWInterface : public hardware_interface::RobotHW
{
public:
ElfinHWInterface(elfin_ethercat_driver::EtherCatManager *manager, const ros::NodeHandle &nh=ros::NodeHandle("~"));
~ElfinHWInterface();
bool prepareSwitch(const std::list<hardware_interface::ControllerInfo> &start_list,
const std::list<hardware_interface::ControllerInfo> &stop_list);
void doSwitch(const std::list<hardware_interface::ControllerInfo> &start_list,
const std::list<hardware_interface::ControllerInfo> &stop_list);
void read_init();
void read_update(const ros::Time &time_now);
void write_update();
private:
std::vector<std::string> elfin_driver_names_;
std::vector<elfin_ethercat_driver::ElfinEtherCATDriver*> ethercat_drivers_;
std::vector<ModuleInfo> module_infos_;
hardware_interface::JointStateInterface jnt_state_interface_;
hardware_interface::PositionJointInterface jnt_position_cmd_interface_;
hardware_interface::EffortJointInterface jnt_effort_cmd_interface_;
elfin_hardware_interface::PosTrqJointInterface jnt_postrq_cmd_interface_;
hardware_interface::PosVelJointInterface jnt_posvel_cmd_interface_;
elfin_hardware_interface::PosVelTrqJointInterface jnt_posveltrq_cmd_interface_;
ros::NodeHandle n_;
ros::Time read_update_time_;
ros::Duration read_update_dur_;
std::vector<bool> pre_switch_flags_;
std::vector<boost::shared_ptr<boost::mutex> > pre_switch_mutex_ptrs_;
bool isModuleMoving(int module_num);
double motion_threshold_;
bool setGroupPosMode(const std::vector<int>& module_no);
bool setGroupTrqMode(const std::vector<int>& module_no);
};
}
#endif
<file_sep>/docs/moveit_plugin_tutorial.md
### MoveIt! RViz Plugin 使用说明
更多说明请见:
http://docs.ros.org/indigo/api/moveit_tutorials/html/doc/ros_visualization/visualization_tutorial.html
#### 设置起始位置
进入"Motion Planning"界面下的Planning选项卡,在"Select Start State"项目下选择"current",然后按下"Update"按钮。

#### 设置目标位置
拖动机械臂末端的标记,到任意一个目标位置。

#### 规划路径
设置好起始位置和目标位置后,等待约5s的时间,然后按下"Plan"按键。此时会显示出一条规划好的轨迹。

#### 实现路径
按下"Execute"按键,机械臂会沿着路径运动。在此过程中,可以按下"Stop"键来让机械臂停止。
<file_sep>/elfin_robot_servo/README.md
elfin_robot_servo
=====
### start servo:
* **roslaunch elfin_robot_servo start_moveit_servo.launch**
### Subscribed Topics
* **/servo_server/delta_twist_cmds**
令机械臂末端往x/y/z方向按照一定速度持续运动
example: servo_movePose() in elfin_robot_servo/src/test.py
* **/servo_server/delta_joint_cmds**
令机械臂各个关节往正/负运动方向按照一定速度持续运动
example: servo_moveJoint() in elfin_robot_servo/src/test.py
### 参考:
```sh
https://ros-planning.github.io/moveit_tutorials/doc/realtime_servo/realtime_servo_tutorial.html
```
### 提示:
在使用末端位置控制时请保证机器人在当前姿态下可以进行空间直线运动
在使用过程中请注意速度设置和发送频率以避免造成意外状况<file_sep>/elfin_ethercat_driver/src/elfin_ethercat_driver.cpp
/*
Created on Mon Sep 17 10:31:06 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include <elfin_ethercat_driver/elfin_ethercat_driver.h>
namespace elfin_ethercat_driver {
ElfinEtherCATDriver::ElfinEtherCATDriver(EtherCatManager *manager, std::string driver_name, const ros::NodeHandle &nh):
driver_name_(driver_name), root_nh_(nh), ed_nh_(nh, driver_name)
{
// Initialize slave_no_
int slave_no_array_default[3]={1, 2, 3};
std::vector<int> slave_no_default;
slave_no_default.clear();
slave_no_default.reserve(3);
for(int i=0; i<3; i++)
{
slave_no_default.push_back(slave_no_array_default[i]);
}
ed_nh_.param<std::vector<int> >("slave_no", slave_no_, slave_no_default);
// Initialize joint_names_
std::vector<std::string> joint_names_default;
joint_names_default.clear();
joint_names_default.reserve(2*slave_no_.size());
for(int i=0; i<slave_no_.size(); i++)
{
std::string num_1=boost::lexical_cast<std::string>(2*(i+1)-1);
std::string num_2=boost::lexical_cast<std::string>(2*(i+1));
std::string name_1="joint";
std::string name_2="joint";
name_1.append(num_1);
name_2.append(num_2);
joint_names_default.push_back(name_1);
joint_names_default.push_back(name_2);
}
ed_nh_.param<std::vector<std::string> >("joint_names", joint_names_, joint_names_default);
// Initialize reduction_ratios_
std::vector<double> reduction_ratios_default;
reduction_ratios_default.clear();
reduction_ratios_default.reserve(2*slave_no_.size());
for(int i=0; i<slave_no_.size(); i++)
{
reduction_ratios_default.push_back(101);
reduction_ratios_default.push_back(101);
}
ed_nh_.param<std::vector<double> >("reduction_ratios", reduction_ratios_, reduction_ratios_default);
// Check the values of reduction ratios
for(int i=0; i<reduction_ratios_.size(); i++)
{
if(reduction_ratios_[i]<1)
{
ROS_ERROR("reduction_ratios[%i] is too small", i);
exit(0);
}
}
// Initialize axis_position_factors_
std::vector<double> axis_position_factors_default;
axis_position_factors_default.clear();
axis_position_factors_default.reserve(2*slave_no_.size());
for(int i=0; i<slave_no_.size(); i++)
{
axis_position_factors_default.push_back(131072);
axis_position_factors_default.push_back(131072);
}
ed_nh_.param<std::vector<double> >("axis_position_factors", axis_position_factors_, axis_position_factors_default);
// Check the values of axis position factors
for(int i=0; i<axis_position_factors_.size(); i++)
{
if(axis_position_factors_[i]<1)
{
ROS_ERROR("axis_position_factors[%i] is too small", i);
exit(0);
}
}
// Initialize axis_torque_factors_
if(!ed_nh_.hasParam("axis_torque_factors"))
{
ROS_ERROR("Please set the param %s/axis_torque_factors", ed_nh_.getNamespace().c_str());
ROS_ERROR("For more details: elfin_robot_bringup/config/elfin_drivers_example.yaml");
exit(0);
}
ed_nh_.getParam("axis_torque_factors", axis_torque_factors_);
// Check the values of axis torque factors
for(int i=0; i<axis_torque_factors_.size(); i++)
{
if(axis_torque_factors_[i]<1)
{
ROS_ERROR("axis_torque_factors[%i] is too small", i);
exit(0);
}
}
// Initialize count_zeros_
if(!ed_nh_.hasParam("count_zeros"))
{
ROS_ERROR("Please set the param %s/count_zeros", ed_nh_.getNamespace().c_str());
ROS_ERROR("For more details: elfin_robot_bringup/config/elfin_drivers_example.yaml");
exit(0);
}
ed_nh_.getParam("count_zeros", count_zeros_);
// Check the number of joint names, reduction ratios, axis position factors
// axis torque factors and count_zeros
if(joint_names_.size()!=slave_no_.size()*2)
{
ROS_ERROR("the number of joint names is %lu, it should be %lu", joint_names_.size(), slave_no_.size()*2);
exit(0);
}
if(reduction_ratios_.size()!=slave_no_.size()*2)
{
ROS_ERROR("the number of reduction ratios is %lu, it should be %lu", reduction_ratios_.size(), slave_no_.size()*2);
exit(0);
}
if(axis_position_factors_.size()!=slave_no_.size()*2)
{
ROS_ERROR("the number of axis position factors is %lu, it should be %lu", axis_position_factors_.size(), slave_no_.size()*2);
exit(0);
}
if(axis_torque_factors_.size()!=slave_no_.size()*2)
{
ROS_ERROR("the number of axis torque factors is %lu, it should be %lu", axis_torque_factors_.size(), slave_no_.size()*2);
exit(0);
}
if(count_zeros_.size()!=slave_no_.size()*2)
{
ROS_ERROR("the number of count_zeros is %lu, it should be %lu", count_zeros_.size(), slave_no_.size()*2);
exit(0);
}
// Initialize count_rad_factors
count_rad_factors_.resize(count_zeros_.size());
for(int i=0; i<count_rad_factors_.size(); i++)
{
count_rad_factors_[i]=reduction_ratios_[i]*axis_position_factors_[i]/(2*M_PI);
}
// Initialize motion_threshold_ and pos_align_threshold_
motion_threshold_=5e-5;
pos_align_threshold_=5e-5;
// Initialize ethercat_client_
ethercat_clients_.clear();
ethercat_clients_.resize(slave_no_.size());
for(int i=0; i<slave_no_.size(); i++)
{
ethercat_clients_[i]=new ElfinEtherCATClient(manager, slave_no_[i]);
}
// Initialize io_slave_no_
int io_slave_no_array_default[1]={4};
std::vector<int> io_slave_no_default;
io_slave_no_default.clear();
io_slave_no_default.reserve(1);
for(int i=0; i<1; i++)
{
io_slave_no_default.push_back(io_slave_no_array_default[i]);
}
ed_nh_.param<std::vector<int> >("io_slave_no", io_slave_no_, io_slave_no_default);
// Initialize ethercat_io_client_
ethercat_io_clients_.clear();
ethercat_io_clients_.resize(io_slave_no_.size());
std::string io_port="io_port";
for(int i=0; i<io_slave_no_.size(); i++)
{
std::string num=boost::lexical_cast<std::string>(i+1);
std::string io_port_name=io_port.append(num);
ethercat_io_clients_[i]=new ElfinEtherCATIOClient(manager, io_slave_no_[i], ed_nh_, io_port_name);
}
//Initialize ros service server
get_txpdo_server_=ed_nh_.advertiseService("get_txpdo", &ElfinEtherCATDriver::getTxPDO_cb, this);
get_rxpdo_server_=ed_nh_.advertiseService("get_rxpdo", &ElfinEtherCATDriver::getRxPDO_cb, this);
get_current_position_server_=ed_nh_.advertiseService("get_current_position", &ElfinEtherCATDriver::getCurrentPosition_cb, this);
get_motion_state_server_=ed_nh_.advertiseService("get_motion_state", &ElfinEtherCATDriver::getMotionState_cb, this);
get_pos_align_state_server_=ed_nh_.advertiseService("get_pos_align_state", &ElfinEtherCATDriver::getPosAlignState_cb, this);
enable_robot_=ed_nh_.advertiseService("enable_robot", &ElfinEtherCATDriver::enableRobot_cb, this);
disable_robot_=ed_nh_.advertiseService("disable_robot", &ElfinEtherCATDriver::disableRobot_cb, this);
clear_fault_=ed_nh_.advertiseService("clear_fault", &ElfinEtherCATDriver::clearFault_cb, this);
recognize_position_=ed_nh_.advertiseService("recognize_position", &ElfinEtherCATDriver::recognizePosition_cb, this);
// Initialize ros publisher
enable_state_pub_=ed_nh_.advertise<std_msgs::Bool>("enable_state", 1);
fault_state_pub_=ed_nh_.advertise<std_msgs::Bool>("fault_state", 1);
// Initialize ros timer
status_update_period_.sec=0;
status_update_period_.nsec=1e+8;
status_timer_=ed_nh_.createTimer(status_update_period_, &ElfinEtherCATDriver::updateStatus, this);
status_timer_.start();
// Recognize the Positions
bool recognize_flag;
ed_nh_.param<bool>("automatic_recognition", recognize_flag, true);
if(recognize_flag)
{
printf("\n recognizing joint positions, please wait a few minutes ... ... \n");
if(recognizePosition())
ROS_INFO("positions are recognized automatically");
else
ROS_INFO("positions aren't recognized automatically");
}
}
ElfinEtherCATDriver::~ElfinEtherCATDriver()
{
for(int i=0; i<ethercat_clients_.size(); i++)
{
if(ethercat_clients_[i]!=NULL)
delete ethercat_clients_[i];
}
for(int i=0; i<ethercat_io_clients_.size(); i++)
{
if(ethercat_io_clients_[i]!=NULL)
delete ethercat_io_clients_[i];
}
}
// true: enabled; false: disabled
bool ElfinEtherCATDriver::getEnableState()
{
bool enable_flag_tmp=true;
for(int i=0; i<ethercat_clients_.size(); i++)
{
enable_flag_tmp=enable_flag_tmp && ethercat_clients_[i]->isEnabled();
}
return enable_flag_tmp;
}
// true: there is a fault; false: there is no fault
bool ElfinEtherCATDriver::getFaultState()
{
bool fault_flag_tmp=false;
for(int i=0; i<ethercat_clients_.size(); i++)
{
fault_flag_tmp=fault_flag_tmp || ethercat_clients_[i]->isWarning();
}
return fault_flag_tmp;
}
// true: robot is moving; false: robot is not moving
bool ElfinEtherCATDriver::getMotionState()
{
std::vector<double> previous_pos;
std::vector<double> last_pos;
previous_pos.resize(count_zeros_.size());
last_pos.resize(count_zeros_.size());
int32_t count1, count2;
for(int i=0; i<ethercat_clients_.size(); i++)
{
ethercat_clients_[i]->getActPosCounts(count1, count2);
previous_pos[2*i]=count1/count_rad_factors_[2*i];
previous_pos[2*i+1]=count2/count_rad_factors_[2*i+1];
}
usleep(10000);
for(int i=0; i<ethercat_clients_.size(); i++)
{
ethercat_clients_[i]->getActPosCounts(count1, count2);
last_pos[2*i]=count1/count_rad_factors_[2*i];
last_pos[2*i+1]=count2/count_rad_factors_[2*i+1];
}
for(int i=0; i<previous_pos.size(); i++)
{
if(fabs(last_pos[i]-previous_pos[i])>motion_threshold_)
{
return true;
}
}
return false;
}
// true: command position counts are aligned with actual position counts
// false: command position counts aren't aligned with actual position counts
bool ElfinEtherCATDriver::getPosAlignState()
{
std::vector<double> act_pos;
std::vector<double> cmd_pos;
act_pos.resize(count_zeros_.size());
cmd_pos.resize(count_zeros_.size());
int32_t count1, count2;
for(int i=0; i<ethercat_clients_.size(); i++)
{
ethercat_clients_[i]->getActPosCounts(count1, count2);
act_pos[2*i]=count1/count_rad_factors_[2*i];
act_pos[2*i+1]=count2/count_rad_factors_[2*i+1];
ethercat_clients_[i]->getCmdPosCounts(count1, count2);
cmd_pos[2*i]=count1/count_rad_factors_[2*i];
cmd_pos[2*i+1]=count2/count_rad_factors_[2*i+1];
}
for(int i=0; i<act_pos.size(); i++)
{
if(fabs(cmd_pos[i]-act_pos[i])>pos_align_threshold_)
{
return false;
}
}
return true;
}
void ElfinEtherCATDriver::updateStatus(const ros::TimerEvent &te)
{
enable_state_msg_.data=getEnableState();
fault_state_msg_.data=getFaultState();
enable_state_pub_.publish(enable_state_msg_);
fault_state_pub_.publish(fault_state_msg_);
}
size_t ElfinEtherCATDriver::getEtherCATClientNumber()
{
return ethercat_clients_.size();
}
ElfinEtherCATClient* ElfinEtherCATDriver::getEtherCATClientPtr(size_t n)
{
return ethercat_clients_[n];
}
std::string ElfinEtherCATDriver::getJointName(size_t n)
{
return joint_names_[n];
}
double ElfinEtherCATDriver::getReductionRatio(size_t n)
{
return reduction_ratios_[n];
}
double ElfinEtherCATDriver::getAxisPositionFactor(size_t n)
{
return axis_position_factors_[n];
}
double ElfinEtherCATDriver::getAxisTorqueFactor(size_t n)
{
return axis_torque_factors_[n];
}
int32_t ElfinEtherCATDriver::getCountZero(size_t n)
{
return count_zeros_[n];
}
bool ElfinEtherCATDriver::recognizePosition()
{
std_srvs::SetBool::Request request;
request.data=true;
std_srvs::SetBool::Response response_clear_fault;
std_srvs::SetBool::Response response_disable;
if(getFaultState())
{
clearFault_cb(request, response_clear_fault);
}
else
{
response_clear_fault.success=true;
}
disableRobot_cb(request, response_disable);
if(response_clear_fault.success && response_disable.success)
{
std::vector<pthread_t> tids;
tids.resize(ethercat_clients_.size());
std::vector<int> threads;
threads.resize(ethercat_clients_.size());
for(int i=0; i<ethercat_clients_.size(); i++)
{
threads[i]=pthread_create(&tids[i], NULL, ethercat_clients_[i]->recognizePoseCmd, (void *)ethercat_clients_[i]);
}
for(int i=0; i<ethercat_clients_.size(); i++)
{
pthread_join(tids[i], NULL);
}
}
else
{
ROS_WARN("there are some faults or the motors aren't disabled, positions can't be recognized");
return false;
}
return true;
}
bool ElfinEtherCATDriver::getTxPDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
std::string result=ethercat_clients_[0]->getTxPDO();
unsigned int reference_length=result.size();
result.reserve(ethercat_clients_.size() * reference_length);
for(int i=1; i<ethercat_clients_.size(); i++)
{
result.append(ethercat_clients_[i]->getTxPDO());
}
resp.success=true;
resp.message=result;
return true;
}
bool ElfinEtherCATDriver::getRxPDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
std::string result=ethercat_clients_[0]->getRxPDO();
unsigned int reference_length=result.size();
result.reserve(ethercat_clients_.size() * reference_length);
for(int i=1; i<ethercat_clients_.size(); i++)
{
result.append(ethercat_clients_[i]->getRxPDO());
}
resp.success=true;
resp.message=result;
return true;
}
bool ElfinEtherCATDriver::getCurrentPosition_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
std::string result=ethercat_clients_[0]->getCurrentPosition();
for(int i=1; i<ethercat_clients_.size(); i++)
{
result.append(ethercat_clients_[i]->getCurrentPosition());
}
resp.success=true;
resp.message=result;
return true;
}
bool ElfinEtherCATDriver::getMotionState_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="request's data is false";
return true;
}
resp.message="true: robot is moving; false: robot is not moving";
resp.success=getMotionState();
return true;
}
bool ElfinEtherCATDriver::getPosAlignState_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="request's data is false";
return true;
}
resp.message="true: cmd pos aligned with actual pos; false: cmd pos not aligned with actual pos";
resp.success=getPosAlignState();
return true;
}
bool ElfinEtherCATDriver::enableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
if(getFaultState())
{
resp.success=false;
resp.message="please clear fault first";
return true;
}
std::vector<pthread_t> tids;
tids.resize(ethercat_clients_.size());
std::vector<int> threads;
threads.resize(ethercat_clients_.size());
for(int i=0; i<ethercat_clients_.size(); i++)
{
threads[i]=pthread_create(&tids[i], NULL, ethercat_clients_[i]->setEnable, (void *)ethercat_clients_[i]);
}
for(int i=0; i<ethercat_clients_.size(); i++)
{
pthread_join(tids[i], NULL);
}
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
bool flag_tmp;
while (ros::ok())
{
flag_tmp=true;
for(int i=0; i<ethercat_clients_.size(); i++)
{
flag_tmp=flag_tmp && ethercat_clients_[i]->isEnabled();
}
if(flag_tmp)
{
resp.success=true;
resp.message="robot is enabled";
return true;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 20e+9)
{
resp.success=false;
resp.message="robot is not enabled";
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
bool ElfinEtherCATDriver::disableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
std::vector<pthread_t> tids;
tids.resize(ethercat_clients_.size());
std::vector<int> threads;
threads.resize(ethercat_clients_.size());
for(int i=0; i<ethercat_clients_.size(); i++)
{
threads[i]=pthread_create(&tids[i], NULL, ethercat_clients_[i]->setDisable, (void *)ethercat_clients_[i]);
}
for(int i=0; i<ethercat_clients_.size(); i++)
{
pthread_join(tids[i], NULL);
}
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
bool flag_tmp;
while (ros::ok())
{
flag_tmp=false;
for(int i=0; i<ethercat_clients_.size(); i++)
{
flag_tmp=flag_tmp || ethercat_clients_[i]->isEnabled();
}
if(!flag_tmp)
{
resp.success=true;
resp.message="robot is disabled";
return true;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 20e+9)
{
resp.success=false;
resp.message="robot is not disabled";
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
bool ElfinEtherCATDriver::clearFault_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
for(int i=0; i<ethercat_clients_.size(); i++)
{
ethercat_clients_[i]->resetFault();
}
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
bool flag_tmp;
while (ros::ok())
{
flag_tmp=false;
for(int i=0; i<ethercat_clients_.size(); i++)
{
flag_tmp=flag_tmp || ethercat_clients_[i]->isWarning();
}
if(!flag_tmp)
{
resp.success=true;
resp.message="Faults are cleared";
return true;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 10e+9)
{
resp.success=false;
resp.message="There are still Faults";
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
bool ElfinEtherCATDriver::recognizePosition_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
if(ethercat_clients_.size()==0)
{
resp.success=false;
resp.message="there is no ethercat client";
return true;
}
bool flag_tmp=recognizePosition();
if(flag_tmp)
{
resp.success=true;
resp.message="positions are recognized";
return true;
}
else
{
resp.success=false;
resp.message="position recognition failed, please disable the servos first";
return true;
}
}
int32_t ElfinEtherCATDriver::getIntFromStr(std::string str)
{
if(str.size()>8 || str.size()%2 !=0)
{
ROS_ERROR("%s 's length should be an even number and less than 8", str.c_str());
exit(0);
}
unsigned char map[4];
int j=0;
for(int i=0; i<str.size(); i+=2)
{
unsigned char high=str[str.size()-2-i];
unsigned char low=str[str.size()-1-i];
if(high>='0' && high<='9')
high = high-'0';
else if(high>='A' && high<='F')
high = high - 'A' + 10;
else if(high>='a' && high<='f')
high = high - 'a' + 10;
else
{
ROS_ERROR("%s 's not a hex number", str.c_str());
exit(0);
}
if(low>='0' && low<='9')
low = low-'0';
else if(low>='A' && low<='F')
low = low - 'A' + 10;
else if(low>='a' && low<='f')
low = low - 'a' + 10;
else
{
ROS_ERROR("%s 's not a hex number", str.c_str());
exit(0);
}
map[j++]=high << 4 | low;
}
for(int k=j; k<4; k++)
{
unsigned char tmp=map[k];
map[k]=tmp-tmp;
}
int32_t result;
result=*(int32_t *)(map);
return result;
}
} // end namespace
int main(int argc, char** argv)
{
ros::init(argc,argv,"elfin_ethercat_driver", ros::init_options::AnonymousName);
elfin_ethercat_driver::EtherCatManager em("eth0");
elfin_ethercat_driver::ElfinEtherCATDriver ed(&em, "elfin");
ros::spin();
}
<file_sep>/elfin_ethercat_driver/include/elfin_ethercat_driver/elfin_ethercat_io_client.h
/*
Created on Tus Nov 17 15:36 2020
@author: Burb
Software License Agreement (BSD License)
Copyright (c) 2020, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: Burb
#ifndef ELFIN_ETHERCAT_IO_CLIENT_H
#define ELFIN_ETHERCAT_IO_CLIENT_H
#include <ros/ros.h>
#include <vector>
#include <elfin_ethercat_driver/elfin_ethercat_manager.h>
#include <elfin_robot_msgs/ElfinIODRead.h>
#include <elfin_robot_msgs/ElfinIODWrite.h>
#include <std_srvs/SetBool.h>
#include <pthread.h>
#include <time.h>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
namespace elfin_io_txpdo {
const int DIGITAL_INPUT=0;
const int ANALOG_INPUT_CHANNEL1=1;
const int ANALOG_INPUT_CHANNEL2=2;
const int SMART_CAMERA_X=3;
const int SMART_CAMERA_Y=4;
}
namespace elfin_io_rxpdo {
const int DIGITAL_OUTPUT=0;
}
namespace elfin_ethercat_driver {
class ElfinEtherCATIOClient{
private:
EtherCatManager* manager_;
ros::NodeHandle n_;
ros::NodeHandle io_nh_;
std::vector<ElfinPDOunit> pdo_input; // txpdo
std::vector<ElfinPDOunit> pdo_output; //rxpdo
int slave_no_;
ros::ServiceServer read_sdo_; //20201116
ros::ServiceServer read_do_; //20201130
ros::ServiceServer write_sdo_; //20201117
ros::ServiceServer get_txsdo_server_;//20201120
ros::ServiceServer get_rxsdo_server_;//20201120
public:
ElfinEtherCATIOClient(EtherCatManager* manager, int slave_no, const ros::NodeHandle& nh, std::string io_port_name);
~ElfinEtherCATIOClient();
int32_t readSDO_unit(int n); // 20201117
int32_t readDO_unit(int n); // 20201130
void writeOutput_unit(int n, int32_t val);
int32_t writeSDO_unit(int n); // 20201117
std::string getTxSDO();
std::string getRxSDO();
bool readSDO_cb(elfin_robot_msgs::ElfinIODRead::Request &req, elfin_robot_msgs::ElfinIODRead::Response &resp); // 20201117
bool readDO_cb(elfin_robot_msgs::ElfinIODRead::Request &req, elfin_robot_msgs::ElfinIODRead::Response &resp); // 20201130
bool writeSDO_cb(elfin_robot_msgs::ElfinIODWrite::Request &req, elfin_robot_msgs::ElfinIODWrite::Response &resp); // 20201117
bool getRxSDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool getTxSDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
};
}
#endif
<file_sep>/docs/API_description_english.md
API description
=====
### Subscribed Topics:
* **elfin_basic_api/joint_goal (sensor_msgs/JointState)**
make the robot move to a position in joint space after planning a trajectory.
example: function_pub_joints() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_basic_api/cart_goal (geometry_msgs/PoseStamped)**
make the robot move to a position in cartesian coordination system after planning a trajectory.
example: function_pub_cart_xxx() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_basic_api/cart_path_goal (geometry_msgs/PoseArray)**
make the robot move through the assigned positions in cartesian coordination system after planning a trajectory composed of lines.
example: function_pub_cart_path_xxx() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_arm_controller/command (trajectory_msgs/JointTrajectory)**
This topic contain a trajectory. When you publish this topic, the robot will move along the trajectory.
* **elfin_teleop_joint_cmd_no_limit (std_msgs/Int64)**
This is a topic for developer, customers are not supposed to use it. A particular joint will move a little distance after subscribing this topic for once.
Meaning of the data in the topic:
| data | joint | direction |
| ------- | ------------| -------------- |
| 1 | elfin_joint1| ccw |
| -1 | elfin_joint1 | cw |
| 2 | elfin_joint2 | ccw |
| -2 | elfin_joint2 | cw |
| 3 | elfin_joint3| ccw |
| -3 | elfin_joint3 | cw |
| 4 | elfin_joint4 | ccw |
| -4 | elfin_joint4 | cw |
| 5 | elfin_joint5| ccw |
| -5 | elfin_joint5 | cw |
| 6 | elfin_joint6 | ccw |
| -6 | elfin_joint6 | cw |
------
### Published Topics:
* **elfin_arm_controller/state (control_msgs/JointTrajectoryControllerState)**
The current status of the joints.
* **elfin_ros_control/elfin/enable_state (std_msgs/Bool)**
The servo status of the robot.
true: enabled / false: disabled
* **elfin_ros_control/elfin/fault_state (std_msgs/Bool)**
The fault status of the robot.
true: warning / false: no fault
* **elfin_basic_api/parameter_updates (dynamic_reconfigure/Config)**
The value of the dynamic parameters of elfin_basic_api, e.g. velocity scaling.
* **elfin_basic_api/reference_link_name (std_msgs/String)**
The reference link in the calculations of the elfin_basic_api node
* **elfin_basic_api/end_link_name (std_msgs/String)**
The end link in the calculations of the elfin_basic_api node
------
### Services:
* **elfin_basic_api/get_reference_link (std_srvs/SetBool)**
You can get the reference link name of *elfin_basic_api* from the response of this service.
* **elfin_basic_api/get_end_link (std_srvs/SetBool)**
You can get the end link name of *elfin_basic_api* from the response of this service.
* **elfin_basic_api/stop_teleop (std_srvs/SetBool)**
Make the robot stop moving.
* **elfin_ros_control/elfin/get_txpdo (std_srvs/SetBool)**
You can get the content of TxPDOs from the response of this service.
* **elfin_ros_control/elfin/get_rxpdo (std_srvs/SetBool)**
You can get the content of RxPDOs from the response of this service.
* **elfin_ros_control/elfin/get_current_position (std_srvs/SetBool)**
You can get the count values of the current joint positions from the response of this service.
* **elfin_basic_api/set_parameters (dynamic_reconfigure/Reconfigure)**
Set the dynamic parameters of elfin_basic_api, e.g. velocity scaling
example: set_parameters() in elfin_robot_bringup/script/set_velocity_scaling.py
* **elfin_ros_control/elfin/recognize_position (std_srvs/SetBool)**
Recognize the position of joints.
* **elfin_ros_control/elfin/io_port1/write_do (elfin_robot_msgs/ElfinIODWrite)**
Write a value into DO
example:
```
rosservice call /elfin_ros_control/elfin/io_port1/write_do "digital_output: 0x001b"
```
* **elfin_ros_control/elfin/io_port1/read_di (elfin_robot_msgs/ElfinIODRead)**
Read the value from DI
example:
```
rosservice call /elfin_ros_control/elfin/io_port1/read_di "data: true"
```
* **elfin_ros_control/elfin/io_port1/get_txpdo (std_srvs/SetBool)**
You can get the content of TxPDOs from the response of this service.
* **elfin_ros_control/elfin/io_port1/get_rxpdo (std_srvs/SetBool)**
You can get the content of RxPDOs from the response of this service.
* **elfin_module_open_brake_slaveX(std_srvs/SetBool)**
When the module is not enabled, you can open the brake of the corresponding module using this service.
for example:
```sh
rosservice call elfin_module_open_brake_slave1 "data: true"
```
* **elfin_module_close_brake_slaveX(std_srvs/SetBool)**
When the module is not enabled, you can close the brake of the corresponding module using this service.
for example:
```sh
rosservice call elfin_module_close_brake_slave1 "data: true"
```
***Following are the services, that support "Elfin Control Panel" interface. customers are not supposed to use them.***
* **elfin_basic_api/enable_robot (std_srvs/SetBool)**
Enable the robot.
* **elfin_ros_control/elfin/enable_robot (std_srvs/SetBool)**
The recommand service for enabling the robot is *elfin_basic_api/enable_robot*. The robot will be enabled directly when you call this service. So you may need to deal with the status of controllers by yourself. For details: http://wiki.ros.org/controller_manager .
* **elfin_basic_api/disable_robot (std_srvs/SetBool)**
Disable the robot.
* **elfin_ros_control/elfin/disable_robot (std_srvs/SetBool)**
The recommand service for disabling the robot is *elfin_basic_api/disable_robot*. The robot will be disabled directly when you call this service. So you may need to deal with the status of controllers by yourself. For details: http://wiki.ros.org/controller_manager .
* **elfin_ros_control/elfin/clear_fault (std_srvs/SetBool)**
Clear fault.
* **elfin_basic_api/set_reference_link (elfin_robot_msgs/SetString)**
Set the reference link in the calculations of the elfin_basic_api node
* **elfin_basic_api/set_end_link (elfin_robot_msgs/SetString)**
Set the end link in the calculations of the elfin_basic_api node
* **elfin_basic_api/joint_teleop (elfin_robot_msgs/SetInt16)**
When this service is called, a particular joint will move in a direction and will NOT stop until it reach the limit position or elfin_basic_api/stop_teleop is called. Please be careful when you call this service.
Meaning of the data in the service:
| data | joint | direction |
| ------- | ------------| -------------- |
| 1 | elfin_joint1| ccw |
| -1 | elfin_joint1 | cw |
| 2 | elfin_joint2 | ccw |
| -2 | elfin_joint2 | cw |
| 3 | elfin_joint3| ccw |
| -3 | elfin_joint3 | cw |
| 4 | elfin_joint4 | ccw |
| -4 | elfin_joint4 | cw |
| 5 | elfin_joint5| ccw |
| -5 | elfin_joint5 | cw |
| 6 | elfin_joint6 | ccw |
| -6 | elfin_joint6 | cw |
* **elfin_basic_api/cart_teleop (elfin_robot_msgs/SetInt16)**
When this service is called, the end link of the robot will move in a direction in cartsian coordination system and will NOT stop until it reach the limit position or elfin_basic_api/stop_teleop is called. Please be careful when you call this service.
Meaning of the data in the service:
| data | axis | direction |
| ------- | ------------| -------------- |
| 1 | X | positive |
| -1 | X | negative |
| 2 | Y | positive |
| -2 | Y | negative |
| 3 | Z | positive |
| -3 | Z | negative |
| 4 | Rx | ccw |
| -4 | Rx | cw |
| 5 | Ry | ccw |
| -5 | Ry | cw |
| 6 | Rz | ccw |
| -6 | Rz | cw |
* **elfin_basic_api/home_teleop (std_srvs/SetBool)**
When this service is called, the robot will move to home position and will NOT stop until it reach the home position or elfin_basic_api/stop_teleop is called. Please be careful when you call this service.
<file_sep>/elfin_hardware_interface/include/elfin_hardware_interface/postrq_command_interface.h
/*
Created on Fri Sep 28 15:54:17 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_HARDWARE_INTERFACE_POSTRQ_COMMAND_INTERFACE_H
#define ELFIN_HARDWARE_INTERFACE_POSTRQ_COMMAND_INTERFACE_H
#include <cassert>
#include <string>
#include <hardware_interface/internal/hardware_resource_manager.h>
#include <hardware_interface/joint_state_interface.h>
namespace elfin_hardware_interface
{
class PosTrqJointHandle : public hardware_interface::JointStateHandle
{
public:
PosTrqJointHandle() : hardware_interface::JointStateHandle(), cmd_pos_(0), cmd_trq_(0) {}
PosTrqJointHandle(const hardware_interface::JointStateHandle& js, double* cmd_pos, double* cmd_trq)
: hardware_interface::JointStateHandle(js), cmd_pos_(cmd_pos), cmd_trq_(cmd_trq)
{
if (!cmd_pos)
{
throw hardware_interface::HardwareInterfaceException("Cannot create handle '" + js.getName() + "'. Command position pointer is null.");
}
if (!cmd_trq)
{
throw hardware_interface::HardwareInterfaceException("Cannot create handle '" + js.getName() + "'. Command torque pointer is null.");
}
}
void setCommand(double cmd_pos, double cmd_trq)
{
setCommandPosition(cmd_pos);
setCommandTorque(cmd_trq);
}
void setCommandPosition(double cmd_pos) {assert(cmd_pos_); *cmd_pos_ = cmd_pos;}
void setCommandTorque(double cmd_trq) {assert(cmd_trq_); *cmd_trq_ = cmd_trq;}
double getCommandPosition() const {assert(cmd_pos_); return *cmd_pos_;}
double getCommandTorque() const {assert(cmd_trq_); return *cmd_trq_;}
private:
double* cmd_pos_;
double* cmd_trq_;
};
class PosTrqJointInterface : public hardware_interface::HardwareResourceManager<PosTrqJointHandle, hardware_interface::ClaimResources> {};
}
#endif
<file_sep>/docs/Torque_HWI.md
力矩模式硬件接口
====
使用硬件接口*hardware_interface::EffortJointInterface*的控制器可以对Elfin进行力矩模式控制。控制器*effort_controllers/JointTrajectoryController*是一个很好的例子,它的使用方法如下:
1. 更改elfin_robot_bringup/config/elfin_arm_control.yaml中的控制器类型:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: effort_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ gains:
+ elfin_joint1: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint2: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint3: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint4: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint5: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint6: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ velocity_ff:
+ elfin_joint1: 1
+ elfin_joint2: 1
+ elfin_joint3: 1
+ elfin_joint4: 1
+ elfin_joint5: 1
+ elfin_joint6: 1
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
gains: PID相关参数
velocity_ff: 此参数会与相应轴的目标速度相乘,以得到相应轴的与速度相关的前馈力矩。
**请注意: 上述例子中的PID参数并不是最优参数,请合理设置PID参数,否则可能会造成危险情况**
2. 按[README.md](../README.md)的说明正常启动机械臂。
3. 启动后即可使用力矩环控制器,此时可使用rqt_reconfigure调整pid参数。
```sh
rosrun rqt_reconfigure rqt_reconfigure
```
<file_sep>/README.md
Elfin Robot
======
Chinese version of the README -> please [click here](./README_cn.md)
<p align="center">
<img src="docs/images/elfin.png" />
</p>
This repository provides ROS support for the Elfin Robot. The recommend operating environment is on Ubuntu 18.04 with ROS Melodic. So far These packages haven't been tested in other environment.
### Installation
#### Ubuntu 18.04 + ROS Melodic
**Install some important dependent software packages:**
```sh
$ sudo apt-get install ros-melodic-soem ros-melodic-gazebo-ros-control ros-melodic-ros-control ros-melodic-ros-controllers
```
**Install or upgrade MoveIt!.**
If you have installed MoveIt!, please make sure that it's been upgraded to the latest version.
Install/Upgrade MoveIt!:
```sh
$ sudo apt-get update
$ sudo apt-get install ros-melodic-moveit-*
```
install trac_ik plugin
```sh
sudo apt-get install ros-melodic-trac-ik
```
**Install this repository from Source**
First set up a catkin workspace (see [this tutorials](http://wiki.ros.org/catkin/Tutorials)).
Then clone the repository into the src/ folder. It should look like /path/to/your/catkin_workspace/src/elfin_robot.
Make sure to source the correct setup file according to your workspace hierarchy, then use catkin_make to compile.
Assuming your catkin workspace folder is ~/catkin_ws, you should use the following commands:
```sh
$ cd ~/catkin_ws/src
$ git clone -b melodic-devel https://github.com/hans-robot/elfin_robot.git
$ cd ..
$ catkin_make
$ source devel/setup.bash
```
---
### Usage with Gazebo Simulation
***There are launch files available to bringup a simulated robot - either Elfin3, Elfin5 or Elfin10.
In the following the commands for Elfin3 are given. For Elfin5 or Elfin10, simply replace the prefix accordingly.***
Bring up the simulated robot in Gazebo:
```sh
$ roslaunch elfin_gazebo elfin3_empty_world.launch
```
Start up RViz with a configuration including the MoveIt! Motion Planning plugin:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch
```
If you don't want to start up RViz at the moment, just run:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch display:=false
```
Start up elfin basic api and "Elfin Control Panel" interface:
```sh
$ roslaunch elfin_basic_api elfin_basic_api.launch
```
> Tutorial about how to use MoveIt! RViz plugin: [docs/moveit_plugin_tutorial_english.md](docs/moveit_plugin_tutorial_english.md)
Tips:
Every time you want to plan a trajectory, you should set the start state to current first.
---
### Usage with real Hardware
***There are launch files available to bringup a real robot - either Elfin3, Elfin5 or Elfin10.
In the following the commands for Elfin3 are given. For Elfin5 or Elfin10, simply replace the prefix accordingly.***
Put the file *elfin_drivers.yaml*, that you got from the vendor, into the folder elfin_robot_bringup/config/.
Connect Elfin to the computer with a LAN cable. Then confirm the ethernet interface name of the connection with `ifconfig`. The default ethernet name is eth0. If the ethernet name is not eth0, you should correct the following line in the file *elfin_robot_bringup/config/elfin_drivers.yaml*
```
elfin_ethernet_name: eth0
```
Load Elfin robot model:
```sh
$ roslaunch elfin_robot_bringup elfin3_bringup.launch
```
Bring up the hardware of Elfin. Before bringing up the hardware, you should setup Linux with PREEMPT_RT properly. There is a [tutorial](https://wiki.linuxfoundation.org/realtime/documentation/howto/applications/preemptrt_setup). There are two versions of elfin EtherCAT slaves. Please bring up the hardware accordingly.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control.launch
```
or
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v2.launch
```
or you bought the RS485 end robot
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v3.launch
```
Start up RViz with a configuration including the MoveIt! Motion Planning plugin:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch
```
If you don't want to start up RViz at the moment, just run:
```sh
$ roslaunch elfin3_moveit_config moveit_planning_execution.launch display:=false
```
Start up elfin basic api and "Elfin Control Panel" interface:
```sh
$ roslaunch elfin_basic_api elfin_basic_api.launch
```
Enable the servos of Elfin with "Elfin Control Panel" interface: if there is no "Warning", just press the "Servo On" button to enable the robot. If there is "Warning", press the "Clear Fault" button first and then press the "Servo On" button.
Tutorial about how to use MoveIt! RViz plugin: [docs/moveit_plugin_tutorial_english.md](docs/moveit_plugin_tutorial_english.md)
Tips:
Every time you want to plan a trajectory, you should set the start state to current first.
Before turning the robot off, you should press the "Servo Off" button to disable the robot.
For more information about API, see [docs/API_description_english.md](docs/API_description_english.md)
<file_sep>/elfin_basic_api/src/elfin_gui.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 28 12:18:05 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
# author: <NAME>
from __future__ import division
import rospy
import math
import os # 20201209: add os path
import tf
import moveit_commander
from std_msgs.msg import Bool, String
from std_srvs.srv import SetBool, SetBoolRequest, SetBoolResponse
from elfin_robot_msgs.srv import SetString, SetStringRequest, SetStringResponse
from elfin_robot_msgs.srv import SetInt16, SetInt16Request
from elfin_robot_msgs.srv import *
import wx
from sensor_msgs.msg import JointState
from actionlib import SimpleActionClient
from control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal
import threading
import dynamic_reconfigure.client
class MyFrame(wx.Frame):
def __init__(self,parent,id):
the_size=(700, 700) # height from 550 change to 700
wx.Frame.__init__(self,parent,id,'Elfin Control Panel',pos=(250,100))
self.panel=wx.Panel(self)
font=self.panel.GetFont()
font.SetPixelSize((12, 24))
self.panel.SetFont(font)
self.listener = tf.TransformListener()
self.robot=moveit_commander.RobotCommander()
self.scene=moveit_commander.PlanningSceneInterface()
self.group=moveit_commander.MoveGroupCommander('elfin_arm')
self.controller_ns='elfin_arm_controller/'
self.elfin_driver_ns='elfin_ros_control/elfin/'
self.elfin_IO_ns='elfin_ros_control/elfin/io_port1/' # 20201126: add IO ns
self.call_read_do_req = ElfinIODReadRequest()
self.call_read_di_req = ElfinIODReadRequest()
self.call_read_do_req.data = True
self.call_read_di_req.data = True
self.call_read_do = rospy.ServiceProxy(self.elfin_IO_ns+'read_do',ElfinIODRead)
self.call_read_di = rospy.ServiceProxy(self.elfin_IO_ns+'read_di',ElfinIODRead)
# 20201126: add service for write_do
self.call_write_DO=rospy.ServiceProxy(self.elfin_IO_ns+'write_do',ElfinIODWrite)
self.elfin_basic_api_ns='elfin_basic_api/'
self.joint_names=rospy.get_param(self.controller_ns+'joints', [])
self.ref_link_name=self.group.get_planning_frame()
self.end_link_name=self.group.get_end_effector_link()
self.ref_link_lock=threading.Lock()
self.end_link_lock=threading.Lock()
self.DO_btn_lock = threading.Lock() # 20201208: add the threading lock
self.DI_show_lock = threading.Lock()
self.js_display=[0]*6 # joint_states
self.jm_button=[0]*6 # joints_minus
self.jp_button=[0]*6 # joints_plus
self.js_label=[0]*6 # joint_states
self.ps_display=[0]*6 # pcs_states
self.pm_button=[0]*6 # pcs_minus
self.pp_button=[0]*6 # pcs_plus
self.ps_label=[0]*6 # pcs_states
# 20201208: add the button array
self.DO_btn_display=[0]*4 # DO states
self.DI_display=[0]*4 # DI states
self.LED_display=[0]*4 # LED states
self.End_btn_display=[0]*4 # end button states
self.btn_height=370 # 20201126: from 390 change to 370
self.btn_path = os.path.dirname(os.path.realpath(__file__)) # 20201209: get the elfin_gui.py path
btn_lengths=[]
self.DO_DI_btn_length=[0,92,157,133] # 20201209: the length come from servo on, servo off, home, stop button
self.btn_interstice=22 # 20201209: come from btn_interstice
self.display_init()
self.key=[]
self.DO_btn=[0,0,0,0,0,0,0,0] # DO state, first four bits is DO, the other is LED
self.DI_show=[0,0,0,0,0,0,0,0] # DI state, first four bits is DI, the other is the end button
self.power_on_btn=wx.Button(self.panel, label=' Servo On ', name='Servo On',
pos=(20, self.btn_height))
btn_lengths.append(self.power_on_btn.GetSize()[0])
btn_total_length=btn_lengths[0]
self.power_off_btn=wx.Button(self.panel, label=' Servo Off ', name='Servo Off')
btn_lengths.append(self.power_off_btn.GetSize()[0])
btn_total_length+=btn_lengths[1]
self.reset_btn=wx.Button(self.panel, label=' Clear Fault ', name='Clear Fault')
btn_lengths.append(self.reset_btn.GetSize()[0])
btn_total_length+=btn_lengths[2]
self.home_btn=wx.Button(self.panel, label='Home', name='home_btn')
btn_lengths.append(self.home_btn.GetSize()[0])
btn_total_length+=btn_lengths[3]
self.stop_btn=wx.Button(self.panel, label='Stop', name='Stop')
btn_lengths.append(self.stop_btn.GetSize()[0])
btn_total_length+=btn_lengths[4]
self.btn_interstice=(550-btn_total_length)/4
btn_pos_tmp=btn_lengths[0]+self.btn_interstice+20 # 20201126: 20:init length + btn0 length + btn_inter:gap
self.power_off_btn.SetPosition((btn_pos_tmp, self.btn_height))
btn_pos_tmp+=btn_lengths[1]+self.btn_interstice
self.reset_btn.SetPosition((btn_pos_tmp, self.btn_height))
btn_pos_tmp+=btn_lengths[2]+self.btn_interstice
self.home_btn.SetPosition((btn_pos_tmp, self.btn_height))
btn_pos_tmp+=btn_lengths[3]+self.btn_interstice
self.stop_btn.SetPosition((btn_pos_tmp, self.btn_height))
self.servo_state_label=wx.StaticText(self.panel, label='Servo state:',
pos=(590, self.btn_height-10))
self.servo_state_show=wx.TextCtrl(self.panel, style=(wx.TE_CENTER |wx.TE_READONLY),
value='', pos=(600, self.btn_height+10))
self.servo_state=bool()
self.servo_state_lock=threading.Lock()
self.fault_state_label=wx.StaticText(self.panel, label='Fault state:',
pos=(590, self.btn_height+60))
self.fault_state_show=wx.TextCtrl(self.panel, style=(wx.TE_CENTER |wx.TE_READONLY),
value='', pos=(600, self.btn_height+80))
self.fault_state=bool()
self.fault_state_lock=threading.Lock()
# 20201209: add the description of end button
self.end_button_state_label=wx.StaticText(self.panel, label='END Button state',
pos=(555,self.btn_height+172))
self.reply_show_label=wx.StaticText(self.panel, label='Result:',
pos=(20, self.btn_height+260)) # 20201126: btn_height from 120 change to 260.
self.reply_show=wx.TextCtrl(self.panel, style=(wx.TE_CENTER |wx.TE_READONLY),
value='', size=(670, 30), pos=(20, self.btn_height+280))# 20201126: btn_height from 140 change to 280.
link_textctrl_length=(btn_pos_tmp-40)/2
self.ref_links_show_label=wx.StaticText(self.panel, label='Ref. link:',
pos=(20, self.btn_height+210)) # 20201126: btn_height from 60 change to 210.
self.ref_link_show=wx.TextCtrl(self.panel, style=(wx.TE_READONLY),
value=self.ref_link_name, size=(link_textctrl_length, 30),
pos=(20, self.btn_height+230)) # 20201126: btn_height from 80 change to 230.
self.end_link_show_label=wx.StaticText(self.panel, label='End link:',
pos=(link_textctrl_length+30, self.btn_height+210))# 20201126: btn_height from 80 change to 200.
self.end_link_show=wx.TextCtrl(self.panel, style=(wx.TE_READONLY),
value=self.end_link_name, size=(link_textctrl_length, 30),
pos=(link_textctrl_length+30, self.btn_height+230))
self.set_links_btn=wx.Button(self.panel, label='Set links', name='Set links')
self.set_links_btn.SetPosition((btn_pos_tmp, self.btn_height+230)) # 20201126: btn_height from 75 change to 220.
# the variables about velocity scaling
velocity_scaling_init=rospy.get_param(self.elfin_basic_api_ns+'velocity_scaling',
default=0.4)
default_velocity_scaling=str(round(velocity_scaling_init, 2))
self.velocity_setting_label=wx.StaticText(self.panel, label='Velocity Scaling',
pos=(20, self.btn_height-55)) # 20201126: btn_height from 70 change to 55
self.velocity_setting=wx.Slider(self.panel, value=int(velocity_scaling_init*100),
minValue=1, maxValue=100,
style = wx.SL_HORIZONTAL,
size=(500, 30),
pos=(45, self.btn_height-35)) # 20201126: btn_height from 70 change to 35
self.velocity_setting_txt_lower=wx.StaticText(self.panel, label='1%',
pos=(20, self.btn_height-35)) # 20201126: btn_height from 45 change to 35
self.velocity_setting_txt_upper=wx.StaticText(self.panel, label='100%',
pos=(550, self.btn_height-35))# 20201126: btn_height from 45 change to 35
self.velocity_setting_show=wx.TextCtrl(self.panel,
style=(wx.TE_CENTER|wx.TE_READONLY),
value=default_velocity_scaling,
pos=(600, self.btn_height-45))# 20201126: btn_height from 55 change to 45
self.velocity_setting.Bind(wx.EVT_SLIDER, self.velocity_setting_cb)
self.teleop_api_dynamic_reconfig_client=dynamic_reconfigure.client.Client(self.elfin_basic_api_ns,
config_callback=self.basic_api_reconfigure_cb)
self.dlg=wx.Dialog(self.panel, title='messag')
self.dlg.Bind(wx.EVT_CLOSE, self.closewindow)
self.dlg_panel=wx.Panel(self.dlg)
self.dlg_label=wx.StaticText(self.dlg_panel, label='hello', pos=(15, 15))
self.set_links_dlg=wx.Dialog(self.panel, title='Set links', size=(400, 100))
self.set_links_dlg_panel=wx.Panel(self.set_links_dlg)
self.sld_ref_link_show=wx.TextCtrl(self.set_links_dlg_panel, style=wx.TE_PROCESS_ENTER,
value='', pos=(20, 20), size=(link_textctrl_length, 30))
self.sld_end_link_show=wx.TextCtrl(self.set_links_dlg_panel, style=wx.TE_PROCESS_ENTER,
value='', pos=(20, 70), size=(link_textctrl_length, 30))
self.sld_set_ref_link_btn=wx.Button(self.set_links_dlg_panel, label='Update ref. link',
name='Update ref. link')
self.sld_set_ref_link_btn.SetPosition((link_textctrl_length+30, 15))
self.sld_set_end_link_btn=wx.Button(self.set_links_dlg_panel, label='Update end link',
name='Update end link')
self.sld_set_end_link_btn.SetPosition((link_textctrl_length+30, 65))
self.set_links_dlg.SetSize((link_textctrl_length+self.sld_set_ref_link_btn.GetSize()[0]+50, 120))
self.call_teleop_joint=rospy.ServiceProxy(self.elfin_basic_api_ns+'joint_teleop',
SetInt16)
self.call_teleop_joint_req=SetInt16Request()
self.call_teleop_cart=rospy.ServiceProxy(self.elfin_basic_api_ns+'cart_teleop',
SetInt16)
self.call_teleop_cart_req=SetInt16Request()
self.call_teleop_stop=rospy.ServiceProxy(self.elfin_basic_api_ns+'stop_teleop',
SetBool)
self.call_teleop_stop_req=SetBoolRequest()
self.call_stop=rospy.ServiceProxy(self.elfin_basic_api_ns+'stop_teleop',
SetBool)
self.call_stop_req=SetBoolRequest()
self.call_stop_req.data=True
self.stop_btn.Bind(wx.EVT_BUTTON,
lambda evt, cl=self.call_stop,
rq=self.call_stop_req :
self.call_set_bool_common(evt, cl, rq))
self.call_reset=rospy.ServiceProxy(self.elfin_driver_ns+'clear_fault', SetBool)
self.call_reset_req=SetBoolRequest()
self.call_reset_req.data=True
self.reset_btn.Bind(wx.EVT_BUTTON,
lambda evt, cl=self.call_reset,
rq=self.call_reset_req :
self.call_set_bool_common(evt, cl, rq))
self.call_power_on=rospy.ServiceProxy(self.elfin_basic_api_ns+'enable_robot', SetBool)
self.call_power_on_req=SetBoolRequest()
self.call_power_on_req.data=True
self.power_on_btn.Bind(wx.EVT_BUTTON,
lambda evt, cl=self.call_power_on,
rq=self.call_power_on_req :
self.call_set_bool_common(evt, cl, rq))
self.call_power_off=rospy.ServiceProxy(self.elfin_basic_api_ns+'disable_robot', SetBool)
self.call_power_off_req=SetBoolRequest()
self.call_power_off_req.data=True
self.power_off_btn.Bind(wx.EVT_BUTTON,
lambda evt, cl=self.call_power_off,
rq=self.call_power_off_req :
self.call_set_bool_common(evt, cl, rq))
self.call_move_homing=rospy.ServiceProxy(self.elfin_basic_api_ns+'home_teleop',
SetBool)
self.call_move_homing_req=SetBoolRequest()
self.call_move_homing_req.data=True
self.home_btn.Bind(wx.EVT_LEFT_DOWN,
lambda evt, cl=self.call_move_homing,
rq=self.call_move_homing_req :
self.call_set_bool_common(evt, cl, rq))
self.home_btn.Bind(wx.EVT_LEFT_UP,
lambda evt, mark=100:
self.release_button(evt, mark) )
self.call_set_ref_link=rospy.ServiceProxy(self.elfin_basic_api_ns+'set_reference_link', SetString)
self.call_set_end_link=rospy.ServiceProxy(self.elfin_basic_api_ns+'set_end_link', SetString)
self.set_links_btn.Bind(wx.EVT_BUTTON, self.show_set_links_dialog)
self.sld_set_ref_link_btn.Bind(wx.EVT_BUTTON, self.update_ref_link)
self.sld_set_end_link_btn.Bind(wx.EVT_BUTTON, self.update_end_link)
self.sld_ref_link_show.Bind(wx.EVT_TEXT_ENTER, self.update_ref_link)
self.sld_end_link_show.Bind(wx.EVT_TEXT_ENTER, self.update_end_link)
self.action_client=SimpleActionClient(self.controller_ns+'follow_joint_trajectory',
FollowJointTrajectoryAction)
self.action_goal=FollowJointTrajectoryGoal()
self.action_goal.trajectory.joint_names=self.joint_names
self.SetMinSize(the_size)
self.SetMaxSize(the_size)
def display_init(self):
js_pos=[20, 20]
js_btn_length=[70, 70, 61, 80]
js_distances=[10, 20, 10, 26]
dis_h=50
for i in xrange(len(self.js_display)):
self.jp_button[i]=wx.Button(self.panel,
label='J'+str(i+1)+' +',
pos=(js_pos[0],
js_pos[1]+(5-i)*dis_h),
size=(70,40))
dis_tmp=js_btn_length[0]+js_distances[0]
self.jp_button[i].Bind(wx.EVT_LEFT_DOWN,
lambda evt, mark=i+1 : self.teleop_joints(evt, mark) )
self.jp_button[i].Bind(wx.EVT_LEFT_UP,
lambda evt, mark=i+1 : self.release_button(evt, mark) )
self.jm_button[i]=wx.Button(self.panel,
label='J'+str(i+1)+' -',
pos=(js_pos[0]+dis_tmp,
js_pos[1]+(5-i)*dis_h),
size=(70,40))
dis_tmp+=js_btn_length[1]+js_distances[1]
self.jm_button[i].Bind(wx.EVT_LEFT_DOWN,
lambda evt, mark=-1*(i+1) : self.teleop_joints(evt, mark) )
self.jm_button[i].Bind(wx.EVT_LEFT_UP,
lambda evt, mark=-1*(i+1) : self.release_button(evt, mark) )
pos_js_label=(js_pos[0]+dis_tmp, js_pos[1]+(5-i)*dis_h)
self.js_label[i]=wx.StaticText(self.panel,
label='J'+str(i+1)+'/deg:',
pos=pos_js_label)
self.js_label[i].SetPosition((pos_js_label[0], pos_js_label[1]+abs(40-self.js_label[i].GetSize()[1])/2))
dis_tmp+=js_btn_length[2]+js_distances[2]
pos_js_display=(js_pos[0]+dis_tmp, js_pos[1]+(5-i)*dis_h)
self.js_display[i]=wx.TextCtrl(self.panel,
style=(wx.TE_CENTER |wx.TE_READONLY),
value=' 0000.00 ',
pos=pos_js_display)
self.js_display[i].SetPosition((pos_js_display[0], pos_js_display[1]+abs(40-self.js_display[i].GetSize()[1])/2))
dis_tmp+=js_btn_length[3]+js_distances[3]
ps_pos=[js_pos[0]+dis_tmp, 20]
ps_btn_length=[70, 70, 53, 80]
ps_distances=[10, 20, 10, 20]
pcs_btn_label=['X', 'Y', 'Z', 'Rx', 'Ry', 'Rz']
pcs_label=['X', 'Y', 'Z', 'R', 'P', 'Y']
unit_label=['/mm:', '/mm:', '/mm:', '/deg:', '/deg:', '/deg:']
for i in xrange(len(self.ps_display)):
self.pp_button[i]=wx.Button(self.panel,
label=pcs_btn_label[i]+' +',
pos=(ps_pos[0],
ps_pos[1]+(5-i)*dis_h),
size=(70,40))
dis_tmp=ps_btn_length[0]+ps_distances[0]
self.pp_button[i].Bind(wx.EVT_LEFT_DOWN,
lambda evt, mark=i+1 : self.teleop_pcs(evt, mark) )
self.pp_button[i].Bind(wx.EVT_LEFT_UP,
lambda evt, mark=i+1 : self.release_button(evt, mark) )
self.pm_button[i]=wx.Button(self.panel,
label=pcs_btn_label[i]+' -',
pos=(ps_pos[0]+dis_tmp,
ps_pos[1]+(5-i)*dis_h),
size=(70,40))
dis_tmp+=ps_btn_length[1]+ps_distances[1]
self.pm_button[i].Bind(wx.EVT_LEFT_DOWN,
lambda evt, mark=-1*(i+1) : self.teleop_pcs(evt, mark) )
self.pm_button[i].Bind(wx.EVT_LEFT_UP,
lambda evt, mark=-1*(i+1) : self.release_button(evt, mark) )
pos_ps_label=(ps_pos[0]+dis_tmp, ps_pos[1]+(5-i)*dis_h)
self.ps_label[i]=wx.StaticText(self.panel,
label=pcs_label[i]+unit_label[i],
pos=pos_ps_label)
self.ps_label[i].SetPosition((pos_ps_label[0], pos_ps_label[1]+abs(40-self.ps_label[i].GetSize()[1])/2))
dis_tmp+=ps_btn_length[2]+ps_distances[2]
pos_ps_display=(ps_pos[0]+dis_tmp, ps_pos[1]+(5-i)*dis_h)
self.ps_display[i]=wx.TextCtrl(self.panel,
style=(wx.TE_CENTER |wx.TE_READONLY),
value='',
pos=pos_ps_display)
self.ps_display[i].SetPosition((pos_ps_display[0], pos_ps_display[1]+abs(40-self.ps_display[i].GetSize()[1])/2))
dis_tmp+=ps_btn_length[3]+ps_distances[3]
# 20201209: add the DO,LED,DI,end button.
for i in xrange(len(self.DO_btn_display)):
self.DO_btn_display[i]=wx.Button(self.panel,label='DO'+str(i),
pos=(20+(self.DO_DI_btn_length[i]+self.btn_interstice)*i,
self.btn_height+40))
self.DO_btn_display[i].Bind(wx.EVT_BUTTON,
lambda evt,marker=i,cl=self.call_write_DO :
self.call_write_DO_command(evt,marker,cl))
self.DI_display[i]=wx.TextCtrl(self.panel, style=(wx.TE_CENTER | wx.TE_READONLY), value='DI'+str(i),
size=(self.DO_btn_display[i].GetSize()),
pos=(20+(self.DO_DI_btn_length[i]+self.btn_interstice)*i,self.btn_height+80))
self.LED_display[i]=wx.Button(self.panel,label='LED'+str(i),
pos=(20+(self.DO_DI_btn_length[i]+self.btn_interstice)*i,self.btn_height+120))
self.LED_display[i].Bind(wx.EVT_BUTTON,
lambda evt, marker=4+i, cl=self.call_write_DO :
self.call_write_DO_command(evt, marker,cl))
png=wx.Image(self.btn_path+'/btn_icon/End_btn'+str(i)+'_low.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.End_btn_display[i]=wx.StaticBitmap(self.panel,-1,png,
pos=(40+(self.DO_DI_btn_length[i]+self.btn_interstice)*i,
self.btn_height+160))
def velocity_setting_cb(self, event):
current_velocity_scaling=self.velocity_setting.GetValue()*0.01
self.teleop_api_dynamic_reconfig_client.update_configuration({'velocity_scaling': current_velocity_scaling})
wx.CallAfter(self.update_velocity_scaling_show, current_velocity_scaling)
def basic_api_reconfigure_cb(self, config):
if self.velocity_setting_show.GetValue()!=config.velocity_scaling:
self.velocity_setting.SetValue(int(config.velocity_scaling*100))
wx.CallAfter(self.update_velocity_scaling_show, config.velocity_scaling)
def action_stop(self):
self.action_client.wait_for_server(timeout=rospy.Duration(secs=0.5))
self.action_goal.trajectory.header.stamp.secs=0
self.action_goal.trajectory.header.stamp.nsecs=0
self.action_goal.trajectory.points=[]
self.action_client.send_goal(self.action_goal)
def teleop_joints(self,event,mark):
self.call_teleop_joint_req.data=mark
resp=self.call_teleop_joint.call(self.call_teleop_joint_req)
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
def teleop_pcs(self,event,mark):
self.call_teleop_cart_req.data=mark
resp=self.call_teleop_cart.call(self.call_teleop_cart_req)
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
def release_button(self, event, mark):
self.call_teleop_stop_req.data=True
resp=self.call_teleop_stop.call(self.call_teleop_stop_req)
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
def call_set_bool_common(self, event, client, request):
btn=event.GetEventObject()
check_list=['Servo On', 'Servo Off', 'Clear Fault']
# Check servo state
if btn.GetName()=='Servo On':
servo_enabled=bool()
if self.servo_state_lock.acquire():
servo_enabled=self.servo_state
self.servo_state_lock.release()
if servo_enabled:
resp=SetBoolResponse()
resp.success=False
resp.message='Robot is already enabled'
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
return
# Check fault state
if btn.GetName()=='Clear Fault':
fault_flag=bool()
if self.fault_state_lock.acquire():
fault_flag=self.fault_state
self.fault_state_lock.release()
if not fault_flag:
resp=SetBoolResponse()
resp.success=False
resp.message='There is no fault now'
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
return
# Check if the button is in check list
if btn.GetName() in check_list:
self.show_message_dialog(btn.GetName(), client, request)
else:
try:
resp=client.call(request)
wx.CallAfter(self.update_reply_show, resp)
except rospy.ServiceException, e:
resp=SetBoolResponse()
resp.success=False
resp.message='no such service in simulation'
wx.CallAfter(self.update_reply_show, resp)
event.Skip()
def thread_bg(self, msg, client, request):
wx.CallAfter(self.show_dialog)
if msg=='Servo Off':
self.action_stop()
rospy.sleep(1)
try:
resp=client.call(request)
wx.CallAfter(self.update_reply_show, resp)
except rospy.ServiceException, e:
resp=SetBoolResponse()
resp.success=False
resp.message='no such service in simulation'
wx.CallAfter(self.update_reply_show, resp)
wx.CallAfter(self.destroy_dialog)
# 20201201: add function for processing value to DO_btn
def process_DO_btn(self,value):
if self.DO_btn_lock.acquire():
for i in range(0,8):
tmp = (value >> (12 + i)) & 0x01
self.DO_btn[i]=tmp
self.DO_btn_lock.release()
# 20201201: add function to read DO.
def call_read_DO_command(self):
try:
client = self.call_read_do
val = client.call(self.call_read_do_req).digital_input
self.process_DO_btn(val)
except rospy.ServiceException, e:
resp=ElfinIODReadResponse()
resp.digital_input=0x0000
# 20201201: add function for processing value
def process_DI_btn(self,value):
if self.DI_show_lock.acquire():
if value > 0:
for i in range(0,8):
tmp = (value >> (16 + i)) & 0x01
self.DI_show[i]=tmp
else:
self.DI_show = [0,0,0,0,0,0,0,0]
self.DI_show_lock.release()
# 20201201: add function to read DI.
def call_read_DI_command(self):
try:
client = self.call_read_di
val = client.call(self.call_read_di_req).digital_input
self.process_DI_btn(val)
except rospy.ServiceException, e:
resp=ElfinIODReadResponse()
resp.digital_input=0x0000
# 20201202: add function to read DO and DI.
def monitor_DO_DI(self,evt):
self.call_read_DI_command()
self.call_read_DO_command()
# 20201126: add function to write DO.
def call_write_DO_command(self, event, marker, client):
self.justification_DO_btn(marker)
request = 0
try:
self.DO_btn_lock.acquire()
for i in range(0,8):
request = request + self.DO_btn[i]*pow(2,i)
resp=client.call(request << 12)
self.DO_btn_lock.release()
except rospy.ServiceException, e:
self.DO_btn_lock.release()
resp=ElfinIODWriteResponse()
resp.success=False
self.justification_DO_btn(marker)
rp=SetBoolResponse()
rp.success=False
rp.message='no such service for DO control'
wx.CallAfter(self.update_reply_show, rp)
# 20201127: add justification to DO_btn
def justification_DO_btn(self,marker):
self.DO_btn_lock.acquire()
if 0 == self.DO_btn[marker]:
self.DO_btn[marker] = 1
else:
self.DO_btn[marker] = 0
self.DO_btn_lock.release()
# 20201201: add function to set DO_btn colour
def set_DO_btn_colour(self):
self.DO_btn_lock.acquire()
for i in range(0,4):
if 0 == self.DO_btn[i]:
self.DO_btn_display[i].SetBackgroundColour(wx.NullColour)
else:
self.DO_btn_display[i].SetBackgroundColour(wx.Colour(200,225,200))
self.DO_btn_lock.release()
# 20201201: add function to set DI_show colour
def set_DI_show_colour(self):
self.DI_show_lock.acquire()
for i in range(0,4):
if 0 == self.DI_show[i]:
self.DI_display[i].SetBackgroundColour(wx.NullColour)
else:
self.DI_display[i].SetBackgroundColour(wx.Colour(200,225,200))
self.DI_show_lock.release()
# 20201207: add function to set LED colour
def set_LED_show_colour(self):
self.DO_btn_lock.acquire()
for i in range(4,8):
if 0 == self.DO_btn[i]:
self.LED_display[i-4].SetBackgroundColour(wx.NullColour)
else:
self.LED_display[i-4].SetBackgroundColour(wx.Colour(200,225,200))
self.DO_btn_lock.release()
# 20201207: add function to set End_btn colour
def set_End_btn_colour(self):
self.DI_show_lock.acquire()
for i in range(4,8):
if 0 == self.DI_show[i]:
png=wx.Image(self.btn_path+'/btn_icon/End_btn'+str(i-4)+'_low.png',wx.BITMAP_TYPE_PNG)
self.End_btn_display[i-4].SetBitmap(wx.BitmapFromImage(png))
else:
png=wx.Image(self.btn_path+'/btn_icon/End_btn'+str(i-4)+'_high.png',wx.BITMAP_TYPE_PNG)
self.End_btn_display[i-4].SetBitmap(wx.BitmapFromImage(png))
self.DI_show_lock.release()
def set_color(self, evt):
wx.CallAfter(self.set_DO_btn_colour)
wx.CallAfter(self.set_DI_show_colour)
wx.CallAfter(self.set_LED_show_colour)
wx.CallAfter(self.set_End_btn_colour)
def show_message_dialog(self, message, cl, rq):
msg='executing ['+message+']'
self.dlg_label.SetLabel(msg)
lable_size=[]
lable_size.append(self.dlg_label.GetSize()[0])
lable_size.append(self.dlg_label.GetSize()[1])
self.dlg.SetSize((lable_size[0]+30, lable_size[1]+30))
t=threading.Thread(target=self.thread_bg, args=(message, cl, rq,))
t.start()
def show_dialog(self):
self.dlg.SetPosition((self.GetPosition()[0]+250,
self.GetPosition()[1]+250))
self.dlg.ShowModal()
def destroy_dialog(self):
self.dlg.EndModal(0)
def closewindow(self,event):
pass
def show_set_links_dialog(self, evt):
self.sld_ref_link_show.SetValue(self.ref_link_name)
self.sld_end_link_show.SetValue(self.end_link_name)
self.set_links_dlg.SetPosition((self.GetPosition()[0]+150,
self.GetPosition()[1]+250))
self.set_links_dlg.ShowModal()
def update_ref_link(self, evt):
request=SetStringRequest()
request.data=self.sld_ref_link_show.GetValue()
resp=self.call_set_ref_link.call(request)
wx.CallAfter(self.update_reply_show, resp)
def update_end_link(self, evt):
request=SetStringRequest()
request.data=self.sld_end_link_show.GetValue()
resp=self.call_set_end_link.call(request)
wx.CallAfter(self.update_reply_show, resp)
def updateDisplay(self, msg):
for i in xrange(len(self.js_display)):
self.js_display[i].SetValue(msg[i])
for i in xrange(len(self.ps_display)):
self.ps_display[i].SetValue(msg[i+6])
if self.ref_link_lock.acquire():
ref_link=self.ref_link_name
self.ref_link_lock.release()
if self.end_link_lock.acquire():
end_link=self.end_link_name
self.end_link_lock.release()
self.ref_link_show.SetValue(ref_link)
self.end_link_show.SetValue(end_link)
def update_reply_show(self,msg):
if msg.success:
self.reply_show.SetBackgroundColour(wx.Colour(200, 225, 200))
else:
self.reply_show.SetBackgroundColour(wx.Colour(225, 200, 200))
self.reply_show.SetValue(msg.message)
def update_servo_state(self, msg):
if msg.data:
self.servo_state_show.SetBackgroundColour(wx.Colour(200, 225, 200))
self.servo_state_show.SetValue('Enabled')
else:
self.servo_state_show.SetBackgroundColour(wx.Colour(225, 200, 200))
self.servo_state_show.SetValue('Disabled')
def update_fault_state(self, msg):
if msg.data:
self.fault_state_show.SetBackgroundColour(wx.Colour(225, 200, 200))
self.fault_state_show.SetValue('Warning')
else:
self.fault_state_show.SetBackgroundColour(wx.Colour(200, 225, 200))
self.fault_state_show.SetValue('No Fault')
def update_velocity_scaling_show(self, msg):
self.velocity_setting_show.SetValue(str(round(msg, 2)*100)+'%') # 20201127: change the show format
def js_call_back(self, data):
while not rospy.is_shutdown():
try:
self.listener.waitForTransform(self.group.get_planning_frame(),
self.group.get_end_effector_link(),
rospy.Time(0), rospy.Duration(100))
(xyz,qua) = self.listener.lookupTransform(self.group.get_planning_frame(),
self.group.get_end_effector_link(),
rospy.Time(0))
break
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
continue
rpy=tf.transformations.euler_from_quaternion(qua)
for i in xrange(len(data.position)):
self.key.append(str(round(data.position[i]*180/math.pi, 2)))
self.key.append(str(round(xyz[0]*1000, 2)))
self.key.append(str(round(xyz[1]*1000, 2)))
self.key.append(str(round(xyz[2]*1000, 2)))
self.key.append(str(round(rpy[0]*180/math.pi, 2)))
self.key.append(str(round(rpy[1]*180/math.pi, 2)))
self.key.append(str(round(rpy[2]*180/math.pi, 2)))
wx.CallAfter(self.updateDisplay, self.key)
self.key=[]
def monitor_status(self, evt):
self.key=[]
current_joint_values=self.group.get_current_joint_values()
for i in xrange(len(current_joint_values)):
self.key.append(str(round(current_joint_values[i]*180/math.pi, 2)))
if self.ref_link_lock.acquire():
ref_link=self.ref_link_name
self.ref_link_lock.release()
if self.end_link_lock.acquire():
end_link=self.end_link_name
self.end_link_lock.release()
while not rospy.is_shutdown():
try:
self.listener.waitForTransform(ref_link, end_link, rospy.Time(0), rospy.Duration(100))
(xyz,qua) = self.listener.lookupTransform(ref_link, end_link, rospy.Time(0))
break
except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
continue
rpy=tf.transformations.euler_from_quaternion(qua)
self.key.append(str(round(xyz[0]*1000, 2)))
self.key.append(str(round(xyz[1]*1000, 2)))
self.key.append(str(round(xyz[2]*1000, 2)))
self.key.append(str(round(rpy[0]*180/math.pi, 2)))
self.key.append(str(round(rpy[1]*180/math.pi, 2)))
self.key.append(str(round(rpy[2]*180/math.pi, 2)))
wx.CallAfter(self.updateDisplay, self.key)
def servo_state_cb(self, data):
if self.servo_state_lock.acquire():
self.servo_state=data.data
self.servo_state_lock.release()
wx.CallAfter(self.update_servo_state, data)
def fault_state_cb(self, data):
if self.fault_state_lock.acquire():
self.fault_state=data.data
self.fault_state_lock.release()
wx.CallAfter(self.update_fault_state, data)
def ref_link_name_cb(self, data):
if self.ref_link_lock.acquire():
self.ref_link_name=data.data
self.ref_link_lock.release()
def end_link_name_cb(self, data):
if self.end_link_lock.acquire():
self.end_link_name=data.data
self.end_link_lock.release()
def listen(self):
rospy.Subscriber(self.elfin_driver_ns+'enable_state', Bool, self.servo_state_cb)
rospy.Subscriber(self.elfin_driver_ns+'fault_state', Bool, self.fault_state_cb)
rospy.Subscriber(self.elfin_basic_api_ns+'reference_link_name', String, self.ref_link_name_cb)
rospy.Subscriber(self.elfin_basic_api_ns+'end_link_name', String, self.end_link_name_cb)
rospy.Timer(rospy.Duration(nsecs=50000000), self.monitor_DO_DI)
rospy.Timer(rospy.Duration(nsecs=50000000), self.set_color)
rospy.Timer(rospy.Duration(nsecs=50000000), self.monitor_status)
if __name__=='__main__':
rospy.init_node('elfin_gui')
app=wx.App(False)
myframe=MyFrame(parent=None,id=-1)
myframe.Show(True)
myframe.listen()
app.MainLoop()
<file_sep>/docs/VelTrqFF_HWI_english.md
Velocity + Torque feed forward mode hardware interface
====
A controller with the hardware interface *'elfin_hardware_interface::PosVelTrqJointInterface'* can control the Elfin in velocity + torque feed forward mode. **Only a robot with the version 2 of elfin EtherCAT slaves supports this hardware interface**.
There is a sample example in the *elfin_ros_controllers* package: *'elfin_pos_vel_controllers/JointTrajectoryController'*. You can use it by the following method.
1. Change the controller type in the file *elfin_robot_bringup/config/elfin_arm_control.yaml*:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: elfin_pos_vel_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
feedforward velocity: desired velocity
feedforward torque: 0
2. Start the robot arm normally as described in the [README_english.md](../README_english.md)<file_sep>/elfin_ikfast_plugins/elfin5_l_ikfast_plugin/elfin5_l_ikfast_plugin/update_ikfast_plugin.sh
search_mode=OPTIMIZE_MAX_JOINT
srdf_filename=elfin5_l.srdf
robot_name_in_srdf=elfin5_l
moveit_config_pkg=elfin5_l_moveit_config
robot_name=elfin5_l
planning_group_name=elfin_arm
ikfast_plugin_pkg=elfin5_l_ikfast_plugin
base_link_name=elfin_base_link
eef_link_name=elfin_end_link
ikfast_output_path=/home/cjw/test_ws/src/elfin_robot/elfin5_l_ikfast_plugin/src/elfin5_l_elfin_arm_ikfast_solver.cpp
rosrun moveit_kinematics create_ikfast_moveit_plugin.py\
--search_mode=$search_mode\
--srdf_filename=$srdf_filename\
--robot_name_in_srdf=$robot_name_in_srdf\
--moveit_config_pkg=$moveit_config_pkg\
$robot_name\
$planning_group_name\
$ikfast_plugin_pkg\
$base_link_name\
$eef_link_name\
$ikfast_output_path
<file_sep>/elfin_ethercat_driver/include/elfin_ethercat_driver/elfin_ethercat_client.h
/*
Created on Mon Sep 17 09:42:14 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_ETHERCAT_CLIENT_H
#define ELFIN_ETHERCAT_CLIENT_H
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Bool.h>
#include <std_srvs/SetBool.h>
#include <vector>
#include <elfin_ethercat_driver/elfin_ethercat_manager.h>
#include <pthread.h>
#include <time.h>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
namespace elfin_txpdo
{
const int AXIS1_STATUSWORD_L16=0;
const int AXIS1_ACTTORQUE_H16=0;
const int AXIS1_ACTPOSITION=1;
const int AXIS1_ACTVELOCITY_L16=2;
const int AXIS1_ERRORCODE_L16=3;
const int AXIS1_MODES_OF_OPERATION_DISPLAY_BYTE2=3;
const int AXIS2_STATUSWORD_L16=4;
const int AXIS2_ACTTORQUE_H16=4;
const int AXIS2_ACTPOSITION=5;
const int AXIS2_ACTVELOCITY_L16=6;
const int AXIS2_ERRORCODE_L16=7;
const int AXIS2_MODES_OF_OPERATION_DISPLAY_BYTE2=7;
}
namespace elfin_rxpdo
{
const int AXIS1_CONTROLWORD_L16=0;
const int AXIS1_MODES_OF_OPERATION_BYTE2=0;
const int AXIS1_TARGET_POSITION=1;
const int AXIS1_TARGET_TORQUE_L16=2;
const int AXIS1_VELFF_H16=2;
const int AXIS2_CONTROLWORD_L16=3;
const int AXIS2_MODES_OF_OPERATION_BYTE2=3;
const int AXIS2_TARGET_POSITION=4;
const int AXIS2_TARGET_TORQUE_L16=5;
const int AXIS2_VELFF_H16=5;
}
namespace elfin_ethercat_driver
{
class ElfinEtherCATClient
{
private:
EtherCatManager* manager_; // old namespace
ros::NodeHandle n_;
ros::Publisher pub_input_;
ros::Publisher pub_output_;
ros::ServiceServer server_enable_;
ros::ServiceServer server_reset_fault_;
ros::ServiceServer server_open_brake_;
ros::ServiceServer server_close_brake_;
std_msgs::String txpdo_msg_;
std_msgs::String rxpdo_msg_;
std::vector<ElfinPDOunit> pdo_input; // txpdo old namespace
std::vector<ElfinPDOunit> pdo_output; //rxpdo old namespace
int slave_no_;
public:
ElfinEtherCATClient(EtherCatManager* manager, int slave_no); // old namespace
~ElfinEtherCATClient();
int32_t readInput_unit(int n);
int32_t readOutput_unit(int n);
void writeOutput_unit(int n, int32_t val);
int16_t readInput_half_unit(int n, bool high_16);
int16_t readOutput_half_unit(int n, bool high_16);
void writeOutput_half_unit(int n, int16_t val, bool high_16);
int8_t readInput_unit_byte(int n, bool high_16, bool high_8);
int8_t readOutput_unit_byte(int n, bool high_16, bool high_8);
void writeOutput_unit_byte(int n, int8_t val, bool high_16, bool high_8);
int32_t getAxis1PosCnt();
int32_t getAxis2PosCnt();
void setAxis1PosCnt(int32_t pos_cnt);
void setAxis2PosCnt(int32_t pos_cnt);
int16_t getAxis1VelCnt();
int16_t getAxis2VelCnt();
void setAxis1VelFFCnt(int16_t vff_cnt);
void setAxis2VelFFCnt(int16_t vff_cnt);
int16_t getAxis1TrqCnt();
int16_t getAxis2TrqCnt();
void setAxis1TrqCnt(int16_t trq_cnt);
void setAxis2TrqCnt(int16_t trq_cnt);
void readInput();
void readOutput();
void writeOutput();
std::string getTxPDO();
std::string getRxPDO();
std::string getCurrentPosition();
void getActPosCounts(int32_t &pos_act_count_1, int32_t &pos_act_count_2);
void getCmdPosCounts(int32_t &pos_cmd_count_1, int32_t &pos_cmd_count_2);
void pubInput();
void pubOutput();
void clearPoseFault();
bool recognizePose();
bool isEnabled();
static void *setEnable(void *threadarg);
static void *setDisable(void *threadarg);
static void *recognizePoseCmd(void *threadarg);
bool isWarning();
void resetFault();
bool inPosMode();
bool inTrqMode();
bool inPosBasedMode();
void setPosMode();
void setTrqMode();
bool enable_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool reset_fault_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool open_brake_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool close_brake_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
};
}
#endif
<file_sep>/docs/VelTrqFF_HWI.md
速度+力矩前馈模式硬件接口
====
使用硬件接口*elfin_hardware_interface::PosVelTrqJointInterface*的控制器可以对Elfin进行速度+力矩前馈模式控制。**只有使用Version 2版本EtherCAT从站的Elfin有这个接口**。
*elfin_ros_controllers*软件包提供了一个简单的例子: *elfin_pos_vel_controllers/JointTrajectoryController*,它的使用方法如下:
1. 更改elfin_robot_bringup/config/elfin_arm_control.yaml中的控制器类型:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: elfin_pos_vel_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
前馈速度: 目标速度
前馈力矩: 0
2. 按[README.md](../README.md)的说明正常启动机械臂。<file_sep>/docs/TorqueFF_HWI.md
力矩前馈模式硬件接口
====
使用硬件接口*elfin_hardware_interface::PosTrqJointInterface*的控制器可以对Elfin进行力矩前馈模式控制。*elfin_ros_controllers*软件包提供了一个简单的例子: *elfin_pos_trq_controllers/JointTrajectoryController*,它的使用方法如下:
1. 更改elfin_robot_bringup/config/elfin_arm_control.yaml中的控制器类型:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: elfin_pos_trq_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ velocity_ff:
+ elfin_joint1: 1
+ elfin_joint2: 1
+ elfin_joint3: 1
+ elfin_joint4: 1
+ elfin_joint5: 1
+ elfin_joint6: 1
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
velocity_ff: 此参数会与相应轴的目标速度相乘,以得到相应轴的与速度相关的前馈力矩。
2. 按[README.md](../README.md)的说明正常启动机械臂。<file_sep>/elfin_kinematic_solver/src/elfin5_ikfast_simple_api.cpp
/*
Created on Wed Dec 05 15:25:32 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include<elfin_kinematic_solver/elfin_kinematic_solver.h>
namespace elfin5_ikfast_simple_api {
#define IKFAST_NO_MAIN // Don't include main() from IKFast
/// \brief The types of inverse kinematics parameterizations supported.
///
/// The minimum degree of freedoms required is set in the upper 4 bits of each type.
/// The number of values used to represent the parameterization ( >= dof ) is the next 4 bits.
/// The lower bits contain a unique id of the type.
enum IkParameterizationType
{
IKP_None = 0,
IKP_Transform6D = 0x67000001, ///< end effector reaches desired 6D transformation
IKP_Rotation3D = 0x34000002, ///< end effector reaches desired 3D rotation
IKP_Translation3D = 0x33000003, ///< end effector origin reaches desired 3D translation
IKP_Direction3D = 0x23000004, ///< direction on end effector coordinate system reaches desired direction
IKP_Ray4D = 0x46000005, ///< ray on end effector coordinate system reaches desired global ray
IKP_Lookat3D = 0x23000006, ///< direction on end effector coordinate system points to desired 3D position
IKP_TranslationDirection5D = 0x56000007, ///< end effector origin and direction reaches desired 3D translation and
/// direction. Can be thought of as Ray IK where the origin of the ray must
/// coincide.
IKP_TranslationXY2D = 0x22000008, ///< 2D translation along XY plane
IKP_TranslationXYOrientation3D = 0x33000009, ///< 2D translation along XY plane and 1D rotation around Z axis. The
/// offset of the rotation is measured starting at +X, so at +X is it 0,
/// at +Y it is pi/2.
IKP_TranslationLocalGlobal6D = 0x3600000a, ///< local point on end effector origin reaches desired 3D global point
IKP_TranslationXAxisAngle4D = 0x4400000b, ///< end effector origin reaches desired 3D translation, manipulator
/// direction makes a specific angle with x-axis like a cone, angle is from
/// 0-pi. Axes defined in the manipulator base link's coordinate system)
IKP_TranslationYAxisAngle4D = 0x4400000c, ///< end effector origin reaches desired 3D translation, manipulator
/// direction makes a specific angle with y-axis like a cone, angle is from
/// 0-pi. Axes defined in the manipulator base link's coordinate system)
IKP_TranslationZAxisAngle4D = 0x4400000d, ///< end effector origin reaches desired 3D translation, manipulator
/// direction makes a specific angle with z-axis like a cone, angle is from
/// 0-pi. Axes are defined in the manipulator base link's coordinate system.
IKP_TranslationXAxisAngleZNorm4D = 0x4400000e, ///< end effector origin reaches desired 3D translation, manipulator
/// direction needs to be orthogonal to z-axis and be rotated at a
/// certain angle starting from the x-axis (defined in the manipulator
/// base link's coordinate system)
IKP_TranslationYAxisAngleXNorm4D = 0x4400000f, ///< end effector origin reaches desired 3D translation, manipulator
/// direction needs to be orthogonal to x-axis and be rotated at a
/// certain angle starting from the y-axis (defined in the manipulator
/// base link's coordinate system)
IKP_TranslationZAxisAngleYNorm4D = 0x44000010, ///< end effector origin reaches desired 3D translation, manipulator
/// direction needs to be orthogonal to y-axis and be rotated at a
/// certain angle starting from the z-axis (defined in the manipulator
/// base link's coordinate system)
IKP_NumberOfParameterizations = 16, ///< number of parameterizations (does not count IKP_None)
IKP_VelocityDataBit =
0x00008000, ///< bit is set if the data represents the time-derivate velocity of an IkParameterization
IKP_Transform6DVelocity = IKP_Transform6D | IKP_VelocityDataBit,
IKP_Rotation3DVelocity = IKP_Rotation3D | IKP_VelocityDataBit,
IKP_Translation3DVelocity = IKP_Translation3D | IKP_VelocityDataBit,
IKP_Direction3DVelocity = IKP_Direction3D | IKP_VelocityDataBit,
IKP_Ray4DVelocity = IKP_Ray4D | IKP_VelocityDataBit,
IKP_Lookat3DVelocity = IKP_Lookat3D | IKP_VelocityDataBit,
IKP_TranslationDirection5DVelocity = IKP_TranslationDirection5D | IKP_VelocityDataBit,
IKP_TranslationXY2DVelocity = IKP_TranslationXY2D | IKP_VelocityDataBit,
IKP_TranslationXYOrientation3DVelocity = IKP_TranslationXYOrientation3D | IKP_VelocityDataBit,
IKP_TranslationLocalGlobal6DVelocity = IKP_TranslationLocalGlobal6D | IKP_VelocityDataBit,
IKP_TranslationXAxisAngle4DVelocity = IKP_TranslationXAxisAngle4D | IKP_VelocityDataBit,
IKP_TranslationYAxisAngle4DVelocity = IKP_TranslationYAxisAngle4D | IKP_VelocityDataBit,
IKP_TranslationZAxisAngle4DVelocity = IKP_TranslationZAxisAngle4D | IKP_VelocityDataBit,
IKP_TranslationXAxisAngleZNorm4DVelocity = IKP_TranslationXAxisAngleZNorm4D | IKP_VelocityDataBit,
IKP_TranslationYAxisAngleXNorm4DVelocity = IKP_TranslationYAxisAngleXNorm4D | IKP_VelocityDataBit,
IKP_TranslationZAxisAngleYNorm4DVelocity = IKP_TranslationZAxisAngleYNorm4D | IKP_VelocityDataBit,
IKP_UniqueIdMask = 0x0000ffff, ///< the mask for the unique ids
IKP_CustomDataBit = 0x00010000, ///< bit is set if the ikparameterization contains custom data, this is only used
/// when serializing the ik parameterizations
};
// Code generated by IKFast56/61
#include "elfin5_ikfast_solver_ebl.cpp"
int num_joints_=6;
int solve(const Eigen::Vector3d &trans, const Eigen::Matrix3d &orient, const std::vector<double> &vfree,
IkSolutionList<IkReal>& solutions)
{
solutions.Clear();
double point[3];
point[0]=trans(0);
point[1]=trans(1);
point[2]=trans(2);
double vals[9];
vals[0] = orient(0, 0);
vals[1] = orient(0, 1);
vals[2] = orient(0, 2);
vals[3] = orient(1, 0);
vals[4] = orient(1, 1);
vals[5] = orient(1, 2);
vals[6] = orient(2, 0);
vals[7] = orient(2, 1);
vals[8] = orient(2, 2);
ComputeIk(point, vals, vfree.size() > 0 ? &vfree[0] : NULL, solutions);
return solutions.GetNumSolutions();
}
void getSolution(const IkSolutionList<IkReal>& solutions, int i, std::vector<double>& solution)
{
solution.clear();
solution.resize(num_joints_);
// IKFast56/61
const IkSolutionBase<IkReal>& sol = solutions.GetSolution(i);
std::vector<IkReal> vsolfree(sol.GetFree().size());
sol.GetSolution(&solution[0], vsolfree.size() > 0 ? &vsolfree[0] : NULL);
}
bool Elfin5KinematicSolver::getPositionIK(const Eigen::Vector3d& trans, const Eigen::Matrix3d& orient, const std::vector<double>& vfree,
const std::vector<double>& seed_state, std::vector<double>& solution)
{
if(seed_state.size()!=6)
{
return false;
}
IkSolutionList<IkReal> solutions;
int numsol = solve(trans, orient, vfree, solutions);
std::vector<LimitObeyingSol> solutions_obey_limits;
LimitObeyingSol solution_tmp;
if (numsol)
{
std::vector<double> solution_obey_limits;
for (std::size_t s = 0; s < numsol; ++s)
{
// All elements of this solution obey limits
getSolution(solutions, s, solution_obey_limits);
double dist_from_seed = 0.0;
for (std::size_t i = 0; i < seed_state.size(); ++i)
{
dist_from_seed += fabs(seed_state[i] - solution_obey_limits[i]);
}
solution_tmp.value=solution_obey_limits;
solution_tmp.dist_from_seed=dist_from_seed;
solutions_obey_limits.push_back(solution_tmp);
}
}
if (!solutions_obey_limits.empty())
{
std::sort(solutions_obey_limits.begin(), solutions_obey_limits.end());
solution = solutions_obey_limits[0].value;
return true;
}
return false;
}
bool Elfin5KinematicSolver::getPositionFK(const std::vector<double>& joint_angles, Eigen::Vector3d& trans, Eigen::Matrix3d& orient)
{
if(joint_angles.size()!=6)
{
return false;
}
IkReal eerot[9], eetrans[3];
IkReal angles[joint_angles.size()];
for (unsigned char i = 0; i < joint_angles.size(); i++)
angles[i] = joint_angles[i];
// IKFast56/61
ComputeFk(angles, eetrans, eerot);
trans << eetrans[0], eetrans[1], eetrans[2];
orient << eerot[0], eerot[1], eerot[2],
eerot[3], eerot[4], eerot[5],
eerot[6], eerot[7], eerot[8];
return true;
}
}
<file_sep>/docs/TorqueFF_HWI_english.md
Torque feed forward mode hardware interface
====
A controller with the hardware interface *'elfin_hardware_interface::PosTrqJointInterface'* can control the Elfin in torque feed forward mode. There is a sample example in the *elfin_ros_controllers* package: *'elfin_pos_trq_controllers/JointTrajectoryController'*. You can use it by the following method.
1. Change the controller type in the file *elfin_robot_bringup/config/elfin_arm_control.yaml*:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: elfin_pos_trq_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ velocity_ff:
+ elfin_joint1: 1
+ elfin_joint2: 1
+ elfin_joint3: 1
+ elfin_joint4: 1
+ elfin_joint5: 1
+ elfin_joint6: 1
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
velocity_ff: velocity related feedforward factor. velocity_ff * desired_velocity = velocity_related_feedforward_torque
2. Start the robot arm normally as described in the [README_english.md](../README_english.md)<file_sep>/elfin_basic_api/src/elfin_basic_api.cpp
/*
Created on Mon Dec 15 10:58:42 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include <elfin_basic_api/elfin_basic_api.h>
namespace elfin_basic_api {
ElfinBasicAPI::ElfinBasicAPI(moveit::planning_interface::MoveGroupInterface *group, std::string action_name, planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor):
group_(group), action_client_(action_name, true), planning_scene_monitor_(planning_scene_monitor), local_nh_("~")
{
teleop_api_=new ElfinTeleopAPI(group, action_name, planning_scene_monitor);
motion_api_=new ElfinMotionAPI(group, action_name, planning_scene_monitor);
dynamic_reconfigure_server_.setCallback(boost::bind(&ElfinBasicAPI::dynamicReconfigureCallback, this, _1, _2));
set_ref_link_server_=local_nh_.advertiseService("set_reference_link", &ElfinBasicAPI::setRefLink_cb, this);
set_end_link_server_=local_nh_.advertiseService("set_end_link", &ElfinBasicAPI::setEndLink_cb, this);
enable_robot_server_=local_nh_.advertiseService("enable_robot", &ElfinBasicAPI::enableRobot_cb, this);
disable_robot_server_=local_nh_.advertiseService("disable_robot", &ElfinBasicAPI::disableRobot_cb, this);
elfin_controller_name_=local_nh_.param<std::string>("controller_name", "elfin_arm_controller");
switch_controller_client_=root_nh_.serviceClient<controller_manager_msgs::SwitchController>("/controller_manager/switch_controller");
list_controllers_client_=root_nh_.serviceClient<controller_manager_msgs::ListControllers>("/controller_manager/list_controllers");
get_motion_state_client_=root_nh_.serviceClient<std_srvs::SetBool>("/elfin_ros_control/elfin/get_motion_state");
get_pos_align_state_client_=root_nh_.serviceClient<std_srvs::SetBool>("/elfin_ros_control/elfin/get_pos_align_state");
raw_enable_robot_client_=root_nh_.serviceClient<std_srvs::SetBool>("/elfin_ros_control/elfin/enable_robot");
raw_disable_robot_client_=root_nh_.serviceClient<std_srvs::SetBool>("/elfin_ros_control/elfin/disable_robot");
ref_link_name_publisher_=local_nh_.advertise<std_msgs::String>("reference_link_name", 1, true);
end_link_name_publisher_=local_nh_.advertise<std_msgs::String>("end_link_name", 1, true);
ref_link_name_msg_.data=group_->getPlanningFrame();
end_link_name_msg_.data=group_->getEndEffectorLink();
ref_link_name_publisher_.publish(ref_link_name_msg_);
end_link_name_publisher_.publish(end_link_name_msg_);
}
ElfinBasicAPI::~ElfinBasicAPI()
{
if(teleop_api_ != NULL)
delete teleop_api_;
if(motion_api_ != NULL)
delete motion_api_;
}
void ElfinBasicAPI::dynamicReconfigureCallback(ElfinBasicAPIDynamicReconfigureConfig &config, uint32_t level)
{
setVelocityScaling(config.velocity_scaling);
}
void ElfinBasicAPI::setVelocityScaling(double data)
{
velocity_scaling_=data;
teleop_api_->setVelocityScaling(velocity_scaling_);
motion_api_->setVelocityScaling(velocity_scaling_);
}
bool ElfinBasicAPI::setRefLink_cb(elfin_robot_msgs::SetString::Request &req, elfin_robot_msgs::SetString::Response &resp)
{
if(!tf_listener_.frameExists(req.data))
{
resp.success=false;
std::string result="There is no frame named ";
result.append(req.data);
resp.message=result;
return true;
}
teleop_api_->setRefFrames(req.data);
motion_api_->setRefFrames(req.data);
ref_link_name_msg_.data=req.data;
ref_link_name_publisher_.publish(ref_link_name_msg_);
resp.success=true;
resp.message="Setting reference link succeed";
return true;
}
bool ElfinBasicAPI::setEndLink_cb(elfin_robot_msgs::SetString::Request &req, elfin_robot_msgs::SetString::Response &resp)
{
if(!tf_listener_.frameExists(req.data))
{
resp.success=false;
std::string result="There is no frame named ";
result.append(req.data);
resp.message=result;
return true;
}
teleop_api_->setEndFrames(req.data);
motion_api_->setEndFrames(req.data);
end_link_name_msg_.data=req.data;
end_link_name_publisher_.publish(end_link_name_msg_);
resp.success=true;
resp.message="Setting end link succeed";
return true;
}
bool ElfinBasicAPI::enableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
// Check request
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
// Check if there is a real driver
if(!raw_enable_robot_client_.exists())
{
resp.message="there is no real driver running";
resp.success=false;
return true;
}
std_srvs::SetBool::Request req_tmp;
std_srvs::SetBool::Response resp_tmp;
// Stop active controllers
if(!stopActCtrlrs(resp_tmp))
{
resp=resp_tmp;
return true;
}
usleep(500000);
// Check motion state
if(!get_motion_state_client_.exists())
{
resp.message="there is no get_motion_state service";
resp.success=false;
return true;
}
req_tmp.data=true;
get_motion_state_client_.call(req_tmp, resp_tmp);
if(resp_tmp.success)
{
resp.message="failed to enable the robot, it's moving";
resp.success=false;
return true;
}
// Check position alignment state
if(!get_pos_align_state_client_.exists())
{
resp.message="there is no get_pos_align_state service";
resp.success=false;
return true;
}
req_tmp.data=true;
get_pos_align_state_client_.call(req_tmp, resp_tmp);
if(!resp_tmp.success)
{
resp.message="failed to enable the robot, commands aren't aligned with actual positions";
resp.success=false;
return true;
}
// Check enable service
if(!raw_enable_robot_client_.exists())
{
resp.message="there is no real driver running";
resp.success=false;
return true;
}
// Enable servos
raw_enable_robot_request_.data=true;
raw_enable_robot_client_.call(raw_enable_robot_request_, raw_enable_robot_response_);
resp=raw_enable_robot_response_;
// Start default controller
if(!startElfinCtrlr(resp_tmp))
{
resp=resp_tmp;
return true;
}
return true;
}
bool ElfinBasicAPI::disableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
// Check request
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
// Check disable service
if(!raw_disable_robot_client_.exists())
{
resp.message="there is no real driver running";
resp.success=false;
return true;
}
// Disable servos
raw_disable_robot_request_.data=true;
raw_disable_robot_client_.call(raw_disable_robot_request_, raw_disable_robot_response_);
resp=raw_disable_robot_response_;
std_srvs::SetBool::Response resp_tmp;
// Stop active controllers
if(!stopActCtrlrs(resp_tmp))
{
resp=resp_tmp;
return true;
}
return true;
}
bool ElfinBasicAPI::stopActCtrlrs(std_srvs::SetBool::Response &resp)
{
// Check list controllers service
if(!list_controllers_client_.exists())
{
resp.message="there is no controller manager";
resp.success=false;
return false;
}
// Find controllers to stop
controller_manager_msgs::ListControllers::Request list_controllers_request;
controller_manager_msgs::ListControllers::Response list_controllers_response;
list_controllers_client_.call(list_controllers_request, list_controllers_response);
std::vector<std::string> controllers_to_stop;
controllers_to_stop.clear();
controller_joint_names_.clear();
for(int i=0; i<list_controllers_response.controller.size(); i++)
{
std::string name_tmp=list_controllers_response.controller[i].name;
std::vector<controller_manager_msgs::HardwareInterfaceResources> resrc_tmp=list_controllers_response.controller[i].claimed_resources;
if(strcmp(name_tmp.c_str(), elfin_controller_name_.c_str())==0)
{
for(int j=0; j<resrc_tmp.size(); j++)
{
controller_joint_names_.insert(controller_joint_names_.end(), resrc_tmp[j].resources.begin(),
resrc_tmp[j].resources.end());
}
break;
}
}
for(int i=0; i<list_controllers_response.controller.size(); i++)
{
std::string state_tmp=list_controllers_response.controller[i].state;
std::string name_tmp=list_controllers_response.controller[i].name;
std::vector<controller_manager_msgs::HardwareInterfaceResources> resrc_tmp=list_controllers_response.controller[i].claimed_resources;
if(strcmp(state_tmp.c_str(), "running")==0)
{
bool break_flag=false;
for(int j=0; j<resrc_tmp.size(); j++)
{
for(int k=0; k<controller_joint_names_.size(); k++)
{
if(std::find(resrc_tmp[j].resources.begin(), resrc_tmp[j].resources.end(),
controller_joint_names_[k])!=resrc_tmp[j].resources.end())
{
break_flag=true;
controllers_to_stop.push_back(name_tmp);
}
if(break_flag)
{
break;
}
}
if(break_flag)
{
break;
}
}
}
}
// Stop active controllers
if(controllers_to_stop.size()>0)
{
// Check switch controller service
if(!switch_controller_client_.exists())
{
resp.message="there is no controller manager";
resp.success=false;
return false;
}
// Stop active controllers
controller_manager_msgs::SwitchController::Request switch_controller_request;
controller_manager_msgs::SwitchController::Response switch_controller_response;
switch_controller_request.start_controllers.clear();
switch_controller_request.stop_controllers=controllers_to_stop;
switch_controller_request.strictness=switch_controller_request.STRICT;
switch_controller_client_.call(switch_controller_request, switch_controller_response);
if(!switch_controller_response.ok)
{
resp.message="Failed to stop active controllers";
resp.success=false;
return false;
}
}
return true;
}
bool ElfinBasicAPI::startElfinCtrlr(std_srvs::SetBool::Response &resp)
{
// Check switch controller service
if(!switch_controller_client_.exists())
{
resp.message="there is no controller manager";
resp.success=false;
return false;
}
// Start active controllers
controller_manager_msgs::SwitchController::Request switch_controller_request;
controller_manager_msgs::SwitchController::Response switch_controller_response;
switch_controller_request.start_controllers.clear();
switch_controller_request.start_controllers.push_back(elfin_controller_name_);
switch_controller_request.stop_controllers.clear();
switch_controller_request.strictness=switch_controller_request.STRICT;
switch_controller_client_.call(switch_controller_request, switch_controller_response);
if(!switch_controller_response.ok)
{
resp.message="Failed to start the default controller";
resp.success=false;
return false;
}
return true;
}
}
<file_sep>/elfin_basic_api/include/elfin_basic_api/elfin_teleop_api.h
/*
Created on Mon Nov 13 15:20:10 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_TELEOP_API_H
#define ELFIN_TELEOP_API_H
#include <ros/ros.h>
#include <vector>
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/conversions.h>
#include <moveit/ompl_interface/ompl_interface.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <actionlib/client/simple_action_client.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <trajectory_msgs/JointTrajectoryPoint.h>
#include <elfin_robot_msgs/SetInt16.h>
#include <elfin_robot_msgs/SetFloat64.h>
#include <std_msgs/Empty.h>
#include <std_srvs/SetBool.h>
#include <std_msgs/Int64.h>
#include <std_msgs/Empty.h>
#include <elfin_basic_api/elfin_basic_api_const.h>
#include <tf/transform_listener.h>
#include <tf_conversions/tf_eigen.h>
namespace elfin_basic_api {
class ElfinTeleopAPI
{
public:
ElfinTeleopAPI(moveit::planning_interface::MoveGroupInterface *group, std::string action_name, planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor);
void teleopJointCmdNoLimitCB(const std_msgs::Int64ConstPtr &msg);
void teleopJointCmdCB(const std_msgs::Int64ConstPtr &msg);
void teleopCartCmdCB(const std_msgs::Int64ConstPtr &msg);
void teleopStopCB(const std_msgs::EmptyConstPtr &msg);
void setVelocityScaling(double data);
void setRefFrames(std::string ref_link);
void setEndFrames(std::string end_link);
bool jointTeleop_cb(elfin_robot_msgs::SetInt16::Request &req, elfin_robot_msgs::SetInt16::Response &resp);
bool cartTeleop_cb(elfin_robot_msgs::SetInt16::Request &req, elfin_robot_msgs::SetInt16::Response &resp);
bool homeTeleop_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool teleopStop_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
void PoseStampedRotation(geometry_msgs::PoseStamped &pose_stamped, const tf::Vector3 &axis, double angle);
private:
moveit::planning_interface::MoveGroupInterface *group_;
moveit::planning_interface::PlanningSceneInterface planning_scene_interface_;
planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor_;
ros::NodeHandle root_nh_, teleop_nh_;
actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction> action_client_;
control_msgs::FollowJointTrajectoryGoal goal_;
ros::Subscriber sub_teleop_joint_command_no_limit_;
ros::ServiceServer joint_teleop_server_;
ros::ServiceServer cart_teleop_server_;
ros::ServiceServer home_teleop_server_;
ros::ServiceServer teleop_stop_server_;
double joint_step_;
double joint_duration_ns_;
double joint_speed_limit_;
double velocity_scaling_;
double joint_speed_default_;
double cart_duration_default_;
double resolution_angle_;
double resolution_linear_;
double joint_speed_;
double cart_duration_; // in second
std::string end_link_;
std::string reference_link_;
std::string default_tip_link_;
std::string root_link_;
tf::TransformListener tf_listener_;
tf::StampedTransform transform_rootToRef_;
tf::StampedTransform transform_tipToEnd_;
};
}
#endif
<file_sep>/elfin_basic_api/cfg/ElfinBasicAPIDynamicReconfigure.cfg
#!/usr/bin/env python
PACKAGE = "elfin_basic_api"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("velocity_scaling", double_t, 0, "the max velocity scaling", 0.4, 0.01, 1.0)
exit(gen.generate(PACKAGE, PACKAGE, "ElfinBasicAPIDynamicReconfigure"))
<file_sep>/docs/API_description.md
API 简介
=====
### Subscribed Topics:
* **elfin_basic_api/joint_goal (sensor_msgs/JointState)**
令机械臂规划到达指定臂型的路径并执行此路径
example: function_pub_joints() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_basic_api/cart_goal (geometry_msgs/PoseStamped)**
令机械臂规划到达指定空间位置的路径并执行此路径
example: function_pub_cart_xxx() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_basic_api/cart_path_goal (geometry_msgs/PoseArray)**
令机械臂规划一条路径,以直线方式依次经过各个指定的点,并执行此路径
example: function_pub_cart_path_xxx() in elfin_robot_bringup/script/cmd_pub.py
* **elfin_arm_controller/command (trajectory_msgs/JointTrajectory)**
本消息内容为一条轨迹,可令机械臂沿着这条轨迹运动
* **elfin_teleop_joint_cmd_no_limit (std_msgs/Int64)**
本指令为调试机器时使用的指令,不建议客户使用。发送本指令后,机械臂的特定关节会向一个方向移动一点距离,连续发送就会连续运动。
消息内容含义如下:
| data | joint | direction |
| ------- | ------------| -------------- |
| 1 | elfin_joint1| ccw |
| -1 | elfin_joint1 | cw |
| 2 | elfin_joint2 | ccw |
| -2 | elfin_joint2 | cw |
| 3 | elfin_joint3| ccw |
| -3 | elfin_joint3 | cw |
| 4 | elfin_joint4 | ccw |
| -4 | elfin_joint4 | cw |
| 5 | elfin_joint5| ccw |
| -5 | elfin_joint5 | cw |
| 6 | elfin_joint6 | ccw |
| -6 | elfin_joint6 | cw |
------
### Published Topics:
* **elfin_arm_controller/state (control_msgs/JointTrajectoryControllerState)**
反映机械臂各个关节的状态
* **elfin_ros_control/elfin/enable_state (std_msgs/Bool)**
反映此时Elfin机械臂上电机的使能状态。
true: 使能 / false: 未使能
* **elfin_ros_control/elfin/fault_state (std_msgs/Bool)**
反映此时Elfin机械臂上电机的报错状态。
true: 有报错 / false: 无报错
* **elfin_basic_api/parameter_updates (dynamic_reconfigure/Config)**
反映elfin_basic_api相关的动态参数,例如: velocity scaling 。
* **elfin_basic_api/reference_link_name (std_msgs/String)**
elfin_basic_api节点计算时所使用的参考基坐标系的名字
* **elfin_basic_api/end_link_name (std_msgs/String)**
elfin_basic_api节点计算时所使用的末端坐标系的名字
------
### Services:
* **elfin_basic_api/get_reference_link (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含elfin_basic_api规划时的参考基坐标系名
* **elfin_basic_api/get_end_link (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含elfin_basic_api规划时的末端坐标系名
* **elfin_basic_api/stop_teleop (std_srvs/SetBool)**
呼叫本服务会令机械臂停止运动
* **elfin_basic_api/set_parameters (dynamic_reconfigure/Reconfigure)**
设置elfin_basic_api相关的动态参数,例如: velocity scaling
example: set_parameters() in elfin_robot_bringup/script/set_velocity_scaling.py
* **elfin_ros_control/elfin/get_txpdo (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含机械臂上从站的txpdo信息
* **elfin_ros_control/elfin/get_rxpdo (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含机械臂上从站的rxpdo信息
* **elfin_ros_control/elfin/get_current_position (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含机械臂各轴的位置的编码器值
* **elfin_ros_control/elfin/recognize_position (std_srvs/SetBool)**
呼叫本服务可使机械臂进行姿态识别
* **elfin_ros_control/elfin/io_port1/write_do (elfin_robot_msgs/ElfinIODWrite)**
向DO中写入内容
example:
```
rosservice call /elfin_ros_control/elfin/io_port1/write_do "digital_output: 0x001b"
```
* **elfin_ros_control/elfin/io_port1/read_di (elfin_robot_msgs/ElfinIODRead)**
从DI中读取内容
example:
```
rosservice call /elfin_ros_control/elfin/io_port1/read_di "data: true"
```
* **elfin_ros_control/elfin/io_port1/get_txpdo (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含IO从站的txpdo信息
* **elfin_ros_control/elfin/io_port1/get_rxpdo (std_srvs/SetBool)**
呼叫本服务得到的反馈信息中会包含IO从站的rxpdo信息
* **elfin_module_open_brake_slaveX(std_srvs/SetBool)**
在模组未使能情况下,呼叫本服务可以打开相应模组的抱闸
for example:
```sh
rosservice call elfin_module_open_brake_slave1 "data: true"
```
* **elfin_module_close_brake_slaveX(std_srvs/SetBool)**
在模组未使能情况下,呼叫本服务可以关闭相应模组的抱闸
for example:
```sh
rosservice call elfin_module_close_brake_slave1 "data: true"
```
***以下Services都会被Elfin Control Panel 界面调用, 不建议客户直接使用***
* **elfin_basic_api/enable_robot (std_srvs/SetBool)**
呼叫本服务可使机械臂使能。
* **elfin_ros_control/elfin/enable_robot (std_srvs/SetBool)**
推荐使用*elfin_basic_api/enable_robot*服务来使能机械臂。呼叫本服务可直接使机械臂使能,所以需自行处理*controllers*的状态。详见: http://wiki.ros.org/controller_manager 。
* **elfin_basic_api/disable_robot (std_srvs/SetBool)**
呼叫本服务可使机械臂去使能。
* **elfin_ros_control/elfin/disable_robot (std_srvs/SetBool)**
推荐使用*elfin_basic_api/disable_robot*服务来使机械臂去使能。呼叫本服务可直接使机械臂去使能,所以需自行处理*controllers*的状态。详见: http://wiki.ros.org/controller_manager 。
* **elfin_ros_control/elfin/clear_fault (std_srvs/SetBool)**
呼叫本服务可使机械臂清除报错状态。
* **elfin_basic_api/set_reference_link (elfin_robot_msgs/SetString)**
设置elfin_basic_api节点计算时所使用的参考基坐标系
* **elfin_basic_api/set_end_link (elfin_robot_msgs/SetString)**
设置elfin_basic_api节点计算时所使用的末端坐标系
* **elfin_basic_api/joint_teleop (elfin_robot_msgs/SetInt16)**
呼叫本服务后,机械臂的特定关节会向一个方向一直移动,直到运动到极限位置或用户调用elfin_basic_api/stop_teleop,请慎用。
消息内容含义如下:
| data | joint | direction |
| ------- | ------------| -------------- |
| 1 | elfin_joint1| ccw |
| -1 | elfin_joint1 | cw |
| 2 | elfin_joint2 | ccw |
| -2 | elfin_joint2 | cw |
| 3 | elfin_joint3| ccw |
| -3 | elfin_joint3 | cw |
| 4 | elfin_joint4 | ccw |
| -4 | elfin_joint4 | cw |
| 5 | elfin_joint5| ccw |
| -5 | elfin_joint5 | cw |
| 6 | elfin_joint6 | ccw |
| -6 | elfin_joint6 | cw |
* **elfin_basic_api/cart_teleop (elfin_robot_msgs/SetInt16)**
呼叫本服务后,机械臂会沿着一个空间方向一直移动,直到运动到极限位置或用户调用elfin_basic_api/stop_teleop,请慎用。
消息内容含义如下:
| data | axis | direction |
| ------- | ------------| -------------- |
| 1 | X | positive |
| -1 | X | negative |
| 2 | Y | positive |
| -2 | Y | negative |
| 3 | Z | positive |
| -3 | Z | negative |
| 4 | Rx | ccw |
| -4 | Rx | cw |
| 5 | Ry | ccw |
| -5 | Ry | cw |
| 6 | Rz | ccw |
| -6 | Rz | cw |
* **elfin_basic_api/home_teleop (std_srvs/SetBool)**
呼叫本服务后,机械臂会一直运动,直到回到零位置或用户调用elfin_basic_api/stop_teleop,请慎用。
<file_sep>/docs/elfin_module_tutorial_english.md
Elfin module tutorial
======
### Usage with Gazebo Simulation
Bring up the simulated module in Gazebo:
```sh
$ roslaunch elfin_gazebo elfin_module_empty_world.launch model:=module_xx # e.g. module_14
```
The module is controlled by "elfin_module_controller/follow_joint_trajectory" action. elfin_robot_bringup/script/elfin_module_cmd_pub.py is an example for that.
```sh
$ rosrun rosrun elfin_robot_bringup elfin_module_cmd_pub.py
```
---
### Usage with real module
Put the file *elfin_drivers.yaml*, that you got from the vendor, into the folder elfin_robot_bringup/config/.
Connect the module to the computer with a LAN cable. Then confirm the ethernet interface name of the connection with `ifconfig`. The default ethernet name is eth0. If the ethernet name is not eth0, you should correct the following line in the file *elfin_robot_bringup/config/elfin_drivers.yaml*
```
elfin_ethernet_name: eth0
```
Load module model:
```sh
$ roslaunch elfin_robot_bringup elfin_module_bringup.launch model:=module_xx # e.g. module_14
```
Bring up the hardware. Before bringing up the hardware, you should setup Linux with PREEMPT_RT properly. There is a [tutorial](https://wiki.linuxfoundation.org/realtime/documentation/howto/applications/preemptrt_setup). There are two versions of elfin EtherCAT slaves. Please bring up the hardware accordingly.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_module_ros_control.launch
```
or
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_module_ros_control_v2.launch
```
Get the status of the model with the following topics:
* **elfin_ros_control/elfin/enable_state (std_msgs/Bool)**
The servo status of the module.
true: enabled / false: disabled
* **elfin_ros_control/elfin/fault_state (std_msgs/Bool)**
The fault status of the module.
true: warning / false: no fault
Clear fault:
```sh
$ rosservice call /elfin_ros_control/elfin/clear_fault "data: true"
```
Enable servos:
```sh
$ rosservice call /elfin_ros_control/elfin/enable_robot "data: true"
```
Start the controller:
If you haven't installed rqt_controller_manager, please install it first
```sh
$ sudo apt-get install ros-<distro>-rqt-controller-manager
```
Using the short name of your ROS distribution instead of `<distro>`, for example: indigo, kinetic.
Start the controller with rqt_controller_manager
```sh
$ rosrun rqt_controller_manager rqt_controller_manager
```

Control the module:
The module is controlled by "elfin_module_controller/follow_joint_trajectory" action. elfin_robot_bringup/script/elfin_module_cmd_pub.py is an example for that.
```sh
$ rosrun elfin_robot_bringup elfin_module_cmd_pub.py
```
disable servos:
```sh
$ rosservice call /elfin_ros_control/elfin/disable_robot "data: true"
```
Stop the controller:
```sh
$ rosrun rqt_controller_manager rqt_controller_manager
```
<file_sep>/docs/elfin_module_tutorial.md
Elfin module tutorial
======
### 使用仿真模型
用Gazebo仿真请运行:
```sh
$ roslaunch elfin_gazebo elfin_module_empty_world.launch model:=module_xx # e.g. module_14
```
利用"elfin_module_controller/follow_joint_trajectory" action 可控制轴转动。elfin_robot_bringup/script/elfin_module_cmd_pub.py 是一个例程,运行它可让轴转动一定角度。
```sh
$ rosrun elfin_robot_bringup elfin_module_cmd_pub.py
```
---
### 使用真实的Elfin模组
先把购买模组时得到的elfin_drivers.yaml放到elfin_robot_bringup/config/文件夹下。
将模组通过网线连接到电脑。先通过`ifconfig`指令来确定与模组连接的网卡名称。本软件包默认的名称是eth0 。假如当前名称不是eth0的话,请对elfin_robot_bringup/config/elfin_drivers.yaml的相应部分进行修改。
```
elfin_ethernet_name: eth0
```
加载Elfin模组模型:
```sh
$ roslaunch elfin_robot_bringup elfin_module_bringup.launch model:=module_xx # e.g. module_14
```
启动硬件,Elfin的控制需要操作系统的实时性支持,运行下面的命令前请先为你的Linux系统内核打好实时补丁。打补丁的方法可以参考这个[教程](http://www.jianshu.com/p/8787e45a9e01)。Elfin机械臂有两种不同版本的EtherCAT从站,在启动硬件前,请先确认你的Elfin的从站版本。
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_module_ros_control.launch
```
或
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_module_ros_control_v2.launch
```
借助以下消息查看模组状态:
* **elfin_ros_control/elfin/enable_state (std_msgs/Bool)**
反映此时电机的使能状态。
true: 使能 / false: 未使能
* **elfin_ros_control/elfin/fault_state (std_msgs/Bool)**
反映此时电机的报错状态。
true: 有报错 / false: 无报错
清错:
```sh
$ rosservice call /elfin_ros_control/elfin/clear_fault "data: true"
```
使能:
```sh
$ rosservice call /elfin_ros_control/elfin/enable_robot "data: true"
```
启动控制器:
如果你没有安装过rqt_controller_manager,请先安装它:
```sh
$ sudo apt-get install ros-<distro>-rqt-controller-manager
```
请用你的ROS版本名代替`<distro>`,例如:indigo, kinetic 。
使用rqt_controller_manager启动控制器
```sh
$ rosrun rqt_controller_manager rqt_controller_manager
```

控制模组:
利用"elfin_module_controller/follow_joint_trajectory" action 可控制轴转动。elfin_robot_bringup/script/elfin_module_cmd_pub.py 是一个例程,运行它可让轴转动一定角度。
```sh
$ rosrun rosrun elfin_robot_bringup elfin_module_cmd_pub.py
```
去使能:
```sh
$ rosservice call /elfin_ros_control/elfin/disable_robot "data: true"
```
关闭控制器:
使用rqt_controller_manager关闭控制器
```sh
$ rosrun rqt_controller_manager rqt_controller_manager
```

<file_sep>/elfin_ethercat_driver/include/elfin_ethercat_driver/elfin_ethercat_manager.h
/*
* Copyright (C) 2015, <NAME>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Tokyo Opensource Robotics Kyokai Association. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// copied from https://github.com/ros-industrial/robotiq/blob/jade-devel/robotiq_ethercat/src/ethercat_manager.cpp
#ifndef ELFIN_ETHERCAT_MANAGER_H
#define ELFIN_ETHERCAT_MANAGER_H
#include <stdexcept>
#include <string>
#include <stdint.h>
#include <boost/scoped_array.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
namespace elfin_ethercat_driver {
typedef struct {
std::string name;
int32_t value;
uint8_t channel;
}ElfinPDOunit;
/**
* \brief EtherCAT exception. Currently this is only thrown in the event
* of a failure to construct an EtherCat manager.
*/
class EtherCatError : public std::runtime_error
{
public:
explicit EtherCatError(const std::string& what)
: std::runtime_error(what)
{}
};
/**
* \brief This class provides a CPP interface to the SimpleOpenEthercatMaster library
* Given the name of an ethernet device, such as "eth0", it will connect,
* start a thread that cycles data around the network, and provide read/write
* access to the underlying io map.
*
* Please note that as used in these docs, 'Input' and 'Output' are relative to
* your program. So the 'Output' registers are the ones you write to, for example.
*/
class EtherCatManager
{
public:
/**
* \brief Constructs and initializes the ethercat slaves on a given network interface.
*
* @param[in] ifname the name of the network interface that the ethercat chain
* is connected to (i.e. "eth0")
*
* Constructor can throw EtherCatError exception if SOEM could not be
* initialized.
*/
EtherCatManager(const std::string& ifname);
~EtherCatManager();
/**
* \brief writes 'value' to the 'channel-th' output-register of the given 'slave'
*
* @param[in] slave_no The slave number of the device to write to (>= 1)
* @param[in] channel The byte offset into the output IOMap to write value to
* @param[in] value The byte value to write
*
* This method currently makes no attempt to catch out of bounds errors. Make
* sure you know your IOMap bounds.
*/
void write(int slave_no, uint8_t channel, uint8_t value);
/**
* \brief Reads the "channel-th" input-register of the given slave no
*
* @param[in] slave_no The slave number of the device to read from (>= 1)
* @param[in] channel The byte offset into the input IOMap to read from
*/
uint8_t readInput(int slave_no, uint8_t channel) const;
/**
* \brief Reads the "channel-th" output-register of the given slave no
*
* @param[in] slave_no The slave number of the device to read from (>= 1)
* @param[in] channel The byte offset into the output IOMap to read from
*/
uint8_t readOutput(int slave_no, uint8_t channel) const;
/**
* \brief write the SDO object of the given slave no
*
* @param[in] slave_no The slave number of the device to read from (>= 1)
* @param[in] index The index address of the parameter in SDO object
* @param[in] subidx The sub-index address of the parameter in SDO object
* @param[in] value value to write
*/
template <typename T>
uint8_t writeSDO(int slave_no, uint16_t index, uint8_t subidx, T value) const;
/**
* \brief read the SDO object of the given slave no
*
* @param[in] slave_no The slave number of the device to read from (>= 1)
* @param[in] index The index address of the parameter in SDO object
* @param[in] subidx The sub-index address of the parameter in SDO object
*/
template <typename T>
T readSDO(int slave_no, uint16_t index, uint8_t subidx) const;
/**
* \brief get the number of clients
*/
int getNumClinets() const;
private:
bool initSoem(const std::string& ifname);
const std::string ifname_;
uint8_t iomap_[4096];
int num_clients_;
boost::thread cycle_thread_;
mutable boost::mutex iomap_mutex_;
bool stop_flag_;
};
}
#endif
<file_sep>/elfin_ethercat_driver/src/elfin_ethercat_client.cpp
/*
Created on Mon Sep 17 10:02:30 2018
@author: <NAME>, Burb
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>, Burb
#include <elfin_ethercat_driver/elfin_ethercat_client.h>
namespace elfin_ethercat_driver
{
ElfinEtherCATClient::ElfinEtherCATClient(EtherCatManager *manager, int slave_no):
manager_(manager), slave_no_(slave_no)
{
std::string info_tx_name="elfin_module_info_tx_slave";
std::string info_rx_name="elfin_module_info_rx_slave";
std::string enable_server_name="elfin_module_enable_slave";
std::string reset_fault_server_name="elfin_module_reset_fault_slave";
std::string open_brake_server_name="elfin_module_open_brake_slave";
std::string close_brake_server_name="elfin_module_close_brake_slave";
std::string slave_num=boost::lexical_cast<std::string>(slave_no);
info_tx_name.append(slave_num);
info_rx_name.append(slave_num);
enable_server_name.append(slave_num);
reset_fault_server_name.append(slave_num);
open_brake_server_name.append(slave_num);
close_brake_server_name.append(slave_num);
pub_input_=n_.advertise<std_msgs::String>(info_tx_name, 1);
pub_output_=n_.advertise<std_msgs::String>(info_rx_name, 1);
server_enable_=n_.advertiseService(enable_server_name, &ElfinEtherCATClient::enable_cb, this);
server_reset_fault_=n_.advertiseService(reset_fault_server_name, &ElfinEtherCATClient::reset_fault_cb, this);
server_open_brake_=n_.advertiseService(open_brake_server_name, &ElfinEtherCATClient::open_brake_cb, this);
server_close_brake_=n_.advertiseService(close_brake_server_name, &ElfinEtherCATClient::close_brake_cb, this);
// init pdo_input and output
std::string name_pdo_input[8]={"Axis1_Statusword and Axis1_Torque_Actual_Value", "Axis1_Position_Actual_Value",
"Axis1_Velocity_Actual_Value", "Axis1_ErrorCode and Axis1_Modes_of_operation_display",
"Axis2_Statusword and Axis2_Torque_Actual_Value", "Axis2_Position_Actual_Value",
"Axis2_Velocity_Actual_Value", "Axis2_ErrorCode and Axis2_Modes_of_operation_display"};
uint8_t channel_pdo_input[8]={0, 4, 8, 12, 32, 36, 40, 44};
pdo_input.clear();
ElfinPDOunit unit_tmp; // old namespace
for(unsigned i=0; i<8; ++i)
{
unit_tmp.name=name_pdo_input[i];
unit_tmp.channel=channel_pdo_input[i];
pdo_input.push_back(unit_tmp);
}
std::string name_pdo_output[6]={"Axis1_Controlword and Axis1_Modes_of_operation", "Axis1_Target_position", "Axis1_Target_Torque and Axis1_VelFF",
"Axis2_Controlword and Axis2_Modes_of_operation", "Axis2_Target_position", "Axis2_Target_Torque and Axis2_VelFF"};
uint8_t channel_pdo_output[6]={0, 4, 8, 32, 36, 40};
pdo_output.clear();
for(unsigned i=0; i<6; ++i)
{
unit_tmp.name=name_pdo_output[i];
unit_tmp.channel=channel_pdo_output[i];
pdo_output.push_back(unit_tmp);
}
manager_->writeSDO<int8_t>(slave_no, 0x1c12, 0x00, 0x00);
manager_->writeSDO<int16_t>(slave_no, 0x1c12, 0x01, 0x1600);
manager_->writeSDO<int16_t>(slave_no, 0x1c12, 0x02, 0x1610);
manager_->writeSDO<int8_t>(slave_no, 0x1c12, 0x00, 0x02);
manager_->writeSDO<int8_t>(slave_no, 0x1c13, 0x00, 0x00);
manager_->writeSDO<int16_t>(slave_no, 0x1c13, 0x01, 0x1a00);
manager_->writeSDO<int16_t>(slave_no, 0x1c13, 0x02, 0x1a10);
manager_->writeSDO<int8_t>(slave_no, 0x1c13, 0x00, 0x02);
writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x0, false);
writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x0, false);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
}
ElfinEtherCATClient::~ElfinEtherCATClient()
{
}
int32_t ElfinEtherCATClient::readInput_unit(int n)
{
if(n<0 || n>=pdo_input.size())
return 0x0000;
uint8_t map[4];
for(int i=0; i<4; i++)
{
map[i]=manager_->readInput(slave_no_, pdo_input[n].channel+i);
}
int32_t value_tmp=*(int32_t *)(map);
return value_tmp;
}
int32_t ElfinEtherCATClient::readOutput_unit(int n)
{
if(n<0 || n>=pdo_output.size())
return 0x0000;
uint8_t map[4];
for(int i=0; i<4; i++)
{
map[i]=manager_->readOutput(slave_no_, pdo_output[n].channel+i);
}
int32_t value_tmp=*(int32_t *)(map);
return value_tmp;
}
void ElfinEtherCATClient::writeOutput_unit(int n, int32_t val)
{
if(n<0 || n>=pdo_output.size())
return;
uint8_t map_tmp;
for(int i=0; i<4; i++)
{
map_tmp=(val>>8*i) & 0x00ff;
manager_->write(slave_no_, pdo_output[n].channel+i, map_tmp);
}
}
int16_t ElfinEtherCATClient::readInput_half_unit(int n, bool high_16)
{
if(n<0 || n>=pdo_input.size())
return 0x0000;
int offset;
if(high_16)
offset=2;
else
offset=0;
uint8_t map[2];
for(int i=0; i<2; i++)
{
map[i]=manager_->readInput(slave_no_, pdo_input[n].channel+offset+i);
}
int16_t value_tmp=*(int16_t *)(map);
return value_tmp;
}
int16_t ElfinEtherCATClient::readOutput_half_unit(int n, bool high_16)
{
if(n<0 || n>=pdo_output.size())
return 0x0000;
int offset;
if(high_16)
offset=2;
else
offset=0;
uint8_t map[2];
for(int i=0; i<2; i++)
{
map[i]=manager_->readOutput(slave_no_, pdo_output[n].channel+offset+i);
}
int16_t value_tmp=*(int16_t *)(map);
return value_tmp;
}
void ElfinEtherCATClient::writeOutput_half_unit(int n, int16_t val, bool high_16)
{
if(n<0 || n>=pdo_output.size())
return;
int offset;
if(high_16)
offset=2;
else
offset=0;
uint8_t map_tmp;
for(int i=0; i<2; i++)
{
map_tmp=(val>>8*i) & 0x00ff;
manager_->write(slave_no_, pdo_output[n].channel+offset+i, map_tmp);
}
}
int8_t ElfinEtherCATClient::readInput_unit_byte(int n, bool high_16, bool high_8)
{
if(n<0 || n>=pdo_input.size())
return 0x0000;
int offset;
if(high_16)
{
if(high_8)
offset=3;
else
offset=2;
}
else
{
if(high_8)
offset=1;
else
offset=0;
}
uint8_t map[1];
for(int i=0; i<1; i++)
{
map[i]=manager_->readInput(slave_no_, pdo_input[n].channel+offset+i);
}
int8_t value_tmp=*(int8_t *)(map);
return value_tmp;
}
int8_t ElfinEtherCATClient::readOutput_unit_byte(int n, bool high_16, bool high_8)
{
if(n<0 || n>=pdo_output.size())
return 0x0000;
int offset;
if(high_16)
{
if(high_8)
offset=3;
else
offset=2;
}
else
{
if(high_8)
offset=1;
else
offset=0;
}
uint8_t map[1];
for(int i=0; i<1; i++)
{
map[i]=manager_->readOutput(slave_no_, pdo_output[n].channel+offset+i);
}
int8_t value_tmp=*(int8_t *)(map);
return value_tmp;
}
void ElfinEtherCATClient::writeOutput_unit_byte(int n, int8_t val, bool high_16, bool high_8)
{
if(n<0 || n>=pdo_output.size())
return;
int offset;
if(high_16)
{
if(high_8)
offset=3;
else
offset=2;
}
else
{
if(high_8)
offset=1;
else
offset=0;
}
uint8_t map_tmp;
for(int i=0; i<1; i++)
{
map_tmp=(val>>8*i) & 0x00ff;
manager_->write(slave_no_, pdo_output[n].channel+offset+i, map_tmp);
}
}
int32_t ElfinEtherCATClient::getAxis1PosCnt()
{
return readInput_unit(elfin_txpdo::AXIS1_ACTPOSITION);
}
int32_t ElfinEtherCATClient::getAxis2PosCnt()
{
return readInput_unit(elfin_txpdo::AXIS2_ACTPOSITION);
}
void ElfinEtherCATClient::setAxis1PosCnt(int32_t pos_cnt)
{
writeOutput_unit(elfin_rxpdo::AXIS1_TARGET_POSITION, pos_cnt);
}
void ElfinEtherCATClient::setAxis2PosCnt(int32_t pos_cnt)
{
writeOutput_unit(elfin_rxpdo::AXIS2_TARGET_POSITION, pos_cnt);
}
int16_t ElfinEtherCATClient::getAxis1VelCnt()
{
return readInput_half_unit(elfin_txpdo::AXIS1_ACTVELOCITY_L16, false);
}
int16_t ElfinEtherCATClient::getAxis2VelCnt()
{
return readInput_half_unit(elfin_txpdo::AXIS2_ACTVELOCITY_L16, false);
}
void ElfinEtherCATClient::setAxis1VelFFCnt(int16_t vff_cnt)
{
writeOutput_half_unit(elfin_rxpdo::AXIS1_VELFF_H16, vff_cnt, true);
}
void ElfinEtherCATClient::setAxis2VelFFCnt(int16_t vff_cnt)
{
writeOutput_half_unit(elfin_rxpdo::AXIS2_VELFF_H16, vff_cnt, true);
}
int16_t ElfinEtherCATClient::getAxis1TrqCnt()
{
return readInput_half_unit(elfin_txpdo::AXIS1_ACTTORQUE_H16, true);
}
int16_t ElfinEtherCATClient::getAxis2TrqCnt()
{
return readInput_half_unit(elfin_txpdo::AXIS2_ACTTORQUE_H16, true);
}
void ElfinEtherCATClient::setAxis1TrqCnt(int16_t trq_cnt)
{
writeOutput_half_unit(elfin_rxpdo::AXIS1_TARGET_TORQUE_L16, trq_cnt, false);
}
void ElfinEtherCATClient::setAxis2TrqCnt(int16_t trq_cnt)
{
writeOutput_half_unit(elfin_rxpdo::AXIS2_TARGET_TORQUE_L16, trq_cnt, false);
}
void ElfinEtherCATClient::readInput()
{
for(int i=0; i<pdo_input.size(); i++)
{
readInput_unit(i);
}
}
void ElfinEtherCATClient::readOutput()
{
for(int i=0; i<pdo_output.size(); i++)
{
readOutput_unit(i);
}
}
std::string ElfinEtherCATClient::getTxPDO()
{
int length=64;
uint8_t map[length];
char temp[8];
std::string result="slave";
result.reserve(640); // the size of result is actually 410
std::string slave_num=boost::lexical_cast<std::string>(slave_no_);
result.append(slave_num);
result.append("_txpdo:\n");
for (unsigned i = 0; i < length; ++i)
{
map[i] = manager_->readInput(slave_no_, i);
sprintf(temp,"0x%.2x",(uint8_t)map[i]);
result.append(temp, 4);
result.append(":");
}
result.append("\n");
return result;
}
std::string ElfinEtherCATClient::getRxPDO()
{
int length=64;
uint8_t map[length];
char temp[8];
std::string result="slave";
result.reserve(640); // the size of result is actually 410
std::string slave_num=boost::lexical_cast<std::string>(slave_no_);
result.append(slave_num);
result.append("_rxpdo:\n");
for (unsigned i = 0; i < length; ++i)
{
map[i] = manager_->readOutput(slave_no_, i);
sprintf(temp,"0x%.2x",(uint8_t)map[i]);
result.append(temp, 4);
result.append(":");
}
result.append("\n");
return result;
}
std::string ElfinEtherCATClient::getCurrentPosition()
{
std::string result="slave";
std::string slave_num=boost::lexical_cast<std::string>(slave_no_);
result.append(slave_num);
result.append("_current_position:\n");
int32_t current_position_1=readInput_unit(elfin_txpdo::AXIS1_ACTPOSITION);
std::string tmp_str_1=boost::lexical_cast<std::string>(current_position_1);
result.append("axis1: ");
result.append(tmp_str_1);
result.append(", ");
int32_t current_position_2=readInput_unit(elfin_txpdo::AXIS2_ACTPOSITION);
std::string tmp_str_2=boost::lexical_cast<std::string>(current_position_2);
result.append("axis2: ");
result.append(tmp_str_2);
result.append(". \n");
return result;
}
void ElfinEtherCATClient::getActPosCounts(int32_t &pos_act_count_1, int32_t &pos_act_count_2)
{
pos_act_count_1=readInput_unit(elfin_txpdo::AXIS1_ACTPOSITION);
pos_act_count_2=readInput_unit(elfin_txpdo::AXIS2_ACTPOSITION);
}
void ElfinEtherCATClient::getCmdPosCounts(int32_t &pos_cmd_count_1, int32_t &pos_cmd_count_2)
{
pos_cmd_count_1=readOutput_unit(elfin_rxpdo::AXIS1_TARGET_POSITION);
pos_cmd_count_2=readOutput_unit(elfin_rxpdo::AXIS2_TARGET_POSITION);
}
void ElfinEtherCATClient::pubInput()
{
txpdo_msg_.data=getTxPDO();
pub_input_.publish(txpdo_msg_);
txpdo_msg_.data.clear();
}
void ElfinEtherCATClient::pubOutput()
{
rxpdo_msg_.data=getRxPDO();
pub_output_.publish(rxpdo_msg_);
rxpdo_msg_.data.clear();
}
void ElfinEtherCATClient::clearPoseFault()
{
// channel1
writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x86, false);
usleep(20000);
writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x6, false);
usleep(20000);
// channel2
writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x86, false);
usleep(20000);
writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x6, false);
usleep(20000);
}
bool ElfinEtherCATClient::recognizePose()
{
//channel1
if((readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6060, 0x0, 0xc);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0xc, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3024, 0x0, 0x11000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0x200000
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0x200000)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3024, 0x0, 0x33000000);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 20e+9)
{
double result = (manager_->readSDO<int32_t>(slave_no_, 0x2043, 0x0));
result = result/4096/2.7*49.7*3.3;
fprintf(stderr,"The voltage of slave %i is: %fV.\n",slave_no_, result);
ROS_WARN("recognizePose phase1 failed while pose recognition in slave %i, channel 1", slave_no_);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return false;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3024, 0x0, 0x0);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 5e+9)
{
ROS_WARN("recognizePose phase 2 failed while pose recognition in slave %i, channel 1", slave_no_);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return false;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
manager_->writeSDO<int8_t>(slave_no_, 0x6060, 0x0, 0x8);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
usleep(50000);
}
else
{
ROS_WARN("recognizePose failed in slave %i, channel 1, the reason might be there is a fault or the motor is enabled", slave_no_);
return false;
}
//channel2
if((readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6860, 0x0, 0xc);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0xc, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3034, 0x0, 0x11000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0x200000
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0x200000)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3034, 0x0, 0x33000000);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 20e+9)
{
ROS_WARN("recognizePose phase1 failed while pose recognition in slave %i, channel 2", slave_no_);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return false;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3034, 0x0, 0x0);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 5e+9)
{
ROS_WARN("recognizePose phase 2 failed while pose recognition in slave %i, channel 2", slave_no_);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return false;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
manager_->writeSDO<int8_t>(slave_no_, 0x6860, 0x0, 0x8);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
usleep(50000);
}
else
{
ROS_WARN("recognizePose failed in slave %i, channel 2, the reason might be there is a fault or the motor is enabled", slave_no_);
return false;
}
return true;
}
bool ElfinEtherCATClient::isEnabled()
{
if((readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false) & 0xf)==0x7
&& (readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false) & 0xf)==0x7)
return true;
else
return false;
}
void *ElfinEtherCATClient::setEnable(void* threadarg)
{
ElfinEtherCATClient *pthis=(ElfinEtherCATClient *)threadarg;
if(pthis->readInput_half_unit(elfin_txpdo::AXIS1_ERRORCODE_L16, false)==0x2000
|| pthis->readInput_half_unit(elfin_txpdo::AXIS2_ERRORCODE_L16, false)==0x2000)
{
if(pthis->isWarning())
{
pthis->clearPoseFault();
}
if(!pthis->recognizePose())
{
return (void *)0;
}
}
if(pthis->isWarning())
{
pthis->clearPoseFault();
}
// enable
if(pthis->isWarning() || pthis->isEnabled())
{
ROS_WARN("setEnable in slave %i failed, the reason might be there is a fault or the motor is enabled", pthis->slave_no_);
return (void *)0;
}
pthis->writeOutput_unit(elfin_rxpdo::AXIS1_TARGET_POSITION, pthis->readInput_unit(elfin_txpdo::AXIS1_ACTPOSITION));
pthis->writeOutput_unit(elfin_rxpdo::AXIS2_TARGET_POSITION, pthis->readInput_unit(elfin_txpdo::AXIS2_ACTPOSITION));
usleep(100000);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x6, false);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x6, false);
pthis->writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
pthis->writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(pthis->readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false)==0x21
&& pthis->readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false)==0x21)
{
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
ROS_WARN("setEnable phase1 in slave %i failed", pthis->slave_no_);
return (void *)0;
}
usleep(10000);
clock_gettime(CLOCK_REALTIME, &tick);
}
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x7, false);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x7, false);
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(pthis->readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false)==0x23
&& pthis->readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false)==0x23)
{
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
ROS_WARN("setEnable phase2 in slave %i failed", pthis->slave_no_);
return (void *)0;
}
usleep(10000);
clock_gettime(CLOCK_REALTIME, &tick);
}
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0xf, false);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0xf, false);
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(pthis->readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false)==0x27
&& pthis->readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false)==0x27)
{
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
ROS_WARN("setEnable phase3 in slave %i failed", pthis->slave_no_);
return (void *)0;
}
usleep(10000);
clock_gettime(CLOCK_REALTIME, &tick);
}
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x1f, false);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x1f, false);
usleep(100000);
}
void *ElfinEtherCATClient::setDisable(void *threadarg)
{
ElfinEtherCATClient *pthis=(ElfinEtherCATClient *)threadarg;
if(pthis->isEnabled())
{
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS1_CONTROLWORD_L16, 0x6, false);
pthis->writeOutput_half_unit(elfin_rxpdo::AXIS2_CONTROLWORD_L16, 0x6, false);
return (void *)0;
}
else
{
return (void *)0;
}
}
void *ElfinEtherCATClient::recognizePoseCmd(void *threadarg)
{
ElfinEtherCATClient *pthis=(ElfinEtherCATClient *)threadarg;
if(pthis->isWarning())
{
pthis->clearPoseFault();
}
if(!pthis->recognizePose())
{
return (void *)0;
}
}
bool ElfinEtherCATClient::isWarning()
{
if((readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false) & 0x08)==0x08
|| (readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false) & 0x08)==0x08)
return true;
else
return false;
}
void ElfinEtherCATClient::resetFault()
{
clearPoseFault();
}
bool ElfinEtherCATClient::inPosMode()
{
if(isEnabled()
&& readInput_unit_byte(elfin_txpdo::AXIS1_MODES_OF_OPERATION_DISPLAY_BYTE2, true, false)==0x8
&& readInput_unit_byte(elfin_txpdo::AXIS2_MODES_OF_OPERATION_DISPLAY_BYTE2, true, false)==0x8)
return true;
else
return false;
}
bool ElfinEtherCATClient::inTrqMode()
{
if(isEnabled()
&& readInput_unit_byte(elfin_txpdo::AXIS1_MODES_OF_OPERATION_DISPLAY_BYTE2, true, false)==0xa
&& readInput_unit_byte(elfin_txpdo::AXIS2_MODES_OF_OPERATION_DISPLAY_BYTE2, true, false)==0xa)
return true;
else
return false;
}
bool ElfinEtherCATClient::inPosBasedMode()
{
return inPosMode();
}
void ElfinEtherCATClient::setPosMode()
{
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
}
void ElfinEtherCATClient::setTrqMode()
{
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0xa, true, false);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0xa, true, false);
}
bool ElfinEtherCATClient::enable_cb(std_srvs::SetBool::Request& req, std_srvs::SetBool::Response& resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
setEnable((void *)this);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while (ros::ok())
{
if(isEnabled())
{
resp.success=true;
resp.message="elfin module is enabled";
return true;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 20e+9)
{
resp.success=false;
resp.message="elfin module is not enabled";
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
bool ElfinEtherCATClient::reset_fault_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="require's data is false";
return true;
}
resetFault();
resp.success=true;
resp.message="fault is reset";
return true;
}
bool ElfinEtherCATClient::open_brake_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="request's data is false";
return true;
}
//channel1
if((readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6060, 0x0, 0xb);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0xb, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3023, 0x0, 0x11000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0x300000
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0x300000)
{
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3023, 0x0, 0x33000000);
usleep(30000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 1 phase 1 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0)
{
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 1 phase 2 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
else
{
resp.message="Channel 1 failed, the reason might be there is a fault or the motor is enabled";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
//channel2
if((readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6860, 0x0, 0xb);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0xb, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3033, 0x0, 0x11000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0x300000
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0x300000)
{
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3033, 0x0, 0x33000000);
usleep(30000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 2 phase 1 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0)
{
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 2 phase 2 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
}
else
{
resp.message="Channel 2 failed, the reason might be there is a fault or the motor is enabled";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
resp.message="band-type brake is opened";
resp.success=true;
return true;
}
bool ElfinEtherCATClient::close_brake_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
if(!req.data)
{
resp.success=false;
resp.message="request's data is false";
return true;
}
//channel1
if((readInput_half_unit(elfin_txpdo::AXIS1_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6060, 0x0, 0xb);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0xb, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3023, 0x0, 0x22000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0x400000
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0x400000)
{
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3023, 0x0, 0x33000000);
usleep(30000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 1 phase 1 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2023, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2024, 0x0)==0)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3023, 0x0, 0x0);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 1 phase 2 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
manager_->writeSDO<int8_t>(slave_no_, 0x6060, 0x0, 0x8);
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
usleep(50000);
}
else
{
resp.message="Channel 1 failed, the reason might be there is a fault or the motor is enabled";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS1_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
//channel2
if((readInput_half_unit(elfin_txpdo::AXIS2_STATUSWORD_L16, false) & 0xc) == 0)
{
manager_->writeSDO<int8_t>(slave_no_, 0x6860, 0x0, 0xb);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0xb, true, false);
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3033, 0x0, 0x22000000);
struct timespec before, tick;
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0x400000
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0x400000)
{
usleep(20000);
manager_->writeSDO<int32_t>(slave_no_, 0x3033, 0x0, 0x33000000);
usleep(30000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 2 phase 1 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
clock_gettime(CLOCK_REALTIME, &before);
clock_gettime(CLOCK_REALTIME, &tick);
while(ros::ok())
{
if(manager_->readSDO<int32_t>(slave_no_, 0x2033, 0x0)==0
&& manager_->readSDO<int32_t>(slave_no_, 0x2034, 0x0)==0)
{
manager_->writeSDO<int32_t>(slave_no_, 0x3033, 0x0, 0x0);
usleep(50000);
break;
}
if(tick.tv_sec*1e+9+tick.tv_nsec - before.tv_sec*1e+9 - before.tv_nsec >= 2e+9)
{
resp.message="Channel 2 phase 2 failed";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
usleep(100000);
clock_gettime(CLOCK_REALTIME, &tick);
}
manager_->writeSDO<int8_t>(slave_no_, 0x6860, 0x0, 0x8);
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
usleep(50000);
}
else
{
resp.message="Channel 2 failed, the reason might be there is a fault or the motor is enabled";
resp.success=false;
writeOutput_unit_byte(elfin_rxpdo::AXIS2_MODES_OF_OPERATION_BYTE2, 0x8, true, false);
return true;
}
resp.message="band-type brake is closed";
resp.success=true;
return true;
}
}
<file_sep>/elfin_ethercat_driver/include/elfin_ethercat_driver/elfin_ethercat_driver.h
/*
Created on Mon Sep 17 10:22:24 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_ETHERCAT_DRIVER_H
#define ELFIN_ETHERCAT_DRIVER_H
#include <elfin_ethercat_driver/elfin_ethercat_client.h>
#include <elfin_ethercat_driver/elfin_ethercat_io_client.h>
namespace elfin_ethercat_driver {
class ElfinEtherCATDriver
{
public:
ElfinEtherCATDriver(EtherCatManager *manager, std::string driver_name, const ros::NodeHandle &nh=ros::NodeHandle("~"));
~ElfinEtherCATDriver();
bool getEnableState();
bool getFaultState();
bool getMotionState();
bool getPosAlignState();
void updateStatus(const ros::TimerEvent &te);
size_t getEtherCATClientNumber();
ElfinEtherCATClient* getEtherCATClientPtr(size_t n);
std::string getJointName(size_t n);
double getReductionRatio(size_t n);
double getAxisPositionFactor(size_t n);
double getAxisTorqueFactor(size_t n);
int32_t getCountZero(size_t n);
bool recognizePosition();
bool getTxPDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool getRxPDO_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool getCurrentPosition_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool getMotionState_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool getPosAlignState_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool enableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool disableRobot_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool clearFault_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
bool recognizePosition_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp);
static int32_t getIntFromStr(std::string str);
private:
std::vector<ElfinEtherCATClient*> ethercat_clients_;
std::vector<int> slave_no_;
std::vector<std::string> joint_names_;
std::vector<double> reduction_ratios_;
std::vector<double> axis_position_factors_;
std::vector<double> axis_torque_factors_;
std::vector<int32_t> count_zeros_;
std::vector<ElfinEtherCATIOClient*> ethercat_io_clients_;
std::vector<int> io_slave_no_;
std::string driver_name_;
ros::NodeHandle root_nh_, ed_nh_;
ros::ServiceServer get_txpdo_server_;
ros::ServiceServer get_rxpdo_server_;
ros::ServiceServer get_current_position_server_;
ros::ServiceServer get_motion_state_server_;
ros::ServiceServer get_pos_align_state_server_;
ros::ServiceServer enable_robot_;
ros::ServiceServer disable_robot_;
ros::ServiceServer clear_fault_;
ros::ServiceServer recognize_position_;
std_msgs::Bool enable_state_msg_;
std_msgs::Bool fault_state_msg_;
ros::Publisher enable_state_pub_;
ros::Publisher fault_state_pub_;
ros::Duration status_update_period_;
ros::Timer status_timer_;
std::vector<double> count_rad_factors_;
double motion_threshold_;
double pos_align_threshold_;
};
}
#endif
<file_sep>/elfin_robot_bringup/script/set_velocity_scaling.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 19:59:24 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
# author: <NAME>
import rospy
from dynamic_reconfigure.srv import Reconfigure, ReconfigureRequest
from dynamic_reconfigure.msg import DoubleParameter, Config
class SetVelocityScaling(object):
def __init__(self):
self.request=ReconfigureRequest()
self.velocity_scaling_goal=0.6
self.elfin_basic_api_ns='elfin_basic_api/'
self.set_parameters_client=rospy.ServiceProxy(self.elfin_basic_api_ns+'set_parameters',
Reconfigure)
def set_parameters(self):
config_empty=Config()
velocity_scaling_param_tmp=DoubleParameter()
velocity_scaling_param_tmp.name='velocity_scaling'
velocity_scaling_param_tmp.value=self.velocity_scaling_goal
self.request.config.doubles.append(velocity_scaling_param_tmp)
self.set_parameters_client.call(self.request)
self.request.config=config_empty
if __name__ == "__main__":
rospy.init_node('set_velocity_scaling', anonymous=True)
svc=SetVelocityScaling()
svc.set_parameters()
rospy.spin()
<file_sep>/docs/Fix_ESI.md
修复ESI (EtherCAT Slave Infomation)
====
如果启动elfin_ros_control.launch(或 elfin_ros_control_v2.launch)时遇到类似以下的报错,可能有下面两个原因。
```
ERROR: slave_no(1) : channel(352) is larger than Input bits (256)
```
## 原因1
你可能用了错的launch文件(详见: [README.md](../README.md))。如果不知道所用的Elfin的从站版本的话,只要把两个launch文件都试一下即可。
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control.launch
```
或
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v2.launch
```
## 原因2
如果确定不是第一个原因,可以考虑是机械臂上的ESI固件错误。
### 修复ESI固件的方法
将Elfin通过网线连接到电脑。先通过`ifconfig`指令来确定与Elfin连接的网卡名称。本软件包默认的名称是eth0 。假如当前名称不是eth0的话,请在下面的步骤中对elfin_ethercat_driver/config/write_esi.yaml的相应部分进行修改。
```
eth_name: eth0
```
Elfin上共有4个EtherCAT从站,如果同一网卡没有连接其他EtherCAT设备的话,4个从站的编号如下图所示:

如果有其他EtherCAT设备的话,请根据实际从站的编号对elfin_ethercat_driver/config/write_esi.yaml的相应部分进行修改。
```
slave_no: [1, 2, 3]
```
以及
```
slave_no: [4]
```
#### 使用Version 1版本EtherCAT从站的Elfin
* 写入模组的ESI
将elfin_ethercat_driver/config/write_esi.yaml文件中的参数设置如下:
```
eth_name: eth0
slave_no: [1, 2, 3]
esi_file: elfin_module.esi
```
之后运行以下命令修复ESI
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
* 写入IO口的ESI
将elfin_ethercat_driver/config/write_esi.yaml文件中的参数设置如下:
```
eth_name: eth0
slave_no: [4]
esi_file: elfin_io_port.esi
```
之后运行以下命令修复ESI
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
最后重启机械臂即可完成修复。
为防误操作,修复后在elfin_ethercat_driver/script/路径下会生成各个从站原ESI的备份。
#### 使用Version 2版本EtherCAT从站的Elfin
* 写入模组的ESI
将elfin_ethercat_driver/config/write_esi.yaml文件中的参数设置如下:
```
eth_name: eth0
slave_no: [1, 2, 3]
esi_file: elfin_module_v2.esi
```
之后运行以下命令修复ESI
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
* 写入IO口的ESI
将elfin_ethercat_driver/config/write_esi.yaml文件中的参数设置如下:
```
eth_name: eth0
slave_no: [4]
esi_file: elfin_io_port_v2.esi
```
之后运行以下命令修复ESI
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
最后重启机械臂即可完成修复。
为防误操作,修复后在elfin_ethercat_driver/script/路径下会生成各个从站原ESI的备份。<file_sep>/elfin_robot/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(elfin_robot)
find_package(catkin REQUIRED)
catkin_metapackage()
<file_sep>/elfin_robot_servo/src/test.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import rospy
import time
from geometry_msgs.msg import TwistStamped,PoseStamped
from control_msgs.msg import JointJog
from std_msgs.msg import Float32
from sensor_msgs.msg import JointState
from controller_manager_msgs.srv import SwitchController, SwitchControllerRequest, SwitchControllerResponse
class test():
def __init__(self):
rospy.init_node('servo_test')
self.elfin_servoPose = rospy.Publisher("/servo_server/delta_twist_cmds", TwistStamped, queue_size=10)
self.elfin_servoJoint = rospy.Publisher("/servo_server/delta_joint_cmds", JointJog, queue_size=10)
self.servo_Pose = TwistStamped()
self.servo_Joint = JointJog()
self.rate = rospy.Rate(10)
def servo_movePose(self):
self.servo_Pose.twist.linear.x = 0.1
self.servo_Pose.twist.linear.y = 0.1
self.servo_Pose.twist.linear.z = 0.1
self.servo_Pose.twist.angular.x = 0.0
self.servo_Pose.twist.angular.y = 0.0
self.servo_Pose.twist.angular.z = 0.0
while not rospy.is_shutdown():
self.servo_Pose.header.stamp = rospy.get_rostime()
self.elfin_servoPose.publish(self.servo_Pose)
self.rate.sleep()
def servo_moveJoint(self):
self.servo_Joint.joint_names = ['elfin_joint1','elfin_joint2','elfin_joint3','elfin_joint4','elfin_joint5','elfin_joint6']
self.servo_Joint.displacements = [0,0.0,0.0,0.0,0.0,0.0]
self.servo_Joint.velocities = [0.5,0.0,0.0,0.0,0.0,0.0]
while not rospy.is_shutdown():
self.servo_Joint.header.stamp = rospy.get_rostime()
self.elfin_servoJoint.publish(self.servo_Joint)
self.rate.sleep()
if __name__=='__main__':
test = test()
test.servo_movePose()
rospy.spin()
<file_sep>/elfin_basic_api/src/elfin_motion_api.cpp
/*
Created on Mon Nov 27 14:22:43 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include "elfin_basic_api/elfin_motion_api.h"
namespace elfin_basic_api {
ElfinMotionAPI::ElfinMotionAPI(moveit::planning_interface::MoveGroupInterface *group, std::string action_name, planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor):
group_(group), action_client_(action_name, true), planning_scene_monitor_(planning_scene_monitor), motion_nh_("~")
{
geometry_msgs::Vector3 gravity_v3;
gravity_v3.x=0;
gravity_v3.y=0;
gravity_v3.z=-9.81;
dynamics_solver_.reset(new dynamics_solver::DynamicsSolver(group->getRobotModel(), group->getName(), gravity_v3));
goal_.trajectory.joint_names=group_->getJointNames();
goal_.trajectory.header.stamp.sec=0;
goal_.trajectory.header.stamp.nsec=0;
joint_goal_sub_=motion_nh_.subscribe("joint_goal", 1, &ElfinMotionAPI::jointGoalCB, this);
cart_goal_sub_=motion_nh_.subscribe("cart_goal", 1, &ElfinMotionAPI::cartGoalCB, this);
cart_path_goal_sub_=motion_nh_.subscribe("cart_path_goal", 1, &ElfinMotionAPI::cartPathGoalCB, this);
get_reference_link_server_=motion_nh_.advertiseService("get_reference_link", &ElfinMotionAPI::getRefLink_cb, this);
get_end_link_server_=motion_nh_.advertiseService("get_end_link", &ElfinMotionAPI::getEndLink_cb, this);
bool torques_publisher_flag=motion_nh_.param<bool>("torques_publish", false);
double torques_publisher_period=motion_nh_.param<double>("torques_publish_period", 0.02);
if(torques_publisher_flag)
{
torques_publisher_=motion_nh_.advertise<std_msgs::Float64MultiArray>("desired_torques", 1);
torques_publisher_timer_=motion_nh_.createTimer(ros::Duration(torques_publisher_period), &ElfinMotionAPI::torquesPubTimer_cb, this);
}
end_link_=group_->getEndEffectorLink();
reference_link_=group_->getPlanningFrame();
default_tip_link_=group_->getEndEffectorLink();
root_link_=group->getPlanningFrame();
}
void ElfinMotionAPI::jointGoalCB(const sensor_msgs::JointStateConstPtr &msg)
{
if(group_->setJointValueTarget(*msg))
{
group_->asyncMove();
}
else
{
ROS_WARN("the robot cannot execute that motion");
}
}
void ElfinMotionAPI::cartGoalCB(const geometry_msgs::PoseStampedConstPtr &msg)
{
std::string reference_link=reference_link_;
if(!msg->header.frame_id.empty())
{
reference_link=msg->header.frame_id;
}
if(!updateTransforms(reference_link))
return;
Eigen::Isometry3d affine_rootToRef, affine_refToRoot;
tf::transformTFToEigen(transform_rootToRef_, affine_rootToRef);
affine_refToRoot=affine_rootToRef.inverse();
Eigen::Isometry3d affine_tipToEnd;
tf::transformTFToEigen(transform_tipToEnd_, affine_tipToEnd);
tf::Pose tf_pose_tmp;
Eigen::Isometry3d affine_pose_tmp;
tf::poseMsgToTF(msg->pose, tf_pose_tmp);
tf::poseTFToEigen(tf_pose_tmp, affine_pose_tmp);
Eigen::Isometry3d affine_pose_goal=affine_refToRoot * affine_pose_tmp * affine_tipToEnd;
if(group_->setPoseTarget(affine_pose_goal))
{
group_->asyncMove();
}
else
{
ROS_WARN("the robot cannot execute that motion");
}
}
void ElfinMotionAPI::trajectoryScaling(moveit_msgs::RobotTrajectory &trajectory, double scale)
{
if(scale<=0 || scale>=1)
{
return;
}
for(int i=0; i<trajectory.joint_trajectory.points.size(); i++)
{
trajectory.joint_trajectory.points[i].time_from_start.operator *=(1.0/scale);
for(int j=0; j<trajectory.joint_trajectory.points[i].velocities.size(); j++)
{
trajectory.joint_trajectory.points[i].velocities[j]*=scale;
}
for(int j=0; j<trajectory.joint_trajectory.points[i].accelerations.size(); j++)
{
trajectory.joint_trajectory.points[i].accelerations[j]*=(scale*scale);
}
}
}
void ElfinMotionAPI::cartPathGoalCB(const geometry_msgs::PoseArrayConstPtr &msg)
{
moveit_msgs::RobotTrajectory cart_path;
moveit::planning_interface::MoveGroupInterface::Plan cart_plan;
std::vector<geometry_msgs::Pose> pose_goal=msg->poses;
std::string reference_link=reference_link_;
if(!msg->header.frame_id.empty())
{
reference_link=msg->header.frame_id;
}
if(!updateTransforms(reference_link))
return;
Eigen::Isometry3d affine_rootToRef, affine_refToRoot;
tf::transformTFToEigen(transform_rootToRef_, affine_rootToRef);
affine_refToRoot=affine_rootToRef.inverse();
Eigen::Isometry3d affine_tipToEnd;
tf::transformTFToEigen(transform_tipToEnd_, affine_tipToEnd);
tf::Pose tf_pose_tmp;
Eigen::Isometry3d affine_pose_tmp;
Eigen::Isometry3d affine_goal_tmp;
for(int i=0; i<pose_goal.size(); i++)
{
tf::poseMsgToTF(pose_goal[i], tf_pose_tmp);
tf::poseTFToEigen(tf_pose_tmp, affine_pose_tmp);
affine_goal_tmp=affine_refToRoot * affine_pose_tmp * affine_tipToEnd;
tf::poseEigenToTF(affine_goal_tmp, tf_pose_tmp);
tf::poseTFToMsg(tf_pose_tmp, pose_goal[i]);
}
double fraction=group_->computeCartesianPath(pose_goal, 0.01, 1.5, cart_path);
if(fraction==-1)
{
ROS_WARN("there is an error while computing the cartesian path");
return;
}
if(fraction==1)
{
ROS_INFO("the cartesian path can be %.2f%% acheived", fraction * 100.0);
trajectoryScaling(cart_path, velocity_scaling_);
cart_plan.trajectory_=cart_path;
group_->asyncExecute(cart_plan);
}
else
{
ROS_INFO("the cartesian path can only be %.2f%% acheived and it will not be executed", fraction * 100.0);
}
}
bool ElfinMotionAPI::getRefLink_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
resp.success=true;
resp.message=reference_link_;
return true;
}
bool ElfinMotionAPI::getEndLink_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
resp.success=true;
resp.message=end_link_;
return true;
}
void ElfinMotionAPI::torquesPubTimer_cb(const ros::TimerEvent& evt)
{
std::vector<double> v_p;
std::vector<double> v_v;
std::vector<double> v_a;
std::vector<geometry_msgs::Wrench> v_w(7);
std::vector<double> v_t(6);
for(int i=0;i<6; i++)
{
v_v.push_back(0);
v_a.push_back(0);
}
robot_state::RobotStatePtr current_state=group_->getCurrentState();
const robot_state::JointModelGroup* jmp=current_state->getJointModelGroup(group_->getName());
current_state->copyJointGroupPositions(jmp, v_p);
dynamics_solver_->getTorques(v_p, v_v, v_a, v_w, v_t);
torques_msg_.data=v_t;
torques_publisher_.publish(torques_msg_);
}
void ElfinMotionAPI::setVelocityScaling(double data)
{
velocity_scaling_=data;
}
void ElfinMotionAPI::setRefFrames(std::string ref_link)
{
reference_link_=ref_link;
}
void ElfinMotionAPI::setEndFrames(std::string end_link)
{
end_link_=end_link;
}
bool ElfinMotionAPI::updateTransforms(std::string ref_link)
{
ros::Rate r(100);
int counter=0;
while(ros::ok())
{
try{
tf_listener_.waitForTransform(ref_link, root_link_, ros::Time(0), ros::Duration(10.0) );
tf_listener_.lookupTransform(ref_link, root_link_, ros::Time(0), transform_rootToRef_);
break;
}
catch (tf::TransformException &ex) {
r.sleep();
counter++;
if(counter>200)
{
ROS_ERROR("%s",ex.what());
ROS_ERROR("Motion planning failed");
return false;
}
continue;
}
}
counter=0;
while(ros::ok())
{
try{
tf_listener_.waitForTransform(end_link_, default_tip_link_, ros::Time(0), ros::Duration(10.0) );
tf_listener_.lookupTransform(end_link_, default_tip_link_, ros::Time(0), transform_tipToEnd_);
break;
}
catch (tf::TransformException &ex) {
r.sleep();
counter++;
if(counter>200)
{
ROS_ERROR("%s",ex.what());
ROS_ERROR("Motion planning failed");
return false;
}
continue;
}
}
return true;
}
}
<file_sep>/docs/Fix_ESI_english.md
Fix ESI (EtherCAT Slave Infomation)
====
If you got an error info as follows, there are two possible reasons.
```
ERROR: slave_no(1) : channel(352) is larger than Input bits (256)
```
## Reason 1
You may have used the wrong launch file(elfin_ros_control.launch/elfin_ros_control_v2.launch) (for details: [README.md](../README.md)). If you don't know which version of Elfin you have. You can just try both of the launch files.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control.launch
```
or
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_robot_bringup elfin_ros_control_v2.launch
```
## Reason 2
If it's not the reason 1, then the ESI on the robot may be wrong.
### How to fix ESI
Connect Elfin to the computer with a LAN cable. Then confirm the ethernet interface name of the connection with `ifconfig`. The default ethernet name is eth0. If the ethernet name is not eth0, in the next steps you should correct the following line in the file *elfin_ethercat_driver/config/write_esi.yaml*.
```
elfin_ethernet_name: eth0
```
There are 4 EtherCAT slaves on the robot. If there is no other EtherCAT device connected to the same NIC, the numbers of the 4 Elfin EtherCAT slaves are as shown below.

If there are other EtherCAT devices, then in the next steps you should correct the following lines in the file *elfin_ethercat_driver/config/write_esi.yaml* accordingly.
```
slave_no: [1, 2, 3]
```
and
```
slave_no: [4]
```
#### Elfin with the version 1 of EtherCAT slaves
* Fix module ESI
Please set the parameters in the file *elfin_ethercat_driver/config/write_esi.yaml* as follows.
```
eth_name: eth0
slave_no: [1, 2, 3]
esi_file: elfin_module.esi
```
Then fix ESI with following commands.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
* Fix IO port ESI
Please set the parameters in the file *elfin_ethercat_driver/config/write_esi.yaml* as follows.
```
eth_name: eth0
slave_no: [4]
esi_file: elfin_io_port.esi
```
Then fix ESI with following commands.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
Finally, restart the robot. Now ESI should be fixed.
Besides, some backup files of the original ESI of the slaves that are fixed are generated in elfin_ethercat_driver/script/ folder.
#### Elfin with the version 2 of EtherCAT slaves
* Fix module ESI
Please set the parameters in the file *elfin_ethercat_driver/config/write_esi.yaml* as follows.
```
eth_name: eth0
slave_no: [1, 2, 3]
esi_file: elfin_module_v2.esi
```
Then fix ESI with following commands.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
* Fix IO port ESI
Please set the parameters in the file *elfin_ethercat_driver/config/write_esi.yaml* as follows.
```
eth_name: eth0
slave_no: [4]
esi_file: elfin_io_port_v2.esi
```
Then fix ESI with following commands.
```sh
$ sudo chrt 10 bash
$ roslaunch elfin_ethercat_driver elfin_esi_write.launch
```
Finally, restart the robot. Now ESI should be fixed.
Besides, some backup files of the original ESI of the slaves that are fixed are generated in elfin_ethercat_driver/script/ folder.
<file_sep>/elfin_robot_bringup/script/elfin_module_stop.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 11:38:22 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
# author: <NAME>
import rospy
from actionlib import SimpleActionClient
from control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal
class ElfinModuleStop(object):
def __init__(self):
self.action_client=SimpleActionClient('elfin_module_controller/follow_joint_trajectory',
FollowJointTrajectoryAction)
self.action_goal=FollowJointTrajectoryGoal()
self.action_goal.trajectory.joint_names=['elfin_module_joint1', 'elfin_module_joint2']
self.action_goal.trajectory.header.stamp.secs=0
self.action_goal.trajectory.header.stamp.nsecs=0
def stop_cmd_pub(self):
self.action_goal.trajectory.points=[]
self.action_client.wait_for_server()
self.action_client.send_goal(self.action_goal)
if __name__ == "__main__":
rospy.init_node("elfin_module_stop", anonymous=True)
stop_cmd_publisher=ElfinModuleStop()
stop_cmd_publisher.stop_cmd_pub()
rospy.spin()
<file_sep>/elfin_ros_control/src/elfin_hardware_interface.cpp
/*
Created on Tue Sep 25 10:16 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
// update the include file
#include "elfin_ros_control/elfin_hardware_interface.h"
namespace elfin_ros_control {
ElfinHWInterface::ElfinHWInterface(elfin_ethercat_driver::EtherCatManager *manager, const ros::NodeHandle &nh):
n_(nh)
{
//Initialize elfin_driver_names_
std::vector<std::string> elfin_driver_names_default;
elfin_driver_names_default.resize(1);
elfin_driver_names_default[0]="elfin";
n_.param<std::vector<std::string> >("elfin_ethercat_drivers", elfin_driver_names_, elfin_driver_names_default);
// Initialize ethercat_drivers_
ethercat_drivers_.clear();
ethercat_drivers_.resize(elfin_driver_names_.size());
for(int i=0; i<ethercat_drivers_.size(); i++)
{
ethercat_drivers_[i]=new elfin_ethercat_driver::ElfinEtherCATDriver(manager, elfin_driver_names_[i]);
}
// Initialize module_infos_
module_infos_.clear();
for(size_t i=0; i<ethercat_drivers_.size(); i++)
{
for(size_t j=0; j<ethercat_drivers_[i]->getEtherCATClientNumber(); j++)
{
ModuleInfo module_info_tmp;
module_info_tmp.client_ptr=ethercat_drivers_[i]->getEtherCATClientPtr(j);
module_info_tmp.axis1.name=ethercat_drivers_[i]->getJointName(2*j);
module_info_tmp.axis1.reduction_ratio=ethercat_drivers_[i]->getReductionRatio(2*j);
module_info_tmp.axis1.axis_position_factor=ethercat_drivers_[i]->getAxisPositionFactor(2*j);
module_info_tmp.axis1.count_zero=ethercat_drivers_[i]->getCountZero(2*j);
module_info_tmp.axis1.axis_torque_factor=ethercat_drivers_[i]->getAxisTorqueFactor(2*j);
module_info_tmp.axis2.name=ethercat_drivers_[i]->getJointName(2*j+1);
module_info_tmp.axis2.reduction_ratio=ethercat_drivers_[i]->getReductionRatio(2*j+1);
module_info_tmp.axis2.axis_position_factor=ethercat_drivers_[i]->getAxisPositionFactor(2*j+1);
module_info_tmp.axis2.count_zero=ethercat_drivers_[i]->getCountZero(2*j+1);
module_info_tmp.axis2.axis_torque_factor=ethercat_drivers_[i]->getAxisTorqueFactor(2*j+1);
module_infos_.push_back(module_info_tmp);
}
}
for(size_t i=0; i<module_infos_.size(); i++)
{
module_infos_[i].axis1.count_rad_factor=module_infos_[i].axis1.reduction_ratio*module_infos_[i].axis1.axis_position_factor/(2*M_PI);
module_infos_[i].axis1.count_rad_per_s_factor=module_infos_[i].axis1.count_rad_factor/750.3;
module_infos_[i].axis1.count_Nm_factor=module_infos_[i].axis1.axis_torque_factor/module_infos_[i].axis1.reduction_ratio;
module_infos_[i].axis2.count_rad_factor=module_infos_[i].axis2.reduction_ratio*module_infos_[i].axis2.axis_position_factor/(2*M_PI);
module_infos_[i].axis2.count_rad_per_s_factor=module_infos_[i].axis2.count_rad_factor/750.3;
module_infos_[i].axis2.count_Nm_factor=module_infos_[i].axis2.axis_torque_factor/module_infos_[i].axis2.reduction_ratio;
}
// Initialize pre_switch_flags_ and pre_switch_mutex_ptrs_
pre_switch_flags_.resize(module_infos_.size());
for(int i=0; i<pre_switch_flags_.size(); i++)
{
pre_switch_flags_[i]=false;
}
pre_switch_mutex_ptrs_.resize(module_infos_.size());
for(int i=0; i<pre_switch_mutex_ptrs_.size(); i++)
{
pre_switch_mutex_ptrs_[i]=boost::shared_ptr<boost::mutex>(new boost::mutex);
}
// Initialize the state and command interface
for(size_t i=0; i<module_infos_.size(); i++)
{
hardware_interface::JointStateHandle jnt_state_handle_tmp1(module_infos_[i].axis1.name,
&module_infos_[i].axis1.position,
&module_infos_[i].axis1.velocity,
&module_infos_[i].axis1.effort);
jnt_state_interface_.registerHandle(jnt_state_handle_tmp1);
hardware_interface::JointStateHandle jnt_state_handle_tmp2(module_infos_[i].axis2.name,
&module_infos_[i].axis2.position,
&module_infos_[i].axis2.velocity,
&module_infos_[i].axis2.effort);
jnt_state_interface_.registerHandle(jnt_state_handle_tmp2);
}
registerInterface(&jnt_state_interface_);
for(size_t i=0; i<module_infos_.size(); i++)
{
hardware_interface::JointHandle jnt_handle_tmp1(jnt_state_interface_.getHandle(module_infos_[i].axis1.name),
&module_infos_[i].axis1.position_cmd);
jnt_position_cmd_interface_.registerHandle(jnt_handle_tmp1);
hardware_interface::JointHandle jnt_handle_tmp2(jnt_state_interface_.getHandle(module_infos_[i].axis2.name),
&module_infos_[i].axis2.position_cmd);
jnt_position_cmd_interface_.registerHandle(jnt_handle_tmp2);
}
registerInterface(&jnt_position_cmd_interface_);
for(size_t i=0; i<module_infos_.size(); i++)
{
hardware_interface::JointHandle jnt_handle_tmp1(jnt_state_interface_.getHandle(module_infos_[i].axis1.name),
&module_infos_[i].axis1.effort_cmd);
jnt_effort_cmd_interface_.registerHandle(jnt_handle_tmp1);
hardware_interface::JointHandle jnt_handle_tmp2(jnt_state_interface_.getHandle(module_infos_[i].axis2.name),
&module_infos_[i].axis2.effort_cmd);
jnt_effort_cmd_interface_.registerHandle(jnt_handle_tmp2);
}
registerInterface(&jnt_effort_cmd_interface_);
for(size_t i=0; i<module_infos_.size(); i++)
{
elfin_hardware_interface::PosTrqJointHandle jnt_handle_tmp1(jnt_state_interface_.getHandle(module_infos_[i].axis1.name),
&module_infos_[i].axis1.position_cmd,
&module_infos_[i].axis1.effort_cmd);
jnt_postrq_cmd_interface_.registerHandle(jnt_handle_tmp1);
elfin_hardware_interface::PosTrqJointHandle jnt_handle_tmp2(jnt_state_interface_.getHandle(module_infos_[i].axis2.name),
&module_infos_[i].axis2.position_cmd,
&module_infos_[i].axis2.effort_cmd);
jnt_postrq_cmd_interface_.registerHandle(jnt_handle_tmp2);
}
registerInterface(&jnt_postrq_cmd_interface_);
for(size_t i=0; i<module_infos_.size(); i++)
{
hardware_interface::PosVelJointHandle jnt_handle_tmp1(jnt_state_interface_.getHandle(module_infos_[i].axis1.name),
&module_infos_[i].axis1.position_cmd,
&module_infos_[i].axis1.vel_ff_cmd);
jnt_posvel_cmd_interface_.registerHandle(jnt_handle_tmp1);
hardware_interface::PosVelJointHandle jnt_handle_tmp2(jnt_state_interface_.getHandle(module_infos_[i].axis2.name),
&module_infos_[i].axis2.position_cmd,
&module_infos_[i].axis2.vel_ff_cmd);
jnt_posvel_cmd_interface_.registerHandle(jnt_handle_tmp2);
}
registerInterface(&jnt_posvel_cmd_interface_);
for(size_t i=0; i<module_infos_.size(); i++)
{
elfin_hardware_interface::PosVelTrqJointHandle jnt_handle_tmp1(jnt_state_interface_.getHandle(module_infos_[i].axis1.name),
&module_infos_[i].axis1.position_cmd,
&module_infos_[i].axis1.vel_ff_cmd,
&module_infos_[i].axis1.effort_cmd);
jnt_posveltrq_cmd_interface_.registerHandle(jnt_handle_tmp1);
elfin_hardware_interface::PosVelTrqJointHandle jnt_handle_tmp2(jnt_state_interface_.getHandle(module_infos_[i].axis2.name),
&module_infos_[i].axis2.position_cmd,
&module_infos_[i].axis2.vel_ff_cmd,
&module_infos_[i].axis2.effort_cmd);
jnt_posveltrq_cmd_interface_.registerHandle(jnt_handle_tmp2);
}
registerInterface(&jnt_posveltrq_cmd_interface_);
// Initialize motion_threshold_
motion_threshold_=5e-5;
}
ElfinHWInterface::~ElfinHWInterface()
{
for(int i=0; i<ethercat_drivers_.size(); i++)
{
if(ethercat_drivers_[i]!=NULL)
delete ethercat_drivers_[i];
}
}
bool ElfinHWInterface::isModuleMoving(int module_num)
{
std::vector<double> previous_pos;
std::vector<double> last_pos;
previous_pos.resize(2);
last_pos.resize(2);
int32_t count1, count2;
module_infos_[module_num].client_ptr->getActPosCounts(count1, count2);
previous_pos[0]=count1/module_infos_[module_num].axis1.count_rad_factor;
previous_pos[1]=count2/module_infos_[module_num].axis2.count_rad_factor;
usleep(10000);
module_infos_[module_num].client_ptr->getActPosCounts(count1, count2);
last_pos[0]=count1/module_infos_[module_num].axis1.count_rad_factor;
last_pos[1]=count2/module_infos_[module_num].axis2.count_rad_factor;
for(int i=0; i<previous_pos.size(); i++)
{
if(fabs(last_pos[i]-previous_pos[i])>motion_threshold_)
{
return true;
}
}
return false;
}
bool ElfinHWInterface::setGroupPosMode(const std::vector<int> &module_no)
{
for(int j=0; j<module_no.size(); j++)
{
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[module_no[j]]);
pre_switch_flags_[module_no[j]]=true;
pre_switch_flags_lock.unlock();
}
usleep(5000);
for(int j=0; j<module_no.size(); j++)
{
module_infos_[module_no[j]].client_ptr->setAxis1VelFFCnt(0x0);
module_infos_[module_no[j]].client_ptr->setAxis2VelFFCnt(0x0);
module_infos_[module_no[j]].client_ptr->setAxis1TrqCnt(0x0);
module_infos_[module_no[j]].client_ptr->setAxis2TrqCnt(0x0);
}
for(int j=0; j<module_no.size(); j++)
{
module_infos_[module_no[j]].client_ptr->setPosMode();
}
usleep(10000);
for(int j=0; j<module_no.size(); j++)
{
if(!module_infos_[module_no[j]].client_ptr->inPosMode())
{
ROS_ERROR("module[%i]: set position mode failed", module_no[j]);
for(int k=0; k<module_no.size(); k++)
{
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[module_no[k]]);
pre_switch_flags_[module_no[k]]=false;
pre_switch_flags_lock.unlock();
}
return false;
}
}
return true;
}
bool ElfinHWInterface::setGroupTrqMode(const std::vector<int> &module_no)
{
for(int j=0; j<module_no.size(); j++)
{
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[module_no[j]]);
pre_switch_flags_[module_no[j]]=true;
pre_switch_flags_lock.unlock();
}
usleep(5000);
for(int j=0; j<module_no.size(); j++)
{
module_infos_[module_no[j]].client_ptr->setAxis1TrqCnt(0x0);
module_infos_[module_no[j]].client_ptr->setAxis2TrqCnt(0x0);
}
for(int j=0; j<module_no.size(); j++)
{
module_infos_[module_no[j]].client_ptr->setTrqMode();
}
usleep(10000);
bool set_trq_success=true;
for(int j=0; j<module_no.size(); j++)
{
if(!module_infos_[module_no[j]].client_ptr->inTrqMode())
{
ROS_ERROR("module[%i]: set torque mode failed, setting position mode", module_no[j]);
set_trq_success=false;
break;
}
}
if(!set_trq_success)
{
for(int j=0; j<module_no.size(); j++)
{
module_infos_[module_no[j]].client_ptr->setPosMode();
}
usleep(10000);
for(int j=0; j<module_no.size(); j++)
{
if(!module_infos_[module_no[j]].client_ptr->inPosMode())
{
ROS_ERROR("module[%i]: set position mode failed too", module_no[j]);
}
}
for(int j=0; j<module_no.size(); j++)
{
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[module_no[j]]);
pre_switch_flags_[module_no[j]]=false;
pre_switch_flags_lock.unlock();
}
return false;
}
return true;
}
bool ElfinHWInterface::prepareSwitch(const std::list<hardware_interface::ControllerInfo> &start_list,
const std::list<hardware_interface::ControllerInfo> &stop_list)
{
std::list<hardware_interface::ControllerInfo>::const_iterator iter;
if(!stop_list.empty())
{
for(iter=stop_list.begin(); iter!=stop_list.end(); iter++)
{
std::vector<hardware_interface::InterfaceResources> stop_resrcs=iter->claimed_resources;
for(int i=0; i<stop_resrcs.size(); i++)
{
std::vector<int> module_no;
module_no.clear();
for(int j=0; j<module_infos_.size(); j++)
{
if(stop_resrcs[i].resources.find(module_infos_[j].axis1.name)!=stop_resrcs[i].resources.end()
|| stop_resrcs[i].resources.find(module_infos_[j].axis2.name)!=stop_resrcs[i].resources.end())
{
if(module_infos_[j].client_ptr->isEnabled())
{
module_no.push_back(j);
}
}
}
std::vector<int> module_no_tmp=module_no;
if(!setGroupPosMode(module_no_tmp))
{
return false;
}
}
}
}
if(start_list.empty())
return true;
for(iter=start_list.begin(); iter!=start_list.end(); iter++)
{
std::vector<hardware_interface::InterfaceResources> start_resrcs=iter->claimed_resources;
for(int i=0; i<start_resrcs.size(); i++)
{
std::vector<int> module_no;
module_no.clear();
for(int j=0; j<module_infos_.size(); j++)
{
bool axis1_exist=(start_resrcs[i].resources.find(module_infos_[j].axis1.name)!=start_resrcs[i].resources.end());
bool axis2_exist=(start_resrcs[i].resources.find(module_infos_[j].axis2.name)!=start_resrcs[i].resources.end());
if(axis1_exist || axis2_exist)
{
if(axis1_exist && axis2_exist)
{
if(!module_infos_[j].client_ptr->isEnabled())
{
ROS_ERROR("can't start %s, because module[%i] is not enabled", iter->name.c_str(), j);
return false;
}
if(isModuleMoving(j))
{
ROS_ERROR("can't start %s, because module[%i] is moving", iter->name.c_str(), j);
return false;
}
module_no.push_back(j);
}
else if(axis1_exist)
{
ROS_ERROR("If %s includes %s, it should include %s too", iter->name.c_str(),
module_infos_[j].axis1.name.c_str(), module_infos_[j].axis2.name.c_str());
return false;
}
else
{
ROS_ERROR("If %s includes %s, it should include %s too", iter->name.c_str(),
module_infos_[j].axis2.name.c_str(), module_infos_[j].axis1.name.c_str());
return false;
}
}
}
if(strcmp(start_resrcs[i].hardware_interface.c_str(), "hardware_interface::PositionJointInterface")==0)
{
std::vector<int> module_no_tmp=module_no;
if(!setGroupPosMode(module_no_tmp))
{
return false;
}
}
else if(strcmp(start_resrcs[i].hardware_interface.c_str(), "hardware_interface::PosVelJointInterface")==0)
{
std::vector<int> module_no_tmp=module_no;
if(!setGroupPosMode(module_no_tmp))
{
return false;
}
}
else if(strcmp(start_resrcs[i].hardware_interface.c_str(), "elfin_hardware_interface::PosTrqJointInterface")==0)
{
std::vector<int> module_no_tmp=module_no;
if(!setGroupPosMode(module_no_tmp))
{
return false;
}
}
else if(strcmp(start_resrcs[i].hardware_interface.c_str(), "elfin_hardware_interface::PosVelTrqJointInterface")==0)
{
std::vector<int> module_no_tmp=module_no;
if(!setGroupPosMode(module_no_tmp))
{
return false;
}
}
else if(strcmp(start_resrcs[i].hardware_interface.c_str(), "hardware_interface::EffortJointInterface")==0)
{
std::vector<int> module_no_tmp=module_no;
if(!setGroupTrqMode(module_no_tmp))
{
return false;
}
}
else
{
if(!module_no.empty())
{
ROS_ERROR("Elfin doesn't support %s", start_resrcs[i].hardware_interface.c_str());
return false;
}
}
}
}
return true;
}
void ElfinHWInterface::doSwitch(const std::list<hardware_interface::ControllerInfo> &start_list,
const std::list<hardware_interface::ControllerInfo> &stop_list)
{
for(size_t i=0; i<pre_switch_flags_.size(); i++)
{
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[i]);
if(pre_switch_flags_[i])
{
module_infos_[i].axis1.velocity_cmd=0;
module_infos_[i].axis1.vel_ff_cmd=0;
module_infos_[i].axis1.effort_cmd=0;
module_infos_[i].axis2.velocity_cmd=0;
module_infos_[i].axis2.vel_ff_cmd=0;
module_infos_[i].axis2.effort_cmd=0;
pre_switch_flags_[i]=false;
}
pre_switch_flags_lock.unlock();
}
}
void ElfinHWInterface::read_init()
{
struct timespec read_update_tick;
clock_gettime(CLOCK_REALTIME, &read_update_tick);
read_update_time_.sec=read_update_tick.tv_sec;
read_update_time_.nsec=read_update_tick.tv_nsec;
for(size_t i=0; i<module_infos_.size(); i++)
{
int32_t pos_count1=module_infos_[i].client_ptr->getAxis1PosCnt();
double position_tmp_1=(pos_count1-module_infos_[i].axis1.count_zero)/module_infos_[i].axis1.count_rad_factor;
if(position_tmp_1>=M_PI)
{
module_infos_[i].axis1.count_zero+=module_infos_[i].axis1.count_rad_factor*2*M_PI;
}
else if(position_tmp_1<-1*M_PI)
{
module_infos_[i].axis1.count_zero-=module_infos_[i].axis1.count_rad_factor*2*M_PI;
}
module_infos_[i].axis1.position=-1*(pos_count1-module_infos_[i].axis1.count_zero)/module_infos_[i].axis1.count_rad_factor;
int32_t pos_count2=module_infos_[i].client_ptr->getAxis2PosCnt();
double position_tmp_2=(pos_count2-module_infos_[i].axis2.count_zero)/module_infos_[i].axis2.count_rad_factor;
if(position_tmp_2>=M_PI)
{
module_infos_[i].axis2.count_zero+=module_infos_[i].axis2.count_rad_factor*2*M_PI;
}
else if(position_tmp_2<-1*M_PI)
{
module_infos_[i].axis2.count_zero-=module_infos_[i].axis2.count_rad_factor*2*M_PI;
}
module_infos_[i].axis2.position=-1*(pos_count2-module_infos_[i].axis2.count_zero)/module_infos_[i].axis2.count_rad_factor;
}
}
void ElfinHWInterface::read_update(const ros::Time &time_now)
{
read_update_dur_=time_now - read_update_time_;
read_update_time_=time_now;
for(size_t i=0; i<module_infos_.size(); i++)
{
int32_t pos_count1=module_infos_[i].client_ptr->getAxis1PosCnt();
int16_t vel_count1=module_infos_[i].client_ptr->getAxis1VelCnt();
int16_t trq_count1=module_infos_[i].client_ptr->getAxis1TrqCnt();
int32_t pos_count_diff_1=pos_count1-module_infos_[i].axis1.count_zero;
double position_tmp1=-1*pos_count_diff_1/module_infos_[i].axis1.count_rad_factor;
module_infos_[i].axis1.position=position_tmp1;
module_infos_[i].axis1.velocity=-1*vel_count1/module_infos_[i].axis1.count_rad_per_s_factor;
module_infos_[i].axis1.effort=-1*trq_count1/module_infos_[i].axis1.count_Nm_factor;
int32_t pos_count2=module_infos_[i].client_ptr->getAxis2PosCnt();
int16_t vel_count2=module_infos_[i].client_ptr->getAxis2VelCnt();
int16_t trq_count2=module_infos_[i].client_ptr->getAxis2TrqCnt();
int32_t pos_count_diff_2=pos_count2-module_infos_[i].axis2.count_zero;
double position_tmp2=-1*pos_count_diff_2/module_infos_[i].axis2.count_rad_factor;
module_infos_[i].axis2.position=position_tmp2;
module_infos_[i].axis2.velocity=-1*vel_count2/module_infos_[i].axis2.count_rad_per_s_factor;
module_infos_[i].axis2.effort=-1*trq_count2/module_infos_[i].axis2.count_Nm_factor;
}
}
void ElfinHWInterface::write_update()
{
for(size_t i=0; i<module_infos_.size(); i++)
{
if(!module_infos_[i].client_ptr->inPosBasedMode())
{
module_infos_[i].axis1.position_cmd=module_infos_[i].axis1.position;
module_infos_[i].axis2.position_cmd=module_infos_[i].axis2.position;
}
double position_cmd_count1=-1 * module_infos_[i].axis1.position_cmd * module_infos_[i].axis1.count_rad_factor + module_infos_[i].axis1.count_zero;
double position_cmd_count2=-1 * module_infos_[i].axis2.position_cmd * module_infos_[i].axis2.count_rad_factor + module_infos_[i].axis2.count_zero;
module_infos_[i].client_ptr->setAxis1PosCnt(int32_t(position_cmd_count1));
module_infos_[i].client_ptr->setAxis2PosCnt(int32_t(position_cmd_count2));
bool is_preparing_switch;
boost::mutex::scoped_lock pre_switch_flags_lock(*pre_switch_mutex_ptrs_[i]);
is_preparing_switch=pre_switch_flags_[i];
pre_switch_flags_lock.unlock();
if(!is_preparing_switch)
{
double vel_ff_cmd_count1=-1 * module_infos_[i].axis1.vel_ff_cmd * module_infos_[i].axis1.count_rad_per_s_factor / 16.25;
double vel_ff_cmd_count2=-1 * module_infos_[i].axis2.vel_ff_cmd * module_infos_[i].axis2.count_rad_per_s_factor / 16.25;
module_infos_[i].client_ptr->setAxis1VelFFCnt(int16_t(vel_ff_cmd_count1));
module_infos_[i].client_ptr->setAxis2VelFFCnt(int16_t(vel_ff_cmd_count2));
double torque_cmd_count1=-1 * module_infos_[i].axis1.effort * module_infos_[i].axis1.count_Nm_factor;
double torque_cmd_count2=-1 * module_infos_[i].axis2.effort * module_infos_[i].axis2.count_Nm_factor;
module_infos_[i].client_ptr->setAxis1TrqCnt(int16_t(torque_cmd_count1));
module_infos_[i].client_ptr->setAxis2TrqCnt(int16_t(torque_cmd_count2));
}
}
}
} // end namespace elfin_ros_control
typedef struct{
controller_manager::ControllerManager *manager;
elfin_ros_control::ElfinHWInterface *elfin_hw_interface;
}ArgsForThread;
static void timespecInc(struct timespec &tick, int nsec)
{
int SEC_2_NSEC = 1e+9;
tick.tv_nsec += nsec;
while (tick.tv_nsec >= SEC_2_NSEC)
{
tick.tv_nsec -= SEC_2_NSEC;
++tick.tv_sec;
}
}
void* update_loop(void* threadarg)
{
ArgsForThread *arg=(ArgsForThread *)threadarg;
controller_manager::ControllerManager *manager=arg->manager;
elfin_ros_control::ElfinHWInterface *interface=arg->elfin_hw_interface;
ros::Duration d(0.001);
struct timespec tick;
clock_gettime(CLOCK_REALTIME, &tick);
//time for checking overrun
struct timespec before;
double overrun_time;
while(ros::ok())
{
ros::Time this_moment(tick.tv_sec, tick.tv_nsec);
interface->read_update(this_moment);
manager->update(this_moment, d);
interface->write_update();
timespecInc(tick, d.nsec);
// check overrun
clock_gettime(CLOCK_REALTIME, &before);
overrun_time = (before.tv_sec + double(before.tv_nsec)/1e+9) - (tick.tv_sec + double(tick.tv_nsec)/1e+9);
if(overrun_time > 0.0)
{
tick.tv_sec=before.tv_sec;
tick.tv_nsec=before.tv_nsec;
}
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tick, NULL);
}
}
int main(int argc, char** argv)
{
ros::init(argc,argv,"elfin_hardware_interface", ros::init_options::AnonymousName);
ros::NodeHandle nh("~");
std::string ethernet_name;
ethernet_name=nh.param<std::string>("elfin_ethernet_name", "eth0");
elfin_ethercat_driver::EtherCatManager em(ethernet_name);
elfin_ros_control::ElfinHWInterface elfin_hw(&em);
elfin_hw.read_init();
controller_manager::ControllerManager cm(&elfin_hw);
pthread_t tid;
ArgsForThread *thread_arg=new ArgsForThread();
thread_arg->manager=&cm;
thread_arg->elfin_hw_interface=&elfin_hw;
pthread_create(&tid, NULL, update_loop, thread_arg);
ros::Rate r(10);
while (ros::ok()) {
ros::spinOnce();
r.sleep();
}
}
<file_sep>/docs/Torque_HWI_english.md
Torque mode hardware interface
====
A controller with the hardware interface *'hardware_interface::EffortJointInterface'* can control the Elfin in torque mode. There is a good example: *'effort_controllers/JointTrajectoryController'*. You can use it by the following method.
1. Change the controller type in the file *elfin_robot_bringup/config/elfin_arm_control.yaml*:
```diff
- elfin_arm_controller:
- type: position_controllers/JointTrajectoryController
- joints:
- - elfin_joint1
- - elfin_joint2
- - elfin_joint3
- - elfin_joint4
- - elfin_joint5
- - elfin_joint6
- constraints:
- goal_time: 0.6
- stopped_velocity_tolerance: 0.1
- stop_trajectory_duration: 0.05
- state_publish_rate: 25
- action_monitor_rate: 10
+ elfin_arm_controller:
+ type: effort_controllers/JointTrajectoryController
+ joints:
+ - elfin_joint1
+ - elfin_joint2
+ - elfin_joint3
+ - elfin_joint4
+ - elfin_joint5
+ - elfin_joint6
+ gains:
+ elfin_joint1: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint2: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint3: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint4: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint5: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ elfin_joint6: {p: 2000, d: 10, i: 50, i_clamp: 10}
+ velocity_ff:
+ elfin_joint1: 1
+ elfin_joint2: 1
+ elfin_joint3: 1
+ elfin_joint4: 1
+ elfin_joint5: 1
+ elfin_joint6: 1
+ constraints:
+ goal_time: 0.6
+ stopped_velocity_tolerance: 0.1
+ stop_trajectory_duration: 0.05
+ state_publish_rate: 25
+ action_monitor_rate: 10
```
gains: PID parameters
velocity_ff: velocity related feedforward factor. velocity_ff * desired_velocity = velocity_related_feedforward_torque
**Please note: The PID parameters in the above example are not optimal parameters. Please set the PID parameters reasonably, otherwise it may cause dangerous situations.**
2. Start the robot arm normally as described in the [README_english.md](../README_english.md)
3. Now you can control the robot with an effort controller and adjust pid parameters with rqt_reconfigure.
```sh
rosrun rqt_reconfigure rqt_reconfigure
```
<file_sep>/elfin_kinematic_solver/include/elfin_kinematic_solver/elfin_kinematic_solver.h
/*
Created on Wed Dec 05 10:15:12 2018
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2018, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#ifndef ELFIN_KINEMATIC_SOLVER_H
#define ELFIN_KINEMATIC_SOLVER_H
#include <ros/ros.h>
#include <vector>
#include <eigen3/Eigen/Eigen>
namespace elfin3_ikfast_simple_api{
// class for storing and sorting solutions
class LimitObeyingSol
{
public:
std::vector<double> value;
double dist_from_seed;
bool operator<(const LimitObeyingSol& a) const
{
return dist_from_seed < a.dist_from_seed;
}
};
// class for forward and inverse kinematic solutions
class Elfin3KinematicSolver{
public:
/**
* @brief Given a desired pose of the end-effector, compute the joint angles to reach it
* @param trans The desired position of the end-effector
* @param orient The desired orientation of the end-effector
* @param vfree The vector of the free links. Since elfin is a 6dof robot, there is no free link.
* So \p vfree should be set as an empty vector
* @param seed_state An initial guess solution for the inverse kinematics
* @param solution A calculated set of joint angles that is closest to \p seed_state
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionIK(const Eigen::Vector3d& trans, const Eigen::Matrix3d& orient, const std::vector<double>& vfree,
const std::vector<double>& seed_state, std::vector<double>& solution);
/**
* @brief Given a set of joint angles, compute the pose of the end-effector
* @param joint_angles The state for which FK is being computed
* @param trans The calculated position of the end-effector
* @param orient The calculated orientation of the end-effector
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionFK(const std::vector<double>& joint_angles, Eigen::Vector3d& trans, Eigen::Matrix3d& orient);
};
}
namespace elfin5_ikfast_simple_api{
// class for storing and sorting solutions
class LimitObeyingSol
{
public:
std::vector<double> value;
double dist_from_seed;
bool operator<(const LimitObeyingSol& a) const
{
return dist_from_seed < a.dist_from_seed;
}
};
// class for forward and inverse kinematic solutions
class Elfin5KinematicSolver{
public:
/**
* @brief Given a desired pose of the end-effector, compute the joint angles to reach it
* @param trans The desired position of the end-effector
* @param orient The desired orientation of the end-effector
* @param vfree The vector of the free links. Since elfin is a 6dof robot, there is no free link.
* So \p vfree should be set as an empty vector
* @param seed_state An initial guess solution for the inverse kinematics
* @param solution A calculated set of joint angles that is closest to \p seed_state
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionIK(const Eigen::Vector3d& trans, const Eigen::Matrix3d& orient, const std::vector<double>& vfree,
const std::vector<double>& seed_state, std::vector<double>& solution);
/**
* @brief Given a set of joint angles, compute the pose of the end-effector
* @param joint_angles The state for which FK is being computed
* @param trans The calculated position of the end-effector
* @param orient The calculated orientation of the end-effector
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionFK(const std::vector<double>& joint_angles, Eigen::Vector3d& trans, Eigen::Matrix3d& orient);
};
}
namespace elfin10_ikfast_simple_api{
// class for storing and sorting solutions
class LimitObeyingSol
{
public:
std::vector<double> value;
double dist_from_seed;
bool operator<(const LimitObeyingSol& a) const
{
return dist_from_seed < a.dist_from_seed;
}
};
// class for forward and inverse kinematic solutions
class Elfin10KinematicSolver{
public:
/**
* @brief Given a desired pose of the end-effector, compute the joint angles to reach it
* @param trans The desired position of the end-effector
* @param orient The desired orientation of the end-effector
* @param vfree The vector of the free links. Since elfin is a 6dof robot, there is no free link.
* So \p vfree should be set as an empty vector
* @param seed_state An initial guess solution for the inverse kinematics
* @param solution A calculated set of joint angles that is closest to \p seed_state
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionIK(const Eigen::Vector3d& trans, const Eigen::Matrix3d& orient, const std::vector<double>& vfree,
const std::vector<double>& seed_state, std::vector<double>& solution);
/**
* @brief Given a set of joint angles, compute the pose of the end-effector
* @param joint_angles The state for which FK is being computed
* @param trans The calculated position of the end-effector
* @param orient The calculated orientation of the end-effector
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionFK(const std::vector<double>& joint_angles, Eigen::Vector3d& trans, Eigen::Matrix3d& orient);
};
}
namespace elfin15_ikfast_simple_api{
// class for storing and sorting solutions
class LimitObeyingSol
{
public:
std::vector<double> value;
double dist_from_seed;
bool operator<(const LimitObeyingSol& a) const
{
return dist_from_seed < a.dist_from_seed;
}
};
// class for forward and inverse kinematic solutions
class Elfin15KinematicSolver{
public:
/**
* @brief Given a desired pose of the end-effector, compute the joint angles to reach it
* @param trans The desired position of the end-effector
* @param orient The desired orientation of the end-effector
* @param vfree The vector of the free links. Since elfin is a 6dof robot, there is no free link.
* So \p vfree should be set as an empty vector
* @param seed_state An initial guess solution for the inverse kinematics
* @param solution A calculated set of joint angles that is closest to \p seed_state
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionIK(const Eigen::Vector3d& trans, const Eigen::Matrix3d& orient, const std::vector<double>& vfree,
const std::vector<double>& seed_state, std::vector<double>& solution);
/**
* @brief Given a set of joint angles, compute the pose of the end-effector
* @param joint_angles The state for which FK is being computed
* @param trans The calculated position of the end-effector
* @param orient The calculated orientation of the end-effector
* @return Returns \c true in the case of success, \c false otherwise.
*/
bool getPositionFK(const std::vector<double>& joint_angles, Eigen::Vector3d& trans, Eigen::Matrix3d& orient);
};
}
#endif
<file_sep>/elfin_basic_api/src/elfin_teleop_api.cpp
/*
Created on Mon Nov 13 15:20:10 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// author: <NAME>
#include "elfin_basic_api/elfin_teleop_api.h"
namespace elfin_basic_api {
ElfinTeleopAPI::ElfinTeleopAPI(moveit::planning_interface::MoveGroupInterface *group, std::string action_name, planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor):
group_(group), action_client_(action_name, true), planning_scene_monitor_(planning_scene_monitor), teleop_nh_("~")
{
goal_.trajectory.joint_names=group_->getJointNames();
goal_.trajectory.header.stamp.sec=0;
goal_.trajectory.header.stamp.nsec=0;
sub_teleop_joint_command_no_limit_=root_nh_.subscribe("elfin_teleop_joint_cmd_no_limit", 1, &ElfinTeleopAPI::teleopJointCmdNoLimitCB, this);
joint_teleop_server_=teleop_nh_.advertiseService("joint_teleop", &ElfinTeleopAPI::jointTeleop_cb, this);
cart_teleop_server_=teleop_nh_.advertiseService("cart_teleop", &ElfinTeleopAPI::cartTeleop_cb, this);
home_teleop_server_=teleop_nh_.advertiseService("home_teleop", &ElfinTeleopAPI::homeTeleop_cb, this);
teleop_stop_server_=teleop_nh_.advertiseService("stop_teleop", &ElfinTeleopAPI::teleopStop_cb, this);
// parameter for teleop no limit
joint_step_=M_PI/100;
joint_duration_ns_=1e+8;
// parameter for normal teleop
joint_speed_limit_=JOINT_SPEED_LIMIT_CONST;
joint_speed_default_=JOINT_SPEED_DEFAULT_CONST;
cart_duration_default_=CART_DURATION_DEFAULT_CONST;
resolution_angle_=0.02;
resolution_linear_=0.005;
end_link_=group_->getEndEffectorLink();
reference_link_=group_->getPlanningFrame();
default_tip_link_=group_->getEndEffectorLink();
root_link_=group_->getPlanningFrame();
}
void ElfinTeleopAPI::setVelocityScaling(double data)
{
velocity_scaling_=data;
joint_speed_=joint_speed_default_*velocity_scaling_;
cart_duration_=cart_duration_default_/velocity_scaling_;
group_->setMaxVelocityScalingFactor(velocity_scaling_);
}
void ElfinTeleopAPI::setRefFrames(std::string ref_link)
{
reference_link_=ref_link;
}
void ElfinTeleopAPI::setEndFrames(std::string end_link)
{
end_link_=end_link;
}
void ElfinTeleopAPI::teleopJointCmdNoLimitCB(const std_msgs::Int64ConstPtr &msg)
{
if(msg->data==0 || abs(msg->data)>goal_.trajectory.joint_names.size())
return;
int joint_num=abs(msg->data);
int symbol;
if(joint_num==msg->data)
symbol=1;
else
symbol=-1;
trajectory_msgs::JointTrajectoryPoint point_tmp;
std::vector<double> position_tmp=group_->getCurrentJointValues();
position_tmp[joint_num-1]+=symbol*joint_step_;
point_tmp.positions=position_tmp;
point_tmp.time_from_start.nsec=joint_duration_ns_;
goal_.trajectory.points.push_back(point_tmp);
action_client_.sendGoal(goal_);
goal_.trajectory.points.clear();
}
bool ElfinTeleopAPI::jointTeleop_cb(elfin_robot_msgs::SetInt16::Request &req, elfin_robot_msgs::SetInt16::Response &resp)
{
if(req.data==0 || abs(req.data)>goal_.trajectory.joint_names.size())
{
resp.success=false;
resp.message="wrong joint teleop data";
return true;
}
int joint_num=abs(req.data);
std::vector<double> position_current=group_->getCurrentJointValues();
std::vector<double> position_goal=position_current;
double joint_current_position=position_current[joint_num-1];
std::string direction=goal_.trajectory.joint_names[joint_num-1];
double sign;
if(joint_num==req.data)
{
position_goal[joint_num-1]=group_->getRobotModel()->getURDF()->getJoint(goal_.trajectory.joint_names[joint_num-1])->limits->upper;
direction.append("+");
sign=1;
}
else
{
position_goal[joint_num-1]=group_->getRobotModel()->getURDF()->getJoint(goal_.trajectory.joint_names[joint_num-1])->limits->lower;
direction.append("-");
sign=-1;
}
double duration_from_speed=fabs(position_goal[joint_num-1]-joint_current_position)/joint_speed_;
if(duration_from_speed<=0.1)
{
resp.success=false;
std::string result="robot can't move in ";
result.append(direction);
result.append(" direction any more");
resp.message=result;
return true;
}
trajectory_msgs::JointTrajectoryPoint point_tmp;
robot_state::RobotStatePtr kinematic_state_ptr=group_->getCurrentState();
robot_state::RobotState kinematic_state=*kinematic_state_ptr;
const robot_state::JointModelGroup* joint_model_group = kinematic_state.getJointModelGroup(group_->getName());
planning_scene_monitor_->updateFrameTransforms();
planning_scene::PlanningSceneConstPtr plan_scene=planning_scene_monitor_->getPlanningScene();
std::vector<double> position_tmp=position_current;
bool collision_flag=false;
int loop_num=1;
while(fabs(position_goal[joint_num-1]-position_tmp[joint_num-1])/joint_speed_>0.1)
{
position_tmp[joint_num-1]+=joint_speed_*0.1*sign;
kinematic_state.setJointGroupPositions(joint_model_group, position_tmp);
if(plan_scene->isStateColliding(kinematic_state, group_->getName()))
{
if(loop_num==1)
{
resp.success=false;
std::string result="robot can't move in ";
result.append(direction);
result.append(" direction any more");
resp.message=result;
return true;
}
collision_flag=true;
break;
}
point_tmp.time_from_start=ros::Duration(0.1*loop_num);
point_tmp.positions=position_tmp;
goal_.trajectory.points.push_back(point_tmp);
loop_num++;
}
if(!collision_flag)
{
kinematic_state.setJointGroupPositions(joint_model_group, position_goal);
if(!plan_scene->isStateColliding(kinematic_state, group_->getName()))
{
point_tmp.positions=position_goal;
ros::Duration dur(duration_from_speed);
point_tmp.time_from_start=dur;
goal_.trajectory.points.push_back(point_tmp);
}
}
action_client_.sendGoal(goal_);
goal_.trajectory.points.clear();
resp.success=true;
std::string result="robot is moving in ";
result.append(direction);
result.append(" direction");
resp.message=result;
return true;
}
bool ElfinTeleopAPI::cartTeleop_cb(elfin_robot_msgs::SetInt16::Request &req, elfin_robot_msgs::SetInt16::Response &resp)
{
if(req.data==0 || abs(req.data)>6)
{
resp.success=false;
resp.message="wrong cart. teleop data";
return true;
}
int operation_num=abs(req.data);
int symbol;
if(operation_num==req.data)
symbol=1;
else
symbol=-1;
geometry_msgs::PoseStamped current_pose=group_->getCurrentPose(end_link_);
ros::Rate r(100);
int counter=0;
while(ros::ok())
{
try{
tf_listener_.waitForTransform(reference_link_, root_link_, ros::Time(0), ros::Duration(10.0) );
tf_listener_.lookupTransform(reference_link_, root_link_, ros::Time(0), transform_rootToRef_);
break;
}
catch (tf::TransformException &ex) {
r.sleep();
counter++;
if(counter>200)
{
ROS_ERROR("%s",ex.what());
resp.success=false;
resp.message="can't get pose of reference frame";
return true;
}
continue;
}
}
counter=0;
while(ros::ok())
{
try{
tf_listener_.waitForTransform(end_link_, default_tip_link_, ros::Time(0), ros::Duration(10.0) );
tf_listener_.lookupTransform(end_link_, default_tip_link_, ros::Time(0), transform_tipToEnd_);
break;
}
catch (tf::TransformException &ex) {
r.sleep();
counter++;
if(counter>200)
{
ROS_ERROR("%s",ex.what());
resp.success=false;
resp.message="can't get pose of teleop frame";
return true;
}
continue;
}
}
Eigen::Isometry3d affine_rootToRef, affine_refToRoot;
tf::transformTFToEigen(transform_rootToRef_, affine_rootToRef);
affine_refToRoot=affine_rootToRef.inverse();
Eigen::Isometry3d affine_tipToEnd;
tf::transformTFToEigen(transform_tipToEnd_, affine_tipToEnd);
tf::Pose tf_pose_tmp;
Eigen::Isometry3d affine_pose_tmp;
tf::poseMsgToTF(current_pose.pose, tf_pose_tmp);
tf::poseTFToEigen(tf_pose_tmp, affine_pose_tmp);
Eigen::Isometry3d affine_current_pose=affine_rootToRef * affine_pose_tmp;
tf::poseEigenToTF(affine_current_pose, tf_pose_tmp);
tf::poseTFToMsg(tf_pose_tmp, current_pose.pose);
std::vector<double> current_joint_states=group_->getCurrentJointValues();
tf::Vector3 x_axis(1, 0, 0);
tf::Vector3 y_axis(0, 1, 0);
tf::Vector3 z_axis(0, 0, 1);
double resolution_alpha=resolution_angle_;
double resolution_delta=resolution_linear_;
robot_state::RobotStatePtr kinematic_state_ptr=group_->getCurrentState();
robot_state::RobotState kinematic_state=*kinematic_state_ptr;
const robot_state::JointModelGroup* joint_model_group = kinematic_state.getJointModelGroup(group_->getName());
planning_scene_monitor_->updateFrameTransforms();
planning_scene::PlanningSceneConstPtr plan_scene=planning_scene_monitor_->getPlanningScene();
trajectory_msgs::JointTrajectoryPoint point_tmp;
std::string direction;
bool ik_have_result=true;
for(int i=0; i<100; i++)
{
switch (operation_num) {
case 1:
current_pose.pose.position.x+=symbol*resolution_delta;
if(symbol==1)
direction="X+";
else
direction="X-";
break;
case 2:
current_pose.pose.position.y+=symbol*resolution_delta;
if(symbol==1)
direction="Y+";
else
direction="Y-";
break;
case 3:
current_pose.pose.position.z+=symbol*resolution_delta;
if(symbol==1)
direction="Z+";
else
direction="Z-";
break;
case 4:
PoseStampedRotation(current_pose, x_axis, symbol*resolution_alpha);
if(symbol==1)
direction="Rx+";
else
direction="Rx-";
break;
case 5:
PoseStampedRotation(current_pose, y_axis, symbol*resolution_alpha);
if(symbol==1)
direction="Ry+";
else
direction="Ry-";
break;
case 6:
PoseStampedRotation(current_pose, z_axis, symbol*resolution_alpha);
if(symbol==1)
direction="Rz+";
else
direction="Rz-";
break;
default:
break;
}
tf::poseMsgToTF(current_pose.pose, tf_pose_tmp);
tf::poseTFToEigen(tf_pose_tmp, affine_pose_tmp);
affine_current_pose=affine_refToRoot * affine_pose_tmp * affine_tipToEnd;
ik_have_result=kinematic_state.setFromIK(joint_model_group, affine_current_pose, default_tip_link_);
if(ik_have_result)
{
if(goal_.trajectory.points.size()!=i)
break;
point_tmp.positions.resize(goal_.trajectory.joint_names.size());
double biggest_shift=0;
for(int j=0; j<goal_.trajectory.joint_names.size(); j++)
{
point_tmp.positions[j]=*kinematic_state.getJointPositions(goal_.trajectory.joint_names[j]);
if(i==0)
{
double shift_tmp=fabs(current_joint_states[j]-point_tmp.positions[j]);
if(shift_tmp>biggest_shift)
biggest_shift=shift_tmp;
}
else {
double shift_tmp=fabs(goal_.trajectory.points[i-1].positions[j]-point_tmp.positions[j]);
if(shift_tmp>biggest_shift)
biggest_shift=shift_tmp;
}
}
if(biggest_shift>cart_duration_*joint_speed_limit_ || plan_scene->isStateColliding(kinematic_state, group_->getName()))
break;
ros::Duration dur((i+1)*cart_duration_);
point_tmp.time_from_start=dur;
goal_.trajectory.points.push_back(point_tmp);
}
else
{
break;
}
}
if(goal_.trajectory.points.size()==0)
{
resp.success=false;
std::string result="robot can't move in ";
result.append(direction);
result.append(" direction any more");
resp.message=result;
return true;
}
action_client_.sendGoal(goal_);
goal_.trajectory.points.clear();
resp.success=true;
std::string result="robot is moving in ";
result.append(direction);
result.append(" direction");
resp.message=result;
return true;
}
bool ElfinTeleopAPI::homeTeleop_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
std::vector<double> position_current=group_->getCurrentJointValues();
std::vector<double> position_goal;
double biggest_shift=0;
int biggest_shift_num;
std::vector<double> joint_ratios;
joint_ratios.resize(position_current.size());
if(position_current.size()!=goal_.trajectory.joint_names.size())
{
resp.success=false;
resp.message="the joints number is wrong";
return true;
}
for(int i=0; i<position_current.size(); i++)
{
if(fabs(position_current[i])>biggest_shift)
{
biggest_shift=fabs(position_current[i]);
biggest_shift_num=i;
}
position_goal.push_back(0);
}
if(biggest_shift<0.001)
{
resp.success=false;
std::string result="Elfin is already in home position";
resp.message=result;
return true;
}
for(int i=0; i<joint_ratios.size(); i++)
{
joint_ratios[i]=position_current[i]/position_current[biggest_shift_num];
}
trajectory_msgs::JointTrajectoryPoint point_tmp;
robot_state::RobotStatePtr kinematic_state_ptr=group_->getCurrentState();
robot_state::RobotState kinematic_state=*kinematic_state_ptr;
const robot_state::JointModelGroup* joint_model_group = kinematic_state.getJointModelGroup(group_->getName());
planning_scene_monitor_->updateFrameTransforms();
planning_scene::PlanningSceneConstPtr plan_scene=planning_scene_monitor_->getPlanningScene();
std::vector<double> position_tmp=position_current;
bool collision_flag=false;
int loop_num=1;
double sign=biggest_shift/position_tmp[biggest_shift_num];
double duration_from_speed=biggest_shift/joint_speed_;
while(fabs(position_goal[biggest_shift_num]-position_tmp[biggest_shift_num])/joint_speed_>0.1)
{
for(int i=0; i<position_tmp.size(); i++)
{
position_tmp[i]-=joint_speed_*0.1*sign*joint_ratios[i];
}
kinematic_state.setJointGroupPositions(joint_model_group, position_tmp);
if(plan_scene->isStateColliding(kinematic_state, group_->getName()))
{
if(loop_num==1)
{
resp.success=false;
std::string result="Stop going to home position";
resp.message=result;
return true;
}
collision_flag=true;
break;
}
point_tmp.time_from_start=ros::Duration(0.1*loop_num);
point_tmp.positions=position_tmp;
goal_.trajectory.points.push_back(point_tmp);
loop_num++;
}
if(!collision_flag)
{
kinematic_state.setJointGroupPositions(joint_model_group, position_goal);
if(!plan_scene->isStateColliding(kinematic_state, group_->getName()))
{
point_tmp.positions=position_goal;
ros::Duration dur(duration_from_speed);
point_tmp.time_from_start=dur;
goal_.trajectory.points.push_back(point_tmp);
}
else if(loop_num==1)
{
resp.success=false;
std::string result="Stop going to home position";
resp.message=result;
return true;
}
}
action_client_.sendGoal(goal_);
goal_.trajectory.points.clear();
resp.success=true;
std::string result="robot is moving to home position";
resp.message=result;
return true;
}
bool ElfinTeleopAPI::teleopStop_cb(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &resp)
{
goal_.trajectory.points.clear();
action_client_.sendGoal(goal_);
resp.success=true;
resp.message="stop moving";
return true;
}
void ElfinTeleopAPI::PoseStampedRotation(geometry_msgs::PoseStamped &pose_stamped, const tf::Vector3 &axis, double angle)
{
tf::Quaternion q_1(pose_stamped.pose.orientation.x, pose_stamped.pose.orientation.y,
pose_stamped.pose.orientation.z, pose_stamped.pose.orientation.w);
tf::Quaternion q_2(axis, angle);
tf::Matrix3x3 m(q_1);
tf::Matrix3x3 m_2(q_2);
m_2.operator *=(m);
double r, p, y;
m_2.getRPY(r,p,y);
q_2.setRPY(r, p, y);
pose_stamped.pose.orientation.x=q_2.getX();
pose_stamped.pose.orientation.y=q_2.getY();
pose_stamped.pose.orientation.z=q_2.getZ();
pose_stamped.pose.orientation.w=q_2.getW();
}
} // end namespace elfin_basic_api
<file_sep>/docs/moveit_plugin_tutorial_english.md
### MoveIt! RViz Plugin Tutorial
More detailed tutorial:
http://docs.ros.org/indigo/api/moveit_tutorials/html/doc/ros_visualization/visualization_tutorial.html
#### Set start state
In the “Planning” tab of the “Motion Planning” subwindow, set the "Select Start State" field to “current”. Then click the "Update" button.

#### Set goal state
Use the marker (which are attached to the tip link of the arm) to drag the arm to a desired goal state.

#### Plan a trajectory
After setting the start state and goal state, wait for around 5 seconds, then press the "Plan" button. You should be able to see a visualization of the arm moving.

#### Execute the trajectory
Press the "Execute" button, robot will move as planned. In this process, you can press the "Stop" button to make the robot stop.
<file_sep>/elfin_robot_bringup/script/cmd_pub.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 27 15:02:10 2017
@author: <NAME>
Software License Agreement (BSD License)
Copyright (c) 2017, Han's Robot Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
# author: <NAME>
import rospy
from sensor_msgs.msg import JointState
from geometry_msgs.msg import PoseStamped, PoseArray, Pose
class CmdPub(object):
def __init__(self):
self.joints_pub=rospy.Publisher('elfin_basic_api/joint_goal', JointState, queue_size=1)
self.cart_pub=rospy.Publisher('elfin_basic_api/cart_goal', PoseStamped, queue_size=1)
self.cart_path_pub=rospy.Publisher('elfin_basic_api/cart_path_goal', PoseArray, queue_size=1)
def function_pub_joints(self):
js=JointState()
js.name=['elfin_joint1', 'elfin_joint2', 'elfin_joint3',
'elfin_joint4', 'elfin_joint5', 'elfin_joint6']
js.position=[0.4, 0.4, 0.4, 0.4, 0.4, 0.4]
js.header.stamp=rospy.get_rostime()
self.joints_pub.publish(js)
def function_pub_cart_elfin3(self):
ps=PoseStamped()
ps.header.stamp=rospy.get_rostime()
ps.header.frame_id='elfin_base_link'
ps.pose.position.x=0.161
ps.pose.position.y=0.061
ps.pose.position.z=0.719
ps.pose.orientation.x=0
ps.pose.orientation.y=0
ps.pose.orientation.z=0
ps.pose.orientation.w=1
self.cart_pub.publish(ps)
# You'd better run this function when the robot has finished
# the motion in function_pub_cart_elfin3()
def function_pub_cart_path_elfin3(self):
pa=PoseArray()
pa.header.stamp=rospy.get_rostime()
pa.header.frame_id='elfin_base_link'
ps=Pose()
ps.position.x=0.201
ps.position.y=0.141
ps.position.z=0.719
ps.orientation.x=0
ps.orientation.y=0
ps.orientation.z=0
ps.orientation.w=1
ps1=Pose()
ps1.position.x=0.241
ps1.position.y=0.221
ps1.position.z=0.719
ps1.orientation.x=0
ps1.orientation.y=0
ps1.orientation.z=0
ps1.orientation.w=1
pa.poses.append(ps)
pa.poses.append(ps1)
self.cart_path_pub.publish(pa)
def function_pub_cart_elfin5(self):
ps=PoseStamped()
ps.header.stamp=rospy.get_rostime()
ps.header.frame_id='elfin_base_link'
ps.pose.position.x=0.258
ps.pose.position.y=-0.031
ps.pose.position.z=0.927
ps.pose.orientation.x=0
ps.pose.orientation.y=0
ps.pose.orientation.z=0
ps.pose.orientation.w=1
self.cart_pub.publish(ps)
# You'd better run this function when the robot has finished
# the motion in function_pub_cart_elfin5()
def function_pub_cart_path_elfin5(self):
pa=PoseArray()
pa.header.stamp=rospy.get_rostime()
pa.header.frame_id='elfin_base_link'
ps=Pose()
ps.position.x=0.308
ps.position.y=-0.131
ps.position.z=0.927
ps.orientation.x=0
ps.orientation.y=0
ps.orientation.z=0
ps.orientation.w=1
ps1=Pose()
ps1.position.x=0.358
ps1.position.y=-0.231
ps1.position.z=0.927
ps1.orientation.x=0
ps1.orientation.y=0
ps1.orientation.z=0
ps1.orientation.w=1
pa.poses.append(ps)
pa.poses.append(ps1)
self.cart_path_pub.publish(pa)
def function_pub_cart_elfin10(self):
ps=PoseStamped()
ps.header.stamp=rospy.get_rostime()
ps.header.frame_id='elfin_base_link'
ps.pose.position.x=0.204
ps.pose.position.y=0.005
ps.pose.position.z=1.143
ps.pose.orientation.x=0
ps.pose.orientation.y=0
ps.pose.orientation.z=0
ps.pose.orientation.w=1
self.cart_pub.publish(ps)
# You'd better run this function when the robot has finished
# the motion in function_pub_cart_elfin10()
def function_pub_cart_path_elfin10(self):
pa=PoseArray()
pa.header.stamp=rospy.get_rostime()
pa.header.frame_id='elfin_base_link'
ps=Pose()
ps.position.x=0.264
ps.position.y=0.125
ps.position.z=1.143
ps.orientation.x=0
ps.orientation.y=0
ps.orientation.z=0
ps.orientation.w=1
ps1=Pose()
ps1.position.x=0.324
ps1.position.y=0.245
ps1.position.z=1.143
ps1.orientation.x=0
ps1.orientation.y=0
ps1.orientation.z=0
ps1.orientation.w=1
pa.poses.append(ps)
pa.poses.append(ps1)
self.cart_path_pub.publish(pa)
if __name__=='__main__':
rospy.init_node('cmd_pub', anonymous=True)
cp=CmdPub()
rospy.sleep(1)
cp.function_pub_joints()
# cp.function_pub_cart_elfin3()
# cp.function_pub_cart_path_elfin3()
# cp.function_pub_cart_elfin5()
# cp.function_pub_cart_path_elfin5()
# cp.function_pub_cart_elfin10()
# cp.function_pub_cart_path_elfin10()
rospy.spin()
|
c03419c6223d10b5f0719f9a0da41a00b7859e17
|
[
"CMake",
"Markdown",
"Python",
"C++",
"Shell"
] | 43
|
C++
|
hans-robot/elfin_robot
|
cb8abeb49c096f75c8a92b9fac3425de5f889eec
|
127e62362498080850867835febbbb21db8b7c89
|
refs/heads/master
|
<file_sep>module ComfortableMexicanSofa::Fixtures
def self.sync(site)
sync_layouts(site)
sync_pages(site)
sync_snippets(site)
end
def self.sync_layouts(site, path = nil, root = true, parent = nil, layout_ids = [])
return unless path ||= find_path(site, 'layouts')
Dir.glob("#{path}/*").select{|f| File.directory?(f)}.each do |path|
slug = path.split('/').last
layout = site.layouts.find_by_slug(slug) || site.layouts.new(:slug => slug)
# updating attributes
if File.exists?(file_path = File.join(path, "_#{slug}.yml"))
if layout.new_record? || File.mtime(file_path) > layout.updated_at
attributes = YAML.load_file(file_path).symbolize_keys!
layout.label = attributes[:label] || slug.titleize
layout.app_layout = attributes[:app_layout] || parent.try(:app_layout)
end
elsif layout.new_record?
layout.label = slug.titleize
layout.app_layout = parent.try(:app_layout)
end
# updating content
if File.exists?(file_path = File.join(path, 'content.html'))
if layout.new_record? || File.mtime(file_path) > layout.updated_at
layout.content = File.open(file_path, 'rb').read
end
end
if File.exists?(file_path = File.join(path, 'css.css'))
if layout.new_record? || File.mtime(file_path) > layout.updated_at
layout.css = File.open(file_path, 'rb').read
end
end
if File.exists?(file_path = File.join(path, 'js.js'))
if layout.new_record? || File.mtime(file_path) > layout.updated_at
layout.js = File.open(file_path, 'rb').read
end
end
# saving
layout.parent = parent
layout.save! if layout.changed?
layout_ids << layout.id
# checking for nested fixtures
layout_ids += sync_layouts(site, path, false, layout, layout_ids)
end
# removing all db entries that are not in fixtures
site.layouts.where('id NOT IN (?)', layout_ids.uniq).each{ |l| l.destroy } if root
# returning ids of layouts in fixtures
layout_ids
end
def self.sync_pages(site, path = nil, root = true, parent = nil, page_ids = [])
return unless path ||= find_path(site, 'pages')
Dir.glob("#{path}/*").select{|f| File.directory?(f)}.each do |path|
slug = path.split('/').last
page = if parent
parent.children.find_by_slug(slug) || parent.children.new(:slug => slug, :site => site)
else
site.pages.root || site.pages.new(:slug => slug)
end
# updating attributes
if File.exists?(file_path = File.join(path, "_#{slug}.yml"))
if page.new_record? || File.mtime(file_path) > page.updated_at
attributes = YAML.load_file(file_path).symbolize_keys!
page.label = attributes[:label] || slug.titleize
page.layout = site.layouts.find_by_slug(attributes[:layout]) || parent.try(:layout)
page.target_page = site.pages.find_by_full_path(attributes[:target_page])
page.is_published = attributes[:is_published].present?? attributes[:is_published] : true
end
elsif page.new_record?
page.label = slug.titleize
page.layout = site.layouts.find_by_slug(attributes[:layout]) || parent.try(:layout)
end
# updating content
blocks_attributes = [ ]
Dir.glob("#{path}/*.html").each do |file_path|
if page.new_record? || File.mtime(file_path) > page.updated_at
label = file_path.split('/').last.split('.').first
blocks_attributes << {
:label => label,
:content => File.open(file_path, 'rb').read
}
end
end
# saving
page.blocks_attributes = blocks_attributes if blocks_attributes.present?
page.save! if page.changed? || blocks_attributes.present?
page_ids << page.id
# checking for nested fixtures
page_ids += sync_pages(site, path, false, page, page_ids)
end
# removing all db entries that are not in fixtures
site.pages.where('id NOT IN (?)', page_ids.uniq).each{ |p| p.destroy } if root
# returning ids of layouts in fixtures
page_ids
end
def self.sync_snippets(site)
return unless path = find_path(site, 'snippets')
snippet_ids = []
Dir.glob("#{path}/*").select{|f| File.directory?(f)}.each do |path|
slug = path.split('/').last
snippet = site.snippets.find_by_slug(slug) || site.snippets.new(:slug => slug)
# updating attributes
if File.exists?(file_path = File.join(path, "_#{slug}.yml"))
if snippet.new_record? || File.mtime(file_path) > snippet.updated_at
attributes = YAML.load_file(file_path).symbolize_keys!
snippet.label = attributes[:label] || slug.titleize
end
elsif snippet.new_record?
snippet.label = slug.titleize
end
# updating content
if File.exists?(file_path = File.join(path, 'content.html'))
if snippet.new_record? || File.mtime(file_path) > snippet.updated_at
snippet.content = File.open(file_path, 'rb').read
end
end
# saving
snippet.save! if snippet.changed?
snippet_ids << snippet.id
end
# removing all db entries that are not in fixtures
site.snippets.where('id NOT IN (?)', snippet_ids).each{ |s| s.destroy }
end
def self.find_path(site, dir)
path = nil
File.exists?(path = File.join(ComfortableMexicanSofa.config.fixtures_path, site.hostname, dir)) ||
!ComfortableMexicanSofa.config.enable_multiple_sites &&
File.exists?(path = File.join(ComfortableMexicanSofa.config.fixtures_path, dir))
return path
end
end<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class FixturesTest < ActiveSupport::TestCase
def setup
@site = cms_sites(:default)
@site.update_attribute(:hostname, 'example.com')
end
def test_sync
Cms::Page.destroy_all
Cms::Layout.destroy_all
Cms::Snippet.destroy_all
assert_difference 'Cms::Layout.count', 2 do
assert_difference 'Cms::Page.count', 2 do
assert_difference 'Cms::Snippet.count', 1 do
ComfortableMexicanSofa::Fixtures.sync(@site)
end
end
end
end
def test_sync_layouts_creating
Cms::Layout.delete_all
assert_difference 'Cms::Layout.count', 2 do
ComfortableMexicanSofa::Fixtures.sync_layouts(@site)
assert layout = Cms::Layout.find_by_slug('default')
assert_equal 'Default Fixture Layout', layout.label
assert_equal "<html>\n <body>\n {{ cms:page:content }}\n </body>\n</html>", layout.content
assert_equal 'body{color: red}', layout.css
assert_equal '// default js', layout.js
assert nested_layout = Cms::Layout.find_by_slug('nested')
assert_equal layout, nested_layout.parent
assert_equal 'Default Fixture Nested Layout', nested_layout.label
assert_equal "<div class='left'> {{ cms:page:left }} </div>\n<div class='right'> {{ cms:page:right }} </div>", nested_layout.content
assert_equal 'div{float:left}', nested_layout.css
assert_equal '// nested js', nested_layout.js
end
end
def test_sync_layouts_updating_and_deleting
layout = cms_layouts(:default)
nested_layout = cms_layouts(:nested)
child_layout = cms_layouts(:child)
layout.update_attribute(:updated_at, 10.years.ago)
nested_layout.update_attribute(:updated_at, 10.years.ago)
child_layout.update_attribute(:updated_at, 10.years.ago)
assert_difference 'Cms::Layout.count', -1 do
ComfortableMexicanSofa::Fixtures.sync_layouts(@site)
layout.reload
assert_equal 'Default Fixture Layout', layout.label
assert_equal "<html>\n <body>\n {{ cms:page:content }}\n </body>\n</html>", layout.content
assert_equal 'body{color: red}', layout.css
assert_equal '// default js', layout.js
nested_layout.reload
assert_equal layout, nested_layout.parent
assert_equal 'Default Fixture Nested Layout', nested_layout.label
assert_equal "<div class='left'> {{ cms:page:left }} </div>\n<div class='right'> {{ cms:page:right }} </div>", nested_layout.content
assert_equal 'div{float:left}', nested_layout.css
assert_equal '// nested js', nested_layout.js
assert_nil Cms::Layout.find_by_slug('child')
end
end
def test_sync_layouts_ignoring
layout = cms_layouts(:default)
layout_path = File.join(ComfortableMexicanSofa.config.fixtures_path, @site.hostname, 'layouts', 'default')
attr_file_path = File.join(layout_path, '_default.yml')
content_file_path = File.join(layout_path, 'content.html')
css_file_path = File.join(layout_path, 'css.css')
js_file_path = File.join(layout_path, 'js.js')
assert layout.updated_at >= File.mtime(attr_file_path)
assert layout.updated_at >= File.mtime(content_file_path)
assert layout.updated_at >= File.mtime(css_file_path)
assert layout.updated_at >= File.mtime(js_file_path)
ComfortableMexicanSofa::Fixtures.sync_layouts(@site)
layout.reload
assert_equal 'default', layout.slug
assert_equal 'Default Layout', layout.label
assert_equal "{{cms:field:default_field_text:text}}\nlayout_content_a\n{{cms:page:default_page_text:text}}\nlayout_content_b\n{{cms:snippet:default}}\nlayout_content_c", layout.content
assert_equal 'default_css', layout.css
assert_equal 'default_js', layout.js
end
def test_sync_pages_creating
Cms::Page.delete_all
layout = cms_layouts(:default)
layout.update_attribute(:content, '<html>{{cms:page:content}}</html>')
nested = cms_layouts(:nested)
nested.update_attribute(:content, '<html>{{cms:page:left}}<br/>{{cms:page:right}}</html>')
assert_difference 'Cms::Page.count', 2 do
ComfortableMexicanSofa::Fixtures.sync_pages(@site)
assert page = Cms::Page.find_by_full_path('/')
assert_equal layout, page.layout
assert_equal 'index', page.slug
assert_equal "<html>Home Page Fixture Content\ndefault_snippet_content</html>", page.content
assert page.is_published?
assert child_page = Cms::Page.find_by_full_path('/child')
assert_equal page, child_page.parent
assert_equal nested, child_page.layout
assert_equal 'child', child_page.slug
assert_equal '<html>Child Page Left Fixture Content<br/>Child Page Right Fixture Content</html>', child_page.content
end
end
def test_sync_pages_updating_and_deleting
page = cms_pages(:default)
page.update_attribute(:updated_at, 10.years.ago)
assert_equal 'Default Page', page.label
child = cms_pages(:child)
child.update_attribute(:slug, 'old')
assert_no_difference 'Cms::Page.count' do
ComfortableMexicanSofa::Fixtures.sync_pages(@site)
page.reload
assert_equal 'Home Fixture Page', page.label
assert_nil Cms::Page.find_by_slug('old')
end
end
def test_sync_pages_ignoring
page = cms_pages(:default)
page_path = File.join(ComfortableMexicanSofa.config.fixtures_path, @site.hostname, 'pages', 'index')
attr_file_path = File.join(page_path, '_index.yml')
content_file_path = File.join(page_path, 'content.html')
assert page.updated_at >= File.mtime(attr_file_path)
assert page.updated_at >= File.mtime(content_file_path)
ComfortableMexicanSofa::Fixtures.sync_pages(@site)
page.reload
assert_equal nil, page.slug
assert_equal 'Default Page', page.label
assert_equal "\nlayout_content_a\ndefault_page_text_content_a\ndefault_snippet_content\ndefault_page_text_content_b\nlayout_content_b\ndefault_snippet_content\nlayout_content_c", page.content
end
def test_sync_snippets_creating
Cms::Snippet.delete_all
assert_difference 'Cms::Snippet.count' do
ComfortableMexicanSofa::Fixtures.sync_snippets(@site)
assert snippet = Cms::Snippet.last
assert_equal 'default', snippet.slug
assert_equal 'Default Fixture Snippet', snippet.label
assert_equal 'Fixture Content for Default Snippet', snippet.content
end
end
def test_sync_snippets_updating
snippet = cms_snippets(:default)
snippet.update_attribute(:updated_at, 10.years.ago)
assert_equal 'default', snippet.slug
assert_equal 'Default Snippet', snippet.label
assert_equal 'default_snippet_content', snippet.content
assert_no_difference 'Cms::Snippet.count' do
ComfortableMexicanSofa::Fixtures.sync_snippets(@site)
snippet.reload
assert_equal 'default', snippet.slug
assert_equal 'Default Fixture Snippet', snippet.label
assert_equal 'Fixture Content for Default Snippet', snippet.content
end
end
def test_sync_snippets_deleting
snippet = cms_snippets(:default)
snippet.update_attribute(:slug, 'old')
assert_no_difference 'Cms::Snippet.count' do
ComfortableMexicanSofa::Fixtures.sync_snippets(@site)
assert snippet = Cms::Snippet.last
assert_equal 'default', snippet.slug
assert_equal 'Default Fixture Snippet', snippet.label
assert_equal 'Fixture Content for Default Snippet', snippet.content
assert_nil Cms::Snippet.find_by_slug('old')
end
end
def test_sync_snippets_ignoring
snippet = cms_snippets(:default)
snippet_path = File.join(ComfortableMexicanSofa.config.fixtures_path, @site.hostname, 'snippets', 'default')
attr_file_path = File.join(snippet_path, '_default.yml')
content_file_path = File.join(snippet_path, 'content.html')
assert snippet.updated_at >= File.mtime(attr_file_path)
assert snippet.updated_at >= File.mtime(content_file_path)
ComfortableMexicanSofa::Fixtures.sync_snippets(@site)
snippet.reload
assert_equal 'default', snippet.slug
assert_equal 'Default Snippet', snippet.label
assert_equal 'default_snippet_content', snippet.content
end
end<file_sep># Small hack to auto-run migrations during testing
namespace :db do
task :abort_if_pending_migrations => [:migrate]
end
namespace :comfortable_mexican_sofa do
namespace :fixtures do
desc 'Import Fixture data into database. (options: SITE=example.com)'
task :import => :environment do |task, args|
site = if ComfortableMexicanSofa.config.enable_multiple_sites
Cms::Site.find_by_hostname(args[:site])
else
Cms::Site.first
end
abort 'SITE is not found. Aborting.' if !site
puts "Syncing for #{site.hostname}"
ComfortableMexicanSofa::Fixtures.sync(site)
puts 'Done!'
end
end
end<file_sep>require File.expand_path('../../test_helper', File.dirname(__FILE__))
class CmsSnippetTest < ActiveSupport::TestCase
def test_fixtures_validity
Cms::Snippet.all.each do |snippet|
assert snippet.valid?, snippet.errors.full_messages.to_s
end
end
def test_validations
snippet = Cms::Snippet.new
snippet.save
assert snippet.invalid?
assert_has_errors_on snippet, [:label, :slug]
end
def test_update_forces_page_content_reload
snippet = cms_snippets(:default)
page = cms_pages(:default)
assert_match snippet.content, page.content
snippet.update_attribute(:content, 'new_snippet_content')
page.reload
assert_match /new_snippet_content/, page.content
end
end
|
a5674f3690f19da6ee56c9ab6795e2fa14761679
|
[
"Ruby"
] | 4
|
Ruby
|
johnantoni/comfortable-mexican-sofa
|
4e14ee8c72af31376dfc87b09dc561607b866358
|
0e2a9115533bb5c9afaa9be2f534ecda61e08d58
|
refs/heads/master
|
<file_sep><?
/**
* Heartland Portico Gateway interface classes.
*
* Primary abstract class 'portico' supplied in this file will allow connection to the Heartland Porico Gateway. Extension classes include:
* 1. BatchClose
* 2. CreditAddToBatch
* 3. CreditAuth
* 4. CreditReturn
* 5. CreditSale
* 6. CreditVoid
* 7. ReportBatchDetail
* 8. ReportBatchSummary
* 9. ReportTxnDetail
*
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* Automatically load '.class.php' files located in the same directory as portico.class.php
* porticoAutoload() is then passed to spl_autoload_register() to preserve correct casing; default
* spl_autoload() forces class names to lowercase before attempting to locate the file
*
* @param string $className PHP automatically supplies $className when class is instantiated (using 'new')
*
* @package porticoAPI
*
*/
function porticoAutoload($className)
{
@require_once(__DIR__.DIRECTORY_SEPARATOR.$className.'.class.php');
}
spl_autoload_register('porticoAutoload');
##*******************************************************************************************##
/**
* porticoAutoloadFail will return custom failure instead of E_COMPILE_ERROR on missing porticoAPI child classes
*
* @package porticoAPI
*
*/
function porticoAutoloadFail()
{
$e = error_get_last();
$bool = $e['type'] == E_COMPILE_ERROR &&
substr($e['message'], 0, 12) == 'require_once' &&
strpos($e['message'], '.class.php') > 0
?true:false;
if($bool === true)
{
preg_match('/portico\/(?P<className>.*)\.class\.php/',$e['message'],$m);
die('API Error: '.$m['className'].' not found in porticoAPI directory. (Class names are case sensitive.)');
}else{
return false;
}
}
register_shutdown_function('porticoAutoloadFail');
##*******************************************************************************************##
/**
* Abstract Heartland Portico gateway interface
*
* Heartland Portico Gateway (fka POSGateway) generic interface abstract class
*
* @package porticoAPI
*
*/
abstract class portico{
/**
* Allows portico system to be put in to DEBUG mode for additional testing:
* Affects porticoResponse::FullRequest
*/
const DEBUG = false;
/**
* GATEWAY Heartland Portico Gateway SOAP Interface address
*/
const GATEWAY = 'https://posgateway.secureexchange.net/Hps.Exchange.PosGateway/PosGatewayService.asmx?wsdl';
/**
* Will override default gateway for certifications or testing
*
* @var string
*/
protected $GATEWAY;
/**
* Request to be sent to Gateway
*
* @var array
*/
protected $request;
/**
* String containing name of functional child class called
*
* @var string
*/
protected $class;
/**
* Common list of required properties
*
* @var array
*/
protected $requiredCommon = [
'SiteId',
'DeviceId',
'LicenseId',
'UserName',
'<PASSWORD>',
'DeveloperId',
'VersionNbr'
];
/**
* SiteId Issued by Heartland Payment Systems
*
* @var string
*/
var $SiteId;
/**
* LicenseId Issued by Heartland Payment Systems
*
* @var string
*/
var $LicenseId;
/**
* DeviceId Issued by Heartland Payment Systems
*
* @var string
*/
var $DeviceId;
/**
* UserName Issued by Heartland Payment Systems
*
* @var string
*/
var $UserName;
/**
* Password Issued by Heartland Payment Systems
*
* @var string
*/
var $Password;
/**
* DeveloperId Issued by Heartland Payment Systems
*
* @var string
*/
var $DeveloperId;
/**
* VersionNbr Issued by Heartland Payment Systems
*
* @var string
*/
var $VersionNbr;
/*********************************************************************************************/
###############################################################################################
/**
* Sets portico::class and set initial values for class variables from optional $defaults array
*
* @param array $defaults Array of key => value pairs to set default or generic values
*
* @return void
*/
public function __construct($defaults = [])
{
$this->class = get_class($this);
$vars = array_keys(get_class_vars(get_class($this)));
if(count($defaults) > 0)
foreach($defaults as $k => $v)
if(in_array($k, $vars))
$this->$k = $v;
}
###############################################################################################
/**
* Sets initial values in $request including header
*
* @return void
*/
protected function initRequest()
{
$this->validateFields();
$this->request = [
'PosRequest' => [
'Ver1.0' => [
'Header' => $this->buildHeader(),
'Transaction' => []
]
]
];
return;
}
/*********************************************************************************************/
###############################################################################################
/**
* Sets the 'Header' array and returns the array directly
*
* @return array Containing values for Header array
*/
private function buildHeader()
{
return [
'SiteId' => $this->SiteId,
'DeviceId' => $this->DeviceId,
'LicenseId' => $this->LicenseId,
'UserName' => $this->UserName,
'Password' => $<PASSWORD>,
'DeveloperId' => $this->DeveloperId,
'VersionNbr' => $this->VersionNbr
];
}
/*********************************************************************************************/
###############################################################################################
/**
* Sets the 'Transaction' array directly to the $request object based on $transaction sent
*
* @param array $transaction transaction element from child class doTransaction() function
*
* @return void
*/
protected function setTransaction($transaction)
{
$this->request['PosRequest']['Ver1.0']['Transaction'] = $transaction;
return;
}
/********************************************************************************************* /
private function debugTransaction()
{
return;
$return = false;
try{
$client = new SoapClient(self::GATEWAY, array('trace'=>1, 'exceptions'=>1));
$response = $client->__soapCall('DoTransaction',$this->request);
}catch(SoapFault $sf){
$return = [
'request' => $client->__getLastRequest(),
'response' => $sf->getTrace()
];
}
return $return?$return:[
'request' => $client->__getLastRequest(),
'response' => $client->__getLastResponse()
];
}
/*********************************************************************************************/
###############################################################################################
/**
* Sends transaction $request to Heartland Portico Gateway for processing after validating fields
*
* @return porticoResponse Formatted response based on child class {className}Resposne object
*/
protected function Transaction()
{
/* return $this->debugTransaction(); */
if(isset($this->GATEWAY) && $this->GATEWAY != '')
$gw = $this->GATEWAY;
else
$gw = self::GATEWAY;
// die(json_encode(['default' => self::GATEWAY, 'set' => $this->GATEWAY, 'used' => $gw]));
try{
$client = new SoapClient($gw, array('trace'=>1, 'exceptions'=>1));
$response = $client->__soapCall('DoTransaction',$this->request);
}catch(Exception $e){
return new FailureResponse($e, null);
}catch(SoapFault $sf){
return new FailureResponse($sf, $client->__getLastRequest());
}
/* GATEWAY FAILURE */
if(isset($response->{'Ver1.0'}->Header->GatewayRspCode) && $response->{'Ver1.0'}->Header->GatewayRspCode != 0)
return new FailureResponse($response, $this->request);
/* CHECK FOR FAILURES use function in child classes */
$failure = method_exists($this, 'checkFailure') && is_callable([$this, 'checkFailure'])?$this->checkFailure($response):false;
if($failure !== false)
return $failure;
$responseClass = $this->class.'Response';
return new $responseClass($response, $this->request);
}
/*********************************************************************************************/
###############################################################################################
/**
* Validates $request object by verifying that all required fields have values,
* then testing those values through validation for current class instance
*
* @uses array merged(portico::requiredCommon, child class::required) as array of required field names
*
* @return void
*
* @throws Exception if required field is not set, empty, or fails validate function (if exists)
*/
protected function validateFields()
{
$function = $this->class;
if($function == 'CreditSale' && $this->swipe)
$function .= 'Swipe';
$fields = array_merge($this->requiredCommon,$this->required[$function]);
foreach($fields as $var)
if(!isset($this->$var) || empty($var))
throw new Exception($function.' borked: '.$var);
if(method_exists($this, 'validate') && is_callable([$this,'validate']))
$this->validate();
return;
}
/*********************************************************************************************/
###############################################################################################
/**
* Sets GATEWAY to override default in cases of testing or certification
*
* @param string $gateway link to new online gateway
*
* @return void
*/
public function setGateway($gateway)
{
if($gateway != '')
$this->GATEWAY = $gateway;
return;
}
/*********************************************************************************************/
###############################################################################################
}
##*******************************************************************************************##
/**
* Abstract Heartland Portico Response class
*
* Common response object
*
* @package porticoAPI
*
*/
abstract class porticoResponse{
/**
* Set to true if transaction was successful, false if transaction failed or error
*
* @var boolean
*/
var $Success;
/**
* Set to transaction type submitted to the gateway
*
* @var string
*/
var $TransType;
/**
* Gateway Response code for failure
*
* @var int
*/
var $RspCode;
/**
* Gateway Response string for failure
*
* @var string
*/
var $RspText;
/**
* Gateway Transaction ID
*
* @var string
*/
var $TxnId;
/**
* Complete SOAP XML from Heartland Portico Gateway (Only set if portico is in DEBUG mode)
*
* @var string
*/
var $FullResponse;
/**
* Request array generated by portico and sent to Heartland Portico Gateway (Only set if portico is in DEBUG mode)
*
* @var array
*/
var $FullRequest;
/**
* Called from child classes to set common response properties
*
* @uses portico::DEBUG Includes FullRequest property if portico is in DEBUG mode
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
protected function __construct($response, $request = '')
{
$this->Success = true;
$this->TransType = preg_replace('/Response$/', '', get_class($this));
$this->RspCode = $response->{'Ver1.0'}->Header->GatewayRspCode;
$this->RspText = $response->{'Ver1.0'}->Header->GatewayRspMsg;
$this->TxnId = $response->{'Ver1.0'}->Header->GatewayTxnId;
$this->FullResponse = $response;
if(portico::DEBUG)
{
$this->FullRequest = $request;
}
}
##*******************************************************************************************##
/**
* Formats Portico UTC dates to YYYY-MM-DD hh:mm:ss format.
*
* @param string UTC formatted date-time to be reformatted
*
* @return string
*
*/
protected function formatUTCDate($date)
{
return date('Y-m-d H:i:s', strtotime($date));
}
}
##*******************************************************************************************##
/**
* Heartland Portico FailureResponse class extending porticoResponse
*
* Response object for transaction failures
*
* @package porticoAPI
*
*/
class FailureResponse extends porticoResponse{
/**
* Contains one of 'SOAPFault', 'Gateway', or 'Transaction'
*
* @var string
*/
var $FailType;
/**
* Check response and builds formatted object.
*
* @uses portico::DEBUG Includes FullResponse property if portico is in DEBUG mode
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request = '')
{
parent::__construct($response, $request);
$this->Success = false;
if(is_object($response) && get_class($response) == 'SoapFault')
{
$this->FailType = 'SOAPFault';
$this->RspCode = $response->faultcode;
$this->RspText = $response->faultstring;
$this->TxnId = NULL;
if(portico::DEBUG)
{
$this->FullResponse = $response->getTrace();
$this->FullRequest = $request;
}
}
if(!isset($this->FailType))
$this->FailType = 'Gateway';
// ELSE MANUALLY SET VIA checkFailure() //
}
}
?><file_sep><?
/**
* Heartland Portico Gateway ReportBatchHistory class.
*
* Class includes ReportBatchHistory functionality linked to SiteId and DeviceId supplied in the header
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* ReportBatchHistory extends portico to return information about previous batches for a given Site ID and Device ID over a period of time. If no dates are provided, ReportBatchHistory will return six days prior to current date.
*
* @package porticoAPI
*
*/
class ReportBatchHistory extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'ReportBatchHistory' => []
];
/**
* Start date-time used to filter the results to a particular date and time range. (date('c') formatting, optional, defaults to current day)
*
* @var string
*/
var $RptStartUtcDT;
/**
* End date-time used to filter the results to a particular date and time range. (date('c') formatting, optional, defaults to current day)
*
* @var string
*/
var $RptEndUtcDT;
/**
* DeviceId to report batches for. (optional, default returns batches for all devices)
*
* @var string
*/
var $ReportDeviceId;
/*********************************************************************************************/
###############################################################################################
/**
* Builds ReportBatchHistory request and submit it to portico::Transaction
*
* @return ReportBatchHistoryResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'ReportBatchHistory' => [
'RptStartUtcDT' => isset($this->RptStartUtcDT)?$this->RptStartUtcDT:date('c', strtotime('midnight')),
'RptEndUtcDT' => isset($this->RptEndUtcDT)?$this->RptEndUtcDT:date('c', strtotime('tomorrow midnight')),
'DeviceId' => isset($this->ReportDeviceId)?$this->ReportDeviceId:null
]
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico ReportBatchSummaryResponse class
*
* Response object for ReportBatchSummary
*
* @package porticoAPI
*
*/
class ReportBatchHistoryResponse extends porticoResponse{
/**
* Summary for ReportBatchHistory response containing fields: 'BatchCnt','BatchAmt'
*
* @var array
*/
var $Summary;
/**
* Details for ReportBatchHistory response indexed by 'DeviceId' then BatchId' and contains multiple arrays
* of fields: 'OpenDate','CloseDate','FirstTransID','LastTransID','BatchTxnCnt','BatchTxnAmt'
*
* @var array
*/
var $Details;
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request = '')
{
parent::__construct($response, $request);
$this->Summary = [
'ReportStart' => $this->formatUTCDate($response->{'Ver1.0'}->Transaction->ReportBatchHistory->Header->RptStartUtcDT),
'ReportEnd' => $this->formatUTCDate($response->{'Ver1.0'}->Transaction->ReportBatchHistory->Header->RptEndUtcDT),
'BatchCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchHistory->Header->BatchCnt,
'BatchAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchHistory->Header->BatchAmt
];
if(is_array($response->{'Ver1.0'}->Transaction->ReportBatchHistory->Details))
$details = $response->{'Ver1.0'}->Transaction->ReportBatchHistory->Details;
else
$details[] = $response->{'Ver1.0'}->Transaction->ReportBatchHistory->Details;
foreach($details as $d)
{
$this->Details[$d->DeviceId][$d->BatchId] = [
'OpenDate' => $this->formatUTCDate($d->OpenUtcDT),
'CloseDate' => empty($d->CloseUtcDT)?'':$this->formatUTCDate($d->CloseUtcDT),
'FirstTransID'=> $d->OpenTxnId,
'LastTransID' => $d->CloseTxnId,
'BatchTxnCnt' => $d->BatchTxnCnt,
'BatchTxnAmt' => $d->BatchTxnAmt
];
}
}
}
?><file_sep><?
/**
* Heartland Portico Gateway ReportTxnDetail class.
*
* Class includes ReportTxnDetail functionality using original TxnId
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* ReportTxnDetail extends portico to return previous transaction details.
*
* @package porticoAPI
*
*/
class ReportTxnDetail extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'ReportTxnDetail' => [
'TxnId'
]
];
/**
* TxnId identifying transaction to void
*
* @var string
*/
var $TxnId;
/*********************************************************************************************/
###############################################################################################
/**
* Builds ReportTxnDetail request and submit it to portico::Transaction
*
* @return ReportTxnDetailResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'ReportTxnDetail' => [
'TxnId' => $this->TxnId
]
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico ReportTxnDetailResponse class
*
* Response object for ReportTxnDetail
*
* @package porticoAPI
*
*/
class ReportTxnDetailResponse extends porticoResponse{
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request)
{
parent::__construct($response, $request);
}
}
?><file_sep><?
/**
* Heartland Portico Gateway CreditAuth class.
*
* Class includes CreditAuth functionality for both swiped and manually entered card information.
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* CreditAuth extends portico for Credit Card transactions, both Manual Entry and Swiped
*
* @package porticoAPI
*
*/
class CreditAuth extends portico{
/**
* Swipe is set to true if using TrackData from MSR card read and set to false if using Manually Entered card data.
*
* @var bool
*/
protected $swipe = false;
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'CreditAuth' => [
'Amt',
'AllowDup',
'AllowPartialAuth',
// 'Version',
'ClientTxnId',
'DirectMktInvoiceNbr',
'DirectMktShipDay',
'DirectMktShipMonth',
'CardNbr',
'ExpMonth',
'ExpYear',
'CardPresent',
'ReaderPresent',
'CVV2',
'CardHolderFirstName',
'CardHolderLastName',
'CardHolderZip'
],
'CreditAuthSwipe' => [
'Amt',
'AllowDup',
'AllowPartialAuth',
// 'Version',
'ClientTxnId',
'DirectMktInvoiceNbr',
'DirectMktShipDay',
'DirectMktShipMonth',
'TrackData'
]
];
/**
* Amount requested for authorization
*
* @var string
*/
var $Amt;
/**
* Important in cases where the client processes a large number of similar transactions in
* a very short period of time; sending "Y" will skip duplicate checking on this transaction
*
* @var string
*/
var $AllowDup;
/**
* Indicates whether or not a partial authorization is supported by terminal
*
* @var string
*/
var $AllowPartialAuth;
/**
* The encryption version used on the supplied data
*
* @var string
*/
var $Version;
/**
* Client generated transaction identifier sent in the request of the original transaction
*
* @var string
*/
var $ClientTxnId;
/**
* Invoice Number
*
* @var string
*/
var $DirectMktInvoiceNbr;
/**
* Ship Day
*
* @var string
*/
var $DirectMktShipDay;
/**
* Ship Month
*
* @var string
*/
var $DirectMktShipMonth;
/**
* Card number; also referred to as Primary Account Number (PAN)
*
* @var string
*/
var $CardNbr;
/**
* Card expiration month
*
* @var string
*/
var $ExpMonth;
/**
* Card expiration year
*
* @var string
*/
var $ExpYear;
/**
* Indicates whether or not the card was present at the time of the transaction
*
* @var string
*/
var $CardPresent;
/**
* Indicates whether or not a reader was present at the time of the transaction
*
* @var string
*/
var $ReaderPresent;
/**
* CVV Number ("Card Verification Value"); 3 digits on VISA, MasterCard and Discover and 4 on American Express
*
* @var string
*/
var $CVV2;
/**
* Cardholder First Name
*
* @var string
*/
var $CardHolderFirstName;
/**
* Cardholder Last Name
*
* @var string
*/
var $CardHolderLastName;
/**
* Cardholder Billing Zip Code
*
* @var string
*/
var $CardHolderZip;
/**
* Full magnetic stripe data
*
* @var string
*/
var $TrackData;
/*********************************************************************************************/
###############################################################################################
/**
* Builds CreditAuth request and submit it to portico::Transaction
*
* @return CreditAuthResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction($swipe = false)
{
$this->swipe = $swipe;
$this->initRequest();
$this->setTransaction([
'CreditAuth' => [
'Block1' => array_merge(
$this->buildBlock1(),
$this->buildCardData()
)
]
]);
return $this->Transaction();
}
/*********************************************************************************************/
###############################################################################################
/**
* Sets values for the 'Block1' array and returns the array
*
* @return array
*/
private function buildBlock1()
{
return [
'Amt' => $this->Amt,
'AllowDup' => $this->AllowDup,
// 'AllowPartialAuth' => $this->AllowPartialAuth,
// 'EncryptionData' => [
// 'Version' => $this->Version
// ],
'DirectMktData' => [
'DirectMktInvoiceNbr' => $this->DirectMktInvoiceNbr,
'DirectMktShipDay' => $this->DirectMktShipDay,
'DirectMktShipMonth' => $this->DirectMktShipMonth
]
];
}
/*********************************************************************************************/
###############################################################################################
/**
* Sets values for the 'CardData' array (and potentially 'CardHolderData' array) and returns the array
*
* @uses portico::swipe
*
* @return array
*/
private function buildCardData()
{
return $this->swipe?[
'CardData' => [
'TrackData' => $this->TrackData,
'method' => 'swipe'
]
]:[
'CardData' => [
'ManualEntry' => [
'CardNbr' => $this->CardNbr,
'ExpMonth' => $this->ExpMonth,
'ExpYear' => $this->ExpYear,
'CardPresent' => $this->CardPresent,
'ReaderPresent' => $this->ReaderPresent
],
],
'CardHolderData' => [
'CardHolderFirstName' => $this->CardHolderFirstName,
'CardHolderLastName' => $this->CardHolderLastName,
'CardHolderAddr' => isset($this->CardHolderAddr)?$this->CardHolderAddr:null,
'CardNbr' => $this->CardNbr,
'CardHolderState' => isset($this->CardHolderState)?$this->CardHolderState:null,
'CardHolderZip' => $this->CardHolderZip,
'CardHolderPhone' => isset($this->CardHolderPhone)?$this->CardHolderPhone:null,
'CardHolderEmail' => isset($this->CardHolderEmail)?$this->CardHolderEmail:null
]
];
}
/*********************************************************************************************/
###############################################################################################
/**
* Validates CreditAuth object before attempting transaction
*
* @throws Exception on invalid data
*/
protected function validate()
{
if($this->swipe)
return true;
$cardTypes = [
3 => 'AMEX',
4 => 'VISA',
5 => 'MC',
6 => 'DISC'
];
if(!in_array(substr($this->CardNbr, 0, 1), ['3','4','5','6']))
throw new Exception('Invalid card brand identifier: '.substr($this->CardNbr, 0, 1));
$ex = [];
if($this->ExpYear < 2000)
$this->ExpYear += 2000;
switch($cardTypes[substr($this->CardNbr, 0, 1)])
{
case 'AMEX':
if(strlen($this->CardNbr) != 15)
$ex[] = 'Invalid AMEX card number length';
if(strlen($this->CVV2) != 4)
$ex[] = 'Invalid AMEX CVV length';
break;
case 'VISA':
case 'MC':
case 'DISC':
if(strlen($this->CardNbr) != 16)
$ex[] = 'Invalid '.$cardTypes[substr($this->CardNbr, 0, 1)].' card number length';
if(strlen($this->CVV2) != 3)
$ex[] = 'Invalid '.$cardTypes[substr($this->CardNbr, 0, 1)].' CVV length';
break;
}
if($this->ExpYear.str_pad($this->ExpMonth, 2, '0', STR_PAD_LEFT) < date('Ym'))
$ex[] = 'Expired Card';
if(!in_array(strlen($this->CardHolderZip), [5,9]))
$ex[] = 'Invalid Billing ZIP Code';
if(count($ex) > 0)
throw new Exception(implode("\n", $ex));
return true;
}
/*********************************************************************************************/
###############################################################################################
/**
* Child class specific function to check for Transaction failures
*
* @param object $response Raw Heartland Portico Gateway response
*
* @return object|boolean
*/
protected function checkFailure($response)
{
if(isset($response->{'Ver1.0'}->Transaction->CreditAuth->RspCode) && $response->{'Ver1.0'}->Transaction->CreditAuth->RspCode != 0)
{
$failure = new FailureResponse($response, $this->request);
$failure->Success = false;
$failure->FailType = 'Transaction';
$failure->RspCode = $response->{'Ver1.0'}->Transaction->CreditAuth->RspCode;
$failure->RspText = $response->{'Ver1.0'}->Transaction->CreditAuth->RspText;
return $failure;
}else{
return false;
}
}
}
##*******************************************************************************************##
/**
* Heartland Portico CreditAuthResponse class
*
* Response object for CreditAuth
*
* @package porticoAPI
*
*/
class CreditAuthResponse extends porticoResponse{
/**
* Authorization Code returned for successful transaction
*
* @var string
*/
var $AuthCode;
/**
* Set to AMEX,DISC,MC, or VISA depending on card type processed
*
* @var string
*/
var $CardType;
/**
* Response Code of transaction usually set to 0
*
* @var string
*/
var $TransRspCode;
/**
* Response Code of transaction usually set to 'APPROVAL'
*
* @var string
*/
var $TransRspText;
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request)
{
parent::__construct($response, $request);
$this->AuthCode = $response->{'Ver1.0'}->Transaction->CreditAuth->AuthCode;
$this->CardType = $response->{'Ver1.0'}->Transaction->CreditAuth->CardType;
$this->TransRspCode = $response->{'Ver1.0'}->Transaction->CreditAuth->RspCode;
$this->TransRspText = $response->{'Ver1.0'}->Transaction->CreditAuth->RspText;
}
}
?><file_sep><?
/**
* Heartland Portico Gateway CreditReturn class.
*
* Class includes CreditReturn functionality using original GatewayTxnId and Amt to return.
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* CreditReturn extends portico to return partial or full amounts to previously completed, successful transaction
* regardless of current batch status (but recommended only for Closed Batches).
*
* @package porticoAPI
*
*/
class CreditReturn extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'CreditReturn' => [
'GatewayTxnId','Amt'
]
];
/**
* GatewayTxnId identifying transaction to return
*
* @var string
*/
var $GatewayTxnId;
/**
* Amount to return to cardholder
*
* @var string
*/
var $Amt;
/*********************************************************************************************/
###############################################################################################
/**
* Builds CreditReturn request and submit it to portico::Transaction
*
* @return CreditReturnResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'CreditReturn' => [
'Block1' => [
'GatewayTxnId' => $this->GatewayTxnId,
'Amt' => $this->Amt
]
]
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico CreditReturnResponse class
*
* Response object for CreditReturn
*
* @package porticoAPI
*
*/
class CreditReturnResponse extends porticoResponse{
}
?><file_sep><?
/**
* Heartland Portico Gateway ReportBatchSummary class.
*
* Class includes ReportBatchSummary functionality linked to SiteId and DeviceId supplied in the header
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* ReportBatchSummary extends portico to return a batch's status information and totals broken down by payment type
*
* @package porticoAPI
*
*/
class ReportBatchSummary extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'ReportBatchSummary' => []
];
/*********************************************************************************************/
###############################################################################################
/**
* Builds ReportBatchSummary request and submit it to portico::Transaction
*
* @return ReportBatchSummaryResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'ReportBatchSummary' => []
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico ReportBatchSummaryResponse class
*
* Response object for ReportBatchSummary
*
* @package porticoAPI
*
*/
class ReportBatchSummaryResponse extends porticoResponse{
/**
* Summary for ReportBatchSummary response containing fields: 'BatchId','CreditCnt','CreditAmt',
* 'DebitCnt','DebitAmt','SaleCnt','SaleAmt','ReturnCnt','ReturnAmt','TotalCnt','TotalAmt','TotalGratuityAmtInfo'
*
* @var array
*/
var $Summary;
/**
* Details for ReportBatchSummary response indexed by 'CardType' and contains multiple arrays of fields: 'CreditCnt',
* 'CreditAmt','DebitCnt','DebitAmt','SaleCnt','SaleAmt','ReturnCnt','ReturnAmt','TotalCnt','TotalAmt','TotalGratuityAmtInfo'
*
* @var array
*/
var $Details;
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request = '')
{
parent::__construct($response, $request);
$this->Summary = [
'BatchId' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->BatchId,
'CreditCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->CreditCnt,
'CreditAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->CreditAmt,
'DebitCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->DebitCnt,
'DebitAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->DebitAmt,
'SaleCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->SaleCnt,
'SaleAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->SaleAmt,
'ReturnCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->ReturnCnt,
'ReturnAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->ReturnAmt,
'TotalCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->TotalCnt,
'TotalAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->TotalAmt,
'TotalGratuityAmtInfo' => $response->{'Ver1.0'}->Transaction->ReportBatchSummary->Header->TotalGratuityAmtInfo
];
foreach($response->{'Ver1.0'}->Transaction->ReportBatchSummary->Details as $d)
{
$this->Details[$d->CardType][] = [
'CreditCnt' => $d->CreditCnt,
'CreditAmt' => $d->CreditAmt,
'DebitCnt' => $d->DebitCnt,
'DebitAmt' => $d->DebitAmt,
'SaleCnt' => $d->SaleCnt,
'SaleAmt' => $d->SaleAmt,
'ReturnCnt' => $d->ReturnCnt,
'ReturnAmt' => $d->ReturnAmt,
'TotalCnt' => $d->TotalCnt,
'TotalAmt' => $d->TotalAmt,
'TotalGratuityAmtInfo' => $d->TotalGratuityAmtInfo
];
}
}
}
?><file_sep><?
/**
* Heartland Portico Gateway CreditVoid class.
*
* Class includes CreditVoid functionality using original GatewayTxnId
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* CreditVoid extends portico to void previously completed, successful transactions in an Open Batch
* essentially removing the transaction from said Open Batch
*
* @package porticoAPI
*
*/
class CreditVoid extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'CreditVoid' => [
'GatewayTxnId'
]
];
/**
* GatewayTxnId identifying transaction to void
*
* @var string
*/
var $GatewayTxnId;
/*********************************************************************************************/
###############################################################################################
/**
* Builds CreditVoid request and submit it to portico::Transaction
*
* @return CreditVoidResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'CreditVoid' => [
'GatewayTxnId' => $this->GatewayTxnId
]
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico CreditVoidResponse class
*
* Response object for CreditVoid
*
* @package porticoAPI
*
*/
class CreditVoidResponse extends porticoResponse{
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request)
{
parent::__construct($response, $request);
}
}
?><file_sep>#!/bin/bash
./bin/apigen.phar generate -s . --exclude "doc*" -d ./doc/ --template-theme=bootstrap --todo --access-levels="public,protected,private"
patch -u doc/resources/style.css << EOF
--- style.css 2015-11-13 10:50:44.750185862 -0600
+++ style.new.css 2015-11-13 11:05:28.866167821 -0600
@@ -220,7 +220,6 @@
}
#rightInner {
- max-width: 1000px;
min-width: 350px;
}
EOF
<file_sep><?
/**
* Heartland Portico Gateway ReportBatchDetail class.
*
* Class includes ReportBatchDetail functionality linked to SiteId and DeviceId supplied in the header
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* ReportBatchDetail extends portico to return information on each transaction currently associated to the specified batch. Batch ID must match Site ID and Device ID. If Batch ID isn't sent, ReportBatchDetail will return current open batch.
*
* @package porticoAPI
*
*/
class ReportBatchDetail extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'ReportBatchDetail' => []
];
/**
* BatchID to return details for. (optional, defaults to current open batch)
*
* @var string
*/
var $BatchId;
/*********************************************************************************************/
###############################################################################################
/**
* Builds ReportBatchDetail request and submit it to portico::Transaction
*
* @return ReportBatchDetailResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'ReportBatchDetail' => [
'BatchId' => isset($this->BatchId)?$this->BatchId:''
]
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico ReportBatchSummaryResponse class
*
* Response object for ReportBatchSummary
*
* @package porticoAPI
*
*/
class ReportBatchDetailResponse extends porticoResponse{
/**
* Summary for ReportBatchDetail response containing fields: 'BatchId','BatchTxnCnt','BatchTxnAmt'
*
* @var array
*/
var $Summary;
/**
* Details for ReportBatchDetail response indexed by 'GatewayTxnId' and contains multiple arrays
* of fields: 'TxnStatus','TxnDate','CardSwiped','CardType','RspCode','RspText','AuthCode','Amt','Cardholder'
*
* @var array
*/
var $Details;
/**
* Check response and builds formatted object.
*
* @param array $response Request array generated by portico and sent to Heartland Portico Gateway
* @param string $request Complete SOAP XML from Heartland Portico Gateway
*/
function __construct($response, $request = '')
{
parent::__construct($response, $request);
$this->Summary = [
'BatchId' => $response->{'Ver1.0'}->Transaction->ReportBatchDetail->Header->BatchId,
'BatchTxnCnt' => $response->{'Ver1.0'}->Transaction->ReportBatchDetail->Header->BatchTxnCnt,
'BatchTxnAmt' => $response->{'Ver1.0'}->Transaction->ReportBatchDetail->Header->BatchTxnAmt,
'BatchOpen' => $this->formatUTCDate($response->{'Ver1.0'}->Transaction->ReportBatchDetail->Header->OpenUtcDT),
'BatchClose' => $this->formatUTCDate($response->{'Ver1.0'}->Transaction->ReportBatchDetail->Header->CloseUtcDT)
];
foreach($response->{'Ver1.0'}->Transaction->ReportBatchDetail->Details as $d)
{
$this->Details[$d->GatewayTxnId] = [
'TxnStatus' => $d->TxnStatus,
'TxnDate' => $this->formatUTCDate($d->TxnUtcDT),
'CardSwiped' => $d->CardSwiped,
'CardType' => $d->CardType,
'RspCode' => $d->RspCode,
'RspText' => $d->RspText,
'AuthCode' => $d->AuthCode,
'Amt' => $d->Amt,
'Cardholder' => $d->CardHolderFirstName.' '.$d->CardHolderLastName
];
}
}
}
?><file_sep><?
/**
* Heartland Portico Gateway BatchClose class.
*
* This file includes the class for BatchClose functionality linked to SiteId and DeviceId supplied in the header
* as well as the BatchCloseResponse response object
*
* @author <NAME> <<EMAIL>>
*
* @copyright 2015 <NAME>
* @license http://www.gnu.org/licenses/ GNU Lesser Public License (LGPL)
*
* @version 0.5.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
##*******************************************************************************************##
/**
* BatchClose extends portico to close current open batch associated with account and device
*
* @package porticoAPI
*
*/
class BatchClose extends portico{
/**
* Array of required properties.
*
* @var array
*/
protected $required = [
'BatchClose' => []
];
/*********************************************************************************************/
###############################################################################################
/**
* Builds BatchClose request and submit it to portico::Transaction
*
* @return BatchCloseResponse|FailureResponse formatted response from Heartland SOAP interface
*/
public function doTransaction()
{
$this->initRequest();
$this->setTransaction([
'BatchClose' => []
]);
return $this->Transaction();
}
}
##*******************************************************************************************##
/**
* Heartland Portico BatchCloseResponse class
*
* Response object for BatchClose
*
* @package porticoAPI
*
*/
class BatchCloseResponse extends porticoResponse{
}
?>
|
1a30b428eb8c0b74ba77dc3df50c97d9c2f3b5c9
|
[
"PHP",
"Shell"
] | 10
|
PHP
|
noxeternal/portico
|
eb65bc58e7f2201aed2d940d6e6e9750ecca734f
|
7941c4659a2cd3941c4daaf0f3e14024ab40a72e
|
refs/heads/master
|
<repo_name>CPrich905/buyvsrent<file_sep>/app.js
// function calcSave() {
// let savings = +document.getElementById('savings').value
// let interest = +document.getElementById('savings-interest').value
// let result = savings * interest
// let total = savings += result
// savingsInterestYr.innerHTML = result
// savingsTotalYr.innerHTML = total
// }
//
// function calcRent() {
// let rent = +document.getElementById('rent').value
// let bills = +document.getElementById('bills').value
// let rbMonth = rent += bills
// let resultRent = rbMonth * 12
// owner1yr.innerHTML = resultRent
// }
//
// function calcMort() {
// let houseUpkeek = +document.getElementById('upkeep-costs').value
// let mortgageMonth = +document.getElementById('mortgage-monthly').value
// let bills = +document.getElementById('bills').value
// let ownerMonth = mortgageMonth += bills
// let resultMortgage = ownerMonth * 12
// owner1yr.innerHTML = resultMortgage += houseUpkeek
}
<file_sep>/README.md
# buyvsrent
A simple buy vs rent calculator.
## Outline
This started as a Python file put together by a friend of my brother (dgmp88). It has since been re-written in JS to keep it as simple as possible and to allow users to run it without having an unnecessary back end.
The intention was to create a simple interface that would allow users to compare the different costs over n years between buying and renting a property.
## Instructions and use.
Clone or download the repository, open in your preferred code-editor then open index.html in your browser of choice.
When it has opened in your browser, add in your numbers for buying & renting a property and review the results populated on the right hand side.
## Process
As the python file had already been written, rewriting in JS was the next step. After this I began building the front end, ensuring all relevant figures were being passed to the correct functions.
## Challenges
1. CHALLENGE: ensuring that if the final mortgage payment was a part payment (e.g. payments are 2,000/month but the final payment is <£2,000), any remaining balance was paid into the savings account.
SOLUTION
2. CHALLENGE: de-conflicting common results from outputs when populating the results table.
SOLUTION: running seperate funcitons for populating the results for each section reduced confusion.
<file_sep>/buy_vs_rent.js
// Accounts object
function Accounts({
savingsStart = 15000,
savingsInterest = 0.07,
savingsPayments = 0,
rentPayments = 0,
rentGrowth = 0,
mortgageStart = 0,
mortgageInterest = 0.025,
mortgagePayments = 0,
houseValue = 0,
houseGrowth = 0.03
} = {}) {
// set up default values
this.savingsStart = savingsStart
this.savingsInterest = savingsInterest
this.savingsPayments = savingsPayments
this.rentPayments = rentPayments
this.rentGrowth = rentGrowth
this.mortgageStart = mortgageStart
this.mortgageInterest = mortgageInterest
this.mortgagePayments = mortgagePayments
this.houseValue = houseValue
this.houseGrowth = houseGrowth
this.savings = savingsStart
this.savings_paid = 0
this.mortgage = mortgageStart
this.mortgagePaid = 0
// set up the object methods
this.step = function () {
// Step a single year
oneOffSavings = 0
// Step 1 month at a time, as savings often compound monthly
for (i = 0; i < 12; i++) {
///// MORTGAGE
// Calculate mortage interest
mInterest = this.mortgage * (this.mortgageInterest / 12);
this.mortgage += mInterest
// Subtract payments
this.mortgage -= this.mortgagePayments
this.mortgagePaid += this.mortgagePayments
// The month the mortgage is paid off, put everything into savings
if ((this.mortgage <= 0) & (this.mortgagePayments != 0)) {
oneOffSavings = -this.mortgage
this.savingsPayments += this.mortgagePayments
this.mortgagePayments = 0
this.mortgage = 0
}
/// SAVINGS
// Add savings interest
sInterest = this.savings * (this.savingsInterest / 12)
this.savings += sInterest
// Monthly contribution + leftovers in case mortgage was paid
this.savings += this.savingsPayments + oneOffSavings
this.savings_paid += this.savingsPayments + oneOffSavings
oneOffSavings = 0
}
// Update house price (annually, it doesn't compound)
houseValueAccrued = this.houseValue * this.houseGrowth
this.houseValue += houseValueAccrued
// Update total assets
this.updateTotalAssets()
}
this.updateTotalAssets = function () {
totalAssets = 0
if (this.mortgagePaid > 0) {
houseFractionOwned =
1 - this.mortgage / (this.mortgage + this.mortgagePaid)
this.housePercentOwned = houseFractionOwned * 100
totalAssets += houseFractionOwned * this.houseValue
}
totalAssets += this.savings - this.mortgage
this.totalAssets = totalAssets
}
// function multplying inputs by years
this.step_n_years = function (years) {
for (year = 0; year < years; year++) {
// console.log(year, this.savings, this.savingsPayments, this.mortgage)
this.step()
}
}
// function to return results in console
this.prettyPrint = function () {
const toPrint = ['mortgage', 'savings', 'totalAssets']
console.log('*'.repeat(70))
for (let k of toPrint) {
// Format v
let v = this[k]
console.log(k, v)
v = v.toFixed(2).toLocaleString()
v = v.toString().padStart(20, ' ')
// Format k
k = k.padEnd(50, ' ')
let info = `${k}${v}`
console.log(info)
}
}
//
this.populateRentResults = function () {
rentSavingsResult.innerHTML = this.savings.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' })
rentAssetsResult.innerHTML = this.totalAssets.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' })
}
this.populateBuyResults = function () {
mortgageResult.innerHTML = this.mortgage.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' })
ownerSavingsResult.innerHTML = this.savings.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' })
ownerTotalAssetsResult.innerHTML = this.totalAssets.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' })
}
}
function test() {
// Check results match python with some sensible parameters
let years = 0
let initialInvestment = 20000
let houseValue = 400000
let mortgageStart = houseValue - initialInvestment
// let rentPayments = 1300
// let monthlyPayments = savingsPayments
// Rent type account
let rentAccount = new Accounts({
savingsPayments: 0,
rentPayments: 1300,
savingsStart: initialInvestment
})
// Mortgage type account
let buyAccount = new Accounts({
savingsPayments: 2000,
mortgagePayments: 2000,
mortgageStart: mortgageStart,
houseValue: houseValue
})
buyAccount.step_n_years(years)
buyAccount.prettyPrint()
rentAccount.step_n_years(years)
rentAccount.prettyPrint()
}
// test()
function runNumbers() {
//COMMON VALUES
let availableIncome = +document.getElementById('availableIncome').value
let years = +document.getElementById('years').value
let savingsStart = +document.getElementById('savingsStart').value
let mortgageInterest = (+document.getElementById('mortgageInterest').value/100)
console.log(mortgageInterest)
let savingsInterest = (+document.getElementById('savingsInterest').value/100)
console.log(savingsInterest)
// sets up a new account for home-owners, taking figures from UI.
let houseValue = +document.getElementById('houseValue').value
let mortgageStart = (houseValue - savingsStart)
let mortgagePayments = +document.getElementById('mortgagePayments').value
let buyAccount = new Accounts({
savingsPayments: availableIncome - mortgagePayments,
mortgagePayments: mortgagePayments,
savingsStart: 0,
houseValue: houseValue,
mortgageStart: mortgageStart,
mortgageInterest: mortgageInterest,
savingsInterest: savingsInterest
})
// runs through results from buyAccount, runs step_n_years() where n = UI then populates results based on output from step_n_years()
buyAccount.step_n_years(years)
buyAccount.populateBuyResults()
// sets up new account for renters, runs step_n_years() where n = UI then populates results based on output from step_n_years()
let rentPayments = +document.getElementById('rentPayments').value
let rentAccount = new Accounts({
savingsPayments: availableIncome - rentPayments,
savingsStart: savingsStart,
rentPayments: rentPayments,
savingsInterest: savingsInterest
})
rentAccount.step_n_years(years)
rentAccount.populateRentResults()
}
|
a6220220292f9e6353327bb35cb0d5fc27c5d546
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
CPrich905/buyvsrent
|
a8e0653ba7fe4d2889230d97cc9f1e668c888f63
|
01e090b453ea5ff0e608be7e1df547c894250fa6
|
refs/heads/master
|
<repo_name>atienzak/pic10c_homework1<file_sep>/README.txt
Siete y Medio - Assignment #1 | PIC10C Fall 2017 | Prof. Salazar
- This runs a simple game of Siete y Medio within the console. The game itself is
similar to Blackjack, where the cards are listed from Ace to Seven (values
1-7) and Jack to King (values all 0.5). The objective of the game is not to
go over 7.5 against the dealer.<file_sep>/homework1/homework1/Cards.cpp
#include "Cards.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <Windows.h>
#include <iomanip>
/* *************************************************
Card class
************************************************* */
// Constructor assigns random rank & suit to card.
Card::Card() {
srand(time(0)); // seed
// time delay is added so that random cards would be drawn by the computer (ie. not on the same second)
int r = 1 + rand() % 3;
if (r == 1)
{
Sleep(1000);
}
else if (r == 2)
{
Sleep(2000);
}
else
{
Sleep(3000);
}
r = 1 + rand() % 4;
switch (r) {
case 1: suit = OROS; break;
case 2: suit = COPAS; break;
case 3: suit = ESPADAS; break;
case 4: suit = BASTOS; break;
default: break;
}
r = 1 + rand() % 10;
switch (r) {
case 1: rank = AS; break;
case 2: rank = DOS; break;
case 3: rank = TRES; break;
case 4: rank = CUATRO; break;
case 5: rank = CINCO; break;
case 6: rank = SEIS; break;
case 7: rank = SIETE; break;
case 8: rank = SOTA; break;
case 9: rank = CABALLO; break;
case 10: rank = REY; break;
default: break;
}
}
// Accessor: returns a string with the suit of the card in Spanish
string Card::get_spanish_suit() const {
string suitName;
switch (suit) {
case OROS:
suitName = "oros";
break;
case COPAS:
suitName = "copas";
break;
case ESPADAS:
suitName = "espadas";
break;
case BASTOS:
suitName = "bastos";
break;
default: break;
}
return suitName;
}
// Accessor: returns a string with the rank of the card in Spanish
string Card::get_spanish_rank() const {
string rankName;
switch (rank) {
case AS:
rankName = "As";
break;
case DOS:
rankName = "Dos";
break;
case TRES:
rankName = "Tres";
break;
case CUATRO:
rankName = "Cuatro";
break;
case CINCO:
rankName = "Cinco";
break;
case SEIS:
rankName = "Seis";
break;
case SIETE:
rankName = "Siete";
break;
case SOTA:
rankName = "Sota";
break;
case CABALLO:
rankName = "Caballo";
break;
case REY:
rankName = "Rey";
break;
default: break;
}
return rankName;
}
// Accessor: returns a string with the suit of the card in English
string Card::get_english_suit() const
{
string suitName;
switch (suit) {
case OROS:
suitName = "Coins";
break;
case COPAS:
suitName = "Cups";
break;
case ESPADAS:
suitName = "Swords";
break;
case BASTOS:
suitName = "Clubs";
break;
default: break;
}
return suitName;
}
// Accessor: returns a string with the rank of the card in English
string Card::get_english_rank() const
{
string rankName;
switch (rank) {
case AS:
rankName = "Ace";
break;
case DOS:
rankName = "Two";
break;
case TRES:
rankName = "Three";
break;
case CUATRO:
rankName = "Four";
break;
case CINCO:
rankName = "Five";
break;
case SEIS:
rankName = "Six";
break;
case SIETE:
rankName = "Seven";
break;
case SOTA:
rankName = "Jack";
break;
case CABALLO:
rankName = "Knight";
break;
case REY:
rankName = "King";
break;
default: break;
}
return rankName;
}
// returns the corresponding values of the cards
double Card::get_value() const
{
double value = 0;
switch (rank) {
case AS:
value = 1;
break;
case DOS:
value = 2;
break;
case TRES:
value = 3;
break;
case CUATRO:
value = 4;
break;
case CINCO:
value = 5;
break;
case SEIS:
value = 6;
break;
case SIETE:
value = 7;
break;
case SOTA:
value = 0.5;
break;
case CABALLO:
value = 0.5;
break;
case REY:
value = 0.5;
break;
default: break;
}
return value;
}
// Assigns a numerical value to card based on rank.
// AS=1, DOS=2, ..., SIETE=7, SOTA=10, CABALLO=11, REY=12
int Card::get_rank() const {
return static_cast<int>(rank) + 1;
}
// Comparison operator for cards
// Returns TRUE if card1 < card2
bool Card::operator < (Card card2) const {
return rank < card2.rank;
}
/* *************************************************
Player class
************************************************* */
// constructors, one with initial money
Player::Player() : myhand({}), money(0) {}
Player::Player(int m) : myhand({}), money(m) {}
/**
computes the total of the value of the cards
@return value of the card
*/
double Player::card_total() const
{
double total = 0;
for (const auto& x : myhand) // add every value of card to total
{
total += x->get_value();
}
return total;
}
/**
adds another card into the hand by pushing back a Card*
*/
void Player::draw_card()
{
Card* newcard = new Card();
myhand.push_back(newcard);
return;
}
/**
checks if player loses the round (ie. card total is more than 7.5)
@return true if lost, false if not
*/
bool Player::check_lose() const
{
if (card_total() > 7.5)
return true;
else
return false;
}
/**
checks if the game has reached its end (ie. money == 0)
@return true if game is finished, false if not
*/
bool Player::check_end() const
{
if (money == 0)
return true;
else
return false;
}
/**
compares who won between the two players based on the total value of their cards
@param another the player with whom to compare
@return true if rhs player has a total higher than the lhs player but lower than 7.5
*/
bool Player::operator < (const Player& another) const
{
return (card_total() < another.card_total());
}
/**
accessor for money
@return the value of money the player has currently
*/
int Player::get_money() const
{
return money;
}
/**
sets money of the player
@param money to be set
*/
void Player::set_money(const int& a)
{
money = a;
return;
}
/**
adds bet to the money
@param a amount of bet won
*/
void Player::win_bet(const int& a)
{
money += a;
return;
}
/**
subtracts bet from money
@param b amount of money lost
*/
void Player::lose_bet(const int& b)
{
money -= b;
return;
}
/**
list cards into the console using cout
*/
void Player::list_cards() const // list cards in their names in spanish and english
{
string line_up = "";
for (const auto& x : myhand) // for every card, cout
{
line_up = x->get_spanish_rank() + " de " + x->get_spanish_suit(); // i want the setw to apply to this whole string
cout << "\t" << left << setw(20) << line_up << "(" << x->get_english_rank() << " of " << x->get_english_suit() << ")" << endl;
}
return;
}
/**
list cards into an ostream object to be used when logging into a txt file
@param ost ostream object to write into the txt file
*/
void Player::log_cards(ostream& ost) const
{
string line_up = "";
for (const auto& x : myhand) // for every card, put into ost
{
line_up = x->get_spanish_rank() + " de " + x->get_spanish_suit(); // i want the setw to apply to this whole string
ost << "\t" << left << setw(20) << line_up << "(" << x->get_english_rank() << " of " << x->get_english_suit() << ")" << endl;
}
return;
}
/**
deletes all cards that have been added
used after the end of each round
*/
void Player::reset_cards()
{
for (vector<Card*>::iterator itr = myhand.begin(); itr != myhand.end(); ++itr)
delete *itr;
myhand = {};
return;
}
/*************************************
Functions needed to play the game
**************************************/
/**
sets the bet to 0, and "do you want another card (y/n)?" back to y
@bet amount of bet to be reset to 0
@another_card sets y/n to y
*/
void reset_round(int& bet, char& another_card)
{
bet = 0;
another_card = 'y';
}
/**
writes into the text file the information about the game
@param you the main player
@param dealer the dealer against whom the player is playing
@param ost the ostream object that would be used to log the files into
@bet the amount of bet in that round
@round_number the round number
*/
void log_file(const Player& you, const Player& dealer, ofstream& ost, const int& bet, int& round_number)
{
ost.open("log_file.txt", ios::app);
ost << "---------------------------------------------\n\nRound number: " << round_number
<< setw(15) << right << "\tMoney left: $" << you.get_money() << "\nBet: $" << bet
<< "\n\nYour cards: \n";
you.log_cards(ost);
ost << "Your total: " << you.card_total() << ".\n\n";
if (dealer.card_total() != 0) // if the player went over 7.5 at the start of the round, then dealer wouldn't have any cards
{
ost << "Dealer's cards: \n";
dealer.log_cards(ost);
ost << "Dealer's total: " << dealer.card_total() << ".\n";
}
ost.close();
}
/**
the main function that executes the game
@param you the main player
@param dealer the dealer against whom the player is playing
*/
void play_game(Player& you, Player& dealer)
{
int starting_money = 0;
int bet = 0;
char another_card = 'y';
int round_number = 1;
ofstream ost; // used for logging into file; declared here so that it wouldn't create ostream onject repeatedly when log_file function is called
cout << "Welcome to <NAME>!\n" << endl
<< "Enter your starting money: ";
cin >> starting_money;
cout << "\n";
you.set_money(starting_money);
do
{
cout << "You have $" << you.get_money() << ". Enter bet: ";
cin >> bet;
cout << "\n";
// if bet is higher than amount of money, prompt player for a valid input
while (bet > you.get_money() || bet == 0)
{
cout << "Enter a valid bet: ";
cin >> bet;
}
// player adds card to his hands
while (another_card == 'y')
{
cout << "Your cards: " << endl;
you.draw_card();
you.list_cards();
cout << "Your total is " << you.card_total() << ". ";
if (you.check_lose()) // if player went over 7.5, end the round before dealer draws cards
{
cout << "You lost the round. You lose $" << bet << "." << "\n\n";
you.lose_bet(bet);
break;
}
cout << "Do you want another card (y/n)? ";
cin >> another_card;
cout << "\n";
if (another_card == 'n') // player doesn't want another card
break;
}
while (!you.check_lose() && dealer.card_total() <= you.card_total()) // if the player hasn't gone over 7.5 yet and
// the dealer's card hasn't gone over the player's total,
// then dealer would draw more cards
{
cout << "Dealer's cards:" << endl;
dealer.draw_card();
dealer.list_cards();
cout << "The dealer's total is " << dealer.card_total() << ".\n\n";
if (dealer.check_lose()) // if dealer goes over 7.5
{
cout << "Congratulations! You won $" << bet << "." << "\n\n";
log_file(you, dealer, ost, you.get_money(), round_number); // log the round before changing money
you.win_bet(bet);
break;
}
else if (you.card_total() < dealer.card_total()) // dealer has more total
{
cout << "You lost the round. You lose $" << bet << "." << "\n\n";
log_file(you, dealer, ost, you.get_money(), round_number); // log the round before changing money
you.lose_bet(bet);
break;
}
cout << "The dealer is drawing another card...\n\n";
}
if (you.check_end()) // if lost all money
{
cout << "You are out of money. Goodbye!\n\n";
}
round_number++;
reset_round(bet, another_card);
you.reset_cards(); // reset rounds
dealer.reset_cards();
} while (!you.check_end()); // do while money is > 0
}<file_sep>/homework1/homework1/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
#include "Cards.h"
using namespace std;
int main()
{
Player you;
Player dealer;
play_game(you, dealer);
}<file_sep>/homework1/homework1/Cards.h
#include <string>
#include <vector>
#include <fstream>
#ifndef CARDS_H
#define CARDS_H
using namespace std;
enum suit_t { OROS, COPAS, ESPADAS, BASTOS };
/*
The values for this type start at 0 and increase by one
afterwards until they get to SIETE.
The rank reported by the function Card::get_rank() below is
the value listed here plus one.
E.g:
The rank of AS is reported as static_cast<int>(AS) + 1 = 0 + 1 = 1
The rank of SOTA is reported as static_cast<int>(SOTA) + 1 = 9 + 1 = 10
*/
enum rank_t { AS, DOS, TRES, CUATRO, CINCO, SEIS, SIETE, SOTA = 9, CABALLO = 10, REY = 11 };
class Card {
public:
// Constructor assigns random rank & suit to card.
Card();
// Accessors
string get_spanish_suit() const;
string get_spanish_rank() const;
// Accessors (returns suit and rank in English)
string get_english_suit() const;
string get_english_rank() const;
// Converts card rank to number.
// The possible returns are: 1, 2, 3, 4, 5, 6, 7, 10, 11 and 12
int get_rank() const;
double get_value() const;
// Compare rank of two cards. E.g: Eight<Jack is true.
// Assume Ace is always 1.
// Useful if you want to sort the cards.
bool operator < (Card card2) const;
private:
suit_t suit;
rank_t rank;
};
//consolidated Hand class into Player because it only contains a vector of Card* as a private member
class Player
{
public:
// default constructor
Player();
/*
constructor, assigns initial value of money
@param m initial amount of money
*/
Player(int m);
/**
computes the total of the value of the cards
@return value of the card
*/
double card_total() const;
/**
adds another card into the hand by pushing back a Card*
*/
void draw_card();
/**
deletes all cards that have been added
used after the end of each round
*/
void reset_cards();
/**
checks if player loses the round (ie. card total is more than 7.5)
@return true if lost, false if not
*/
bool check_lose() const;
/**
checks if the game has reached its end (ie. money == 0)
@return true if game is finished, false if not
*/
bool check_end() const;
/**
compares who won between the two players based on the total value of their cards
@param another the player with whom to compare
@return true if rhs player has a total higher than the lhs player but lower than 7.5
*/
bool operator < (const Player& another) const;
/**
accessor for money
@return the value of money the player has currently
*/
int get_money() const;
/**
sets money of the player
@param money to be set
*/
void set_money(const int& a);
/**
adds bet to the money
@param a amount of bet won
*/
void win_bet(const int& a);
/**
subtracts bet from money
@param b amount of money lost
*/
void lose_bet(const int& b);
/**
list cards into the console using cout
*/
void list_cards() const;
/**
list cards into an ostream object to be used when logging into a txt file
@param ost ostream object to write into the txt file
*/
void log_cards(ostream& ost) const;
private:
//player's money, set by constructors
int money;
//cards by the player
vector<Card*> myhand;
};
//functions needed to play the game
/**
sets the bet to 0, and "do you want another card (y/n)?" back to y
@bet amount of bet to be reset to 0
@another_card sets y/n to y
*/
void reset_round(int& bet, char& another_card);
/**
writes into the text file the information about the game
@param you the main player
@param dealer the dealer against whom the player is playing
@param ost the ostream object that would be used to log the files into
@bet the amount of bet in that round
@round_number the round number
*/
void log_file(const Player& you, const Player& dealer, ofstream& ost, const int& bet, int& round_number);
/**
the main function that executes the game
@param you the main player
@param dealer the dealer against whom the player is playing
*/
void play_game(Player& you, Player& dealer);
#endif
|
bfd1fb2d1c0a4d96d6840334821a44fae28a1308
|
[
"Text",
"C++"
] | 4
|
Text
|
atienzak/pic10c_homework1
|
73aaedc8bf9cb71cbfa6592980885c5e05552083
|
2e93a1496773949161c4c4bf732a134ecbca3ca7
|
refs/heads/master
|
<repo_name>CaioBartholomeu/TimeConversion<file_sep>/TimeConversion/TimeConversion/ContentView.swift
//
// ContentView.swift
// TimeConversion
//
// Created by <NAME> on 11/08/21.
//
import SwiftUI
struct ContentView: View {
@State private var number = ""
@State private var selectedTime = 0
var times = ["hour", "minute", "second"]
@State private var hour = 0
@State private var minute:Int = 0
@State private var second = 0
func totalCalculation (){
if times[selectedTime] == "hour" {
hour = Int(number) ?? 0
minute = Int(number)!*60
second = Int(number)!*60*60
}
if times[selectedTime] == "minute" {
hour = Int(number)!/60
minute = Int(number) ?? 0
second = Int(number)!*60
}
if times[selectedTime] == "second" {
hour = Int(number)!/60/60
minute = Int(number)!/60
second = Int(number) ?? 0
}
}
var body: some View {
NavigationView{
Form {
Section{
Section(header: Text("Choice")) {
Picker("Tip percentage", selection: $selectedTime) {
ForEach(0 ..< times.count) {
Text("\(self.times[$0])")
}
}
.pickerStyle(SegmentedPickerStyle())
}
TextField("Enter a number", text: $number).keyboardType(.decimalPad)
Group{
Button("Calculate"){
if number != "" {
totalCalculation()
}
}
}
Text("hour: \(hour)")
Text("minute: \(minute)")
Text("second: \(second)")
}
}
.navigationBarTitle("Time Conversion", displayMode:.inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
f0008acb3de4358fda38b50a47afb6aef9f8164d
|
[
"Swift"
] | 1
|
Swift
|
CaioBartholomeu/TimeConversion
|
f4927ea2e08173977ce3227f6cfa49b8a9b7c417
|
4bee1b7fcbdc767202db804a72b6823ec7c2a83a
|
refs/heads/master
|
<file_sep>language_detection
--------
To use, simply do:
>>> from language_detection import language_detection
>>> detector=language_detection()
>>> print detector.language_list() #list of 50 supported languages
>>> print detector.language_id(mytext) #The language ID of input text
>>> print detector.language_name(mytext) #The name of input text's language
<file_sep>from .language import language_detection<file_sep>import pickle
import os
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics import pairwise
class language_detection:
def __init__(self):
# ''' Constructor for this class. '''
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.svd=pickle.load(open(__location__+"//data//svd.MODEL",'rb'))
self.vocabulary=pickle.load(open(__location__+"//data//lexicon.MODEL",'rb'))
self.id_of_languages=pickle.load(open(__location__+"//data//language_id.MODEL",'rb'))
self.svdmatrix=pickle.load(open(__location__+"//data//svdmatrix.MODEL",'rb'))
def language_list(self):
lan_list=[]
for item in self.id_of_languages.keys():
lan_list.append((self.id_of_languages[item]['id'],self.id_of_languages[item]['name']))
return lan_list
def index_finder(self,text):
clean_text=self.clean(text)
n_gram=self.ngram_extractor(clean_text)
matrix=self.ngram_to_matrix(n_gram)
svd_matrix=self.svd_transform(matrix)
index=self.detect_similarity(svd_matrix)
return index
def language_id(self,text):
index=self.index_finder(text)
print "The Language ID is: "+self.id_of_languages[index]["id"]
return self.id_of_languages[index]["id"]
def language_name(self,text):
index=self.index_finder(text)
print "The Language Name is: "+self.id_of_languages[index]["name"]
return self.id_of_languages[index]["name"]
def clean(self,text):
try:
clean_text=text.decode("utf8").lower()
except:
clean_text=text.lower()
clean_text=clean_text.replace(" ","")
return clean_text
def ngram_extractor(self,text):
n_gram_list=[]
for i in range(len(text)-3):
n_gram_list.append(text[i:i+4])
return list(set(n_gram_list))
def ngram_to_matrix(self,n_gram):
matrix=[0]*len(self.vocabulary)
for gram in n_gram:
try:
position=self.vocabulary[gram]
matrix[position]=1
except:
pass
return matrix
def svd_transform(self,matrix):
return self.svd.transform([matrix])
def detect_similarity(self,svd_matrix):
ind=0
max_sim=-1
sim=pairwise.cosine_similarity(self.svdmatrix,svd_matrix)
for i in range(len(sim)):
if(sim[i]>max_sim):
max_sim=sim[i]
ind=i
return ind
<file_sep>from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(name='language_detection',
version='0.1',
description='The fast language detection module',
url='https://github.com/salarmohtaj/language_detection',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['language_detection'],
package_data={'language_detection': ['data//*.MODEL']},
include_package_data=True,
install_requires=['sklearn'],
zip_safe=False)
|
c4dcb872d7cbd29bf38cef424faaa510bdaed4cc
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
salarmohtaj/language_detection
|
815a98ebf75b287e93b63d7ea81d63e297e21e04
|
cc04c854862442ca7f545dbef9e8497e0e5bf6f1
|
refs/heads/master
|
<file_sep>package com.lol.josb.tarealogin;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText txtUsuario;
private EditText txtContrasena;
private Button btnEntrar;
private Button btnRegistrar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creamos el toolbar
Toolbar toolbar =(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Toolbar xD");
setSupportActionBar(toolbar);
//Obtenemos una referencia a los controles de la interfaz
btnEntrar=(Button)findViewById(R.id.BtnEntrar);
btnRegistrar=(Button)findViewById(R.id.BtnRegistrar);
txtContrasena=(EditText)findViewById(R.id.TxtContrasena);
txtUsuario=(EditText)findViewById(R.id.TxtUsuario);
//Añadimos eventos a los botones
btnRegistrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creamos el intent
Intent intent=new Intent(MainActivity.this,Registro.class);
startActivity(intent);
}
});
btnEntrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creamos el intent
Intent intent=new Intent(MainActivity.this, Entrar.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Aqui añadimos funcionalidad al menu
@Override
public boolean onOptionsItemSelected(MenuItem item ) {
switch (item.getItemId()){
case R.id.action_add:
action("Add");
return true;
case R.id.action_edit:
action("Edit");
return true;
case R.id.action_settings:
action("Settings");
return true;
case R.id.action_help:
action("Help");
return true;
case R.id.action_about:
action("About");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Esto manda notificaciones en pantalla
public void action(String mensaje){
Toast.makeText(this, mensaje, Toast.LENGTH_SHORT).show();
}
}
|
d3766ef35cd6b6fb36b78a97d28a59208ca12a69
|
[
"Java"
] | 1
|
Java
|
josomab2/TareaLogin
|
93cc12a8f164347f7ab2554379706c79ce7ae161
|
d740d27c5e1b9c97468c3c8440570cfe8b2604b7
|
refs/heads/master
|
<file_sep>source "https://rubygems.org"
gem 'rake'
gem 'sinatra'
gem 'sinatra-contrib'
gem 'haml'
gem 'httparty'
gem 'encrypted_cookie'
# Sass & Compass
gem 'sass'
gem 'compass'
# Database
gem "pg"
gem "activerecord"
gem "sinatra-activerecord"
# GitLab API
gem 'gitlab'
# Web server
gem 'unicorn'
group :test do
gem 'rspec'
gem 'capybara'
end
<file_sep>class TimeLog < ActiveRecord::Base
validates_presence_of :time, :day, :issue_iid, :project_id, :user_id
end
<file_sep>APP_ROOT = File.dirname(__FILE__)
SECRET = File.join(APP_ROOT, '.secret')
# Change this to restrict login with one instance
GITLAB_SERVER = nil# Ex. 'http://demo.gitlab.com'
require 'rubygems'
require 'sinatra/base'
require "sinatra/reloader"
require 'haml'
require 'gitlab'
require 'encrypted_cookie'
require 'securerandom'
class GitLabTimeTracking < Sinatra::Base
# Create .secret file for EncryptedCookie
unless File.exists?(SECRET)
File.open(SECRET, 'w') { |file| file.write(SecureRandom.hex(32)) }
end
use Rack::Session::EncryptedCookie,
secret: File.read(File.join(APP_ROOT, '.secret')).strip
configure :development do
register Sinatra::Reloader
end
set :database_file, "#{APP_ROOT}/config/database.yml"
require 'sinatra/activerecord'
require './helpers/render_partial'
require './models/user'
require './models/time_log'
get '/' do
authenticate_user!
@day_to = if params[:day_to]
params[:day_to].to_date
else
Date.today
end
@day_from = @day_to - 1.week
@time_logs = TimeLog.where(user_id: current_user.id).where("day >= ? AND day <= ?", @day_from, @day_to)
@days = (@day_from..@day_to).to_a
haml :index
end
get '/profile' do
authenticate_user!
haml :profile
end
get '/login' do
haml :login
end
get '/logout' do
sign_out
redirect '/'
end
post '/user_sessions' do
begin
user = User.authenticate(params[:user_session])
rescue Gitlab::Error::Unauthorized
@error = "Wrong login or password"
rescue URI::InvalidURIError
@error = "Wrong server url"
end
if user && sign_in(user)
redirect '/'
else
haml :login
end
end
get '/log_time' do
authenticate_user!
@projects = current_user.projects
haml :log_time
end
post '/create_time_log' do
authenticate_user!
time_log = TimeLog.new(params['time_log'])
time_log.user_id = current_user.id
if time_log.save
redirect '/'
else
haml :log_time
end
end
helpers do
def current_user
@current_user ||= begin
if session[:current_user]
User.new(Marshal.load(session[:current_user]))
end
end
end
def sign_in(user)
session[:current_user] = Marshal.dump user.to_hash
end
def sign_out
session[:current_user] = nil
end
def authenticate_user!
unless current_user
redirect '/login'
return
end
end
def gravatar_icon(user_email = '', size = 40)
gravatar_url ||= 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=mm'
user_email.strip!
sprintf gravatar_url, hash: Digest::MD5.hexdigest(user_email.downcase), size: size
end
def link_to(title, path, opts={})
"<a href='#{path}' class='#{opts[:class]}'>#{title}</a>"
end
def issue_url(project, id)
project.web_url + '/issues/' + id.to_s
end
end
# start the server if ruby file executed directly
run! if app_file == $0
end
<file_sep>namespace :css do
desc "Clear the CSS"
task :clear => ["compile:clear"]
desc "Compile CSS"
task :compile => ["compile:default"]
namespace :compile do
task :clear do
puts "*** Clearing CSS ***"
system "rm -Rfv public/stylesheets/*"
end
task :default => :clear do
puts "*** Compiling CSS ***"
system "compass compile"
end
desc "Compile CSS for production"
task :prod => :clear do
puts "*** Compiling CSS ***"
system "compass compile --output-style compressed --force"
end
end
end
<file_sep>ENV['RACK_ENV'] = 'test'
require 'capybara'
require 'capybara/dsl'
require_relative '../app'
Capybara.app = GitLabTimeTracking
module Helpers
def sign_in
visit '/login'
fill_in 'user_session_email', with: '<EMAIL>'
fill_in 'user_session_password', with: '<PASSWORD>'
fill_in 'user_session_url', with: 'http://demo.gitlab.com'
click_button "Sign in"
end
end
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
config.include Capybara
config.include Helpers
end
<file_sep>module RenderPartial
def partial(page, options={})
haml page, options.merge!(:layout => false)
end
end
if respond_to?(:helpers)
helpers RenderPartial
end
<file_sep>class User
attr_reader :attributes
def self.authenticate(params)
if GITLAB_SERVER
url = GITLAB_SERVER
else
url = params.delete('url')
end
unless url =~ URI::regexp
raise URI::InvalidURIError
end
client = Gitlab.client(endpoint: url + '/api/v3/')
response = client.session(params['email'], params['password'])
if response
User.new(response.to_hash.merge("url" => url))
end
end
def initialize(hash)
@attributes = hash
end
def method_missing(meth, *args, &block)
if attributes.has_key?(meth.to_s)
attributes[meth.to_s]
else
super
end
end
def projects
client = Gitlab.client(endpoint: self.url + '/api/v3/', private_token: self.private_token)
client.projects(per_page: 100)
end
def project(id)
client = Gitlab.client(endpoint: self.url + '/api/v3/', private_token: self.private_token)
client.project(id)
end
def to_hash
@attributes
end
end
<file_sep>require 'spec_helper'
describe 'Login' do
before { visit '/login' }
it { page.should have_content 'Sign in' }
it 'should login using valid credentials' do
sign_in
page.should have_content '<NAME>'
page.should have_content 'Logout'
end
end
<file_sep>desc "Run unicorn web server"
task :unicorn => ["unicorn:development"]
namespace :unicorn do
desc "Run unicorn web server for development"
task :development do
system "unicorn -c config/unicorn.rb -E development -p 4567"
end
desc "Run unicorn web server for production"
task :production do
system "unicorn -c config/unicorn.rb -E production -D"
end
end
<file_sep>desc 'Run the app'
task :s do
system "rackup -p 4567"
end
<file_sep># GitLab Time Tracking
Time tracking app for GitLab

## Requirements:
* Ruby 1.9+
* Postgresql
## Postgresql
Postgresql database:
# Install the database packages
sudo apt-get install -y postgresql-9.1 postgresql-client libpq-dev
# Login to PostgreSQL and create user/database
sudo -u postgres psql -d template1
template1=# CREATE USER your-username CREATEDB;
template1=# CREATE DATABASE gtt_production OWNER your-username;
template1=# \q
## App
Get source code
git clone https://gitlab.com/dzaporozhets/gitlab-time-tracking.git
cd gitlab-time-tracking
Setup libs:
bundle install
Edit db ssettings:
cp config/database.yml.postgresql config/database.yml
vim config/database.yml
## Development
Create db tables:
bundle exec rake db:setup
Start app on localhost:4567
rake s
## Production
Create db tables:
bundle exec rake db:setup RACK_ENV=production
Create tmp and log dirs
mkdir tmp
mkdir tmp/sockets
mkdir tmp/pids
mkdir log
Start unicorn:
bundle exec rake unicorn:production
Install nginx:
sudo apt-get install nginx
Setup nginx `http` section:
# use the socket we configured in our unicorn.rb
upstream unicorn_server {
server unix:/path/to/app/tmp/sockets/unicorn.sock;
}
# configure the virtual host
server {
# replace with your domain name
server_name my-sinatra-app.com;
# replace this with your static Sinatra app files, root + public
root /path/to/app/public;
# port to listen for requests on
listen 80;
location / {
try_files $uri @app;
}
location @app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
# pass to the upstream unicorn server mentioned above
proxy_pass http://unicorn_server;
}
}<file_sep>if ENV['RACK_ENV'] = 'development'
dates = (1.weeks.ago.to_date..Date.today).to_a
times = [0.5, 1, 1.5, 2, 4]
projects = [1,2,3]
issues = [1,2,3,4,5]
20.times do
TimeLog.create(
time: times.sample,
day: dates.sample,
issue_iid: issues.sample,
project_id: projects.sample,
)
end
end
<file_sep>require 'spec_helper'
describe 'Login' do
before {
sign_in
visit '/profile'
}
it { page.should have_content 'Hi, <NAME>' }
it { page.should have_content 'GitLab profile' }
end
|
da50cd6e0a819a11c5508017d4deabfd436a7aa6
|
[
"Markdown",
"Ruby"
] | 13
|
Ruby
|
dzaporozhets/gitlab-time-tracking
|
0fc4154eeec24ce776791ce68086c4b090f429eb
|
10f2f56587ba3a16f9e9ec23c4cd30a9a2c12b90
|
refs/heads/main
|
<file_sep>var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
// button.innerHTML = count + " people chose this too!";
button.classList.add('correct');
}
// document.getElementById("clickme")addEventListener('click', function()
// {document.getElementById("clickme").classList.add('correct');});
// var correct= document.getElementById("clickme");
// clickme.className += " correct";
// var button = document.getElementById("clickme"),
// button.onclick = function () {
// var element = document.getElementById("clickme");
// element.classList.toggle("correct");
// // button.classList.add('correct');
// }
// init controller
var controller = new ScrollMagic.Controller();
new ScrollMagic.Scene({triggerElement: '#end1'})
.setClassToggle('#animation1')
.addIndicators()
.addTo(controller);
// build scene
// var scene = new ScrollMagic.Scene({triggerElement: "#animation1"})
// // trigger a velocity opaticy animation
// .setVelocity("#end1", {opacity: 0}, {duration: 400})
// .addIndicators() // add indicators (requires plugin)
// .addTo(controller);
|
f8be2b1d49b5e97a684dd2dcb3beb683e1521e75
|
[
"JavaScript"
] | 1
|
JavaScript
|
dinakhalil1/thesiswebsite
|
fa1898c938d7bbc5583cc14a41367cc44c4bc1a8
|
9581da03dd133c66a60a3ddb9e0e3bde6c57ce50
|
refs/heads/master
|
<file_sep>from django.http import HttpResponse
from django.shortcuts import render, redirect
# Create your views here.
from mall.models import User, Miaosha, Wrapper
def index(request):
username = request.COOKIES.get('username')
miaoshalist = Miaosha.objects.all()
wrapperlist = Wrapper.objects.all()
return render(request, '天狗商城.html', context={
'username':username,
'miaoshalist':miaoshalist,
'wrapperlist':wrapperlist,
})
def register(request):
if request.method == 'GET':
return render(request, '注册.html')
elif request.method == 'POST':
email = request.POST.get('email')
username = request.POST.get('username')
password = <PASSWORD>('<PASSWORD>')
user = User()
user.username = username
user.password = <PASSWORD>
user.email = email
user.save()
response = redirect('mall:index')
response.set_cookie('username', user.username)
return response
def login(request):
if request.method == 'GET':
return render(request, '注册.html')
elif request.method == 'POST':
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')
users = User.objects.all().filter(username=username).filter(password=password)
if users.exists():
user = users[0]
response = redirect('mall:index')
response.set_cookie('username', user.username)
return response
else:
return HttpResponse('登录失败')
def logout(request):
response = redirect('mall:index')
response.delete_cookie('username')
return response
def showdetails(request, num=1):
goods = Miaosha.objects.all().get(id=num)
username = request.COOKIES.get('username')
return render(request, '商品详情1.html', context={
'username':username,
'goods':goods,
})
def cart(request):
username = request.COOKIES.get('username')
return render(request, '我的购物车.html', context={'username':username})<file_sep>$(function() {
$(".num_first").html(b.length);
$("#nav_feiLei").mouseenter(function() {
$(".sideNav").show();
var navLit = $(".navList");
navLit.mouseenter(function() {
$(this).find("ul").show().parent().siblings().find("ul").hide();
$(this).find("h3 a").removeClass().addClass("change").parent().parent().siblings().find("h3 a").removeClass("change")
$(this).find("h3").addClass("fuck").parent().siblings().find("h3").removeClass("fuck");
});
navLit.mouseleave(function() {
$(this).find("ul").hide();
$(this).find("h3 a").removeClass("change");
$(this).find("h3").removeClass("fuck");
})
})
$(".sideNav").mouseleave(function() {
$(".sideNav").hide();
})
})
//注册
$(function() {
var email = $("#email");
var emailTip = $("#emailTip");
var username = $("#username");
var usernameTip = $("#usernameTip");
var pwd1 = $("#<PASSWORD>");
var pwd1Tip = $("#pwd1Tip");
var pwd2 = $("#pwd2");
var pwd2Tip = $("#pwd2Tip");
var ok1 = false;
var ok2 = false;
var ok3 = false;
var ok4 = false;
var ok5 = false;
//输入邮箱
email.on({
"focus": function() {
emailTip.html("填写正确的邮箱");
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
if(email.val() == "") {
emailTip.html("邮箱不正确");
}
if(email.val() != "") {
var reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
if(reg.test(email.val())) {
emailTip.html("填写对了");
ok1 = true;
} else {
emailTip.html("邮箱格式不正确");
}
for(var i = 0; i < users.length; i++) {
if(users[i].email == $("#email").val()) {
emailTip.html("邮箱已注册");
return;
}
}
}
}
})
//输入用户名
username.on({
"focus": function() {
usernameTip.html("4-20英文字符,数字,'_'的组合.");
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
if(username.val() == "") {
usernameTip.html("你输入的用户名不正确");
}
if(username.val() != "") {
var reg = /^[a-zA-Z]\w{4,20}$/;
if(reg.test(username.val())) {
usernameTip.html("用户名可以注册");
ok2 = true;
} else {
usernameTip.html("你输入的用户名格式不正确");
}
for(var i = 0; i < users.length; i++) {
if(users[i].name == $("#username").val()) {
usernameTip.html("用户名已注册");
return;
}
}
}
}
})
//输入密码
pwd1.on({
"focus": function() {
pwd1Tip.html("6-16位字符");
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
if(pwd1.val() == "") {
pwd1Tip.html("密码不合法,请确认");
}
if(pwd1.val() != "") {
var reg = /^[a-zA-Z]\w{6,16}$/;
if(reg.test(pwd1.val())) {
pwd1Tip.html("密码合法");
ok3 = true;
} else {
pwd1Tip.html("密码不合法");
}
}
}
})
//重复密码
pwd2.on({
"focus": function() {
pwd2Tip.html("两次密码必须一致");
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
if(pwd2.val() == "") {
pwd2Tip.html("密码不合法,请确认");
}
if(pwd1.val() == pwd2.val()) {
pwd2Tip.html("密码一致");
ok4 = true;
} else {
pwd2Tip.html("密码不一致");
}
}
})
$("#Txtidcode").on({
"focus": function() {
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
}
})
//验证码
$.idcode.setCode();
$("#lognUp").click(function() {
var isby = $.idcode.validateCode();
if(isby) {
console.log("验证码输入正确");
ok5 = true;
} else {
// alert("验证码输入错误")
}
if(ok1 && ok2 && ok3 && ok4 && ok5) {
} else {
// return false;
}
})
})
//登录
$(function() {
var name = $("#user");
var pwd = $("#pwd");
name.on({
"focus": function() {
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
}
})
pwd.on({
"focus": function() {
$(this).css("border-color", "orange");
},
"blur": function() {
$(this).css("border-color", "");
}
})
})<file_sep>from django.conf.urls import url
from mall import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^register/$', views.register, name='register'),
url(r'^showdetails/(\d+)/$', views.showdetails, name='showdetails'),
url(r'^cart/$', views.cart, name='cart'),
]<file_sep>$(function () {
$('img').each(function () {
var oldsrc = $(this).attr('src')
var newsrc = "{% static '" + oldsrc + "' %}"
$(this).attr('src', newsrc)
})
console.log($('body').html())
})
// window.onload = function () {
// arry1 = document.getElementsByTagName("img")
// for(var i in arry1){
// var oldsrc = arry1[i].src
// var newsrc = "{% static '" + oldsrc + "' %}"
// arry1[i].src = newsrc
// }
// console.log('44444')
// console.log(document.body.innerHTML)
// }<file_sep>$(function() {
// //用户名显示
// var a = $.cookie("loginUser");
// console.log(a);
// if(a) {
// $("#p").html("您好:" + a + "用户!" + "<a class='exit'>退出</a>");
// } else {
// $("#p").html();
// }
// $(".exit").click(function() {
// $(this).css("cursor", "pointer")
// $.cookie("loginUser", "", {
// expires: 20,
// path: "/"
// })
// window.location.reload();
// })
//商品列表移入移出
$("#nav_feiLei").mouseenter(function() {
$(".sideNav").show();
var navLit = $(".navList");
navLit.mouseenter(function() {
$(this).find("ul").show().parent().siblings().find("ul").hide();
$(this).find("h3 a").removeClass().addClass("change").parent().parent().siblings().find("h3 a").removeClass("change")
$(this).find("h3").addClass("fuck").parent().siblings().find("h3").removeClass("fuck");
});
navLit.mouseleave(function() {
$(this).find("ul").hide();
$(this).find("h3 a").removeClass("change");
$(this).find("h3").removeClass("fuck");
})
})
$(".sideNav").mouseleave(function() {
$(".sideNav").hide();
});
})
//获取cookie
$(function() {
var goodsList = $.cookie("cart");
if(goodsList) {
$("#Tr").css("display", "none");
$("table tfoot").show();
goodsList = JSON.parse(goodsList);
console.log(goodsList);
for(var i = 0; i < goodsList.length; i++) {
var goods = goodsList[i]; //每个商品
//创建节点
var td1 = $("<td></td>");
var p = $("<p></p>");
var img = $("<img>");
imgsrc = "/static/"+ goods.img;
img.attr("src", imgsrc);
img.css("float", "left");
var avt = $("<a>" + goods.name + ",颜色:" + goods.color + "</a>");
p.append(img, avt);
p.css({
"line-height": "18px",
fontSize: "16px",
"text-align": "left",
});
td1.append(p);
var td2 = $("<td>" + goods.price + "</td>");
td2.css("font-weight", "bold");
var td3 = $("<td></td>");
var b = $("<b class='b'>" + goods.sprice + "</b>");
td3.append(b);
b.css("color", "#d90000");
var td4 = $("<td></td>");
var a1 = $("<a class='a_left'>-</a>");
var input1 = $("<input>");
input1.css({
width: "60px",
height: "20px",
border: "1px solid #ccc"
})
input1.attr("value", goods.num);
input1.attr("readonly", "readonly");
var a2 = $("<a class='a_right'>+</a>");
td4.append(a1, input1, a2);
var td5 = $("<td></td>");
var prices = goods.sprice.substring(1);
var strong = $("<strong class='str'>" + "¥" + prices * goods.num + "</strong>");
td5.append(strong);
strong.css("color", "#ff0000");
var td6 = $("<td></td>");
var a = $("<a class='art'>取消订购</a>");
a.css("cursor", "pointer");
td6.append(a);
var tr = $("<tr class='trnum'></tr>");
tr.append(td1, td2, td3, td4, td5, td6);
$("tbody").append(tr);
$(".special").html("¥" + prices * goods.num);
$(".number").html($(".trnum").length);
//把每种商品占据表格的总长度存进新的cookie当中,让其它页面同步
var b = $.cookie("cart") ? JSON.parse($.cookie("cart")) : [];
$(".num_first").html(b.length);
}
//清空购物车
$(".clear").click(function() {
$.cookie("cart", "", {
expires: 0,
path: "/"
});
alert("购物车已清除");
$("table tbody").hide();
$("table tfoot").hide();
$("#Tr").show();
window.location.reload();
})
//取消订购
$(".art").click(function() {
var i = $(this).index(".art");
goodsList.splice(i, 1);
$.cookie("cart", "", {
expires: 0,
path: "/"
});
$.cookie("cart", JSON.stringify(goodsList), {
expires: 30,
path: "/"
});
alert("订单已取消!");
window.location.reload();
if(!goodsList) {
$("#Tr").show();
$("table tfoot").hide();
}
});
//结算
$(".money").click(function() {
alert("付款成功");
$(".art").html("已付款");
$("table tfoot").hide();
})
//数量减少
$(".a_left").click(function() {
var t = $(this).parent().parent().find('input');
t.val(parseInt(t.val()) - 1)
var con1 = $(this).parent().parent().find(".str");
var con2 = ($(this).parent().parent().find(".b").html()).substring(1);
con1.html("¥" + con2 * parseInt(t.val()));
if(parseInt(t.val()) < 1) {
t.val(1);
con1.html($(this).parent().parent().find(".b").html());
}
setTotal();
//当前减少的数量写入cookie
var i = $(this).index(".a_left");
goodsList[i].num = t.val();
$.cookie("cart", "", {
expires: 0,
path: "/"
});
$.cookie("cart", JSON.stringify(goodsList), {
expires: 30,
path: "/"
});
})
//数量增加
$(".a_right").click(function() {
var t = $(this).parent().parent().find('input');
t.val(parseInt(t.val()) + 1)
var con1 = $(this).parent().parent().find(".str");
var con2 = $(this).parent().parent().find(".b").html().substring(1);
con1.html("¥" + con2 * parseInt(t.val()));
setTotal();
//当前增加的数量写入cookie
var i = $(this).index(".a_right");
goodsList[i].num = t.val();
$.cookie("cart", "", {
expires: 0,
path: "/"
});
$.cookie("cart", JSON.stringify(goodsList), {
expires: 30,
path: "/"
});
})
//价格总计函数
function setTotal() {
var s = 0;
var t = 0;
//遍历每一行的商品
$(".trnum").each(function() {
var count = $(this).find('.b').html().substring(1);
s += parseInt($(this).find('input').val()) * count;
t += parseInt($(this).find('input').val()) * 373;
});
$(".special").html("¥" + s);
$('.fen').html(t)
}
setTotal();
}
})<file_sep>{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<title>天狗商城</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/swiper.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/主页.css' %}" />
<script src="{% static 'js/jquery-3.1.0.js' %}"></script>
<script src="{% static 'js/swiper.min.js' %}"></script>
<script src="{% static 'js/jquery.cookie.js' %}"></script>
<script src="{% static 'js/主页.js' %}"></script>
</head>
<body>
<!--顶部开始-->
<div id="header_top">
<div id="header">
<p id="p">您好:欢迎光临天狗商城!
{% if username %}
<b>{{ username }}</b>
<a href="{% url 'mall:logout' %}">退出</a>
{% else %}
<a href="{% url 'mall:login' %}">请登录</a>,新用户?
<a href="{% url 'mall:login' %}">免费注册</a>
{% endif %}
</p>
<div id="header_list">
<a href="{% url 'mall:cart' %}">
<p id="p2">购物车<span style="color: red;" class="num_first">0</span>件</p>
</a>
<span><a href="#">我的订单</a></span>|
<span><a href="#">网站地图</a></span>|
<span><a href="#">帮助中心</a></span>|
<span><a href="#">加入收藏</a></span>|
<span><a href="#">设为首页</a></span>
</div>
</div>
</div>
<!--顶部结束-->
<!--logo开始-->
<div id="logo">
<div id="logo_tu">
<img src="{% static 'img/p201401211350199562.jpg' %}" alt="图片">
</div>
<div id="search">
<div id="search_txt">
<span>商品</span>
<div id="search_con">
<input type="text" name="" id="txt" value="多搜搜,意外惊喜等你拿">
</div>
<p>
<a href="#">手机</a>/
<a href="#">钟表</a>/
<a href="#">家电</a>/
<a href="#">电脑</a>/
<a href="#">男装</a>/
<a href="#">女装</a>/
<a href="#">灯具</a>/
<a href="#">童装</a>/
<a href="#">儿童玩具</a>/
<a href="#">笔记本</a>/
<a href="#">平板</a>/
<a href="#">相机</a>/
<a href="#">鞋</a>/
</p>
</div>
<div id="search_suo">
<input type="button" id="btn" value="搜索">
</div>
</div>
</div>
<!--logo结束-->
<!--导航栏1开始-->
<div id="nav">
<div id="nav_feiLei">
<a href="#">所有商品分类</a>
</div>
<ul id="nav_list">
<li>
<a href="#">首页</a>
</li>
<li>
<a href="#">手机数码</a>
</li>
<li>
<a href="#">礼品箱包</a>
</li>
<li>
<a href="#">厨具用品</a>
</li>
<li>
<a href="#">电脑办公</a>
</li>
<li>
<a href="#">服饰鞋帽</a>
</li>
<li>
<a href="#">个护化妆</a>
</li>
<li>
<a href="#">母婴用品</a>
</li>
</ul>
<div id="nav_con">
<dl>
<dd>
<div class="hot"></div>
<a href="#">分销</a>
</dd>
<dd>
<div class="new"></div>
<a href="#">导航</a>
</dd>
<dd>
<div class="diy"></div>
<a href="#">团购</a>
</dd>
<dd>
<div class="go"></div>
<a href="#">充值</a>
</dd>
</dl>
</div>
</div>
<!--导航栏1结束-->
<!--导航栏2开始-->
<div id="nav2">
{# <div id="nav2_sd"></div>#}
<div class="sideNav">
<div class="navList">
<h3 class="icon_11"><a href="#">家用电器</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">大家电</a></dt>
<dd>
<a href="#">平板电视</a>|
<a href="#">空调</a>|
<a href="#">冰箱</a>|
<a href="#">洗衣机</a>|
<a href="#">家庭影院</a>|
<a href="#">DVD播放机</a>|
<a href="#">迷你音响</a>|
<a href="#">烟机/灶具</a>|
<a href="#">热水器</a>|
<a href="#">消毒柜/洗碗机</a>|
<a href="#">酒柜/冰吧/冷柜</a>|
<a href="#">家电配件</a>|
<a href="#">家电下乡</a>|
</dd>
</dl>
<dl>
<dt><a href="#">生活电器</a></dt>
<dd>
<a href="#">取暖电器</a>|
<a href="#">净化器</a>|
<a href="#">加湿器</a>|
<a href="#">吸尘器</a>|
<a href="#">净水设备</a>|
<a href="#">饮水机</a>|
<a href="#">挂烫机/熨斗</a>|
<a href="#">电话机</a>|
<a href="#">插座</a>|
<a href="#">收录/音机</a>|
<a href="#">除湿/干衣机</a>|
<a href="#">清洁机</a>|
<a href="#">电风扇</a>|
<a href="#">冷风扇</a>|
<a href="#">其它生活电器</a>|
</dd>
</dl>
<dl>
<dt><a href="#">厨房电器</a></dt>
<dd>
<a href="#">料理/榨汁机</a>|
<a href="#">豆浆机</a>|
<a href="#">电饭煲</a>|
<a href="#">电压力锅</a>|
<a href="#">面包机</a>|
<a href="#">咖啡机</a>|
<a href="#">微波炉</a>|
<a href="#">电烤箱</a>|
<a href="#">电磁炉</a>|
<a href="#">电饼档/烧烤箱</a>|
<a href="#">煮蛋器</a>|
<a href="#">酸奶机</a>|
<a href="#">电炖锅</a>|
<a href="#">电水壶/热水瓶</a>|
<a href="#">多用途锅</a>|
<a href="#">果蔬解毒机</a>|
<a href="#">其它厨房电器</a>|
</dd>
</dl>
<dl>
<dt><a href="#">个护健康</a></dt>
<dd>
<a href="#">剃须刀</a>|
<a href="#">剃/脱毛器</a>|
<a href="#">口腔护理</a>|
<a href="#">电吹风</a>|
<a href="#">美容器</a>|
<a href="#">按摩椅</a>|
<a href="#">按摩器</a>|
<a href="#">足浴盆</a>|
<a href="#">血压计</a>|
<a href="#">健康秤/厨房秤</a>|
<a href="#">血糖仪</a>|
<a href="#">体温计</a>|
<a href="#">计步器/脂肪检测仪</a>|
<a href="#">其它健康电器</a>|
</dd>
</dl>
<dl>
<dt><a href="#">五金家装</a></dt>
<dd>
<a href="#">电动工具</a>|
<a href="#">手动工具</a>|
<a href="#">仪器仪表</a>|
<a href="#">浴霸/排气扇</a>|
<a href="#">灯具</a>|
<a href="#">LED灯</a>|
<a href="#">洁身器</a>|
<a href="#">水槽</a>|
<a href="#">龙头</a>|
<a href="#">淋浴花洒</a>|
<a href="#">厨卫五金</a>|
<a href="#">家具五金</a>|
<a href="#">门铃</a>|
<a href="#">电气开关</a>|
<a href="#">插座</a>|
<a href="#">电工电料</a>|
<a href="#">监控安防</a>|
<a href="#">电线/线缆</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_07"><a href="#">珠宝首饰</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">七匹狼</a></dt>
<dt><a href="#">耐克</a></dt>
<dt><a href="#">亲贝</a></dt>
<dt><a href="#">龙之昱</a></dt>
<dt><a href="#">亲亲宝贝</a></dt>
<dt><a href="#"></a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_08"><a href="#">时尚钟表</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_09"><a href="#">运动健康</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_16"><a href="#">图像音像</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_05"><a href="#">家居家装</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_06"><a href="#">厨具用品</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_10"><a href="#">电脑办公</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_01"><a href="#">服饰鞋帽</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_02"><a href="#">个护化妆</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_12"><a href="#">汽车用品</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_14"><a href="#">玩具乐器</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
<div class="navList">
<h3 class="icon_15"><a href="#">食品保健</a></h3>
<ul>
<div id="ul_left">
<h4>选择分类</h4>
<dl>
<dt><a href="#">时尚饰品</a></dt>
<dd>
<a href="#">项链</a>|
<a href="#">手脚脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">头饰</a>|
<a href="#">胸针</a>|
<a href="#">婚庆饰品</a>|
<a href="#">饰品配件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">纯金K金</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
</dd>
</dl>
<dl>
<dt><a href="#">金银投资</a></dt>
<dd>
<a href="#">工艺金</a>|
<a href="#">工艺银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">银饰</a></dt>
<dd>
<a href="#">吊坠/项链</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指/耳饰</a>|
<a href="#">宝宝金银</a>|
</dd>
</dl>
<dl>
<dt><a href="#">翡翠玉石</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">手镯/手串</a>|
<a href="#">戒指</a>|
<a href="#">耳饰</a>|
<a href="#">挂件/摆件/把件</a>|
<a href="#">高值收藏</a>|
</dd>
</dl>
<dl>
<dt><a href="#">水晶玛瑙</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯/手链/脚链</a>|
<a href="#">戒指</a>|
<a href="#">头饰/胸针</a>|
<a href="#">摆件/挂件</a>|
</dd>
</dl>
<dl>
<dt><a href="#">宝石珍珠</a></dt>
<dd>
<a href="#">项链/吊坠</a>|
<a href="#">耳饰</a>|
<a href="#">手镯</a>|
<a href="#">手链</a>|
<a href="#">戒指</a>|
</dd>
</dl>
<dl>
<dt><a href="#">婚庆</a></dt>
<dd>
<a href="#">婚嫁首饰</a>|
<a href="#">婚纱摄影</a>|
<a href="#">婚纱礼服</a>|
<a href="#">婚庆用品/礼品</a>|
<a href="#">婚宴</a>|
</dd>
</dl>
</div>
<div id="ul_right">
<h2>热门品牌</h2>
<dl>
<dt><a href="#">西门子</a></dt>
<dt><a href="#">海尔</a></dt>
<dt><a href="#">松下</a></dt>
<dt><a href="#">飞利浦</a></dt>
<dt><a href="#">小霸王</a></dt>
<dt><a href="#">创维</a></dt>
</dl>
<h2>促销活动:</h2>
</div>
</ul>
</div>
</div>
<!--轮播图开始-->
<div id="iFocus">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
{% for wrapper in wrapperlist %}
<div class="swiper-slide">
<img src="{% static wrapper.img %}" alt="">
</div>
{% endfor %}
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</div>
</div>
<!--导航栏2结束-->
<!--商标图片开始-->
<div id="smallImg">
<a href="#"><img src="{% static 'img/p201406071435494008.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201312061100260276.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201404011334302415.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201603161259330219.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201603161302213462.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201603151537553117.jpg' %}"></a>
<a href="#"><img src="{% static 'img/p201603212021240460.jpg' %}"></a>
<a href="#" id="smallImg_a">更多</a>
</div>
<!--商标图片结束-->
<!--秒杀商品开始-->
<div id="shoping">
<div id="shoping_left">
<ul id="shoping_tf">
<li class="active">秒杀</li>
<li>超值特惠</li>
<li>人气特卖</li>
<li>今日抢购</li>
</ul>
{% for miaosha in miaoshalist %}
<dl class=shoping_phone>
<dt>
<a href="{% url 'mall:showdetails' miaosha.id %}">
<img src="{% static miaosha.img %}"/>
</a>
</dt>
<dd class="phone_title">{{ miaosha.content }}</dd>
<dd>
抢购价格:<span>{{ miaosha.price }}</span>
<strong>元</strong>
</dd>
<dd>{{ miaosha.miao }}</dd>
</dl>
{% endfor %}
</div>
<div id="shoping_right">
<img src="{% static 'img/tg0591_falsh22.jpg' %}" style="width: 235px;height: 300px;">
</div>
</div>
<!--秒杀商品结束-->
<!--促销开始-->
<div id="sale">
<div id="sale_top">
<h1>会员促销 <span>Brand Promotions</span> </h1>
</div>
<div id="sale_bottom">
<img src="{% static 'img/tg0591_falsh11.jpg' %}" style="width:280px ;height: 310px;">
<img src="{% static 'img/tg0591_falsh14.jpg' %}" style="width:280px ;height: 310px;">
<img src="{% static 'img/tg0591_falsh15.jpg' %}" style="width:280px ;height: 150px;">
<img src="{% static 'img/tg0591_falsh16.jpg' %}" style="width:280px ;height: 150px;">
<img src="{% static 'img/tg0591_falsh13.jpg' %}" style="width:280px ;height: 150px;">
<img src="{% static 'img/tg0591_falsh17.jpg' %}" style="width:280px ;height: 150px;">
</div>
</div>
<!--促销结束-->
<!--手机数码开始-->
<div id="numerical">
<div id="numerical_top">
<h1>手机数码<span>Brand Promotions</span> </h1>
<div id="numerical_top_a">
<span><a href="#">手机通讯</a></span>
<span><a href="#">手机配件</a></span>
<span><a href="#">摄影摄像</a></span>
<span><a href="#">数码配件</a></span>
<span><a href="#">时尚影音</a></span>
</div>
</div>
<div id="numerical_bottom">
<div id="bigImg">
<a style="opacity: 0;"><img src="{% static 'img/zmgd888_falsh20.jpg' %}"></a>
<a style="opacity: 0;"><img src="{% static 'img/tg0591_falsh7.jpg' %}"></a>
<a style="opacity: 1;"><img src="{% static 'img/tg0591_falsh19.jpg' %}"></a>
<a style="opacity: 0;"><img src="{% static 'img/tg0591_falsh46.jpg' %}"></a>
</div>
<div id="phone_list">
<ul>
<li>
<a><img src="{% static 'img/midP20160313145249235.jpg' %}"></a>
<p>
<a>魅族 MX4 16GB 灰色 移动4G手机</a>
</p><b>¥999元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316132640993.jpg' %}"></a>
<p>
<a>魅族 PR05 64GB 银白色 移动联通双4G手机 双卡双待</a>
</p><b>¥3099元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316133300714.jpg' %}"></a>
<p>
<a>Huawei/华为 Mate8全网通</a>
</p><b>¥3699元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316133759283.jpg' %}"></a>
<p>
<a>Huawei/华为 荣耀畅玩5X</a>
</p><b>¥1599元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316134241222.jpg' %}"></a>
<p>
<a>分期免息送16G卡皮套钢化膜Huawei/华为 荣耀7全网通4G</a>
</p><b>¥2469元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316135002531.jpg' %}"></a>
<p>
<a>Huawei/华为 P8青春版 电信移动 联通 双4G智能手机双</a>
</p><b>¥1388元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316135451288.jpg' %}"></a>
<p>
<a>Huawei/华为 P8标准版双4G手机</a>
</p><b>¥2288元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316135827379.jpg' %}"></a>
<p>
<a>送32G/电源耳机皮套 Huaw<br>ei/华为 荣耀畅玩4C手机</a>
</p><b>¥799元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20160316135827379.jpg' %}"></a>
<p>
<a>Huawei/华为 荣耀6 移动联<br>通 4G智能手机</a>
</p><b>¥1599元</b></li>
</ul>
<ul>
<li>
<a><img src="{% static 'img/midP20130125170822435.jpg' %}"></a>
<p>
<a>索尼(SONY) NEX-F3K 微单<br>单镜套机 粉色(E18-55mm F)</a>
</p><b>¥3370元</b></li>
</ul>
</div>
</div>
</div>
<!--手机数码结束-->
<!--图开始-->
<div id="BigImg"></div>
<!--图结束-->
<!--厨房、办公开始-->
<div id="work">
<div id="work_left">
<div id="left_t">
<h1>厨具用品<span>Brand Promotions</span> </h1>
<div id="left_t_a">
<span><a href="#">烹饪锅具</a></span>
<span><a href="#">刀剪砧板</a></span>
<span><a href="#">收纳保鲜</a></span>
<span><a href="#">水酒刀具</a></span>
</div>
</div>
<div id="left_b">
<a href="#"><img src="{% static 'img/tg0591_falsh26.jpg' %}"></a>
<a href="#"><img src="{% static 'img/tg0591_falsh27.jpg' %}"></a>
<a href="#"><img src="{% static 'img/zmgd888_falsh28.jpg' %}"></a>
<a href="#"><img src="{% static 'img/zmgd888_falsh29.jpg' %}"></a>
</div>
</div>
<div id="work_right">
<div id="right_t">
<h1>电脑办公<span>Brand Promotions</span> </h1>
<div id="right_t_a">
<span><a href="#">电脑整机</a></span>
<span><a href="#">电脑配件</a></span>
<span><a href="#">外设产品</a></span>
<span><a href="#">网络产品</a></span>
</div>
</div>
<div id="right_b">
<div id="right_b_img">
<a href="#"><img src="{% static 'img/tg0591_falsh33.jpg' %}"></a>
<a href="#"><img src="{% static 'img/zmgd888_falsh30.jpg' %}"></a>
<a href="#"><img src="{% static 'img/zmgd888_falsh31.jpg' %}"></a>
<a href="#"><img src="{% static 'img/tg0591_falsh32.jpg' %}"></a>
</div>
<div id="right_b_con">
<dl>
<dt><img src="{% static 'img/midP20130604152951152.jpg' %}"></dt>
<dd>惠普(HP) Envy dv4-<br>5213x 14.0英寸笔记本</dd>
<dd><span>¥4682元</span></dd>
</dl>
<dl>
<dt><img src="{% static 'img/midP20130128160238754.jpg' %}"></dt>
<dd>清华同方(TongFang) 精锐<br>X2-B203 台式电脑(双核</dd>
<dd><span>¥2256元</span></dd>
</dl>
<dl style="border-right: none;">
<dt><img src="{% static 'img/midP20130127143251661.jpg' %}"></dt>
<dd>苹果(Apple) iPad mini<br>MD5CH/A 7.9英寸平板电脑</dd>
<dd><span>¥4969元</span></dd>
</dl>
</div>
</div>
</div>k
</div>
<!--厨房、办公结束-->
<!--服饰鞋帽开始-->
<div id="clothes">
<div id="clothes_top">
<h1>服饰鞋帽<span>Brand Promotions</span> </h1>
<div id="clothes_top_a">
<span><a href="#">男装</a></span>
<span><a href="#">女装</a></span>
<span><a href="#">运动</a></span>
<span><a href="#">内衣</a></span>
<span><a href="#">配饰</a></span>
<span><a href="#">男鞋</a></span>
<span><a href="#">女鞋</a></span>
<span><a href="#">童装</a></span>
<span><a href="#">童鞋</a></span>
<span><a href="#">裤子</a></span>
<span style="width: 70px;"><a href="#">情侣套装</a></span>
</div>
</div>
<div id="clothes_bottom">
<div id="bottom_left">
<a href="#"><img src="{% static 'img/tg0591_falsh37.jpg' %}" style="z-index: 20;"></a>
<a href="#"><img src="{% static 'img/tg0591_falsh34.jpg' %}"></a>
<a href="#"><img src="{% static 'img/tg0591_falsh35.jpg' %}"></a>
<a href="#"><img src="{% static 'img/tg0591_falsh36.jpg' %}"></a>
</div>
<div id="clothes_list">
<dl>
<dt><img src="{% static 'img/midP20130507110404305.jpg' %}"></dt>
<dd>4006#热卖人气爆款 夏季时<br>尚简约短袖t恤 男 字母印花</dd>
<dd><span>¥35元</span></dd>
</dl>
<dl>
<dt><img src="{% static 'img/midP20130427163130308.jpg' %}"></dt>
<dd>凉鞋超高细跟露趾缎面镶钻<br>金属吊饰</dd>
<dd><span>¥186元</span></dd>
</dl>
<dl>
<dt><img src="{% static 'img/midP20130815101406262.jpg' %}"></dt>
<dd>秋装新品 薄款韩版修身显瘦<br>小脚牛仔裤</dd>
<dd><span>¥72元</span></dd>
</dl>
<dl>
<dt><img src="{% static 'img/midP2013042810115373.jpg' %}"></dt>
<dd>韩版新品男款衬衫 格子拼接<br>男士衬衫 修身休闲短袖衬衫</dd>
<dd><span>¥74元</span></dd>
</dl>
<dl style="border-right: none;">
<dt><img src="{% static 'img/midP20130112110730991.jpg' %}"></dt>
<dd>秋冬新款都市休闲时尚毛毛<br>绒男式加厚夹克外套</dd>
<dd><span>¥248元</span></dd>
</dl>
<dl style="border-bottom: none;">
<dt><img src="{% static 'img/midP20130428091631683.jpg' %}"></dt>
<dd>拖鞋超高细跟露趾缎面串珠<br>蝴蝶结</dd>
<dd><span>¥140元</span></dd>
</dl>
<dl style="border-bottom: none;">
<dt><img src="{% static 'img/midP20130505103859758.jpg' %}"></dt>
<dd>潮流时尚夏款新品T恤 男士<br>撞色条纹时尚修身休闲短袖P</dd>
<dd><span>¥91元</span></dd>
</dl>
<dl style="border-bottom: none;">
<dt><img src="{% static 'img/midP20130501143639745.jpg' %}"></dt>
<dd>新款男士打底衫 休闲男式纯<br>色T恤 时尚男款圆领短袖T恤</dd>
<dd><span>¥50元</span></dd>
</dl>
<dl style="border-bottom: none;">
<dt><img src="{% static 'img/midP20130428110620823.jpg' %}"></dt>
<dd>潮流男款衬衫 男式中袖衬衫<br>七分男式衬衫 时尚修身休闲</dd>
<dd><span>¥56元</span></dd>
</dl>
<dl style="border-right: none;border-bottom: none;">
<dt><img src="{% static 'img/midP20130427172825901.jpg' %}"></dt>
<dd>拖鞋超高细跟宽口缎面豹纹<br>镶钻蝴蝶结</dd>
<dd><span>¥160元</span></dd>
</dl>
</div>
</div>
</div>
<!--服饰鞋帽结束-->
<!--时装秀图片开始-->
<div id="showImg"></div>
<!--时装秀图片结束-->
<!--热门商品开始-->
<div id="host">
<h2>热门商品分类</h2>
<ul id="host_list">
<li>
<h3><a href="#">珠宝首饰</a></h3>
<p>
<a href="#">时尚饰品</a>
<a href="#">纯金K金</a>
<a href="#">金银投资</a>
</p>
</li>
<li>
<h3><a href="#">烹饪锅具</a></h3>
<p>
<a href="#">炒锅</a>
<a href="#">煎锅</a>
<a href="#">压力锅</a>
</p>
</li>
<li>
<h3><a href="#">电脑整机</a></h3>
<p>
<a href="#">笔记本</a>
<a href="#">超极本</a>
<a href="#">上网本</a>
</p>
</li>
<li>
<h3><a href="#">男装</a></h3>
<p>
<a href="#">衬衫</a>
<a href="#">T恤</a>
<a href="#">针织衫</a>
</p>
</li>
<li>
<h3><a href="#">女装</a></h3>
<p>
<a href="#">衬衫</a>
<a href="#">T恤</a>
<a href="#">针织衫/羊毛衫</a>
</p>
</li>
<li>
<h3><a href="#">配饰</a></h3>
<p>
<a href="#">眼镜</a>
<a href="#">腰带</a>
<a href="#">帽子</a>
</p>
</li>
<li>
<h3><a href="#">面部护理</a></h3>
<p>
<a href="#">洁面乳</a>
<a href="#">爽肤水</a>
<a href="#">精华露</a>
</p>
</li>
<li>
<h3><a href="#">魅力彩妆</a></h3>
<p>
<a href="#">粉底/遮瑕</a>
<a href="#">腮红</a>
<a href="#">眼影/眼线</a>
</p>
</li>
<li>
<h3><a href="#">香水SPA</a></h3>
<p>
<a href="#">女士香水</a>
<a href="#">男士香水</a>
<a href="#">组合套装</a>
</p>
</li>
<li>
<h3><a href="#">潮流女包</a></h3>
<p>
<a href="#">钱包/卡包</a>
<a href="#">手拿包</a>
<a href="#">单肩包</a>
</p>
</li>
<li>
<h3><a href="#">乐器相关</a></h3>
<p>
<a href="#">钢琴</a>
<a href="#">电子琴</a>
<a href="#">手风琴</a>
</p>
</li>
</ul>
</div>
<!--热门商品开始-->
<!--footerbg开始-->
<div id="footerbg">
<div id="friendlik">
<strong>友情链接:</strong>
<a href="#">天狗网商城</a>
<a href="#">介休市弘盛昌家具建材装饰城</a>
<a href="#">介休鸿宪居装饰公司</a>
<a href="#">介休家具建材网</a>
<a href="#">天狗网络科技有限公司</a>
<a href="#">天狗网络科技自助建站系统</a>
<a href="#">天狗网上商城</a>
<a href="#">涛涛三味火锅餐饮有限公司</a>
</div>
<div id="con">
<div id="con_left">
<ul>
<li>
<img src="{% static 'img/tel.jpg' %}"> "客服服务热线"
<div id="pong">
03547357121 13383445351
<br>
<a href="#"><img src="{% static 'img/T1FXHXXahjXXXAK3zo-77-18.gif' %}"></a>
</div>
<span>(7*24小时服务)</span>
</li>
<li>
<a href="#"><img src="{% static 'img/button_111.gif' %}"></a>
</li>
</ul>
</div>
<div id="con_right">
<span id="boottom_help">
<ul>
<li>
<img src="{% static 'img/gu0.jpg' %}">
<h3>关于我们</h3>
</li>
<li class="mar">
<a href="#">货源提供</a>
</li>
<li class="mar">
<a href="#">联系客服</a>
</li>
<li class="mar">
<a href="#">商城简介</a>
</li>
</ul>
<ul>
<li>
<img src="{% static 'img/gu1.jpg' %}">
<h3>售后服务</h3>
</li>
<li class="mar">
<a href="#">产品退换</a>
</li>
<li class="mar">
<a href="#">订单查询</a>
</li>
<li class="mar">
<a href="#">收货说明</a>
</li>
<li class="mar">
<a href="#">在线旺旺客服</a>
</li>
</ul>
<ul>
<li>
<img src="{% static 'img/gu2.jpg' %}">
<h3>支付宝</h3>
</li>
<li class="mar">
<a href="#">支付宝</a>
</li>
<li class="mar">
<a href="#">货到付款</a>
</li>
<li class="mar">
<a href="#">银行付款</a>
</li>
</ul>
<ul>
<li>
<img src="{% static 'img/gu3.jpg' %}">
<h3>购物指南</h3>
</li>
<li class="mar">
<a href="#">购物流程</a>
</li>
<li class="mar">
<a href="#">常见问题</a>
</li>
<li class="mar">
<a href="#">会员注册</a>
</li>
</ul>
<ul>
<li>
<img src="{% static 'img/gu4.jpg' %}">
<h3>配送方式</h3>
</li>
<li class="mar">
<a href="#">运费标准</a>
</li>
<li class="mar">
<a href="#">配送政策</a>
</li>
<li class="mar">
<a href="#">订单说明</a>
</li>
</ul>
</span>
<ul>
<li style="width: 140px;float: left;">
<img src="{% static 'img/wx.jpg' %}">
<h3><a href="#">手机扫二维码登录</a></h3>
</li>
<li style="float: right;">
{# <a href="#"><img src="{% static 'undefined' %}"></a>#}
</li>
</ul>
</div>
</div>
</div>
<!--footerbg结束-->
<div id="footer">
天狗网络科技有限公司版权所有<br> 站长统计
</div>
</body>
</html><file_sep>from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=40)
password = models.CharField(max_length=100)
email = models.CharField(max_length=30)
token = models.CharField(max_length=100,default='')
# 秒杀商品模板
class Miaosha(models.Model):
img = models.CharField(max_length=100)
maximg = models.CharField(max_length=100, default='')
hdimg = models.CharField(max_length=100, default='')
content = models.CharField(max_length=200)
price = models.IntegerField()
sprice = models.IntegerField(default=0)
miao = models.CharField(max_length=50)
no = models.CharField(max_length=40, null=True)
# 轮播图模板
class Wrapper(models.Model):
img = models.CharField(max_length=100)
# 购物车模板
class Cart(models.Model):
user = models.ForeignKey(User)
goods = models.ForeignKey(Miaosha)
number = models.IntegerField()
isselect = models.BooleanField(default=True)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-11-08 03:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mall', '0002_miaosha_wrapper'),
]
operations = [
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('number', models.IntegerField()),
('isselect', models.BooleanField(default=True)),
('goods', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mall.Miaosha')),
],
),
migrations.AddField(
model_name='user',
name='token',
field=models.CharField(default='', max_length=100),
),
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(max_length=100),
),
migrations.AddField(
model_name='cart',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mall.User'),
),
]
|
10c740bcad8a209d736e701905fe60a0274d755e
|
[
"JavaScript",
"Python",
"HTML"
] | 8
|
Python
|
Gavin923/dogshop
|
17c9b8b929dc88d32ce7089a4ed2cbd614249dad
|
b0e8f81d823415750365799b2a70a52766fb249f
|
refs/heads/master
|
<repo_name>phillipalee/MVCControllerDI<file_sep>/insert_into_records.sql
use [RecordDB]
insert into Records (howMany) values (5)<file_sep>/RecordRepo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MVCControllerDI
{
public class RecordRepo : IRecordRepo
{
private RecordContext _context = new RecordContext();
public IEnumerable<Record> GetRecords()
{
return _context.Records;
}
}
}
<file_sep>/Controllers/ThingsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MVCControllerDI.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MVCControllerDI.Controllers
{
public class ThingsController : Controller
{
private IRecordRepo _recordRepo;
private ILogger _logger;
public ThingsController(IRecordRepo repo, ILogger<ThingsController> logger)
{
_recordRepo = repo;
_logger = logger;
}
public IActionResult Index()
{
var records = _recordRepo.GetRecords();
var model = new ThingsModel { Things = records };
_logger.LogInformation("in index now said spiderman");
if (records.Count() > 0)
{
model.response = "Some stuff";
}
else
{
model.response = "No stuff";
}
return View("Things", model);
}
}
}<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using MVCControllerDI.Controllers;
namespace MVCControllerDI
{
public class Program
{
public static void Main(string[] args)
{
//// create the mock data source
//var mockRecRepo = new Mock<IRecordRepo>();
//// set up the behavior that you want (you could have it return a value(s)
//mockRecRepo.Setup(x => x.GetRecords())
// .Returns(Enumerable.Empty<Record>);
//// Here's a demo of passing the controller the repository in the constructor
//var controller = new ThingsController(mockRecRepo.Object);
//// put the View object in a var
//var result = controller.Index();
// break at the next satement and check out what's in result. Then just let it run
var host = CreateHostBuilder(args).Build();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.AddEventLog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
<file_sep>/IRecordRepo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MVCControllerDI
{
public interface IRecordRepo
{
public IEnumerable<Record> GetRecords();
}
}
<file_sep>/RecordContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace MVCControllerDI
{
public class RecordContext : DbContext
{
public virtual DbSet<Record> Records { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
optionsBuilder.UseSqlServer (configuration.GetConnectionString("Storage"));
optionsBuilder.EnableDetailedErrors();
}
}
}
<file_sep>/Models/ThingsModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MVCControllerDI.Models
{
public class ThingsModel
{
public IEnumerable<Record> Things { get; set; }
public string response { get; set; }
}
}
|
8569f40c4d68b3be751443ba22da12c63e64b3b9
|
[
"C#",
"SQL"
] | 7
|
SQL
|
phillipalee/MVCControllerDI
|
a6f84251213eb71f15364c17e669676ee56541fb
|
46c3ee66d36de71740086c359e4eb10e7a9254f3
|
refs/heads/master
|
<repo_name>onuryilmaz/BundleExample<file_sep>/src/main/java/me/onuryilmaz/bundle/example/BundleReaderTest.java
package me.onuryilmaz.bundle.example;
import java.util.Locale;
/**
* Main class for {@link BundleReader}
*
*/
public class BundleReaderTest {
public static void main(String[] args) {
String name = "<NAME>";
String key = "hello_world";
String bundle_name = "example";
if (args.length > 0) {
name = args[0];
}
BundleReader bundleReader = new BundleReader(bundle_name);
System.out.println(bundleReader.getString(key, name));
BundleReader bundleReaderFR = new BundleReader(bundle_name, Locale.FRENCH);
System.out.println(bundleReaderFR.getString(key, name));
BundleReader bundleReaderES = new BundleReader(bundle_name, "es");
System.out.println(bundleReaderES.getString(key, name));
BundleReader bundleReaderIT = new BundleReader(bundle_name, "it");
System.out.println(bundleReaderIT.getString(key, name));
}
}
<file_sep>/src/main/resources/example.properties
hello_world=Hello World {0}<file_sep>/src/main/resources/example_it.properties
hello_world=Ciao Mondo {0}<file_sep>/src/main/resources/example_fr.properties
hello_world=Bonjour Monde {0}<file_sep>/src/main/resources/example_es.properties
hello_world=Hola Mundo {0}
|
bde86ff5cec7de8fc72861952ab00d9b2b503434
|
[
"Java",
"INI"
] | 5
|
Java
|
onuryilmaz/BundleExample
|
148f15ca0da4755dc9f7c3cd2c859d4280f9f74d
|
ccfb7a68678005cca6f997582656a37ab1ec56c9
|
refs/heads/master
|
<file_sep><?php
/*This file should receive a link somethong like this: http://noobix.000webhostapp.com/TX.php
If you paste that link to your browser, it should update b1 value with this TX.php file. Read more details below.
The ESP will send a link like the one above but with more than just b1. It will have b1, b2, etc...
*/
require('db.php'); //We include the database_connect.php which has the data for the connection to the database
$query = 'Select * from ESP';
//Get all the values form the table on the database
$result = mysqli_query($conn,$query); //table select is ESPtable2, must be the same on yor database
//Loop through the table and filter out data for this unit id equal to the one taht we've received.
$row = mysqli_fetch_all($result,MYSQLI_ASSOC);
foreach($row as $row)
{
$b1 = $row['BUTTON1'];
$b2 = $row['BUTTON2'];
$b3 = $row['BUTTON3'];
$b4 = $row['BUTTON4'];
}
echo "_b1$b1##_b2$b2##_b3$b3##_b4$b4##";
?>
<file_sep><?php
require('db.php');
$query = 'Select * from ESP';
$result = mysqli_query($conn,$query);
$post = mysqli_fetch_all($result,MYSQLI_ASSOC);
$image_location =['icons/eye-slash.svg','icons/eye.svg'];
$Status =['OFF','ON'];
$image_location_array =[];
$Status_array=[];
$Inverted_values_array=[];
$Button_array=['BUTTON1','BUTTON2','BUTTON3','BUTTON4'];
//This will decide what will be displayed on the screen when site is fired for the first time
foreach($post as $post)
{
#For Button 1
if ($post['BUTTON1'] == 1)
{
$image_location_array[0] = $image_location[1];
$Status_array[0]=$Status[1];
}#ON
else
{
$image_location_array[0] = $image_location[0];
$Status_array[0]=$Status[0];
}
#For Button 2
if($post['BUTTON2'] == 1)
{
$image_location_array[1] = $image_location[1];
$Status_array[1]=$Status[1];
}#ON
else
{
$image_location_array[1] = $image_location[0];
$Status_array[1]=$Status[0];
}
#For Button 3
if($post['BUTTON3'] == 1)
{
$image_location_array[2] = $image_location[1];
$Status_array[2]=$Status[1];
}#ON
else
{
$image_location_array[2] = $image_location[0];
$Status_array[2]=$Status[0];
}
#For Button 4
if($post['BUTTON4'] == 1)
{
$image_location_array[3] = $image_location[1];
$Status_array[3]=$Status[1];
}#ON
else
{
$image_location_array[3] = $image_location[0];
$Status_array[3]=$Status[0];
}
}
for($i=0;$i<4;$i++)
{
if($Status_array[$i] == 'OFF')
{
$Inverted_values_array[] = 1;
}
else
{
$Inverted_values_array[] = 0;
}
}
<file_sep>This file contains the source code of the projects - "Smart Dustbin Management System" and "Smart Traffic Monitoring System" under the theme "Smart and Sustainable Development" for HACKVSIT 3.0
The tech stack involved are IoT, arduino, JavaScript, CSS, PHP and HTML.
<file_sep><?php
$conn = mysqli_connect('localhost','root','Tar<PASSWORD>','IOT');
if(mysqli_connect_errno())
{
echo 'Database Not connected' . mysqli_connect_errno();
}
?><file_sep><?php
include_once('header.php');
require('db.php');
require('logic.php');
$unit_id ='1';
//mysqli_close($conn);
echo "
<body>
<header class='showcase'>
<div class='container content '>
<div class='row'>
<div class='col'>
<img src='$image_location_array[0]' alt='' title='Bootstrap'>
<p>$Status_array[0]</p>
<td>
<form action= newupdate.php method= 'post'>
<input type='hidden' name='value' value=$Inverted_values_array[0] size='15' >
<input type='hidden' name='unit' value=$unit_id >
<input type='hidden' name='column' value=$Button_array[0] >
<input type= 'submit' name= 'change_but' value = 'Switch'>
</form>
</td>
</div>
<div class='col'>
<img src='$image_location_array[1]' alt='' title='Bootstrap'>
<p>$Status_array[1]</p>
<td>
<form action= newupdate.php method= 'post'>
<input type='hidden' name='value' value=$Inverted_values_array[1] size='15' >
<input type='hidden' name='unit' value=$unit_id >
<input type='hidden' name='column' value=$Button_array[1] >
<input type= 'submit' name= 'change_but' value = 'Switch'>
</form>
</td>
</div>
<div class='col'>
<img src='$image_location_array[2]' alt='' title='Bootstrap'>
<p>$Status_array[2]</p>
<td>
<form action= newupdate.php method= 'post'>
<input type='hidden' name='value' value=$Inverted_values_array[2] size='15' >
<input type='hidden' name='unit' value=$unit_id >
<input type='hidden' name='column' value=$Button_array[2] >
<input type= 'submit' name= 'change_but' value = 'Switch'>
</form>
</td>
</div>
<div class='col'>
<img src='$image_location_array[3]' alt='' title='Bootstrap'>
<p>$Status_array[3]</p>
<td>
<form action= newupdate.php method= 'post'>
<input type='hidden' name='value' value=$Inverted_values_array[3] size='15' >
<input type='hidden' name='unit' value=$unit_id >
<input type='hidden' name='column' value=$Button_array[3] >
<input type= 'submit' name= 'change_but' value = 'Switch'>
</form>
</td>
</div>
</div>
</div>
</header>
" ;
?>
<?php include_once('footer.php')?>
<file_sep>#include <Ultrasonic.h> // import ultrasonic library
Ultrasonic ultrasonic(10,9); // Register ultrasonic sensor with interface pins trig:2, echo:3
Ultrasonic ultrasonic2(2,3);
#define senyellow1 5
#define senyellow2 7
#define sengreen 4
#define senred 6
void setup()
{
pinMode(senyellow1,OUTPUT);
pinMode(senyellow2,OUTPUT);
pinMode(sengreen,OUTPUT);
pinMode(senred,OUTPUT);
pinMode(12,OUTPUT);
digitalWrite(12,HIGH);
Serial.begin(9600);
}
void loop() {
//Sensor 1
int check = ultrasonic.distanceRead();
Serial.println(check);
if(check <= 75)
{
//Serial.print("Dustbin is filled Less than 50%");
digitalWrite(sengreen,LOW);
digitalWrite(senyellow1,LOW);
}
else if (check >= 120)
{
digitalWrite(sengreen,HIGH);
digitalWrite(senyellow1,LOW);
}
else
{
digitalWrite(sengreen,LOW);
digitalWrite(senyellow1,HIGH);
}
//Sensor 2
int check2 = ultrasonic2.distanceRead();
Serial.println(check2);
if(check2 <= 75)
{
//Serial.print("Dustbin is filled Less than 50%");
digitalWrite(senred,LOW);
digitalWrite(senyellow2,LOW);
}
else if (check2 >= 120)
{
digitalWrite(senred,HIGH);
digitalWrite(senyellow2,LOW);
}
else
{
digitalWrite(senred,LOW);
digitalWrite(senyellow2,HIGH);
}
delay(5000); // waits half a second
}
|
70b87e6796deb8bca9a896465fc88d16f72c007e
|
[
"Markdown",
"C++",
"PHP"
] | 6
|
PHP
|
Tarster/HackVsit
|
7bca5189ea9b75fc84c0fda6feb1799fd00eb8e2
|
aea16fe5047c40ab5edae9c0fcc9339847947280
|
refs/heads/master
|
<file_sep>var CfnLambda = require('cfn-lambda');
var AWS = require('aws-sdk');
var Uploader = require('./lib/password');
function PasswordGeneratorHandler(event, context) {
var PasswordGenerator = CfnLambda({
Create: Uploader.Create,
Update: Uploader.Update,
Delete: Uploader.Delete,
SchemaPath: [__dirname, 'src', 'schema.json']
});
// Not sure if there's a better way to do this...
AWS.config.region = currentRegion(context);
return PasswordGenerator(event, context);
}
function currentRegion(context) {
return context.invokedFunctionArn.match(/^arn:aws:lambda:(\w+-\w+-\d+):/)[1];
}
exports.handler = PasswordGeneratorHandler;
<file_sep># AWS CloudFormation Custom Resource for Password Generator
This custom resource is based on [cfn-lambda](https://github.com/andrew-templeton/cfn-lambda), you can see this project for more advanced configuration.
## Install
Clone the repository on laptop. Inside the root folder:
```
$ npm install
$ npm run cfn-lambda-deploy
```
This command deploy the lambda helper on your default AWS region and `us-east-1`, `us-west-2`, `eu-west-1`, `ap-northeast-1`. To change this configuration you can follow this [link](https://github.com/andrew-templeton/cfn-lambda#deployment-of-lambdas)
## Example
You can test the custom resource by running `example/uploader.cform`. This only parameter is the name of the lambda function created during the installation.
<file_sep>var generatePassword = require("password-generator");
var UPPERCASE_RE = /([A-Z])/g;
var LOWERCASE_RE = /([a-z])/g;
var NUMBER_RE = /([\d])/g;
var SPECIAL_CHAR_RE = /([\?\-])/g;
var NON_REPEATING_CHAR_RE = /([\w\d\?\-])\1{2,}/g;
function isStrongEnough(password, options) {
var uc = password.match(UPPERCASE_RE);
var lc = password.match(LOWERCASE_RE);
var n = password.match(NUMBER_RE);
var sc = password.match(SPECIAL_CHAR_RE);
var nr = password.match(NON_REPEATING_CHAR_RE);
return !nr &&
uc && uc.length >= options.uppercaseMinCount &&
lc && lc.length >= options.lowercaseMinCount &&
n && n.length >= options.numberMinCount &&
sc && sc.length >= options.specialMinCount;
}
var defaultOptions = {
memorable: false,
length: 12,
uppercaseMinCount: 1,
lowercaseMinCount: 1,
numberMinCount: 1,
specialMinCount: 0
};
var strongOptions = {
memorable: false,
length: 32,
uppercaseMinCount: 3,
lowercaseMinCount: 3,
numberMinCount: 2,
specialMinCount: 2
}
var Create = function(params, reply) {
var options = params.Strong == 'true' ? strongOptions : defaultOptions;
if (params.Memorable) options.memorable = params.Memorable == 'true';
if (params.Length) options.length = params.Length;
if (params.UppercaseMinCount) options.uppercaseMinCount = params.UppercaseMinCount;
if (params.LowercaseMinCount) options.lowercaseMinCount = params.LowercaseMinCount;
if (params.NumberMinCount) options.numberMinCount = params.NumberMinCount;
if (params.SpecialMinCount) options.specialMinCount = params.SpecialMinCount;
var password = "";
while (!(password != "" && (isStrongEnough(password, options) || options.memorable))) {
password = generatePassword(options.length, options.memorable, /[\w\d\?\-]/);
}
return reply(null, password)
};
var Update = function(physicalId, params, oldParams, reply) {
Create(params, reply);
};
var Delete = function(physicalId, params, reply) {
reply(null, physicalId);
};
exports.Create = Create;
exports.Update = Update;
exports.Delete = Delete;
<file_sep>#!/bin/bash
node_modules/.bin/cfn-lambda zip --output deploy/archive.zip
echo "Deploy $TRAVIS_TAG version to S3"
aws s3 cp deploy/archive.zip s3://chatanoo-deployment/aws-cloudformation-password-generator/$TRAVIS_TAG.zip
echo "Upload latest"
aws s3api put-object \
--bucket chatanoo-deployment \
--key aws-cloudformation-password-generator/latest.zip \
--website-redirect-location /chatanoo-deployment/aws-cloudformation-password-generator/$TRAVIS_TAG.zip
|
be5550045654ddbe87dc9b6e4ce20926794b1d50
|
[
"JavaScript",
"Markdown",
"Shell"
] | 4
|
JavaScript
|
mazerte/aws-cloudformation-password-generator
|
f37ca1db1f78d9fecc97dc0023defe963f3a41ae
|
4cc73ff7d932133b5c994f8972586f29f541b1d1
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace capitaltoday2.Helpers
{
public class EmailTemplateHelper
{
public static string GetTemplate(string name)
{
string filepath = System.Web.HttpContext.Current.Server.MapPath("\\content\\emails\\" + name + ".htm");
string content = string.Empty;
using (var stream = new StreamReader(filepath))
{
content = stream.ReadToEnd();
}
return content;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace capitaltoday2.CloudStorage.Refinance
{
public class RefinanceClient : TableStorageClient<Refinance>
{
public RefinanceClient() : base("Refinance") { }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace capitaltoday2.CloudStorage.Acquisition
{
public class AcquisitionClient : TableStorageClient<Acquisition>
{
public AcquisitionClient() : base("Acquisition") { }
}
}<file_sep>using SendGrid;
using SendGrid.Helpers.Mail;
using System.Configuration;
using System.Threading.Tasks;
namespace capitaltoday2.Helpers
{
public class EmailHelper
{
public static async Task SendEmail(Mail pEmail)
{
await Execute(pEmail);
}
public static async Task SendEmail(string pTo, string pFrom, string pSubject, string pBody, bool pHTML)
{
Email from = new Email(pFrom);
Email to = new Email(pTo);
Content content;
if (pHTML)
{
content = new Content("text/html", pBody);
}
else
{
content = new Content("text/plain", pBody);
}
Mail mail = new Mail(from, pSubject, to, content);
await Execute(mail);
}
private static async Task Execute(Mail pEmail)
{
string apiKey = ConfigurationManager.AppSettings["SendGridApiKey"];
dynamic sg = new SendGridAPIClient(apiKey);
dynamic response = await sg.client.mail.send.post(requestBody: pEmail.Get());
}
}
}<file_sep>using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(capitaltoday2.Startup))]
namespace capitaltoday2
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Net;
using capitaltoday2.CloudStorage.Acquisition;
using capitaltoday2.CloudStorage.Refinance;
using capitaltoday2.Helpers;
namespace capitaltoday2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult submitRefinanceAccount(Refinance pRefinance)
{
try
{
RefinanceClient tableStorage = new RefinanceClient();
tableStorage.Add(pRefinance);
//send email to user
string emailTemplate = EmailTemplateHelper.GetTemplate("Refinance");
string emailBody = string.Format(emailTemplate, pRefinance.Name);
EmailHelper.SendEmail(pRefinance.Email, "<EMAIL>", "Your Refinance Request Follow up", emailBody, true);
//send email to mortgage broker
string emailTemplate2 = EmailTemplateHelper.GetTemplate("RefinanceReferral");
string emailBody2 = string.Format(emailTemplate2, pRefinance.Name, pRefinance.LastName, pRefinance.Email, pRefinance.Phone, pRefinance.MarketValue, pRefinance.LoanBalance, pRefinance.PropertyType, pRefinance.UnitNumber, pRefinance.OtherDescription, pRefinance.PropertyState);
//EmailHelper.SendEmail("<EMAIL> ", "<EMAIL>", "New refinance request", emailBody2, true);
EmailHelper.SendEmail("<EMAIL> ", "<EMAIL>", "New refinance request", emailBody2, true);
EmailHelper.SendEmail("<EMAIL>", "<EMAIL>", "New refinance request", emailBody2, true);
return Content(JsonConvert.SerializeObject(new { }), "application/json");
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, ex.Message);
}
}
[HttpPost]
public ActionResult submitAcquisitionAccount(Acquisition pAcquisition)
{
try
{
AcquisitionClient tableStorage = new AcquisitionClient();
tableStorage.Add(pAcquisition);
string emailTemplate = EmailTemplateHelper.GetTemplate("Acquisition");
string emailBody = string.Format(emailTemplate, pAcquisition.Name);
EmailHelper.SendEmail(pAcquisition.Email, "<EMAIL>", "Your Loan Request Follow up", emailBody, true);
//send email to mortgage broker
string emailTemplate2 = EmailTemplateHelper.GetTemplate("AcquisitionReferral");
string emailBody2 = string.Format(emailTemplate2, pAcquisition.Name, pAcquisition.LastName, pAcquisition.Email, pAcquisition.Phone, pAcquisition.PurchasePrice, pAcquisition.RequestedLoanAmount, pAcquisition.PropertyType, pAcquisition.UnitNumber, pAcquisition.OtherDescription, pAcquisition.PropertyState);
//EmailHelper.SendEmail("<EMAIL> ", "<EMAIL>", "New loan request", emailBody2, true);
EmailHelper.SendEmail("<EMAIL> ", "<EMAIL>", "New loan request", emailBody2, true);
EmailHelper.SendEmail("<EMAIL>", "<EMAIL>", "New loan request", emailBody2, true);
return Content(JsonConvert.SerializeObject(new { }), "application/json");
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, ex.Message);
}
}
public ActionResult Sandbox()
{
return View();
}
public ActionResult DeleteRefinanceAccounts()
{
try
{
RefinanceClient tableStorage = new RefinanceClient();
tableStorage.DeleteTable();
return Content(JsonConvert.SerializeObject(new { }), "application/json");
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, ex.Message);
}
}
public ActionResult DeleteAcquisitionAccounts()
{
try
{
AcquisitionClient tableStorage = new AcquisitionClient();
tableStorage.DeleteTable();
return Content(JsonConvert.SerializeObject(new { }), "application/json");
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, ex.Message);
}
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Dashboard()
{
ViewBag.Message = "Dashboard";
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.Storage.Table;
namespace capitaltoday2.CloudStorage.Refinance
{
public class Refinance: TableEntity
{
public Refinance()
{
PartitionKey = "Refinance";
RowKey = Guid.NewGuid().ToString();
}
public string MarketValue { get; set; }
public string LoanBalance { get; set; }
public string PropertyType { get; set; }
public string UnitNumber { get; set; }
public string OtherDescription { get; set; }
public string PropertyState { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.Storage.Table;
namespace capitaltoday2.CloudStorage.Acquisition
{
public class Acquisition : TableEntity
{
public Acquisition()
{
PartitionKey = "Acquisition";
RowKey = Guid.NewGuid().ToString();
}
public string PurchasePrice { get; set; }
public string RequestedLoanAmount { get; set; }
public string PropertyType { get; set; }
public string UnitNumber { get; set; }
public string OtherDescription { get; set; }
public string PropertyState { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}
|
ad8a5398b6ee6fbd0dd55f00acd4582779c1400b
|
[
"C#"
] | 8
|
C#
|
blueberry20/capitaltoday
|
3bba9f77a0933f0815d36dca2e7ca148652e28a2
|
d48be0e6fdef5ecc7cf13577f4b2b4192249ecc7
|
refs/heads/master
|
<repo_name>leohlgctzby/react-gzhipin-client<file_sep>/src/redux/action-types.js
export const AUTH_SUCCESS = 'auth_success' //注册或者登录成功
export const ERROR_MSG = 'error_msg' //注册或者登录错误提示信息 请求前/请求后
export const RECEIVE_USER = 'receive_user' //接收用户
export const RESET_USER = 'reset_user' //重置用户
export const RECEIVE_USER_LIST = 'receive_user_list'//接收用户列表数据
export const RECEIVE_MSG_LIST ='receive_msg_list' //接收所有相关消息列表
export const RECEIVE_MSG ='receive_msg' //接收一条消息
export const MSG_RECEIVE ='msg_receive' //已经查看过某个聊天消息<file_sep>/src/utils/index.js
// 用户主界面
// dashen:/dashen
// laoban:/laoban
// 用户信息完善界面
// dashen:/dasheninfo
// laoban:/laobaninfo
// 判断是否已经完善信息?user.header是否有值
// 判断用户类型:user.type
export function getRedirectTo(type, header) {
let path = ''
if(type==='laoban') {
path = 'laoban'
} else {
path = 'dashen'
}
if(!header) {
path += 'info'
}
return path
}
|
5e2892ba62ed4eecd4d66efee89b2db761209b61
|
[
"JavaScript"
] | 2
|
JavaScript
|
leohlgctzby/react-gzhipin-client
|
9c87b6358210591e27b20a178f1d1b409b7980a9
|
6542b4fb68d2b343b12d79fe1d6da6eeaeee501c
|
refs/heads/main
|
<repo_name>sergeantsnape/pygame-snake<file_sep>/snake.py
import random
import time
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Snake.exe")
clk = pygame.time.Clock()
def text_msg(n, s, x, y, c):
base_font = pygame.font.Font('Poppins-Bold.ttf', n)
text = base_font.render(s, True, c)
text_rect = text.get_rect()
text_rect.center = (x, y)
return text, text_rect
def splash_screen():
screen.fill((255, 255, 255))
img = pygame.image.load('833674.png')
screen.blit(img, (50, 50))
text, text_rect = text_msg(20, 'PRESS |___| TO PLAY', 250, 400, (0, 0, 0))
screen.blit(text, text_rect)
pygame.display.update()
play = True
while play:
for e in pygame.event.get():
if e.type == pygame.QUIT:
play = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_SPACE:
return game_loop()
pygame.quit()
def game_over():
text1, text_rect1 = text_msg(60, 'GAME OVER', 250, 125, (255, 0, 0))
screen.blit(text1, text_rect1)
text2, text_rect2 = text_msg(20, "PLAY AGAIN", 250, 250, (255, 0, 0))
screen.blit(text2, text_rect2)
text3, text_rect3 = text_msg(20, "(Y/N)", 250, 275, (255, 0, 0))
screen.blit(text3, text_rect3)
pygame.display.update()
again = True
while again:
for e in pygame.event.get():
if e.type == pygame.QUIT:
again = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_y:
return game_loop()
if e.key == pygame.K_n:
again = False
pygame.quit()
def game_loop():
# <<- variables ->>
run = True
x, y = 250, 250
c_w = 10
x_c = -1
y_c = -1
v = 10
s = 5
s_l = []
leng = 1
move = False
# <<- ---------- ->>
# grid of 10X10 px
f_x = round(random.randrange(0, 500 - c_w) / 10) * 10
f_y = round(random.randrange(0, 500 - c_w) / 10) * 10
# <<-Main game loop->>
while run:
# pygame.time.Clock()
# closing window (default)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP :
if leng == 1:
y_c, x_c = -v, 0
if leng != 1 and x_c !=0:
y_c, x_c = -v, 0
move = True
if event.key == pygame.K_DOWN :
if leng == 1:
y_c, x_c = v, 0
if leng != 1 and x_c != 0:
y_c, x_c = v, 0
move = True
if event.key == pygame.K_RIGHT :
if leng == 1:
x_c, y_c = v, 0
if leng != 1 and y_c != 0:
x_c, y_c = v, 0
move = True
if event.key == pygame.K_LEFT:
if leng == 1:
x_c, y_c = -v, 0
if leng != 1 and y_c != 0:
x_c, y_c = -v, 0
move = True
screen.fill((200, 200, 200))
# movement initialization
if move:
y += y_c
x += x_c
# hits block
if y >= 500 - c_w or y < 0 or x >= 500 - c_w or x < 0:
time.sleep(0.3)
game_over()
# snake body constraints
s_l.append([x, y])
if len(s_l) > leng:
s_l.pop(0)
for i in s_l[:-1]:
if i == [x, y]:
game_over()
# snake body
for mov in s_l:
pygame.draw.rect(screen, (255, 255, 255), (mov[0], mov[1], c_w, c_w))
# food
pygame.draw.rect(screen, (255, 0, 0), (f_x, f_y, c_w, c_w))
# snake eats food
if x == f_x and y == f_y:
f_x = round(random.randrange(0, 500 - 2 * c_w) / 10) * 10
f_y = round(random.randrange(0, 500 - 2 * c_w) / 10) * 10
leng += 1
s += 0.8
# score board
score = pygame.font.Font('Poppins-Thin.ttf', 20).render('SCORE ' + str(leng - 1), True, (0, 0, 0))
screen.blit(score, (0, 0))
# refreshes the screen (default)
pygame.display.update()
clk.tick(s)
pygame.quit()
def main():
splash_screen()
if __name__ == '__main__':
main()
|
381d0b985377fe07ae6ec00fb88cfd13c087a50f
|
[
"Python"
] | 1
|
Python
|
sergeantsnape/pygame-snake
|
869a12f506a1cba7fe82b7a3cb414d15b33280ef
|
3c9c0933e9e067077f520d932acea4cd7d197074
|
refs/heads/master
|
<repo_name>Inch129/AppBoosterTask<file_sep>/App.js
import {StackNavigator} from 'react-navigation';
import MasterActivity from "./MasterActivity";
import DetailsActivity from "./DetailsActivity";
const Navigation = StackNavigator({
Master: {
screen: MasterActivity,
},
Details: {
screen: DetailsActivity,
},
});
export default Navigation;<file_sep>/MasterActivity.js
import React, {Component} from 'react';
import {FlatList, View, StatusBar, ToolbarAndroid, Text} from 'react-native';
import ListItem from './ListItem';
import * as css from './Styles';
export default class MasterActivity extends Component {
constructor(props) {
super(props);
this.state = {
page: 1
};
}
//Из стилей он ругался на нулевой индекс, типо там # стояла, оставил так, ну его.
static navigationOptions = {
title: 'Список доступных заданий',
headerStyle: { backgroundColor: '#1160AA' },
headerTitleStyle: { color: '#D1F386' },
};
/**
* Оставлю даже консоль.лог,
* Сегодня я солдат удачи,
* Поломал, однако, голову как мог,
* Хотел бы сделать я иначе.
* @param item
*/
eventItem(item) {
console.log(this.props);
let {navigate} = this.props.navigation;
return navigate('Details', {
item: item,
pluralize: this._pluralize
});
}
/**
* Рендер компонентов списка, проброс пропсов
* @param item
* @returns {ListItem}
* @private
*/
_renderItem = ({item}) => {
return <ListItem pluralize={this._pluralize} eventComponentMain={this.eventItem.bind(this, item)} item={item}/>
};
/**
* Получаем данные с JSON, попытка сделать endless scroll
* Но честно говоря, заработай он с первого раза - я бы удивился.
* @returns {Promise<any>}
* @private
*/
_makeRequest = () => {
return fetch('https://gist.githubusercontent.com/KELiON/1e0a30bf603716875b5f717650113924/raw/7be9852a54ae29eda43d2691045586c0976ccdd5/offers.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.offers
}, function () {
/**
* Получаем из апи текущую строку и закидываем в стейт
* Можно было просто прибавлять + 1 к текущему, но без апи все равно не то,
* Ибо нужно знать количество страниц, не могу сказать, что будет, если выйти за их максимум.
*/
/* this.setState = {
page: responseJson.offers.meta.current_page
}*/
});
})
.catch((error) => {
console.error(error);
});
};
/**
* Для отсеивания "некрасивых" чисел, вроде [5.0, 2.0, -1.0, etc...]
* Предполагается, что цены
* @param number
* @returns {int, double}
* @private
*/
_filterFormat = (number) => {
let pattern = /\d*\.0/;
if (pattern.test(number)) {
return parseInt(number);
}
return number;
};
/**
* Склоняем
* @param number
* @returns {String}
* @private
*/
_pluralize = (number) => {
if (isNaN(number)) {
return warn("Не число");
}
let check = this._filterFormat(number);
switch (check) {
case 1:
return check + " рубль";
case 2:
case 3:
case 4:
return check + " рубля";
default:
break;
}
return check + " рублей";
};
/**
* Не будем заставлять пользователя ждать, и подгрузим порцию сразу
*/
componentDidMount() {
this._makeRequest();
}
/**
*Данная функция приблизительно отражает подгрузку данных
* @private
*/
_loadMore = () => {
this.setState = {
page: this.state.page + 1
}, () => {
this._makeRequest();
};
};
render() {
/**
* Рендерим сам список
* Закомментированные пропсы - события, когда упёрлись в пол, дёргает loadMore
*/
return (
<View >
<FlatList
data={this.state.data}
renderItem={this._renderItem}
/*onEndReached={this._loadMore}*/
/*onEndTreshold={0}*/
keyExtractor={(item, index) => index}
/>
<View style={css.masterScreen.containerTooltip}>
<Text style={css.masterScreen.tooltip}>Не забывай: количество заданий ограничено. Больше активности - больше прибыли</Text>
</View>
</View>
);
}
}
<file_sep>/android/settings.gradle
rootProject.name = 'AppBoosterProject'
include ':app'
<file_sep>/DetailsActivity.js
import React, {Component} from 'react';
import {View, Text, Image, Button, Linking} from 'react-native';
import * as css from './Styles';
export default class DetailsActivity extends Component {
static navigationOptions = {
title: 'Задания',
headerStyle: {backgroundColor: '#1160AA'},
headerTitleStyle: {color: '#D1F386'},
};
_filterFormat = (number) => {
let pattern = /\d*\.0/;
if (pattern.test(number)) {
return parseInt(number);
}
return number;
};
/**
* Я пытался передать их через пропсы в навигатор
* Создал отдельный хелпер, со статическими и не статическими методами
* Не знаю по какой причине - но эти меры не помогли избежать данного повтора кода
*
*/
_pluralize = (number) => {
if (isNaN(number)) {
return warn("Не число");
}
let check = this._filterFormat(number);
switch (check) {
case 1:
return check + " рубль";
case 2:
case 3:
case 4:
return check + " рубля";
default:
break;
}
return check + " рублей";
};
/**
*
* @returns {*}
*/
render() {
let {state} = this.props.navigation;
let reward = this._pluralize(state.params.item.reward);
return (
<View style={css.details.detailsContainer}>
<View><Text style={css.details.infoText}>Вы хотите скачать и установить приложение</Text></View>
<View style={css.details.detailsHeadContainer}>
<Image style={css.details.detailsHeadImg} source={{uri: state.params.item.icon}}/>
<View style={css.details.detailsHeadTextContainer}>
<Text style={css.details.detailsHeadTitleText}>{state.params.item.title}</Text>
<Text style={css.details.detailsHeadBonus}>Бонусом Вам будет зачислено - <Text style={{color:"#F54D42"}}>{reward}</Text></Text>
</View>
</View>
<View><Text style={css.details.paragraphsTitle}>Для этого нужно выполнить несколько простых шагов:</Text></View>
<View><Text style={css.details.regularParagraph}>1)Необходимо перейти по ссылке. По ней Вы попадётё в PlayMarket.</Text></View>
<View><Text style={css.details.regularParagraph}>2)Прокрутить вниз и найти приложение с данной иконкой и названием.</Text></View>
<View><Text style={css.details.regularParagraph}>3)Скачать, запустить и <Text style={{color: "red"}}>обязательно</Text> перейти в приложение AppBonus.</Text></View>
<View><Text style={css.details.lastParagraph}>4)Примите Ваш честно заработанный бонус. Сделать эти шаги куда проще, даже чем читать, не так ли?</Text></View>
<Button
onPress={() => Linking.openURL(state.params.item.download_link)}
title={"Скачать для получения бонуса"}
/>
<View><Text style={css.details.editWarnings}>- Скачать и запустить, не стоит делать лишних движений</Text></View>
<View><Text style={css.details.editWarnings}>- Если сеть капризничает, возможно приложение присоединится к веселью. Убедитесь в твердости намерений WiFi\3G помочь Вам в заработке</Text></View>
<View><Text style={css.details.editWarnings}>- Мы с удовольствием зачислим Вам бонус в диапазоне от 5 минут до нескольких часов</Text></View>
</View>
)
}
}
<file_sep>/README.md
# AppBoosterTask
По поводу доп. заданий: реализовал endless scroll, но возможности проверить нет.
Относительно второй задачи - Google Store открывается уже в WebView, не уверен, то ли это поведение, которое ожидалось, но чисто технически, когда человек установит приложение, то зайдя повторно на активити с деталями и перейдя в очередной раз в Google Store - у него кнопка изменится на "открыть", не знаю, считается ли это.
Насчет АПИ - всё хорошо, мне оно понравилось, единственное что я бы изменил, это иконки. Точнее информация о них. К примеру я пытался использовать PixelRatio, но например, белый фон иконки ютуба меня смущал, и постоянно казалось, что я ставлю слишком большие иконки по размеру. Насколько я помню, андроид самостоятельно растягивает картинки в случае, если они должны занимать больше своего фактического размера, в самом андроиде размер элемента можно было всегда "узнать" установив в него wrap_content, не помню как это работало в отношении картинок\иконок, но здесь трудновато представить реальный размер - и это плачевно для андроида, поскольку адекватная работа с картинками происходит в основном через Bitmap, иначе он просто разрывает\размывает растровые изображения, при таком обилии DPI и разрешений экранов оно и не мудрено.
Вкратце:
1)Добавить исходный размер иконки NxN pix (к названию).
2)Лучше, добавить несколько вариантов для больших и маленьких экранов.
3)В идеале - разбить на растровые и векторные. Не знаю как в РН с векторными дела обстоят только.
За время написания тестового у меня возникало много спорных и не до конца понятных вещей, которые все описывать здесь смысла не имеет. Если возникнут интересующие вопросы - меня всегда можно найти в телеграмм.
<file_sep>/Helper.js
export default class Helper {
/**
* Склоняем
* @param number
* @returns {String}
*
*/
pluralize = (number) => {
if (isNaN(number)) {
return warn("Не число");
}
let check = this._filterFormat(number);
switch (check) {
case 1:
return check + " рубль";
case 2:
case 3:
case 4:
return check + " рубля";
default:
break;
}
return check + " рублей";
};
/**
* Для отсеивания "некрасивых" чисел, вроде [5.0, 2.0, -1.0, etc...]
* Предполагается, что цены
* @param number
* @returns {int, double}
* @private
*/
_filterFormat = (number) => {
let pattern = /\d*\.0/;
if (pattern.test(number)) {
return parseInt(number);
}
return number;
};
}<file_sep>/Styles.js
import React from "react";
import {StyleSheet} from "react-native";
export const colors = {
"card_background": "#DDDDDD",
"row_background": "#E3F3F7",
"card_text_color": "#1989AC",
"tooltip_color": "#F6F6F6",
"tooltip_container": "#598798",
"warningText": "#F96D00"
};
/**
* Стили основного экрана
*/
export const masterScreen = StyleSheet.create({
containerTooltip: {
backgroundColor: colors.tooltip_container
},
tooltip: {
color: colors.tooltip_color,
fontSize: 18,
textAlign: "center",
margin: 15
}
});
/**
* Стили окна с подробной информацией
*/
export const details = StyleSheet.create({
container: {
backgroundColor: colors.card_text_color
},
infoText: {
fontSize: 18,
marginBottom: 10,
color: "#008080"
},
detailsContainer: {
margin: 15
},
detailsHeadContainer: {
flexDirection: "row",
alignItems: "center"
},
detailsHeadImg: {
width: 100,
height: 100
},
detailsHeadTextContainer: {
flexDirection: "column",
alignItems: "stretch"
},
detailsHeadTitleText: {
margin: 10,
marginTop: 30,
fontSize: 17
},
detailsHeadBonus: {
margin: 10,
marginBottom: 30,
fontSize: 17
},
paragraphsTitle: {
fontSize: 19
},
regularParagraph: {
fontSize: 16,
marginTop: 10
},
lastParagraph: {
fontSize: 16,
marginTop: 10,
marginBottom: 20
},
editWarnings: {
fontSize: 16,
margin: 5,
marginTop: 15,
color: colors.warningText
}
});
/**
* Стили конкретного элемента
*/
export const listItem = StyleSheet.create({
row: {
flexDirection: "row", //основная
flex: 1,
backgroundColor: colors.row_background
},
card: {
elevation: 2,
borderRadius: 2,
backgroundColor: colors.card_background,
flex: 1,
flexDirection: 'row', // основная
justifyContent: 'flex-start', // основная
alignItems: 'center', // второстепенная
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 18,
paddingRight: 16,
marginLeft: 14,
marginRight: 14,
marginTop: 0,
marginBottom: 4,
},
img: {
width: 70,
height: 70,
margin: 5
},
cardTextContainer: {
flex: 1,
margin: 10,
alignItems: "center", //второстепенная
flexDirection: "column" //основная
},
cardText: {
fontSize: 16,
color: colors.card_text_color,
marginTop: 10
}
});
|
091e793e380532c38c8bfd5a8d95c4f5c0bef1b5
|
[
"JavaScript",
"Markdown",
"Gradle"
] | 7
|
JavaScript
|
Inch129/AppBoosterTask
|
f63c65ad46d6f808c12acde3b563b64c067a347c
|
ac7a6f1c0fb63bc93472e39a9d7542bce6998784
|
refs/heads/master
|
<file_sep>FROM centos:centos8
# Install the needed bits for centos
RUN set -ex; \
yum -y update; \
yum -y install openssl-devel postgresql-devel gcc gcc-c++ make git
# Build jsonP and install as a shared lib
ENV jsonp_src src/jsonP
ENV jsonp_dst /opt/jsonP
ENV bld /opt/build
RUN set -ex; \
mkdir -p {bld}; \
mkdir -p ${jsonp_dst}/include
COPY ${jsonp_src}/jsonP-libs.conf /etc/ld.so.conf.d/
COPY ${jsonp_src}/Makefile ${bld}/
#RUN g++ -O3 -fPIC -I ${jsonp_dst}/include ${jsonp_bld}/src/*.cpp -shared -o ${jsonp_dst}/libjsonP.so.1.0 -Wl,-soname,libjsonP.so.1
RUN set -ex; \
cd ${bld}; \
git clone https://github.com/ErikDeveloperNot/jsonP_dyn.git; \
cp ${bld}/jsonP_dyn/*.h ${jsonp_dst}/include; \
mv Makefile ${bld}/jsonP_dyn; \
cd ${bld}/jsonP_dyn; \
make; \
ldconfig; \
ln /opt/jsonP/libjsonP.so.1 /opt/jsonP/libjsonP.so; \
ldconfig
# Build hiredis (c-client)
ENV redis_src /opt/hiredis
RUN set -ex; \
mkdir -p ${redis_src}; \
cd /opt; \
git clone https://github.com/redis/hiredis.git; \
cd hiredis; \
make dynamic; \
make install; \
echo "/usr/local/lib" > /etc/ld.so.conf.d/hiredis.conf; \
ldconfig
# Build sync_server
ENV sync_src src/sync/src
ENV sync_cfg src/sync/config
ENV sync_dst /opt/sync_server
COPY ${sync_cfg}/Makefile ${bld}/
RUN set -ex; \
mkdir -p ${sync_dst}; \
cd ${bld}; \
git clone https://github.com/ErikDeveloperNot/sync_server.git; \
mv Makefile sync_server; \
cd sync_server; \
make; \
yum -y erase gcc gcc-c++ make git
COPY ${sync_cfg}/* ${sync_dst}/
#RUN g++ -O2 -I ${jsonp_dst}/include -I /usr/include/openssl -pthread -o ${sync_dst}/sync_server ${sync_bld}/*.cpp -lpq -L${jsonp_dst} -ljsonP -lssl -lcrypto -Wl,-rpath,${jsonp_dst}
EXPOSE 8443
CMD /opt/sync_server/startup.sh
<file_sep>INCLUDES=-I /opt/jsonP/include -I /usr/include/openssl -I /opt/hiredis
CXX=g++
# Max performance, 03 runs into issues
CXXFLAGS=-g -O2 -fgcse-after-reload -fipa-cp-clone -floop-interchange -floop-unroll-and-jam -fpeel-loops -fpredictive-commoning -fsplit-paths -ftree-loop-distribute-patterns -ftree-loop-distribution -ftree-loop-vectorize -ftree-partial-pre -pthread
# Debug build
#CXXFLAGS=-g -pthread
# Default build
#CXXFLAGS=-pthread
LIBS=-lpq -L/opt/jsonP -ljsonP -lssl -lcrypto -lhiredis
LDFLAGS=-Wl,-rpath,/opt/jsonP
FINAL_DIR=/opt/sync_server
OBJ=Config.o register_server_exception.o config_http.o server.o data_store_connection.o main.o sync_handler.o RedisStore.o
#OBJ = ./src/file_chunk_impl.cpp ./src/jsonP_json.cpp ./src/jsonP_push_parser.cpp ./src/jsonP_buffer_parser.cpp ./src/jsonP_parser.cpp
sync_server: ${OBJ}
${CXX} ${CXXFLAGS} ${INCLUDES} -o ${FINAL_DIR}/$@ $^ ${LIBS} ${LDFLAGS}
${OBJ}:
${CXX} ${CXXFLAGS} ${INCLUDES} -c ./*.cpp
clean:
-rm -f *.o core *.core
exit
all: sync_server clean
<file_sep>#!/bin/bash
export LD_LIBRARY_PATH=/opt/openssl-1.1.1c/lib
home=/opt/sync_server
cd $home
one=1
for x in 9 8 7 6 5 4 3 2 1
do
if [ -f server.log.${x} ]
then
ext=$((x + one))
mv server.log.${x} server.log.${ext}
fi
done
if [ -f server.log ]
then
mv server.log server.log.1
fi
edit_hosts=`grep passvault /etc/hosts`
if [ "$edit_hosts" == "" ]
then
server=`ip -4 addr show dev eth0 | grep inet | awk '{print$2}' | awk -F"/" '{print$1}'`; line=`grep ${server} /etc/hosts`; sed "s/${line}/${line} passvault.erikdevelopernot.net/" /etc/hosts > hosts.temp; cat hosts.temp > /etc/hosts
rm hosts.temp
fi
echo "" >> server.log
echo "" >> server.log
echo "Starting Sync Server" >> server.log
echo `date` >> server.log
echo "Starting Sync Server"
echo `date`
#nohup ./sync_server server.config > server.log 2>&1 &
./sync_server server.config > server.log 2>&1
<file_sep>#!/bin/bash
#chown postgres:postgres /pg_hba.conf
#chown postgres:postgres /postgresql.conf
#chmod 644 /pg_hba.conf
#chmod 644 /postgresql.conf
cp -rf /pg_hba.conf /var/lib/postgresql/data
cp -rf /postgresql.conf /var/lib/postgresql/data
<file_sep>INCLUDES=-I "/opt/jsonP/include"
CXX=g++
CXXFLAGS=-O3 -std=c++11 -fPIC
LDFLAGS=-Wl,-soname,libjsonP.so.1
FINAL_DIR=/opt/jsonP
OBJ=file_chunk_impl.o jsonP_json.o jsonP_push_parser.o jsonP_buffer_parser.o jsonP_parser.o
#OBJ = ./src/file_chunk_impl.cpp ./src/jsonP_json.cpp ./src/jsonP_push_parser.cpp ./src/jsonP_buffer_parser.cpp ./src/jsonP_parser.cpp
libjsonP.so.1.0: ${OBJ}
${CXX} ${CXXFLAGS} ${INCLUDES} -shared -o ${FINAL_DIR}/$@ $^ ${LDFLAGS}
${OBJ}:
${CXX} ${CXXFLAGS} ${INCLUDES} -c *.cpp
clean:
-rm -f *.o core *.core
exit
all: libjsonP.so.1.0 clean
<file_sep>#!/bin/bash
kill `ps -ef | grep "\.\/sync_server server.config" | awk '{print $2}'`
|
b750435a431fae24280c46a44dfd25dee68086a5
|
[
"Makefile",
"Dockerfile",
"Shell"
] | 6
|
Dockerfile
|
ErikDeveloperNot/sync_server_docker
|
b394d937db4d579b9976ea3c38001f4fb80aada0
|
a440acd2bafbaad55a66cdf5c5dc6736d3026ad4
|
refs/heads/main
|
<repo_name>JHardisty333/fluffly-waddle<file_sep>/README.md
# NoSQL: Social Network API
## Week 18 Challenge
## Scope
An API for a social network web application where users can share their thoughts, react to friends’ thoughts, and create a friend list.
## Demostration
The following animations demonstrate the application functionality:
`get-routes-all-users`

`get-routes`

`post-delete-routes`

`post-put-delete-routes`

## Built With
*HTML *JS
## Contribution
Made by <NAME>. 🖤
<file_sep>/routes/api/userRoutes.js
const router = require("express").Router();
const {getUsers, createUser, getUserById, addFriend, deleteFriend} = require('../../controller/userController');
router.route('/').get(getUsers).post(createUser);
router.route('/:id').get(getUserById).put().delete();
router.route('/:userId/friends/:friendId').post(addFriend).delete(deleteFriend);
module.exports = router;<file_sep>/controller/thoughtController.js
const {Thought} = require('../models');
const thoughtController = {
getThoughts(req,res) {
Thought.find()
.then(allUsers => res.json(allUsers))
.catch(err => res.status(500).json(err));
},
getThoughtsById(req,res) {
Thought.find(req.params.id)
.populate('reactions')
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
createThought(req,res) {
Thought.create(req.body)
.then(createdThought => res.json(createdThought))
.catch(err => res.status(500).json(err));
},
updateThoughtById(req,res) {
Thought.findByIdAndUpdate(req.params.id, {$set:req.body})
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
deleteThought(req,res) {
Thought.findByIdAndDelete(req.params.id)
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
addReaction(req,res) {
Thought.findByIdAndUpdate(req.params.id {$push: {reactions: params.friendId}})
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
deleteReaction(req,res) {
Thought.findByIdAndDelete(req.params.id {$pull: {reactions: {reactionId: params.friendId}}})
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
}
}
module.exports = thoughtController;<file_sep>/controller/userController.js
const {User} = require('../models');
const userController = {
getUsers(req,res) {
User.find()
.then(allUsers => res.json(allUsers))
.catch(err => res.status(500).json(err));
},
createUser(req,res) {
User.create(req.body)
.then(createdUser => res.json(createdUser))
.catch(err => res.status(500).json(err));
},
getUserById(req,res) {
User.findById(req.params.id)
.populate('thoughts')
.populate('friends')
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
deleteUser(req,res) {
User.findByIdAndDelete(req.params.id)
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
updateById(req,res) {
User.findByIdAndUpdate(req.params.id, {$set:req.body})
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
addFriend(req,res) {
User.findByIdAndUpdate(req.params.id, {$push: { friends: params.friendId}})
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
deleteFriend(req,res) {
User.findByIdAndDelete(req.params.id)
.then(user => res.json(user))
.catch(err => res.status(500).json(err));
},
}
module.exports = userController;
|
0f2f46a8b329d3221fc213d41737f342b581387c
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
JHardisty333/fluffly-waddle
|
d02065e9c8129c9fe3eec6ba94885df44534a665
|
f186475d0379e597422c5f0ec1b86078eecff9b3
|
refs/heads/master
|
<file_sep>from __future__ import unicode_literals
from django.apps import AppConfig
from django.shortcuts import render
from service.views import swarm_client
class MonitorConfig(AppConfig):
name = 'monitor'
<file_sep>[flake8]
exclude = */migrations/*,mathilde/settings_docker.py
max-line-length = 160
ignore =
<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
import logging
import requests
import time
from django.shortcuts import render_to_response, HttpResponse
from models import Job, Result
from celery import task
from .serializers import PeriodictaskSerializer
import json
from django.utils import timezone
from rest_framework import viewsets
from service.models import Agent
from djcelery.models import PeriodicTask
from djcelery import models as celery_models
from rest_framework import permissions
from rest_framework.parsers import JSONParser, FormParser
from service.serializers import ImageSerializer
logger = logging.getLogger(__name__)
class JobViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
# authentication_classes = (SessionAuthentication, BasicAuthentication)
parser_classes = (JSONParser, FormParser)
def get_queryset(self):
user = self.request.user
return user.id
def get_serializer_class(self):
if self.request.user.is_staff:
return ImageSerializer
return ImageSerializer
def operate_fail(self, data):
return Response(data, status=status.HTTP_400_BAD_REQUEST)
def operate_success(self):
return Response("success", status=status.HTTP_200_OK)
def job_manage(self,request):
if request.method == 'POST':
# print request
delete_job(request)
scripts = Job.objects.all()
return render(request,
'job_manage.html', {
'username': request.user.username, 'show_list': scripts})
def job_run(self,request, **kwargs):
data=request.data
if request.method == 'POST':
script_name = data.get('job_name')
if not script_name:
return self.operate_fail('no script name')
script_obj = Job.objects.filter(job_name=script_name)[0]
agent_hosts_lis = request.POST.lists()
for agent_host_set in agent_hosts_lis:
agent = agent_host_set[0]
print agent
try:
ip_addr = Agent.objects.get(host_name=agent).host_ip
except:
return self.operate_fail('no agent ip in db')
script = script_obj.info
headers = {'Accept': 'application/json'}
# r = requests.post('http://127.0.0.1:8000', data=script, headers=headers)
try:
add_celery_job.delay(script, script_name, ip_addr)
except Exception as ex:
logger.error(ex)
return self.operate_fail('异步组件错误:{}'.format(ex))
# r = requests.post('http://10.6.168.161:8000', data=script, headers=headers)
scripts = Job.objects.all()
return render(request,
'job_manage.html', {
'username': request.user.username, 'show_list': scripts})
else:
print data
scripts = Job.objects.all()
agents = Agent.objects.all()
print data.get('job_name')
if not request.GET.get('job_name'):
return render(request,
'job_run.html', {
'username':
request.user.username, 'scripts': scripts,
'agents': agents})
else:
job_name = request.GET.get('job_name')
return render(request,
'job_run.html', {
'username':
request.user.username, 'scripts': scripts,
'agents': agents, 'choiced_script': job_name})
def deal_periodictask(self,request):
"""
deal action of container,include delete,stop,start
:param request:
:return: HTML
"""
data = request.data
task_names = data.getlist('task_names')
if data.get('action') == 'delete':
logger.debug('Start delete containers :{}'.format(task_names))
for task in task_names:
logger.debug('Start delete container :{}'.format(task))
try:
task_obj = PeriodicTask.objects.get(name=task)
task_obj.delete()
except Exception as ex:
return self.operate_fail('Task dose not exit. {}'.format(ex))
elif data.get('action') == 'stop':
logger.debug('Start stop containers :{}'.format(task_names))
for task in task_names:
logger.debug('Start stop container :{}'.format(task))
try:
task_obj = PeriodicTask.objects.get(name=task)
task_obj.enabled=0
task_obj.save()
except Exception as ex:
return self.operate_fail('Task dose not exit. {}'.format(ex))
elif data.get('action') == 'start':
logger.debug('Start start task :{}'.format(task_names))
for task in task_names:
logger.debug('Start start task :{}'.format(task))
try:
task_obj = PeriodicTask.objects.get(name=task)
task_obj.enabled = 1
task_obj.save()
except Exception as ex:
return self.operate_fail('Task dose not exit. {}'.format(ex))
tasks = celery_models.PeriodicTask.objects.all()
return render(request,
'job_periodictask.html', {'task_list': tasks, 'username': request.user.username})
def job_result(self,request):
if request.method == 'POST':
# delete_services(request)
pass
logger.info('Getting job was called')
tasks = celery_models.TaskMeta.objects.all()
for task in tasks:
id = task.task_id
if Result.objects.filter(task_id=id):
continue
try:
result_info = requests.get('http://localhost:5555/api/task/info/{}'.format(id))
except Exception as ex:
logger.error(ex)
return self.operate_fail('wrong:{}'.format(ex))
if not result_info:
continue
data = result_info.text
result_obj = Result()
data = json.loads(data)
result_obj.result = data.get('result')
result_obj.task_id = id
result_obj.status = data.get('state')
# result_obj.date_done = data.get('date_done')
result_obj.args = data.get('args')
result_obj.kwargs = data.get('kwargs')
result_obj.started = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data.get('started')))
result_obj.received = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data.get('received')))
result_obj.name = data.get('name')
result_obj.save()
jobs = Result.objects.all().order_by('-started')
return render(request,
'job_result.html', {
'username': request.user.username, 'show_list': jobs})
def job_periodictask(self,request):
if request.method == 'POST':
pass
else:
# task_list={}
tasks = celery_models.PeriodicTask.objects.all()
return render(request,
'job_periodictask.html', {'task_list': tasks, 'username': request.user.username})
def job_upload(request):
print request
if request.method == 'POST':
myFile = request.FILES.get('script', None)
name = request.POST.get('name')
describe = request.POST.get('describe')
if name:
save_name = name
else:
save_name = myFile
# print(myFile._size) # 文件大小字节数
if Job.objects.filter(job_name=myFile).exists():
return render('400.html', {'info': '脚本已经存在'})
data = myFile.read()
job_obj = Job()
job_obj.job_name = save_name
job_obj.info = data
job_obj.describe = describe
job_obj.save()
return render(request,
'job_upload.html', {
'username': request.user.username})
else:
return render(request,
'job_upload.html', {
'username': request.user.username})
def delete_job(request):
post_jobs = request.POST.getlist('post_jobs')
for job_name in post_jobs:
logger.debug('Start delete script :{}'.format(job_name))
try:
job_obj = Job.objects.get(job_name=job_name)
job_obj.delete()
except Exception as ex:
# return Response(
# 'Service dose not exit. {}'.format(ex),
# status=status.HTTP_400_BAD_REQUEST)
return render_to_response('400.html')
def job_result(request):
if request.method == 'POST':
# delete_services(request)
pass
logger.info('Getting job was called')
# sql='select * from '
tasks = celery_models.TaskMeta.objects.all()
for task in tasks:
id = task.task_id
if Result.objects.filter(task_id=id):
continue
try:
result_info = requests.get('http://localhost:5555/api/task/info/{}'.format(id))
except Exception as ex:
logger.error(ex)
return render_to_response('400.html')
data = result_info.text
if not data:
continue
result_obj = Result()
data = json.loads(data)
result_obj.result = data.get('result')
result_obj.task_id = id
result_obj.status = data.get('state')
# result_obj.date_done = data.get('date_done')
result_obj.args = data.get('args')
result_obj.kwargs = data.get('kwargs')
result_obj.started = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data.get('started')))
result_obj.received = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data.get('received')))
result_obj.name = data.get('name')
result_obj.save()
jobs = Result.objects.all()
return render(request,
'job_result.html', {
'username': request.user.username, 'show_list': jobs})
# return HttpResponseRedirect("http://10.6.168.161:5555/tasks")
def job_periodictask(request):
if request.method == 'POST':
pass
else:
# task_list={}
tasks = celery_models.PeriodicTask.objects.all()
return render_to_response('job_periodictask.html', {'task_list': tasks, 'username': request.user.username})
@task()
def add_celery_job(script, script_name, ip_addr):
headers = {'Accept': 'application/json'}
r = requests.post('http://{0}:8000/job/{1}'.format(ip_addr, script_name), data=script, headers=headers)
print 'success'
print r
@task()
def call_agent_change_ip(agent_ip, instance_name, assignment_ip, subnet_mask, gateway_ip):
headers = {'Accept': 'application/json'}
# time.sleep(5)
script = {"instance_name": instance_name,
"assignment_ip": assignment_ip,
"subnet_mask": subnet_mask,
"gateway_ip": gateway_ip}
# data= json.dump(script)
data = json.JSONEncoder().encode(script)
r = requests.post('http://{0}:8000/assignment_ip'.format(agent_ip), data=data, headers=headers)
print r
def call_agent_cp_configuration(agent_host_ip, instance_name, configuration_name, data, dir):
headers = {'Accept': 'application/json'}
script = {"instance_name": instance_name,
"configuration_name": configuration_name,
"data": data,
"dir": dir}
# data= json.dump(script)
script = json.JSONEncoder().encode(script)
r = requests.post('http://{0}:8000/docker_cp'.format(agent_host_ip), data=script, headers=headers)
print r.text
class PeriodictaskViewSet(viewsets.ModelViewSet):
model = celery_models.PeriodicTask
ENABLED_POST_VALUE = 'true'
DISABLED_POST_VALUE = 'false'
TASK_NAME = None
def operate_fail(self, data):
return Response(data, status=status.HTTP_400_BAD_REQUEST)
def operate_success(self):
return HttpResponse("success", status=status.HTTP_200_OK)
def disable_task(self, name):
pass
def judge_exist(self, data):
if not data:
return None
return data
def adapt_contab_type(self, data):
if not data:
return '*'
return data
def create_periodictask_db(self):
if self.interval:
PeriodicTask.objects.create(
name=self.name, task=self.task, interval=self.interval,
args=self.args, description=self.description)
return self.operate_success()
elif self.crontab:
PeriodicTask.objects.create(
name=self.name, task=self.task, crontab=self.crontab,
args=self.args, description=self.description)
return self.operate_success()
def create_periodictask(self, request, *args, **kwargs):
data = request.data
enabled = data.get('enabled', 'false')
if enabled not in [self.ENABLED_POST_VALUE, self.DISABLED_POST_VALUE]:
return self.operate_fail('无效参数')
# if enabled == self.DISABLED_POST_VALUE:
# self.disable_task(self.TASK_NAME)
# return self.operate_success()
else:
# try:
interval = data.get('interval')
if interval:
every = interval.get('every')
if every:
every = int(every)
period = self.judge_exist(interval.get('period'))
if every and period:
interval_obj, created = celery_models.IntervalSchedule.objects.get_or_create(every=every,
period=period)
self.interval = interval_obj
crontab = data.get('crontab')
if crontab:
minute = self.adapt_contab_type(crontab.get('minute'))
hour = self.adapt_contab_type(crontab.get('hour'))
day_of_week = self.adapt_contab_type(crontab.get('day_of_week'))
day_of_month = self.adapt_contab_type(crontab.get('day_of_month'))
# if day_of_month > 28 or day_of_month < 1:
# return self.operate_fail('日期必须在1-28日之间')
month_of_year = self.adapt_contab_type(crontab.get('month_of_year'))
crontab_obj, created = celery_models.CrontabSchedule.objects.get_or_create(
minute=minute, hour=hour, day_of_week=day_of_week, day_of_month=day_of_month,
month_of_year=month_of_year
)
self.crontab = crontab_obj
self.name = data.get('name')
self.task = data.get('task')
self.args = data.get('args')
self.description = data.get('description')
if enabled == self.ENABLED_POST_VALUE:
self.enabled = True
else:
self.enabled = False
self.create_periodictask_db()
return self.operate_success()
def update_periodictask(self, request):
print request.data
return Response("success", status=status.HTTP_200_OK)
def delete_periodictask(self, request):
print request.data
return Response("success", status=status.HTTP_200_OK)
def get_periodictasks(self, request, **kwargs):
print request.data
return Response("success", status=status.HTTP_200_OK)
def get_serializer_class(self):
if self.request.user.is_staff:
return PeriodictaskSerializer
return PeriodictaskSerializer
def get_queryset(self):
user = self.request.user
return user.id
<file_sep>SWARM_URL = '10.6.168.160:2376'
HARBOR_URL='http://10.6.168.54'
<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
import django.utils
class Job(models.Model):
job_name = models.CharField(max_length=512)
updated_at = models.DateTimeField(auto_now=True)
info = models.BinaryField(default={}, blank=True)
# info = models.CharField(max_length=512)
describe = models.CharField(max_length=512, blank=True)
class Result(models.Model):
task_id = models.CharField(max_length=512)
status = models.CharField(max_length=512, blank=True)
result = models.CharField(max_length=512, null=True)
date_done = models.CharField(max_length=512, blank=True)
args = models.CharField(max_length=512, blank=True)
kwargs = models.CharField(max_length=512, blank=True)
name = models.CharField(max_length=512, blank=True)
started = models.CharField(max_length=512, blank=True)
received = models.CharField(max_length=512, blank=True)
<file_sep>FROM ubuntu:16.04
MAINTAINER wangtengyu <EMAIL>
RUN apt-get update && \
apt-get install -y libpq-dev python-pip python-dev nginx dnsutils libmysqlclient-dev rabbitmq-server && \
mkdir -p /var/log/weitac_gateway/ && \
chmod 775 /var/log/weitac_gateway/
RUN easy_install supervisor
RUN easy_install supervisor-stdout
RUN pip install uwsgi
RUN rm -rf /etc/nginx/sites-enabled/default
# nginx config
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
RUN mkdir -p /var/log/weitac_gateway
RUN mkdir -p /var/log/uwsgi/
WORKDIR /weitac_gateway
ENV C_FORCE_ROOT="true"
EXPOSE 8080
COPY requirements.txt /
RUN pip install -r /requirements.txt
COPY . /weitac_gateway
RUN ln -s /weitac_gateway/conf/weitac_gateway_nginx.conf /etc/nginx/sites-enabled/weitac_gateway_nginx.conf
RUN ln -s /weitac_gateway/conf/supervisord.conf /etc/supervisord.conf
RUN chmod +x /weitac_gateway/run.sh
CMD ["/weitac_gateway/run.sh"]
<file_sep># -*- coding: utf-8 -*-
from rest_framework import serializers
from service.models import Service
from django.contrib.auth.models import User
from djcelery import models as celery_models
from djcelery.models import PeriodicTask
class PeriodictaskSerializer(serializers.ModelSerializer):
class Meta:
model = PeriodicTask
fields = ('name', 'task', 'interval', 'crontab', 'args',
'kwargs','enabled','description')<file_sep>import time
from django.utils import timezone
from service.models import Instance
from service.models import IpInfo, Agent
import datetime
def datetime_to_timestamp(t):
stamp = int(time.mktime(t.timetuple()))
return stamp
def save(dic_info):
print dic_info
service = dic_info.get('service')
# created_at = datetime_to_timestamp(timezone.now())
# created_at = timezone.now()
created_at = datetime.datetime.now()
service.created_at = created_at
service.save()
instance_list = dic_info.get('instance')
for instance in instance_list:
instance.service = service
instance.save()
def change_db_ip(instance_name, ip, subnet_mask, gateway_ip):
# print (instance_name, ip, subnet_mask, gateway_ip)
instance = Instance.objects.get(name=instance_name)
ipinfo = IpInfo.objects.get_or_create(address=ip, subnet_mask=subnet_mask, gateway_ip=gateway_ip)
print ipinfo
print instance
instance.continer_ip = ipinfo[0]
instance.save()
def create_agent_info(node_name, node_ip):
return Agent.objects.get_or_create(host_ip=node_ip, host_name=node_name)[0]
<file_sep>import requests
id=12
result_info = requests.get('http://localhost:5555/api/task/info/{}'.format(id))
print '...'+result_info.text+'...'
if result_info.text:
print True
print type(result_info.text)<file_sep>import docker
SWARM_URL = '10.6.168.160:2375'
swarm_client = docker.Client(base_url='tcp://{}'.format(SWARM_URL), timeout=10)
print swarm_client.info()<file_sep># -*- coding: utf-8 -*-
from rest_framework import serializers
from service.models import Container
from models import MonitorInfo
import logging
logger = logging.getLogger(__name__)
class MonotorSerializer(serializers.ModelSerializer):
class Meta:
model = MonitorInfo
def store(self, container_name, validated_data):
try:
container = Container.objects.get(name=container_name)
validated_data['container'] = container
except Exception as ex:
logger.error(ex)
return MonitorInfo.objects.create(**validated_data)
def get_obj(self, container_name):
try:
container = Container.objects.get(name=container_name)
return MonitorInfo.objects.filter(container=container).order_by('-created_at')
except Exception as ex:
logger.error(ex)
return False
<file_sep>from __future__ import unicode_literals
from django.db import models
# from json_field.fields import JSONField
from service.models import Container
# Create your models here.
class MonitorInfo(models.Model):
container = models.ForeignKey(Container, null=True)
created_at = models.DateTimeField(auto_now_add=True)
cpu_stats = models.TextField()
networks = models.TextField()
memory_stats = models.TextField()
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-21 07:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('service', '0003_container'),
]
operations = [
migrations.RenameField(
model_name='container',
old_name='host',
new_name='agent',
),
]
<file_sep>from django.db import models
# Create your models here.
class Celery_event(models.Model):
result = models.CharField(max_length=512)
name = models.CharField(max_length=512)
updated_at = models.DateTimeField(auto_now=True)
# info = models.CharField(max_length=512)
describe = models.CharField(max_length=512, blank=True)<file_sep># -*- coding: utf-8 -*-
# import base64
#
# b = 'gAJLBC4='
# print base64.decodestring(b)
import pickle
import cPickle
# json更适合跨语言,字符串,基本数据类型的序列化
# pickle,更适用python所有类型的序列化
# li = [11, 22, 33]
# r = pickle.dumps(li) # 和json相同 序列化对象成字符串 只能python用
# print(r, type(r))
# rr = pickle.loads(r) # 反序列化字符串回对象 只能python用
# print(rr, type(rr))
# r1 = pickle.dump(li, open("dd", "wb"))
#
# r2 = pickle.load(open("dd", "rb"))
# print(r2)
r='gAJLBC4='
# print cPickle.dumps(r)
print pickle.loads(r)
<file_sep>import logging
import requests
import base64
import docker
import json
swarm_client = docker.Client(base_url='tcp://10.6.168.160:2376', timeout=60)
logger = logging.getLogger(__name__)
# from services.settings import SWARM_URL
# a= swarm_client.containers(filters={'status':'exited'})
# for b in a :
# print b['Names'][0].split('/')[-1]
<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Configuration(models.Model):
configuration_name = models.CharField(max_length=512)
updated_at = models.DateTimeField(auto_now=True)
info = models.BinaryField(default={}, blank=True)
# info = models.CharField(max_length=512)
describe=models.CharField(max_length=512,blank=True)<file_sep>Django==1.10.6
djangorestframework==3.5.4
docker-py==1.8.1
MySQL-python==1.2.5
celery==3.1.24
django-celery==3.2.1
django-json-field==0.5.7
requests==2.12.4
flower==0.9.1
jsonfield<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from .models import Agent
from django.shortcuts import render_to_response
class Agent_views(viewsets.ModelViewSet):
"""
one master to agents
"""
def register_agent(self, request):
data = request.data
print data
# print request.META
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
regip = real_ip.split(",")[0]
except:
try:
regip = request.META['REMOTE_ADDR']
except:
regip = ""
print regip
agent=Agent()
agent.host_ip=regip
agent.cpu=data.get('cpu')
agent.host_name=data.get('hostname')
agent.memory=data.get('mem')
agent.disk=data.get('disk')
agent.network_flow=data.get('io')
agent.save()
return Response('success',status=status.HTTP_200_OK)
def agent_manage(request):
if request.method=='POST':
pass
else:
datas=Agent.objects.all()
return render_to_response('agent_manage.html',{
'username': request.user.username, 'show_list':datas})<file_sep># -*- coding: utf-8 -*-
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets
from models import Instance, Agent, Image, Container
from serializers import ImageSerializer, ContainerSerializer
import logging
import requests
import docker
import time
from django.utils import timezone
from utils import service_DBclient
from job.views import call_agent_change_ip
from rest_framework.parsers import JSONParser, FormParser
import json
from django.shortcuts import render
from rest_framework import permissions
from settings import HARBOR_URL, SWARM_URL
logger = logging.getLogger(__name__)
swarm_client = docker.Client(base_url='tcp://{}'.format(SWARM_URL), timeout=60)
swarm_create_client = docker.Client(base_url='tcp://{}'.format(SWARM_URL), timeout=100)
def datetime_to_timestamp(t):
stamp = int(time.mktime(t.timetuple()))
return stamp
class ContainerViewSet(viewsets.ModelViewSet):
"""
Container control Set,include create,delete,stop,list.
"""
permission_classes = (permissions.IsAuthenticated,)
# authentication_classes = (SessionAuthentication, BasicAuthentication)
parser_classes = (JSONParser, FormParser)
# def get_queryset(self):
# """
# restframework
# :return:
# """
# user = self.request.user
# return user.id
#
# def get_serializer_class(self):
# if self.request.user.is_staff:
# return ImageSerializer
# return ImageSerializer
def operate_fail(self, data):
"""
deal bad request
:param data:
:return:
"""
return Response(data, status=status.HTTP_400_BAD_REQUEST)
def operate_success(self):
"""
return success Response
:return:
"""
return Response("success", status=status.HTTP_200_OK)
def create_container(self, request):
"""
create contianer.
:param request:
:return: HTML
"""
data = request.data
if request.method == 'POST':
logger.info('create container is called')
container_name = data.get('container_name')
try:
project = data['project']
repository = data['repository']
tag = data['tag']
image_name = 'docker.weitac.com/{}/{}:{}'.format(project, repository, tag)
except:
return self.operate_fail('Not image was checked')
environment = data.get('environment')
if not environment:
environment = None
hostname = data.get('hostname')
if not hostname:
hostname = 'haproxy.weitac.com'
command = data.get('command')
if not command:
command = '/usr/sbin/init'
volumes = data.get('volumes')
if not volumes:
volumes = './conf:/etc/haproxy'
ip = data.get('ip')
logger.info('Create a container: {}'.format(container_name))
data = {'name': container_name,
'image_name': image_name,
'environment': environment,
'hostname': hostname,
'command': command,
'volumes': volumes}
serializer = ContainerSerializer(data=data)
if not serializer.is_valid():
logger.error('Serializer is not valid')
return self.operate_fail('Serializer is not valid')
if serializer.is_exist(container_name):
logger.error('Container {} exits'.format(container_name))
return self.operate_fail('container {} is exist'.format(container_name))
container = serializer.create(data)
'''
not good
'''
instance = Instance_client()
service_name = container_name
instance_id = 1
bl, result = instance.create_instance \
(service_name, instance_id, image_name, environment, hostname, command, volumes)
if not bl:
return self.operate_fail('Not create container success')
if bl:
instance.start_instance(result)
serializer.update(container, {'state': 'running'})
else:
return self.operate_fail('Not start container success')
host_obj = Instance_client().search_host_info(container_name)
serializer.update_agent(container, host_obj)
return render(request, 'container_create.html',
{'username': request.user.username})
else:
return render(request, 'container_create.html',
{'username': request.user.username})
def list_containers(self, request):
"""
query all containers.
:param request:
:return: HTML
"""
logger.info('Getting containers was called')
containers = Container.objects.all()
return render(request,
'container_manage.html', {
'username': request.user.username, 'show_list': containers})
def deal_containers(self, request):
"""
deal action of container,include delete,stop,start
:param request:
:return: HTML
"""
data = request.data
container_names = data.getlist('container_names')
if data.get('action') == 'delete':
logger.debug('Start delete containers :{}'.format(container_names))
for container in container_names:
logger.debug('Start delete container :{}'.format(container))
try:
container_obj = Container.objects.get(name=container)
except Exception as ex:
return self.operate_fail('Container dose not exit. {}'.format(ex))
result = Instance_client().delete_instance(container)
if result is True:
container_obj.delete()
else:
return self.operate_fail('Delete service error')
elif data.get('action') == 'stop':
logger.debug('Start stop containers :{}'.format(container_names))
for container in container_names:
logger.debug('Start stop container :{}'.format(container))
try:
container_obj = Container.objects.get(name=container)
except Exception as ex:
return self.operate_fail('Container dose not exit. {}'.format(ex))
result = Instance_client().stop_instance(container)
if result is True:
container_obj.state = 'Exited'
container_obj.save()
else:
return self.operate_fail('Delete service error')
elif data.get('action') == 'start':
logger.debug('Start start containers :{}'.format(container_names))
for container in container_names:
logger.debug('Start start container :{}'.format(container))
try:
container_obj = Container.objects.get(name=container)
except Exception as ex:
return self.operate_fail('Container dose not exit. {}'.format(ex))
result = Instance_client().start_instance(container)
if result is True:
container_obj.state = 'running'
container_obj.save()
else:
return self.operate_fail('Delete service error')
containers = Container.objects.all()
return render(request,
'container_manage.html', {
'username': request.user.username, 'show_list': containers})
def assignment_ip(instance_name):
"""
assignment ip to a container
:param instance_name:
:return:
"""
try:
instance_obj = Instance.objects.get(name=instance_name)
except Exception as ex:
logger.error('Did not have this instance {}:{}'.format(instance_name, ex))
return
if not instance_obj.continer_ip:
return
agent_ip = instance_obj.host.host_ip
intance_ip = instance_obj.continer_ip.address
subnet_mask = instance_obj.continer_ip.subnet_mask
gateway_ip = instance_obj.continer_ip.gateway_ip
call_agent_change_ip.delay(agent_ip, instance_name, intance_ip, subnet_mask, gateway_ip)
class Instance_client(object):
"""
This class is crated for service's instances,since one service have
multiple instances.But new project is use container instead of service.This
method is be retained to control container's status.
"""
model = Instance
def create_instance(self, service_name, instance_id, image_name, environment, hostname, command, volumes):
instance_name = service_name
logger.info('Create a docker instance: {}'.format(instance_name))
# cmd_data = ["nginx",
# "-g",
# "daemon off;"]
# labels_data = {
# "com.example.vendor": "Acme",
# "com.example.license": "GPL",
# "com.example.version": "1.0"}
# HostConfig = {"NetworkMode": "bridge"}
try:
print image_name, command, instance_name, hostname, volumes
r = swarm_client.create_container(image=image_name,
command=command,
name=instance_name,
# environment=environment,
hostname=hostname,
volumes=volumes,
)
except Exception as ex:
logger.error("Error{}".format(ex))
return None, ex
# service = Service.objects.get(service_name=service_name)
container_id = r.get('Id')
# created_at = datetime_to_timestamp(timezone.now())
created_at = (timezone.now())
try:
"""
create agent info in db.
"""
a = swarm_client.inspect_container(container_id)
node_name = a.get('Node').get('Name')
node_ip = a.get('Node').get('IP')
agent_obj = service_DBclient.create_agent_info(node_name, node_ip)
except Exception as ex:
agent_obj = None
logger.debug('Did not get agent info:{}'.format(ex))
b = Instance(name=instance_name, created_at=created_at,
instance_id=instance_id,
continer_id=container_id,
command=command,
hostname=hostname,
volumes=volumes,
environment=environment,
host=agent_obj
)
# service = service,
# host='hostname'
# b.save()
# container_id = json.loads(r.text).get('Id')
logger.info('Create docker continer :{}'.format(instance_name))
return b, container_id
# def create_instance(self, service_name, instance_id, image_name, environment, hostname, command, volumes):
# instance_name = service_name + '_{}'.format(instance_id)
#
# logger.info('Create a docker instance: {}'.format(instance_name))
# # cmd_data = ["nginx",
# # "-g",
# # "daemon off;"]
# # labels_data = {
# # "com.example.vendor": "Acme",
# # "com.example.license": "GPL",
# # "com.example.version": "1.0"}
# # HostConfig = {"NetworkMode": "bridge"}
# try:
# print image_name, command, instance_name, hostname, volumes
# r = swarm_client.create_container(image=image_name,
# command=command,
# name=instance_name,
# # environment=environment,
# hostname=hostname,
# volumes=volumes,
#
# )
#
# except Exception as ex:
# logger.error("Error{}".format(ex))
# return None, ex
# # service = Service.objects.get(service_name=service_name)
# container_id = r.get('Id')
# # created_at = datetime_to_timestamp(timezone.now())
# created_at = (timezone.now())
# try:
# """
# create agent info in db.
# """
# a = swarm_client.inspect_container(container_id)
#
# node_name = a.get('Node').get('Name')
# node_ip = a.get('Node').get('IP')
# agent_obj = service_DBclient.create_agent_info(node_name, node_ip)
# except Exception as ex:
# agent_obj = None
# logger.debug('Did not get agent info:{}'.format(ex))
# b = Instance(name=instance_name, created_at=created_at,
# instance_id=instance_id,
# continer_id=container_id,
# command=command,
# hostname=hostname,
# volumes=volumes,
# environment=environment,
# host=agent_obj
# )
# # service = service,
# # host='hostname'
# # b.save()
# # container_id = json.loads(r.text).get('Id')
# logger.info('Create docker continer :{}'.format(instance_name))
# return b, container_id
def start_instance(self, continer_id):
logger.info('Start continer of: {}'.format(continer_id))
try:
swarm_client.start(container=continer_id)
return True
# requests.post(SWARM_URL + '/containers/{}/start'.format(continer_id))
except Exception as ex:
logger.error("Error: {}".format(ex))
return False
def delete_instance(self, continer_id):
logger.info('Delete continer of: {}'.format(continer_id))
# print continer_id
try:
swarm_client.stop(container=continer_id)
swarm_client.remove_container(container=continer_id)
except requests.exceptions.HTTPError as ex:
logger.error("Error: {}".format(ex))
return True
except requests.exceptions.ConnectionError as ex:
logger.error("Error: {}".format(ex))
return False
return True
def add_host_info(self, db_info):
mapping = {}
a = swarm_client.containers()
for b in a:
host_name = b.get('Names')[0].split('/')[1]
server_name = b.get('Names')[0].split('/')[2]
mapping[server_name] = host_name
instances = db_info.get('instance')
for instance in instances:
host_name = mapping.get(instance.name)
try:
instance.host = Agent.objects.get(host_name=host_name)
except:
pass
return db_info
def search_host_info(self, container_name):
mapping = {}
a = swarm_client.containers()
for b in a:
host_name = b.get('Names')[0].split('/')[1]
server_name = b.get('Names')[0].split('/')[2]
mapping[server_name] = host_name
host_name = mapping.get(container_name)
print host_name
try:
host = Agent.objects.get(host_name=host_name)
except:
return None
return host
def stop_instance(self, instance_name):
logger.info('Stop continer of: {}'.format(instance_name))
try:
swarm_client.stop(container=instance_name)
return True
# requests.post(SWARM_URL + '/containers/{}/start'.format(continer_id))
except Exception as ex:
logger.error("Error: {}".format(ex))
return False
def get_exited_instance(self):
result_list = []
exited_containers = swarm_client.containers(filters={'status': 'exited'})
for exited_container in exited_containers:
container = exited_container['Names'][0].split('/')[-1]
result_list.append(container)
return result_list
class ImageViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
# permission_classes = (permissions.AllowAny,)
# authentication_classes = (SessionAuthentication, BasicAuthentication)
# parser_classes = (JSONParser, FormParser)
def get_queryset(self):
user = self.request.user
return user.id
def update_image(self, request, **kwargs):
try:
r = requests.get('{}/api/search'.format(HARBOR_URL))
except requests.ConnectionError as ex:
logger.error(ex)
return Response('Fail connet to Harbor.try again', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as ex:
logger.error(ex)
return Response('Fail', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# http://10.6.168.54/api/repositories/tags?repo_name=tengyu/weitac_gateway
dic_info = json.loads(r.text)
repositorys = dic_info.get('repository')
for repository in repositorys:
repository_name = repository.get('repository_name')
tags_str = requests.get('{0}/api/repositories/tags?repo_name={1}'.format(HARBOR_URL, repository_name))
tags = json.loads(tags_str.text)
for tag in tags:
project = repository_name.split('/')[0]
repository = repository_name.split('/')[1]
create_update_image(project, repository, tag)
images = Image.objects.all()
return render(request, 'image_manage.html', {
'username': request.user.username, 'show_list': images})
# def get_image(self, request, **kwargs):
# print request
# print request.data
# request_json = False
# if 'json' in request.GET.keys():
# request_json = True
#
# result = dict()
# images = Image.objects.all()
# for image in images:
# if image.project not in result:
# result.setdefault(image.project)
# result[image.project] = dict()
# if image.repository not in result[image.project]:
# result[image.project].setdefault(image.repository)
# result[image.project][image.repository] = list()
# result[image.project][image.repository].append(image.tag)
# if request_json == True:
# return Response(result, status=status.HTTP_200_OK)
# else:
# return JsonResponse(result, status=status.HTTP_200_OK)
# def get_serializer_class(self,data,'ss'):
# return ImageSerializer('2',data)
def get_serializer_class(self):
if self.request.user.is_staff:
return ImageSerializer
return ImageSerializer
def get_project(self, request, **kwargs):
logger.info('Get project is request')
images = Image.objects.values_list('project')
news_projects = []
for id in images:
if id[0] not in news_projects:
news_projects.append(id[0])
return Response(news_projects, status=status.HTTP_200_OK)
def get_repository(self, request, **kwargs):
project = kwargs.get('project')
images = Image.objects.filter(project=project).values_list('repository')
news_repositorys = []
for id in images:
if id[0] not in news_repositorys:
news_repositorys.append(id[0])
return Response(news_repositorys, status=status.HTTP_200_OK)
def get_tag(self, request, **kwargs):
project = kwargs.get('project')
repository = kwargs.get('repository')
images = Image.objects.filter(project=project, repository=repository).values_list('tag')
news_tags = []
for id in images:
if id[0] not in news_tags:
news_tags.append(id[0])
return Response(news_tags, status=status.HTTP_200_OK)
def list_images(self, request):
data = request.data
logger.info('Getting images was called')
images = Image.objects.all()
return render(request,
'image_manage.html', {
'username': request.user.username, 'show_list': images})
def create_update_image(project, repository, tag):
if not Image.objects.filter(project=project, repository=repository, tag=tag):
logger.info('add new {}/{}:{}'.format(project, repository, tag))
image_obj = Image()
image_obj.project = project
image_obj.repository = repository
image_obj.tag = tag
image_obj.name = 'docker.weitac.com/{}/{}:{}'.format(project, repository, tag)
image_obj.save()
<file_sep>from celery.result import AsyncResult
a= AsyncResult(id='aa74684f-966a-4249-82cb-cb71f5a5bff8',backend='')
print a.result
<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
# from redisco import models
# from json_field.fields import JSONField
from django.utils import timezone
from agent.models import Agent
# Create your models here.
class IpInfo(models.Model):
address = models.CharField(max_length=20)
is_used = models.BooleanField(default=False)
gateway_ip = models.CharField(max_length=20)
subnet_mask = models.CharField(max_length=20,default=24)
class Service(models.Model):
service_name = models.CharField(max_length=512)
instance_amount = models.IntegerField()
image_name = models.CharField(max_length=512)
created_at = models.CharField(max_length=512, null=True)
updated_at = models.DateTimeField(auto_now=True)
# details = JSONField(default={}, blank=True)
details = models.CharField(max_length=512, null=True)
finished_at = models.IntegerField(default=0)
class Instance(models.Model):
name = models.CharField(max_length=512)
service = models.ForeignKey(Service, null=True)
instance_id = models.CharField(max_length=20, null=True)
continer_id = models.CharField(max_length=512, null=True)
continer_ip = models.ForeignKey(IpInfo, null=True)
# image_name = models.CharField(max_length=512)
created_at = models.CharField(max_length=512, null=True)
updated_at = models.DateTimeField(auto_now=True)
host = models.ForeignKey(Agent, null=True)
# details = JSONField(default={}, blank=True)
details = models.CharField(max_length=512, null=True)
command = models.CharField(max_length=512, null=True)
hostname = models.CharField(max_length=512, null=True)
volumes = models.CharField(max_length=512, null=True)
environment = models.CharField(max_length=512, null=True)
state = models.CharField(max_length=20,null=True)
# app_id = models.CharField(db_index=True, max_length=512)
# finished_at = models.IntegerField(default=0)
# survived_day = models.DateField(default=datetime.date.today)
# size = models.CharField(max_length=256, default='None')
# app_info = models.ForeignKey(AppSizeInfo, null=True)
# category = models.CharField(default='service', max_length=7)
# # details = models.CharField(max_length=512, null=True)
# def is_finished(self):
# return self.finished_at != 0
#
# class Meta:
# unique_together = ('instance_id', 'survived_day')
class Image(models.Model):
name = models.CharField(max_length=512)
project = models.CharField(max_length=512)
repository = models.CharField(max_length=512)
tag = models.CharField(max_length=512)
registry = models.CharField(max_length=512, default='docker.weitac.com')
class Container(models.Model):
name = models.CharField(max_length=512)
continer_id = models.CharField(max_length=512, null=True)
continer_ip = models.ForeignKey(IpInfo, null=True)
image_name = models.CharField(max_length=512)
created_at = models.CharField(max_length=512, null=True)
updated_at = models.DateTimeField(auto_now=True)
agent = models.ForeignKey(Agent, null=True)
# details = JSONField(default={}, blank=True)
details = models.CharField(max_length=512, null=True)
command = models.CharField(max_length=512, null=True)
hostname = models.CharField(max_length=512, null=True)
volumes = models.CharField(max_length=512, null=True)
environment = models.CharField(max_length=512, null=True)
state = models.CharField(max_length=20,default='ready')<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-29 03:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('service', '0005_auto_20170324_1524'),
]
operations = [
migrations.CreateModel(
name='MonitorInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('cpu_stats', models.TextField()),
('networks', models.TextField()),
('memory_stats', models.TextField()),
('container', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='service.Container')),
],
),
]
<file_sep># -*- coding: utf-8 -*-
from __future__ import division
from rest_framework import status
from rest_framework.response import Response
from django.shortcuts import render
from service.views import swarm_client
from rest_framework import viewsets
from rest_framework import permissions
from .serializers import MonotorSerializer
from django.utils import timezone
import json
import logging
logger = logging.getLogger(__name__)
# Create your views here.
class MonitorViewSet(viewsets.ModelViewSet):
"""
Monitor control Set,include create,delete,list.
"""
permission_classes = (permissions.IsAuthenticated,)
# authentication_classes = (SessionAuthentication, BasicAuthentication)
def list_monitor(self, request):
logger.debug('List monitors is called')
container_name = request.GET.get('container_name')
data_list = MonitorManager().query_monitor(container_name)
return render(request, 'monitor_manage.html', {
'username': request.user.username, 'show_list': data_list})
def create_monitor(self, request):
"""
API for colletct montitor data for all containers in swarm cluster.
And store in db.
:param request:
:return: Response
"""
result = MonitorManager().store_containers_monitor_in_db(swarm_client)
return self._operate_success()
def delete_monitor(self, request):
"""
Just for api,if you want delete some monitor data,which is far away from now.
:return: Boole
"""
def _operate_fail(self, data):
"""
deal bad request
:param data:
:return:
"""
return Response(data, status=status.HTTP_400_BAD_REQUEST)
def _operate_success(self):
"""
return success Response
:return:
"""
return Response("success", status=status.HTTP_200_OK)
class MonitorManager(object):
def __init__(self):
pass
def query_monitor(self, container_name):
datas = MonitorDBManager().get(container_name)
result = []
if not datas:
return []
for data in datas:
cpu_stats = json.loads(data.cpu_stats)
networks = json.loads(data.networks)
memory_stats = json.loads(data.memory_stats)
created_at = data.created_at
# print memory_stats.get('usage')
# print type(memory_stats.get('usage'))
config = MonitorConfig(cpu_stats, networks, memory_stats, created_at)
result.append(config.decode_data)
return result
def _get_monitor(self, server_name):
result = dict()
stats = swarm_client.stats(server_name, decode=True, stream=False)
cpu_stats = stats.get('cpu_stats')
networks = stats.get('networks')
memory_stats = stats.get('memory_stats')
result['cpu_stats'] = json.dumps(cpu_stats)
result['networks'] = json.dumps(networks)
result['memory_stats'] = json.dumps(memory_stats)
return result
def _get_containers(self, swarm_client):
"""
get all the containers'name.
:return:
"""
a = swarm_client.containers()
result = []
for b in a:
host_name = b.get('Names')[0].split('/')[1]
server_name = b.get('Names')[0].split('/')[2]
result.append(server_name)
return result
def store_containers_monitor_in_db(self, swarm_client):
data_dic = dict()
service_names = self._get_containers(swarm_client)
for service_name in service_names:
data = self._get_monitor(service_name)
data_dic[service_name] = (data)
MonitorDBManager().store(data_dic)
return 'true'
class MonitorDBManager(object):
def __init__(self):
pass
def store(self, data_lis):
for service_name, data in data_lis.items():
# print service_name
MonotorSerializer().store(service_name, data)
def get(self, container_name):
datas = MonotorSerializer().get_obj(container_name)
return datas
class MonitorConfig(object):
cpu_stats = dict()
networks = dict()
memory_stats = dict()
created_at = timezone.now()
def __init__(self, cpu_stats, networks, memory_stats, created_at):
self.cpu_stats = cpu_stats
self.networks = networks
self.memory_stats = memory_stats
self.created_at = created_at
self._del_mem()
self._del_cpu()
self._del_io()
def decode_data(self):
result = dict()
result['mem_percent'] = self.mem_percent
result['mem_limit'] = self.mem_limit
result['mem_usage'] = self.mem_usage
result['cpu_percent'] = self.cpu_percent
result['networks_rx'] = self.networks_rx
result['networks_tx'] = self.networks_tx
result['created_at'] = self.created_at
return result
def _del_mem(self):
limit = self.memory_stats.get('limit')
usage = self.memory_stats.get('usage')
self.mem_percent = '{}%'.format(round(usage / limit, 2))
self.mem_limit = self._add_unit(limit)
self.mem_usage = self._add_unit(usage)
def _del_cpu(self):
total_usage = self.cpu_stats.get('cpu_usage').get('total_usage')
system_cpu_usage = self.cpu_stats.get('system_cpu_usage')
self.cpu_percent = '{}%'.format(round((total_usage * 10000) / system_cpu_usage, 2))
def _del_io(self):
rx_bytes = self.networks.get('eth0').get('rx_bytes')
tx_bytes = self.networks.get('eth0').get('tx_bytes')
self.networks_rx = self._add_unit(rx_bytes)
self.networks_tx = self._add_unit(tx_bytes)
def _add_unit(self, data):
if not isinstance(data, int):
return False
# if len(str(data)) < 3:
# return '{}B'.format(data)
if 6 > len(str(data)) > 3:
return '{}KB'.format(round(data / 1000, 1))
if 9 > len(str(data)) > 6:
return '{}MB'.format(round(data / 1000000, 1))
if 9 < len(str(data)):
return '{}GB'.format(round(data / 1000000000, 1))
else:
return '{}B'.format(data)<file_sep>OS = Linux
VERSION = 0.0.1
CURDIR = $(shell pwd)
SOURCEDIR = $(CURDIR)
ECHO = echo
RM = rm -rf
MKDIR = mkdir
FLAKE8 = flake8
PIP_INSTALL = pip install
RUN_MOCK_TESTS = ./run-mock-tests.sh
.PHONY: setup build test help
all: setup build test
setup:
$(PIP_INSTALL) $(FLAKE8)
build:
$(FLAKE8) $(SOURCEDIR) --show-source --show-pep8 --statistics --count
test:
$(RUN_MOCK_TESTS)
help:
@$(ECHO) "Targets:"
@$(ECHO) "all - setup, build and test"
@$(ECHO) "setup - set up prerequisites for build"
@$(ECHO) "build - perform static analysis"
@$(ECHO) "test - run unit tests"<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template import Context, Template
from django.template.context_processors import csrf
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
def index(request):
'''判断用户是否登陆'''
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
username = request.user.username
return render_to_response('container_manage.html', {'username': username})
def login(request):
# c = {}
# c.update(csrf(request))
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('<PASSWORD>')
if username is not None and password is not None:
user = auth.authenticate(username=username, password=<PASSWORD>)
if user is not None and user.is_active:
auth.login(request, user)
# request.session['username']=username
return HttpResponseRedirect('/index/')
else:
return render_to_response(
'login.html', {
'login_error': '用户名或密码错误!'})
# return render_to_response('login.html',context=RequestContext(request, {'uf':uf}))
return render(request,'login.html',Context({'uf':'kk'}))
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/login/')
<file_sep>from django.test import TestCase
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weitac_gateway.settings')
import sys
sys.path.append("../")
import django
django.setup()
# Create your tests here.
from job.models import Result
jobs = Result.objects.all().order_by('-started')
for job in jobs:
print job.name<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Agent(models.Model):
host_name = models.CharField(max_length=20)
host_ip = models.CharField(max_length=20)
cpu = models.CharField(max_length=512)
memory = models.CharField(max_length=512)
network_flow = models.CharField(max_length=512)
disk = models.CharField(max_length=512)
<file_sep>import time
from django.utils import timezone
from service.models import Instance
from service.models import IpInfo, Agent
import datetime
def update_instance(instance_name, status):
instance = Instance.objects.get(name=instance_name)
instance.state = status
instance.save()
<file_sep># -*- coding: utf-8 -*-
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from monitor.views import MonitorViewSet
from rest_framework.request import Request
from service.views import swarm_client
from rest_framework.request import Request
from monitor.views import MonitorManager
@shared_task
def create_monitor():
return MonitorManager().store_containers_monitor_in_db(swarm_client)
@shared_task
def add(x, y):
return x + y
@shared_task
def mul(x, y):
return x * y
@shared_task
def xsum(numbers):
return sum(numbers)
# # -*- coding: utf-8 -*-
# from __future__ import absolute_import, unicode_literals
# # import os
# # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weitac_gateway.settings')
# # import sys
# # sys.path.append("../")
# # import django
# # django.setup()
# from celery import Celery,shared_task, task
# app = Celery('tasks',backend='db+mysql://weitac:111111@10.6.168.163:3306/weitac_gateway')
# @app.task
# def add(x, y):
# print x+y
# # a=pickle.dumps(x+y)
# return x+y
#
#
# @task
# def add1(x, y):
# print x+y
# # a=pickle.dumps(x+y)
# return x+y
# app = Celery('tasks')
#
# @shared_task
# def add(x, y):
# return x + y
# from __future__ import absolute_import
#
# import os
# from celery import shared_task, task
# from celery import Celery
#
# # set the default Django settings module for the 'celery' program.
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weitac_gateway.settings')
#
# from django.conf import settings # noqa
#
# # app = Celery('proj')
# app = Celery()
#
# # Using a string here means the worker will not have to
# # pickle the object when using Windows.
# # app.config_from_object('django.conf:settings')
#
#
# # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# #
# # @app.task
# # def celery(func, *args, **kw):
# # """
# # 装饰器来异步执行,为了result等存入数据库
# # :param func:
# # :return:
# # """
# #
# # def wrapper(*args, **kw):
# # print 'call %s():' % func.__name__
# # result = func(*args, **kw)
# # store(result, *args, **kw)
# # return func(*args, **kw)
# # return wrapper(*args, **kw)
#
#
# @app.task(bind=True)
# def debug_task(self):
# # print('Request: {0!r}'.format(self.request))
# print('Request')
#
#
# # @shared_task
# # @app.task(bind=True)
#
#
# # @celery
# @app.task
# def add(x, y):
# return x + y
#
#
# def store(result, *args, **kw):
# print result
#
#
# if __name__ == '__main__':
# # g = add.delay(2, 2)
# g = add(2, 2)
# print g
# # print g.id
# # print g.result
# # print g.status
# # a = debug_task.delay()
# # print a.id
# # print a.result(timeout=10)
<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets
from models import Configuration
from service.models import Agent
import logging
from service.serializers import ImageSerializer
import ConfigParser
import StringIO
from utils.configuration_client import del_xml_configuration, del_conf_configuration
from django.shortcuts import render_to_response
from job.views import call_agent_cp_configuration
from service.models import Instance
from rest_framework.parsers import JSONParser, FormParser
# from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework import permissions
logger = logging.getLogger(__name__)
def configuration_manage(request):
scripts = Configuration.objects.all()
return render_to_response(
'configuration_manage.html', {
'username': request.user.username, 'show_list': scripts})
def configuration_upload(request):
if request.method == 'POST':
# script= request.POST.get('script')
# print type(script)
print request
myFile = request.FILES.get('script', None)
name = request.POST.get('name')
describe = request.POST.get('describe')
print name, describe
if name:
save_name = name
else:
save_name = myFile
# print(myFile._size) # 文件大小字节数
if Configuration.objects.filter(configuration_name=myFile).exists():
return render_to_response('400.html', {'info': '脚本已经存在'})
data = myFile.read()
job_obj = Configuration()
job_obj.configuration_name = save_name
job_obj.info = data
job_obj.describe = describe
job_obj.save()
return render_to_response(
'configuration_upload.html', {
'username': request.user.username})
else:
return render_to_response(
'configuration_upload.html', {
'username': request.user.username})
def configuration_update(request):
if request.method == 'POST':
# print request
script_name = request.GET.get('job_name')
if not script_name:
return render_to_response('400.html')
script_obj = Configuration.objects.filter(job_name=script_name)[0]
agent_hosts_lis = request.POST.lists()
# r = requests.post('http://10.6.168.161:8000', data=script, headers=headers)
return render_to_response('configuration_manage.html')
else:
scripts = Configuration.objects.all()
agents = Agent.objects.all()
if not request.GET.get('job_name'):
return render_to_response(
'job_run.html', {
'username':
request.user.username, 'scripts': scripts,
'agents': agents})
else:
job_name = request.GET.get('job_name')
return render_to_response(
'job_run.html', {
'username':
request.user.username, 'scripts': scripts,
'agents': agents, 'choiced_script': job_name})
class ConfigurationViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
# authentication_classes = (SessionAuthentication, BasicAuthentication)
parser_classes = (JSONParser, FormParser)
def get_queryset(self):
user = self.request.user
return user.id
def get_serializer_class(self):
if self.request.user.is_staff:
return ImageSerializer
return ImageSerializer
def operate_fail(self, data):
return Response(data, status=status.HTTP_400_BAD_REQUEST)
def operate_success(self):
return Response("success", status=status.HTTP_200_OK)
def get_configuration(self, request, **kwargs):
return self.operate_fail('not support')
def update_configuration(self, request):
if request.method == 'PUT':
data = request.DATA
instance_name = data.get('instance_name')
configuration_name = data.get('configuration_name')
configuration_dir = data.get('configuration_dir')
obj = Configuration.objects.get(configuration_name=configuration_name)
file_obj = StringIO.StringIO()
file_obj.write(obj.info)
file_obj.seek(0)
changed_file = StringIO.StringIO()
configuration_type = configuration_name.split('.')[-1]
if configuration_type == 'xml':
change = data.get('change')
new = data.get('new')
config = del_xml_configuration(file_obj, change, new)
config.write(changed_file)
changed_file.seek(0)
data = changed_file.read()
elif configuration_type == 'cnf':
sections = data.get('parameters')
config = ConfigParser.RawConfigParser(allow_no_value=True)
s = StringIO.StringIO()
s.write(obj.info)
s.seek(0)
config.readfp(s)
for section, value_dic in sections.items():
for parameter, parameter_value in value_dic.items():
config.set(section, parameter, parameter_value)
config.write(changed_file)
changed_file.seek(0)
data = changed_file.read()
elif configuration_type == 'conf':
change = data.get('change')
delete = data.get('delete')
data = del_conf_configuration(file_obj, change, delete)
else:
return Response('Configuration type not support', status=status.HTTP_400_BAD_REQUEST)
try:
instance_obj = Instance.objects.get(name=instance_name)
except Exception as ex:
logger.error(ex)
return self.operate_fail(ex)
agent_obj = instance_obj.host
agent_host_ip = agent_obj.host_ip
dir = configuration_dir
try:
call_agent_cp_configuration(agent_host_ip, instance_name, configuration_name, data, dir)
except Exception as ex:
return self.operate_fail(ex)
return self.operate_success()
def upload_configuration(self, request):
if request.GET.get('source') == 'master':
data = request.DATA
myFile = request.FILES.get('script', None)
name = data.get('name')
describe = data.get('describe')
if name:
save_name = name
else:
save_name = myFile.name
# print(myFile._size) # 文件大小字节数
if Configuration.objects.filter(configuration_name=save_name).exists():
return self.operate_fail('脚本已经存在')
data = myFile.read()
job_obj = Configuration()
job_obj.configuration_name = save_name
job_obj.info = data
job_obj.describe = describe
job_obj.save()
return self.operate_success()
def delete_configuration(self, reqest):
return self.operate_fail('not support')
<file_sep>#!/bin/sh
/usr/local/bin/autopep8 --verbose --recursive --exclude migrations,settings_docker.py --max-line-length 80 --in-place --aggressive --aggressive .;
<file_sep>#!/bin/sh
#chmod u+x trigger.sh
#nohup /weitac_gateway/trigger.sh > /weitac_gateway/trigger.date &
#if "$MIGRAGEDB" in "true"; then
# /usr/bin/python /weitac_gateway/manage.py migrate --settings=weitac_gateway.settings
#fi
#/usr/local/bin/supervisord --nodaemon # Run supervisord in the foreground
python manage.py makemigrations
python manage.py migrate
#nohup python manage.py celery worker --loglevel=info --config=celeryconfig &
#nohup python manage.py celery worker --loglevel=info --config=celeryconfig &
#nohup python manage.py celery beat
/usr/local/bin/supervisord --nodaemon
<file_sep>from django.test import TestCase
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weitac_gateway.settings')
import sys
sys.path.append("../")
import django
django.setup()
from monitor.views import MonitorViewSet,MonitorManager
from celery import shared_task
from service.views import swarm_client
from rest_framework.request import Request
@shared_task
def create_monitor():
return MonitorManager().store_containers_monitor_in_db(swarm_client)
# Create your tests here.
# def get_monitor():
# # print swarm_client.containers()
# mapping = {}
# a = swarm_client.containers()
# for b in a:
# host_name = b.get('Names')[0].split('/')[1]
# server_name = b.get('Names')[0].split('/')[2]
#
# stats = swarm_client.stats(server_name, decode=True, stream=False)
# # print server_name,stats
# # stats = self.docker.stats(cid, decode=True)
# cpu_stats = stats.get('cpu_stats')
# networks = stats.get('networks')
# memory_stats = stats.get('memory_stats')
# print cpu_stats
# print type(cpu_stats)
# print networks
# print memory_stats
if __name__ == '__main__':
create_monitor().delay()
# MonitorViewSet().create_monitor(Request)<file_sep>[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /weitac_gateway
# set DJANGO_SETTINGS_MODULE
env = DJANGO_SETTINGS_MODULE=weitac_gateway.settings
#module = django.core.handlers.wsgi:WSGIHandler()
module = django.core.wsgi:get_wsgi_application()
# process-related settings
# master
master = True
# maximum number of worker processes
processes = 50
# the socket (use the full path to be safe
socket = /weitac_gateway/weitac_gateway.sock
;socket =127.0.0.1:8080
# ... with appropriate permissions - may be needed
chmod-socket = 666
# clear environment on exit
vacuum = true
logto=/var/log/uwsgi/weitac_gateway.log
<file_sep># README #
##Weitac_gateway
###docker run -d -p 8080:8080 --name weitac-gatway docker.weitac.com/tengyu/weitac_gateway:0.3<file_sep>import time
from django.utils import timezone
from service.models import Instance
from service.models import IpInfo, Agent
import datetime
def get_jobs(num):
# instance = Instance.objects.get(name=instance_name)
# instance.state = status
# instance.save()
pass<file_sep>"""
Django settings for weitac_gateway project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import djcelery
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# TEMPLATE_DEBUG = DEBUG
# ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['*']
# APPEND_SLASH = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'service',
'login',
'job',
'agent',
'djcelery',
'monitor',
# 'django_celery_results',
'rest_framework',
# 'rest_framework.authtoken',
'configuration'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'weitac_gateway.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = 'staticfiles'
WSGI_APPLICATION = 'weitac_gateway.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
# 'NAME': os.path.join(BASE_DIR, 'user_data'),
'NAME': 'weitac_gateway',
'ENGINE': 'django.db.backends.mysql',
'USER': 'weitac',
# 'USER': 'root',
'PASSWORD': '<PASSWORD>',
'HOST': '10.6.168.163',
# 'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
# LANGUAGE_CODE = 'zh-Hans'
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
LOG_PATH = '/var/log/weitac_gateway/'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s][%(threadName)s]' +
'[%(name)s:%(lineno)d] %(message)s'}
},
'handlers': {
'debug': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': LOG_PATH + 'debug.log',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'info': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': LOG_PATH + 'info.log',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
# 'filename': LOG_PATH + '.error.log',
'filename': LOG_PATH + 'error.log',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers': ['console', 'debug', 'info', 'error'],
'level': 'INFO',
'propagate': False
},
'django.request': {
'handlers': ['console', 'debug', 'info', 'error'],
'level': 'INFO',
'propagate': False,
},
'': {
'handlers': ['console', 'debug', 'info', 'error'],
'level': 'DEBUG',
'propagate': False
},
}
}
djcelery.setup_loader()
BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_BROKER_URL = 'amqp://guest:guest@localhost//'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'
CELERY_RESULT_SERIALIZER = 'json'
# CELERY_RESULT_DBURI = "mysql+mysqlconnector://root:111111@localhost:3306/weitac_gateway"
# CELERY_RESULT_DBURI = "db+mysql://root:111111@localhost:3306/weitac_gateway"
CELERY_TASK_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TIMEZONE = TIME_ZONE
CELERY_ENABLE_UTC = True
# CELERY_ALWAYS_EAGER = True
CELERY_IMPORTS = ("job.tasks", "job.views", "job.tasks",)
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-21 07:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('agent', '0001_initial'),
('service', '0002_auto_20170320_1718'),
]
operations = [
migrations.CreateModel(
name='Container',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
('continer_id', models.CharField(max_length=512, null=True)),
('image_name', models.CharField(max_length=512)),
('created_at', models.CharField(max_length=512, null=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('details', models.CharField(max_length=512, null=True)),
('command', models.CharField(max_length=512, null=True)),
('hostname', models.CharField(max_length=512, null=True)),
('volumes', models.CharField(max_length=512, null=True)),
('environment', models.CharField(max_length=512, null=True)),
('state', models.CharField(max_length=20, null=True)),
('continer_ip', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='service.IpInfo')),
('host', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='agent.Agent')),
],
),
]
<file_sep># -*- coding: utf-8 -*-
from rest_framework import serializers
from service.models import Service, Container
from django.contrib.auth.models import User
from models import Image
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
class ServiceSerializer(serializers.ModelSerializer):
# username = serializers.CharField(source='app_info.username')
# region = serializers.CharField(source='app_info.region_info')
class Meta:
model = Service
fields = ('service_name', 'instance_amount', 'image_name', 'details')
def create(self):
return Service(**self.object)
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('name', 'project', 'repository', 'tag', 'registry')
class ContainerSerializer(serializers.ModelSerializer):
# username = serializers.CharField(source='app_info.username')
# region = serializers.CharField(source='app_info.region_info')
class Meta:
model = Container
fields = ('name', 'image_name', 'environment', 'created_at','hostname', 'command', 'volumes')
def create(self, validated_data):
return Container.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `Container` instance, given the validated data.
"""
instance.name = validated_data.get('name', instance.name)
instance.image_name = validated_data.get('image_name', instance.image_name)
instance.environment = validated_data.get('environment', instance.environment)
instance.hostname = validated_data.get('hostname', instance.hostname)
instance.command = validated_data.get('command', instance.command)
instance.volumes = validated_data.get('volumes', instance.volumes)
instance.state = validated_data.get('state', instance.state)
instance.save()
return instance
def is_exist(self, name):
if Container.objects.filter(name=name).exists():
return True
else:
return False
def update_agent(self, instance, agent):
instance.agent = agent
instance.save()
return instance
def get_obj(self, validated_data):
return Container.objects.get(**validated_data)
<file_sep>import docker
SWARM_URL = '10.6.168.160:2376'
swarm_client = docker.Client(base_url='tcp://{}'.format(SWARM_URL), timeout=60)
def search_host_info(container_name):
mapping = {}
a = swarm_client.containers()
for b in a:
# print b
host_name = b.get('Names')[0].split('/')[1]
server_name = b.get('Names')[0].split('/')[2]
mapping[server_name] = host_name
print host_name
print server_name
host_name = mapping.get(container_name)
print host_name
try:
host = Agent.objects.get(host_name=host_name)
except:
return None
return host
if __name__ == '__main__':
search_host_info('zz')<file_sep>"""weitac_gateway URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from service.views import ImageViewSet, ContainerViewSet
from django.conf.urls import url
from django.contrib import admin
from job.views import JobViewSet, PeriodictaskViewSet
from configuration.views import ConfigurationViewSet
from agent.views import Agent_views, agent_manage
from login import views as login_views
from job import views as job_views
from job.views import JobViewSet
from configuration import views as configuration_views
from monitor.views import MonitorViewSet
APP_URL_REGEX = '[A-Za-z0-9-_.]+'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', login_views.index, name='index'),
url(r'^index/$', login_views.index, name='index'),
url(r'^login/$', login_views.login, name='login'),
url(r'^logout/$', login_views.logout, name='logout'),
# API for container
url(r'^create_container/$',
ContainerViewSet.as_view({'post': 'create_container',
'get': 'create_container'})),
url(r'^container_manage/$',
ContainerViewSet.as_view({'post': 'deal_containers',
'get': 'list_containers'})),
# API for image
url(r'^image_manage/$',
ImageViewSet.as_view({'get': 'list_images'})),
url(r'^image/$',
ImageViewSet.as_view({'get': 'get_project',
'post': 'update_image'})),
url(r'^image/(?P<project>{})/?$'.format(APP_URL_REGEX),
ImageViewSet.as_view({'get': 'get_repository'})),
url(r'^image/(?P<project>{})/(?P<repository>{})/?$'.format(APP_URL_REGEX, APP_URL_REGEX),
ImageViewSet.as_view({'get': 'get_tag'})),
url(r'^update_image/$',
ImageViewSet.as_view({'post': 'update_image'})),
# API for job
url(r'^job_manage/$',
JobViewSet.as_view({'post': 'job_manage',
'get': 'job_manage'})),
# url(r'^job_upload/$',
# JobViewSet.as_view({'get': 'job_upload',
# 'post': 'job_upload'})),
url(r'^job_upload/$', job_views.job_upload, name='job_upload'),
url(r'^job_run/$',
JobViewSet.as_view({'get': 'job_run',
'post': 'job_run'})),
url(r'^job_result/$',
JobViewSet.as_view({'get': 'job_result',
'post': 'job_result'})),
url(r'^job_periodictask/$',
JobViewSet.as_view({'get': 'job_periodictask',
'post': 'deal_periodictask'})),
url(r'^periodictask/?',
PeriodictaskViewSet.as_view({'post': 'create_periodictask',
'put': 'update_periodictask',
'delete': 'delete_periodictask',
'get': 'get_periodictasks',
})),
# API for configuration
url(r'^configuration_manage/$', configuration_views.configuration_manage, name='configuration_manage'),
url(r'^configuration_upload/$', configuration_views.configuration_upload, name='configuration_upload'),
url(r'^configuration_update/$', configuration_views.configuration_update, name='configuration_update'),
# url(r'^configuration/$', 'configurations.views.configuration_update'),
url(r'^configuration/?',
ConfigurationViewSet.as_view({'get': 'get_configuration',
'post': 'upload_configuration',
'put': 'update_configuration',
'delete': 'delete_configuration'})),
# API for agent
url(r'^agent_manage/$', agent_manage, name='agent_manage'),
url(r'^registry/$',
Agent_views.as_view({'post': 'register_agent'})),
# API for monitor
url(r'^create_monitor/$',
MonitorViewSet.as_view({'post': 'create_monitor',
'get': 'create_monitor'})),
url(r'^monitor_manage/$',
MonitorViewSet.as_view({'post': 'delete_monitor',
'get': 'list_monitor'})),
]
<file_sep># -*-coding: utf-8 -*-
import os
# from psycopg2.extras import MinTimeLoggingConnection
import argparse
import datetime
# parser = argparse.ArgumentParser()
# DEFAULTDATE = datetime.datetime.now()
# parser.add_argument("-t", "--type",
# help='usage type.eg app,volume,networking',
# default="app")
# parser.add_argument("-d", "--date",
# help='billing date',
# default='{}-{}-{}'.format(DEFAULTDATE.year, DEFAULTDATE.month, DEFAULTDATE.day))
# parser.add_argument("-e", "--environment",
# help="set environment",
# default='mathilde.settings')
# args = parser.parse_args()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weitac_gateway.settings')
import sys
sys.path.append("../")
import django
django.setup()
from service.models import Service
# from celery.backends.database import Task,TaskSet
from djcelery import models as celery_models
from rest_framework import viewsets
al=celery_models.PeriodicTask.objects.all()
# celery_models.PeriodicTask.ojects.get(name='add')
# a= TaskSet.objects.all()
for a in al:
# print a.name
print a.task
print a.enabled
#
# class CeleryViewSet(viewsets.ModelViewSet):
# def read(self, request, *args, **kwargs):
# try:
# task = celery_models.PeriodicTask.objects.get(name=self.TASK_NAME)
# if task.enabled:
# return {
# 'enabled': True,
# 'day_of_month': int(task.crontab.day_of_month),
# 'last_run_at': task.last_run_at if task.last_run_at else '0'
# }
# else:
# return {'enabled': False}
# except celery_models.PeriodicTask.DoesNotExist:
# return {'enabled': False}
#
# def create(self, request, *args, **kwargs):
# enabled = request.POST.get('enabled', None)
# if enabled not in [self.ENABLED_POST_VALUE, self.DISABLED_POST_VALUE]:
# return self.operate_fail('无效参数')
# if enabled == self.DISABLED_POST_VALUE:
# self.disable_task(self.TASK_NAME)
# return self.operate_success()
# else:
# try:
# day_of_month = int(request.POST.get('day_of_month', ''))
# if day_of_month > 28 or day_of_month < 1:
# return self.operate_fail('日期必须在1-28日之间')
# task, created = celery_models.PeriodicTask.objects.get_or_create(name="monthly_reading",
# task="mrs_app.my_celery.tasks.monthly_reading_task")
# if created:
# crontab = celery_models.CrontabSchedule.objects.create(day_of_month=day_of_month,
# hour=0,
# minute=0)
# crontab.save()
# task.crontab = crontab
# task.enabled = True
# task.save()
# else:
# task.crontab.day_of_month = day_of_month
# task.crontab.save()
# task.enabled = True
# task.save()
# return self.operate_success()
# except ValueError:
# return self.operate_fail('抄表日不能为空')
#
#
# def disable_task(self, name):
# try:
# task = celery_models.PeriodicTask.objects.get(name=name)
# task.enabled = False
# task.save()
# return True
# except celery_models.PeriodicTask.DoesNotExist:
# return True
def read(request, *args, **kwargs):
try:
task = celery_models.PeriodicTask.objects.get(name=TASK_NAME)
if task.enabled:
return {
'enabled': True,
'day_of_month': int(task.crontab.day_of_month),
'last_run_at': task.last_run_at if task.last_run_at else '0'
}
else:
return {'enabled': False}
except celery_models.PeriodicTask.DoesNotExist:
return {'enabled': False}
def create(self, request, *args, **kwargs):
enabled = request.POST.get('enabled', None)
if enabled not in [self.ENABLED_POST_VALUE, self.DISABLED_POST_VALUE]:
return self.operate_fail('无效参数')
if enabled == self.DISABLED_POST_VALUE:
self.disable_task(self.TASK_NAME)
return self.operate_success()
else:
try:
day_of_month = int(request.POST.get('day_of_month', ''))
if day_of_month > 28 or day_of_month < 1:
return self.operate_fail('日期必须在1-28日之间')
task, created = celery_models.PeriodicTask.objects.get_or_create(name="monthly_reading",
task="mrs_app.my_celery.tasks.monthly_reading_task")
if created:
crontab = celery_models.CrontabSchedule.objects.create(day_of_month=day_of_month,
hour=0,
minute=0)
crontab.save()
task.crontab = crontab
task.enabled = True
task.save()
else:
task.crontab.day_of_month = day_of_month
task.crontab.save()
task.enabled = True
task.save()
return self.operate_success()
except ValueError:
return self.operate_fail('抄表日不能为空')
def disable_task(self, name):
try:
task = celery_models.PeriodicTask.objects.get(name=name)
task.enabled = False
task.save()
return True
except celery_models.PeriodicTask.DoesNotExist:
return True<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-20 09:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('service', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='instance',
name='host',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='agent.Agent'),
),
migrations.DeleteModel(
name='Agent',
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-09 03:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Agent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('host_name', models.CharField(max_length=20)),
('host_ip', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Image',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
('project', models.CharField(max_length=512)),
('repository', models.CharField(max_length=512)),
('tag', models.CharField(max_length=512)),
('registry', models.CharField(default='docker.weitac.com', max_length=512)),
],
),
migrations.CreateModel(
name='Instance',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
('instance_id', models.CharField(max_length=20, null=True)),
('continer_id', models.CharField(max_length=512, null=True)),
('created_at', models.CharField(max_length=512, null=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('details', models.CharField(max_length=512, null=True)),
('command', models.CharField(max_length=512, null=True)),
('hostname', models.CharField(max_length=512, null=True)),
('volumes', models.CharField(max_length=512, null=True)),
('environment', models.CharField(max_length=512, null=True)),
('state', models.CharField(max_length=20, null=True)),
],
),
migrations.CreateModel(
name='IpInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('address', models.CharField(max_length=20)),
('is_used', models.BooleanField(default=False)),
('gateway_ip', models.CharField(max_length=20)),
('subnet_mask', models.CharField(default=24, max_length=20)),
],
),
migrations.CreateModel(
name='Service',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('service_name', models.CharField(max_length=512)),
('instance_amount', models.IntegerField()),
('image_name', models.CharField(max_length=512)),
('created_at', models.CharField(max_length=512, null=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('details', models.CharField(max_length=512, null=True)),
('finished_at', models.IntegerField(default=0)),
],
),
migrations.AddField(
model_name='instance',
name='continer_ip',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='service.IpInfo'),
),
migrations.AddField(
model_name='instance',
name='host',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='service.Agent'),
),
migrations.AddField(
model_name='instance',
name='service',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='service.Service'),
),
]
<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.response import Response
from rest_framework import viewsets
# from models import Service, Instance, Agent
import logging
import requests
import docker
# from docker import utils as docker_utils
import time
from django.utils import timezone
from service.serializers import ServiceSerializer
from utils import service_DBclient
from django.shortcuts import render_to_response
from job.views import call_agent_change_ip
from django.http import HttpRequest, QueryDict
from django.contrib.auth.decorators import login_required
from rest_framework.parsers import JSONParser, FormParser
# from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework import permissions
import datetime
import base64
from django.http import HttpResponse
import json
import json
from django.core.serializers.json import DjangoJSONEncoder
# Create your views here.
def event_handle(request):
instance_name = request.GET.get('instance_name')
print request
# if request.method == 'POST':
# ips = request.POST
# info_dic = {}
return HttpResponse("success", status=status.HTTP_200_OK)
<file_sep># -*-coding: utf-8 -*-
import datetime
import json
from djcelery import models as celery_models
from django.utils import timezone
from celery import task
def create_task(name, task, task_args, crontab_time):
'''
创建任务
name # 任务名字
task # 执行的任务 "myapp.tasks.add"
task_args # 任务参数 {"x":1, "Y":1}
crontab_time # 定时任务时间 格式:
{
'month_of_year': 9 # 月份
'day_of_month': 5 # 日期
'hour': 01 # 小时
'minute':05 # 分钟
}
'''
# task任务, created是否定时创建
task, created = celery_models.PeriodicTask.objects.get_or_create(
name=name,
task=task)
# 获取 crontab
crontab = celery_models.CrontabSchedule.objects.filter(
**crontab_time).first()
if crontab is None:
# 如果没有就创建,有的话就继续复用之前的crontab
crontab = celery_models.CrontabSchedule.objects.create(
**crontab_time)
task.crontab = crontab # 设置crontab
task.enabled = True # 开启task
task.kwargs = json.dumps(task_args) # 传入task参数
expiration = timezone.now() + datetime.timedelta(day=1)
task.expires = expiration # 设置任务过期时间为现在时间的一天以后
task.save()
return True
def disable_task(name):
'''
关闭任务
'''
try:
task = celery_models.PeriodicTask.objects.get(name=name)
task.enabled = False # 设置关闭
task.save()
return True
except celery_models.PeriodicTask.DoesNotExist:
return True
@task()
def delete():
'''
删除任务
从models中过滤出过期时间小于现在的时间然后删除
'''
return celery_models.PeriodicTask.objects.filter(
expires__lt=timezone.now()).delete()
|
19f487b977c05ed60935b157210311d8c8c361a3
|
[
"Markdown",
"Makefile",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 47
|
Python
|
xiaoyaosheng/weitac_gateway
|
7168dd1c35975caf9e44c915dff6cf6e304e2474
|
39e1c28c491486efc8d30ee108c30fe6592172bd
|
refs/heads/master
|
<repo_name>helloworld466/sonarqube-project2<file_sep>/sonar-project.properties
sonar.projectKey=Final
sonar.projectName=Final
sonar.projectVersion=1.0
sonar.sources=.
sonar.sourceEncoding=UTF-8
sonar.host.url=http://172.24.125.69:9080
sonar.projectBaseDir=/var/lib/jenkins/workspace/sample
<file_sep>/README.md
# sonarqube-project2
Final repo for project
<file_sep>/src/main/java/com/mycompany/helloworld1/HelloWorld.java
package com.mycompany.helloworld1;
public class HelloWorld {
private String hello;
private String world;
HelloWorld(){
hello = "Hello";
world = "World";
}
public String fromMessage(){
String message;
message = hello + " " + world;
return message;
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
System.out.println(helloWorld.fromMessage());
}
}
|
d3de2773fbf3063cc370627960c3e9d8e7f5f1e2
|
[
"Markdown",
"Java",
"INI"
] | 3
|
INI
|
helloworld466/sonarqube-project2
|
bd2e477bb4cf273e3b4b4a0b76d2179f6754251a
|
5e7e22fb28e088153a2c912dd4216014e82c2b21
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from './core/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
isAuth: boolean = false;
constructor(private auth: AuthService) { }
ngOnInit() {
this.auth.authState().subscribe(res => {
this.isAuth = !!res && !!res.email
})
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { MEvent } from '../types/m-event';
import { Observable } from '@firebase/util';
@Injectable({
providedIn: 'root'
})
export class EventService {
private EventsCollection: AngularFirestoreCollection<MEvent>
events: Observable<MEvent[]>
event: Observable<MEvent>
constructor(private afs: AngularFirestore) {
this.afs.firestore.settings({timestampsInSnapshots: true})
}
create(newEvent: Partial<MEvent>): Promise<void> {
console.log("Event", newEvent)
return this.afs.collection('events').doc<Partial<MEvent>>(newEvent.name.replace(' ', '-')).set(newEvent)
}
get(id: string) {
return this.afs.collection('events').doc<MEvent>(id).valueChanges()
}
update(id: string, newEvent: Partial<MEvent>): Promise<void> {
return this.afs.collection('events').doc(id).update(newEvent)
}
delete(id: string): Promise<void> {
return this.afs.collection('events').doc<MEvent>(id).delete()
}
checkIn(userId: string) {
console.log('not implemented')
}
checkOut(userId: string) {
console.log('not implemented')
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Router, Resolve, ParamMap, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MEvent } from '../types/m-event';
import { Observable } from '@firebase/util';
import { EventService } from '../core/event.service';
@Injectable({
providedIn: 'root'
})
export class EventResolverService implements Resolve<MEvent> {
constructor(private eventDB: EventService, private router: Router) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let eventId = route.paramMap.get('id');
return this.eventDB.get(eventId)
.map((res: MEvent) => {
if (res) return res
this.router.navigate(['/events'])
return null
})
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { CreateEventComponent } from './create-event/create-event.component';
import { EventsComponent } from './events/events.component';
import { ProfileComponent } from './profile/profile.component';
import { ExploreComponent } from './explore/explore.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: '', pathMatch: 'full', redirectTo: 'home' },
{ path: 'create-event', component: CreateEventComponent },
{ path: 'events', component: EventsComponent },
{ path: 'event/:id', loadChildren: './event/event.module#EventModule' },
{ path: 'explore', component: ExploreComponent },
{ path: 'profile', component: ProfileComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class RoutingModule { }<file_sep>import { Component } from '@angular/core';
import { AuthService } from "../core/auth.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(private auth: AuthService) { }
signIn() {
this.auth.googleSignIn().then(res => {
console.log(res.user, res.additionalUserInfo)
})
.catch(err => {
console.warn(err)
})
.then(() => {
this.auth.authState().subscribe(res => {
console.log("AuthState", res)
})
})
}
logOut() {
this.auth.logOut()
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EventRoutingModule } from "./event-routing.module";
import { NgMaterialModule } from '../core/ng-material/ng-material.module';
import { EventComponent } from './event/event.component';
import { ChatComponent } from './chat/chat.component';
import { ChatMessageComponent } from './event/chat-message.component';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
NgMaterialModule,
FormsModule,
EventRoutingModule,
],
declarations: [EventComponent, ChatComponent, ChatMessageComponent]
})
export class EventModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../core/auth.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
messages: any[] = []
userId: string
message: string = ""
constructor(private auth: AuthService) { }
checkForEnter(e: KeyboardEvent) {
if (e.key === "Enter") this.sendMessage()
}
sendMessage() {
let message = this.message.trim()
if (message) {
console.log(message)
this.messages.push({ userId: this.userId, message })
this.message = ""
}
}
ngOnInit() {
this.auth.authState().subscribe(user => {
this.userId = user.uid
})
}
}
<file_sep>import { NgModule } from '@angular/core';
import {
MatButtonModule,
MatCheckboxModule,
MatSidenavModule,
MatToolbarModule,
MatIconModule,
MatListModule,
MatDividerModule,
MatCardModule,
MatExpansionModule,
MatDatepickerModule,
MatFormFieldModule,
MatNativeDateModule,
MatInputModule,
MatStepperModule,
MatSnackBarModule,
MatProgressBarModule,
MatChipsModule
} from '@angular/material';
const MATERIAL_MODULES = [
MatButtonModule,
MatCheckboxModule,
MatSidenavModule,
MatToolbarModule,
MatIconModule,
MatListModule,
MatExpansionModule,
MatDatepickerModule,
MatFormFieldModule,
MatInputModule,
MatNativeDateModule,
MatCardModule,
MatDividerModule,
MatStepperModule,
MatDatepickerModule,
MatSnackBarModule,
MatProgressBarModule,
MatChipsModule,
]
@NgModule({
imports: [
MATERIAL_MODULES
],
exports: [
MATERIAL_MODULES
],
})
export class NgMaterialModule { }<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
// import { EventModule } from './event/event.module';
import { RoutingModule } from "./app-router.module";
import { CoreModule } from "./core/core.module";
import { environment } from '../environments/environment';
import { HomeComponent } from './home/home.component';
import { CreateEventComponent } from './create-event/create-event.component';
import { EventsComponent } from './events/events.component';
import { ProfileComponent } from './profile/profile.component';
import { ExploreComponent } from './explore/explore.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
CreateEventComponent,
EventsComponent,
ProfileComponent,
ExploreComponent,
],
imports: [
BrowserModule,
RoutingModule,
NoopAnimationsModule,
AngularFireModule.initializeApp(environment.firebase, 'ashinzekene-meet-me'),
AngularFireAuthModule,
AngularFirestoreModule,
// EventModule,
CoreModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { MUser } from '../types/m-user';
import { UserService } from '../core/user.service';
import { MatSnackBar } from '@angular/material';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Partial<MUser> = {}
isCreating: boolean = false
constructor(private auth: AuthService, private userDB: UserService, private snackbar: MatSnackBar) { }
async updateProfile() {
if (this.isCreating) {
return
}
this.isCreating = true
try {
await this.userDB.create(this.user)
this.snackbar.open("Updated your profile", "Done", {
duration: 3000
})
} catch (err) {
console.log("Could not update", err)
}
this.isCreating = false
}
ngOnInit() {
let duser: Partial<MUser> = {}
this.auth.authState().switchMap(user => {
let { email, emailVerified, uid, displayName, photoURL } = user
duser.email = email
duser.emailVerified = emailVerified
duser.displayName = displayName
duser.photoURL = photoURL
duser.uid = uid
return this.userDB.get(user.uid)
})
.subscribe(dbUser => {
this.user = !!dbUser ? { ...duser, ...dbUser } : duser
})
}
}<file_sep>/*
* Public API Surface of angular-media-query
*/
export * from './lib/angular-media-query.service';
export * from './lib/angular-media-query.component';
export * from './lib/angular-media-query.module';
<file_sep>import { NgModule } from '@angular/core';
import { AngularMediaQueryComponent } from './angular-media-query.component';
@NgModule({
imports: [
],
declarations: [AngularMediaQueryComponent],
exports: [AngularMediaQueryComponent]
})
export class AngularMediaQueryModule { }
<file_sep>import { NgModule } from '@angular/core';
import { NgMaterialModule } from "./ng-material/ng-material.module";
import { CommonModule } from "@angular/common";
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MainComponent } from "./main/main.component";
import { AuthService } from './auth.service';
import { UserService } from './user.service';
import { EventService } from './event.service';
import { TimeValidatorDirective } from "./time-validator.directive";
@NgModule({
imports: [NgMaterialModule, CommonModule, FormsModule, ReactiveFormsModule],
exports: [NgMaterialModule, CommonModule, FormsModule, ReactiveFormsModule],
declarations: [MainComponent, TimeValidatorDirective],
providers: [AuthService, UserService, EventService],
})
export class CoreModule { }
<file_sep>import { UserInfo } from "firebase";
export interface MUser extends UserInfo {
githubUsername?: string
facebookUsername?: string
url?: string
phone?: string
emailVerified?: boolean
}<file_sep>import { MUser } from "./m-user";
export type MEvent = {
name: string
description: string
tagline: string
startDate: Date
startTime: string
endTime: string
imageUrl: string
location: string
endDate?: Date
checkedInUsers?: MUser[]
}<file_sep>import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn } from '@angular/forms';
@Directive({
selector: '[appTimeValidator]',
providers: [{ provide: NG_VALIDATORS, useExisting: TimeValidatorDirective }]
})
export class TimeValidatorDirective implements Validator {
@Input('appTimeValidator') test: string
validate(control: AbstractControl): { [key: string]: any } {
return timeValidator()
}
}
function timeValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
let hm: Array<string> = control.value.split(':')
try {
let hmNum: Array<number> = hm.map(parseInt)
if (hmNum.length !== 2) {
return { 'wrong-time': { value: control.value } }
}
if (hmNum[0] > 12) {
return { 'wrong-time': { value: control.value } }
}
if (hmNum[1] > 59) {
return { 'wrong-time': { value: control.value } }
}
} catch (err) {
return { 'wrong-time': { value: control.value } }
}
return null
};
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { MUser } from '../types/m-user';
import { Observable } from '@firebase/util';
@Injectable({
providedIn: 'root'
})
export class UserService {
private UsersCollection: AngularFirestoreCollection<MUser>
users: Observable<MUser[]>
user: Observable<MUser>
constructor(private afs: AngularFirestore) {
this.afs.firestore.settings({timestampsInSnapshots: true})
}
create(user: Partial<MUser>): Promise<void> {
return this.afs.collection('users').doc(user.uid).set(user)
}
get(uid: string) {
return this.afs.collection('users').doc<MUser>(uid).valueChanges()
}
update(uid: string, user: Partial<MUser>): Promise<void> {
return this.afs.collection('users').doc<MUser>(uid).update(user)
}
delete(uid: string): Promise<void> {
return this.afs.collection('users').doc<MUser>(uid).delete()
}
}
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { MEvent } from '../types/m-event';
import { EventService } from '../core/event.service';
import { MatSnackBar } from '@angular/material';
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-create-event',
templateUrl: './create-event.component.html',
styleUrls: ['./create-event.component.css']
})
export class CreateEventComponent implements OnInit, OnDestroy {
newEvent: Partial<MEvent> = {}
dateToday: Date = new Date()
minEndDate: Date = new Date()
startDateSubscription: any
isCreating: boolean = false
constructor(private eventDB: EventService, private snackbar: MatSnackBar, private router: Router) { }
ngOnInit() {
this.startDateSubscription = Observable.of(this.newEvent.startDate)
.subscribe(dt => {
this.minEndDate = dt || this.dateToday
})
}
async createEvent() {
if (this.isCreating) {
return
}
this.isCreating = true
try {
await this.eventDB.create(this.newEvent)
this.snackbar.open("Event Created successfully", "Done", {
duration: 2000
})
this.router.navigate(['/events'])
} catch (err) {
this.snackbar.open("Could not create event", "Done", {
duration: 2000
})
console.log(err)
}
this.isCreating = false
}
ngOnDestroy() {
this.startDateSubscription.unsubscribe()
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private afAuth: AngularFireAuth) {}
googleSignIn() {
return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
}
emailSignup({ email, password }) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
}
emailLogin({ email, password }) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
}
logOut() {
return this.afAuth.auth.signOut()
}
authState() {
return this.afAuth.authState
}
updateUser(user) {
return this.afAuth.auth.updateCurrentUser(user)
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'chat-message',
styles: [`
`],
template: `
<mat-chip-list>
<mat-chip *ngIf="isUser; else notUserContent" [color]="primary" selected="true">
<ng-content></ng-content>
</mat-chip>
<ng-template #notUserContent>
<mat-chip [color]="accent" selected="true">
<ng-content></ng-content>
</mat-chip>
</ng-template>
</mat-chip-list>
`
})
export class ChatMessageComponent implements OnInit {
@Input() isUser: boolean = false
constructor() { }
ngOnInit() { }
}
|
1f267de78918679f03a4cf7cbb872ff6028e231c
|
[
"TypeScript"
] | 20
|
TypeScript
|
ashinzekene/meet-me
|
996d34fd31acc14cc055dcdb3f1e85fb0f36b91f
|
4a28a3eaa1e579735759d90b1b5fab36016bbcf6
|
refs/heads/master
|
<repo_name>uit-no/hpc-doc<file_sep>/applications/chemistry/Dalton/firsttime_dalton.rst
.. _first_time_dalton:
================================
First time you run a Dalton job?
================================
This page contains info aimed at first time
users of Dalton on Stallo. Please look carefully through the
provided examples. Also note that the job-script example is rather richly
commented to provide additional and relevant info.
If you want to run this testjob, copy the input example and the job script example shown below
into your test job folder (which I assume you have created in advance).
Dalton needs one molecule file and one input file. For simplicity, we have tarred them together and you
may download them here: :download:`Dalton files<../files/dalton_example_files.tar.gz>`
Molcas runscrip example
-----------------------
.. include:: ../files/job_dalton.sh
:literal:
You can also download the runscript file here: :download:`Dalton run script<../files/job_dalton.sh>`
The runscript example and the input are also on Stallo
------------------------------------------------------
Type:
.. code-block:: bash
cd <whatever_test_folder_you_have> # For instance testdalton
cp -R /global/hds/software/notur/apprunex/dalton/* .
When you have all the necessary files in the correct folders, submit the job by typing:
.. code-block:: bash
sbatch job_dalton.sh
Good luck.
<file_sep>/applications/chemistry/ORCA/ORCA.rst
.. _ORCA:
====
ORCA
====
Some users have requested an installation of the ORCA quantum chemistry program
on Stallo. Unfortunately, ORCA does not come with a computer center license,
which basically means that we cannot easily install it globally on Stallo.
However, the code is free of charge and available for single users or at
research group level, provided compliance with the *ORCA End User License
Agreement*. This means that interested users can download the precompiled
executables from the ORCA web page themselves, and run the code on Stallo.
* Homepage: https://orcaforum.kofo.mpg.de
Installation
============
The following has been tested for version 4.2.1 on Stallo:
1) Go to the ORCA forum page and register as user
2) Wait for activation e-mail (beware of spam filters...)
3) Log in and click on **Downloads** in the top menu
4) Download the Linux x86-64 complete archive and place it somewhere in your home folder
5) Extract the tarball: ``$ tar xf orca_4_2_1_linux_x86-64_openmpi314.tar.xz``
6) The ``orca`` executable is located in the extracted archive and should work out of the box
Usage
=====
In order to run ORCA in parallel the OpenMPI module must be loaded, and it is
important to use the **full path** to the executable
.. code-block:: bash
$ module load OpenMPI/3.1.3-GCC-8.2.0-2.31.1
$ /full/path/to/orca orca.inp >orca.out
Note that the calculation should not be launched by ``mpirun``, but you should use
the input keyword ``nprocs``. A very simple example input file is provided below.
Please refer to the ORCA manual (can be downloaded from the same download page
on the ORCA forum) for details on how to run the code for your application.
ORCA input example
------------------
.. include:: ../files/orca.inp
:literal:
<file_sep>/applications/chemistry/Gaussian/GaussView.rst
=========
GaussView
=========
Gaussview is a visualization program that can be used to open Gaussian output
files and checkpoint files (.chk) to display structures, molecular orbitals,
normal modes, etc. You can also set up jobs and submit them directly.
Official documentation: https://gaussian.com/gaussview6/
GaussView on Stallo
-------------------
To load and run GaussView on Stallo, load the relevant Gaussian module, and
then call GaussView::
$ module avail Gaussian
$ module load Gaussian/g16_B.01
$ gview
<file_sep>/applications/chemistry/TURBOMOLE/run_turbo.rst
.. _turbomole_example:
==========================
TURBOMOL runscript example
==========================
.. include:: ../files/job_turbo.sh
:literal:
TURBOMOL example on Stallo
--------------------------
The above runscript can be found on Stallo along with the necessary input files
to perform a simple DFT calculation. To get access to the examples directory,
load the ``notur`` module
.. code-block:: bash
$ module load notur
$ cp -r /global/hds/software/notur/apprunex/TURBOMOLE .
From this directory you can submit the example script (you need to specify a
valid account in the script first)
.. code-block:: bash
$ sbatch job_turbo.sh
The calculation should take less than 2 min, but may spend much more than this
in the queue. Verify that the output file ``dscf.out`` ends with
.. code-block:: bash
**** dscf : all done ****
Please refer to the TURBOMOLE manual for how to setup different types of
calculations.
<file_sep>/applications/chemistry/ADF/advanced.rst
.. _adf_advanced:
==============================
Information for advanced users
==============================
Scaling behaviour
-----------------
Since ADF is a very complex code, able to solve a vast range of chemistry problems - giving a unified advice regarding scaling is difficult. We will try to inspect scaling behaviour related to most used areas of application. For a standard geometry optimization, it seems to scale well in the region of 4-6 full nodes (60-100 cores) at least. For linear transit we would currently stay at no more than 4 full nodes or less currently.Unless having tests indicating otherwise, users who want to run large jobs should allocate no more than the prescribed numbers of processors. More information will come.
Memory allocation
-----------------
On Stallo there are 32 GB and 128GB nodes. Pay close attention to memory usage of job on the nodes where you run, and if necessary redistribute the job so that it uses less than all cores on the node until the limit of 32 GB/core. More than that, you will need to ask for access to the highmem-queue. As long as you do not ask for more than 2 GB/core, using the pmem-flag for torque does in principle give no meaning.
How to restart an ADF job
-------------------------
#. In the directory where you started your job, rename or copy the job-output t21 file into $SCM_TMPDIR/TAPE21.
#. In job.inp file, put RESTART TAPE21 just under the comment line.
#. Submit job.inp file as usual.
This might also be automized, we are working on a solution for restart after unexpected downtime.
How to run ADF using fragments
------------------------------
This is a brief introduction to how to create fragments necessary for among other things, BSSE calculations and proper broken symmetry calculations.
**Running with fragments:**
* Download and modify script for fragment create run, e.g. this template: Create.TZP.sh (modify ACCOUNT, add desired atoms and change to desired basis and desired functional)
* Run the create job in the same folder as the one where you want to run your main job(s) (sbatch Create.TZP.sh).
* Put the line cp $init/t21.* . in your ADF run script (in your $HOME/bin directory)
* In job.inp, specify correct file name in FRAGMENT section, e.g. “H t21.H_tzp”. * Submit job.inp as usual.
Running with fragments is only necessary when you want to run a BSSE calculations or manipulate charge and/or atomic mass for a given atom (for instance modeling heavy isotope labelled samples for frequency calculations).
<file_sep>/news/news.rst
.. figure:: tag.jpg
:scale: 57 %
Found in Via Notari, Pisa; (c) <NAME>.
.. _news:
News and notifications
======================
News about planned/unplanned downtime, changes in hardware, and important
changes in software will be published on the HPC UiT twitter account
`<https://twitter.com/hpc_uit>`_ and on the login screen of stallo.
For more information on the different situations see below.
System status and activity
--------------------------
You can get a quick overview of the system load on Stallo on the
`Sigma2 hardware page <https://www.sigma2.no/hardware/status>`_.
More information on the system load, queued jobs, and node states can
be found on the `jobbrowser page <http://stallo-login2.uit.no/slurmbrowser/html/squeue.html>`_
(only visible from within the UiT network).
Planned/unplanned downtime
--------------------------
In the case of a planned downtime, a reservation will be made in the
queuing system, so new jobs, that would not finish until the downtime,
won't start. If the system goes down, running jobs will be restarted,
if possible. We apologize for any inconveniences this may cause.
<file_sep>/help/hpc-qa-sessions.rst
Open Question & Answer Sessions for All Users
=============================================
Learn new tricks and ask & discuss questions
--------------------------------------------
Meet the HPC staff, discuss problems and project ideas, give feedback or suggestions on how to improve services, and get advice for your projects.
Join us on `Zoom <https://uit.zoom.us/j/65284253551>`_, get yourself a coffee or tea and have a chat. It doesn’t matter from which institute or university you are, you are **welcome to join at any time**.
This time we will start with a **short seminar about “Helpful Tools & Services we offer you might not know about”**.
Afterwards we have the open question and answer session.
We can talk about:
- Problems/questions regarding the Stallo/Vilje shutdown and migration
- Questions regarding data storage and management
- Help with programming and software management
- Help with project organization and data management
- Anything else
If you think you might have a challenging question or topics for us, you can also send them to us before, so we can come prepared and help you better. If you have general or specific questions about the event: <EMAIL>
Next event
-------------
- **2020-10-13, 13:00 - 15:00**, `online Zoom meeting <https://uit.zoom.us/j/65284253551>`_
Past events
+++++++++++
- 2020-10-10, 13:00 - 15:00, online Zoom meeting
- 2020-04-23, 13:00 - 15:00, online Zoom meeting
- 2020-02-19, 10:00 - 12:00, `main kantina <http://bit.ly/36Fhd9y>`_
- 2019-11-12, 14:00 - 16:00, `main kantina <http://bit.ly/36Fhd9y>`_
- 2019-09-11, 10:00 - 12:30, MH bygget atrium
Similar events which serve as inspiration
+++++++++++++++++++++++++++++++++++++++++
- https://scicomp.aalto.fi/news/garage.html
- https://openworking.wordpress.com/2019/02/04/coding-problems-just-pop-over/
<file_sep>/applications/chemistry/Gaussian/job-example.rst
====================
Gaussian job example
====================
To run this example create a directory, step into it, create the input file and submit the script with::
$ sbatch gaussian-runscript.sh
Input example
-------------
Direct download link: :download:`input example <example.com>`
.. literalinclude:: example.com
:language: none
Runscript example
-----------------
Direct download link: :download:`runscript example <gaussian-runscript.sh>`
.. literalinclude:: gaussian-runscript.sh
:language: bash
<file_sep>/applications/chemistry/Gaussian/gaussian-runscript.sh
#!/bin/bash -l
#SBATCH --account=nn....k
#SBATCH --job-name=example
#SBATCH --output=example.log
# Stallo nodes have either 16 or 20 cores: 80 is a multiple of both
#SBATCH --ntasks=80
# make sure no other job runs on the same node
#SBATCH --exclusive
# syntax is DD-HH:MM:SS
#SBATCH --time=00-00:30:00
# allocating 30 GB on a node and leaving a bit over 2 GB for the system
#SBATCH --mem-per-cpu=1500MB
################################################################################
# no bash commands above this line
# all sbatch directives need to be placed before the first bash command
# name of the input file without the .com extention
input=example
# flush the environment for unwanted settings
module --quiet purge
# load default program system settings
module load Gaussian/g16_B.01
# set the heap size for the job to 20 GB
export GAUSS_LFLAGS2="--LindaOptions -s 20000000"
# split large temporary files into smaller parts
lfs setstripe –c 8 .
# create scratch space for the job
export GAUSS_SCRDIR=/global/work/${USER}/${SLURM_JOB_ID}
tempdir=${GAUSS_SCRDIR}
mkdir -p ${tempdir}
# copy input and checkpoint file to scratch directory
cp ${SLURM_SUBMIT_DIR}/${input}.com ${tempdir}
if [ -f "${SLURM_SUBMIT_DIR}/${input}.chk" ]; then
cp ${SLURM_SUBMIT_DIR}/${input}.chk ${tempdir}
fi
# run the code
cd ${tempdir}
time g16.ib ${input}.com > ${input}.out
# copy output and checkpoint file back
cp ${input}.out ${SLURM_SUBMIT_DIR}
cp ${input}.chk ${SLURM_SUBMIT_DIR}
# remove the scratch directory after the job is done
# cd ${SLURM_SUBMIT_DIR}
# rm -rf /global/work/${USER}/${SLURM_JOB_ID}
exit 0
<file_sep>/applications/chemistry/Dalton/Dalton.rst
.. _Dalton:
======
Dalton
======
Related information
===================
.. toctree::
:maxdepth: 1
firsttime_dalton.rst
General information
===================
Description
-----------
Dalton is an ab initio quantum chemistry computer program. It is capable of calculating various molecular properties using the Hartree-Fock, MP2, MCSCF and coupled cluster theories. Dalton also supports density functional theory calculations.
Online information from vendor
------------------------------
* Homepage: http://daltonprogram.org/
* Documentation: http://daltonprogram.org/documentation/
* For download: http://daltonprogram.org/download/
License and access policy
-------------------------
Dalton is licensed under the GPL 2. That basically means that everyone may freely use the program.
Citation
--------
When publishing results obtained with the referred software referred, check the following page to find the correct citation(s): http://daltonprogram.org/citation/
Usage
=====
You load the application by typing:
.. code-block:: bash
module load Dalton/2016-130ffaa0-intel-2017a
For more information on available versions of Dalton, type:
.. code-block:: bash
module avail Dalton
<file_sep>/applications/physics/COMSOL/firsttime_comsol.rst
.. _first_time_comsol:
=================================
First time you run an COMSOL job?
=================================
This page contains info aimed at first time
users of COMSOL on Stallo, but may also be usefull to
more experienced users. Please look carefully through the
provided examples. Also note that the job-script example is rather richly
commented to provide additional and relevant info.
If you want to run this testjob, download the copies of the scripts and put them
into your test job folder (which I assume you have created in advance).
COMSOL input example
--------------------
The file used in this example can also downloaded here: :download:`Small test for COMSOL <../files/comsol_smalltest.mph>`.
Place this file in a job folder of choice, say COMSOLFIRSTJOB in your home directory on Stallo.
then, copy the job-script as seen here:
.. include:: ../files/run_comsol.sh
:literal:
(Can also be downloaded from here: :download:`run_comsol.sh <../files/run_comsol.sh>`)
Before you can submit a job, you need to know what "type" of study you want to perform (please read more about that on the vendor support page). For example purpose, I have chosed study 4 - named std04; and this is the second variable argument to the run script (see comments in script).
Place this script in the same folder and type:
.. code-block:: bash
sbatch run_comsol.sh comsol_smalltest std04
You may now have submitted your first COMSOL job.
Good luck with your (MULTI)physics!
<file_sep>/help/contact.rst
Contact
=======
If you need help, please file a support request via <EMAIL>, and
our local team of experts will try to assist you as soon as possible. Please
state in the email that the request is about Stallo.
.. image:: rtfm.png
Credit: https://xkcd.com/293/
Postal address
--------------
.. code-block:: none
Seksjon for digital forskningstjeneste/HPC
Nofima
Muninbakken 9-13
UiT Norges Arktiske Universitet
9037 Tromsø
Find us on `Mazemap <https://use.mazemap.com/?v=1&campusid=5&desttype=point&dest=18.97468,69.68186,3&zoom=17>`_
<file_sep>/applications/chemistry/TURBOMOLE/TURBOMOLE.rst
.. _TURBOMOLE:
============================
The TURBOMOLE program system
============================
Information regarding the quantum chemistry program system TURBOMOLE.
Related information
===================
.. toctree::
:maxdepth: 1
run_turbo.rst
General Information
===================
Description
-----------
TURBOMOLE is a quantum chemical program package, initially developed in the
group of Prof. Dr. <NAME> at the University of Karlsruhe and at the
Forschungszentrum Karlsruhe. In 2007, the TURBOMOLE GmbH (Ltd) was founded by
the main developers of the program, and the company took over the responsibility
for the coordination of the scientific development of the program, to which it
holds all copy and intellectual property rights.
Online info from vendor
-----------------------
* Homepage: http://www.turbomole-gmbh.com
* Documentation: http://www.turbomole-gmbh.com/turbomole-manuals.html
License information
-------------------
Sigma2 holds a national TURBOMOLE license covering all computing centers in Norway.
Citation
--------
When publishing results obtained with this software, please check with the
developers web page in order to find the correct citation(s).
TURBOMOLE on Stallo
===================
Usage
-----
To see which versions of TURBOMOLE are available
.. code-block:: bash
$ module avail turbomole
Note that the latest (as of May 2018) version 7.2 comes in three different
parallelization variants
* TURBOMOLE/7.2
* TURBOMOLE/7.2.mpi
* TURBOMOLE/7.2.smp
where the latter two correspond to the old separation between distributed memory
(mpi) and shared memory (smp) implementations that some users may know from
previous versions of the program. We recommend, however, to use the new hybrid
parallelization scheme (new in v7.2) provided by the ``TURBOMOLE/7.2`` module.
In order to run efficiently in hybrid parallel the SLURM setup must be correct
by specifying CPUs rather than tasks per node
.. code-block:: bash
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=20
i.e. do NOT specify ``--ntasks=40``. Also, some environment variables must be
set in the run script
.. code-block:: bash
export TURBOTMPDIR=/global/work/${USER}/${SLURM_JOBID}
export PARNODES=${SLURM_NTASKS}
export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}
See the TURBOMOLE example for more details.
NOTE: The new hybrid program (v7.2) will launch a separate server process in
addition to the requested parallel processes, so if you run e.g. on 20 cores
each on two nodes you will find one process consuming up to 2000% CPU on each
node plus a single process on the first node consuming very little CPU.
NOTE: We have found that the hybrid program (v7.2) runs efficiently only if
*full* nodes are used, e.i. you should always ask for ``--cpus-per-node=20``,
and scale the number of nodes by the size of the calculation.
<file_sep>/README.md
# HPC-services user documentation
Served via http://hpc-uit.readthedocs.org.
Copyright (c) 2020
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
<NAME>,
UiT The Arctic University of Norway.
## License
Text is licensed under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/),
code examples are provided under the [MIT](https://opensource.org/licenses/MIT) license.
## Locally building the HTML for testing
```
git clone https://github.com/uit-no/hpc-doc.git
cd hpc-doc
virtualenv venv
source venv/bin/activate
pip install sphinx
pip install sphinx_rtd_theme
sphinx-build . _build
```
Then point your browser to `_build/index.html`.
## Getting started with RST and Sphinx
- http://sphinx-doc.org/rest.html
- http://sphinx-doc.org/markup/inline.html#cross-referencing-arbitrary-locations
<file_sep>/stallo/uit-guidelines.rst
.. _guidelines:
Guidelines for use of computer equipment at the UiT The Arctic University of Norway
===================================================================================
Definitions
-----------
Explanation of words and expressions used in these guidelines.
users:
Every person who has access to and who uses the University's
computer equipment. This includes employees students and others who
are granted access to the computer equipment.
user contract:
Agreement between users and department(s) at the University who
regulate the user's right of access to the computer equipment. The
user contract is also a confirmation that these guidelines are
accepted by the user.
data:
All information that is on the computer equipment. This includes
both the contents of data files and software.
computer network:
Hardware and/or software which makes it possible to establish a
connection between two or more computer terminals. This includes
both private, local, national and international computer networks
which are accessible through the computer equipment.
breakdown:
Disturbances and abnormalities which prevent the user from
(stoppage) maximum utilization of the computer equipment.
computer equipment:
This includes hardware, software, data, services and computer
network.
hardware:
Mechanical equipment that can be used for data processing.
private data:
Data found in reserved or private areas or that are marked as
private. The data in a user's account is to be regarded as private
irrespective of the rights attached to the data.
resources:
Resources refers to the computer equipment including time and the
capacity available for the persons who are connected to the
equipment.
Purpose
-------
The purpose of these guidelines is to contribute towards the development of a
computer environment in which the potential provided by the computer equipment
can be utilized in the best possible way by the University and by society at
large. This is to promote education and research and to disseminate knowledge
about scientific methods and results.
Application
-----------
These guidelines apply to the use of the University's computer equipment and
apply to all users who are granted access to the computer equipment. The
guidelines are to be part of a user contract and are otherwise to be accessible
at suitable places such as the terminal room. The use of the computer equipment
also requires that the user knows any possible supplementary regulations.
Good Faith
----------
Never leave any doubt as to your identity and give your full name in addition
to explaining your connection to the University. A user is always to identify
him/ herself by name, his/ her own user identity, password or in another
regular way when using services on the computer network. The goodwill of
external environments is not to be abused by the user accessing information not
intended for the user, or by use of the services for purposes other than that
for which they are intended. Users are to follow the instructions from system
administrators about the use of computer equipment. Users are also expected to
familiarize themselves with the user guides, manuals, documentation etc. in
order to reduce the risk of breakdowns or loss of data or equipment (through
ignorance). On termination of employment or studies, it is the users
responsibility to ensure that copies of data owned or used by the University
are secured on behalf of the University.
Data Safety
-----------
Users are obliged to take the necessity measures to prevent the loss of data
etc. by taking back-up copies, careful storage of media, etc. This can be done
by ensuring that the systems management take care of it. Your files are in
principle personal but should be protected so that they cannot be read by
others. Users are obliged to protect the integrity of their passwords or other
safety elements known to them, in addition to preventing unauthorized people
from obtaining access to the computer equipment. Introducing data involves the
risk of unwanted elements such as viruses. Users are obliged to take measures
to protect the computer equipment from such things. Users are obliged to report
circumstances that may have importance for the safety or integrity of the
equipment to the closest superior or to the person who is responsible for data
safety.
Respect for Other Users Privacy
-------------------------------
Users may not try to find out another persons password, etc., nor try to obtain
unauthorized access to another persons data. This is true independent of
whether or not the data is protected. Users are obliged to familiarize
themselves with the special rules that apply to the storage of personal
information (on others). If a user wishes to register personal information, the
user concerned is obliged to ensure that there is permission for this under the
law for registration of information on persons or rules authorized by the law
or with acceptance of rights given to the University. In cases where
registration of such information is not permitted by these rules the user is
obliged to apply for (and obtain? ) the necessary permission. Users are bound
by the oaths of secrecy concerning personal relationships of which the user
acquires knowledge through use of computer equipment, ref. to the definition in
section 13 second section of the Administration Law, (forvaltningslovens
section 13 annet ledd).
Proper Use
----------
The computer equipment of the University may not be used to advance slander or
discriminating remarks, nor to distribute pornography or spread secret
information, or to violate the peace of private life or to incite or take part
in illegal actions. This apart, users are to restrain from improper
communication on the network.
The computer equipment is to be used in accordance with the aims of the
University. This excludes direct commercial use.
Awareness of the Purposes for Use of Resources
----------------------------------------------
The computer equipment of the University is to strengthen and support
professional activity, administration, research and teaching. Users have a
co-responsibility in making the best possible use of the resources.
Rights
------
Data is usually linked to rights which make their use dependent on agreements
with the holder of the rights. Users commit themselves to respecting other
people's rights. This applies also when the University makes data accessible.
The copying of programs in violation of the rights of use and/or license
agreement is not permitted.
Liability
---------
Users themselves are responsible for the use of data which is made accessible
via the computer equipment. The University disclaims all responsibility for any
loss that results from errors or defects in computer equipment, including for
example, errors or defects in data, use of data from accessible databases or
other data that has been obtained through the computer network etc. The
University is not responsible for damage or loss suffered by users as a
consequence of insufficient protection of their own data.
Surveillance
------------
The systems manager has the right to seek access to the individual user's
reserved areas on the equipment for the purpose of ensuring the equipment's'
proper functioning or to control that the user does not violate or has not
violated the regulations in these guidelines. It is presupposed that such
access is only sought when it is of great importance to absolve the University
from responsibility or bad reputation. If the systems manager seeks such
access, the user should be warned about it in an appropriate way. Ordinarily
such a warning should be given in writing and in advance. If the use of a
workstation, terminal or other end user equipment is under surveillance because
of operational safety or other considerations, information about this must be
given in an appropriate way. The systems managers are bound by oaths of secrecy
with respect to information about the user or the user's activity which they
obtain in this way, the exception being that circumstances which could
represent a violation of these guidelines may be reported to superior
authorities.
Sanctions
---------
Breach of these guidelines can lead to the user being denied access to the
University's data services, in addition to which there are sanctions that the
University can order, applying other rules. Breach of privacy laws, oaths of
secrecy etc. can lead to liability or punishment. The usual rules for dismissal
or (forced) resignation of employees or disciplinary measures against students,
apply to users who misuse the computer equipment. The reasons for sanctions
against a user are to be stated, and can be ordered by the person who has
authority given by the University. Disciplinary measures against students are
passed by the University Council, ref. section 47 of the University law.
Complaints
----------
Complaints about sanctions are to be directed to the person(s) who order
sanctions. If the complaint is not complied with, it is sent on to the
University Council for final decision. Complaints about surveillance have the
same procedure as for sanctions. The procedure for complaints about dismissal
or resignation of employees are the usual rules for the University, and rules
otherwise valid in Norwegian society. Decisions about disciplinary measures
against students cannot be complained about, See § 47 of the University law.
<file_sep>/stallo/shutdown.rst
.. _stallo_shutdown:
===============
Stallo Shutdown
===============
Stallo is getting old and will be shutdown this year.
Hardware failures cause more and more nodes to fail due to high age.
The system will stay in production and continue **service until
at least 31. December 2020**.
We will help you with finding alternatives to your computational and
storage needs and with moving your workflows and data to one of our
other machines like Betzy, Saga and Fram.
If you have questions, special needs or problems, please contact us at
<EMAIL>
Alternatives
============
For an overview of alternatives especially for local projects, please
have look `this presentation <https://docs.google.com/presentation/d/1tkXTj9L_9grOYKXcaKmP12jF5_5YzIuj6g4y8X78IUw/edit?usp=sharing>`_
Computional resources
---------------------
- `Betzy <https://documentation.sigma2.no/hpc_machines/betzy.html>`_
- `Saga <https://documentation.sigma2.no/hpc_machines/saga.html>`_
- `Fram <https://documentation.sigma2.no/hpc_machines/fram.html>`_
- Kubernetes based cloud infrastructure:
`NIRD toolkit <https://www.sigma2.no/nird-toolkit>`_
Storage
-------
- `NIRD <https://documentation.sigma2.no/files_storage/nird.html>`_
- `UiT research storage <https://uit.no/infrastruktur/enhet?p_document_id=668862>`_ for short- to mid-term storage of work in progress datasets
(only for UiT researchers)
- `UiT Research Data Portal <https://en.uit.no/forskning/art?p_document_id=548687>`_ for publishing final datasets and results
- `Overview <re3data.org>`_ over public research data repositories
<file_sep>/applications/physics/files/run_comsol.sh
#!/bin/bash -l
# Note that this is a setup for the highmem 128GB nodes. To run on the regular
# nodes, change to the normal partition and reduce the memory requirement.
#####################################
#SBATCH --job-name=comsol_runex
#SBATCH --nodes=2
#SBATCH --cpus-per-task=16 # Highmem nodes have 16 cores
#SBATCH --mem-per-cpu=7500MB # Leave some memory for the system to work
#SBATCH --time=0-01:00:00 # Syntax is DD-HH:MM:SS
#SBATCH --partition=highmem # For regular nodes, change to "normal"
#SBATCH --mail-type=ALL # Notify me at start and finish
#SBATCH --exclusive # Not necessary, implied by the specs above
##SBATCH --account=nnXXXXk # Change to your account and uncomment
#####################################
# define input
inp=$1 # First input argument: Name of input without extention
std=$2 # Second input argument: Type of study
ext=mph # We use the same naming scheme as the software default extention
# define directories
submitdir=${SLURM_SUBMIT_DIR}
workdir=/global/work/${USER}/${SLURM_JOBID}
# create work directory
mkdir -p ${workdir}
# move input to workdir
cp ${inp}.${ext} ${workdir}
# load necessary modules
module purge --quiet
module load COMSOL/5.3-intel-2016a
# run calculation in workdir
cd ${workdir}
time comsol -nn ${SLURM_NNODES}\
-np ${SLURM_CPUS_PER_TASK}\
-mpirsh /usr/bin/ssh\
-mpiroot $I_MPI_ROOT\
-mpi intel batch\
-inputfile ${inp}.${ext}\
-outputfile ${inp}_out.${ext}\
-study ${std}\
-mlroot /global/apps/matlab/R2014a
# move output back
mv *out* $submitdir
# cleanup
cd $submitdir
rm -r ${workdir}
exit 0
<file_sep>/stallo/getting_started.rst
.. _getting_started:
===============
Getting started
===============
Here you will get the basics to work with Stallo. Please study carefully the links at the end of each paragraph to get more detailed information.
Get an account
--------------
If you are associated with UiT The Arctic University of Norway, you may apply locally. :doc:`/account/uitquota`
You can also apply for an account for Stallo or any of the other Norwegian computer clusters at the `Metacenter account application <https:/www.metacenter.no/user/application/form/notur/>`_. This is also possible if you already have a local account. :doc:`/account/account`
Change temporary password
-------------------------
The password you got by SMS has to be changed on `MAS <https://www.metacenter.no/user/login/?next=/user/password/>`_ within one week, or else the loginaccount will be closed again - and you need to contact us for reopening.
You can't use the temporary password for logging in to Stallo.
Connect to Stallo
-----------------
You may connect to Stallo via *SSH* to ``stallo.uit.no``. This means that on Linux and OSX you may directly connect by opening a terminal and writing ``ssh username@stallo.uit.no``. From Windows, you may connect via PuTTY which is available in the Software Center. X-forwarding for graphical applications is possible. There exists also a webinterface to allow easy graphical login. Please see the following link for details to all mentioned methods. :doc:`/account/login`
On nodes and files
------------------
When you login, you will be on a login node. Do *not* run any long-lasting programs here. The login node shall only be used for job preparation (see below) and simple file operations.
You will also be in your home directory ``/home/username``. Here, you have 300 GB at your disposal that will be backed up regularly. For actual work, please use the global work area at ``/global/work/username``. This space is not backed up, but it has a good performance and is 1000 TB in size. Please remove old files regularly. :doc:`/storage/storage`
To move files from your computer to Stallo or vice versa, you may use any tool that works with *ssh*. On Linux and OSX, these are scp, rsync, or similar programs. On Windows, you may use WinSCP. :doc:`/storage/file_transfer`
Run a program
-------------
There are many programs pre-installed. You may get a list of all programs by typing ``module avail``. You can also search within that list. ``module avail blast`` will search for Blast (case-insensitive). When you found your program of choice, you may load it using ``module load BLAST+/2.7.1-intel-2017b-Python-2.7.14``. All program files will now be available, i.e. you can now simply call ``blastp -version`` to run Blast and check the loaded version. You can also compile your own software, if necessary. :doc:`/software/modules`
To eventually run the program, you have to write a job script. In this script, you can define how long the job (i.e. the program) will run and how much memory and compute cores it needs. For the actual computation, you need to learn at least the basics of Linux shell scripting. You can learn some basics here: :doc:`/account/linux`.
When you wrote the job script, you can start it with ``sbatch jobscript.sh``. This will put the script in the queue, where it will wait until an appropriate compute node is available. You can see the status of your job with ``squeue -u username``. :doc:`/jobs/batch` and :doc:`/jobs/examples`
Every job that gets started will be charged to your quota. Your quota is calculated in hours of CPU time and is connected to your specific project. To see the status of your quota account(s), type ``cost`` :doc:`/account/accounting`
Get help
--------
Do you need help with Stallo? Write us an email to <EMAIL>. You can also request new software (either an update or entirely new software), suggest changes to this documentation, or send us any other suggestions or issues concerning Stallo to that email address. Please also read the rest of this documentation.
Happy researching!
<file_sep>/applications/chemistry/files/job_dalton.sh
#!/bin/bash -l
# Write the account to be charged here
# (find your account number with `cost`)
#SBATCH --account=nnXXXXk
#SBATCH --job-name=daltonexample
# we ask for 20 cores
#SBATCH --ntasks=20
# run for five minutes
# d-hh:mm:ss
#SBATCH --time=0-00:05:00
# 500MB memory per core
# this is a hard limit
#SBATCH --mem-per-cpu=500MB
# Remove percentage signs to turn on all mail notification
#%%%SBATCH --mail-type=ALL
# You may not place bash commands before the last SBATCH directive!
# Load Dalton
# You can find all installed Dalton installations with:
# module avail dalton
module load Dalton/2013.2
# Define the input files
molecule_file=caffeine.mol
input_file=b3lyp_energy.dal
# Define and create a unique scratch directory
SCRATCH_DIRECTORY=/global/work/${USER}/daltonexample/${SLURM_JOBID}
mkdir -p ${SCRATCH_DIRECTORY}
cd ${SCRATCH_DIRECTORY}
# Define and create a temp directory
TEMP_DIR=${SCRATCH_DIRECTORY}/temp
mkdir -p ${TEMP_DIR}
# copy input files to scratch directory
cp ${SLURM_SUBMIT_DIR}/${input_file} ${SLURM_SUBMIT_DIR}/${molecule_file} ${SCRATCH_DIRECTORY}
# run the code
dalton -N ${SLURM_NTASKS} -t ${TEMP_DIR} ${input_file} ${molecule_file}
# copy output and tar file to submit dir
cp *.out *.tar.gz ${SLURM_SUBMIT_DIR}
# we step out of the scratch directory and remove it
cd ${SLURM_SUBMIT_DIR}
rm -rf ${SCRATCH_DIRECTORY}
# happy end
exit 0
<file_sep>/applications/chemistry/Gaussian/overview.rst
======================
Gaussian and GaussView
======================
.. toctree::
:maxdepth: 1
job-example.rst
gaussian_on_stallo.rst
GaussView.rst
`Gaussian <http://gaussian.com>`_ is a popular computational chemistry program.
Official documentation: http://gaussian.com/man
License and access
------------------
The license is commercial/proprietary and constitutes of 4 site licenses for the 4 current host
institutions of NOTUR installations; NTNU, UiB, UiO, UiT. Only
persons from one of these institutions have access to the Gaussian Software
system installed on Stallo. Note that users that do not come from one of the
above mentioned institutions still may be granted access, but they need to
document access to a valid license for the version in question first.
* To get access to the code, you need to be in the ``gaussian`` group of users.
* To be in the ``gaussian`` group of users, you need be qualified for it - see above.
Citation
--------
For the recommended citation, please consult http://gaussian.com/citation/.
<file_sep>/storage/file_transfer.rst
.. _file_transfer:
=================================
Transferring files to/from Stallo
=================================
Only ssh type of access is open to stallo. Therefore to upload or
download data only scp and sftp can be used.
To transfer data to and from stallo use the following address:
::
stallo.uit.no
This address has nodes with 10Gb network interfaces.
Basic tools (scp, sftp)
Standard scp command and sftp clients can be used:
::
ssh stallo.uit.no
ssh -l <username> stallo.uit.no
sftp stallo.uit.no
sftp <<EMAIL>
Mounting the file system on you local machine using sshfs
---------------------------------------------------------
For linux users::
sshfs [user@]stallo.uit.no:[dir] mountpoint [options]
eg.::
sshfs <EMAIL>: /home/steinar/stallo-fs/
Windows users may buy and install
`expandrive <https://www.expandrive.com/windows>`_.
High-performance tools
======================
NONE cipher
-----------
This cipher has the highest transfer rate. Keep in mind that data after
authentication is NOT encrypted, therefore the files can be sniffed and
collected unencrypted by an attacker. To use you add the following to
the client command line:
::
-oNoneSwitch=yes -oNoneEnabled=yes
Anytime the None cipher is used a warning will be printed on the screen:
::
"WARNING: NONE CIPHER ENABLED"
If you do not see this warning then the NONE cipher is not in use.
MT-AES-CTR
If for some reason (eg: high confidentiality) NONE cipher can't be used,
the multithreaded AES-CTR cipher can be used, add the following to the
client command line (choose one of the numbers):
::
-oCipher=aes[128|192|256]-ctr
or:
::
-caes[128|192|256]-ctr.
Subversion and rsync
--------------------
The tools subversion and rsync is also available for transferring files.
<file_sep>/stallo/stallo.rst
.. _about_stallo:
============
About Stallo
============
Resource description
====================
Key numbers about the Stallo cluster: compute nodes, node interconnect,
operating system, and storage configuration.
+-------------------------+----------------------------------------------+---------------------------------------------+
| | Aggregated | Per node |
+=========================+==============================================+=============================================+
| Peak performance | 312 Teraflop/s | 332 Gigaflop/s / 448 Gigaflops/s |
+-------------------------+----------------------------------------------+---------------------------------------------+
| | | | 304 x HP BL460 gen8 blade servers | | 1 x HP BL460 gen8 blade servers |
| | # Nodes | | 328 x HP SL230 gen8 servers | | 1 x. HP SL230 gen8 servers |
+-------------------------+----------------------------------------------+---------------------------------------------+
| | | | 608 / 4864 | | 2 / 16 |
| | # CPU's / # Cores | | 656 / 6560 | | 2 / 20 |
+-------------------------+----------------------------------------------+---------------------------------------------+
| | | | 608 x 2.60 GHz Intel Xeon E5 2670 | | 2 x 2.60 GHz Intel Xeon E5 2670 |
| | Processors | | 656 x 2.80 GHz Intel Xeon E5 2680 | | 2 x 2.80 Ghz Intel Xeon E5 2680 |
+-------------------------+----------------------------------------------+---------------------------------------------+
| Total memory | 26.2 TB | 32 GB (32 nodes with 128 GB) |
+-------------------------+----------------------------------------------+---------------------------------------------+
| Internal storage | 155.2 TB | 500 GB (32 nodes with 600GB raid) |
+-------------------------+----------------------------------------------+---------------------------------------------+
| Centralized storage | 2000 TB | 2000 TB |
+-------------------------+----------------------------------------------+---------------------------------------------+
| Interconnect | Gigabit Ethernet + Infiniband :sup:`1` | Gigabit Ethernet + Infiniband :sup:`1` |
+-------------------------+----------------------------------------------+---------------------------------------------+
+-------------------------------------+-----------------------+
| Compute racks | 11 |
+-------------------------------------+-----------------------+
| Infrastructure racks | 2 |
+-------------------------------------+-----------------------+
| Storage racks | 3 |
+-------------------------------------+-----------------------+
1) All nodes in the cluster are connected with Gigabit Ethernet and
QDR Infiniband.
.. _linux-cluster:
Stallo - a Linux cluster
========================
This is just a quick and brief introduction to the general features of Linux Clusters.
A Linux Cluster - one machine, consisting of many machines
----------------------------------------------------------
On one hand you can look at large Linux Clusters as rather large and powerful supercomputers, but on the other hand you can look at them as just a large bunch of servers and some storage system(s) connected with each other through a (high speed) network. Both of these views are fully correct, and it's therefore important to be aware of the strengths and the limitations of such a system.
Clusters vs. SMP’s
------------------
Until July 2004, most of the supercomputers available to Norwegian HPC users were more or less large Symmetric Multi Processing (SMP's) systems; like the HP Superdome's at UiO and UiT, the IBM Regatta at UiB and the SGI Origion and IBM p575 systems at NTNU.
On SMP systems most of the resources (CPU, memory, home disks, work disks, etc) are more or less uniformly accessible for any job running on the system. This is a rather simple picture to understand, it’s nearly as your desktop machine – just more of everything: More users, more CPU’s, more memory, more disks etc.
On a Linux Cluster the picture is quite different. The system consists of several independent compute nodes (servers) connected with each other through some (high speed) network and maybe hooked up on some storage system. So the HW resources (like CPU, memory, disk, etc) in a cluster are in general distributed and only locally accessible at each server.
Linux operating system (Rocks): `<http://www.rocksclusters.org/>`_
==================================================================
Since 2003, the HPC-group at has been one of five international
development sites for the Linux operating system Rocks. Together with
people in Singapore, Thailand, Korea and USA, we have developed a tool
that has won international recognition, such as the price for "Most
important software innovation " both in 2004 and 2005 in HPCWire. Now
Rocks is a de-facto standard for cluster-management in Norwegian
supercomputing.
Stallo - Sami mythology
========================
In the folklore of the Sami, a Stallo (also Stallu or Stalo) is a sami wizard.
"The Sami traditions up North differ a bit from other parts of Norwegian
traditions. You will find troll and draug and some other creatures as well,
but the Stallo is purely Sami. He can change into all kinds of beings,;
animals, human beings, plants, insects, bird – anything. He can also “turn”
the landscape so you miss your direction or change it so you don’t recognise
familiar surroundings. Stallo is very rich and smart, he owns silver and
reindeers galore, but he always wants more. To get what he wants he tries to
trick the Samis into traps, and the most popular Sami stories tell how people
manage to fool Stallo." NB! Don’t mix Stallo with the noaide! He is a real
wizard whom people still believe in.
<file_sep>/jobs/files/slurm-timeout-cleanup.sh
#!/bin/bash -l
# job name
#SBATCH --job-name=example
# replace this by your account
#SBATCH --account=...
# one core only
#SBATCH --ntasks=1
# we give this job 4 minutes
#SBATCH --time=0-00:04:00
# asks SLURM to send the USR1 signal 120 seconds before end of the time limit
#SBATCH --signal=B:USR1@120
# define the handler function
# note that this is not executed here, but rather
# when the associated signal is sent
your_cleanup_function()
{
echo "function your_cleanup_function called at $(date)"
# do whatever cleanup you want here
}
# call your_cleanup_function once we receive USR1 signal
trap 'your_cleanup_function' USR1
echo "starting calculation at $(date)"
# the calculation "computes" (in this case sleeps) for 1000 seconds
# but we asked slurm only for 240 seconds so it will not finish
# the "&" after the compute step and "wait" are important
sleep 1000 &
wait
<file_sep>/jobs/files/slurm-blueprint.sh
#!/bin/bash -l
##############################
# Job blueprint #
##############################
# Give your job a name, so you can recognize it in the queue overview
#SBATCH --job-name=example
# Define, how many nodes you need. Here, we ask for 1 node.
# Each node has 16 or 20 CPU cores.
#SBATCH --nodes=1
# You can further define the number of tasks with --ntasks-per-*
# See "man sbatch" for details. e.g. --ntasks=4 will ask for 4 cpus.
# Define, how long the job will run in real time. This is a hard cap meaning
# that if the job runs longer than what is written here, it will be
# force-stopped by the server. If you make the expected time too long, it will
# take longer for the job to start. Here, we say the job will take 5 minutes.
# d-hh:mm:ss
#SBATCH --time=0-00:05:00
# Define the partition on which the job shall run. May be omitted.
#SBATCH --partition normal
# How much memory you need.
# --mem will define memory per node and
# --mem-per-cpu will define memory per CPU/core. Choose one of those.
#SBATCH --mem-per-cpu=1500MB
##SBATCH --mem=5GB # this one is not in effect, due to the double hash
# Turn on mail notification. There are many possible self-explaining values:
# NONE, BEGIN, END, FAIL, ALL (including all aforementioned)
# For more values, check "man sbatch"
#SBATCH --mail-type=END,FAIL
# You may not place any commands before the last SBATCH directive
# Define and create a unique scratch directory for this job
SCRATCH_DIRECTORY=/global/work/${USER}/${SLURM_JOBID}.stallo-adm.uit.no
mkdir -p ${SCRATCH_DIRECTORY}
cd ${SCRATCH_DIRECTORY}
# You can copy everything you need to the scratch directory
# ${SLURM_SUBMIT_DIR} points to the path where this script was submitted from
cp ${SLURM_SUBMIT_DIR}/myfiles*.txt ${SCRATCH_DIRECTORY}
# This is where the actual work is done. In this case, the script only waits.
# The time command is optional, but it may give you a hint on how long the
# command worked
time sleep 10
#sleep 10
# After the job is done we copy our output back to $SLURM_SUBMIT_DIR
cp ${SCRATCH_DIRECTORY}/my_output ${SLURM_SUBMIT_DIR}
# In addition to the copied files, you will also find a file called
# slurm-1234.out in the submit directory. This file will contain all output that
# was produced during runtime, i.e. stdout and stderr.
# After everything is saved to the home directory, delete the work directory to
# save space on /global/work
cd ${SLURM_SUBMIT_DIR}
rm -rf ${SCRATCH_DIRECTORY}
# Finish the script
exit 0
<file_sep>/account/linux.rst
.. _linux:
==================
Linux command line
==================
New on Linux systems?
=====================
This page contains some tips on how to get started using the Stallo cluster on
UiT if you are not too familiar with Linux/ Unix. The information is intended
for both users that are new to Stallo and for users that are new to
Linux/UNIX-like operating systems. Please consult the rest of the user guide
for information that is not covered in this chapter.
For details about the hardware and the operating system of stallo, and basic
explanation of Linux clusters please see the :ref:`about_stallo` part of this
documentation.
To find out more about the storage and file systems on the machines, your disk
quota, how to manage data, and how to transfer file to/from Stallo, please read
the :ref:`file_transfer` section.
ssh
---
The only way to connect to Stallo is by using ssh. Check
the :ref:`login` in this documentation to learn more about ssh.
scp
---
The machines are stand-alone systems. The machines do not (NFS-)mount remote
disks. Therefore you must explicitly transfer any files you wish to use to the
machine by scp. For more info, see :ref:`file_transfer`.
Running jobs on the machine
---------------------------
You must execute your jobs by submitting them to the batch system. There is a
dedicated section :doc:`/jobs/batch` in our user guide that explain how to use the
batch system. The pages explains how to write job scripts, and how to submit,
manage, and monitor jobs. It is not allowed to run long or large memory jobs
interactively (i.e., directly from the command line).
Common commands
---------------
pwd
Provides the full pathname of the directory you are currently in.
cd
Change the current working directory.
ls
List the files and directories which are located in the directory you are currently in.
find
Searches through one or more directory trees of a file system, locates files based on some user-specified
criteria and applies a user-specified action on each matched file. e.g.::
find . -name 'my*' -type f
The above command searches in the current directory (.) and below it, for files and directories with names starting with my.
"-type f" limits the results of the above search to only regular files, therefore excluding directories,
special files, pipes, symbolic links, etc. my* is enclosed in single quotes (apostrophes) as otherwise the
shell would replace it with the list of files in the current directory starting with "my".
grep
Find a certain expression in one or more files, e.g::
grep apple fruitlist.txt
mkdir
Create new directory.
rm
Remove a file. Use with caution.
rmdir
Remove a directory. Use with caution.
mv
Move or rename a file or directory.
vi/vim or emacs
Edit text files, see below.
less/ more
View (but do not change) the contents of a text file one screen at a time, or, when combined with other commands (see below)
view the result of the command one screen at a time. Useful if a command prints several screens of information on
your screen so quickly, that you don't manage to read the first lines before they are gone.
\|
Called "pipe" or "vertical bar" in English. Group 2 or more commands together, e.g.::
ls -l | grep key | less
This will list files in the current directory (ls), retain only the lines of *ls* output containing the string "key" (grep),
and view the result in a scrolling page (less).
More info on manual pages
-------------------------
If you know the UNIX-command that you would like to
use but not the exact syntax, consult the manual pages on the system to
get a brief overview. Use 'man [command]' for this. For example, to
get the right options to display the contents of a directory, use 'man
ls'. To choose the desired options for showing the current status of
processes, use 'man ps'.
Text editing
------------
Popular tools for editing files on Linux/UNIX-based
systems are 'vi' and 'emacs'. Unfortunately the commands within both
editors are quite cryptic for beginners. It is probably wise to spend
some time understanding the basic editing commands before starting to
program the machine.
vi/vim
Full-screen editor. Use 'man vi' for quick help.
emacs
Comes by default with its own window. Type 'emacs -nw' to
invoke emacs in the active window. Type 'Control-h i' or follow the
menu 'Help->manuals->browse-manuals-with-info' for help. 'Control-h
t' gives a tutorial for beginners.
Environment variables
---------------------
The following variables are automatically available after you log in::
$USER your account name
$HOME your home directory
$PWD your current directory
You can use these variables on the command line or in shell scripts by
typing $USER, $HOME, etc. For instance: 'echo $USER'. A complete
listing of the defined variables and their meanings can be obtained by
typing 'printenv '.
You can define (and redefine) your own variables by typing::
export VARIABLE=VALUE
Aliases
-------
If you frequently use a command that
is long and has for example many options to it, you can put an alias
(abbreviation) for it in your ``~/.bashrc`` file. For example, if you
normally prefer a long listing of the contents of a directory with the
command 'ls -laF | more', you can put following line in your ``~/.bashrc`` file::
alias ll='ls -laF | more'
You must run 'source ~/.bashrc' to update your
environment and to make the alias effective, or log out and in :-). From
then on, the command 'll' is equivalent to 'ls -laF | more'.
Make sure that the chosen abbreviation is not already an existing
command, otherwise you may get unexpected (and unwanted) behavior. You
can check the existence and location of a program, script, or alias by
typing::
which [command]
whereis [command]
~/bin
-----
If you frequently use a self-made or self-installed program or script that you
use in many different directories, you can create a directory ~/bin in which
you put this program/script. If that directory does not already exist, you can
do the following. Suppose your favorite little program is called 'myscript' and is
in your home ($HOME) directory::
mkdir -p $HOME/bin
cp myscript $HOME/bin
export PATH=$PATH:$HOME/bin
PATH is a colon-separated list of directories that are searched in the
order in which they are specified whenever you type a command. The first
occurrence of a file (executable) in a directory in this PATH variable
that has the same name as the command will be executed (if possible). In
the example above, the 'export' command adds the ~/bin directory to
the PATH variable and any executable program/script you put in the
~/bin directory will be recognized as a command. To add the ~/bin
directory permanently to your PATH variable, add the above
'export' command to your ~/.bashrc file and update your environment
with 'source ~/.bashrc'.
Make sure that the names of the programs/scripts are not already
existing commands, otherwise you may get unexpected (and unwanted)
behaviour. You can check the contents of the PATH variable by typing::
printenv PATH
echo $PATH
<file_sep>/jobs/job_management.rst
.. _job_management:
Managing jobs
=============
The lifecycle of a job can be managed with as little as three different
commands:
#. Submit the job with ``sbatch <script_name>``.
#. Check the job status with ``squeue``. (to limit the display to only
your jobs use ``squeue -u <user_name>``.)
#. (optional) Delete the job with ``scancel <job_id>``.
You can also hold the start of a job:
scontrol hold <job_id>
Put a hold on the job. A job on hold will not start or block other jobs from starting until you release the hold.
scontrol release <job_id>
Release the hold on a job.
Job status descriptions in squeue
---------------------------------
When you run ``squeue`` (probably limiting the output with ``squeue -u <user_name>``), you will get a list of all jobs currently running or waiting to start. Most of the columns should be self-explaining, but the *ST* and *NODELIST (REASON)* columns can be confusing.
*ST* stands for *state*. The most important states are listed below. For a more comprehensive list, check the `squeue help page section Job State Codes <https://slurm.schedmd.com/squeue.html#lbAG>`_.
R
The job is running
PD
The job is pending (i.e. waiting to run)
CG
The job is completing, meaning that it will be finished soon
The column *NODELIST (REASON)* will show you a list of computing nodes the job is running on if the job is actually running. If the job is pending, the column will give you a reason why it still pending. The most important reasons are listed below. For a more comprehensive list, check the `squeue help page section Job Reason Codes <https://slurm.schedmd.com/squeue.html#lbAF>`_.
Priority
There is another pending job with higher priority
Resources
The job has the highest priority, but is waiting for some running job to finish.
QOS*Limit
This should only happen if you run your job with ``--qos=devel``. In developer mode you may only have one single job in the queue.
launch failed requeued held
Job launch failed for some reason. This is normally due to a faulty node. Please contact us via <EMAIL> stating the problem, your user name, and the jobid(s).
Dependency
Job cannot start before some other job is finished. This should only happen if you started the job with ``--dependency=...``
DependencyNeverSatisfied
Same as *Dependency*, but that other job failed. You must cancel the job with ``scancel JOBID``.
<file_sep>/development/files/perf-reports.sh
#!/usr/bin/env bash
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=20
#SBATCH --time=0-00:10:00
module load perf-reports/5.1
# create temporary scratch area for this job on the global file system
SCRATCH_DIRECTORY=/global/work/$USER/$SLURM_JOBID
mkdir -p $SCRATCH_DIRECTORY
# run the performance report
# all you need to do is to launch your "normal" execution
# with "perf-report"
cd $SCRATCH_DIRECTORY
perf-report mpiexec -n 20 $SLURM_SUBMIT_DIR/example.x
# perf-report generates summary files in html and txt format
# we copy result files to submit dir
cp *.html *.txt $SLURM_SUBMIT_DIR
# clean up the scratch directory
cd /tmp
rm -rf $SCRATCH_DIRECTORY
<file_sep>/applications/chemistry/Gaussian/gaussian_on_stallo.rst
.. _gaussian_on_stallo:
==========================
Memory and number of cores
==========================
This page contains info about special features related to
the Gaussian install made on Stallo, but also general issues
related to Gaussian only vaguely documented elsewhere.
Choosing the right version
--------------------------
To see which versions of Gaussien are available, use::
$ module avail Gaussian/
To load a specific version of Gaussian, use for instance::
$ module load Gaussian/g16_B.01
Gaussian over Infiniband
------------------------
First note that the Gaussian installation on Stallo is the Linda parallel
version, so it scales somewhat initially. On top of this, Gaussian is installed
with a little trick, where the loading of the executable is intercepted before
launched, and an alternative socket library is loaded. This enables the
running Gaussian natively on the Infiniband network giving us
two advantages:
* The parallel fraction of the code scales to more cores.
* The shared memory performance is significantly enhanced (small scale performance).
But since we do this trick, we are greatly depending on altering the specific
node address into the input file: To run gaussian in parallel requires the
additional keywords ``%LindaWorkers`` and ``%NProcshared`` in the ``Link 0`` part of the
input file. This is taken care of by a wrapper script around the
original binary in each individual version folder. This
is also commented in the job script example. Please use
our example when when submitting jobs.
We have also taken care of the rsh/ssh setup in our installation procedure, to
avoid .tsnet.config dependency for users.
Parallel scaling
----------------
Gaussian is a rather large program system with a range of different binaries,
and users need to verify whether the functionality they use is parallelized and
how it scales.
Due to the preload Infiniband trick, we have a somewhat more generous policy
when it comes to allocating cores/nodes to Gaussian jobs but before computing a
table of different functionals and molecules, we strongly advice users to first
study the scaling of the code for a representative system.
Please do not reuse scripts inherited from others without studying the
performance and scaling of your job. If you need assistance with this, please
contact the user support.
We do advice people to use up to 256 cores (``--tasks``). We have observed
acceptable scaling of the current Gaussian install beyond 16 nodes for the jobs
that do scale outside of one node (i.e. the binaries in the $gXXroot/linda-exe
folder). Linda networking overhead seems to hit hard around this amount of
cores, causing us to be somewhat reluctant to advice going beyond 256 cores.
Since we have two different architectures with two different core counts on
Stallo, the ``--exclusive`` flag is important to ensure that the distribution
of jobs across the whole system are done in a rather flexible and painless way.
Memory allocation
-----------------
Gaussian takes care of memory allocation internally.
That means that if the submitted job needs more memory per core than what is in
average available on the node, it will automatically scale down the number of
cores to mirror the need. This also means that you always should ask for full
nodes when submitting Gaussian jobs on Stallo! This is taken care of by the
``--exclusive`` flag and commented in the job script example.
The ``%mem`` allocation of memory in the Gaussian input file means two things:
* In general it means memory/node – for share between ``nprocshared``, and
additional to the memory allocated per process. This is also documented by
Gaussian.
* For the main process/node it also represents the network
buffer allocated by Linda since the main Gaussian process takes a part
and Linda communication process takes a part equally sized – thus you should
never ask for more than half of the physical memory on the nodes, unless they
have swap space available - which you never should assume.
The general ``%mem`` limit will always be half of the physical memory
pool given in MB instead of GB - 16000MB instead of 16GB since this leaves a
small part for the system. That is why we would actually advise to use 15GB as
maximum ``%mem`` size.
Large temporary outputs on Stallo
---------------------------------
As commented here :doc:`/storage/storage` there is an issue related to very
large temporary files on Stallo. Please read up on it at act accordingly. This
issue is also commented in the job script example.
|
77481cc7458a487104a0f6d6c1850ee80cec456c
|
[
"Markdown",
"reStructuredText",
"Shell"
] | 28
|
reStructuredText
|
uit-no/hpc-doc
|
5f3f2f25d16fb1ef13ff0eebbe2c20e56821b2ef
|
eaf9cf6303836ea93ec898164898b32ceb2493ef
|
refs/heads/master
|
<repo_name>BKSum/hackerrankjava<file_sep>/src/main/java/introduction/Loops.java
/**
*
*/
package introduction;
import java.util.*;
/**
* @author Brandon
*
*/
public class Loops {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for(int i=1; i<=10;i++){
System.out.println(new StringBuilder().append(N).append(" x ").append(i).append(" = ").append(N*i));
}
in.close();
}
}
|
ac51955ea002d1f5babc0be8553e9b2b44901e81
|
[
"Java"
] | 1
|
Java
|
BKSum/hackerrankjava
|
d0c4876b0b2d924470b943bba4b132d4e535dbd1
|
40ed2d9931eca26daf716c104c6a515f0602b3a5
|
refs/heads/develop
|
<repo_name>EziamakaNV/purelykels<file_sep>/src/Components/Home.js
import React, { Component } from 'react';
import Header from './Header';
import Footer from './Footer'
class Home extends Component {
render(){
return(
/* React.fragment helps reduce the amount of nodes
i.e eliminates the need of a div wrapper*/
<React.Fragment>
<main>
<Header/>
<section>
<h1>
The number 1 Akara Joint!
</h1>
</section>
<section></section>
<Footer year = { 2019 }/>
</main>
</React.Fragment>
)
}
}
export default Home<file_sep>/src/Components/Logo.js
import React, { Component } from 'react';
class Logo extends Component {
render(){
return (
<React.Fragment>
<section>
Akara Chevron
</section>
</React.Fragment>
);
}
}
export default Logo;<file_sep>/src/Components/Header.js
import React, { Component } from 'react';
import Logo from './Logo';
import NavLinks from './NavLinks';
import HeaderSignIn from './HeaderSignIn';
class Header extends Component {
render(){
return(
/* React.fragment helps reduce the amount of nodes
i.e eliminates the need of a div wrapper*/
<React.Fragment>
<header class = 'display-flex'>
<section class = 'display-flex'>
<Logo/>
<NavLinks/>
</section>
<HeaderSignIn/>
</header>
</React.Fragment>
)
}
}
export default Header;
|
9f09debab7189fd39d420a8110858f9de35a3fc7
|
[
"JavaScript"
] | 3
|
JavaScript
|
EziamakaNV/purelykels
|
f45e8dd99bf8f913e8feebf8af64843c8d4aced2
|
479e022a74488321e51f7d4f367cd59c67a5d2ba
|
refs/heads/master
|
<repo_name>raml-org/raml-cli<file_sep>/src/commands/mock.ts
/**
* This command handles requests to mock a specific API specification. Mocking
* means to generate a fake service based on the examples defined in the spec
* for any endpoint.
*
* This command is using the raml-mock-service implementation underneath.
*
* Github: https://github.com/raml-org/raml-mock-service
*/
const mock = require('raml-mock-service')
const http = require('http')
const finalhandler = require('finalhandler')
const Router = require('osprey').Router
const morgan = require('morgan')
const fs = require('fs')
const cconsole = require('colorize').console
exports.command = 'mock <file> [options]'
exports.desc = 'Mocks a root RAML document.'
exports.builder = {
'port': {
description: 'Port number to bind the proxy.',
default: '8080',
nargs: 1,
requiresArg: true,
alias: 'p'
},
'cors': {
description: 'Enable CORS with the API',
boolean: true
}
}
exports.handler = function(argv) {
if (!fs.existsSync(argv.file)) {
cconsole.log('#red[File \'%s\' does not exist!]', argv.file)
process.exit(1)
}
mockService(argv.file, argv.port, argv.cors);
}
/**
* Call osprey-mocking-service to handle the input and generate a
* mock service for a given RAML file.
*
* @param file contains the API specification to generate the mocking service
* @param port defines on which port the mocking service should run (default: 8080)
* @param cors enables CORS with the API (default: false)
*/
function mockService(file: string, port: number, cors: boolean): void {
var options = {
cors: !!cors
}
mock.loadFile(file, options)
.then(function (app) {
var router = new Router()
// Log API requests.
router.use(morgan('combined'))
router.use(app)
var server = http.createServer(function (req, res) {
router(req, res, finalhandler(req, res))
})
server.listen(port, function () {
console.log('Mock service running at http://localhost:' + server.address().port)
})
})
.catch(function (err) {
console.log(err && err.stack || err.message)
process.exit(1)
})
}
<file_sep>/src/commands/compile.ts
import converter = require('oas-raml-converter')
const cconsole = require('colorize').console
exports.command = 'compile <file> [options]'
exports.desc = 'Compiles a root RAML document into a valid OpenAPI 2.0 document.'
exports.builder = {
'output': {
description: 'Compiled OpenAPI 2.0 document file path.',
default: './openapi.yml',
nargs: 1,
requiresArg: true,
alias: 'o'
}
}
exports.handler = function(argv) {
cconsole.log('Compile #blue[%s]...', argv.file)
// compile a RAML document `argv.file` into an OAS document `argv.output`
compile(argv.file, argv.output)
}
function compile(inputFile: string, outputFile: string): void {
var autoToOAS = new converter.Converter(converter.Formats.AUTO, converter.Formats.OAS)
var options = {
validate: true, // Parse both input and output to check that its a valid document
format: 'yaml', // Output format: json (default for OAS) or yaml (default for RAML)
}
autoToOAS.convertFile(inputFile, options).then(function(result) {
require('fs')
.writeFile(outputFile, result, function(err) {
if(err) {
cconsole.error('#red[%s]', err)
process.exit(1)
}
cconsole.log("#green[Successfully compiled OAS 2.0 document.]")
})
})
.catch(function(err) {
cconsole.error('#red[%s]', err)
process.exit(1)
})
}
<file_sep>/src/commands/init.ts
import path = require('path')
import Handlebars = require('handlebars')
import fs = require('fs')
const cconsole = require('colorize').console
const inquirerPrompt = require('inquirer').createPromptModule()
var defaultTemplate = `#%RAML 1.0
title: {{title}}
{{#if description}}
description: {{description}}
{{/if}}
`
exports.command = 'init [options]'
exports.desc = 'Initialize a RAML document.'
exports.builder = {
'template': {
description: 'File path of a custom Handlebars template.',
nargs: 1,
requiresArg: true,
alias: 't'
}
}
exports.handler = async function(argv) {
console.log("init...")
init(argv.template)
}
interface UserInput {
title: string,
description: string
}
function init(templateFile: string): void {
collectUserInput().then(input => {
if(templateFile) {
fs.readFile(templateFile, 'utf8', function(err, content) {
if(err) {
cconsole.error('#red[%s]', err)
process.exit(1)
}
initRamlDocument(content, input)
})
} else {
initRamlDocument(defaultTemplate, input)
}
})
.catch(function(err) {
cconsole.error('#red[%s]', err)
process.exit(1)
})
}
async function collectUserInput(): Promise<UserInput> {
const titleInput = await inquirerPrompt({
type: 'input',
name: 'title',
message: 'What is the title of your API? (empty string is not allowed):',
validate (title) {
if(title === '') {
return false
}
return true
}
})
const descInput = await inquirerPrompt({
type: 'input',
name: 'description',
message: 'How would you describe your API? (Enter to skip):'
})
return {
title: titleInput.title,
description: descInput.description
}
}
function initRamlDocument(source: string, context: UserInput): void {
console.log(context)
const template = Handlebars.compile(source)
const raml = template(context)
fs.writeFile("api.raml", raml, function(err) {
if(err) {
cconsole.error('#red[%s]', err)
process.exit(1)
}
cconsole.log('#green[Initialization successful!]')
})
}<file_sep>/src/commands/validate.ts
import raml_parser = require('raml-1-parser')
import path = require('path')
import fs = require('fs')
const cconsole = require('colorize').console
exports.command = 'validate <file>'
exports.desc = 'Validates a root RAML document against the RAML specification.'
exports.handler = function(argv) {
cconsole.log('Validating #blue[%s]...', argv.file)
const api = raml_parser.loadApi(argv.file, { rejectOnErrors: true, attributeDefaults: true })
api.then(function (result) {
cconsole.log('#green[Valid!]')
}).catch(function(error) {
cconsole.error('#red[%s]', JSON.stringify(error, null, 2))
process.exit(1)
})
}
<file_sep>/README.md
# RAML CLI Tool
> A handy command-line tool for RAML enthusiasts.
## Features
- **validate** - Validates a root RAML document against the specification.
- **compile** - Compiles a root RAML document into a valid OpenAPI 2.0 document.
- **init** - Initialize a basic RAML document based on user input.
- **mock** - Mocks a root RAML document.
## Installation
```
$ npm install -g raml-cli
```
## Usage
```
Usage: raml <command>
Commands:
compile <file> [options] Compiles a root RAML document into a valid OpenAPI 2.0
document.
init [options] Initialize a RAML document.
mock <file> [options] Mocks a root RAML document .
validate <file> Validates a root RAML document against the RAML
specification.
Options:
--help, -h Show help [boolean]
--version, -v Show version number [boolean]
For more information go to https://github.com/raml-org/raml-cli
```
## Command Overview
### `raml validate <file>`
The command can be used for validating the syntax of a RAML document as follows:
```
raml validate examples/simple.raml
```
if it succeds you see something like the following:
```
Validating examples/simple.raml...
Valid!
```
otherwise it will fail with a message containing an explanation on the error.
### `raml compile <file> [options]`
Compiles a root RAML document into a valid OpenAPI 2.0 document. It can be used as follows:
```
raml compile examples/simple.raml
```
if it succeds you see something like the following:
```
Compile examples/simple.raml...
Successfully compiled OAS 2.0 document.
```
otherwise it will fail with a message containing an explanation on the error.
#### Command options
**-o, --output [value]**
Type: `String`
Default: `openapi.yml`
Compiled OpenAPI 2.0 document file path.
### `raml init [options]`
Initialize a basic RAML document based on user input. It can be used as follows:
```
raml init
```
if it succeds you see something like the following:
```
init...
? What is the title of your API? (empty string is not allowed): <your title>
? How would you describe your API? (Enter to skip): <your description>
Initialization successful!
```
otherwise it will fail with a message containing an explanation on the error.
This command is using [Handlebars](http://handlebarsjs.com/) under the hood to initialize the RAML document. The following properties are supported at the moment:
- `title` (Title of your API and is equivalent to RAML's root node `title` - required)
- `description` (Description of your API and is equivalent to RAML's root node `description` - optional)
#### Command options
**-t, --template [value]**
Type: `String`
File path of a custom Handlebars template.
### `raml mock <file> [options]`
Mocks a root RAML document. It can be used as follows:
```
raml mock examples/simple.raml
```
if it succeds you see something like the following:
```
Mock service running at http://localhost:8080
```
otherwise it will fail with a message containing an explanation on the error.
#### Command options
**-p, --port [value]**
Type: `String`
Port number to bind the proxy. Default: `8080`.
**--cors [value]**
Type: `boolean`
Enable CORS with the API. Default: `false`.
|
9bbe1be3882e37eb42df52b5588f8090e3ff372d
|
[
"Markdown",
"TypeScript"
] | 5
|
TypeScript
|
raml-org/raml-cli
|
647690f0e9f24de6c2d5c9e7c43c4ea3079a82f8
|
a1759bc63614bb0ab020a51005e59a9c4c7421e9
|
refs/heads/master
|
<repo_name>harshumakkar/projects<file_sep>/README.md
# projects
This repository includes Calculator and Tictactoe that I made using Java.
<file_sep>/tictactoe.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class tictactoe implements ActionListener
{
Frame f;
JTextField tf1;
JButton res;
int count = 0;
int count00=0;
int count01=0;
int count02=0;
int count10=0;
int count11=0;
int count12=0;
int count20=0;
int count21=0;
int count22=0;
JButton b[][]= {
{new JButton (),new JButton (),new JButton ()},
{new JButton (),new JButton (),new JButton ()},
{new JButton (),new JButton (),new JButton ()},
};
tictactoe()
{
res = new JButton("Reset button");
res.setBounds(118,510,150,50);
f = new Frame();
tf1=new JTextField("Black's Turn");
tf1.setHorizontalAlignment(JTextField.CENTER);
tf1.setBounds(40,50,303,50);
res.addActionListener(this);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j].addActionListener(this);
}
}
f.add(tf1);
f.add(res);
f.addWindowListener(new WindowEventListener());
int x=40,y=200,width_=100,height_=100;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j].setBounds(x,y,width_,height_);
f.add(b[i][j]);
x=x+103;
}
y=y+100;
x=40;
}
Toolkit t=f.getToolkit();
Dimension screensize= t.getScreenSize();
int width=screensize.width*3/10;
int height=screensize.height*8/10;
f.setBounds(width/4,height/6,width,height);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b[0][0])
{
if(count00==0)
{
count00=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[0][0].setText("X");
b[0][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[0][0].setText("O");
b[0][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[0][1])
{
if(count01==0)
{
count01=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[0][1].setText("X");
b[0][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[0][1].setText("O");
b[0][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[0][2])
{
if(count02==0)
{
count02=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[0][2].setText("X");
b[0][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[0][2].setText("O");
b[0][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[1][0])
{
if(count10==0)
{
count10=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[1][0].setText("X");
b[1][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[1][0].setText("O");
b[1][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[1][1])
{
if(count11==0)
{
count11=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[1][1].setText("X");
b[1][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[1][1].setText("O");
b[1][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[1][2])
{
if(count12==0)
{
count12=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[1][2].setText("X");
b[1][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[1][2].setText("O");
b[1][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[2][0])
{
if(count20==0)
{
count20=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[2][0].setText("X");
b[2][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[2][0].setText("O");
b[2][0].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[2][1])
{
if(count21==0)
{
count21=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[2][1].setText("X");
b[2][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[2][1].setText("O");
b[2][1].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if(e.getSource()==b[2][2])
{
if(count22==0)
{
count22=1;
if(count%2==0)
{
tf1.setText("White's Turn");
b[2][2].setText("X");
b[2][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
else
{
tf1.setText("Black's Turn");
b[2][2].setText("O");
b[2][2].setFont(new Font("Arial", Font.PLAIN, 50));
}
count++;
}
}
if( (b[0][0].getText()=="X" && b[0][1].getText()=="X" && b[0][2].getText()=="X")
|| (b[1][0].getText()=="X" && b[1][1].getText()=="X" && b[1][2].getText()=="X")
|| (b[2][0].getText()=="X" && b[2][1].getText()=="X" && b[2][2].getText()=="X")
||(b[0][0].getText()=="X" && b[1][0].getText()=="X" && b[2][0].getText()=="X")
|| (b[0][1].getText()=="X" && b[1][1].getText()=="X" && b[2][1].getText()=="X")
|| (b[0][2].getText()=="X" && b[1][2].getText()=="X" && b[2][2].getText()=="X")
|| (b[0][0].getText()=="X" && b[1][1].getText()=="X" && b[2][2].getText()=="X")
|| (b[0][2].getText()=="X" && b[1][1].getText()=="X" && b[2][0].getText()=="X"))
{
tf1.setText("BLACK WINS....!");
tf1.setBackground(Color.PINK);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j].setBackground(Color.BLACK);
}
}
}
else if((b[0][0].getText()=="O" && b[0][1].getText()=="O" && b[0][2].getText()=="O")
|| (b[1][0].getText()=="O" && b[1][1].getText()=="O" && b[1][2].getText()=="O")
|| (b[2][0].getText()=="O" && b[2][1].getText()=="O" && b[2][2].getText()=="O")
|| (b[0][0].getText()=="O" && b[1][0].getText()=="O" && b[2][0].getText()=="O")
|| (b[0][1].getText()=="O" && b[1][1].getText()=="O" && b[2][1].getText()=="O")
|| (b[0][2].getText()=="O" && b[1][2].getText()=="O" && b[2][2].getText()=="O")
|| (b[0][0].getText()=="O" && b[1][1].getText()=="O" && b[2][2].getText()=="O")
|| (b[0][2].getText()=="O" && b[1][1].getText()=="O" && b[2][0].getText()=="O"))
{
tf1.setText("WHITE WINS....!");
tf1.setBackground(Color.PINK);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j].setBackground(Color.WHITE);
}
}
}
if(count==9)
{
tf1.setText("GAME OVER");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j].setBackground(Color.RED);
}
}
}
if(e.getSource()==res)
{
new tictactoe();
}
}
public static void main(String... s)
{
new tictactoe();
}
}
class WindowEventListener extends WindowAdapter
{
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
}
<file_sep>/Calc.java
import java.awt.*;
import java.awt.event.*;
//package com.javacodegeeks.javabasics.stringarray;
public class Calc implements ActionListener
{
Frame f;
TextField tf;
Button b[][]= {{new Button ("%"),new Button("CE"),new Button("C"),new Button("clr"),new Button("\u00F7")},{new Button("\u221A"),new Button("7"),new Button("8"),new Button("9"),new Button("\u00D7")},{new Button("x\u00B2"),new Button("4"),new Button("5"),new Button("6"),new Button("-")},{new Button("x\u00B3"),new Button("1"),new Button("2"),new Button("3"),new Button("+")},{new Button("1/x"),new Button("\u00B1"),new Button("0"),new Button("."),new Button("=")}};
Calc(String s )
{
tf=new TextField();
f= new Frame(s);
int x=40,y=100,width_=100,height_=100;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
b[i][j].setBounds(x,y,width_,height_);
f.add(b[i][j]);
x=x+100;
}
y=y+100;
x=40;
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
(b[i][j]).addActionListener(this);
}
}
Toolkit t=f.getToolkit();
Dimension screensize= t.getScreenSize();
int width=screensize.width*8/10;
int height=screensize.height*8/10;
f.setBounds(width/8,height/8,width,height);
tf.setBounds(40,50,500,50);
f.add(tf);
f.setBackground(Color.BLACK);
f.addWindowListener(new WindowEventListener());
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== b[1][1])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "7");
}
else
{
tf.setText("7");
}
}
if(e.getSource()==b[1][2])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "8");
}
else
{
tf.setText("8");
}
}
if(e.getSource()== b[1][3])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "9");
}
else
{
tf.setText("9");
}
}
if(e.getSource()== b[2][1])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "4");
}
else
{
tf.setText("4");
}
}
if(e.getSource()== b[2][2])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "5");
}
else
{
tf.setText("5");
}
}
if(e.getSource()== b[2][3])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "6");
}
else
{
tf.setText("6");
}
}
if(e.getSource()== b[3][1])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "1");
}
else
{
tf.setText("1");
}
}
if(e.getSource()== b[3][2])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "2");
}
else
{
tf.setText("2");
}
}
if(e.getSource()== b[3][3])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "3");
}
else
{
tf.setText("3");
}
}
if(e.getSource()== b[4][2])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "0");
}
else
{
tf.setText("0");
}
}
if(e.getSource()== b[3][4])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "+");
}
}
if(e.getSource()== b[2][4])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "-");
}
}
if(e.getSource()== b[1][4])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "\u00D7");
}
}
if(e.getSource()== b[0][4])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "\u00F7");
}
}
if(e.getSource()== b[0][2])
{
if(tf.getText()!= null)
{
tf.setText("");
}
}
if(e.getSource()== b[4][3])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + ".");
}
}
if(e.getSource()== b[0][0])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "%");
}
}
if(e.getSource()== b[1][0])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( "\u221A" + s1);
}
}
if(e.getSource()== b[2][0])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "\u00B2");
}
}
if(e.getSource()== b[3][0])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( s1 + "\u00B3");
}
}
if(e.getSource()== b[4][0])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
tf.setText( "1/" + s1);
}
}
if(e.getSource()==b[4][4])
{
if(tf.getText()!= null)
{
String s1=tf.getText();
String findstring="+";
boolean found=false;
for(String element:s1)
{
// String[] s1=new String[5];
//String[] parts = new String[s1.length()];
//parts=s1.split("+");
//String part1=parts[0];
//String part2=parts[1];
//System.out.println(part1);
//String sum=part1+part2;
//tf.setText("sum");
}
}
}
public static void main(String[] s)
{
new Calc("CASIO");
}
}
class WindowEventListener extends WindowAdapter
{
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
}
|
a0639af94b4bc21ed953057323e86d75da0c5578
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
harshumakkar/projects
|
03b5f1ecb401e51f939183c957087ffb5683dbed
|
1d4008d4a10a2753a23121796010a3f89042ad9e
|
refs/heads/master
|
<file_sep>use syntax::ast;
use syntax::ptr::P;
use component_builder::ComponentBuilder;
use syntax::ext::base::ExtCtxt;
#[derive(Debug)]
pub struct ECSBuilder {
pub component_builders: Vec<ComponentBuilder>
}
impl ECSBuilder {
pub fn build(&self, context: &ExtCtxt) -> Vec<P<ast::Item>> {
let component_indices: Vec<Option<P<ast::Item>>> =
self.component_builders.iter().fold(vec![], |acc, builder| -> Vec<Option<P<ast::Item>>> {
acc + &*builder.build_index(context)
});
let component_decls: Vec<Vec<ast::TokenTree>> =
self.component_builders.iter().map(|builder| -> Vec<ast::TokenTree> {
builder.build_decl(context)
}).collect();
let component_inits: Vec<Vec<ast::TokenTree>> =
self.component_builders.iter().map(|builder| -> Vec<ast::TokenTree> {
builder.build_init(context)
}).collect();
let structure = quote_item!(context,
#[derive(Debug, Clone)]
pub struct ECS {
$component_decls
};
);
let implementation = quote_item!(context,
impl ECS {
pub fn new() -> ECS {
ECS {
$component_inits
}
}
}
);
let items = component_indices + &[structure, implementation];
items.into_iter().map(|item| item.unwrap()).collect()
}
}
<file_sep>#![crate_type="dylib"]
#![feature(plugin_registrar, quote, rustc_private, unicode)]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::ptr::P;
use syntax::util::small_vector::SmallVector;
use syntax::parse;
use syntax::ast::TokenTree;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::codemap::Span;
use rustc::plugin::Registry;
use ecs_builder::ECSBuilder;
mod utils {
pub mod string_utils;
}
mod ecs_parser;
mod ecs_builder;
mod component_builder;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("component_store", expand);
}
fn expand(context: &mut ExtCtxt, _: Span, tokens: &[TokenTree]) -> Box<MacResult + 'static> {
let ecs_builder = match parse(context, tokens) {
Ok(result) => result,
Err(e) => panic!(e)
};
let ecs = MacroResult { ecs: ecs_builder.build(context) };
Box::new(ecs) as Box<MacResult>
}
struct MacroResult {
ecs: Vec<P<ast::Item>>
}
impl MacResult for MacroResult {
fn make_items(self: Box<MacroResult>) -> Option<SmallVector<P<ast::Item>>> {
Some(SmallVector::many(self.ecs.clone()))
}
}
fn parse(context: &mut ExtCtxt, tokens: &[TokenTree]) -> Result<ECSBuilder, &'static str> {
let mut parser = parse::new_parser_from_tts(context.parse_sess(), context.cfg(), tokens.to_vec());
ecs_parser::parse(&mut parser)
}
<file_sep>[package]
name = "component_store"
version = "0.0.1"
authors = ["<NAME> <<EMAIL>>"]
[lib]
name = "component_store"
crate_type = ["dylib"]
<file_sep>use syntax::parse::parser::Parser;
use syntax::parse::token;
use ecs_builder::ECSBuilder;
use component_builder::ComponentBuilder;
pub fn parse(parser: &mut Parser) -> Result<ECSBuilder, &'static str> {
match parse_component_header(parser) {
Ok(_) =>
parse_components(parser).map(|component_builders| -> ECSBuilder {
ECSBuilder {
component_builders: component_builders
}
}),
Err(e) => Err(e)
}
}
fn parse_component_header(parser: &mut Parser) -> Result<(), &'static str> {
match parse_ident(parser) {
Ok(parsed_ident) =>{
if &*parsed_ident == "components" {
if parser.eat(&token::Colon) { Ok(()) }
else { Err("Expected header to be followed by a colon") }
}
else { Err("Expected header to be `components:`") }
},
Err(e) => Err(e)
}
}
fn parse_components(parser: &mut Parser) -> Result<Vec<ComponentBuilder>, &'static str> {
parse_components_recursive(parser, Vec::new())
}
fn parse_components_recursive(parser: &mut Parser, mut components: Vec<Result<ComponentBuilder, &'static str>>) -> Result<Vec<ComponentBuilder>, &'static str> {
components.push(parse_component(parser));
match parser.token {
token::Ident(_, _) => { parse_components_recursive(parser, components) }
token::Eof => {
components.iter().fold(Ok(Vec::new()), |z, elem| -> Result<Vec<ComponentBuilder>, &'static str> {
let copy_elem = elem.clone();
match copy_elem {
Err(e) => Err(e),
Ok(component) => z.map(|v| -> Vec<ComponentBuilder> {
let mut next_vec = v.clone();
next_vec.push(component.clone());
next_vec
})
}
})
}
_ => { Err("Failed to parse list of components") }
}
}
fn parse_component(parser: &mut Parser) -> Result<ComponentBuilder, &'static str> {
parse_component_name(parser).and_then(|name| -> Result<ComponentBuilder, &'static str> {
parse_optional_plural(parser).and_then(|plural| -> Result<ComponentBuilder, &'static str> {
parse_optional_indices(parser).and_then(|indices| -> Result<ComponentBuilder, &'static str> {
let plural_or_default = plural.clone().unwrap_or(name.clone() + "s");
let indices_or_default = indices.clone().unwrap_or(Vec::new());
Ok(ComponentBuilder::new(name.clone(), plural_or_default, indices_or_default))
})
})
})
}
fn parse_component_name(parser: &mut Parser) -> Result<String, &'static str> {
match parse_ident(parser) {
Ok(pass) => Ok(pass),
Err(_) => Err("Failed to parse component name")
}
}
fn parse_ident(parser: &mut Parser) -> Result<String, &'static str> {
let result = match parser.token {
token::Ident(i, _) => Ok(i.as_str().to_string()),
_ => Err("Failed to parse ident")
};
parser.bump();
result
}
fn parse_optional_plural(parser: &mut Parser) -> Result<Option<String>, &'static str> {
if !parser.eat(&token::BinOp(token::Slash)) { return Ok(None) };
let result = match parser.token {
token::Ident(i, _) => Ok(Some(i.as_str().to_string())),
_ => Err("Pluralization name not found after slash")
};
parser.bump();
result
}
fn parse_optional_indices(parser: &mut Parser) -> Result<Option<Vec<String>>, &'static str> {
if !parser.eat(&token::LArrow) { return Ok(None) };
parse_index_list(parser).map(|inner| -> Option<Vec<String>> { Some(inner) })
}
fn parse_index_list(parser: &mut Parser) -> Result<Vec<String>, &'static str> {
parse_index_list_recursive(parser, Vec::new())
}
fn parse_index_list_recursive(parser: &mut Parser, mut indices: Vec<Result<String, &'static str>>) -> Result<Vec<String>, &'static str> {
indices.push(parse_index(parser));
if parser.eat(&token::Comma) { parse_index_list_recursive(parser, indices) }
else {
indices.iter().fold(Ok(Vec::new()), |z, elem| -> Result<Vec<String>, &'static str> {
let copy_elem = elem.clone();
match copy_elem {
Err(e) => Err(e),
Ok(index) => z.map(|v| -> Vec<String> {
let mut next_vec = v.clone();
next_vec.push(index.clone());
next_vec
})
}
})
}
}
fn parse_index(parser: &mut Parser) -> Result<String, &'static str> {
match parse_ident(parser) {
Ok(pass) => Ok(pass),
Err(_) => Err("Failed to parse index name")
}
}
<file_sep>use syntax::ast;
use syntax::ptr::P;
use syntax::ext::base::ExtCtxt;
use syntax::parse::token;
use utils::string_utils::snake_case;
#[derive(Debug, Clone)]
pub struct IdentPair {
snake: ast::Ident,
camel: ast::Ident
}
impl IdentPair {
pub fn new(name: &String) -> IdentPair {
IdentPair {
snake: ast::Ident::new(token::intern(&*snake_case(name))),
camel: ast::Ident::new(token::intern(&*name)),
}
}
}
#[derive(Debug, Clone)]
pub struct ComponentBuilder {
pub name: String,
pub plural: String,
pub indices: Vec<String>,
pub idents: ComponentBuilderIdents
}
#[derive(Debug, Clone)]
pub struct ComponentBuilderIdents {
pub name: IdentPair,
pub plural: IdentPair,
pub index: IdentPair,
pub find: IdentPair,
pub find_all: IdentPair,
pub remove: IdentPair,
pub remove_all: IdentPair,
pub update: IdentPair
}
impl ComponentBuilder {
pub fn new(name: String, plural: String, indices: Vec<String>) -> ComponentBuilder {
ComponentBuilder {
name: name.clone(),
plural: plural.clone(),
indices: indices,
idents: ComponentBuilderIdents {
name: IdentPair::new(&(name.clone() + "Component")),
plural: IdentPair::new(&plural),
index: IdentPair::new(&(name.clone() + "Index")),
find: IdentPair::new(&("find_".to_string() + &*name)),
find_all: IdentPair::new(&("find_all_".to_string() + &*plural)),
remove: IdentPair::new(&("remove_".to_string() + &*name)),
remove_all: IdentPair::new(&("remove_all_".to_string() + &*plural)),
update: IdentPair::new(&("update_".to_string() + &*name))
}
}
}
pub fn build_index(&self, context: &ExtCtxt) -> Vec<Option<P<ast::Item>>> {
let name_ident = self.idents.name.camel.clone();
let index_ident = self.idents.index.camel.clone();
let find_ident = self.idents.find.snake.clone();
let find_all_ident = self.idents.find_all.snake.clone();
let remove_ident = self.idents.remove.snake.clone();
let remove_all_ident = self.idents.remove_all.snake.clone();
let update_ident = self.idents.update.snake.clone();
let structure = quote_item!(context,
#[derive(Clone, Debug)]
pub struct $index_ident {
primary_index: HashMap<String, $name_ident>
}
);
let implementation = quote_item!(context,
impl $index_ident {
pub fn new() -> $index_ident {
$index_ident {
primary_index: HashMap::new()
}
}
pub fn $find_all_ident(&self) -> Vec<&$name_ident> {
self.primary_index.values().collect()
}
pub fn $find_ident<Q: ?Sized>(&self, key: &Q) -> Option<&$name_ident>
where String: std::borrow::Borrow<Q>, Q: std::hash::Hash + std::cmp::Eq {
self.primary_index.get(key)
}
pub fn $update_ident(&mut self, key: String, value: $name_ident) -> Option<$name_ident> {
self.primary_index.insert(key, value)
}
pub fn $remove_all_ident(&mut self) {
self.primary_index = HashMap::new();
}
pub fn $remove_ident<Q: ?Sized>(&mut self, key: &Q)
where String: std::borrow::Borrow<Q>, Q: std::hash::Hash + std::cmp::Eq {
self.primary_index.remove(key);
}
}
);
vec!(structure, implementation)
}
pub fn build_decl(&self, context: &ExtCtxt) -> Vec<ast::TokenTree> {
let index_ident = self.idents.index.camel.clone();
let plural_ident = self.idents.plural.snake.clone();
quote_tokens!(context,
pub $plural_ident: $index_ident,
)
}
pub fn build_init(&self, context: &ExtCtxt) -> Vec<ast::TokenTree> {
let index_ident = self.idents.index.camel.clone();
let plural_ident = self.idents.plural.snake.clone();
quote_tokens!(context,
$plural_ident: $index_ident::new(),
)
}
}
<file_sep>pub fn snake_case(s: &String) -> String {
let mut snake = s.chars().fold(String::new(), |acc, letter| -> String {
if letter.is_uppercase() { append_upper(acc, letter.to_lowercase()) }
else if [' ', '-', '_'].contains(&letter) { append_seperator(acc) }
else { append_other(acc, letter.to_lowercase()) }
});
match snake.chars().next_back() {
Some(last) if last == '_' => {
snake.pop();
snake
}
_ => snake
}
}
fn append_upper(mut prev: String, tail: char) -> String {
match prev.chars().next_back() {
None => {
prev.push(tail);
prev
}
Some(last) if last == '_' => {
prev.push(tail);
prev
}
_ => {
prev.push('_');
prev.push(tail);
prev
}
}
}
fn append_seperator(mut prev: String) -> String {
match prev.chars().next_back() {
None => prev,
Some(last) if last == '_' => prev,
_ => {
prev.push('_');
prev
}
}
}
fn append_other(mut prev: String, tail: char) -> String {
prev.push(tail);
prev
}
#[test]
fn test_snake_on_empty() {
let original_string = "".to_string();
assert_eq!(snake_case(&original_string), original_string);
}
#[test]
fn test_snake_on_single_upper() {
let original_string = "A".to_string();
let expected_string = "a".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
#[test]
fn test_snake_on_single_lower() {
let original_string = "a".to_string();
assert_eq!(snake_case(&original_string), original_string);
}
#[test]
fn test_snake_on_single_upper_word() {
let original_string = "Abc".to_string();
let expected_string = "abc".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
#[test]
fn test_snake_on_single_lower_word() {
let original_string = "abc".to_string();
assert_eq!(snake_case(&original_string), original_string);
}
#[test]
fn test_snake_on_multi_upper_word() {
let original_string = "AbcDefGhi".to_string();
let expected_string = "abc_def_ghi".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
#[test]
fn test_snake_on_multi_upper_word_with_seperators() {
let original_string = "Abc Def_Ghi-jkl".to_string();
let expected_string = "abc_def_ghi_jkl".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
#[test]
fn test_snake_on_leading_space() {
let original_string = " _ Abc".to_string();
let expected_string = "abc".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
#[test]
fn test_snake_on_trailing_space() {
let original_string = "bc d ".to_string();
let expected_string = "bc_d".to_string();
assert_eq!(snake_case(&original_string), expected_string);
}
|
1f556a64eb1168ad1d42771848b5476227485a7d
|
[
"TOML",
"Rust"
] | 6
|
Rust
|
rschifflin/rust-component-store
|
f6d79138458ef3a7d0e7e1d39d32624b4f957924
|
9497f79f139b9a4b0836eb427a6d437987b1a956
|
refs/heads/master
|
<repo_name>kevinpost/IT202-fullstack-prototype<file_sep>/public/js/application/common/pages/form/Field.js
define([
'app'
,'marionette'
,'text!./Field.html'
], function(
App
,Marionette
,tpl
) {
'use strict';
return Marionette.ItemView.extend({
template: tpl,
events: {
'blur input': '_blur'
},
initialize: function() {
this._configureModel();
},
onRender: function() {
this._renderInput();
},
validate: function() {
},
getValue: function() {
return this.model.get('value');
},
displayError: function(error) {
var $input = this.$el.find('input');
$input.tooltip({
title: error,
trigger: 'manual'
});
$input.tooltip('show');
},
clearError: function() {
this.$el.find('input').tooltip('destroy');
},
_configureModel: function() {
},
_renderInput: function() {
var type = this.model.get('type'),
name = this.model.get('name');
if(type !== 'select') {
var input = document.createElement('input');
input.id = name;
input.setAttribute('name', name);
input.setAttribute('type', type);
this.$el.append(input);
this.input = input;
}
},
_blur: function() {
this._setValue();
this.clearError();
this.validate();
},
_setValue: function() {
var value = $(this.input).val();
this.model.set('value', value);
}
});
});<file_sep>/public/js/app.js
define([
'marionette'
,'handlebars'
,'application/common/pages/layout/LayoutView'
,'application/common/pages/messages/Messages'
], function(
Marionette
,Handlebars
,LayoutView
,MessagesView
) {
'use strict';
var App = new Marionette.Application();
App.addRegions({
body: 'body'
});
App.addInitializer(function() {
// we want to override backbone's manual use of the underscore templating engine
Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate) {
return Handlebars.compile(rawTemplate);
}
// load default view and define map application regions
App.body.show(new LayoutView());
App.addRegions({
messages: '#messages',
header: '#header',
content: '#content',
footer: '#footer'
});
// message view
App.messages.show(new MessagesView(App));
// module loading
});
return App;
});<file_sep>/router.js
module.exports = function(app, express) {
var router = express.Router();
app.use('/api', router);
/**
* Router mapping object automatically sets up app routers to controllers and functions.
*
* '/<url in relation to '/api'>': {
* type: '<HTTP request type (e.g. POST). IF NONE SPECIFIED, DEFAULT = GET>'
* cont: '<controller path in relation to './controllers'>',
* func: '<function name in controller object>
* }
*
*/
var routes = {
// grocery example
'/grocery/add': {
type: 'POST',
cont: 'grocery',
func: 'add'
},
'/grocery/get': {
cont: 'grocery',
func: 'get'
},
// test routes
'/testGet': {
cont: 'test',
func: 'testGet'
},
'/testSave': {
type: 'POST',
cont: 'test',
func: 'testSave'
},
// auth
'/login': {
type: 'POST',
cont: 'auth',
func: 'login'
}
}
/**
* Route mapping to application controllers.
*/
for(var key in routes) {
var opts = routes[key],
controller = require('./app/controllers/' + opts.cont),
type = opts.type;
// default to 'GET if does not exist, conver to lowcaps'
if(type === undefined) {
type = 'get'
}
type = type.toLowerCase();
router[type](key, controller[opts.func])
}
console.log('Routes mapped to controllers!')
}<file_sep>/public/js/application/pages/form/views/add.js
define([
'app'
,'marionette'
,'text!../templates/add.html'
,'bootstrap'
], function(
App
,Marionette
,tpl
) {
var ItemModel = Backbone.Model.extend({
defaults: {
name: String,
quantity: Number,
notes: String
},
url: function() {
return '/api/grocery/add'
}
});
'use strict';
return Marionette.ItemView.extend({
template: tpl,
events: {
'blur input': 'updateField',
'click button': 'submitForm'
},
model: new ItemModel(),
updateField: function(e) {
var field = e.target;
this.model.set(field.name, field.value);
},
processResponse: function(resp) {
console.log(resp);
console.log(this);
},
submitForm: function(e) {
e.preventDefault();
App.vent.trigger('message:error', 'Not functioning yet!');
}
});
});<file_sep>/public/js/config.js
require.config({
// define dependencies
paths: {
jQuery: 'libs/jquery',
underscore: 'libs/underscore',
backbone: 'libs/backbone',
marionette: 'libs/backbone.marionette',
handlebars: 'libs/handlebars',
bootstrap: 'libs/bootstrap',
text: 'libs/text',
'backbone-forms': 'libs/backbone-forms',
// shortcuts
common: 'application/common'
},
// defining shims (AMD design pattern)
shim: {
bootstrap: {
deps: ['jQuery']
},
jQuery: {
exports: '$'
},
underscore: {
exports: '_'
},
handlebars: {
exports: 'Handlebars'
},
backbone: {
deps: ['jQuery', 'underscore'],
exports: 'Backbone'
},
marionette: {
deps: ['jQuery', 'underscore', 'backbone'],
exports: 'Marionette'
},
backboneForms: {
deps: ['backbone']
}
}
});
require(['app', 'router'], function(App, Router) {
App.start();
var router = new Router();
Backbone.history.start();
});<file_sep>/app/modules/modelValidator2.js
// DEPRECATED!!!
var validator = {
validate: function(model, rules, callback) {
var errors = [];
for(var fieldName in rules) {
console.log(fieldName);
var value = model[fieldName];
// escape if parameter is missing in model
if(value === undefined) {
console.log('parameter undefined');
errors.push({
fieldName: fieldName,
message: 'Parameter undefined'
});
errors.push({
});
callback(errors);
return;
}
for(var validator in rules[fieldName]) {
var param = rules[fieldName][validator],
valid = this.validators[validator](value, param),
message;
if(valid !== true) {
// valid false? get message from list, else use provided
message = (valid === false) ? this.messages[validator] : valid;
}
if(message !== undefined && message.length) {
errors.push({
fieldName: fieldName,
message: message
});
}
}
}
errors = errors.length ? errors : false;
if(callback) {
callback(errors);
}
},
validators: {
required: function(value, param) {
if(param && value) {
return true;
}
return false;
},
maxLength: function(value, param) {
if(String(value).length >= param) {
return true;
}
return 'Maximum lenth is ' + param;
}
},
messages: {
required: 'This is a required field',
maxLength: 'Maximum length exceeded'
}
}
exports.validate = function(model, rules, callback) {
validator.validate(model, rules, callback);
}<file_sep>/public/js/application/common/pages/layout/LayoutView.js
define([
'marionette'
,'text!./Layout.html'
], function(
Marionette
,tpl
) {
'use strict';
return Marionette.LayoutView.extend({
template: tpl
});
});<file_sep>/public/js/application/common/pages/messages/Message.js
define([
'marionette'
,'text!./Message.html'
], function(
Marionette
,tpl
) {
'use strict';
return Marionette.ItemView.extend({
template: tpl,
className: 'alert alert-dismissible',
initialize: function(opts) {
opts.type = opts.type || 'success';
opts.message = opts.message || '';
this.model = new Backbone.Model(opts);
this.$el.addClass('alert-' + opts.type);
this.$el.attr('role', 'alert');
},
onRender: function() {
// automatically dismiss alert after 3 seconds
var self = this;
setTimeout(function() {
self.destroy();
}, 3000);
}
});
});<file_sep>/app/models/groceryItem.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var GroceryItemSchema = new Schema({
name: String,
quantity: Number,
notes: String
});
module.exports = mongoose.model('GroceryItem', GroceryItemSchema);<file_sep>/app/controllers/auth.js
exports.login = function(req, res) {
res.json({
data: {
token: ''
},
messages: [
{
type: 'success',
message: 'auth\'d'
}
]
})
}<file_sep>/public/js/application/pages/form/views/add2.js
define([
'app'
,'marionette'
,'text!../templates/layout.html'
,'common/pages/form/Form'
], function(
App
,Marionette
,tpl
,FormView
) {
'use strict';
return FormView.extend({
service: {
url: 'api/grocery/add'
},
fields: {
name: {
label: 'Item Name',
type: 'text',
required: true
},
quantity: {
type: 'number',
required: true
},
notes: {
type: 'textarea'
}
},
rules: {
name: {
required: true,
maxLength: 30
},
quantity: {
required: true
},
notes: {
maxLength: 50
}
},
onResponse: function(response) {
console.log(response);
}
});
});<file_sep>/public/js/router.js
define([
'app'
,'backbone'
,'marionette'
,'application/common/pages/404/404'
,'application/common/pages/login/login'
], function(
App
,Backbone
,Marionette
,view404
,LoginView
) {
'use strict';
// define app routes
var Router = Backbone.Marionette.AppRouter.extend({
routes: {
'*action': 'loadRoute'
},
loadRoute: function(route) {
if (route === '') {
route = 'index';
}
var view = require([('application/pages/' + route + '/views/index')], function(view) {
App.content.show(new view());
},
// if we can't find the file...
function(error) {
App.content.show(new view404(route));
});
}
});
return Router;
});<file_sep>/app/modules/modelValidator.js
var validator = {
validators: {
required: function(value, param) {
if(param && value) {
return true;
}
return false;
},
maxLength: function(value, param) {
if(String(value).length <= param) {
return true;
}
return 'Maximum length is ' + param;
}
},
messages: {
required: 'This is a required field',
maxLength: 'Maximum length exceeded'
},
/**
* Don't touch below
*/
validateModel: function(model, rules, callback) {
var errors = [];
for(var fieldName in rules) {
var error = this.validateField(model[fieldName], rules[fieldName]);
if(error !== true) {
error = {
fieldName: fieldName,
message: error
};
errors.push(error);
}
}
if(callback) {
callback(errors);
}
},
validateField: function(value, rules) {
var message;
for(var rule in rules) {
var validator = this.validators[rule],
param = rules[rule],
valid = validator(value, param);
if(valid !== true) {
message = (valid === false) ? this.messages[rule] : valid;
break;
}
}
if(message) {
return message;
}
else return true;
}
}
exports.validate = function(model, rules, callback) {
validator.validateModel(model, rules, callback);
}<file_sep>/public/js/application/pages/form/views/list.js
define([
'app'
,'marionette'
,'./listItem'
,'../collections/items'
], function(
App
,Marionette
,ListItemView
,Collection
) {
'use strict';
return Marionette.CollectionView.extend({
childView: ListItemView,
collection: new Collection(),
initialize: function() {
this.collection.fetch();
var self = this;
App.vent.on('form:response:received', function() {
self.collection.fetch();
});
}
});
});<file_sep>/app.js
/**
* Express App Bootstrap
*/
var express = require('express')
,mongoose = require('mongoose')
,fs = require('fs')
,path = require('path')
,passport = require('passport')
,bodyParser = require('body-parser')
//,BasicStrategy = require('passport-http').BasicStrategy;
DigestStrategy = require('passport-http').DigestStrategy
;
var app = express();
var port = process.env.PORT || 3000;
// Passport Authentication
passport.use(new DigestStrategy({qop: 'auth'},
function(username, done) {
}
));
// Serve public directory:
app.use(express.static(path.join(__dirname, 'public')));
// Body Parser to recognize JSON
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// Mongoose Setup:
mongoose.connect('mongodb://localhost/bootstrap')
// Pull in application router:
require('./router')(app, express);
app.listen(port);
console.log('Express app launched on port ' + port);<file_sep>/public/js/application/modules/session.js
define([
'marionette'
], function(
Marionette
) {
'use strict';
return Marionette.Module.extend({
initialize: function() {
},
onStart: function() {
},
onStop: function() {
}
});
});<file_sep>/public/js/application/common/pages/messages/Messages.js
define([
'marionette'
,'text!./Messages.html'
,'./Message'
], function(
Marionette
,tpl
,MessageView
) {
'use strict';
return Marionette.ItemView.extend({
template: tpl,
className: 'clearfix container',
types: ['success','warning','error'],
initialize: function(App) {
this._bindVentListeners(App);
},
message: function(type, message) {
type = (type === 'error') ? 'danger' : type;
var message = new MessageView({
type: type,
message: message
});
this.$el.append(message.render().el);
},
_bindVentListeners: function(App) {
var self = this;
_.each(this.types, function(type) {
var messager = function(message) {
self.message(type, message)
}
App.vent.on('message:' + type, messager)
});
}
});
});<file_sep>/public/README.md
prototype
=========
Prototype application for IT 202 NJIT CCS
<file_sep>/app/modules/modelHandler.js
var Validator = require('../modules/modelValidator'),
Response = function() {
this.data = {};
this.messages = [];
this.errors = [];
}
var form = {
add: function(opts, callback) {
var req = opts.req || null,
res = opts.res || null,
model = opts.model || null,
rules = opts.rules || null,
success = opts.success || null,
response = new Response();
console.log(model);
// validate the model with the rules
Validator.validate(model, rules, function(errors) {
// if no errors, attempt to save the object
if(!errors.length) {
model.save(function(err) {
if(err) {
response.errors.push({
fieldName: null,
message: 'An error occured, please contact your system adminsitrator.'
});
}
else if(success){
response.messages.push({
type: 'success',
message: success
});
}
if(callback) {
var newResponse = callback(response) || false;
if(newResponse) {
res.json(newResponse);
}
// if not returned back, return the original as a fail safe
else res.json(response);
}
// if no callback defined
else res.json(response);
});
}
// otherwise, notify the user that model validation failed
else {
console.log(errors);
response.errors = errors;
res.json(response);
}
});
}
};
exports.save = function(opts, callback) {
form.add(opts, callback);
}<file_sep>/app/controllers/test.js
var TestModel = require('../models/testModel'),
Validator = require('../modules/modelValidator'),
ModelHandler = require('../modules/modelHandler');
exports.testGet = function(req, res) {
res.json({
message: 'hello world'
});
}
exports.testSave = function(req, res) {
var testModel = new TestModel(req.query),
rules = {
testValue: {
required: true,
maxLength: 30
},
testValue2: {
required: true,
maxLength: 30
}
};
ModelHandler.save({
req: req,
res: res,
model: testModel,
rules: rules,
success: 'Success!'
}, function(response) {
console.log(response);
response.messages.push({
type: 'success',
message: 'test add extra message'
});
// must return response if callback defined
return response;
});
}
<file_sep>/public/js/application/pages/index/views/index.js
define([
'app'
,'marionette'
,'text!../templates/template.html'
], function(
App
,Marionette
,tpl
) {
'use strict';
return Marionette.ItemView.extend({
template: tpl
});
});<file_sep>/public/js/application/common/pages/login/login.js
define([
'app'
,'backbone'
,'marionette'
,'text!./template.html'
], function(
App
,Backbone
,Marionette
,tpl
) {
'use strict';
return Marionette.ItemView.extend({
template: tpl,
events: {
'click #login-btn': 'submitLogin'
},
submitLogin: function(e) {
e.preventDefault();
var data = {
username: $('#username').val(),
password: <PASSWORD>').val()
};
console.log(data);
}
});
});
|
25b0338f2e837fa904c1882638c443b74be7be04
|
[
"JavaScript",
"Markdown"
] | 22
|
JavaScript
|
kevinpost/IT202-fullstack-prototype
|
8e05b34a698d8287e43658268a6197b7cd707f7b
|
fd78a9b562b3310219baef140917653bca1361b5
|
refs/heads/master
|
<file_sep># Programming Assignment 1
This repository is used as a way to provide to students
a starting point for CSC 220 Programming Assignment 1,
as well as a way to turn in the assignment.
Programming Assignment 1 is based on
[Programming Project](http://proquest.safaribooksonline.com/9781284141092/sec10_10_7_html#sec10-10-7)
55 from Chapter 10 of the textbook,
as developed within the framework of this repository.
Some additional directions:
+ The package structure started in the repository must be followed, including both the names and contents of the packages.
+ Each java and xml file must have an appropriate header comment, including the student's name, email address, and the date of submission.
+ Comments within the existing classes in the repository provide specific directions that also must be followed.
+ You should clone this repository to a folder on your network drive (i.e., your H drive), then create a new local branch named
pa1-*your-mountunion-email-name*. For example, I would create a branch named pa1-weberk.
Your score will be based on the following items:
| Item | Possible score |
|------|---------------:|
| `UtilityCustomer` is properly declared according to the specifications in the textbook | 3 |
| `GasCustomer` is properly declared according to the specifications in the textbook | 3 |
| `ElecticCustomer` is properly declared according to the specifications in the textbook | 3 |
| Package structure is the same as that originally provided in the master branch of the repository | 2 |
| Good programming practices, including naming and indentation conventions, as well as proper use of access modifiers such as `private` and `protected`, are followed | 3|
| Every file has an appropriate header comment | 2 |
| The client creates several objects of each subclass and adds them to `customerList` | 2 |
| The client steps through `customerList` and prints the bill amount and customer name for each customer in the list | 2|
| Total | 20|
|Exra credit: the bill amounts and customer names are displayed in the client's FXML pane instead of the Java console | 3 |
Programming Assignment 1 is due Friday, September 14 at class time.
You will turn the assignment in by pushing your branch to GitHub. **Note Well:** this will not be possible until class time of the day that it's due, and it will *only* be possible to do this during class that day.
<file_sep>/*
<NAME>
PA5 - Dr. Weber CSC 220
12/7/2018
ClothingStack class
*/
package clothing;
import java.util.ArrayList;
import javafx.scene.paint.Color;
public class ClothingStack
{
private static class Node<ClothingItem> { ClothingItem item; Node next; }
private Node<ClothingItem> first;
public ClothingStack( )
{
first = null;
} // end of constructor
public ClothingStack( ClothingItem item )
{
Node<ClothingItem> tmp = new Node<>();
tmp.item = item;
tmp.next = null;
first = tmp;
}
public void push(ClothingItem item)
{
Node<ClothingItem> tmp = new Node<>();
tmp.item = item;
if ( first != null )
{
first = tmp.next;
first = tmp;
}
else
{
first = tmp;
tmp.next = null;
}
}
public ClothingItem pop()
{
Node<ClothingItem> tmp = new Node<>();
if ( first == null )
{
System.out.println("Can't pop empty stack.");
return null;
}
else
{
tmp.item = first.item;
first = first.next;
return tmp.item;
}
}
public ClothingItem peek()
{
if (first == null)
{
System.out.println("Can't peek empty stack.");
return null;
}
else
{
return first.item;
}
}
// This is an additional method your code must implement.
// Returns true iff there is at least one item on the stack.
public boolean hasNext()
{
if (first != null) {
return true;
} else
{
return false;
}
}
@Override
public String toString()
{
if (first == null)
{
return "";
}
else
{
return first.item.toString();
}
}
public ClothingItem[] itemsOfColor(Color color)
{
Node<ClothingItem> tmp = first;
tmp.item = first.item;
ClothingItem item = tmp.item;
ArrayList<ClothingItem> items = new ArrayList<>();
while (tmp.next != null)
{
if (item.getColor().equals(color))
{
items.add(item);
}
tmp = tmp.next;
}
if ( tmp.next == null && item.getColor( ).equals(color) )
{
items.add( item );
}
ClothingItem[] clothesOfColor =
items.toArray(new ClothingItem[items.size()]);
return clothesOfColor;
}
public int numberOfItemsWashableAtHighTemperature()
{
int highSum = 0;
Node<ClothingItem> tmp = first;
ClothingItem item = tmp.item;
while ( tmp.next != null )
{
if ( item.getWash().equals(true))
{
highSum += 1;
}
tmp = tmp.next;
}
if ( tmp.next == null && item.getWash( ).equals(true) )
{
highSum += 1;
}
return highSum; // Replace with your own code.
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author schrotbe2021
*/
public class NHLPlayer {
private String name;
private Integer gamesPlayed, goals, assists;
private Boolean allStar;
public NHLPlayer(String n, Integer gp, Integer g, Integer a, Boolean as) {
name = n;
gamesPlayed = gp;
goals = g;
assists = a;
allStar = as;
} // end of constructor
public String toString(){
String answer;
answer = name + " has " + goals + " goals and " + assists + " assists in " + gamesPlayed
+ " games played. It is " + allStar + " that he made the All Star team in 2018.";
return answer;
} //end of toString
// getters
public String getName() {
return name;
}
public Integer getgamesPlayed() {
return gamesPlayed;
}
public Integer getGoals() {
return goals;
}
public Integer getAssists() {
return assists;
}
public Boolean getallStar() {
return allStar;
}
//setters
public void setName( String n ) {
name = n;
}
public void setgamesPlayed( Integer gp ) {
gamesPlayed = gp;
}
public void setGoals ( Integer g ) {
goals = g;
}
public void setAssists( Integer a ) {
assists = a;
}
public void setallStar ( Boolean as ) {
allStar = as;
}
} //end of NHLPlayer
<file_sep>/*
The arraylist inside the arraylist class.
*/
package pa2_package;
public class ProcessString {
public String behavior;
public Integer runTime;
public ProcessString(String b, Integer t)
{
behavior = b;
runTime = t;
}
public Integer timePassed() {
runTime--;
return runTime;
}
public ProcessString getTraceTape() { return this; }
public void setType(String t)
{
t = behavior;
}
public Integer getStateBurst() { return runTime; }
public void setRunTime(Integer r)
{
r = runTime;
}
@Override
public String toString()
{
return "" + behavior + " " + runTime + " ";
}
}
<file_sep>/*
<NAME>
PA1 CS370
Dr. Klayder
Description: An operating system simulator that simulates process being
ran using the Round Robin Algorithm
Log: [Date, Time (Hours), Description]
[9/3, 1.0, GUI Design, Documentation, Added supporting classes]
[9/4, 1.0, Added constructor Simulator.java, Added validityCheck() to simulator,
Tested to make sure validity checks are working]
[9/10, 1.5, Added fillArray() method, general cleaning up of code]
[9/11, 1.0, Finished read button but no output]
[9/12, 1.0, Fixed problem of no output after pressing stats button,
added ticker and newList to schedule processes.]
[9/17, 3.0, Cleaned up documentation, Finished ticker, added readList
Added running clock, Added JSlider, run/pause button gets
information from slider]
[11/2, 5.0 Added move to runningList and move to waitingList]
[11/3 3.0 Made processes able to jump from ready to running, running
to waiting, and waiting to running]
[11/5, 4.0 Added calculation for CPU utilization, throughput, and
waiting times]
[11/13, 2.0 Added FirstResponse, turnaround time, dispatch latency,
and added more documentation.]
Revisions:
[12/3, .5 Fixed dispatch latency to only when it goes into running.]
[12/4, 1.0 Added documentation for data members in Process.java & Simulator.java
Fixed doc to say Operating System simulator. Fixed average wait time
to correct formula.
*/
package pa2_package;
public class ProcessJFrame extends javax.swing.JFrame {
private final Simulator sim;
private Integer tickValue;
public ProcessJFrame() {
initComponents();
sim = new Simulator(inputArea, outputArea); // Initializes simulator.
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
aboutButton = new javax.swing.JButton();
readButton = new javax.swing.JButton();
statsButton = new javax.swing.JButton();
tickButton = new javax.swing.JButton();
runPauseButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
inputArea = new javax.swing.JTextArea();
inputLabel = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
outputArea = new javax.swing.JTextArea();
outputLabel = new javax.swing.JLabel();
clearText = new javax.swing.JButton();
tickSlider = new javax.swing.JSlider();
tickLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
aboutButton.setText("About");
aboutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutButtonActionPerformed(evt);
}
});
readButton.setText("Read Data");
readButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
readButtonActionPerformed(evt);
}
});
statsButton.setText("Stats");
statsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
statsButtonActionPerformed(evt);
}
});
tickButton.setText("Tick");
tickButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tickButtonActionPerformed(evt);
}
});
runPauseButton.setText("Run/Pause");
runPauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runPauseButtonActionPerformed(evt);
}
});
inputArea.setColumns(20);
inputArea.setRows(5);
jScrollPane1.setViewportView(inputArea);
inputLabel.setText("Input:");
outputArea.setColumns(20);
outputArea.setRows(5);
jScrollPane2.setViewportView(outputArea);
outputLabel.setText("Output:");
clearText.setText("Clear Text Areas");
clearText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearTextActionPerformed(evt);
}
});
tickSlider.setMajorTickSpacing(100);
tickSlider.setMaximum(5000);
tickSlider.setMinimum(100);
tickSlider.setOrientation(javax.swing.JSlider.VERTICAL);
tickSlider.setPaintTicks(true);
tickSlider.setValue(3000);
tickSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tickSliderStateChanged(evt);
}
});
tickLabel.setText("Tick Speed:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(clearText)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(outputLabel)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tickSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(13, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(aboutButton)
.addGap(18, 18, 18)
.addComponent(readButton)
.addGap(18, 18, 18)
.addComponent(statsButton)
.addGap(18, 18, 18)
.addComponent(tickButton)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(runPauseButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tickLabel)
.addGap(59, 59, 59))))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(aboutButton)
.addComponent(readButton)
.addComponent(statsButton)
.addComponent(tickButton)
.addComponent(runPauseButton))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(inputLabel))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tickLabel)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(outputLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(tickSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(clearText)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed
clearText();
inputArea.setText("<NAME>\n"
+ "Operating System Simulator v3.0\n"
+ "PA2 CSC370\n"
+ " Notes: An operating system simulator taking data in and scheduling the proceses using the ROund Robin Algorithm.");
}//GEN-LAST:event_aboutButtonActionPerformed
// Displays about information.
private void readButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readButtonActionPerformed
outputArea.setText("");
sim.validityCheck();
sim.fillArray();
}//GEN-LAST:event_readButtonActionPerformed
// Clears output, validates data and fills the array.
private void clearTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearTextActionPerformed
clearText();
}//GEN-LAST:event_clearTextActionPerformed
private void statsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_statsButtonActionPerformed
sim.statsButton();
}//GEN-LAST:event_statsButtonActionPerformed
private void tickButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tickButtonActionPerformed
sim.tickButton();
}//GEN-LAST:event_tickButtonActionPerformed
private void runPauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runPauseButtonActionPerformed
sim.runPauseButton(tickSlider);
}//GEN-LAST:event_runPauseButtonActionPerformed
private void tickSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tickSliderStateChanged
tickLabel.setText("Tick Speed: " + Integer.toString(tickSlider.getValue()) + " ms");
tickValue = tickSlider.getValue();
}//GEN-LAST:event_tickSliderStateChanged
public void clearText(){
inputArea.setText("");
outputArea.setText("");
} // Method makes it easier to clear text areas.
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ProcessJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProcessJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProcessJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProcessJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ProcessJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton aboutButton;
private javax.swing.JButton clearText;
private javax.swing.JTextArea inputArea;
private javax.swing.JLabel inputLabel;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea outputArea;
private javax.swing.JLabel outputLabel;
private javax.swing.JButton readButton;
private javax.swing.JButton runPauseButton;
private javax.swing.JButton statsButton;
private javax.swing.JButton tickButton;
private javax.swing.JLabel tickLabel;
private javax.swing.JSlider tickSlider;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
<NAME>
Dr. Weber
CSC 220
10/2/2018
PA2
*/
package client;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Client extends Application {
// This starts the View part of this MVC application.
// The Model is started in ClientController.
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ClientView.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
// This launches the entire Application.
public static void main(String[] args) {
launch(args);
}
}
<file_sep>
import java.awt.Color;
import java.awt.Graphics;
/*
* 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.
*/
/**
*
* @author schrotbe2021
*/
public class Background {
private Integer anchorX, anchor2X, anchorRX;
private Integer anchorY, anchor2Y, anchorRY;
private Integer rows, columns;
public Background() {
anchorX = 0;
anchorY = 250;
anchor2X = 0;
anchor2Y = 490;
anchorRX = 800;
anchorRY = 0;
rows = 5;
columns = 30;
} // end of constructor
void draw(Graphics g){
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 250, 800, 240);
g.setColor(new Color(144, 238, 144));
g.fillRect(0, 0, 800, 250);
g.setColor(Color.BLACK);
g.drawLine(775, 250, 775, 490);
g.drawLine(0, 250, 800, 250);
g.drawLine(0, 290, 800, 290);
g.drawLine(0, 330, 800, 330);
g.drawLine(0, 370, 800, 370);
g.drawLine(0, 410, 800, 410);
g.drawLine(0, 450, 800, 450);
g.drawLine(0, 490, 800, 490);
} // end of draw method
} // end of Background class
<file_sep># Mount_Union_CS
Programs I have written in Mount Union Computer Science Classes
<file_sep>/*
<NAME>
Dr. Weber
CSC 220
10/2/2018
PA2
*/
package utility_customer_hierarchy;
public class GasCustomer extends UtilityCustomer {
private static Double priceForGas = 3.0;
public GasCustomer(Integer aN, String aT, Double c){
super();
accountNumber = aN;
accountType = aT;
consumption = c;
} // end of constructor
@Override
public double calculateBill(){
double bill = consumption * priceForGas;
return bill;
}
}
<file_sep># Programming Assignment 3
This repository is used as a way to provide to students
a starting point for CSC 220 Programming Assignment 3,
as well as a way to turn in the assignment.
Programming Assignment 3 is basically Programming Project
100 from [Chapter 12](https://proquest.safaribooksonline.com/book/programming/java/9781284141092/chapter-10-object-oriented-programming-part-3-inheritance-polymorphism-and-interfaces/ch10_html#X2ludGVybmFsX0h0bWxWaWV3P3htbGlkPTk3ODEyODQxNDEwOTIlMkZzZWMxMl8yMF83X2h0bWwmcXVlcnk9Qk9PSw==) of the textbook.
Notes:
+ The starting point code distributed in this repository lays out the package structure of the project. **Do not** change the package names nor delete the existing classes; if you need to add classes, put them in one of the three packages provided.
+ You will need to research on your own how to use the JavaFX `ListView` control. Remember that I have added several links in the [Resources](https://silver.mountunion.edu/cs/csc/CSC220/Fall2018/#resources) section of the course web page.
Your score will be based on the following rubric:
| Item | Possible score |
|------|---------------:|
| Final project structure is the same Model-View-Controller structure as is provided by this repository | 2 |
| Good programming practices, including naming and indentation conventions, as well as proper use of access modifiers such as `private` and `protected`, are followed | 2 |
| **Every** file has an appropriate header comment | 2 |
| The application saves the phone numbers to a text file when the user exits the application | 4 |
| The application reads the phone numbers saved from the last session with the application when it first starts up | 4 |
| All exceptions are caught and handled in some appropriate way | 3 |
| The user can add name/phone number entries | 4 |
| The user can delete name/phone number entries | 4 |
| Total | 25|
Programming Assignment 3 is due Wednesday, October 24, at class time.
You will turn the assignment in by pushing your branch to GitHub. **Note Well:** this will not be possible until class time of the day that it's due, and it will *only* be possible to do this during class that day.
<file_sep>/*
CSC 320
Lab 3
File: Maze.java
*/
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.*;
public class Maze {
private MazeSquare[][] mazeMatrix;
private int numRows;
private int numCols;
public Maze(int r, int c, int sizeOfASquare, int windowWidth) {
numRows = r;
numCols = c;
mazeMatrix = new MazeSquare[numRows][numCols];
// for maze to be centered horizontally, left-most column
// should start at 1/2 of (windowWidth - widthOfMaze)
int xAnchor = (int) (0.5*(windowWidth - numCols * sizeOfASquare));
for (r = 0; r < numRows; r++) {
for (c = 0; c < numCols; c++) {
mazeMatrix[r][c] = new MazeSquare(c*sizeOfASquare + xAnchor, r*sizeOfASquare + 30, sizeOfASquare);
}
}
//****
//**** UNCOMMENT THE STATEMENT THAT FOLLOWS THIS INSTRUCTION
//****
generateMaze();
} // end of constructor()
public void draw(Graphics g) {
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
mazeMatrix[r][c].draw( g );
}
}
g.setColor(Color.green);
MazeSquare startSq = mazeMatrix[0][0];
g.fillRect(startSq.getX()+3, startSq.getY()+3,
startSq.getSize()-6, startSq.getSize()-6);
g.setColor(Color.red);
MazeSquare endSq = mazeMatrix[numRows-1][numCols-1];
g.fillRect(endSq.getX()+3, endSq.getY()+3,
endSq.getSize()-6, endSq.getSize()-6);
} // end of draw()
public MazeSquare getSquare(int r, int c) {
return mazeMatrix[r][c];
} // end of getSquare()
public int getRows() { return numRows; }
public int getCols() { return numCols; }
public void generateMaze() {
int currRow = (int)(Math.random()*numRows);
int currCol = (int)(Math.random()*numCols);
//****
//**** UNCOMMENT THE STATEMENT THAT FOLLOWS THIS INSTRUCTION
//****
StackOfObjs cellStack;
//****
//**** THE NUMBER OF CELLS IN THE MAZE IS numRows TIMES numCols
//****
//**** INSTANTIATE cellStack WITH A CAPACITY OF TWICE THE
//**** NUMBER OF CELLS IN THE MAZE
//****
int totCells = numRows*numCols;
cellStack = new StackOfObjs(2 * totCells);
int visitedCells = 1;
while (visitedCells < totCells) {
ArrayList neighbors = new ArrayList();
if (currRow > 0 && !mazeMatrix[currRow][currCol].hasNBorder() ) {
if (mazeMatrix[currRow-1][currCol].hasAllWallsIntact()) {
neighbors.add(new MazeGenObj(mazeMatrix[currRow-1][currCol], currRow-1, currCol) );
}
}
if (currRow < numRows-1 && !mazeMatrix[currRow][currCol].hasSBorder() ) {
if (mazeMatrix[currRow+1][currCol].hasAllWallsIntact()) {
neighbors.add(new MazeGenObj(mazeMatrix[currRow+1][currCol], currRow+1, currCol) );
}
}
if (currCol > 0 && !mazeMatrix[currRow][currCol].hasWBorder() ) {
if (mazeMatrix[currRow][currCol-1].hasAllWallsIntact()) {
neighbors.add(new MazeGenObj(mazeMatrix[currRow][currCol-1], currRow, currCol-1) );
}
}
if (currCol < numCols-1 && !mazeMatrix[currRow][currCol].hasEBorder() ) {
if (mazeMatrix[currRow][currCol+1].hasAllWallsIntact()) {
neighbors.add(new MazeGenObj(mazeMatrix[currRow][currCol+1], currRow, currCol+1) );
}
}
if (neighbors.size() > 0) {
MazeGenObj nextCell = (MazeGenObj) neighbors.get((int) (Math.random()*neighbors.size()));
if (nextCell.getRow() == currRow - 1) { // north neighbor
mazeMatrix[currRow][currCol].removeNWall();
mazeMatrix[currRow-1][currCol].removeSWall();
} // end if north neighbor
else if (nextCell.getRow() == currRow + 1) { // south neighbor
mazeMatrix[currRow][currCol].removeSWall();
mazeMatrix[currRow+1][currCol].removeNWall();
} // end if south neighbor
else if (nextCell.getCol() == currCol - 1) { // west neighbor
mazeMatrix[currRow][currCol].removeWWall();
mazeMatrix[currRow][currCol-1].removeEWall();
} // end if west neighbor
else if (nextCell.getCol() == currCol + 1) { // east neighbor
mazeMatrix[currRow][currCol].removeEWall();
mazeMatrix[currRow][currCol+1].removeWWall();
} // end if east neighbor
//****
//**** PUSH THE VARIABLE currRow ONTO THE cellStack
//****
cellStack.push(currRow);
//****
//**** PUSH THE VARIABLE currCol ONTO THE cellStack
//****
cellStack.push(currCol);
if (nextCell.getRow() == currRow - 1) // move north
currRow--;
else if (nextCell.getRow() == currRow + 1) // move south
currRow++;
else if (nextCell.getCol() == currCol - 1) // move west
currCol--;
else if (nextCell.getCol() == currCol + 1) // move east
currCol++;
visitedCells++;
} // end if there are neighbors with intact walls
else {
//****
//**** POP THE STACK INTO currCol, CASTING THE RETURN VALUE TO AN
//**** Integer OBJECT
//****
currCol = (Integer) cellStack.pop();
//****
//**** POP THE STACK INTO currRow, CASTING THE RETURN VALUE TO AN
//**** Integer OBJECT
//****
currRow = (Integer) cellStack.pop();
} // end else
} // end while
} // end of generateMaze()
} // end of class Maze
<file_sep>/*<NAME> w/ <NAME>
CSC270 problem 16
Dr. Weber
10/14/18
*/
#include <stdio.h>
#define MAX 100
int maximum(int list[]);
int size;
int main() {
int list[MAX], max, i;
printf("Enter the size of the array:\n ");
scanf("%d", &size);
printf("Enter %d integers: ", size);
for(i = 0; i < size; i++) {
scanf("%d", &list[i]);
}
max = maximum(list);
printf("\nLargest element of the array is %d\n\n", max);
return 0;
}
int maximum(int list[]) {
static int i = 0, max =- 9999;
if(i < size) {
if(max < list[i])
max = list[i];
i++;
maximum(list);
}
return max;
}<file_sep>////// file: LinkedList.java
public class LinkedList {
protected Link first;
protected int size;
private Link last;
public LinkedList() {
size = 0;
first = last = null;
} // end of constructor
public Link getFirst() {
return first;
} // end of getFirst()
public int getSize() {
return size;
} // end of getSize()
public void insertFirst(Object newObj) {
Link newestLink = new Link(newObj);
if (first == null) {
first = newestLink;
last = newestLink;
} else {
newestLink.next = first;
first = newestLink;
}
size++;
} // end of insertFirst()
public Object deleteFirst() {
Object answer = first.data;
if (size == 1) {
first = null;
last = null;
} else {
first = first.next;
}
size--;
return answer;
} // end of deleteFirst()
public void insertLast(Object obj) {
Link newLink = new Link(obj);
if (first == null) {
newLink.next = null;
first = newLink;
last = newLink;
} else {
last.next = newLink;
last = newLink;
}
size++;
}
} // end class LinkedList
<file_sep>
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class MUPanel extends JPanel {
// 1. Declare private objects here:
private Background background;
public Piece[] gamePieces;
private Integer count, anchorX, anchorY, step;
private Color pieceColor;
private String name;
public Boolean endGame;
private Random randGen;
// constructor method
public MUPanel() {
setLayout(null);
setPreferredSize(new Dimension(800, 600));
setName("Mount Union Java Program");
setUp();
setBackground(Color.WHITE);
background = new Background();
gamePieces = new Piece[6];
anchorX = 4;
anchorY = 257;
endGame = false;
// 2. Instantiate objects here by calling "new":
for (int i = 0; i < gamePieces.length; i++){
if (i == 0){
name = "1";
pieceColor = Color.RED;
} else if (i == 1){
name = "2";
pieceColor = Color.ORANGE;
} else if (i == 2){
name = "3";
pieceColor = Color.YELLOW;
} else if (i == 3){
name = "4";
pieceColor = Color.GREEN;
} else if (i == 4){
name = "5";
pieceColor = Color.PINK;
} else if (i == 5){
name = "6";
pieceColor = Color.magenta;
}
if(anchorX <= 775){
endGame = false;
}else{
endGame = true;
}
gamePieces[i] = new Piece(anchorX, anchorY, pieceColor, name);
anchorY += 40;
}
} // end of constructor
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // This line must be first in this method!
// 3. Call methods of objects here:
background.draw(g);
for (int i = 0; i < gamePieces.length; i++){
gamePieces[i].draw(g);
}
} // end of paintComponent()
public void movePieces( Piece[] theArray){
for ( int i = 0; i < gamePieces.length; i++ ){
if (endGame == false){
gamePieces[i].moveHorizontally();
}
}
} // end of movePieces()
/***********************************************
* Do NOT change or delete anything below here!
***********************************************/
public void setUp() {
for (Component c: getComponents())
c.setSize(c.getPreferredSize());
JFrame f = new JFrame(getName());
f.setContentPane(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(false);
}
public static void main(String args[]){new MUPanel();}
} // end of class MUPanel
<file_sep>/*<NAME> w/ <NAME>
CSC270 problem 16
Dr. Weber
10/14/18
*/
#include <stdio.h>
int fib(num);
int main() {
int num;
int answer;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0) {
printf("Cannot do operation.\n");
}
else
{
result = fibonacci(num);
printf("The %d number in fibonacci sequence is %d.\n", num, answer);
}
return 0;
}
int fib(int num) {
if (num < 2) {
return num;
return(fib(num - 1) + fib(num - 2));
}
}
<file_sep>/*
CSC 320
Program # 3
Author: <NAME>
Date: 2/22/2020
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
public class MUPanel extends JPanel implements ActionListener {
//*********
// Objects for GUI:
//*********
private TextArea theArea;
private JButton browseCountyButton, browseBorderButton,
openCountyButton, openBorderButton,
processButton;
private JTextField countyFileNameField, borderFileNameField;
private Choice firstCountyChoice, secondCountyChoice;
/*
@Label: Label to display count name
@String[]: Array for list of counties in X_counties.txt
@LinkedList[]: LinkedList array of bordering counties in X_starter_borders.txt
*/
private Label countyLabel;
private String[] countyArray;
private LinkedList[] countyLinkedList;
public MUPanel() {
setLayout(null);
setPreferredSize(new Dimension(800, 600));
setName("CSC 320 Program # 3 - Bordering Counties");
setBackground(new Color(0xa0, 0xb7, 0x45));
setUpGUI();
} // end of MUPanel constructor
public void readCountyNamesFromFile(BufferedReader inFile) throws IOException {
int lineNum = -1;
theArea.setText(""); // erases previous displayed output
// Diplays name of states above text area with countyLabel. Found at bottom of setupGUI()
String labelCounty = inFile.readLine();
countyLabel.setText(labelCounty);
/*
Reads number of counties and instantiates array for list of counties
Also instantiates Linked List of counties
*/
Integer numCounties = Integer.parseInt(inFile.readLine());
countyArray = new String[numCounties];
countyLinkedList = new LinkedList[numCounties];
/*
Sets default drop down to toggle a choice.
*/
firstCountyChoice.add("Choose county...");
secondCountyChoice.add("Choose county...");
/*
Reads first line.
While there are lines to read, add one to nextLine for countyArray,
store the input into countyArray, add the input to the dropdown
menus, and go to the next line.
*/
String line = inFile.readLine();
while (line != null) {
lineNum++;
countyArray[lineNum] = line;
firstCountyChoice.add(line);
secondCountyChoice.add(line);
line = inFile.readLine();
} // end while
} // end of readCountyNamesFromFile
// Builds linked list of adjacent counties into countyLinkedList
public void buildAdjacencyLists(BufferedReader inFile) throws IOException {
/*
@lineNum: Current variable to add to LinkedList for countyArray.
@currentCountyNumber: Finds current county in countyArray to build LinkedList of county being read
*/
int lineNum = 0;
int currCountyNumber = -1;
theArea.setText(""); // erases previous displayed output
// @line: Reads first line of input
String line = inFile.readLine();
// while loop if input line is not empty
while (line != null) {
/*
Adds one to lineNum for array control.
@colon: Finds index of colon in input for substring
@county: Takes substring of the input for name of the county to add linked list
for loop iterating through countyArray:
Checks if @county is in the array countyArray and stores
it as the index to build LinkedList of adjacent counties.
*/
lineNum++;
Integer colon = line.indexOf(":");
String county = line.substring(0, colon);
for(int i = 0; i < countyArray.length; i++) {
if (countyArray[i].equals(county))
currCountyNumber = i;
} // end for loop
/*
@countyLinkedList[currCountyNumber]: instantiates new linked list in index of county
@adjCountiesString: Substring of the input of adjacent counties
@adjCounties: String array of adjacent counties split by a comma.
@addLinkPos: Position of adjacent county to add in countyArray
*/
countyLinkedList[currCountyNumber] = new LinkedList();
String adjCountiesString = line.substring(colon + 1);
String[] adjCounties = adjCountiesString.split(",");
Integer addLinkPos = -1;
/*
for loop iterating adjCounties input:
Trims white space of input
for loop iterating through countyArray
if adjacentCounty in input is found in countyArray store
index to be added to countyLinkedList of currentCounty
*/
for (int i = 0; i < adjCounties.length; i++) {
line.trim();
for (int j = 0; j < countyArray.length; j++) {
if (countyArray[j].equals(adjCounties[i]))
addLinkPos = j;
} //end for loop
countyLinkedList[currCountyNumber].insertFirst(addLinkPos);
} // end for loop
line = inFile.readLine();
} // end while
} // end of buildAdjacencyLists
public void checkForAdjacentCounties() {
/*
@firstInput: takes input of first dropdown menu
@secondInput: takes input of first dropdown menu
*/
String firstInput = firstCountyChoice.getSelectedItem();
String secondInput = secondCountyChoice.getSelectedItem();
/*
@firstInputPosition: Position of input in countyArray
@secondInputPosition: Position of input in countyArray
*/
Integer firstInputPosition = -1;
Integer secondInputPosition = -1;
/*
for loop iterating through county array
if statements finds the posiiton of each input and stores
into first and second position
*/
for (int i = 0; i < countyArray.length; i++) {
if (firstInput.equals(countyArray[i]))
firstInputPosition = i;
if (secondInput.equals(countyArray[i]))
secondInputPosition = i;
} // end for loop
/*
@current: takes first link of countyLinkedList in first input position
@found: check for if the county is found in loop for text area output
*/
Link current = countyLinkedList[firstInputPosition].getFirst();
Boolean found = false;
/*
while loop iterates through links
if position of second input is in the first input
print they are adjacent to area
set found to true
move to the next link
*/
while(current != null) {
if (current.data == secondInputPosition) {
theArea.append(firstInput + " is adjacent to " + secondInput + ".\n\n");
found = true;
}
current = current.next;
} // end of while
/*
if second input is not in first input
print they are not adjacent
*/
if (found == false) {
theArea.append(firstInput + " is not adjacent to " + secondInput + ".\n\n");
} // end if
} // end checkForAdjacenctCounties
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source.equals(processButton)) {
checkForAdjacentCounties();
} // end of processButton handler
if (source.equals(browseCountyButton)) {
JFileChooser fc = new JFileChooser(".\\");
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
countyFileNameField.setText( file.getName() );
}
openCountyButton.setEnabled(true);
} // end of browseCountyButton handler
if (source.equals(browseBorderButton)) {
JFileChooser fc = new JFileChooser(".\\");
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
borderFileNameField.setText( file.getName() );
}
openBorderButton.setEnabled(true);
} // end of browseBorderButton handler
if (source.equals(openCountyButton)) {
String filename = countyFileNameField.getText();
try {
FileReader fr = new FileReader( filename );
BufferedReader inFile = new BufferedReader( fr );
readCountyNamesFromFile(inFile);
inFile.close();
theArea.append("^^^^^^^^^^^^^^^^\n" +
"The file " + filename +
" was successfully read\n");
browseBorderButton.setEnabled(true);
firstCountyChoice.setEnabled(true);
secondCountyChoice.setEnabled(true);
}
catch (FileNotFoundException exep) {
theArea.append("The file \"" + filename + "\" was not found.\n");
}
catch (IOException exep) {
theArea.append(exep + "\n");
}
} // end of openCountyButton handler
if (source.equals(openBorderButton)) {
String filename = borderFileNameField.getText();
try {
FileReader fr = new FileReader( filename );
BufferedReader inFile = new BufferedReader( fr );
buildAdjacencyLists(inFile);
inFile.close();
theArea.append("^^^^^^^^^^^^^^^^\n" +
"The file " + filename +
" was successfully read\n");
processButton.setEnabled(true);
}
catch (FileNotFoundException exep) {
theArea.append("The file \"" + filename + "\" was not found.\n");
}
catch (IOException exep) {
theArea.append(exep + "\n");
}
} // end of openBorderButton handler
} // end of actionPerformed
private void setUpGUI() {
Font biggerFont = new Font("Serif", Font.BOLD, 14);
theArea = new TextArea();
theArea.setBounds(10, 180, 760, 360);
theArea.setFont( new Font("Monospaced", Font.BOLD, 16) );
add(theArea);
openCountyButton = new JButton("Read County File");
openCountyButton.setBounds(10, 130, 130, 30);
openCountyButton.setEnabled(false);
openCountyButton.addActionListener(this);
add(openCountyButton);
openBorderButton = new JButton("Read Border File");
openBorderButton.setBounds(155, 130, 130, 30);
openBorderButton.addActionListener(this);
openBorderButton.setEnabled(false);
add(openBorderButton);
browseCountyButton = new JButton("Browse for file");
browseCountyButton.setBounds(540, 20, 120, 30);
browseCountyButton.addActionListener(this);
add(browseCountyButton);
Label inputLabel = new Label("County Name File:");
inputLabel.setBounds(20, 20, 130, 30);
inputLabel.setFont( biggerFont );
add(inputLabel);
countyFileNameField = new JTextField("Browse for a County File");
countyFileNameField.setBounds(160, 20, 360, 30);
countyFileNameField.setFont( new Font("SansSerif", Font.BOLD, 14) );
add(countyFileNameField);
browseBorderButton = new JButton("Browse for file");
browseBorderButton.setBounds(540, 70, 120, 30);
browseBorderButton.setEnabled(false);
browseBorderButton.addActionListener(this);
add(browseBorderButton);
Label inputLabel2 = new Label("Border Name File:");
inputLabel2.setBounds(20, 70, 130, 30);
inputLabel2.setFont( biggerFont );
add(inputLabel2);
borderFileNameField = new JTextField("Browse for a Border File");
borderFileNameField.setBounds(160, 70, 360, 30);
borderFileNameField.setFont( new Font("SansSerif", Font.BOLD, 14) );
add(borderFileNameField);
Label choiceLabel1 = new Label("Choose a County:");
choiceLabel1.setBounds(340, 115, 130, 25);
choiceLabel1.setFont( biggerFont );
add(choiceLabel1);
firstCountyChoice = new Choice();
firstCountyChoice.setBounds(340, 140, 130, 25);
firstCountyChoice.setEnabled(false);
add(firstCountyChoice);
Label choiceLabel2 = new Label("Choose another:");
choiceLabel2.setBounds(485, 115, 130, 25);
choiceLabel2.setFont( biggerFont );
add(choiceLabel2);
secondCountyChoice = new Choice();
secondCountyChoice.setBounds(485, 140, 130, 25);
secondCountyChoice.setEnabled(false);
add(secondCountyChoice);
processButton = new JButton("Are they adjacent?");
processButton.setBounds(630, 130, 140, 30);
processButton.addActionListener(this);
processButton.setEnabled(false);
add(processButton);
countyLabel = new Label("");
countyLabel.setBounds(10, 155, 200, 30);
countyLabel.setFont(biggerFont);
add(countyLabel);
} // end of setUpGUI
/***********************************************
* Do NOT change or delete anything below here!
***********************************************/
public void frame()
{
// for (Component c: getComponents())
// c.setSize(c.getPreferredSize());
JFrame f = new JFrame(getName());
f.setContentPane(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String args[]){new MUPanel().frame();}
} // end of class MUPanel
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author schrotbe2021
*/
public class Goalie {
private String name;
private Integer gamesPlayed, saves, shots;
private Boolean allStar;
public Goalie(String n, Integer gp, Integer s, Integer sh, Boolean as) {
name = n;
gamesPlayed = gp;
saves = s;
shots = sh;
allStar = as;
} // end of constructor
public String toString(){
String answer;
answer = name + " has " + saves + " saves facing " + shots + " shots in " + gamesPlayed
+ " games played. It is " + allStar + " that he made the All Star team in 2018.";
return answer;
} //end of toString
// getters
public String getName(){
return name;
}
public Integer getSaves(){
return saves;
}
public Integer getShots(){
return shots;
}
public Integer getgamesPlayed(){
return gamesPlayed;
}
public Boolean getallStar() {
return allStar;
}
//setters
public void setName( String n ) {
name = n;
}
public void setSaves( Integer s ){
saves = s;
}
public void setShots( Integer sh ){
shots = sh;
}
public void setgamesPlayed( Integer gp ){
gamesPlayed = gp;
}
public void setallStar( Boolean as ){
allStar = as;
}
}
<file_sep>/////// file: Link.java
public class Link {
public Object data;
public Link next;
private Link last;
public Link(Object obj) {
data = obj;
next = null;
} // end of specific constructor
public Link() {
data = null;
next = null;
} // end of generic constructor
} // end class Link
<file_sep>/*
This class will be like the RaceCar class in lab2. Simulator class will build the process class.
*/
package pa2_package;
import java.util.ArrayList;
public class Process {
private String processName; // Name of process
private Integer creationTime; // Time it goes into newList
private ArrayList<ProcessString> traceTape; // CPU and I/O bursts
private Integer timeNew, timeReady, timeRunning,
timeWaiting, timeTerminated, firstResponseTime, dispatchLatency,
timeToTerminate;
private Double averageWaitTime;
/*
Data members:
timeNew = total time process is in new
timeReady = total time process is in ready
timeRunning = total time process is in running
timeWaiting = total time process is in waiting
timeTerminated = total time process is in terminated
dispatchLatency = total time process spent switching from ready to running
timeToTerminate = how long the process took to terminate
averageWaitTime = calulation of average wait time for the procees
*/
public Process(String n, Integer t, ArrayList<ProcessString> tape)
{
processName = n;
creationTime = t;
traceTape = tape;
timeNew = 0;
timeReady = 0;
timeRunning = 0;
timeWaiting = 0;
timeTerminated = 0;
dispatchLatency = 0;
timeToTerminate = 0;
averageWaitTime = 0.0;
}
//Methods for incrementing time in each list.
public void incrementNew() { timeNew++; }
public void incrementReady() { timeReady++; }
public void incrementRunning() { timeRunning++; }
public void incrementWaiting() { timeWaiting++; }
public void incrementTerminated() { timeTerminated++; }
public void incrementLatency() { dispatchLatency++; }
//Methods to retrieve times, name, and trace tape.
public Integer getRunningTime() { return timeRunning; }
public Integer getWaitTime() { return timeWaiting; }
public Integer getLatency() { return dispatchLatency; }
public Integer getTimeToTerminate() { return timeToTerminate; }
public Integer getFirstResponse() { return firstResponseTime; }
public String getName() { return processName; }
public Integer getCreationTime() { return creationTime; }
public ArrayList<ProcessString> getTraceTape() { return traceTape; }
public Double getAverageWait() { return averageWaitTime; }
// Sets the timeToterminate and firstResponse variables.
public void setTimeToTerminate(Integer t) { timeToTerminate = t; }
public void setFirstResponse(Integer f) { firstResponseTime = f; }
public void setAverageWait(Double w) { averageWaitTime = w; }
// Returns string of the trace tape.
public String traceToString() {
String result = "";
for ( ProcessString p : traceTape )
{
result += p.toString();
}
return result;
}
@Override
public String toString()
{
return processName + " :: " + creationTime + " :: " + traceToString()
+ " \n\t" + timeNew + " " + timeReady + " " + timeRunning + " "
+ timeWaiting + " " + timeTerminated + " " + dispatchLatency;
}
}
<file_sep>/* CSC xxx Project/Lab # x
* <NAME>
* Today's Date
*
* Project Description:
*
* Acknowledgements:
*
*/
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class MUFrame extends javax.swing.JFrame {
private Integer totalGoalsTot, totalAssistsCum, count, total, gpTotal, min, max;
private Double goalsAverage;
// declare private data here
// constructor method
public MUFrame() {
initComponents();
count = 0;
totalGoalsTot = 0;
totalAssistsCum = 0;
gpTotal = 0;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
} // end of constructor
// declare other methods here
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
drawingPanel = new javax.swing.JPanel();
nameTextField = new javax.swing.JTextField();
editNameLabel = new javax.swing.JLabel();
gamesPlayedLabel = new javax.swing.JLabel();
gamesPlayedTextField = new javax.swing.JTextField();
goalsLabel = new javax.swing.JLabel();
goalsTextField = new javax.swing.JTextField();
assistsTextField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
processDataButton = new javax.swing.JButton();
displayStatsButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
outputArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
editNameLabel.setText("Name:");
gamesPlayedLabel.setText("Games Played:");
goalsLabel.setText("Goals:");
jLabel1.setText("Assists:");
jLabel3.setText("NHL Player");
processDataButton.setText("Process Form Data");
processDataButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
processDataButtonActionPerformed(evt);
}
});
displayStatsButton.setText("Display Numeric Stats");
displayStatsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
displayStatsButtonActionPerformed(evt);
}
});
outputArea.setColumns(20);
outputArea.setRows(5);
jScrollPane1.setViewportView(outputArea);
javax.swing.GroupLayout drawingPanelLayout = new javax.swing.GroupLayout(drawingPanel);
drawingPanel.setLayout(drawingPanelLayout);
drawingPanelLayout.setHorizontalGroup(
drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(drawingPanelLayout.createSequentialGroup()
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(drawingPanelLayout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(drawingPanelLayout.createSequentialGroup()
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(gamesPlayedLabel)
.addComponent(jLabel1)
.addComponent(editNameLabel)
.addComponent(goalsLabel))
.addGap(18, 18, 18)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gamesPlayedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(goalsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(assistsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(drawingPanelLayout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(processDataButton)
.addGap(50, 50, 50)
.addComponent(displayStatsButton))))
.addGroup(drawingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 645, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(29, Short.MAX_VALUE))
);
drawingPanelLayout.setVerticalGroup(
drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(drawingPanelLayout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(editNameLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(gamesPlayedLabel)
.addComponent(gamesPlayedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(goalsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(goalsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(assistsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(62, 62, 62)
.addGroup(drawingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(displayStatsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
.addComponent(processDataButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(drawingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void processDataButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processDataButtonActionPerformed
String namePlayer, nameGoalie, goals, assists, gamesPlayed;
namePlayer = nameTextField.getText();
goals = goalsTextField.getText();
assists = assistsTextField.getText();
gamesPlayed = gamesPlayedTextField.getText();
String goalsInput = goalsTextField.getText();
Integer goalsScored = Integer.parseInt(goalsInput);
Integer assistsDealt = Integer.parseInt(assists);
Integer gamesPlayedNum = Integer.parseInt(gamesPlayed);
outputArea.append(namePlayer + " had " + goals + " goals and " + assistsDealt + " assists in " + gamesPlayedNum + " games played in the 2018 season.\n\n");
}//GEN-LAST:event_processDataButtonActionPerformed
private void displayStatsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_displayStatsButtonActionPerformed
String namePlayer, goals, assists, gamesPlayed;
Integer count;
namePlayer = nameTextField.getText();
goals = goalsTextField.getText();
String goalsInput = goalsTextField.getText();
Integer goalsScored = Integer.parseInt(goalsInput);
totalGoalsTot = totalGoalsTot + goalsScored;
outputArea.append(" So far there have been " + totalGoalsTot + " goals scored this year in the NHL.\n\n");
assists = assistsTextField.getText();
String assistsInput = assistsTextField.getText();
Integer assistsGiven = Integer.parseInt(assistsInput);
totalAssistsCum = totalAssistsCum + assistsGiven;
outputArea.append(" So far there have been " + totalAssistsCum + " assists this year in the NHL.\n\n");
gamesPlayed = gamesPlayedTextField.getText();
String gamesPlayedNum = gamesPlayedTextField.getText();
Integer gsNum = Integer.parseInt(gamesPlayedNum);
gpTotal = gpTotal + gsNum;
DecimalFormat avg = new DecimalFormat("#.000");
goalsAverage = 1.0 * totalGoalsTot / gpTotal;
outputArea.append(" The avergae goals scored per games this year is " + avg.format(goalsAverage) + " among players.\n\n");
if(goalsScored < min){
min = goalsScored;
}
outputArea.append(" The lowest number of goals this season was " + min + " goals.\n\n");
if(goalsScored > max){
max = goalsScored;
}
outputArea.append(" The highest number of goals scored this season was " + max + " goals.\n\n");
}//GEN-LAST:event_displayStatsButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MUFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField assistsTextField;
private javax.swing.JButton displayStatsButton;
private javax.swing.JPanel drawingPanel;
private javax.swing.JLabel editNameLabel;
private javax.swing.JLabel gamesPlayedLabel;
private javax.swing.JTextField gamesPlayedTextField;
private javax.swing.JLabel goalsLabel;
private javax.swing.JTextField goalsTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nameTextField;
private javax.swing.JTextArea outputArea;
private javax.swing.JButton processDataButton;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ben
*/
public class PlayerRecord
{
// Data read from file.
private final String
name,
team,
position;
private final Integer
goals,
assists,
points,
penaltyMin;
public PlayerRecord(String n, String t, String p, int g, int a, int ps, int pM)
{
name = n;
team = t;
position = p;
goals = g;
assists = a;
points = ps;
penaltyMin = pM;
} // End of constructor
// Getters
public String getName() { return name; }
public String getTeam() { return team; }
public String getPosition() { return position; }
public Integer getGoals() { return goals; }
public Integer getAssists() { return assists; }
public Integer getPoints() { return points; }
public Integer getPenaltyMin() { return penaltyMin; }
/*
Given a parameter of category choice from the category combo box.
Switch statement then returns the correct category value to display.
Format is {player name} ({category})
*/
public String toString(String s)
{
String result = name + " (";
switch(s)
{
case "goals":
result += goals + ")";
break;
case "assists":
result += assists + ")";
break;
case "points":
result += points + ")";
break;
case "penalty minutes":
result += penaltyMin + ")";
break;
}
return result;
}
} // End of PlayerRecord
<file_sep>/*
<NAME> - PA1
Class for Electric Customer
Dr. Weber
*/
package utility_customer_hierarchy;
/**
*
* @author schrotbe2021
*/
public class ElectricCustomer extends UtilityCustomer {
private Integer kWattHoursUsed = 10;
private static Double pricePerKwHour = 2.5;
private static Integer deliveryFee = 30;
private Integer ID;
public ElectricCustomer(Integer kW, Integer iD){
super(iD);
kWattHoursUsed = kW;
}
public void setKWattHoursUsed(Integer kW){
kWattHoursUsed = kW;
}
public Integer getKWattHoursUsed(){
return kWattHoursUsed;
}
@Override
public Double calculateBill() {
Double bill = (kWattHoursUsed * pricePerKwHour) + deliveryFee;
return bill;
}
public String toString(){ return super.toString(); }
}
<file_sep>/** UtilityCustomer
* Schroth, Ben
* CSC220 Dr. Weber
* Represents a generic utility customer account
*/
package utility_customer_hierarchy;
import java.util.Random;
public abstract class UtilityCustomer {
private Integer accountNumber = 0;
private static Integer nextAccountNumber = 0;
public abstract Double calculateBill();
// Constructor for UtilityCustomer with their ID.
public UtilityCustomer(Integer iD){
accountNumber = iD;
}
//mutator for account
public Integer setAccountNum(Integer aN){
this.accountNumber = aN;
return aN;
}
//accessor for account
public Integer getAccountNumber(){
return accountNumber;
}
// toString
@Override
public String toString(){ return "Account Number ==> " + accountNumber; }
}<file_sep>/*
Way Cool Systems, Inc.
Prototype User Interface
Last updated: 1/7/20
Connect4 game template
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MUPanel extends JPanel implements ActionListener, ItemListener, MouseListener, MouseMotionListener {
private final int HUMAN = 0;
private final int COMPUTER = 1;
private Connect4Board theBoard;
private TextArea theArea, messageArea;
private Button createButton;
private Choice redPlayerChoice, greenPlayerChoice;
private Label redPlayerLabel, greenPlayerLabel;
private int currentTurnColor = Connect4Square.RED;
private int redPlayer = HUMAN;
private int greenPlayer = HUMAN;
private int occupiedSpaces = 0;
private boolean gameOver = false;
public MUPanel() {
setLayout(null);
setPreferredSize(new Dimension(800, 600));
setName("Play Connect4!");
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
theBoard = new Connect4Board();
theArea = new TextArea();
theArea.setBounds(600, 120, 190, 100);
theArea.setText("GREEN moves first\n");
theArea.append( "0,0,0,0,0,0,0,0,0\n");
theArea.append( "0,0,0,0,0,0,0,0,0\n");
theArea.append( "0,0,0,0,0,0,0,0,0\n");
theArea.append( "0,0,1,0,0,0,0,0,0\n");
theArea.append( "0,0,2,0,0,0,0,0,0\n");
theArea.append( "0,1,2,0,0,0,1,0,0\n");
theArea.append( "0,1,1,0,0,0,1,0,2\n");
theArea.append( "0,2,2,1,0,0,1,2,2\n");
add(theArea);
messageArea = new TextArea();
messageArea.setBounds(50, 480, 700, 110);
add(messageArea);
createButton = new Button("Initialize Game Board");
createButton.addActionListener(this);
createButton.setBounds(610, 90, 170, 20);
add(createButton);
redPlayerLabel = new Label("RED player:");
redPlayerLabel.setBounds(600, 340, 100, 20);
add(redPlayerLabel);
redPlayerChoice = new Choice();
redPlayerChoice.addItemListener(this);
redPlayerChoice.setBounds(620, 365, 100, 25);
redPlayerChoice.addItem("Human");
redPlayerChoice.addItem("Computer");
add(redPlayerChoice);
greenPlayerLabel = new Label("GREEN player:");
greenPlayerLabel.setBounds(600, 410, 100, 20);
add(greenPlayerLabel);
greenPlayerChoice = new Choice();
greenPlayerChoice.addItemListener(this);
greenPlayerChoice.setBounds(620, 435, 100, 25);
greenPlayerChoice.addItem("Human");
greenPlayerChoice.addItem("Computer");
add(greenPlayerChoice);
} // end of MUPanel constructor
public void paintComponent( Graphics g ) {
super.paintComponent( g );
if (!gameOver) {
if (occupiedSpaces < 72) {
if (currentTurnColor == Connect4Square.RED && redPlayer == COMPUTER) {
makeAMove(Connect4Square.RED);
}
if (currentTurnColor == Connect4Square.GREEN && greenPlayer == COMPUTER) {
makeAMove(Connect4Square.GREEN);
}
int winner = theBoard.checkForAWinner();
if (winner == Connect4Square.RED) {
messageArea.setText("RED player has won the game");
gameOver = true;
}
else if (winner == Connect4Square.GREEN) {
messageArea.setText("GREEN player has won the game");
gameOver = true;
}
else if (occupiedSpaces >= 72) {
messageArea.setText("Game ends in a draw");
gameOver = true;
}
}
}
theBoard.drawBoard(g);
g.setFont(new Font("Helvetica", Font.BOLD, 18));
g.setColor(Color.MAGENTA.darker());
g.drawString("MU", 15, 50);
g.drawString("Connect4!", 15, 75);
if (currentTurnColor == Connect4Square.RED) {
g.setColor(Color.RED);
g.drawString(" RED to move", 625, 280);
}
else {
g.setColor(Color.GREEN);
g.drawString("GREEN to move", 625, 280);
}
} // end of paintComponent
public void makeAMove(int colorOfMove) {
// randomly choose a column
int c;
do {
c = (int) (Math.random()*9);
} while (theBoard.getValue(0,c) != Connect4Square.EMPTY);
theBoard.setSelectedColumn(c);
int r = theBoard.getRowOfLowestEmptySquareInSelectedColumn();
if (r >= 0) {
theBoard.setSelectedRow(r);
if (currentTurnColor == Connect4Square.RED) {
theBoard.setSelected(Connect4Square.RED);
currentTurnColor = Connect4Square.GREEN;
messageArea.setText("Placed a RED piece in\n row "
+ r + ", column " + c);
}
else {
theBoard.setSelected(Connect4Square.GREEN);
currentTurnColor = Connect4Square.RED;
messageArea.setText("Placed a GREEN piece in\n row "
+ r + ", column " + c);
}
}
occupiedSpaces++;
repaint();
}
public void actionPerformed( ActionEvent event ) {
Object source = event.getSource();
if (source.equals(createButton)) {
gameOver = false;
currentTurnColor = theBoard.initializeBoard(theArea.getText());
if (currentTurnColor == Connect4Square.RED) {
redPlayer = HUMAN;
redPlayerChoice.select(0);
}
else if (currentTurnColor == Connect4Square.GREEN) {
greenPlayer = HUMAN;
greenPlayerChoice.select(0);
}
messageArea.setText("Game Board reset");
occupiedSpaces = 0;
for (int r = 0; r < 8; r++)
for (int c = 0; c < 8; c++)
if (theBoard.getValue(r, c) != Connect4Square.EMPTY)
occupiedSpaces++;
} // end of create Button processing
repaint();
} // end of actionPerformed()
public void itemStateChanged(ItemEvent event) {
Object source = event.getSource();
if (source.equals(redPlayerChoice)) {
int usersSelection = redPlayerChoice.getSelectedIndex();
if (usersSelection != redPlayer) {
redPlayer = usersSelection;
theBoard = new Connect4Board();
currentTurnColor = Connect4Square.RED;
}
} // end redPlayerChoice
if (source.equals(greenPlayerChoice)) {
int usersSelection = greenPlayerChoice.getSelectedIndex();
if (usersSelection != greenPlayer) {
greenPlayer = usersSelection;
theBoard = new Connect4Board();
currentTurnColor = Connect4Square.RED;
}
} // end greenPlayerChoice
occupiedSpaces = 0;
gameOver = false;
repaint();
}
public void mousePressed(MouseEvent e) {
if (130 < e.getX() && e.getX() < 580 && 30 < e.getY() && e.getY() < 480) {
int c = (e.getX() - 130) / 50;
theBoard.setSelectedColumn(c);
int r = theBoard.getRowOfLowestEmptySquareInSelectedColumn();
if (r >= 0) {
theBoard.setSelectedRow(r);
if (currentTurnColor == Connect4Square.RED) {
theBoard.setSelected(Connect4Square.RED);
currentTurnColor = Connect4Square.GREEN;
}
else {
theBoard.setSelected(Connect4Square.GREEN);
currentTurnColor = Connect4Square.RED;
}
occupiedSpaces++;
repaint();
}
}
} // end of mousePresed()
public void mouseClicked(MouseEvent e){ }
public void mouseReleased(MouseEvent e){ }
public void mouseEntered(MouseEvent e){ }
public void mouseExited(MouseEvent e){ }
public void mouseMoved(MouseEvent e) {
int r = -1;
int c = -1;
if (130 < e.getX() && e.getX() < 580 && 30 < e.getY() && e.getY() < 430) {
r = (e.getY() - 30) / 50;
c = (e.getX() - 130) / 50;
}
theBoard.setSelectedRow(r);
theBoard.setSelectedColumn(c);
repaint();
} // end of mouseMoved
public void mouseDragged(MouseEvent e){ }
/***********************************************
* Do NOT change or delete anything below here!
***********************************************/
public void frame()
{
for (Component c: getComponents())
c.setSize(c.getPreferredSize());
JFrame f = new JFrame(getName());
f.setContentPane(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
} // end of frame()
public static void main(String args[]){new MUPanel().frame();}
} // end of class MUPanel()<file_sep># Programming Assignment 2
This repository is used as a way to provide to students
a starting point for CSC 220 Programming Assignment 2,
as well as a way to turn in the assignment.
Programming Assignment 2 is based on
the `UtilityCustomer` class hierarchy described in
[Programming Project](http://proquest.safaribooksonline.com/9781284141092/sec10_10_7_html#sec10-10-7)
55 from Chapter 10 of the textbook,
with the following changes:
+ The data used to initialize the objects in the `ArrayList<UtilityCustomer>` list will come from a file called **customers.txt**. There is a [sample](https://github.com/csc220-mountunion/ProgrammingAssignment2/blob/master/customers.txt) of this file in the top level of the repository folder structure; you can see that each line has an account id, the type of customer, and the amount of gas or electricity that was consumed. I recommend you use the `java.util.Scanner` class to read the data in.
+ Before the program steps through the list and prints out each customer's information (account number and bill),
the list should be sorted so that the smallest bill comes first.
Do not write the sort method yourself, use [`java.util.Collections.sort`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-) to do it for you;
you will have to provide a `Comparator` so that the `sort` method will know how to compare two `UtilityCustomer` objects.
As in [Programming Assignment 1](https://github.com/csc220-mountunion/ProgrammingAssignment2/blob/master/README-PA1.md)
, the package structure started in the repository must be followed, including both the names and contents of the packages.
Your score will be based on the following rubric:
| Item | Possible score |
|------|---------------:|
| `UtilityCustomer` class hierarchy is properly declared according to the specifications in Programming Assignment 1 and the textbook | 6 |
| Package structure is the same as that originally provided in the master branch of the repository | 2 |
| Good programming practices, including naming and indentation conventions, as well as proper use of access modifiers such as `private` and `protected`, are followed | 3|
| Every file has an appropriate header comment | 2 |
| The client reads data from **customers.txt** to instantiate `UtilityCustomer` objects and inserts them into `customerList` | 5 |
| The client uses `Collections.sort` to sort `customerList` so that the customer with the smallest bill comes first | 5 |
| The client steps through `customerList` and prints the bill amount and customer id for each customer in the list | 2|
| Total | 25|
|Exra credit: the bill amounts and customer ids are displayed in the client's FXML pane instead of the Java console | 3 |
Programming Assignment 2 is due Wednesday, October 3, at class time.
You will turn the assignment in by pushing your branch to GitHub. **Note Well:** this will not be possible until class time of the day that it's due, and it will *only* be possible to do this during class that day.
<file_sep># Programming Assignment 5
You are to write a Java program to solve [problem 66 from Chapter 14](https://proquest.safaribooksonline.com/book/programming/java/9781284141092/chapter-10-object-oriented-programming-part-3-inheritance-polymorphism-and-interfaces/ch10_html#X2ludGVybmFsX0h0bWxWaWV3P3htbGlkPTk3ODEyODQxNDEwOTIlMkZzZWMxNF8xNF83X2h0bWwmcXVlcnk9) of the textbook, except you will be using a linked data structure for the stack instead of an array-based implementation, and you will provide an additional `hasNext` method as was described in class.
Test code for the `ClothingStack` class should use the JUnit testing framework that will be discussed in class in the final two weeks.
This repository has starting point code for the [`ClothingItem`](https://github.com/csc220-mountunion/ProgrammingAssignment5/blob/master/src/clothing/ClothingItem.java) and [`ClothingStack`](https://github.com/csc220-mountunion/ProgrammingAssignment5/blob/master/src/clothing/ClothingStack.java) classes; some additional information is provided in comments therein.
Your score will be based on the following rubric:
| Item | Possible score |
|------|---------------:|
| Initial program structure as provided is followed | 2 |
| Good programming practices are followed | 2 |
| **Every** file has an appropriate header comment | 2 |
| Correct implementation of `ClothingItem` class| 3 |
| Correct implementation of linked structure for `ClothingStack`| 3 |
| Correct implementation **and tests** of `ClothingStack` constructor| 2 |
| Correct implementation **and tests** of `ClothingStack.push` | 2 |
| Correct implementation **and tests** of `ClothingStack.pop` | 2 |
| Correct implementation **and tests** of `ClothingStack.peek` | 2 |
| Correct implementation **and tests** of `ClothingStack.hasNext` | 2 |
| Correct implementation **and tests** of `ClothingStack.toString` | 4 |
| Correct implementation **and tests** of `ClothingStack.itemsOfColor` | 4 |
| Correct implementation **and tests** of `ClothingStack.numberOfItemsWashableAtHighTemperature` | 3 |
| JUnit test framework correctly used | 2 |
| Total | 35 |
Programming Assignment 5 is due Friday, December 7, at class time.
You will turn the assignment in by pushing your branch to the repository, as in Programming Assignments 1 though 3.
<file_sep>/*
<NAME>
PA3 CSC 220
Dr. Weber
10/23/2018
*/
package phone_list_model;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Model
{
public static ObservableList<String> readPhoneList(){
List<String> list = new ArrayList<String>();
ObservableList<String> contacts = FXCollections.observableList(list);
try(Scanner s = new Scanner(new File("phone_list.txt"))){
while(s.hasNextLine()){
String name = s.nextLine();
contacts.add(name);
}
} catch(FileNotFoundException fe){
System.out.println("phone_list.txt not found");
}
return contacts;
}
}
<file_sep>/*
<NAME>
Dr. Weber
CSC 220
10/2/2018
PA2
*/
package utility_customer_hierarchy;
public class ElectricCustomer extends UtilityCustomer {
private static Double priceForElectric = 2.5;
public ElectricCustomer(Integer aN, String aT, Double c){
super();
accountNumber = aN;
accountType = aT;
consumption = c;
} // end of constructor
@Override
public double calculateBill(){
double bill = consumption * priceForElectric;
return bill;
}
}
|
8c3df9d596e94f51acf22368ac50d2077d7b49f6
|
[
"Markdown",
"Java",
"C"
] | 28
|
Markdown
|
schrotbe2021/Mount_Union_CS
|
0da1434247bd3c4a425d2c6ce94809df478aada2
|
eb4abe5f3150cef3ab711791f7a1540d107d0e34
|
refs/heads/master
|
<repo_name>strausd/ReactWeather<file_sep>/example-promise.js
// function getTempCallback(location, callback) {
// callback(undefined, 78);
// callback('City not found');
// }
//
// getTempCallback('Dallas', function (err, temp) {
// if(err) {
// console.log('error', err);
// } else {
// console.log('Success', temp)
// }
// });
// function getTempPromise(location) {
// return new Promise(function (resolve, reject) {
// setTimeout(function () {
// resolve(79);
// reject('City not found');
// }, 1000);
// });
// }
//
// getTempPromise('Dallas').then(function (temp) {
// console.log("Success!", temp);
// }, function(err) {
// console.log("Error.", err);
// });
function addPromise(a, b) {
return new Promise(function (resolve, reject) {
if((typeof a === 'number') && (typeof b === 'number')) {
resolve(a + b);
} else {
reject('Both must be numbers');
}
});
}
addPromise(8, 3).then(function (num) {
console.log(num + " is the sum!");
}, function (err) {
console.log(err);
});
|
df35795a283ecbbbacbdbc4a0be6475b63ba9ee9
|
[
"JavaScript"
] | 1
|
JavaScript
|
strausd/ReactWeather
|
2640359177accf6ee6a3dd9a2aa27df3b3db8afe
|
f2ce9476e2b67f24cdb5fd500ed9020f748450af
|
refs/heads/master
|
<file_sep>package com.debug.steadyjack;
import com.debug.steadyjack.service.InitService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest {
@Autowired
private InitService initService;
}
|
059ef36a34aa0c479f1b3a9b09b8b8ff835cfb68
|
[
"Java"
] | 1
|
Java
|
mmmmyan/RabbitMqWithBoot
|
bfcc6947cedafb4204560d7c1629bf0e750e4cea
|
ac486d69e34f03a803aaaa985fbe0207239f958d
|
refs/heads/master
|
<file_sep>let express = require('express');
let morgan = require('morgan');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
let jsonParser = bodyParser.json();
let {StudentList} = require('./model');
let app = express();
app.use(express.static('public'));
app.use(morgan('dev'));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
if (req.method === "OPTIONS") {
return res.send(204);
}
next();
});
let estudiantes = [{
nombre : "Miguel",
apellido : "Ángeles",
matricula : 1730939
},
{
nombre : "Erick",
apellido : "González",
matricula : 1039859
},
{
nombre : "Victor",
apellido : "Villareal",
matricula : 1039863
},
{
nombre : "Carlos",
apellido : "Estrada",
matricula : 1039919
},
{
nombre : "Francisco",
apellido : "Sánchez",
matricula : 1196903
},
{
nombre : "Victor",
apellido : "Cárdenas",
matricula : 816350
}];
app.get('/api/getById', (req, res) => {
let id = req.query.id;
let result = estudiantes.find((elemento) => {
if (elemento.matricula == id) {
return elemento;
}
});
if (result) {
return res.status(200).json(result);
}
else {
res.statusMessage = "El alumno no se encuentra en la lista.";
return res.status(404).send();
}
});
// http://localhost:8080/api/getById?id=1039919
app.get('/api/getByName/:name', (req, res) => {
let name = req.params.name;
let result = estudiantes.filter((elemento) => {
if (elemento.nombre === name) {
return elemento;
}
});
if (result.length > 0) {
return res.status(200).json(result);
}
else {
res.statusMessage = "El alumno no se encuentra en la lista.";
return res.status(404).send();
}
});
// http://localhost:8080/api/getByName/Victor
app.get('/api/students', (req, res) => {
StudentList.getAll()
.then(studentList => {
return res.status(200).json(studentList);
})
.catch(error => {
res.statusMessage = "Hubo un error de conexión con la BD.";
return res.status(500).send();
});
res.status(200).json(estudiantes);
});
app.post('/api/newStudent', jsonParser, (req, res) => {
let nombre = req.body.nombre;
let apellido = req.body.apellido;
let matricula = req.body.matricula;
if (nombre !== undefined && apellido !== undefined && matricula !== undefined) {
let result = estudiantes.find(estudiante => estudiante.matricula === matricula);
if (result === undefined) {
let estudiante = {nombre, apellido, matricula};
estudiantes.push(estudiante);
res.statusMessage = `Estudiante ${nombre} ${apellido} con la matrícula ${matricula} ha sido agregado a la lista de estudiantes.`;
return res.status(201).send();
}
else {
res.statusMessage = "La mátricula ingresada ya existe.";
return res.status(409).send();
}
}
else {
res.statusMessage = "Ingrese todos los elementos (nombre, apellido y matrícula).";
return res.status(406).send();
}
});
app.put('/api/updateStudent/:id', jsonParser, (req, res) => {
let nombre = req.body.nombre;
let apellido = req.body.apellido;
let matricula = req.body.matricula;
if (matricula !== undefined && (nombre !== undefined || apellido !== undefined)) {
}
else {
res.statusMessage("Ingrese una matrícula y un nombre o un apllido.");
return res.status(406).send();
}
});
function runServer(port, databaseUrl){
return new Promise( (resolve, reject ) => {
mongoose.connect(databaseUrl, response => {
if ( response ){
return reject(response);
}
else{
server = app.listen(port, () => {
console.log( "App is running on port " + port );
resolve();
})
.on( 'error', err => {
mongoose.disconnect();
return reject(err);
})
}
});
});
}
function closeServer(){
return mongoose.disconnect()
.then(() => {
return new Promise((resolve, reject) => {
console.log('Closing the server');
server.close( err => {
if (err){
return reject(err);
}
else{
resolve();
}
});
});
});
}
runServer(8080, "mongodb://localhost/university/");
module.exports = {app, runServer, closeServer};<file_sep>elemento.addEventListener("click", (event) => {
console.log("click");
});<file_sep># Class 2 Notes
## Input types:
* "password"
* "radio"
* "checkbox"
* "date"
* "number"
* "email"
* "tel"
### Each input must be assigned to its respective label.
## Tags
* select - creates a drop-down list with options.
* textarea - creates an HTML text area.
* div - for content (block).
* span - for content (inline).
## Different sections
* main
* section
* header
* footer
## Elements that shouldn't be used
* br
* hr<file_sep>function fetchCocktails() {
let userInput = $('.userInput').val();
let url = `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${userInput}`;
$.ajax({
url : url,
method : "GET",
dataType : "json",
success : function(responseJSON) {
displayResults(responseJSON);
},
error : function(err) {
console.log(err);
}
});
}
function displayResults(responseJSON) {
let results = $("#results");
let drinks = responseJSON.drinks;
$("#results").empty();
drinks.forEach((drink)=> {
let ingredients = '';
for(let i = 1; i <= 15; i++) {
let ingredient = `strIngredient${i}`;
let measure = `strMeasure${i}`;
if (drink[ingredient] == null) {
console.log('No ingredient' + i);
break;
}
else {
if (drink[measure] !== null) {
ingredients += `<li>${drink[ingredient]} - ${drink[measure]}</li>`;
}
else {
ingredients += `<li>${drink[ingredient]}</li>`;
}
}
}
results.append(`<div class="drink">
<h1>${drink.strDrink}</h1>
<img class="dimension" src="${drink.strDrinkThumb}" />
<h3> Ingredients </h3>
<ul> ${ingredients} </ul>
</div>`);
})
}
function watchForm() {
let form = document.getElementById('cocktails');
form.addEventListener('submit', (event) => {
event.preventDefault();
fetchCocktails();
});
}
function init() {
watchForm();
}
init();<file_sep>function fetchGithub() {
let userInput = $('.userInput').val();
let url = `https://api.github.com/users/${userInput}/repos`;
$.ajax({
url : url,
method : "GET",
dataType : "json",
success : function(responseJSON) {
displayResults(responseJSON);
},
error : function(err) {
console.log(err);
}
});
}
function displayResults(responseJSON) {
let repositories = responseJSON;
let results = $("#results");
$("#results").empty();
repositories.forEach((repository) => {
results.append(`<div class="repository">
<h1>${repository.name}</h1>
<h3> Repository URL: <a href= "${repository.html_url}"> ${repository.html_url} </a> </h3>
</div>`);
})
}
function watchForm() {
let form = document.getElementById('users');
form.addEventListener('submit', (event) => {
event.preventDefault();
fetchGithub();
});
}
function init() {
watchForm();
}
init();<file_sep># Seguridad web, CORS y cookies
## Tres partes en las que tenemos que pensar al hacer una aplicación web
* Privacidad
* Integridad
* Autenticidad
## Capas
* Capa Presentación (HTML, CSS, JavaScript)
* Capa Aplicación (Servidor)
* Capa Datos (BD)
## Clientes
* Fat Client (Capa Presentación principalmente y un poco de Capa Aplicación)
* Thin Client (Capa Aplicación y Capa Datos)
## XSS (Cross-site scripting)
### Cómo evitar
* Validar formas
* Sanitizar inputs
* Expresiones regulares
* Limitar etiquetas de entrada
* Validar datos de entrada
* Codificar texto
## Inyección SQL
* Primer orden (Logra entrar a la base de datos)
* Segundo orden (Deja algo corriendo permanentemente en la base de datos como un proceso)
* Lateral (Obtener privilegios de administrador para cambiar o borrar datos en la base de datos, o instalar software)
## Backend
* Encriptar datos
* Manejo de sesiones
* Mantener los datos en constante cambio
* Reglas / capchas
## Phishing/Spamming
* Notifícale al usuario de lo que es y lo que no es ("No solicitamos información por correo")
## Denial of Service / Botnets
* Capchas
* IP DNS bloqueas una entrada
* Doble autentificación
## Encriptación
### Simétrica
* Es cuando el emisor y el receptor, las dos partes que se comunican, tienen una llave pública para cifrar y descifrar los mensajes que se envían.
### Asimétrica
* Es cuando el emisor usa la llave pública del receptor para que sólo ese receptor pueda descifrar el mensaje con su llave privada.<file_sep>function fetchNews() {
let userInput = $('.userInput').val();
let url = 'https://newsapi.org/v2/everything?' +
`q=${userInput}&` +
'from=2020-01-20&' +
'sortBy=popularity&' +
'apiKey=<KEY>';
$.ajax({
url : url,
method : "GET",
dataType : "json",
success : function(responseJSON) {
displayResults(responseJSON);
},
error : function(err) {
console.log(err);
}
});
}
function displayResults(responseJSON) {
let results = $("#results");
$('#results').empty();
responseJSON.articles.forEach((el)=> {
results.append(`<div>
<h1>${el.title}</h1>
<p>
<img class="dimension" src="${el.urlToImage}" />
</p>
<p>${el.author}</p>
<p>${el.description}</p>
</div>`);
});
}
function watchForm() {
let form = document.getElementById('news');
form.addEventListener('submit', (event) => {
event.preventDefault();
fetchNews();
});
}
function init() {
watchForm();
}
init();<file_sep># Web development class (Winter 2020)<file_sep># MongoDB
### Correr en una terminal el siguiente comando:
* ~/mongodb/bin/mongod --dbpath=/Users/moisesfernandez/data/db
### Correr en otra terminal o tab de terminal
* ~/mongodb/bin/mongo
### Para crear la base de datos
* USE DBNAME
* DBNAME.students (crea la tabla)
* db.students.insert({nombre: "Maria", matricula: 123456, apellido: "Salazar"})
* db.collection.update({_id:_}, {$set:{actualizar}.})
* db.collection.remove({_id:_})
* db.students.find()
* db.students.find().pretty()
### POST
* Mongo - .insert
* mongoose - .create
### GET
* Mongo - .findOne / .find
* mongoose - .findOne / .find
### DELETE
* Mongo - .remove
* mongoose - .remove / .findByIdAndRemove / .findOneAndRemove
### PUT
* Mongo - .update
* mongoose - .update / .findByIdAndUpdate / .findOneAndUpdate<file_sep># Class 12 Notes
## NodeJS
* node -v (node version)
* npm init
* npm install -g npm
* npm install --save express
* node index.js
* npm start (se configura el start en el json para no hacer node index.js)<file_sep>import React from 'react';
import './App.css';
import Hoby from './Hoby';
import NuevoHoby from './NuevoHoby';
import Students from './Students';
import {BrowserRouter, Route, Link} from 'react-router-dom';
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
nombre: "Alfredo",
apellido: "Salazar",
hobbies: [{
nombre: "Programar"
},
{
nombre: "Dar clases"
},
{
nombre: "<NAME>"
},
{
nombre: "<NAME>"
}
],
students: [],
apiURL: "http://localhost:8080"
}
}
agregaHoby = (hoby) => {
let listaNueva = [...this.state.hobbies, hoby];
// listaNueva.push(hoby);
this.setState({
hobbies: listaNueva
});
}
componentDidMount() {
let url = `${this.state.apiURL}/api/students`;
let settings = {
method: 'GET'
}
fetch(url, settings)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJSON => {
this.setState({
students: responseJSON
})})
.catch(err => {
console.log(err);
});
}
render() {
return (
<BrowserRouter>
<nav>
<Link to='/'> Home </Link>
<Link to='/students'> Students </Link>
</nav>
<Route path='/students'
render={(props) => <Students lista={this.state.students}/>}/>
<div>
Hola de nuevo {this.state.nombre} {this.state.apellido}
<NuevoHoby agregaHoby={this.agregaHoby}/>
<div>
{this.state.hobbies.map((hoby, index) => {
return (
<Hoby accion={hoby.nombre} test={index} />
)
})}
</div>
</div>
</BrowserRouter>
)
}
}
export default App;<file_sep>import React from 'react';
function NuevoHoby(props) {
function click(event) {
event.preventDefault();
let nuevoHoby = {
nombre: event.target.nuevo.value
};
props.agregaHoby(nuevoHoby);
}
return (
<form onSubmit={(event) => click(event)} id="hobyForm">
<label htmlFor="hobyNuevo"> Nuevo hobby : </label>
<input type="text" id="hobyNuevo" name="nuevo" />
<button type="submit">
Agregar
</button>
</form>
)
}
export default NuevoHoby;<file_sep>{
method: "GET",
body: ...,
headers: {
'Content-Type': _
}
}
// Lo de arriba es lo de settings del fetch.
// JavaScript
fetch(url, settings)
.then((response) => {
console.log(response);
if (response.ok) {
return response;
}
throw new Error(response.statusText);
})
.then((responseJSON) => {
console.log(responseJSON);
})
.catch((err) => {
console.log(err);
});
// AJAX
$.ajax({
url: url,
method: "GET",
data: "Datos a enviar", // En JS sería lo del body de settings.
ContentType: "Tipo de dato que se envía al servidor", // En JS sería lo de headers de settings.
dataType: "Tipo de dato que recibimos del servidor",
success: function(responseJSON) {
},
error: function(err) {
}
});<file_sep>import React from 'react';
function Hoby(props) {
return (
<div>
{props.accion}
{props.test}
</div>
)
}
export default Hoby;<file_sep># Class 4 Notes
## CSS
* fieldset > span - la flechita es una regla que dice que se aplique sólo a los spans hijos siguientes dentro del fieldset.
* display: block - hace que se ocupe toda la línea (también se puede usar display: in-line).
* display: none - para ir mostrando al usuario feedback de lo que está suciendo en la página, que se despliegue cuando le hizo algo como olvidar el nombre o llenar algo.
* /* */ - para hacer un comentario.
* en fieldset > span, se dividen de la siguiente manera las secciones:
* background-image, background-repeat, background-position, background-color.
* select[name=nombre] - es para aplicarlo sólo al select con ese nombre.
* .nombreDeClase - para aplicarlo a los elementos de esa clase
* #nombreElemento1 #nombreElemento2 - para aplicarlo en ambos elementos<file_sep># Class 7 Notes
### Tipos de eventos para elementos:
* Click
### Important commands
* addEventListener("evento", función)
* event.target
* event.preventDefault()
* value
* textContent
* innerHTML
* getAttribute("")
* setAttribute("","")
* getElementById("")
* getElementsByClassName("")
* getElementsByTagName("")
* getElementsByname<file_sep># Class 1 Notes
* The attributes in each html element have the following functions
* Describe
* Identify
* Group
* Get certain behaviour
* The main html file is usually called index.html since thats what servers render by default.
* Each html element has two main components: head and body.
* In the head, we provide content that describes our webpage.
* In the body, we have the structure and boy of the webpage.
* Meta tags are essentially little content descriptors that help tell search engines what a web page is about.
Charset is a meta attribute to allow for specific characters.
* Element ids must be unique.
## Elements
### [Headers](https://www.w3schools.com/html/html_headings.asp)
* Header ranges go from 1 - 6.
### [Tables](https://www.w3schools.com/html/html_tables.asp)
* Table Head - <thead\>
* Table Body - <tbody\>
* Table Row - <trow\>
* Table Data - <td\>
* Table Header - <th\>
* Table Foot - <tfoot\>
### [Lists](https://www.w3schools.com/html/html_lists.asp)
* Ordered List - <ol\>
* Unordered List - <ul\>
* List item - <li\>
### [Navigation](https://www.w3schools.com/tags/tag_a.asp)
* Anchor Tag - <a\>
* Target attribute specifies where to open the linked document.
* _blank
* _self
* _parent
* _top
### [Media](https://www.w3schools.com/html/html_images.asp)
* Image - <img\>
* Video - <video\>
### [Forms](https://www.w3schools.com/html/html_forms.asp)
* Form - <form\>
* Label - <labe\>
* Input - <input\>
* Type attribute changes behaviour
* text
* password
* button
<file_sep>let passport = require('passport');
let bcrypt = require('bcrypt');
let password = '<PASSWORD>';
let username = 'alfredo';
// Register
bcrypt.hash(password, 10)
.then(hasspassword => {
return UserList.create({username, password: hashpassword})
.then(user => {
return user;
})
});
// Login
let passParam = '<PASSWORD>';
let username = 'alfredo';
return Users.find({username})
.then(user => {
let hashpassword = user.password;
return bcrypt.compare(passParam, hashpassword);
})
.then(ok => {
if(ok)
return user;
else
throw Error(_);
});<file_sep>function handleThumbnailClicks() {
$( '.thumbnail' ).on( 'click', function( event ) {
const imgSrc = $( event.currentTarget ).find( 'img' ).attr( 'src' );
const imgAlt = $( event.currentTarget ).find( 'img' ).attr( 'alt' );
$( '.hero img' ).attr( 'src', imgSrc ).attr( 'alt', imgAlt );
// Accomplishes the same as line 6 with only one use off .attr()
// by passing it an object with multiple properties.
// See: http://api.jquery.com/attr/#attr-attributes
// $('.hero img').attr({'src': imgSrc, 'alt': imgAlt});
});
}
function init(){
$( handleThumbnailClicks );
}
$( init );<file_sep>* Class 8 Notes
<file_sep># Class 5 Notes
### justify-ccontent (horizontal)
### align-items (vertical)
* flex-start - arriba
* center - centra
* flex-end - abajo
* stretch - ajustar el tamaño del padre
* Si uso width, tengo que usar justify-content, align es para vertical.<file_sep># Class 6 Notes
* La etiqueta del script para javascript va justo arriba de donde cierra el tag del body.
## Javascript
* let es para declarar variables locales.
* var es para declarar variables globales.
* == no le importan los tipos, 4 == '4' da true.
* === checa los tipos, 4 === '4' da false.
* map es un ciclo que copia los elementos de un arreglo a otro arreglo (si no se contempla un caso y no sabe qué hacer con él, va a guardar undefined en ese espacio).
* Si no es una arrow function, es global.
* Arrow function es local.
* La variable document es para la lógica en JavaScript (DOM).<file_sep># Notes Class 10
## AJAX (Asynchronous JavaScript And XML)
* Sirve para que agilizar el proceso de comunicación con la página.
## API (Application Programming Interface)
* Sirve para comunicarse entre el cliente (HTML, CSS y JS (AJAX)) y el servidor (Node.js).
### Métodos
* GET - recibir datos de un recurso específico del servidor.
* POST - crear algo nuevo en el servidor.
* PUT - actualizar algo del servidor
* DELETE - borrar algo del servidor.
## JavaScript
* Método fetch(url, settings)
* settings - qué método voy a utilizar
{
method: "GET",
body: ...,
headers:
}
* El fetch se reconoce como una promesa con el servidor, el cliente espera hasta que el servidor le mande la respuesta.<file_sep>import React from 'react';
function Students(props) {
return (<div>
{props.lista.map((student,index) => {
return (
<div>
<h2>{student.nombre}</h2>
<p>{student.matricula}</p>
</div>
)
})}
</div>)
}
export default Students;<file_sep># Notes Class 3
## Maneras de agregar estilo
* Enlazar un archivo externo
* En la etiqueta style
* En el atributo style
## Prioridades
1 id
2 class
3 elemento
#### Si los dos son el mismo, toma el que esté más abajo en la hoja de estilos
## CSS
* Padding arriba derecha abajo izquierda<file_sep>// JQuery.
let menu = $('#menu')
$('.formElement')
$('div')
/*
<ul id="menu">
<li></li>
*/
$(menu).html();
$(menu).html('<li>...</li>'); // Sobreescribe los elementos de la lista.
$(menu).append('...'); // Agregar un elemento al final de la lista.
$(menu).prepend('...'); // Agregar un elemento al principio de la lista.
$(menu).text(); // Regresa un string con todos los elementos adentro del selector.
$(menu).addClass('_');
$(menu).removeClass('_');
$(menu).attr('id'); // Regresa el valor de un atributo (the first matched element).
$(menu).attr('id', 'valor'); // Asignar el atributo y el valor.
// En code.html.
let home = $('.home').parent(); // Regresaría al "menu". Si no hay parent, regresa undefined.
$(home).next(); // Se iría al siguiente elemento. Si ya no hay otro después, regresa undefined.
$(home).parent().siblings(); // Regresa todos los elementos que tienen el mismo padre.
$(home).children(); // En "menu", regresaría "home" y "about".
$('body').find('about').forEach(function(item){ // Busca el elemento en los hijos.
console.log(item);
});
$('body').closets('about').forEach(function(item){ // Busca el elemento en los padres.
console.log(item);
});
// Eventos.
$(menu).on('click', function() {
});
$('#menu').on("click", ".contact", function(e){ // Para aplicar un evento a un elemento añadido dinamicamente.
$(this) // Con this puedo saber a qué elemento le apliqué la función. Aquí sería al elemento contact.
e.target
});<file_sep>## Block Elements
* fieldset
* form
* ul
* ol
* li
* p
* h1 - h6
* table
* video
* div
## Inline Elements
* input
* label
* select
* textarea
* button
* img
* a
* span
|
b02c45eccc39e809e24b88448c4697ab489a6a68
|
[
"JavaScript",
"Markdown"
] | 27
|
JavaScript
|
moyfdzz/web-development
|
f96c2cd94ade62424c3ee3d5c00d18f461e4c43d
|
830ac7420c0e481774a8d108a6db6d568a7fbf3b
|
refs/heads/master
|
<file_sep>public class ExtendedClass extends BaseClass {
protected void base() {
System.out.println("I'm the extended TWO implemetation");
}
}
<file_sep>#!/bin/sh
set -e
echo "Cleaning up"
#find . -name \*.java | xargs javac
find . -name \*.class -delete
echo "Compiling top-level classes"
javac *.java
pushd extension
echo "Compiling extension classes"
javac *.java -cp ..
popd
echo "Compiling extension2 classes"
pushd extension2
javac *.java -cp ..
popd
<file_sep>#!/bin/sh
# the following commented code is *wrong* because it puts the extension code directly
# into the classpath which is not what is intended by the demonstration, as we're
# playing with the classloader in particular
#java Main -cp .:extension/
# this is correct AFAIK
java Main -cp .
<file_sep>#!/bin/sh
find . -name \*.class -delete
|
d4f6e1bde22b6db435d2c9042f9e5e4fe625a76a
|
[
"Java",
"Shell"
] | 4
|
Java
|
gleenn/overriding-loaded-class-playground
|
8f20b0b8f3ee4526b8278bd0203204a36ebb9c75
|
c7b76f398ff429fb02184cfa83ee1de80483d2cd
|
refs/heads/main
|
<file_sep>## When preparing Coding Interview, you are assessed to have:
1. Analytic skills: How can you think through a problem. thought process.
2. Coding Skills: clean, organised, readable.
3. Technical Skills: understand fundamentals, not memorising?
4. Communication Skills: fit well, work well?
## Know the existance of Data Structure and Algorithm?
- and When you should use a certain data structure over the other?
### Refer "https://www.youtube.com/watch?v=XKu_SEDAykw&ab_channel=LifeatGoogle"
- Interviewer will see what steps we take.
<file_sep>//Given 2 arrays, create a function that lets a user know (ture/false) whether these two arrays contain any common items.
//For wxample:
const array1 = ["a", "b", "c", "x"];
const array2 = ["z", "y", "i"];
// should return false.
//
const array3 = ["a", "b", "c", "x"];
const array4 = ["z", "y", "x"];
// Should return true.
//
// ------
// 2 parameters - arrays - no size limit
// return true of false.
// naive/brute force approach: netsted loops, O(n^2).
function containsCommonItem1(arr1, arr2) {
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; i++) {
if (arr1[i] === arr2[j]) {
return true;
}
}
}
return false;
}
// not efficient as there are two nested for loops: O(a*b)
// O(1) - Space compexity
// If we convert array1 into obj, could be better.
// array1 --> obj {
// a: true,
// b: true,
// c: true,
// x: true
//}
// array2[index] === obj.properties
function cotainsCommonItem2(arr1, arr2) {
// loop through first array and create object where properties === items in the array
let map = {};
for (let i = 0; i < arr1.length; i++) {
if (!map[arr1[i]]) {
// if map.a does not exist
const item = array1[i];
map[item] = true;
}
}
// console.log(map);
// loop through second array and check if item in second array exists on created object.
for (let j = 0; j < arr2.length; j++) {
if (map[arr2[j]]) {
return console.log(true);
}
}
return console.log(false);
}
// Two seperate for loops.
// O(a+b); Time Complexity.
// O(a) - Space Compexity
// cotainsCommonItem2(array1, array2);
// Can we assume always 2 params?
function containsCommonItem3(arr1, arr2) {
return console.log(arr1.some((item) => arr2.includes(item)));
}
containsCommonItem3(array3, array4);
|
3dafb3e04a7aa36860827f54795c64b72e683857
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
David-Myeonghan/2_For_Coding_Interview
|
d6a7292133068f0a13ae4389abf4a39c8039da36
|
fa37678cbe8b96f48ee239555fc90b96001e633b
|
refs/heads/main
|
<repo_name>Shambonik/MusicJumpServer<file_sep>/musicjump/src/main/java/com/example/musicjump/controllers/RegisterController.java
package com.example.musicjump.controllers;
import com.example.musicjump.DTO.RegistrationDTO;
import com.example.musicjump.DTO.SuccessDTO;
import com.example.musicjump.services.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RequestMapping("/reg")
@RequiredArgsConstructor
public class RegisterController {
private final UserService userService;
@GetMapping
public String getRegPage(Model model){
model.addAttribute("user", new RegistrationDTO());
return "registration";
}
@PostMapping("/admin")
public String addAdmin(RegistrationDTO registration){
if(userService.addUser(registration, true).isSuccess()){
return "redirect:/auth";
}
return "redirect:/reg";
}
}
<file_sep>/musicjump/src/main/java/com/example/musicjump/controllers/AdminController.java
package com.example.musicjump.controllers;
import com.example.musicjump.DTO.AddSkinDTO;
import com.example.musicjump.services.SkinService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
private final SkinService skinService;
@GetMapping
public String getAdminPage(Model model){
model.addAttribute("list", skinService.getAllSkins());
model.addAttribute("skin", new AddSkinDTO());
return "admin";
}
@PostMapping("/add_skin")
public String addSkin(AddSkinDTO addSkinDTO){
return skinService.addSkin(addSkinDTO);
}
}
<file_sep>/musicjump/src/main/java/com/example/musicjump/services/SkinService.java
package com.example.musicjump.services;
import com.example.musicjump.DTO.AddSkinDTO;
import com.example.musicjump.models.Skin;
import com.example.musicjump.models.User;
import com.example.musicjump.repos.SkinRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class SkinService {
private final SkinRepo skinRepo;
private final UserService userService;
public List<Skin> getAllSkins(){
return skinRepo.findAll();
}
public String addSkin(AddSkinDTO addSkinDTO){
Skin skin = new Skin(addSkinDTO.getName(), addSkinDTO.getCost());
skinRepo.save(skin);
userService.setSkinToAllUsers(skin);
return "redirect:/admin";
}
}
|
d37ed4a5fdde71b4b9d1fb3c3b4fdc7395c18cce
|
[
"Java"
] | 3
|
Java
|
Shambonik/MusicJumpServer
|
66d547d78ab1f34177b5940ec19f457f3cfe650b
|
b6687b284eee9b7d4507b2493e04d4ec0c646a5b
|
refs/heads/master
|
<repo_name>ClaudioAmato/moodify-spotify<file_sep>/client/src/app/services/manumission-check.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { ManumissionCheckService } from './manumission-check.service';
describe('ManumissionCheckService', () => {
let service: ManumissionCheckService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ManumissionCheckService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>/client/src/app/pages/search/search.page.ts
import { EmojiFeedback } from './../../interfaces/EmojiFeedback';
import { TrackData } from './../../interfaces/TrackData';
import { ManumissionCheckService } from './../../services/manumission-check.service';
import { UserProfile } from './../../interfaces/UserProfile';
import { MachineLearningService } from './../../services/machineLearning.service';
import { LogoutService } from './../../services/logout.service';
import { EmojisService } from './../../services/emojis.service';
import { Double } from '../../classes/Double';
import { AlertController, LoadingController, IonSearchbar } from '@ionic/angular';
import { SharedParamsService } from './../../services/shared-params.service';
import { Component, ViewChild } from '@angular/core';
import SpotifyWebApi from 'spotify-web-api-js';
@Component({
selector: 'app-search',
templateUrl: 'search.page.html',
styleUrls: ['search.page.scss'],
})
export class SearchPage {
// spotifyApi
spotifyApi = new SpotifyWebApi();
// search variables
searchTrack: Array<{ key: string, image: any, name: string }> = [];
@ViewChild('searchbar') myInput: IonSearchbar;
// pair used for the reinforcement learning
doubleToUpload: Double = new Double();
currentMusicplaying: TrackData = null;
idUser = '';
// emojis
arrayEmoji: Array<EmojiFeedback> = [];
divEmoji = false;
feedbackEmoji = true;
waitNewFeedback = false;
feedback: string;
// Player variables
soundPlayer = new Audio();
currentPreview: any = undefined;
currentPlaying: any = undefined;
spotifyWindow: Window;
_previewIntervalHandler: any;
_previewTimeOut: any;
_playIntervalHandler: any;
constructor(private shared: SharedParamsService, private logoutService: LogoutService,
private alertController: AlertController, private emoji: EmojisService,
private learningService: MachineLearningService, private loadingCtrl: LoadingController,
private manumission: ManumissionCheckService) {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.setAccessToken(this.shared.getToken());
this.arrayEmoji = this.emoji.getArrayEmoji();
if (this.shared.getTargetMood() !== null) {
this.initializeSessionDB();
}
}
}
}
ionViewDidLeave() {
this.stop(null);
if (this.feedbackEmoji) {
this.divEmoji = false;
this.searchTrack = [];
this.currentMusicplaying = null;
}
}
// Initialize user's session from DB if it exist
initializeSessionDB() {
this.presentLoading('Loading data ...').then(() => {
const userProfile: UserProfile = this.shared.getUserProfile();
this.idUser = userProfile.ID;
this.learningService.getUserData(this.idUser, this.shared.getCurrentMood(), this.shared.getTargetMood())
.then(result => {
if (result.buff === null && result.features === null) {
// console.log('User not found');
}
this.loadingCtrl.dismiss().then(() => {
this.myInput.setFocus();
});
});
});
}
// this function let user searching an artist
searchMusic($event) {
this.divEmoji = false;
this.stop(null);
if (this.currentMusicplaying !== null) {
this.currentMusicplaying = null;
}
if ($event.detail.value.length > 0) {
let dataSearch: { key: string, image: any, name: string };
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.search($event.detail.value, ['track'], { /*market: this.country_code,*/ limit: 5, offset: 0 })
.then((response) => {
if (this.searchTrack.length > 0) {
this.searchTrack = [];
}
if (response !== undefined) {
for (const trackItem of response.tracks.items) {
if (trackItem.album.images.length !== 0) {
dataSearch = {
key: trackItem.id,
image: trackItem.album.images[1].url,
name: trackItem.name,
};
}
else {
dataSearch = {
key: trackItem.id,
image: 'assets/img/noImgAvailable.png',
name: trackItem.name,
};
}
this.searchTrack.push(dataSearch);
}
}
}).catch(err => {
console.log(err);
});
}
}
} else {
if (this.searchTrack.length > 0) {
this.searchTrack = [];
}
}
}
// This function clear search input
clearInput() {
if (this.searchTrack.length > 0) {
this.searchTrack = [];
}
}
// This function uses spotify API to get a specific track and load its information
onClickTrack(idTrack: string) {
this.divEmoji = true;
this.waitNewFeedback = false;
if (this.searchTrack.length > 0) {
this.searchTrack = [];
}
let popularity;
this.presentLoading('Loading data ...').then(() => {
this.spotifyApi.getTrack(idTrack).then((response) => {
if (response !== undefined) {
if (response.album.images[0].url !== undefined) {
this.currentMusicplaying = {
uriID: response.uri,
idTrack,
artists_name: response.artists,
image: response.album.images[1].url,
currentlyPlayingPreview: false,
currentlyPlayingSong: false,
duration: response.duration_ms,
song_name: response.name,
album_name: undefined,
release_date: response.album['release_date'],
preview_url: response.preview_url,
external_urls: response.external_urls.spotify,
features: undefined
};
}
else {
this.currentMusicplaying = {
uriID: response.uri,
idTrack,
artists_name: response.artists,
image: 'assets/img/noImgAvailable.png',
currentlyPlayingPreview: false,
currentlyPlayingSong: false,
duration: response.duration_ms,
song_name: response.name,
album_name: undefined,
release_date: response.album['release_date'],
preview_url: response.preview_url,
external_urls: response.external_urls.spotify,
features: undefined
};
}
if (response.album['album_type'] !== 'single') {
this.currentMusicplaying.album_name = response.album.name
}
popularity = response.popularity;
}
this.feedbackEmoji = false;
this.divEmoji = true;
}).then(() => {
this.spotifyApi.getAudioFeaturesForTrack(this.currentMusicplaying.idTrack).then((response2) => {
if (response2 !== undefined) {
this.currentMusicplaying.features = {
key: response2.key,
mode: response2.mode,
time_signature: response2.time_signature,
acousticness: response2.acousticness,
danceability: response2.danceability,
energy: response2.energy,
instrumentalness: response2.instrumentalness,
liveness: response2.liveness,
loudness: response2.loudness,
speechiness: response2.speechiness,
valence: response2.valence,
tempo: response2.tempo,
popularity
}
}
}).then(() => {
this.loadingCtrl.dismiss();
}).catch(err => {
console.log(err);
});
}).catch(err => {
console.log(err);
});
});
}
// this function is used to initialize double to upload to the DB
uploadFeedbackToDB() {
this.doubleToUpload.mood = this.feedback;
this.doubleToUpload.spotifyFeatures = this.currentMusicplaying.features;
if (!this.manumission.isTampered()) {
this.learningService.trainModel(this.doubleToUpload, this.shared.getCurrentMood());
this.learningService.uploadPersonal(this.doubleToUpload, this.idUser, this.shared.getCurrentMood(), false);
}
}
// this function is used to get emotion feedback double
onGivenFeedback(feedback: string) {
const data = this.arrayEmoji.find(currentEmotion => currentEmotion.name === feedback);
if (this.feedbackEmoji && this.waitNewFeedback) {
const image = document.querySelector('#current' + this.arrayEmoji.indexOf(data)) as HTMLElement;
if (image.style.filter !== 'none') {
this.alertChangeFeedback(feedback);
}
}
else {
let image: any;
for (let i = 0; i < this.arrayEmoji.length; i++) {
image = document.querySelector('#current' + i) as HTMLElement;
if (i !== this.arrayEmoji.indexOf(data)) {
image.style.filter = 'grayscale(100%) blur(1px)';
}
else {
image.style.filter = 'none';
}
}
this.waitNewFeedback = true;
this.feedback = feedback;
this.feedbackEmoji = true;
this.uploadFeedbackToDB();
}
}
// this function open spotify browser and play the selected song/music
// tslint:disable-next-line: variable-name
openSpotifyPlayer(external_urls: string) {
if (this.currentPlaying !== undefined) {
this.currentMusicplaying.currentlyPlayingSong = false;
this.currentPlaying = undefined;
}
if (this.currentPreview !== undefined) {
this.stop(this.currentPreview.uriID);
}
if (this.currentMusicplaying !== undefined || this.currentMusicplaying !== null) {
this.currentPlaying = this.currentMusicplaying;
if (this.currentMusicplaying.external_urls !== null) {
this.currentMusicplaying.currentlyPlayingSong = true;
this.spotifyWindow = window.open(external_urls, '_blank');
this.clearInput();
this.checkWindowClosed(this.currentMusicplaying);
} setTimeout(() => {
this.currentPlaying = undefined;
this.currentMusicplaying.currentlyPlayingSong = false;
}, this.currentMusicplaying.duration);
}
}
// this function checks every second if the opened window
// of spotify music/song is closed and is used for removing
// the play button image over the album image
async checkWindowClosed(data: any) {
this._playIntervalHandler = setInterval(() => {
if (this.spotifyWindow !== undefined) {
if (this.spotifyWindow.closed && data !== undefined) {
this.currentMusicplaying.currentlyPlayingSong = false;
clearInterval(this._playIntervalHandler);
}
}
}, 1000);
}
// this function play the preview of the song if it is available
playPreview(uri: string) {
// if current playing
if (this.soundPlayer.currentTime > 0) {
this.stop(uri);
}
if (this.currentMusicplaying !== undefined) {
if (this.currentMusicplaying.preview_url !== null) {
this.currentMusicplaying.currentlyPlayingPreview = true;
this.soundPlayer.src = this.currentMusicplaying.preview_url;
this.soundPlayer.play();
this.progressBar();
}
this._previewTimeOut = setTimeout(() => {
this.soundPlayer.pause();
this.soundPlayer.currentTime = 0;
if (this.currentMusicplaying !== undefined) {
this.currentMusicplaying.currentlyPlayingPreview = false;
}
}, 30000);
}
}
// this function is used in combination with "playPreview" function
// only for visual scope
async progressBar() {
this._previewIntervalHandler = setInterval(() => {
}, 100);
}
// this function stop a preview music/song if it is in playing
stop(uri: string) {
this.soundPlayer.pause();
clearInterval(this._previewIntervalHandler);
clearTimeout(this._previewTimeOut);
this.soundPlayer.currentTime = 0;
this.currentPreview = undefined;
this.currentPlaying = undefined;
if (uri !== null) {
if (this.currentMusicplaying !== undefined) {
this.currentMusicplaying.currentlyPlayingPreview = false;
}
}
}
// Logout form the website
logout() {
this.logoutService.logout();
}
/** ALERTS */
/* ALERT NO PREVIEW BUTTON */
async noPreview() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'No preview is available for this song',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
/* ALERT CHECK EXPIRATION TOKEN */
async alertTokenExpired() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'Your token is expired. Click ok to refresh it!',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
handler: () => {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8888/login';
}
else {
window.location.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
}
}
],
backdropDismiss: false
});
await alert.present();
}
/* ALERT USER CHANGE HIS/HER FEEDBACK FOR A SONG */
async alertChangeFeedback(feedback: string) {
const alert = await this.alertController.create({
header: 'Change Feedback',
cssClass: 'alertClassWarning',
message: 'Do you want to change the previous feedback?',
buttons: [
{
text: 'Yes',
cssClass: 'alertMedium',
handler: () => {
const doubleDelete = new Double();
doubleDelete.setMood(this.doubleToUpload.mood);
doubleDelete.spotifyFeatures = {
key: -this.doubleToUpload.spotifyFeatures.key,
mode: -this.doubleToUpload.spotifyFeatures.mode,
time_signature: -this.doubleToUpload.spotifyFeatures.time_signature,
acousticness: -this.doubleToUpload.spotifyFeatures.acousticness,
danceability: -this.doubleToUpload.spotifyFeatures.danceability,
energy: -this.doubleToUpload.spotifyFeatures.energy,
instrumentalness: -this.doubleToUpload.spotifyFeatures.instrumentalness,
liveness: -this.doubleToUpload.spotifyFeatures.liveness,
loudness: -this.doubleToUpload.spotifyFeatures.loudness,
speechiness: -this.doubleToUpload.spotifyFeatures.speechiness,
valence: -this.doubleToUpload.spotifyFeatures.valence,
tempo: -this.doubleToUpload.spotifyFeatures.tempo,
popularity: -this.doubleToUpload.spotifyFeatures.popularity
}
this.learningService.uploadPersonal(doubleDelete, this.idUser, this.shared.getCurrentMood(), true);
this.waitNewFeedback = false;
this.onGivenFeedback(feedback);
}
},
{
text: 'No',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
// Round features to 3rd decimal number
roundTo(value, places) {
const power = Math.pow(10, places);
return Math.round(value * power) / power;
}
/* ALERT LOGOUT */
async alertLogout() {
const alert = await this.alertController.create({
header: 'Logout',
cssClass: 'alertClassWarning',
message: 'Are you sure to logout?',
buttons: [
{
text: 'OK',
cssClass: 'alertMedium',
handler: () => {
this.logout();
}
},
{
text: 'Cancel',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
// Loading data
async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
/* REFRESH PAGE */
doRefresh(event) {
window.location.reload();
setTimeout(() => {
event.target.complete();
}, 5000);
}
}
<file_sep>/client/src/environments/environment.ts
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
firebaseConfig: {
apiKey: '<KEY>',
authDomain: 'moodify-spotify.firebaseapp.com',
databaseURL: 'https://moodify-spotify.firebaseio.com',
projectId: 'moodify-spotify',
storageBucket: 'moodify-spotify.appspot.com',
messagingSenderId: '303921443720',
appId: '1:303921443720:web:b359c0f50f49bcaea1803d',
measurementId: 'G-EE0FP6L4F2'
}
};
export const keyToken = 'token';
export const keyRefreshToken = 'refreshToken';
export const keyPreviousDay = 'previousDay';
export const keyExpirationToken = 'expirationToken';
export const keyCurrentMood = 'currentMood';
export const keyTargetMood = 'targetMood';
export const keyUserProfile = 'userProfile';
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
<file_sep>/client/src/app/tabs/tabs-routing.module.ts
import { TabsPage } from './tabs.page';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: '',
component: TabsPage,
children: [
{
path: 'suggest',
children: [
{
path: '',
loadChildren: () =>
import('../pages/suggest/suggest.module').then(m => m.SuggestPageModule)
}
]
},
{
path: 'search',
children: [
{
path: '',
loadChildren: () =>
import('../pages/search/search.module').then(m => m.SearchPageModule)
}
]
},
{
path: 'profile',
children: [
{
path: '',
loadChildren: () =>
import('../pages/profile/profile.module').then(m => m.ProfilePageModule)
}
]
},
{
path: 'changeMood',
children: [
{
path: '',
loadChildren: () =>
import('../pages/change-mood/change-mood.module').then(m => m.ChangeMoodPageModule)
}
]
},
{
path: '',
redirectTo: '/tab/suggest',
pathMatch: 'full'
}
]
},
{
path: '',
redirectTo: '/tab/suggest',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule { }
<file_sep>/client/src/app/mood-set/mood-set.page.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { MoodSetPage } from './mood-set.page';
describe('MoodSetPage', () => {
let component: MoodSetPage;
let fixture: ComponentFixture<MoodSetPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MoodSetPage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(MoodSetPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/client/src/app/pages/change-mood/change-mood.page.ts
import { ManumissionCheckService } from './../../services/manumission-check.service';
import { EmojisService } from './../../services/emojis.service';
import { LogoutService } from './../../services/logout.service';
import { NavController, AlertController } from '@ionic/angular';
import { SharedParamsService } from './../../services/shared-params.service';
import { Component } from '@angular/core';
@Component({
selector: 'app-change-mood',
templateUrl: 'change-mood.page.html',
styleUrls: ['change-mood.page.scss']
})
export class ChangeMoodPage {
currentEmotion: { name: string, image: string };
targetEmotion: { name: string, image: string };
constructor(private shared: SharedParamsService, private navCtrl: NavController,
private alertController: AlertController, private logoutService: LogoutService,
private emoji: EmojisService, private manumission: ManumissionCheckService) {
if (!this.manumission.isTampered()) {
this.initializeImages();
}
}
// initialize image
initializeImages() {
this.currentEmotion = this.emoji.getArrayEmoji().find(emotion => emotion.name === this.shared.getCurrentMood());
this.targetEmotion = this.emoji.getArrayEmoji().find(emotion => emotion.name === this.shared.getTargetMood());
}
// change your starting and target mood function
goToMoodSet() {
this.logoutService.removeCurrentMood();
this.logoutService.removeTargetMood();
this.navCtrl.navigateRoot('/mood');
}
// Logout form the website
logout() {
this.logoutService.logout();
}
/** ALERTS */
/* ALERT LOGOUT */
async alertLogout() {
const alert = await this.alertController.create({
header: 'Logout',
cssClass: 'alertClassWarning',
message: 'Are you sure to logout?',
buttons: [
{
text: 'OK',
cssClass: 'alertMedium',
handler: () => {
this.logout();
}
},
{
text: 'Cancel',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
/* ALERT CHANGE MOOD */
async alertMood() {
const alert = await this.alertController.create({
header: 'MOOD',
cssClass: 'alertClass',
message: 'Do you want to change your starting and target mood?',
buttons: [
{
text: 'OK',
cssClass: 'alertMedium',
handler: () => {
this.goToMoodSet();
}
},
{
text: 'Cancel',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
/* REFRESH PAGE */
doRefresh(event) {
window.location.reload();
setTimeout(() => {
event.target.complete();
}, 5000);
}
}
<file_sep>/client/src/app/services/manumission-check.service.ts
import { AlertController } from '@ionic/angular';
import { SharedParamsService } from './shared-params.service';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ManumissionCheckService {
constructor(private sharedParamsService: SharedParamsService, private alertController: AlertController) { }
public isTampered() {
if (this.sharedParamsService.getUserProfile() === null ||
this.sharedParamsService.getCurrentMood() === null ||
this.sharedParamsService.getTargetMood() === null ||
this.sharedParamsService.getToken() === null ||
this.sharedParamsService.getRefreshToken() === null ||
this.sharedParamsService.getPreviousDay() === null ||
this.sharedParamsService.getExpirationToken() === null
) {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8888/login';
}
else {
window.location.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
return true;
}
else {
return false;
}
}
}
<file_sep>/client/src/app/interfaces/UserProfile.ts
import { TrackFeatures } from './TrackFeatures';
import { UserPreferences } from './UserPreferences';
export interface UserProfile {
preferences: UserPreferences,
targetFeatures: TrackFeatures,
profilePhoto: any,
email: string;
name: string;
url: string;
country: string;
ID: string;
}<file_sep>/client/src/app/services/initialize-train.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { InitializeTrainService } from './initialize-train.service';
describe('InitializeTrainService', () => {
let service: InitializeTrainService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(InitializeTrainService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>/client/src/app/services/initialize-train.service.ts
import { LoadingController } from '@ionic/angular';
import { MachineLearningService } from './machineLearning.service';
import { TrackFeatures } from '../interfaces/TrackFeatures';
import { Double } from '../classes/Double';
import { EmojisService } from './emojis.service';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class InitializeTrainService {
constructor(private emoji: EmojisService, private learningService: MachineLearningService,
private loadingCtrl: LoadingController) { }
initialize() {
const arrayEmoji = this.emoji.getArrayEmoji();
const trackData: TrackFeatures = {
key: 5,
mode: 0,
time_signature: 4,
acousticness: 0.5,
danceability: 0.5,
energy: 0.5,
instrumentalness: 0.5,
liveness: 0.5,
loudness: -30,
speechiness: 0.5,
valence: 0.5,
tempo: 120,
popularity: 50
}
this.presentLoading('Loading data ...').then(() => {
for (const emoji of arrayEmoji) {
for (const emoji2 of arrayEmoji) {
const double = new Double();
double.mood = emoji2.name;
double.spotifyFeatures = trackData;
this.learningService.trainModel(double, emoji.name);
}
}
}).then(() => {
this.loadingCtrl.dismiss();
});
}
// Loading data
private async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
}
<file_sep>/client/src/app/mood-set/mood-set.page.ts
import { UserProfile } from './../interfaces/UserProfile';
import { MachineLearningService } from '../services/machineLearning.service';
import { EmojisService } from './../services/emojis.service';
import { SharedParamsService } from './../services/shared-params.service';
import { NavController, LoadingController } from '@ionic/angular';
import { Component } from '@angular/core';
@Component({
selector: 'app-mood-set',
templateUrl: './mood-set.page.html',
styleUrls: ['./mood-set.page.scss'],
})
export class MoodSetPage {
arrayEmoji: Array<{ name: string, image: string }> = [];
currentEmotion: string = undefined;
targetEmotion: string = undefined;
constructor(private navCtrl: NavController, private shared: SharedParamsService,
private emoji: EmojisService, private learningService: MachineLearningService,
private loadingCtrl: LoadingController) {
this.arrayEmoji = this.emoji.getArrayEmoji();
}
currentState(emoji: string) {
if (this.currentEmotion === undefined || this.currentEmotion !== emoji) {
this.currentEmotion = emoji;
let image: any;
const data = this.arrayEmoji.find(currentEmotion => currentEmotion.name === this.currentEmotion);
for (let i = 0; i < this.arrayEmoji.length; i++) {
image = document.querySelector('#current' + i) as HTMLElement;
if (i !== this.arrayEmoji.indexOf(data)) {
image.style.filter = 'grayscale(100%) blur(1px)';
}
else {
image.style.filter = 'none';
}
}
}
}
targetState(emoji: string) {
if (this.targetEmotion === undefined || this.targetEmotion !== emoji) {
this.targetEmotion = emoji;
let image: any;
const data = this.arrayEmoji.find(targetEmotion => targetEmotion.name === this.targetEmotion);
for (let i = 0; i < this.arrayEmoji.length; i++) {
image = document.querySelector('#target' + i) as HTMLElement;
if (i !== this.arrayEmoji.indexOf(data)) {
image.style.filter = 'grayscale(100%) blur(1px)';
}
else {
image.style.filter = 'none';
}
}
}
}
confirmMood() {
this.shared.setCurrentMood(this.currentEmotion);
this.shared.setTargetMood(this.targetEmotion);
const userProfile: UserProfile = this.shared.getUserProfile();
if (userProfile.targetFeatures === undefined) {
this.presentLoading('Loading data ...').then(() => {
this.learningService.getUserData(userProfile.ID, this.shared.getCurrentMood(), this.shared.getTargetMood())
.then(result2 => {
if (result2.buff !== null && result2.features !== null) {
userProfile.targetFeatures = result2.features;
this.shared.setUserProfile(userProfile);
}
else {
// console.log('User not found in DB');
}
}).then(() => {
this.loadingCtrl.dismiss();
this.navCtrl.navigateRoot('/tab/suggest');
});
});
}
else {
this.navCtrl.navigateRoot('/tab/suggest');
}
}
/* REFRESH PAGE */
doRefresh(event) {
window.location.reload();
setTimeout(() => {
event.target.complete();
}, 5000);
}
// Loading data
async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
}
<file_sep>/client/src/app/services/emojis.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class EmojisService {
startPath = 'assets/emoji/';
endPath = '.png';
amused = 'amused';
angry = 'angry';
anxious = 'anxious';
calm = 'calm';
sad = 'sad';
energy = 'energy';
happy = 'happy';
sensual = 'sensual';
arrayNameEmoji = [
this.energy,
this.amused,
this.happy,
this.sensual,
this.calm,
this.anxious,
this.sad,
this.angry
];
arrayImgEmoji = [
this.startPath + this.energy + this.endPath,
this.startPath + this.amused + this.endPath,
this.startPath + this.happy + this.endPath,
this.startPath + this.sensual + this.endPath,
this.startPath + this.calm + this.endPath,
this.startPath + this.anxious + this.endPath,
this.startPath + this.sad + this.endPath,
this.startPath + this.angry + this.endPath
];
arrayEmoji: Array<{ name: string, image: string }> = [];
constructor() {
for (let i = 0; i < 8; i++) {
this.arrayEmoji.push({ name: this.arrayNameEmoji[i], image: this.arrayImgEmoji[i] });
}
}
getEmojiImg(emoji: string) {
for (const imgEmoji in this.arrayImgEmoji) {
if (imgEmoji === emoji) {
return imgEmoji;
}
}
return null;
}
getArrayEmoji() {
return this.arrayEmoji;
}
}
<file_sep>/client/src/app/services/preferences.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { PreferencesServices } from './preferences.service';
describe('PreferencesServices', () => {
let service: PreferencesServices;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(PreferencesServices);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>/client/src/app/pages/suggest/suggest.page.ts
import { EmojiFeedback } from './../../interfaces/EmojiFeedback';
import { RecommendationParameterService } from '../../services/recommendation-parameter.service';
import { TrackData } from './../../interfaces/TrackData';
import { ManumissionCheckService } from './../../services/manumission-check.service';
import { UserProfile } from './../../interfaces/UserProfile';
import { MachineLearningService } from './../../services/machineLearning.service';
import { LogoutService } from './../../services/logout.service';
import { EmojisService } from './../../services/emojis.service';
import { Double } from '../../classes/Double';
import { AlertController, LoadingController, NavController } from '@ionic/angular';
import { SharedParamsService } from './../../services/shared-params.service';
import { Component } from '@angular/core';
import SpotifyWebApi from 'spotify-web-api-js';
@Component({
selector: 'app-suggest',
templateUrl: 'suggest.page.html',
styleUrls: ['suggest.page.scss'],
})
export class SuggestPage {
// spotifyApi
spotifyApi = new SpotifyWebApi();
// search suggested music array
recommendationTrack: Array<{ key: string, image: any, name: string }> = [];
currentIndexPlaying = 0;
listOfListened: string[] = [];
// features desired
desiredFeature: any;
// pair used for the reinforcement learning
doubleToUpload: Double = new Double();
currentMusicplaying: TrackData = null;
userProfile: UserProfile;
bufferLimit: number;
wrongFeedback = 0;
// emojis
divEmoji = false;
feedback: string;
feedbackPerTrack: Array<{ feedback: string, feedbackEmoji: boolean, waitNewFeedback: boolean, arrayEmoji: Array<EmojiFeedback> }> = []
// Player variables
soundPlayer = new Audio();
currentPreview: any = undefined;
currentPlaying: any = undefined;
spotifyWindow: Window;
_previewIntervalHandler: any;
_previewTimeOut: any;
_playIntervalHandler: any;
constructor(private shared: SharedParamsService, private logoutService: LogoutService,
private alertController: AlertController, private emoji: EmojisService,
private learningService: MachineLearningService, private loadingCtrl: LoadingController,
private manumission: ManumissionCheckService, private recommendation: RecommendationParameterService,
private navCtrl: NavController) {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.setAccessToken(this.shared.getToken());
}
}
}
ionViewDidLeave() {
this.stop(null);
}
// Initialize user's session from DB if it exist
initializeSessionDB() {
this.presentLoading('Loading data ...').then(() => {
this.userProfile = this.shared.getUserProfile();
let tempDesiredFeature: any;
this.learningService.getUserData(this.userProfile.ID, this.shared.getCurrentMood(), this.shared.getTargetMood())
.then(result => {
if (result.buff !== null && result.features !== null) {
this.bufferLimit = result.buff.numFeed;
tempDesiredFeature = {
limit: 100,
target_acousticness: result.features.acousticness,
target_key: result.features.key,
target_mode: result.features.mode,
target_time_signature: result.features.time_signature,
target_danceability: result.features.danceability,
target_energy: result.features.energy,
target_instrumentalness: result.features.instrumentalness,
target_liveness: result.features.liveness,
target_loudness: result.features.loudness,
target_speechiness: result.features.speechiness,
target_valence: result.features.valence,
target_tempo: result.features.tempo,
target_popularity: result.features.popularity,
}
let pref1: { seed_artists: string[], seed_genres: string[] };
let pref2;
if (this.userProfile.preferences !== undefined) {
pref1 = this.recommendation.getRecommendation(this.userProfile);
if (pref1 === undefined) {
this.recommendation.autoSearchFavGenres(this.userProfile).then(res => {
pref2 = res;
if (pref2 !== undefined) {
tempDesiredFeature.seed_genres = pref2;
}
}).then(() => {
if (pref2 === undefined) {
this.recommendation.generateRandomGenresSeed(this.userProfile).then(res2 => {
pref2 = res2;
if (pref2 !== undefined) {
tempDesiredFeature.seed_genres = pref2;
}
});
}
this.loadingCtrl.dismiss();
this.desiredFeature = tempDesiredFeature;
this.recommendMusic();
});
}
else {
if (pref1.seed_artists.length > 0) {
tempDesiredFeature.seed_artists = pref1.seed_artists;
}
if (pref1.seed_genres.length > 0) {
tempDesiredFeature.seed_genres = pref1.seed_genres;
}
this.loadingCtrl.dismiss();
this.desiredFeature = tempDesiredFeature;
this.recommendMusic();
}
}
else {
this.recommendation.generateRandomGenresSeed(this.userProfile).then(res3 => {
pref2 = res3;
if (pref2 !== undefined) {
tempDesiredFeature.seed_genres = pref2;
}
this.loadingCtrl.dismiss();
this.desiredFeature = tempDesiredFeature;
this.recommendMusic();
});
}
}
else {
this.loadingCtrl.dismiss();
this.navCtrl.navigateRoot('/login');
}
});
});
}
ionViewWillEnter() {
if (this.shared.getTargetMood() !== null) {
this.initializeSessionDB();
}
}
// this function search for a music based on user suggested features
// and seeds (genres and/or favorite artist)
recommendMusic() {
this.divEmoji = false;
this.stop(null);
this.recommendationTrack = [];
this.feedbackPerTrack = [];
if (this.currentMusicplaying !== null) {
this.currentMusicplaying = null;
}
let dataSearch: { key: string, image: any, name: string };
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
const arrayEmoji = this.emoji.getArrayEmoji();
this.spotifyApi.getRecommendations(this.desiredFeature)
.then((response) => {
if (response !== undefined) {
for (const trackItem of response.tracks) {
if (trackItem['album'].images.length !== 0) {
dataSearch = {
key: trackItem.id,
image: trackItem['album'].images[1].url,
name: trackItem.name,
};
}
else {
dataSearch = {
key: trackItem.id,
image: 'assets/img/noImgAvailable.png',
name: trackItem.name,
};
}
const initFeedArray: {
feedback: string, feedbackEmoji: boolean,
waitNewFeedback: boolean, arrayEmoji: Array<EmojiFeedback>
} = {
arrayEmoji,
feedbackEmoji: true,
waitNewFeedback: false,
feedback: undefined
}
if (this.listOfListened.length > 0) {
let found = false;
for (const item of this.listOfListened) {
if (item === dataSearch.key) {
found = true;
break;
}
}
if (!found) {
this.recommendationTrack.push(dataSearch);
this.feedbackPerTrack.push(initFeedArray);
}
}
else {
this.recommendationTrack.push(dataSearch);
this.feedbackPerTrack.push(initFeedArray);
}
}
if (this.recommendationTrack.length > 0) {
this.onClickTrack(this.currentIndexPlaying);
}
else {
this.listOfListened = [];
this.initializeSessionDB();
}
}
}).catch(err => {
console.log(err);
});
}
}
}
// This function uses spotify API to get a specific track and load its information
onClickTrack(indexOfTrack: number) {
this.stop(null);
this.currentIndexPlaying = indexOfTrack;
const idTrack = this.recommendationTrack[indexOfTrack].key;
this.divEmoji = true;
let popularity;
let image: any;
if (this.feedbackPerTrack[indexOfTrack].feedback !== undefined) {
const data = this.feedbackPerTrack[indexOfTrack].arrayEmoji
.find(currentEmotion => currentEmotion.name === this.feedbackPerTrack[indexOfTrack].feedback);
for (let i = 0; i < this.feedbackPerTrack[indexOfTrack].arrayEmoji.length; i++) {
image = document.querySelector('#s_current' + i) as HTMLElement;
if (i !== this.feedbackPerTrack[indexOfTrack].arrayEmoji.indexOf(data)) {
image.style.filter = 'grayscale(100%) blur(1px)';
}
else {
image.style.filter = 'none';
}
}
}
else {
for (let i = 0; i < this.feedbackPerTrack[indexOfTrack].arrayEmoji.length; i++) {
image = document.querySelector('#s_current' + i) as HTMLElement;
if (image !== null) {
image.style.filter = 'none';
}
}
}
this.presentLoading('Loading data ...').then(() => {
this.spotifyApi.getTrack(idTrack).then((response) => {
if (response !== undefined) {
this.currentMusicplaying = {
uriID: response.uri,
idTrack,
artists_name: response.artists,
image: undefined,
currentlyPlayingPreview: false,
currentlyPlayingSong: false,
duration: response.duration_ms,
song_name: response.name,
album_name: undefined,
release_date: response.album['release_date'],
preview_url: response.preview_url,
external_urls: response.external_urls.spotify,
features: undefined
};
if (response.album['album_type'] !== 'single') {
this.currentMusicplaying.album_name = response.album.name
}
if (response.album.images[0].url !== undefined) {
this.currentMusicplaying.image = response.album.images[1].url;
}
else {
this.currentMusicplaying.image = 'assets/img/noImgAvailable.png';
}
popularity = response.popularity;
}
this.divEmoji = true;
}).then(() => {
this.spotifyApi.getAudioFeaturesForTrack(this.currentMusicplaying.idTrack).then((response2) => {
if (response2 !== undefined) {
this.currentMusicplaying.features = {
key: response2.key,
mode: response2.mode,
time_signature: response2.time_signature,
acousticness: response2.acousticness,
danceability: response2.danceability,
energy: response2.energy,
instrumentalness: response2.instrumentalness,
liveness: response2.liveness,
loudness: response2.loudness,
speechiness: response2.speechiness,
valence: response2.valence,
tempo: response2.tempo,
popularity
}
}
this.loadingCtrl.dismiss();
}).catch(err => {
console.log(err);
});
}).catch(err => {
console.log(err);
});
});
}
// this function is used to initialize double to upload to the DB
uploadFeedbackToDB() {
this.doubleToUpload.mood = this.feedback;
this.doubleToUpload.spotifyFeatures = this.currentMusicplaying.features;
if (!this.manumission.isTampered()) {
this.learningService.trainModel(this.doubleToUpload, this.shared.getCurrentMood());
this.learningService.uploadPersonal(this.doubleToUpload, this.userProfile.ID, this.shared.getCurrentMood(), false);
if (this.doubleToUpload.mood === this.shared.getTargetMood()) {
if (++this.bufferLimit === 5) {
this.currentIndexPlaying = 0;
this.initializeSessionDB();
this.wrongFeedback = 0;
}
}
else {
if (++this.wrongFeedback > 10) {
this.alertRecommendation();
}
}
}
}
// this function is used to get emotion feedback double
onGivenFeedback(feedback: string) {
const data = this.feedbackPerTrack[this.currentIndexPlaying].arrayEmoji
.find(currentEmotion => currentEmotion.name === feedback);
if (this.feedbackPerTrack[this.currentIndexPlaying].feedbackEmoji &&
this.feedbackPerTrack[this.currentIndexPlaying].waitNewFeedback) {
const image = document.querySelector('#current' +
this.feedbackPerTrack[this.currentIndexPlaying].arrayEmoji.indexOf(data)) as HTMLElement;
if (image.style.filter !== 'none') {
this.alertChangeFeedback(feedback);
}
}
else {
let image: any;
for (let i = 0; i < this.feedbackPerTrack[this.currentIndexPlaying].arrayEmoji.length; i++) {
image = document.querySelector('#s_current' + i) as HTMLElement;
if (i !== this.feedbackPerTrack[this.currentIndexPlaying].arrayEmoji.indexOf(data)) {
image.style.filter = 'grayscale(100%) blur(1px)';
}
else {
image.style.filter = 'none';
}
}
this.feedbackPerTrack[this.currentIndexPlaying].waitNewFeedback = true;
this.feedback = feedback;
this.feedbackPerTrack[this.currentIndexPlaying].feedbackEmoji = true;
this.feedbackPerTrack[this.currentIndexPlaying].feedback = feedback;
this.listOfListened.push(this.currentMusicplaying.idTrack);
this.uploadFeedbackToDB();
}
}
// this function open spotify browser and play the selected song/music
// tslint:disable-next-line: variable-name
openSpotifyPlayer(external_urls: string) {
if (this.currentPlaying !== undefined) {
this.currentMusicplaying.currentlyPlayingSong = false;
this.currentPlaying = undefined;
}
if (this.currentPreview !== undefined) {
this.stop(this.currentPreview.uriID);
}
if (this.currentMusicplaying !== undefined || this.currentMusicplaying !== null) {
this.currentPlaying = this.currentMusicplaying;
if (this.currentMusicplaying.external_urls !== null) {
this.currentMusicplaying.currentlyPlayingSong = true;
this.spotifyWindow = window.open(external_urls, '_blank');
this.checkWindowClosed(this.currentMusicplaying);
} setTimeout(() => {
this.currentPlaying = undefined;
this.currentMusicplaying.currentlyPlayingSong = false;
}, this.currentMusicplaying.duration);
}
}
// this function checks every second if the opened window
// of spotify music/song is closed and is used for removing
// the play button image over the album image
async checkWindowClosed(data: any) {
this._playIntervalHandler = setInterval(() => {
if (this.spotifyWindow !== undefined) {
if (this.spotifyWindow.closed && data !== undefined) {
this.currentMusicplaying.currentlyPlayingSong = false;
clearInterval(this._playIntervalHandler);
}
}
}, 1000);
}
// this function play the preview of the song if it is available
playPreview(uri: string) {
// if current playing
if (this.soundPlayer.currentTime > 0) {
this.stop(uri);
}
if (this.currentMusicplaying !== undefined) {
if (this.currentMusicplaying.preview_url !== null) {
this.currentMusicplaying.currentlyPlayingPreview = true;
this.soundPlayer.src = this.currentMusicplaying.preview_url;
this.soundPlayer.play();
this.progressBar();
}
this._previewTimeOut = setTimeout(() => {
this.soundPlayer.pause();
this.soundPlayer.currentTime = 0;
if (this.currentMusicplaying !== undefined) {
this.currentMusicplaying.currentlyPlayingPreview = false;
}
}, 30000);
}
}
// this function is used in combination with "playPreview" function
// only for visual scope
async progressBar() {
this._previewIntervalHandler = setInterval(() => {
}, 100);
}
// this function stop a preview music/song if it is in playing
stop(uri: string) {
this.soundPlayer.pause();
clearInterval(this._previewIntervalHandler);
clearTimeout(this._previewTimeOut);
this.soundPlayer.currentTime = 0;
this.currentPreview = undefined;
this.currentPlaying = undefined;
if (uri !== null) {
if (this.currentMusicplaying !== undefined) {
this.currentMusicplaying.currentlyPlayingPreview = false;
}
}
}
// Logout form the website
logout() {
this.logoutService.logout();
}
/** ALERTS */
/* ALERT NO PREVIEW BUTTON */
async noPreview() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'No preview is available for this song',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
/* ALERT CHECK EXPIRATION TOKEN */
async alertTokenExpired() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'Your token is expired. Click ok to refresh it!',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
handler: () => {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8888/login';
}
else {
window.location.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
}
}
],
backdropDismiss: false
});
await alert.present();
}
/* ALERT USER CHANGE HIS/HER FEEDBACK FOR A SONG */
async alertChangeFeedback(feedback: string) {
const alert = await this.alertController.create({
header: 'Change Feedback',
cssClass: 'alertClassWarning',
message: 'Do you want to change the previous feedback?',
buttons: [
{
text: 'Yes',
cssClass: 'alertMedium',
handler: () => {
const doubleDelete = new Double();
doubleDelete.setMood(this.doubleToUpload.mood);
doubleDelete.spotifyFeatures = {
key: -this.doubleToUpload.spotifyFeatures.key,
mode: -this.doubleToUpload.spotifyFeatures.mode,
time_signature: -this.doubleToUpload.spotifyFeatures.time_signature,
acousticness: -this.doubleToUpload.spotifyFeatures.acousticness,
danceability: -this.doubleToUpload.spotifyFeatures.danceability,
energy: -this.doubleToUpload.spotifyFeatures.energy,
instrumentalness: -this.doubleToUpload.spotifyFeatures.instrumentalness,
liveness: -this.doubleToUpload.spotifyFeatures.liveness,
loudness: -this.doubleToUpload.spotifyFeatures.loudness,
speechiness: -this.doubleToUpload.spotifyFeatures.speechiness,
valence: -this.doubleToUpload.spotifyFeatures.valence,
tempo: -this.doubleToUpload.spotifyFeatures.tempo,
popularity: -this.doubleToUpload.spotifyFeatures.popularity
}
this.learningService.uploadPersonal(doubleDelete, this.userProfile.ID, this.shared.getCurrentMood(), true);
if (doubleDelete.mood === this.shared.getTargetMood()) {
this.wrongFeedback = this.wrongFeedback + 2;
}
this.feedbackPerTrack[this.currentIndexPlaying].waitNewFeedback = false;
this.onGivenFeedback(feedback);
}
},
{
text: 'No',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
// Round features to 3rd decimal number
roundTo(value, places) {
const power = Math.pow(10, places);
return Math.round(value * power) / power;
}
/* ALERT LOGOUT */
async alertLogout() {
const alert = await this.alertController.create({
header: 'Logout',
cssClass: 'alertClassWarning',
message: 'Are you sure to logout?',
buttons: [
{
text: 'OK',
cssClass: 'alertMedium',
handler: () => {
this.logout();
}
},
{
text: 'Cancel',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
/* ALERT BAD RECOMMENDATION */
private async alertRecommendation() {
const alert = await this.alertController.create({
header: 'Oops',
cssClass: 'alertClassError',
message: 'It seems the algorithm is not working! Please search a song that makes you ' + this.shared.getTargetMood(),
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
handler: () => {
this.navCtrl.navigateRoot('/tab/search');
}
}
],
backdropDismiss: false
});
await alert.present();
}
// Loading data
async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
/* REFRESH PAGE */
doRefresh(event) {
window.location.reload();
setTimeout(() => {
event.target.complete();
}, 5000);
}
}<file_sep>/client/README.md
# moodify-spotify
Web App that use Spotify API
<file_sep>/client/src/app/login/login.page.ts
import { InitializeTrainService } from './../services/initialize-train.service';
import { UserProfile } from './../interfaces/UserProfile';
import { EmojisService } from './../services/emojis.service';
import { Double } from '../classes/Double';
import { MachineLearningService } from '../services/machineLearning.service';
import { UserPreferences } from './../interfaces/UserPreferences';
import { PreferencesServices } from './../services/preferences.service';
import { SharedParamsService } from './../services/shared-params.service';
import { Component } from '@angular/core';
import { NavController, LoadingController } from '@ionic/angular';
import SpotifyWebApi from 'spotify-web-api-js';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage {
// spotifyAPI
spotifyApi = new SpotifyWebApi();
params: any;
href: string;
// User profile
userProfile: UserProfile;
// Handler
end = false;
_checkDB: any;
constructor(private shared: SharedParamsService, private prefService: PreferencesServices,
private navCtrl: NavController, private loadingCtrl: LoadingController, private emoji: EmojisService,
private initialize: InitializeTrainService,
private learningService: MachineLearningService) {
this.params = this.getHashParams();
// if already logged
if (this.shared.getExpirationToken() !== null && this.params.access_token === undefined) {
if (this.shared.checkExpirationToken()) {
this.initializeHref();
this.onClickLogin();
}
else {
this.initializeSessionDB();
}
}
// if it's a redirect
else if (this.params.access_token !== undefined) {
this.presentLoading('Logging in ...').then(() => {
window.history.replaceState({}, document.title, '/' + 'login');
if (this.shared.getExpirationToken() !== null) {
this.shared.setPreviousDay(this.shared.getExpirationToken());
}
else {
this.shared.setPreviousDay(new Date());
}
this.shared.setExpirationToken(new Date());
this.shared.setToken(this.params.access_token);
this.shared.setRefreshToken(this.params.refresh_token);
this.initializeSessionDB();
}).finally(() => {
this.loadingCtrl.dismiss();
});
}
// if it's not a redirect or never logged wait button login pressed
else {
this.initializeHref();
}
}
// this function call the login server
onClickLogin() {
this.presentLoading('Awaiting for Moodify-Spotify Server ...').then(() => {
window.location.href = this.href;
});
}
getHashParams() {
const hashParams = {};
const r = /([^&;=]+)=?([^&;]*)/g;
const q = window.location.hash.substring(1);
let e = r.exec(q);
while (e) {
hashParams[e[1]] = decodeURIComponent(e[2]);
e = r.exec(q);
}
return hashParams;
}
// Initialize user's session from DB if it exist
initializeSessionDB() {
this.spotifyApi.setAccessToken(this.shared.getToken());
this.presentLoading('Loading data ...').then(() => {
this.spotifyApi.getMe().then((response) => {
this.userProfile = {
ID: response.id,
country: response.country,
targetFeatures: undefined,
url: response.external_urls.spotify,
email: response.email,
profilePhoto: (undefined || response.images.length === 0) ? 'assets/img/noImgAvailable.png' : response.images[0].url,
name: response.display_name,
preferences: undefined
}
}).then(() => {
this.prefService.getUserPreferences(this.userProfile.ID).then(result => {
if (result !== undefined) {
const userPreferences: UserPreferences = {
favoriteGenres: result.favoriteGenres,
hatedGenres: result.hatedGenres,
favoriteSingers: result.favoriteSingers
}
this.userProfile.preferences = userPreferences;
}
})
}).then(() => {
this.learningService.getUser(this.userProfile.ID).then(result2 => {
if (result2 !== undefined) {
if (this.shared.getCurrentMood() !== undefined && this.shared.getTargetMood() !== undefined) {
this.learningService.getUserData(this.userProfile.ID, this.shared.getCurrentMood(), this.shared.getTargetMood())
.then(result3 => {
this.userProfile.targetFeatures = result3.features;
}).then(() => {
this.loadingCtrl.dismiss();
this.checkSetMood();
});
}
else {
this.loadingCtrl.dismiss();
}
}
else {
this.copyModel();
}
});
});
});
}
// this function redirect page if moods were already Set
checkSetMood() {
this.shared.setUserProfile(this.userProfile);
this.loadingCtrl.dismiss();
if (
this.shared.getCurrentMood() !== null &&
this.shared.getTargetMood() !== null
) {
this.navCtrl.navigateRoot('/tab/suggest');
}
else {
this.navCtrl.navigateRoot('/mood');
}
}
// This function initialize the redirection page to the login
// based if is localhost or web
initializeHref() {
if (window.location.href.includes('localhost')) {
this.href = 'http://localhost:8888/login';
}
else {
this.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
}
// This function let user to use a different account
changeAccount() {
const url = 'https://www.spotify.com/logout/'
const spotifyLogoutWindow = window.open(url, 'Spotify Logout', 'width=700,height=500,top=40,left=40')
setTimeout(() => spotifyLogoutWindow.close(), 2000)
}
// Loading data
async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
copyModel() {
const arrayEmoji = this.emoji.getArrayEmoji();
for (const [index, emoji] of arrayEmoji.entries()) {
for (const [index2, emoji2] of arrayEmoji.entries()) {
this.learningService.getModelData(emoji.name, emoji2.name).then(result => {
if (result !== undefined) {
const double = new Double();
double.mood = emoji2.name;
double.spotifyFeatures = result.features;
this.learningService.uploadPersonal(double, this.userProfile.ID, emoji.name, false);
}
}).then(() => {
if (index * index2 === Math.pow(arrayEmoji.length - 1, 2)) {
this.checkSetMood();
}
});
}
}
}
}
<file_sep>/client/src/app/services/preferences.service.ts
import { UserPreferences } from './../interfaces/UserPreferences';
import { LoadingController, AlertController } from '@ionic/angular';
import { AngularFirestore } from '@angular/fire/firestore';
import { Injectable } from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/database';
@Injectable({
providedIn: 'root'
})
export class PreferencesServices {
database = firebase.database();
constructor(private afs: AngularFirestore, private loadingCtrl: LoadingController,
private alertController: AlertController) {
}
uploadPreferences(userPreferences: UserPreferences, id: string) {
this.presentLoading('Loading data ...').then(() => {
firebase.database().ref('preferences/' + id).set({
favoriteGenres: userPreferences.favoriteGenres,
hatedGenres: userPreferences.hatedGenres,
favoriteSingers: userPreferences.favoriteSingers
}).then(() => {
this.loadingCtrl.dismiss();
this.alertSuccess('Preferences uploaded', 'Your preferences has been uploaded', 'alertClassPrimary');
}).catch(() => {
this.loadingCtrl.dismiss();
this.alertSuccess('Error', 'Your preferences has not been uploaded', 'alertClassError');
});
});
}
async getUserPreferences(userID: string) {
let pref: UserPreferences;
const db = firebase.database()
const ref = db.ref('/preferences/' + userID)
const snapshot = await ref.once('value');
const values = snapshot.val();
if (values === null) {
return undefined;
}
else {
pref = {
favoriteGenres: values.favoriteGenres,
hatedGenres: values.hatedGenres,
favoriteSingers: values.favoriteSingers
};
return pref;
}
}
updatePreferences(userPreferences: UserPreferences, id: string) {
this.presentLoading('Loading data ...').then(() => {
firebase.database().ref('preferences/' + id).update({
favoriteGenres: userPreferences.favoriteGenres,
hatedGenres: userPreferences.hatedGenres,
favoriteSingers: userPreferences.favoriteSingers
}).then(() => {
this.loadingCtrl.dismiss();
this.alertSuccess('Preferences uploaded', 'Your preferences has been uploaded', 'alertClassPrimary');
}).catch(() => {
this.loadingCtrl.dismiss();
this.alertSuccess('Error', 'Your preferences has not been uploaded', 'alertClassError');
});
});
}
// Loading data
private async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
/* ALERT SUCCESS */
private async alertSuccess(head: string, text: string, classCSS: string) {
const alert = await this.alertController.create({
header: head,
cssClass: classCSS,
message: text,
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
// timeout of 2 seconds for the alert
setTimeout(() => {
alert.dismiss();
}, 10000);
}
}
<file_sep>/client/src/app/pages/profile/profile.page.ts
import { ManumissionCheckService } from './../../services/manumission-check.service';
import { UserProfile } from './../../interfaces/UserProfile';
import { LogoutService } from './../../services/logout.service';
import { PreferencesServices } from '../../services/preferences.service';
import { SharedParamsService } from './../../services/shared-params.service';
import { Component } from '@angular/core';
import SpotifyWebApi from 'spotify-web-api-js';
import { AlertController, LoadingController } from '@ionic/angular';
import { UserPreferences } from '../../interfaces/UserPreferences';
@Component({
selector: 'app-profile',
templateUrl: 'profile.page.html',
styleUrls: ['profile.page.scss']
})
export class ProfilePage {
// spotifyAPI
spotifyApi = new SpotifyWebApi();
// User variables
userProfile: UserProfile;
// Artists variables
topArtistsMap = {};
suggestfavArtist: Array<{ key: string, image: any, name: string, checked: boolean }> = [];
searchFavArtist: Array<{ key: string, image: any, name: string, checked: boolean }> = [];
selectedFavArtist: Array<{ key: string, image: any, name: string, checked: boolean }> = [];
singerDiv = false;
preventSearchBug = false;
// Genres variables
topGenresMap = [];
genresAvailable: Array<{ key: string, checkedFav: boolean, checkedHate: boolean }> = [];
favGenresSelected = [];
hatedGenresSelected = [];
// preferences changes variable
backupselectedFavArtist: Array<{ key: string, image: any, name: string, checked: boolean }> = [];
backupfavGenresSelected = [];
backuphatedGenresSelected = [];
hasChange = false;
// html variables
showArtist = 'Show';
showFavoriteGenres = 'Show';
showHatedGenres = 'Show';
constructor(private shared: SharedParamsService, private alertController: AlertController,
private prefService: PreferencesServices, private logoutService: LogoutService,
private manumission: ManumissionCheckService, private loadingCtrl: LoadingController) {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.setAccessToken(this.shared.getToken());
this.userProfile = this.shared.getUserProfile();
if (this.userProfile.preferences !== undefined) {
if (this.userProfile.preferences.favoriteGenres !== undefined) {
this.favGenresSelected = this.userProfile.preferences.favoriteGenres;
this.backupfavGenresSelected = this.favGenresSelected.slice();
}
if (this.userProfile.preferences.hatedGenres !== undefined) {
this.hatedGenresSelected = this.userProfile.preferences.hatedGenres;
this.backuphatedGenresSelected = this.hatedGenresSelected.slice();
}
if (this.userProfile.preferences.favoriteSingers !== undefined) {
if (this.userProfile.preferences.favoriteSingers.length > 0) {
this.presentLoading('Loading data ...').then(() => {
this.spotifyApi.getArtists(this.userProfile.preferences.favoriteSingers).then((response) => {
if (response !== undefined) {
for (const artist of response.artists) {
const dataArtist = {
key: artist.id,
image: artist.images[0].url,
name: artist.name,
checked: true
};
this.selectedFavArtist.push(dataArtist);
this.backupselectedFavArtist.push(dataArtist);
}
}
this.initializeGenresSeeds();
this.autoSearchFavGenres();
this.loadingCtrl.dismiss();
});
});
}
else {
this.initializeGenresSeeds();
this.autoSearchFavGenres();
}
}
else {
this.initializeGenresSeeds();
this.autoSearchFavGenres();
}
}
else {
this.initializeGenresSeeds();
this.autoSearchFavGenres();
}
}
}
}
// Function that submit the user preferences (used for cold start)
onClickSubmit() {
const favArtist = [];
this.backupselectedFavArtist = [];
for (let i = 0; i < this.selectedFavArtist.length; i++) {
favArtist[i] = this.selectedFavArtist[i].key;
this.backupselectedFavArtist.push(this.selectedFavArtist[i]);
}
const pref: UserPreferences = {
favoriteGenres: this.favGenresSelected,
favoriteSingers: favArtist,
hatedGenres: this.hatedGenresSelected
}
if (this.userProfile.preferences !== undefined) {
this.prefService.updatePreferences(pref, this.userProfile.ID);
}
else {
this.prefService.uploadPreferences(pref, this.userProfile.ID);
}
this.userProfile.preferences = pref;
this.shared.setUserProfile(this.userProfile);
this.backupfavGenresSelected = this.favGenresSelected.slice();
this.backuphatedGenresSelected = this.hatedGenresSelected.slice();
this.hasChange = false;
}
// Function that search for your favorite musics' genres
// based on your top artist's music genres
autoSearchFavGenres() {
const temTopGenresMap = {};
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.getMyTopArtists({ limit: 50, time_range: 'long_term' }).then((response) => {
if (response !== undefined) {
for (const [index, item] of response.items.entries()) {
// cycle on all the genres of the artist
let checked = false;
for (const genres of item.genres) {
if (temTopGenresMap[genres] === undefined) {
temTopGenresMap[genres] = 1;
}
else {
temTopGenresMap[genres] += 1;
}
}
if (index < 10) {
if (this.userProfile.preferences !== undefined) {
if (this.userProfile.preferences.favoriteSingers !== undefined) {
for (const pref of this.userProfile.preferences.favoriteSingers) {
if (pref === item.id) {
checked = true;
break;
}
}
}
}
const data = {
key: item.id,
image: item.images[0].url,
name: item.name,
checked
};
this.suggestfavArtist.push(data);
}
}
this.topGenresMap = this.sortProperties(temTopGenresMap);
}
}).catch(err => {
console.log(err);
});
}
}
}
// this function sort your top array of
// genres" from the higher to the lower
sortProperties(obj) {
// convert object into array
const sortable = [];
for (const key in obj)
if (obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]
// sort items by value order descending
sortable.sort((a, b) => {
return b[1] - a[1]; // compare numbers
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
/* FAVORITE AND HATED GENRES */
// This function get all spotify's seed's genres available
initializeGenresSeeds() {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.getAvailableGenreSeeds().then((response) => {
if (response !== undefined) {
let data: { key: string, checkedFav: boolean, checkedHate: boolean };
for (const genres of response.genres) {
let checkFav = false;
let checkHate = false;
if (this.userProfile.preferences !== undefined) {
if (this.userProfile.preferences.favoriteGenres !== undefined) {
for (const favGen of this.userProfile.preferences.favoriteGenres) {
if (genres === favGen) {
checkFav = true;
break;
}
}
}
if (this.userProfile.preferences.hatedGenres !== undefined) {
for (const hateGen of this.userProfile.preferences.hatedGenres) {
if (genres === hateGen) {
checkHate = true;
break;
}
}
}
}
data = {
key: genres,
checkedFav: checkFav,
checkedHate: checkHate
}
this.genresAvailable.push(data);
}
}
});
}
}
}
// This function open Div of artist preference
showFavGenresDiv() {
const favDiv = document.querySelector('#favDiv') as HTMLElement;
if (favDiv.style.display !== 'block') {
favDiv.style.display = 'block';
this.showFavoriteGenres = 'Hide';
}
else {
favDiv.style.display = 'none';
this.showFavoriteGenres = 'Show';
}
}
// This function open Div of artist preference
showHatedGenresDiv() {
const hatedDiv = document.querySelector('#hateDiv') as HTMLElement;
if (hatedDiv.style.display !== 'block') {
hatedDiv.style.display = 'block';
this.showHatedGenres = 'Hide';
}
else {
hatedDiv.style.display = 'none';
this.showHatedGenres = 'Show';
}
}
// this function update the genres' preferences of the user
updateGenresPref(whereSelected, genres) {
const dataSelected = this.genresAvailable.find(genData => genData.key === genres)
switch (whereSelected) {
// if user use "favorite" for adding or removing a genres preference
case 'favorite':
if (dataSelected !== undefined) {
dataSelected.checkedFav = !dataSelected.checkedFav;
if (dataSelected.checkedFav) {
this.favGenresSelected.push(dataSelected.key);
}
else {
this.favGenresSelected.splice(this.favGenresSelected.indexOf(dataSelected.key), 1);
}
}
break;
// if user use "hated" for adding or removing a genres preference
case 'hated':
if (dataSelected !== undefined) {
dataSelected.checkedHate = !dataSelected.checkedHate;
if (dataSelected.checkedHate) {
this.hatedGenresSelected.push(dataSelected.key);
}
else {
this.hatedGenresSelected.splice(this.hatedGenresSelected.indexOf(dataSelected.key), 1);
}
}
break;
default: break;
}
this.checkChangePreferences();
}
checkChangePreferences() {
if (this.backuphatedGenresSelected.length !== this.hatedGenresSelected.length) {
this.hasChange = true;
return;
}
for (let i = 0; i < this.hatedGenresSelected.length; i++) {
if (this.backuphatedGenresSelected[i] !== this.hatedGenresSelected[i]) {
this.hasChange = true;
return;
}
}
if (this.backupfavGenresSelected.length !== this.favGenresSelected.length) {
this.hasChange = true;
return;
}
for (let i = 0; i < this.favGenresSelected.length; i++) {
if (this.backupfavGenresSelected[i] !== this.favGenresSelected[i]) {
this.hasChange = true;
return;
}
}
if (this.backupselectedFavArtist.length !== this.selectedFavArtist.length) {
this.hasChange = true;
return;
}
for (let i = 0; i < this.selectedFavArtist.length; i++) {
if (this.backupselectedFavArtist[i].key !== this.selectedFavArtist[i].key) {
this.hasChange = true;
return;
}
}
this.hasChange = false;
}
/* SINGER PREFERENCES */
// This function open Div of artist preference
showSingerPref() {
this.singerDiv = !this.singerDiv;
if (!this.singerDiv) {
this.clearSearch();
}
this.showArtist = this.singerDiv === false ? 'Show' : 'Hide';
}
// This function add or remove a favorite artist
// from an array of the user's favorite artist
updateSingerPref(whereSelected, singer) {
const dataSearch = this.searchFavArtist.find(artist => artist.key === singer);
const dataSelected = this.selectedFavArtist.find(artist => artist.key === singer);
const dataSuggest = this.suggestfavArtist.find(artist => artist.key === singer);
switch (whereSelected) {
// if user use "search" for adding or removing an artist
case 'search':
if (!this.preventSearchBug) {
if (dataSearch !== undefined) {
this.searchFavArtist[this.searchFavArtist.indexOf(dataSearch)].checked = !dataSearch.checked;
const newDataSearch = this.searchFavArtist.find(artist => artist.key === singer);
// I add it to
if (dataSelected === undefined) {
this.selectedFavArtist.push(newDataSearch);
if (dataSuggest !== undefined) {
this.suggestfavArtist[this.suggestfavArtist.indexOf(dataSuggest)].checked = true;
}
}
// I delete it
else {
this.selectedFavArtist.splice(this.selectedFavArtist.indexOf(dataSelected), 1);
if (dataSuggest !== undefined) {
this.suggestfavArtist[this.suggestfavArtist.indexOf(dataSuggest)].checked = false;
}
}
}
}
this.preventSearchBug = false;
break;
// if user use "favorite section" for removing an artist
case 'favorite':
if (dataSearch !== undefined) {
this.searchFavArtist[this.searchFavArtist.indexOf(dataSearch)].checked = false;
}
if (dataSuggest !== undefined) {
this.suggestfavArtist[this.suggestfavArtist.indexOf(dataSuggest)].checked = false;
}
if (dataSelected !== undefined) {
this.selectedFavArtist.splice(this.selectedFavArtist.indexOf(dataSelected), 1);
}
if (dataSearch !== undefined) {
this.preventSearchBug = true;
}
break;
// if user use "suggest" for adding or removing an artist
case 'suggest':
this.suggestfavArtist[this.suggestfavArtist.indexOf(dataSuggest)].checked = true;
const newDataSuggest = this.suggestfavArtist.find(artist => artist.key === singer);
if (dataSelected === undefined) {
this.selectedFavArtist.push(this.suggestfavArtist[this.suggestfavArtist.indexOf(newDataSuggest)]);
}
if (dataSearch !== undefined) {
this.searchFavArtist[this.searchFavArtist.indexOf(dataSearch)].checked = true;
}
if (dataSearch !== undefined) {
this.preventSearchBug = true;
}
break;
default: break;
}
this.checkChangePreferences();
}
/* This function let you search an artist */
searchArtist($event) {
let dataSearch: { key: string, image: any, name: string, checked: boolean };
let dataSelected: { key: string, image: any, name: string, checked: boolean };
let check: boolean;
if ($event.detail.value.length > 0) {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
this.spotifyApi.search($event.detail.value, ['artist'], { market: 'US', limit: 5, offset: 0 }).then((response) => {
if (this.searchFavArtist.length > 0) {
this.searchFavArtist = [];
}
if (response !== undefined) {
for (const itemArtist of response.artists.items) {
dataSelected = this.selectedFavArtist.find(artist => artist.key === itemArtist.id);
if (dataSelected !== undefined) {
check = true;
}
else {
check = false;
}
if (itemArtist.images.length !== 0) {
dataSearch = {
key: itemArtist.id,
image: itemArtist.images[0].url,
name: itemArtist.name,
checked: check
};
}
else {
dataSearch = {
key: itemArtist.id,
image: 'assets/img/noImgAvailable.png',
name: itemArtist.name,
checked: check
};
}
this.searchFavArtist.push(dataSearch);
}
}
});
}
}
} else {
if (this.searchFavArtist.length > 0) {
this.searchFavArtist = [];
}
}
}
// clear searchbar
clearSearch() {
if (this.searchFavArtist.length > 0) {
this.searchFavArtist = [];
}
}
// Logout form the website
logout() {
this.logoutService.logout();
}
/** ALERTS */
/* ALERT CHECK EXPIRATION TOKEN */
async alertTokenExpired() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'Your token is expired. Click ok to refresh it!',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
handler: () => {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8888/login';
}
else {
window.location.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
}
}
],
backdropDismiss: false
});
await alert.present();
}
/** ALERTS */
/* ALERT LOGOUT */
async alertLogout() {
const alert = await this.alertController.create({
header: 'Logout',
cssClass: 'alertClassWarning',
message: 'Are you sure to logout?',
buttons: [
{
text: 'OK',
cssClass: 'alertMedium',
handler: () => {
this.logout();
}
},
{
text: 'Cancel',
cssClass: 'alertConfirm',
}
],
});
await alert.present();
}
// Loading data
async presentLoading(str: string) {
const loading = await this.loadingCtrl.create({
message: str,
});
return await loading.present();
}
/* REFRESH PAGE */
doRefresh(event) {
window.location.reload();
setTimeout(() => {
event.target.complete();
}, 5000);
}
}
<file_sep>/client/src/app/services/shared-params.service.ts
import { UserProfile } from './../interfaces/UserProfile';
import {
keyTargetMood, keyExpirationToken, keyToken, keyRefreshToken,
keyPreviousDay, keyUserProfile
} from './../../environments/environment';
import { Injectable } from '@angular/core';
import { keyCurrentMood } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class SharedParamsService {
constructor() {
}
/* SETTERS TOKEN*/
public setToken(data) {
localStorage.setItem(keyToken, data);
}
public setRefreshToken(data) {
localStorage.setItem(keyRefreshToken, data);
}
public setExpirationToken(time) {
localStorage.setItem(keyExpirationToken, time);
}
public setPreviousDay(time) {
localStorage.setItem(keyPreviousDay, time);
}
/* GETTERS TOKEN */
public getRefreshToken() {
return localStorage.getItem(keyRefreshToken);
}
public getToken() {
return localStorage.getItem(keyToken);
}
public getExpirationToken() {
return localStorage.getItem(keyExpirationToken);
}
public getPreviousDay() {
return localStorage.getItem(keyPreviousDay);
}
public checkExpirationToken() {
const ONE_HOUR = 59 * 60 * 1000; // 59 minutes after expiration in millisecond
const currentDate = new Date();
const storageDate = new Date(JSON.parse(JSON.stringify(this.getExpirationToken())));
// an hour is passed
if (((currentDate.getTime() - storageDate.getTime()) > ONE_HOUR)) {
localStorage.removeItem(keyExpirationToken);
return true;
}
else {
return false;
}
}
/* SETTERS MOOD*/
public setCurrentMood(currentMood) {
localStorage.setItem(keyCurrentMood, currentMood);
}
public setTargetMood(targetMood) {
localStorage.setItem(keyTargetMood, targetMood);
}
/* GETTERS MOOD */
public getCurrentMood() {
return localStorage.getItem(keyCurrentMood);
}
public getTargetMood() {
return localStorage.getItem(keyTargetMood);
}
/* SETTERS USER PROFILE */
public setUserProfile(userProfile: UserProfile) {
localStorage.setItem(keyUserProfile, JSON.stringify(userProfile));
}
/* GETTERS USER PROFILE */
public getUserProfile() {
return JSON.parse(localStorage.getItem(keyUserProfile));
}
}
<file_sep>/client/src/app/services/recommendation-parameter.service.ts
import { UserProfile } from './../interfaces/UserProfile';
import { AlertController } from '@ionic/angular';
import { SharedParamsService } from './shared-params.service';
import { ManumissionCheckService } from './manumission-check.service';
import { Injectable } from '@angular/core';
import SpotifyWebApi from 'spotify-web-api-js';
@Injectable({
providedIn: 'root'
})
export class RecommendationParameterService {
// spotifyAPI
spotifyApi = new SpotifyWebApi();
// Genres variables
genresAvailable = [];
constructor(private manumission: ManumissionCheckService, private shared: SharedParamsService,
private alertController: AlertController) {
this.spotifyApi.setAccessToken(this.shared.getToken());
this.spotifyApi.getAvailableGenreSeeds().then((response1) => {
if (response1 !== undefined) {
const userProfile = this.shared.getUserProfile();
for (const genres of response1.genres) {
if (userProfile.preferences !== undefined) {
if (userProfile.preferences.hatedGenres !== undefined) {
for (const hate of userProfile.preferences.hatedGenres) {
if (hate !== genres) {
this.genresAvailable.push(genres);
}
}
}
}
}
}
});
}
getRecommendation(userProfile: UserProfile): { seed_artists: string[], seed_genres: string[] } {
let dataRecommendation: { seed_artists: string[], seed_genres: string[] } = { seed_artists: [], seed_genres: [] };
if (userProfile.preferences !== undefined) {
if (userProfile.preferences.favoriteGenres !== undefined &&
userProfile.preferences.favoriteSingers !== undefined) {
let rand = Math.floor(Math.random() * 4) + 1;
if (userProfile.preferences.favoriteSingers.length < userProfile.preferences.favoriteGenres.length) {
rand = 5 - rand;
}
for (let i = 0; i < rand && i < userProfile.preferences.favoriteSingers.length; i++) {
dataRecommendation.seed_artists.push(userProfile.preferences.favoriteSingers[i]);
}
for (let i = 0; i < (5 - rand) && i < userProfile.preferences.favoriteGenres.length; i++) {
dataRecommendation.seed_genres.push(userProfile.preferences.favoriteGenres[i]);
}
return dataRecommendation;
}
else if (userProfile.preferences.favoriteGenres !== undefined &&
userProfile.preferences.favoriteSingers === undefined) {
dataRecommendation = {
seed_artists: [],
seed_genres: userProfile.preferences.favoriteGenres,
}
return dataRecommendation;
}
else if (userProfile.preferences.favoriteGenres === undefined &&
userProfile.preferences.favoriteSingers !== undefined) {
dataRecommendation = {
seed_artists: userProfile.preferences.favoriteSingers,
seed_genres: []
}
return dataRecommendation;
}
else {
return undefined;
}
}
}
/* FAVORITE AND HATED GENRES */
// This function get all spotify's seed's genres available
async generateRandomGenresSeed(userProfile: UserProfile) {
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
return undefined;
}
else {
const genresAvailable = [];
const randomGenres = [];
return await this.spotifyApi.getAvailableGenreSeeds().then((response) => {
if (response !== undefined) {
for (const genres of response.genres) {
if (userProfile.preferences !== undefined) {
if (userProfile.preferences.hatedGenres !== undefined) {
for (const hate of userProfile.preferences.hatedGenres) {
if (hate !== genres) {
genresAvailable.push(genres);
}
}
}
}
else {
genresAvailable.push(genres);
}
}
for (let i = 0; i < 5 && i < genresAvailable.length; i++) {
const rand = Math.floor(Math.random() * genresAvailable.length);
randomGenres.push(genresAvailable[rand]);
genresAvailable.splice(rand, 1);
}
return randomGenres;
}
});
}
} else {
return undefined;
}
}
// Function that search for your favorite musics' genres
// based on your top artist's music genres
async autoSearchFavGenres(userProfile) {
const temTopGenresMap = {};
if (!this.manumission.isTampered()) {
if (this.shared.checkExpirationToken()) {
this.alertTokenExpired();
}
else {
let topGenresMap = [];
return await this.spotifyApi.getMyTopArtists({ limit: 50, time_range: 'long_term' }).then((response) => {
if (response !== undefined) {
for (const item of response.items) {
// cycle on all the genres of the artist
for (const genres1 of item.genres) {
for (const availabe of this.genresAvailable) {
if (this.similarity(availabe, genres1) > 0.4) {
if (temTopGenresMap[availabe] === undefined) {
temTopGenresMap[availabe] = 1;
}
else {
temTopGenresMap[availabe] += 1;
}
}
}
}
}
topGenresMap = this.sortProperties(temTopGenresMap);
const genres = [];
if (topGenresMap.length === 0) {
return undefined;
}
else {
for (let i = 0; i < 5 && i < topGenresMap.length; i++) {
const rand = this.myRandom(topGenresMap.length);
genres.push(topGenresMap[rand][0]);
topGenresMap.splice(rand, 1);
}
}
return genres;
}
}).catch(err => {
console.log(err);
});
}
}
}
// this function return va
myRandom(maxLen: number) {
const rnd = Math.random(), rnd2 = Math.random();
const first = Math.floor(maxLen / 10), second = Math.floor(maxLen / 2);
let x: number;
if (rnd < 0.75) {
x = Math.floor(rnd2 * first);
return (x);
}
else if (rnd < 0.9) {
x = Math.floor(rnd2 * (second - first) + first);
return (x);
}
else {
x = Math.floor(rnd2 * (maxLen - second) + second);
return (x);
}
}
// this function sort your top array of
// genres" from the higher to the lower
sortProperties(obj) {
// convert object into array
const sortable = [];
for (const key in obj)
if (obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]
// sort items by value order descending
sortable.sort((a, b) => {
return b[1] - a[1]; // compare numbers
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
/** ALERTS */
/* ALERT CHECK EXPIRATION TOKEN */
async alertTokenExpired() {
const alert = await this.alertController.create({
header: 'Error',
cssClass: 'alertClassError',
message: 'Your token is expired. Click ok to refresh it!',
buttons: [
{
text: 'OK',
cssClass: 'alertConfirm',
handler: () => {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8888/login';
}
else {
window.location.href = 'https://moodify-spotify-server.herokuapp.com/login';
}
}
}
],
backdropDismiss: false
});
await alert.present
}
similarity(s1, s2) {
let longer = s1;
let shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
const longerLength = longer.length;
if (longerLength === 0) {
return 1.0;
}
return (longerLength - this.editDistance(longer, shorter)) / parseFloat(longerLength);
}
editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
const costs = new Array();
for (let i = 0; i <= s1.length; i++) {
let lastValue = i;
for (let j = 0; j <= s2.length; j++) {
if (i === 0)
costs[j] = j;
else {
if (j > 0) {
let newValue = costs[j - 1];
if (s1.charAt(i - 1) !== s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
}<file_sep>/client/src/app/interfaces/TrackData.ts
import { TrackFeatures } from './TrackFeatures';
export interface TrackData {
uriID: string,
idTrack: string,
artists_name: any[],
image: any,
currentlyPlayingPreview: boolean,
currentlyPlayingSong: boolean,
duration: number,
song_name: string,
album_name: string,
release_date: string,
preview_url: string,
external_urls: string,
features: TrackFeatures
}<file_sep>/client/src/app/services/mood-guard.service.ts
import { SharedParamsService } from './shared-params.service';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MoodGuardService {
constructor(private shared: SharedParamsService) { }
checkMood() {
if (this.shared.getCurrentMood() == null || this.shared.getTargetMood() == null) {
return true;
}
else {
return false;
}
}
checkSameDay() {
const today = new Date();
const someDate = new Date(JSON.parse(JSON.stringify(this.shared.getPreviousDay())));
return someDate.getDate() === today.getDate() &&
someDate.getMonth() === today.getMonth() &&
someDate.getFullYear() === today.getFullYear();
}
}
<file_sep>/client/src/app/interfaces/UserPreferences.ts
export interface UserPreferences {
favoriteGenres: string[];
hatedGenres: string[];
favoriteSingers: string[];
}<file_sep>/client/src/app/services/logout.service.ts
import { NavController } from '@ionic/angular';
import { keyCurrentMood } from 'src/environments/environment';
import { keyToken, keyRefreshToken, keyExpirationToken, keyTargetMood, keyUserProfile } from './../../environments/environment';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LogoutService {
constructor(private navCtrl: NavController) { }
/* REMOVERS */
public removeToken() {
localStorage.removeItem(keyToken);
}
public removeRefreshToken() {
localStorage.removeItem(keyRefreshToken);
}
public removeExpirationToken() {
localStorage.removeItem(keyExpirationToken);
}
public removeCurrentMood() {
localStorage.removeItem(keyCurrentMood);
}
public removeTargetMood() {
localStorage.removeItem(keyTargetMood);
}
public removeUser() {
localStorage.removeItem(keyUserProfile);
}
public removeAllShared() {
this.removeToken();
this.removeRefreshToken();
this.removeExpirationToken();
this.removeCurrentMood();
this.removeTargetMood();
this.removeUser();
}
logout() {
this.removeAllShared();
this.navCtrl.navigateRoot('/login');
}
}
<file_sep>/client/src/app/classes/Double.ts
import { TrackFeatures } from './../interfaces/TrackFeatures';
export class Double {
mood: string;
spotifyFeatures: TrackFeatures;
constructor() {
this.mood = null;
this.spotifyFeatures = {
key: null,
mode: null,
time_signature: null,
acousticness: null,
danceability: null,
energy: null,
instrumentalness: null,
liveness: null,
loudness: null,
speechiness: null,
valence: null,
tempo: null,
popularity: null
};
}
setMood(mood: string) {
this.mood = mood;
}
setSpotifyFeatures(trackFeatures: TrackFeatures) {
this.spotifyFeatures.acousticness = trackFeatures.acousticness;
this.spotifyFeatures.key = trackFeatures.key;
this.spotifyFeatures.mode = trackFeatures.mode;
this.spotifyFeatures.time_signature = trackFeatures.time_signature;
this.spotifyFeatures.acousticness = trackFeatures.acousticness;
this.spotifyFeatures.danceability = trackFeatures.danceability;
this.spotifyFeatures.energy = trackFeatures.energy;
this.spotifyFeatures.instrumentalness = trackFeatures.instrumentalness;
this.spotifyFeatures.liveness = trackFeatures.liveness;
this.spotifyFeatures.loudness = trackFeatures.loudness;
this.spotifyFeatures.speechiness = trackFeatures.speechiness;
this.spotifyFeatures.valence = trackFeatures.valence;
this.spotifyFeatures.tempo = trackFeatures.tempo;
this.spotifyFeatures.popularity = trackFeatures.popularity;
}
getMood() {
return this.mood;
}
getSpotifyFeatures() {
return this.spotifyFeatures;
}
}
<file_sep>/client/src/app/services/recommendation-parameter.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { RecommendationParameterService as RecommendationParameterService } from './recommendation-parameter.service';
describe('RecommendationParameterService', () => {
let service: RecommendationParameterService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(RecommendationParameterService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>/client/src/app/tabs/tabs.page.ts
import { LogoutService } from './../services/logout.service';
import { SharedParamsService } from './../services/shared-params.service';
import { MoodGuardService } from './../services/mood-guard.service';
import { Component } from '@angular/core';
import { NavController, AlertController } from '@ionic/angular';
@Component({
selector: 'app-tabs',
templateUrl: 'tabs.page.html',
styleUrls: ['tabs.page.scss']
})
export class TabsPage {
splashPortrait = false;
splashLandscape = false;
width: number;
height: number;
i: number;
constructor(private shared: SharedParamsService, private logoutService: LogoutService,
private navCtrl: NavController, private alertController: AlertController,
private moodGuard: MoodGuardService) {
if (this.moodGuard.checkMood()) {
if (window.location.href.includes('localhost')) {
window.location.href = 'http://localhost:8100/mood';
}
else {
window.location.href = 'https://moodify-spotify.web.app/mood';
}
} else {
if (!this.moodGuard.checkSameDay()) {
this.alertNewDay();
}
}
}
// change your starting and target mood function
goToMoodSet() {
this.logoutService.removeCurrentMood();
this.logoutService.removeTargetMood();
this.shared.setPreviousDay(this.shared.getExpirationToken());
this.navCtrl.navigateRoot('/mood');
}
/** ALERTS */
/* ALERT NEW DAY NEW MOOD */
async alertNewDay() {
const alert = await this.alertController.create({
header: 'Here you go again!',
cssClass: 'alertClassPrimary',
message: 'It seems it\'s a new day.<br/><br/>' +
'Are you still ' + this.shared.getCurrentMood().toUpperCase() + '<br/>' +
'and your target is ' + this.shared.getTargetMood().toUpperCase() + '?',
buttons: [
{
text: 'Change them!',
cssClass: 'alertMedium',
handler: () => {
this.goToMoodSet();
}
},
{
text: 'Keep them!',
cssClass: 'alertConfirm',
}
],
backdropDismiss: false
});
await alert.present();
}
}
<file_sep>/client/src/app/services/machineLearning.service.ts
import { TrackFeatures } from './../interfaces/TrackFeatures';
import { Double } from '../classes/Double';
import { AngularFirestore } from '@angular/fire/firestore';
import { Injectable } from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/database';
@Injectable({
providedIn: 'root'
})
export class MachineLearningService {
database = firebase.database();
bufferModelLength = 10;
bufferUserLength = 5;
constructor(private afs: AngularFirestore) {
}
// This function upload or update model data mood
trainModel(double: Double, startingMood: string) {
this.getModelData(startingMood, double.getMood()).then((featureStored) => {
let tempFeat: TrackFeatures;
let tempBufFeat: TrackFeatures;
const buff: { feat: TrackFeatures, numFeed: number } = { feat: double.spotifyFeatures, numFeed: 1 };
if (featureStored.buff !== null && featureStored.features !== null) {
buff.numFeed = featureStored.buff.numFeed + 1;
tempBufFeat = this.addToBuff(double, featureStored.buff.feat);
tempFeat = featureStored.features;
buff.feat = tempBufFeat;
if (buff.numFeed >= this.bufferModelLength) {
tempFeat = this.doMean(buff.feat, this.bufferModelLength);
buff.numFeed = 1;
buff.feat = tempFeat;
}
firebase.database().ref('model/' + startingMood + '/' + double.getMood()).update({
features: tempFeat,
buffer: buff
});
}
else {
firebase.database().ref('model/' + startingMood + '/' + double.getMood()).set({
features: double.spotifyFeatures,
buffer: buff
});
}
});
}
// This function upload or update user data mood
uploadPersonal(double: Double, id: string, startingMood: string, changeFeedback: boolean) {
this.getUserData(id, startingMood, double.getMood()).then((featureStored) => {
let tempFeat: TrackFeatures;
let tempBufFeat: TrackFeatures;
const buff: { feat: TrackFeatures, numFeed: number } = {
feat: double.spotifyFeatures,
numFeed: 1
};
if (featureStored.features !== null && featureStored.buff !== null) {
if (!changeFeedback) {
buff.numFeed = featureStored.buff.numFeed + 1;
}
else {
buff.numFeed = featureStored.buff.numFeed - 1;
}
tempBufFeat = this.addToBuff(double, featureStored.buff.feat);
tempFeat = featureStored.features;
buff.feat = tempBufFeat;
if (buff.numFeed >= this.bufferUserLength) {
tempFeat = this.doMean(buff.feat, this.bufferUserLength);
buff.numFeed = 1;
buff.feat = tempFeat;
}
if (buff.numFeed !== 0) {
firebase.database().ref('user/' + id + '/' + startingMood + '/' + double.getMood()).update({
features: tempFeat,
buffer: buff
});
}
}
else {
firebase.database().ref('user/' + id + '/' + startingMood + '/' + double.getMood()).set({
features: double.spotifyFeatures,
buffer: buff
});
}
});
}
// This function return model data table
async getModelData(startingMood: string, targetMood: string) {
const db = firebase.database();
const ref1 = db.ref('/model/' + startingMood + '/' + targetMood + '/features');
const ref2 = db.ref('/model/' + startingMood + '/' + targetMood + '/buffer');
const snapshot1 = await ref1.once('value');
const snapshot2 = await ref2.once('value');
const values: { features: TrackFeatures, buff: { feat: TrackFeatures, numFeed: number } } = {
features: snapshot1.val(),
buff: snapshot2.val()
}
if (values === null) {
return undefined;
}
else {
return values;
}
}
// This function return user data table
async getUserData(userID: string, startingMood: string, targetMood: string) {
const db = firebase.database();
const ref1 = db.ref('/user/' + userID + '/' + startingMood + '/' + targetMood + '/features');
const ref2 = db.ref('/user/' + userID + '/' + startingMood + '/' + targetMood + '/buffer');
const snapshot1 = await ref1.once('value');
const snapshot2 = await ref2.once('value');
const values: { features: TrackFeatures, buff: { feat: TrackFeatures, numFeed: number } } = {
features: snapshot1.val(),
buff: snapshot2.val()
}
if (values === null) {
return undefined;
}
else {
return values;
}
}
// This function tell if user exist
async getUser(userID: string) {
const db = firebase.database();
const ref = db.ref('/user/' + userID);
const snapshot = await ref.once('value');
const values = snapshot.val();
if (values === null) {
return undefined;
}
else {
return values;
}
}
// Round features to 3rd decimal number
private roundTo(value, places) {
const power = Math.pow(10, places);
return Math.round(value * power) / power;
}
private doMean(buffer: TrackFeatures, bufferLen: number) {
const MeanTrack: TrackFeatures = {
key: Math.round(buffer.key / bufferLen),
mode: Math.round(buffer.mode / bufferLen),
time_signature: Math.round(buffer.time_signature / bufferLen),
acousticness: this.roundTo((buffer.acousticness / bufferLen), 2),
danceability: this.roundTo((buffer.danceability / bufferLen), 2),
energy: this.roundTo((buffer.energy / bufferLen), 2),
instrumentalness: this.roundTo((buffer.instrumentalness / bufferLen), 2),
liveness: this.roundTo((buffer.liveness / bufferLen), 2),
loudness: this.roundTo((buffer.loudness / bufferLen), 2),
speechiness: this.roundTo((buffer.speechiness / bufferLen), 2),
valence: this.roundTo((buffer.valence / bufferLen), 2),
tempo: this.roundTo((buffer.tempo / bufferLen), 2),
popularity: Math.round(buffer.popularity / bufferLen),
}
return MeanTrack;
}
private addToBuff(double: Double, buffFeat: TrackFeatures) {
const Values: TrackFeatures = {
key: (double.spotifyFeatures.key + buffFeat.key),
mode: (double.spotifyFeatures.mode + buffFeat.mode),
time_signature: (double.spotifyFeatures.time_signature + buffFeat.time_signature),
acousticness: this.roundTo(((double.spotifyFeatures.acousticness + buffFeat.acousticness)), 5),
danceability: this.roundTo(((double.spotifyFeatures.danceability + buffFeat.danceability)), 5),
energy: this.roundTo(((double.spotifyFeatures.energy + buffFeat.energy)), 5),
instrumentalness: this.roundTo(((double.spotifyFeatures.instrumentalness + buffFeat.instrumentalness)), 5),
liveness: this.roundTo(((double.spotifyFeatures.liveness + buffFeat.liveness)), 5),
loudness: this.roundTo(((double.spotifyFeatures.loudness + buffFeat.loudness)), 5),
speechiness: this.roundTo(((double.spotifyFeatures.speechiness + buffFeat.speechiness)), 5),
valence: this.roundTo(((double.spotifyFeatures.valence + buffFeat.valence)), 5),
tempo: this.roundTo(((double.spotifyFeatures.tempo + buffFeat.tempo)), 5),
popularity: (double.spotifyFeatures.popularity + buffFeat.popularity),
}
return Values;
}
}
|
804c912f55959a6ee99c30f6a63192a1d0ad4e1b
|
[
"Markdown",
"TypeScript"
] | 28
|
TypeScript
|
ClaudioAmato/moodify-spotify
|
540e995d9849eb5b78a1be715f9b1ae7625dc6c5
|
049710e66bddf28bc7b21d7168c87d9d8d01fda6
|
refs/heads/master
|
<repo_name>wwarne/quest_scraping<file_sep>/svexitru/user_agents.py
user_agents = {
'chrome_windows': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/47.0.2526.73 Safari/537.36',
'chrome_linux': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/41.0.2227.0 Safari/537.36',
'chrome_macos': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/41.0.2227.1 Safari/537.36',
'firefox_windows': 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04',
'firefox_linux': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0',
'firefox_mac': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0',
'firefox_win10': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0',
'edge_windows': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240',
}
<file_sep>/grab_sv_exit.py
from svexitru.downloader import RequestDownloader
from svexitru.crawlers import SvExitCityCrawler, SvExitQuestCrawler
from svexitru.pipelines import SvExitCityPipeline, SvExitQuestPipeline
from svexitru.middleware import StatisticMiddleware, ErrorReportingMiddleware
from svexitru.models import SvExitCity, db_connect, create_svexit_tables
from sqlalchemy.orm import sessionmaker
from pomp.core.engine import Pomp
from datetime import datetime
start_time = datetime.now()
# Grab URLs of all cities
city_pomp = Pomp(
downloader=RequestDownloader(),
pipelines=[SvExitCityPipeline()]
)
city_pomp.pump(SvExitCityCrawler())
engine = db_connect()
# create_svexit_tables(engine)
Session = sessionmaker(bind=engine)
se = Session()
all_city_info = se.query(SvExitCity).all()
all_cities = [(city.id, city.url) for city in all_city_info]
dont_parse = [city.url for city in all_city_info]
se.close()
statistics = StatisticMiddleware()
quest_pomp = Pomp(
downloader=RequestDownloader(),
middlewares=[statistics, ErrorReportingMiddleware()],
pipelines=[SvExitQuestPipeline()]
)
for city_id, city_url in all_cities:
print('---Parsing {}---'.format(city_url))
quest_pomp.pump(SvExitQuestCrawler(
start_url=city_url,
city_id=city_id,
dont_parse_urls=dont_parse
))
print('------------------ Total time -------------')
t = datetime.now() - start_time
print('It has took {} seconds'.format(t.seconds))
print("Statistics: \n {}".format(statistics))
print('----------- RPS (Requests per second)--------')
print(statistics.requests / t.seconds)<file_sep>/phobiaru/models.py
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from phobiaru import db_settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database connection using settings from db_settings.py
:return: SQLAlchemy engine instance
"""
return create_engine(URL(**db_settings.DATABASE))
def create_phobia_tables(engine):
DeclarativeBase.metadata.create_all(engine)
# Create tables.
# Will not attempt to recreate tables already present in the target database.
class PhobiaCity(DeclarativeBase):
"""
SQLAlchemy PhobiaCity model
"""
__tablename__ = 'phobia_cities'
id = Column(Integer, primary_key=True)
name = Column('name', String)
url = Column('url', String)
crawled = Column('crawled', DateTime)
class PhobiaQuest(DeclarativeBase):
"""
SQLAlchemy PhobiaQuest model
"""
__tablename__ = 'phobia_quests'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('phobia_cities.id'))
city = relationship(PhobiaCity)
name = Column('name', String)
url = Column('url', String, unique=True)
min_age = Column('min_age', Integer, nullable=True)
address = Column('address', String, nullable=True)
phone = Column('phone', String, nullable=True)
min_players = Column('min_players', Integer, nullable=True)
max_players = Column('max_players', Integer, nullable=True)
time = Column('time', Integer, nullable=True)
description = Column('description', String, nullable=True)
crawled = Column('crawled', DateTime)
status = Column('status', String, nullable=True)
images = relationship('PhobiaQuestImage', back_populates='quest', cascade='all, delete-orphan')
age_with_parents = Column('age_with_parents', Integer)
address_notes = Column('address_notes', String)
email = Column('email', String)
class PhobiaQuestImage(DeclarativeBase):
"""
SQLAlchemy PhobiaQuestImage model
"""
__tablename__ = 'phobia_images'
id = Column(Integer, primary_key=True)
url = Column('url', String)
quest_id = Column(Integer, ForeignKey('phobia_quests.id', ondelete='CASCADE'))
quest = relationship('PhobiaQuest', back_populates='images')
<file_sep>/svexitru/models.py
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from svexitru import db_settings
DeclarativeBase = declarative_base()
def db_connect():
"""
Performs database connection using settings from db_settings.py
:return: SQLAlchemy engine instance
"""
return create_engine(URL(**db_settings.DATABASE))
def create_svexit_tables(engine):
DeclarativeBase.metadata.create_all(engine)
# Create tables.
# Will not attempt to recreate tables already present in the target database.
class SvExitCity(DeclarativeBase):
"""
SQLAlchemy PhobiaCity model
"""
__tablename__ = 'sv_exit_cities'
id = Column(Integer, primary_key=True)
name = Column('name', String)
url = Column('url', String)
crawled = Column('crawled', DateTime)
class SvExitQuest(DeclarativeBase):
"""
SQLAlchemy PhobiaQuest model
"""
__tablename__ = 'sv_exit_quests'
id = Column(Integer, primary_key=True)
city_id = Column(Integer, ForeignKey('sv_exit_cities.id'))
city = relationship(SvExitCity)
name = Column('name', String)
url = Column('url', String, unique=True)
min_age = Column('min_age', Integer, nullable=True)
address = Column('address', String, nullable=True)
phone = Column('phone', String, nullable=True)
min_players = Column('min_players', Integer, nullable=True)
max_players = Column('max_players', Integer, nullable=True)
time = Column('time', Integer, nullable=True)
description = Column('description', String, nullable=True)
crawled = Column('crawled', DateTime)
status = Column('status', String, nullable=True)
images = relationship('SvExitQuestImage', back_populates='quest', cascade='all, delete-orphan')
class SvExitQuestImage(DeclarativeBase):
"""
SQLAlchemy PhobiaQuestImage model
"""
__tablename__ = 'sv_exit_images'
id = Column(Integer, primary_key=True)
url = Column('url', String)
quest_id = Column(Integer, ForeignKey('sv_exit_quests.id', ondelete='CASCADE'))
quest = relationship('SvExitQuest', back_populates='images')
<file_sep>/phobiaru/items.py
from datetime import datetime
from pomp.contrib.item import Item, Field
class PhobiaQuestItem(Item):
"""
A model used by crawler
"""
city = Field()
name = Field()
url = Field()
min_age = Field()
address = Field()
phone = Field()
min_players = Field()
max_players = Field()
time = Field()
description = Field()
crawled = Field()
status = Field()
images = Field()
age_with_parents = Field()
address_notes = Field()
email = Field()
def __init__(self):
super().__init__()
if not self.crawled:
self.crawled = datetime.now()
def __str__(self):
return 'QuestItem from {url}. ' \
'Photos: {ph_count}'.format(url=self.url,
ph_count=len(self.images) if self.images else 'N/A')
class PhobiaCityItem(Item):
name = Field()
url = Field()
crawled = Field()
def __str__(self):
return 'City from {}'.format(self.url)
<file_sep>/svexitru/downloader.py
# downloader fetching data by requests package.
import random
import requests as requestlib
from pomp.core.base import BaseHttpRequest, BaseHttpResponse, BaseDownloader, BaseCrawlException
from .user_agents import user_agents
class ReqRequest(BaseHttpRequest):
def __init__(self, url):
self.url = url
class ReqResponse(BaseHttpResponse):
def __init__(self, req, resp):
self.req = req
if not isinstance(resp, Exception):
self.content = resp.content
self.status_code = resp.status_code
self.headers = resp.headers
@property
def request(self):
return self.req
class RequestDownloader(BaseDownloader):
# Share Session between get calls.
_connection_session = None
@property
def session(self):
if self._connection_session is None:
self._connection_session = requestlib.Session()
return self._connection_session
def get(self, requests):
responses = []
for request in requests:
response = self._fetch(request)
responses.append(response)
return responses
def _fetch(self, request):
agent = random.choice(list(user_agents.values()))
headers = {'user-agent': agent}
if isinstance(request, str):
request = ReqRequest(request)
try:
res = self.session.get(request.url, headers=headers, timeout=5)
if res.status_code == 200:
return ReqResponse(request, res)
elif res.status_code in (401, 403):
return BaseCrawlException(request,
exception=Exception(
'Access forbidden to site {} ({})'.format(request.url,
res.status_code)))
elif 400 <= res.status_code < 500:
return BaseCrawlException(request,
exception=Exception(
'Assuming unrestricted access {} ({})'.format(request.url,
res.status_code)))
elif res.status_code >= 500:
return BaseCrawlException(request,
exception=Exception(
'Remote server returned ServerError {} ({})'.format(request.url,
res.status_code)))
else:
return BaseCrawlException(request,
exception=Exception(
'Remote server returned status {} ({})'.format(request.url,
res.status_code)))
except Exception as e:
return BaseCrawlException(request, exception=e)
<file_sep>/svexitru/middleware.py
from pomp.core.base import BaseMiddleware
class StatisticMiddleware(BaseMiddleware):
def __init__(self):
self.requests = self.responses = self.exceptions = 0
def process_request(self, request, crawler, downloader):
self.requests += 1
return request
def process_response(self, response, crawler, downloader):
self.responses += 1
return response
def process_exception(self, exception, crawler, downloader):
self.exceptions += 1
return exception
def __str__(self):
return 'requests/responses/exceptions ' \
'= {s.requests}/{s.responses}/{s.exceptions}' \
.format(s=self)
class ErrorReportingMiddleware(BaseMiddleware):
def process_exception(self, exception, crawler, downloader):
# exception is a BaseCrawlerExceprion(Request, exception)
# so exception.exception.args[0] - it's a text from exception
print(exception.exception.args[0])
return exception
<file_sep>/svexitru/pipelines.py
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
from .models import SvExitCity, SvExitQuest, SvExitQuestImage, db_connect, create_svexit_tables
from pomp.core.base import BasePipeline
class SvExitCityPipeline(BasePipeline):
"""
Pipeline for storing scraped city items in the database
"""
Session = None
def start(self, crawler):
engine = db_connect()
create_svexit_tables(engine)
self.Session = sessionmaker(bind=engine)
def process(self, crawler, item):
session = self.Session()
# Check is it Quest or QuestImage
try:
city_in_base = session.query(SvExitCity).filter(SvExitCity.url == item.url).one()
except NoResultFound:
city_in_base = SvExitCity()
city_in_base.name = item.name
city_in_base.url = item.url
city_in_base.crawled = item.crawled
try:
session.add(city_in_base)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
def stop(self, crawler):
print('Stop called')
class SvExitQuestPipeline(BasePipeline):
Session = None
def start(self, crawler):
engine = db_connect()
create_svexit_tables(engine)
self.Session = sessionmaker(bind=engine)
def process(self, crawler, item):
"""
Check every element for existence in DB before saving.
If an element exist - update its properties.
"""
session = self.Session()
try:
quest_in_base = session.query(SvExitQuest).filter(SvExitQuest.url == item.url).one()
except NoResultFound:
quest_in_base = SvExitQuest()
quest_in_base.url = item.url
quest_in_base.city_id = item.city_id
quest_in_base.name = item.name
quest_in_base.min_age = item.min_age or 0
quest_in_base.address = item.address
quest_in_base.phone = item.phone
quest_in_base.min_players = item.min_players or 0
quest_in_base.max_players = item.max_players or 0
quest_in_base.time = item.time or 0
quest_in_base.description = item.description
quest_in_base.crawled = item.crawled
quest_in_base.status = item.status
try:
session.add(quest_in_base)
session.commit()
except:
session.rollback()
session.close()
raise
if item.images:
for image in item.images:
instance = session.query(SvExitQuestImage).filter_by(url=image, quest=quest_in_base).first()
if instance:
continue
else:
temp = SvExitQuestImage(
url=image,
quest=quest_in_base
)
try:
session.add(temp)
except:
session.rollback()
session.close()
raise
session.commit()
session.close()
print('Successfully added {}'.format(item))
def stop(self, crawler):
pass
<file_sep>/phobiaru/crawlers.py
from lxml import html
from pomp.core.base import BaseCrawler
from .items import PhobiaCityItem, PhobiaQuestItem
from .downloader import PhantomDownloader, PhantomRequest
from urllib.parse import urljoin
from datetime import datetime
import re
class PhobiaCityCrawler(BaseCrawler):
CITY_PATH = '//li[contains(concat(" ", @class, " "), " city ")]/a'
ENTRY_REQUESTS = PhantomRequest('http://phobia.ru/cities/')
def extract_items(self, response):
tree = html.fromstring(response.content)
for city in tree.xpath(self.CITY_PATH):
city_item = PhobiaCityItem()
city_item.name = ''.join(city.xpath('text()'))
partial_url = ''.join(city.xpath('@href'))
city_item.url = urljoin(response.req.url, partial_url)
city_item.crawled = datetime.now()
yield city_item
class PhobiaQuestCrawler(BaseCrawler):
# на титульной странице города
# выбираем все квесты, которые работают! (В разработке не берём)
# те, которые работают имеют класс enabled
ALL_QUESTS_IN_CITY = '//*[@id="quests_tab"]/div/div[contains(@class, "enabled")]'
ALL_QUEST_SITE_VER2 = './/div[@class="quest"]//div[@class="right_side"]/a'
ALL_QUEST_SITE_VER3 = './/div[@class="quest_list"]//div[@class="right_side"]/a'
# на странице с квестом
QUEST_NAME = '//*[@id="qi-name"]/text()'
QUEST_GAMERS = '//*[@id="qi-gamers"]/text()'
QUEST_TIME = '//*[@id="qi-duration"]/text()'
QUEST_DESCRIPTION = '//*[@id="qi-description"]/text()'
QUEST_PHONE = '//*[@id="qi-phone"]/text()'
QUEST_EMAIL = '//*[@id="qi-email"]/a/text()'
QUEST_ADDRESS = '//*[@id="qi-address"]/text()'
QUEST_ADDRESS_NOTES = '//*[@id="qi-address-desc"]/text()'
QUEST_AGE = '//*[@id="qi-age"]/text()'
def __init__(self, start_url, city_id):
self.city = city_id
self.ENTRY_REQUESTS = PhantomRequest(start_url)
# превращает строку типа 'ш34л 4d' в список ['34', '4']
self.gamers = re.compile('(\d+)')
super().__init__()
def extract_items(self, response):
tree = html.fromstring(response.content)
quest_name = tree.xpath(self.QUEST_NAME)
all_q = tree.xpath(self.ALL_QUESTS_IN_CITY)
all_q_ver2 = tree.xpath(self.ALL_QUEST_SITE_VER2)
if quest_name:
quest = PhobiaQuestItem()
quest.time = ''.join(tree.xpath(self.QUEST_TIME)).strip()
if 'минут' in quest.time:
quest.time = quest.time.split(' ')[0]
try:
quest.time = int(quest.time)
except ValueError:
quest.time = 0
quest.name = ''.join(tree.xpath(self.QUEST_NAME))
quest.url = response.req.url
quest.address = ''.join(tree.xpath(self.QUEST_ADDRESS))
quest.address_notes = ''.join(tree.xpath(self.QUEST_ADDRESS_NOTES))
quest.city_id = self.city
quest.description = ''.join(tree.xpath(self.QUEST_DESCRIPTION)).strip()
quest.email = ''.join(tree.xpath(self.QUEST_EMAIL))
quest.phone = ''.join(tree.xpath(self.QUEST_PHONE))
# Количество игроков указано - строкой - от 2 до 4, к примеру. Поэтому выцепляем
# регуляркой цифры из этой строки
players = [int(num) for num in self.gamers.findall(''.join(tree.xpath(self.QUEST_GAMERS)))]
quest.min_players = players[0]
quest.max_players = players[-1]
# Возраст тоже пишется строкой -
# Минимальный возраст участников: от 8 лет с родителями, от 14 без
# Поэтому используя ту-же самую регулярку, выцепляю эти два возраста
ages = [int(age) for age in self.gamers.findall(''.join(tree.xpath(self.QUEST_AGE)))]
quest.age = max(ages)
quest.age_with_parents = min(ages)
# У квестов, которые в разработке даже нет страниц, так что
quest.status = True
if response.images:
quest.images = response.images
quest.crawled = datetime.now()
yield quest
# Если мы на титульной странице города
if all_q:
for one_quest in all_q:
_url = ''.join(one_quest.xpath('div[2]/h2/a/@href'))
next_url = urljoin(response.req.url, _url)
yield PhantomRequest(url=next_url)
if all_q_ver2:
# Второй вариант главной страницы сайта
for one_quest in all_q_ver2:
_url = ''.join(one_quest.xpath('@href'))
next_url = urljoin(response.req.url, _url)
yield PhantomRequest(url=next_url)
if not quest_name and not all_q and not all_q_ver2:
all_q_ver3 = tree.xpath(self.ALL_QUEST_SITE_VER3)
if all_q_ver3:
# Третий вариант главной страницы сайта
for one_quest in all_q_ver3:
_url = ''.join(one_quest.xpath('@href'))
next_url = urljoin(response.req.url, _url)
yield PhantomRequest(url=next_url)
else:
print('Unknown page on {}'.format(response.req.url))
<file_sep>/phobiaru/pipelines.py
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
from .models import PhobiaCity, PhobiaQuest, PhobiaQuestImage, db_connect, create_phobia_tables
from pomp.core.base import BasePipeline
class PhobiaCityPipeline(BasePipeline):
Session = None
def start(self, crawler):
engine = db_connect()
create_phobia_tables(engine)
self.Session = sessionmaker(bind=engine)
def process(self, crawler, item):
session = self.Session()
try:
city_in_base = session.query(PhobiaCity).filter(PhobiaCity.url == item.url).one()
except NoResultFound:
city_in_base = PhobiaCity()
city_in_base.name = item.name
city_in_base.url = item.url
city_in_base.crawled = item.crawled
try:
session.add(city_in_base)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
class PhobiaQuestPipeline(BasePipeline):
Session = None
def start(self, crawler):
engine = db_connect()
create_phobia_tables(engine)
self.Session = sessionmaker(bind=engine)
def process(self, crawler, item):
session = self.Session()
try:
quest_in_base = session.query(PhobiaQuest).filter(PhobiaQuest.url == item.url).one()
except NoResultFound:
quest_in_base = PhobiaQuest()
quest_in_base.url = item.url
quest_in_base.city_id = item.city_id
quest_in_base.name = item.name
quest_in_base.min_age = item.min_age or 0
quest_in_base.address = item.address
quest_in_base.phone = item.phone
quest_in_base.min_players = item.min_players or 0
quest_in_base.max_players = item.max_players or 0
quest_in_base.time = item.time or 0
quest_in_base.description = item.description
quest_in_base.crawled = item.crawled
quest_in_base.status = item.status
quest_in_base.age_with_parents = item.age_with_parents or 0
quest_in_base.address_notes = item.address_notes
quest_in_base.email = item.email
try:
session.add(quest_in_base)
session.commit()
except:
session.rollback()
session.close()
raise
if item.images:
for image in item.images:
try:
image_in_base = session.query(PhobiaQuestImage).filter_by(url=image, quest=quest_in_base).one()
except NoResultFound:
image_in_base = PhobiaQuestImage()
image_in_base.url = image
image_in_base.quest = quest_in_base
session.add(image_in_base)
try:
session.commit()
except:
session.rollback()
session.close()
raise
session.close()
print('Successfully added {s} ({s.name})'.format(s=item))
<file_sep>/svexitru/crawlers.py
from lxml import html
from pomp.core.base import BaseCrawler
from svexitru.items import SvExitCityItem, SvExitQuestItem
from svexitru.downloader import ReqRequest
from urllib.parse import urljoin
from datetime import datetime
class SvExitCityCrawler(BaseCrawler):
"""
Example of city html element
<a id="bx_3094277961_2876" href="http://abakan.sv-exit.ru/">
<span class="name">Абакан</span>
2 КВЕСТА, 0 В РАЗРАБОТКЕ
</a>
"""
ENTRY_REQUESTS = ['http://msk.sv-exit.ru/']
SVEXIT_TOWNS_XPATH = '//ul[@class="town"]/li/a'
def extract_items(self, response):
if response.status_code == 200:
converted = response.content.decode('utf-8')
tree = html.fromstring(converted)
for city in tree.xpath(self.SVEXIT_TOWNS_XPATH):
item = SvExitCityItem()
item.name = ''.join(city.xpath('span/text()'))
item.url = ''.join(city.xpath('@href'))
if not item.url:
item.url = response.request.url
item.crawled = datetime.now()
yield item
else:
print('Error on page {}, status code {}'.format(response.req.url, response.status_code))
class SvExitQuestCrawler(BaseCrawler):
# xpath for city main page
ALL_QUESTS_IN_CITY = './/*[@id="quests"]/div[2]/a'
# xpaths for retrieve one quest information
QUEST_NAME = './/body/div[2]/div/div[1]/h1/text()'
QUEST_MIN_AGE = '//span[@class="age_max_big"]/text()'
QUEST_ADDRESS = '/tr[1]/td[2]/div[@class="name"]/text()'
QUEST_PHONE = '//span[@class="phone"]/text()'
QUEST_MIN_PLAYERS = './/*[@id="mincountplayer"]/text()'
QUEST_MAX_PLAYERS = './/*[@id="maxcountplayer"]/text()'
QUEST_TIME = './/div[@class="name"]/text()'
QUEST_DESCRIPTION = './/*[@id="scrollbar2"]/div[1]/div/text()'
QUEST_IMAGES = './/body/div[2]/div/div[2]/div/img/@src'
QUEST_STATUS = '//span[contains(concat(" ", @class , " "), " time ")]'
def __init__(self, start_url, dont_parse_urls, city_id):
"""
:param start_url: The city's main page
:param dont_parse_urls: A list of all cities main pages. For example - on Moscow page there is a
link 'Quests in Balashikha'. It is decorated like a normal link to a quest.
So if we found a link to a different city in a quest's link area - we'll ignore it.
:param city_id: An ID of the current city we parse. Without it it's impossible to save data
in database properly.
"""
self.city = city_id
self._parsed_urls = dont_parse_urls
self.ENTRY_REQUESTS = ReqRequest(start_url)
super().__init__()
def extract_items(self, response):
if response.status_code != 200:
print('Error on page {}, status code {}'.format(response.req.url, response.status_code))
return
converted = response.content.decode('utf-8')
tree = html.fromstring(converted)
quest_name = tree.xpath(self.QUEST_NAME)
all_q = tree.xpath(self.ALL_QUESTS_IN_CITY)
if all_q:
# we on the city's main page (with a list of quests in this city)
for one_link in all_q:
new_url = ''.join(one_link.xpath('@href'))
next_url = urljoin(response.req.url, new_url)
if next_url not in self._parsed_urls:
self._parsed_urls.append(next_url)
yield ReqRequest(next_url)
if quest_name:
# We are on Quest's single page
quest = SvExitQuestItem()
quest.city_id = self.city
quest.url = response.req.url
quest.name = ''.join(quest_name)
quest.min_age = ''.join(tree.xpath(self.QUEST_MIN_AGE))
# Sometimes there are few elements on a page that looks like an address.
# Usually the address is the longest one.
quest.address = ''
for addr in tree.xpath(self.QUEST_ADDRESS):
if len(addr.strip()) > len(quest.address):
quest.address = addr.strip()
quest.phone = ''.join(tree.xpath(self.QUEST_PHONE))
quest.min_players = ''.join(tree.xpath(self.QUEST_MIN_PLAYERS))
quest.max_players = ''.join(tree.xpath(self.QUEST_MAX_PLAYERS))
for item in tree.xpath(self.QUEST_TIME):
if 'МИНУТ' in item:
quest.time = item.split(' ')[0]
if quest.time is None:
quest.time = 0
quest.description = ''.join(tree.xpath(self.QUEST_DESCRIPTION)).strip()
quest.city = self.city
images_urls = tree.xpath(self.QUEST_IMAGES)
if images_urls:
quest.images = []
for image in images_urls:
quest.images.append(urljoin(quest.url, image))
if tree.xpath(self.QUEST_STATUS):
quest.status = False
# it's 'coming soon' quest
else:
quest.status = True
# it's an active quest
quest.crawled = datetime.now()
yield quest
if not all_q and not quest_name:
print('Unknown page on {}'.format(response.req.url))
<file_sep>/phobiaru/downloader.py
from pomp.core.base import BaseHttpRequest, BaseHttpResponse, BaseDownloadWorker, BaseCrawlException
from pomp.contrib.concurrenttools import ConcurrentDownloader
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time
class PhantomRequest(BaseHttpRequest):
def __init__(self, url):
self.url = url
self.driver_url = None
def __str__(self):
return '<{s.__class__.__name__} url: {s.url}> ' \
'wdriver: {s.driver_url}'.format(s=self)
class PhantomResponse(BaseHttpResponse):
def __init__(self, req, body, images=None):
self.req = req
self.content = body
if images:
self.images = images
@property
def request(self):
return self.req
class PhantomWorker(BaseDownloadWorker):
def __init__(self):
self.pid = 'windows'
# on linux
# self.pid = os.getpid()
def get_one(self, request):
# attach webdriver to already started phantomjs node
user_agent = (
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/39.0.2171.95 Safari/537.36'
)
dcap = DesiredCapabilities.PHANTOMJS.copy()
dcap['phantomjs.page.settings.userAgent'] = user_agent
driver = webdriver.Remote(
command_executor=request.driver_url,
desired_capabilities=dcap,
)
driver.get(request.url)
# wait untill JS renders the page
try:
WebDriverWait(driver, 10).until(
expected_conditions.presence_of_element_located(
(By.XPATH, './/*[@id="footer"]')
)
)
except TimeoutException:
print(request.url + ' не загрузился')
return BaseCrawlException(request=request, exception=TimeoutException)
image_elements = []
try:
# Этот элемент появляется на иностранных сайтах, и на некоторых русских.
# Берлин, Дубай, Минск, Майами, Самара, Саратов, Чебоксары
element = driver.find_element_by_xpath('.//*[@id="lang_select"]')
if element:
opt_ru, opt_en = None, None
for option in element.find_elements_by_tag_name('option'):
if option.text == 'Ru':
opt_ru = option
elif option.text == 'En':
opt_en = option
if opt_ru:
opt_ru.click()
time.sleep(3)
elif opt_en:
opt_en.click()
time.sleep(3)
# if element:
# select = Select(element)
# select.deselect_all()
# select.select_by_visible_text('En')
# select.deselect_all()
# select.select_by_visible_text('Ru')
except NoSuchElementException:
pass
try:
if driver.find_element_by_xpath('.//*[@id="quest-image"]'):
current_image = 'n/a'
while current_image not in image_elements:
""" Картинки на сайте переключаются нажатием на картинку стрелочки.
через JS изменяется стиль элемента - меняется адрес картинки.
Перебираем картинки и записываем их в list до тех пор, пока не начнут повторяться.
И заодно обрезаем слева текст `background-image: url(` и справа `);`
"""
current_image = driver.find_element_by_xpath('.//*[@id="quest-image"]').get_attribute('style')[22:][:-2]
image_elements.append(current_image)
driver.find_element_by_xpath('.//*[@id="next_img"]').click()
driver.implicitly_wait(4)
# time.sleep(1)
current_image = driver.find_element_by_xpath('.//*[@id="quest-image"]').get_attribute('style')[22:][:-2]
except NoSuchElementException:
pass
# finish - get current document body
body = driver.execute_script('return document.documentElement.outerHTML;')
return PhantomResponse(request, body, image_elements)
class PhantomDownloader(ConcurrentDownloader):
def __init__(self, phantom_drivers, *args, **kwargs):
self.drivers = phantom_drivers
super().__init__(*args, **kwargs)
def prepare(self, *args, **kwargs):
super().prepare(*args, **kwargs)
def get(self, requests):
# associate each request with phantomjs node
def _associate_driver_url(request):
request.driver_url = self.drivers[0].command_executor._url
self.drivers.rotate(1)
return request
return super().get(
map(_associate_driver_url, requests)
)
def stop(self):
super().stop()
# for driver in self.drivers:
# driver.close()
# driver.quit()
# for linux
# pid = driver.service.process.pid
# HACK - phantomjs does not exited after close and quit
# try:
# os.kill(pid, signal.SIGTERM)
# except ProcessLookupError:
# pass
<file_sep>/grab_phobia.py
from phobiaru.downloader import PhantomDownloader, PhantomWorker
from phobiaru.crawlers import PhobiaCityCrawler, PhobiaQuestCrawler
from phobiaru.pipelines import PhobiaCityPipeline, PhobiaQuestPipeline
from phobiaru.middleware import StatisticMiddleware
from phobiaru.models import PhobiaCity, db_connect
from sqlalchemy.orm import sessionmaker
from pomp.core.engine import Pomp
from datetime import datetime
from collections import deque
from selenium import webdriver
# On windows the subprocesses will import (i.e. execute) the main module at start.
# so we need to protect the main code with 'if __name__ == '__main__':'
# to avoid creating subprocesses recursively:
if __name__ == '__main__':
pool_size = 2
start_time = datetime.now()
# start phantomjs nodes
ph_drivers = deque(
[
webdriver.PhantomJS() for _ in range(pool_size)
]
)
# Grab URLs of all cities
city_pomp = Pomp(
downloader=PhantomDownloader(
pool_size=2,
worker_class=PhantomWorker,
phantom_drivers=ph_drivers,
),
pipelines=[PhobiaCityPipeline()]
)
city_pomp.pump(PhobiaCityCrawler())
engine = db_connect()
Session = sessionmaker(bind=engine)
se = Session()
all_cities = [(city.id, city.url) for city in se.query(PhobiaCity).all()]
se.close()
statistics = StatisticMiddleware()
for city_id, city_url in all_cities:
quest_pomp = Pomp(
downloader=PhantomDownloader(
pool_size=2,
worker_class=PhantomWorker,
phantom_drivers=ph_drivers,
),
middlewares=[statistics],
pipelines=[PhobiaQuestPipeline()]
)
print('--- Parsing {} ---'.format(city_url))
quest_pomp.pump(PhobiaQuestCrawler(
start_url=city_url,
city_id=city_id
))
print('------------------ Total time -------------')
t = datetime.now() - start_time
print('It has took {} seconds'.format(t.seconds))
print("Statistics: \n {}".format(statistics))
print('----------- RPS (Requests per second)--------')
print(statistics.requests / t.seconds)
for driver in ph_drivers:
driver.close()
driver.quit()
|
467cd053e32edfe3d8bf28990fca729416766896
|
[
"Python"
] | 13
|
Python
|
wwarne/quest_scraping
|
62124e53b2abb01dc77f55f1c269ef2d36ab9b66
|
f294a57febe0563a97bb3c1b2f61cef7651e833a
|
refs/heads/master
|
<file_sep>#!/bin/sh
cd ../qpf/build
node r.js -o config.js
cp ../dist/qpf.js ../../epage/static/lib/qpf.js
cp ../src/style/base.less ../../epage/static/style/qpf/base.less
# cp -r ../src/components/less/images ../../emage/example/static/style/qpf/images<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var Meta = qpf.use("meta/meta");
var command = require("core/command");
var contextMenu = require("modules/common/contextmenu");
var Viewport = Meta.derive(function(){
return {
scale : ko.observable(1.0)
}
}, {
type : 'VIEWPORT',
css : "viewport",
template : '<div class="qpf-viewport-elements-container"></div>\
<div class="qpf-viewport-ruler-h"></div>\
<div class="qpf-viewport-ruler-v"></div>',
initialize : function(){
this.scale.subscribe(this._scale, this);
this._scale(this.scale());
contextMenu.bindTo(this.$el, function(target){
var $epageEl = $(target).parents('.epage-element');
if($epageEl.length){
var items = [{
label : "删除",
exec : function(){
command.execute("remove", $epageEl.attr("data-epage-eid"));
}
}, {
label : "复制",
exec : function(){
command.execute("copy", $epageEl.attr("data-epage-eid"));
}
}];
}else{
var items = [];
}
items.push({
label : "粘贴",
exec : function(){
var els = command.execute("paste");
}
});
return items;
});
},
afterRender : function(){
this._$elementsContainer = this.$el.find(".qpf-viewport-elements-container");
},
addElement : function(el){
if(this._$elementsContainer){
this._$elementsContainer.append(el.$wrapper);
}
},
removeElement : function(el){
el.$wrapper.remove();
},
_scale : function(val){
this.$el.css({
"-webkit-transform" : "scale(" + val + "," + val +")",
"-moz-transform" : "scale(" + val + "," + val +")",
"-o-transform" : "scale(" + val + "," + val +")",
"transform" : "scale(" + val + "," + val +")"
});
}
})
Meta.provideBinding("viewport", Viewport);
return Viewport;
})<file_sep>define(function(require){
var factory = require("core/factory");
var ko = require("knockout");
var _ = require("_");
factory.register("image", {
type : "IMAGE",
extendProperties : function(){
return {
src : ko.observable("")
}
},
onCreate : function($wrapper){
var img = document.createElement("img");
var self = this;
var updateImageSize = _.debounce(function(width, height){
img.width = width;
img.height = height;
}, 1);
// Size of image;
ko.computed(function(){
var width = self.properties.width(),
height = self.properties.height();
if(img.src && img.complete){
updateImageSize(width, height);
}
});
ko.computed(function(){
img.onload = function(){
var width = img.width,
height = img.height;
self.properties.width(width);
self.properties.height(height);
img.onload = null;
}
img.src = self.properties.src();
});
// Border radius
ko.computed({
read : function(){
var br = self.uiConfig.borderRadius.items;
$(img).css({
'border-radius' : _.map(br, function(item){
return item.value() + "px"
}).join(" ")
})
}
});
$wrapper.append(img);
},
onExport : function(json){
json.properties.src = this.makeAsset("image", "src", json.properties.src, json.assets);
}
})
})<file_sep>define(function(require){
var factory = require("core/factory");
var ko = require("knockout");
var onecolor = require("onecolor");
factory.register("text", {
type : "TEXT",
extendProperties : function(){
return {
text : ko.observable("请输入文字"),
fontFamily : ko.observable("黑体, SimHei"),
fontSize : ko.observable(16),
color : ko.observable(0x000000),
horzontalAlign : ko.observable('center'),
verticleAlign : ko.observable('middle'),
lineHeight : ko.observable(0)
}
},
extendUIConfig : function(){
return {
text : {
label : "文本",
ui : "textfield",
text : this.properties.text
},
fontFamily : {
label : "字体",
ui : "combobox",
class : "small",
items : [
{ text:'宋体',value:'宋体,SimSun'},
{ text:'微软雅黑',value:'微软雅黑,Microsoft YaHei'},
{ text:'楷体',value:'楷体,楷体_GB2312, SimKai'},
{ text:'黑体',value:'黑体, SimHei'},
{ text:'隶书',value:'隶书, SimLi'},
{ text:'Andale Mono',value:'andale mono'},
{ text:'Arial',value:'arial, helvetica,sans-serif'},
{ text:'Arial Black',value:'arial black,avant garde'},
{ text:'Comic Sans Ms',value:'comic sans ms'},
{ text:'Impact',value:'impact,chicago'},
{ text:'Times New Roman',value:'times new roman'}
],
value : this.properties.fontFamily
},
fontSize : {
label : "大小",
ui : "spinner",
value : this.properties.fontSize
},
color : {
label : "颜色",
ui : "color",
color : this.properties.color
},
horzontalAlign : {
label : "水平对齐",
ui : "combobox",
class : "small",
items : [{
value : 'left',
text : "左对齐"
}, {
value : 'center',
text : "居中"
}, {
value : 'right',
text : "右对齐"
}],
value : this.properties.horzontalAlign
},
verticleAlign : {
label : "垂直对齐",
ui : "combobox",
class : "small",
items : [{
value : 'top',
text : "顶部对齐"
}, {
value : 'middle',
text : "居中"
}, {
value : 'bottom',
text : "底部对齐"
}],
value : this.properties.verticleAlign
},
lineHeight : {
label : "行高",
ui : "spinner",
min : 0,
value : this.properties.lineHeight
}
}
},
onCreate : function($wrapper){
var $text = $("<span style='line-height:normal;display:inline-block;vertical-align:middle;width:100%;'></span>");
var self = this;
$wrapper.append($text);
//Font family
ko.computed(function(){
var fontFamily = self.properties.fontFamily();
$text.css({
'font-family' : fontFamily
})
})
//Font size and text color
ko.computed(function(){
var text = self.properties.text();
var fontSize = self.properties.fontSize()+"px";
var color = onecolor(self.properties.color()).css();
$text.html(text)
.css({
"font-size" : fontSize,
"color" : color
})
});
//Text align
ko.computed(function(){
var verticleAlign = self.properties.verticleAlign();
var horzontalAlign = self.properties.horzontalAlign();
$text.css({
'text-align' : horzontalAlign,
'vertical-align' : verticleAlign
})
});
//Line height
ko.computed(function(){
var lineHeight = self.properties.lineHeight();
if(lineHeight){
$text.css({
'line-height' : lineHeight + 'px'
})
}
});
ko.computed(function(){
var height = self.properties.height();
if(height){
$wrapper.css({
'line-height' : height + 'px'
})
}
})
}
});
})<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var $ = require("$");
var _ = require("_");
var onecolor = require("onecolor");
var koMapping = require("ko.mapping");
var command = require("./command");
var Draggable = qpf.mixin.Draggable;
var Element = qpf.core.Clazz.derive(function(){
var hasBackground = ko.observable(false);
var isBackgroundImageGradient = ko.computed({
read : function(){
return hasBackground() &&
ret.properties.backgroundImageType() === 'gradient'
},
deferEvaluation : true
});
var isBackgroundImageFile = ko.computed({
read : function(){
return hasBackground() &&
ret.properties.backgroundImageType() === 'file'
}
})
var ret = {
name : "",
icon : "",
eid : genEID(),
$wrapper : $('<div></div>'),
type : "ELEMENT",
// Properties view model
properties : {
id : ko.observable(""),
width : ko.observable(100),
height : ko.observable(100),
left : ko.observable(0),
top : ko.observable(0),
zIndex : ko.observable(0),
//-------------------
// Background
background : hasBackground,
backgroundColor : ko.observable(0xffffff),
backgroundImageType : ko.observable("none"),
backgroundGradientStops : ko.observableArray([{
percent : ko.observable(0),
color : ko.observable('rgba(255, 255, 255, 1)')
}, {
percent : ko.observable(1),
color : ko.observable('rgba(0, 0, 0, 1)')
}]),
backgroundGradientAngle : ko.observable(180),
//-------------------
// Border radius
borderTopLeftRadius : ko.observable(0),
borderTopRightRadius : ko.observable(0),
borderBottomRightRadius : ko.observable(0),
borderBottomLeftRadius : ko.observable(0),
//-------------------
// Shadow
hasShadow : ko.observable(false),
shadowOffsetX : ko.observable(0),
shadowOffsetY : ko.observable(0),
shadowBlur : ko.observable(10),
shadowColor : ko.observable(0),
//-------------------
// Border
link : ko.observable("")
},
onResize : function(){},
onMove : function(){},
onCreate : function(){},
onRemove : function(){},
onExport : function(){},
onImport : function(){},
onOutput : function(){}
}
// UI Config for property Panel
var props = ret.properties;
ret.uiConfig = {
id : {
label : "id",
field : "style",
ui : "textfield",
text : props.id
},
position : {
label : "位置",
ui : "vector",
field : "layout",
items : [{
name : "left",
type : "spinner",
value : props.left,
precision : 0,
step : 1
},{
name : "top",
type : "spinner",
value : props.top,
precision : 0,
step : 1
}]
},
size : {
label : "宽高",
ui : "vector",
field : "layout",
items : [{
name : "width",
type : "spinner",
value : props.width,
precision : 0,
step : 1
}, {
name : "height",
type : "spinner",
value : props.height,
precision : 0,
step : 1
}],
// constrainProportion : ko.observable(true),
constrainType : "ratio"
},
zIndex : {
label : "Z",
ui : "spinner",
field : 'layout',
value : props.zIndex,
step : 1,
precision : 0
},
background : {
label : "背景",
ui : "checkbox",
field : "style",
checked : hasBackground
},
backgroundColor : {
label : "背景色",
ui : "color",
field : "style",
color : props.backgroundColor,
visible : hasBackground
},
backgroundImageType : {
label : "背景图片",
ui : "combobox",
class : "small",
field : "style",
items : [{
text : "无",
value : "none"
}, {
text : "渐变",
value : "gradient"
}, {
text : "图片文件",
value : "file"
}],
value : props.backgroundImageType,
visible : hasBackground
},
backgroundGradient : {
ui : "gradient",
field : "style",
stops : props.backgroundGradientStops,
angle : props.backgroundGradientAngle,
visible : isBackgroundImageGradient
},
borderRadius : {
label : "圆角",
ui : "vector",
field : "style",
items : [{
name : "top-left",
type : "slider",
value : props.borderTopLeftRadius,
precision : 0,
step : 1,
min : 0
}, {
name : "top-right",
type : "slider",
value : props.borderTopRightRadius,
precision : 0,
step : 1,
min : 0
}, {
name : "bottom-right",
type : "slider",
value : props.borderBottomRightRadius,
precision : 0,
step : 1,
min : 0
}, {
name : "bottom-left",
type : "slider",
value : props.borderBottomLeftRadius,
precision : 0,
step : 1,
min : 0
}],
constrainProportion : ko.observable(true)
},
shadow : {
label : "阴影",
ui : "checkbox",
field : "style",
checked : props.hasShadow
},
shadowSize : {
field : "style",
ui : "slider",
min : 1,
max : 100,
precision : 0,
value : props.shadowBlur,
visible : props.hasShadow
},
shadowOffset : {
ui : "vector",
field : "style",
items : [{
name : "shadowOffsetX",
type : "slider",
min : -100,
max : 100,
precision : 0,
value : props.shadowOffsetX
}, {
name : "shadowOffsetY",
type : "slider",
min : -100,
max : 100,
precision : 0,
value : props.shadowOffsetY
}],
visible : props.hasShadow
},
shadowColor : {
ui : "color",
field : "style",
color : props.shadowColor,
visible : props.hasShadow
},
link : {
label : "超链接",
ui : "textfield",
value : props.link
}
};
return ret;
}, {
initialize : function(config){
this.$wrapper.attr("data-epage-eid", this.eid);
var self = this,
properties = self.properties;
if(config){
if(config.extendProperties){
var extendedProps = config.extendProperties.call(this);
if(extendedProps){
_.extend(properties, extendedProps);
}
}
// Extend UI Config in the properties panel
if(config.extendUIConfig){
var extendedUIConfig = config.extendUIConfig.call(this);
if(extendedUIConfig){
_.extend(this.uiConfig, extendedUIConfig);
}
}
}
if(config){
_.extend(self, _.omit(config, "properties"));
}
var inCreate = true;
// Left and top
ko.computed({
read : function(){
var left = properties.left(),
top = properties.top();
self.$wrapper.css({
left : left + "px",
top : top + "px"
})
// Dont trigger the event when the element is initializing
if( ! inCreate){
self.onMove(left, top);
};
}
});
// Width and height
ko.computed({
read : function(){
var width = properties.width(),
height = properties.height();
self.resize(width, height);
if( ! inCreate){
self.onResize(width, height);
}
inCreate = false;
}
});
// Z Index
ko.computed({
read : function(){
self.$wrapper.css({
'z-index' : self.properties.zIndex()
})
}
});
// Border radius
ko.computed({
read : function(){
var br = self.uiConfig.borderRadius.items;
self.$wrapper.css({
'border-radius' : _.map(br, function(item){
return item.value() + "px"
}).join(" ")
})
}
});
// Background
ko.computed({
read : function(){
// If use background
var useBackground = self.properties.background();
var backgroundColor = self.properties.backgroundColor();
if(useBackground){
// Background color
self.$wrapper.css({
'background-color' : onecolor(backgroundColor).css()
});
// No background image
switch(self.properties.backgroundImageType()){
case "none":
self.$wrapper.css({
'background-image' : 'none'
});
break;
case 'gradient':
// Gradient background image
var stops = self.properties.backgroundGradientStops();
var angle = self.properties.backgroundGradientAngle();
var cssStr = 'linear-gradient(' + angle + 'deg, '+
_.map(stops, function(stop){
return onecolor(stop.color()).cssa()
+ ' '
+ Math.floor(stop.percent() * 100) + '%';
}).join(", ") + ')';
self.$wrapper.css({
'background-image' : '-webkit-' + cssStr,
'background-image' : '-moz-' + cssStr,
'background-image' : cssStr
});
break;
}
}else{
self.$wrapper.css({
'background' : 'none'
})
}
}
});
// Shadow
ko.computed({
read : function(){
var props = self.properties;
var shadowOffsetX = Math.floor(props.shadowOffsetX())+"px",
shadowOffsetY = Math.floor(props.shadowOffsetY())+"px",
shadowBlur = Math.floor(props.shadowBlur())+"px",
shadowColor = Math.floor(props.shadowColor());
if(shadowBlur && props.hasShadow()){
self.$wrapper.css({
'box-shadow' : [shadowOffsetX, shadowOffsetY, shadowBlur, onecolor(shadowColor).css()].join(' ')
})
}else{
self.$wrapper.css({
'box-shadow' : 'none'
})
}
}
})
this.$wrapper.css({
position : "absolute"
});
this.$wrapper.addClass("epage-element epage-" + this.type.toLowerCase());
this.onCreate(this.$wrapper);
if( ! this.properties.id()){
this.properties.id(genID(this.type))
}
},
syncPositionManually : function(){
var left = parseInt(this.$wrapper.css("left"));
var top = parseInt(this.$wrapper.css("top"));
this.properties.left(left);
this.properties.top(top);
},
resize : function(width, height){
this.$wrapper.width(width);
this.$wrapper.height(height);
},
rasterize : function(){},
export : function(){
var json = {
eid : this.eid,
type : this.type,
properties : koMapping.toJS(this.properties),
assets : {
// key is the image name
// value is the image base64 Url
images : {}
}
};
this.onExport(json);
return json;
},
import : function(json){
koMapping.fromJS(json.properties, {}, this.properties);
delete this.properties['__ko_mapping__'];
this.onImport(json);
},
makeAsset : function(type, name, data, root){
var globalName = this.eid + "#" + name;
if( ! root[type]){
root[type] = {};
}
root[type][globalName] = {
data : data,
type : type
};
return "url(" + type + "/" + globalName + ")";
},
build : function(){}
});
var id = {};
function genID(type){
if(!id[type]){
id[type] = 0;
}
return type + "_" + id[type]++;
}
var eid = 1;
function genEID(){
return eid++;
}
return Element;
})<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var componentFactory = require("core/factory");
var command = require("core/command");
var Module = require("../module");
var xml = require("text!./hierarchy.xml");
var _ = require("_");
var propertyModule = require("../property/index");
var contextMenu = require("modules/common/contextmenu");
var ElementView = require("./element");
var hierarchy = new Module({
name : "hierarchy",
xml : xml,
// Elements data source
// {
// id : ko.observable(),
// target : Element
// }
elementsList : ko.observableArray([]),
// List of selected elements, support multiple select
selectedElements : ko.observableArray([]),
ElementView : ElementView,
_selectElements : function(data){
hierarchy.selectedElements(_.map(data, function(item){
return item.target;
}));
},
selectElementsByEID : function(eidList){
var elements = [];
_.each(eidList, function(eid){
var el = componentFactory.getByEID(eid);
if(el){
elements.push(el);
}
});
hierarchy.selectedElements(elements);
},
load : function(elementsList){
this.elementsList(_.map(elementsList, function(element){
return {
id : element.properties.id,
target : element
}
}));
_.each(elementsList, function(element){
hierarchy.trigger("create", element);
})
}
});
hierarchy.elements = ko.computed({
read : function(){
return _.map(hierarchy.elementsList(), function(item){
return item.target;
});
},
deferEvaluation : true
});
hierarchy.on("start", function(){
hierarchy.mainComponent.$el.delegate(".qpf-ui-element", "dblclick", function(e){
hierarchy.trigger("focus", $(this).qpf("get")[0].target());
});
contextMenu.bindTo(hierarchy.mainComponent.$el, function(target){
var $uiEl = $(target).parents(".qpf-ui-element");
if($uiEl.length){
return [{
label : "删除",
exec : function(){
command.execute("remove", $uiEl.qpf("get")[0].target());
}
}, {
label : "复制",
exec : function(){
command.execute("copy", $uiEl.qpf("get")[0].target());
}
}]
}else{
return [{
label : "粘贴",
exec : function(){
var els = command.execute("paste");
}
}]
}
});
});
ko.computed(function(){
var selectedElements = hierarchy.selectedElements();
element = selectedElements[selectedElements.length-1];
if(element){
propertyModule.showProperties(element.uiConfig);
}
hierarchy.trigger("select", selectedElements);
});
// Register commands
command.register("create", {
execute : function(name, properties){
var element = componentFactory.create(name, properties);
hierarchy.elementsList.push({
id : element.properties.id,
target : element
});
// Dispatch create event
hierarchy.trigger("create", element);
hierarchy.selectedElements([element]);
},
unexecute : function(name, properties){
}
});
command.register("remove", {
execute : function(element){
if( typeof(element) === "string"){
element = componentFactory.getByEID(element);
}
componentFactory.remove(element);
hierarchy.elementsList(_.filter(hierarchy.elementsList(), function(data){
return data.target !== element;
}));
hierarchy.selectedElements.remove(element);
propertyModule.showProperties([]);
hierarchy.trigger("remove", element);
},
unexecute : function(){
}
});
command.register("removeselected", {
execute : function(){
},
unexecute : function(){
}
})
var clipboard = [];
command.register("copy", {
execute : function(element){
if(typeof(element) === "string"){
element = componentFactory.getByEID(element);
}
clipboard = [element];
}
});
command.register("copyselected", {
execute : function(){
}
})
command.register("paste", {
execute : function(){
var res = [];
_.each(clipboard, function(item){
var el = componentFactory.clone(item);
hierarchy.elementsList.push({
target : el,
id : el.properties.id
});
hierarchy.trigger("create", el);
res.push(el);
});
hierarchy.selectedElements(res);
return res;
},
unexecute : function(){
}
});
return hierarchy;
})<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var Module = require("../module");
var xml = require("text!./component.xml");
var component = new Module({
name : "component",
xml : xml
});
return component;
})<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var Module = require("../module");
var Viewport = require("./viewport");
var xml = require("text!./viewport.xml");
var _ = require("_");
var command = require("core/command");
var hierarchy = require("modules/hierarchy/index");
var viewport = new Module({
name : "viewport",
xml : xml,
viewportWidth : ko.observable(960),
viewportHeight : ko.observable(600),
viewportScale : ko.observable(1)
});
// Control points of each direction
var resizeControls = {
// Top left
$tl : $('<div class="resize-control tl"></div>'),
// Top center
$tc : $('<div class="resize-control tc"></div>'),
// Top right
$tr : $('<div class="resize-control tr"></div>'),
// Left center
$lc : $('<div class="resize-control lc"></div>'),
// Right center
$rc : $('<div class="resize-control rc"></div>'),
// Bottom left
$bl : $('<div class="resize-control bl"></div>'),
// Bottom center
$bc : $('<div class="resize-control bc"></div>'),
// Bottom right
$br : $('<div class="resize-control br"></div>')
};
var $outline = $('<div class="element-select-outline"></div>');
$outline.append(resizeControls.$tl);
$outline.append(resizeControls.$tc);
$outline.append(resizeControls.$tr);
$outline.append(resizeControls.$lc);
$outline.append(resizeControls.$rc);
$outline.append(resizeControls.$bl);
$outline.append(resizeControls.$bc);
$outline.append(resizeControls.$br);
var _viewport;
viewport.on("start", function(){
_viewport = viewport.mainComponent.$el.find("#ViewportMain").qpf("get")[0];
viewport.$el.delegate('.epage-element', "click", selectElement);
initDragUpload();
});
function selectElement(e){
var eid = $(this).attr("data-epage-eid");
if(eid){
hierarchy.selectElementsByEID([eid]);
}
}
hierarchy.on("create", function(element){
_viewport.addElement(element);
});
hierarchy.on("remove", function(element){
_viewport.removeElement(element)
});
hierarchy.on("select", function(elements){
var lastElement = elements[elements.length-1];
if( ! lastElement){
return;
}
lastElement.$wrapper.append($outline);
draggable.clear();
_.each(elements, function(element){
draggable.add(element.$wrapper);
});
selectedElements = elements;
});
hierarchy.on("focus", function(element){
$('#Viewport').animate({
scrollTop : element.$wrapper.position().top - 50 + 'px',
scrollLeft : element.$wrapper.position().left - 50 + 'px'
}, 'fast')
});
var selectedElements = [];
var draggable = new qpf.mixin.Draggable();
// Update the position property manually
draggable.on("drag", function(){
_.each(selectedElements, function(element){
element.syncPositionManually();
})
})
// Drag upload
var imageReader = new FileReader();
function initDragUpload(){
viewport.mainComponent.$el[0].addEventListener("dragover", function(e){
e.stopPropagation();
e.preventDefault();
});
viewport.mainComponent.$el[0].addEventListener("drop", function(e){
e.stopPropagation();
e.preventDefault();
var file = e.dataTransfer.files[0];
if(file && file.type.match(/image/)){
imageReader.onload = function(e){
imageReader.onload = null;
command.execute("create", "image", {
src : e.target.result
})
}
imageReader.readAsDataURL(file);
}
});
}
return viewport;
})<file_sep>define(function(require){
var qpf = require("qpf");
var ko = require("knockout");
var Module = require("../module");
var xml = require("text!./property.xml");
var _ = require("_");
var PropertyItemView = require("./property");
var property = new Module({
name : "property",
xml : xml,
layoutProperties : ko.observableArray([]),
styleProperties : ko.observableArray([]),
customProperties : ko.observableArray([]),
showProperties : function(properties){
var layoutProperties = [];
var styleProperties = [];
var customProperties = [];
_.each(properties, function(property){
if(property.ui){
property.type = property.ui;
var config = _.omit(property, 'label', 'ui', 'field', 'visible');
var item = {
label : property.label,
config : ko.observable(config)
}
if(property.visible){
item.visible = property.visible;
}
switch(property.field){
case "layout":
layoutProperties.push(item);
break;
case "style":
styleProperties.push(item);
break;
default:
customProperties.push(item);
}
}
})
this.layoutProperties(layoutProperties);
this.styleProperties(styleProperties);
this.customProperties(customProperties);
},
PropertyItemView : PropertyItemView
});
return property;
});
|
0e638549ba646dae70721c56ddcdafac9103ec6f
|
[
"JavaScript",
"Shell"
] | 9
|
Shell
|
chalecao/epage
|
9e5449a37336117b556361da196da821e0654381
|
7d5eb6bc2450a2906f2a80c5479dfc0a54abc33e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.