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/main | <file_sep>let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
// Write your code below:
// Step 3. Create generateTarget() function
const generateTarget = () => {
return Math.floor(Math.random() * 10);
};
// This function returns a random integer between 0 and 9
// Step 8.2 Create alert() to tell user they are out of range
function alert(boolean) {
if (true) {
return 'Out of range! Please choose a number between 0-9.';
}
};
// Step 8.1 Create getAbsoluteDistance() function
const getAbsoluteDistance = (num1, num2) => {
return Math.abs(num1-num2)
}
// Step 4. Create a compareGuesses() function
const compareGuesses = (humanGuess, computerGuess, targetGuess) => {
if(humanGuess > 9 || humanGuess < 0) {
return alert(true); // if < 0 or > 9, out or range
}
else if (getAbsoluteDistance(targetGuess, humanGuess) <= getAbsoluteDistance(targetGuess, computerGuess)) {
return true; // if abs distance of human is smaller or tied, human wins
}
else {
return false; // if abs distance of computer is smaller, computer wins
}
};
// Step 5. Create an updateScore() function
function updateScore(champ) {
if (champ === 'human') {
humanScore++; // if human wins, add 1
}
else if (champ === 'computer') {
computerScore++; // if computer wins, add 1
}
else {
return 'Error! String should be \'human\' or \'computer\''; // Catch any errors
}
};
// Step 6 Create an advancedRound() function
const advanceRound = () => currentRoundNumber++;
/*
console.log(compareGuesses(4,1,2));
console.log(compareGuesses(17,8,6));
console.log(compareGuesses(5,9,3));
*/
| df45405654decc2d21655845a02c1a4e7720db5b | [
"JavaScript"
] | 1 | JavaScript | orlanerosette/number-guesser-starting | b8070dcc261813c4a062ad4ba5e7168053dbd1c4 | 7fa4aed0df989c59a07bfb993c1c16c8d74c4632 |
refs/heads/master | <repo_name>ashlyjustin/hackdUnhackd<file_sep>/user_login/forms.py
from django import forms
from user_login.models import UserProfile
from user_login.models import Skills
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model=User
fields = ('username','first_name','last_name','email','password')
class UserProfileForm(forms.ModelForm):
userpic = forms.ImageField(required=False)
class Meta():
model=UserProfile
fields = ('user_pic',)
class SkillForm(forms.ModelForm):
class Meta():
model = Skills
fields = '__all__'
<file_sep>/user_login/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class UserProfile(models.Model):
user_name = models.OneToOneField(User,on_delete=models.CASCADE)
user_pic = models.ImageField(upload_to='profile_pics')
# def __str__(self) :
# return self.User.user
class Skills(models.Model):
userName=models.ForeignKey(UserProfile,on_delete=models.CASCADE)
skill1=models.CharField(max_length=16)
skill2=models.CharField(max_length=16)
skill3=models.CharField(max_length=16)
extraSkills = models.CharField(max_length=264)
<file_sep>/client_login/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class UserProf(models.Model):
user_name = models.OneToOneField(User,on_delete=models.CASCADE)
# def __str__(self) :
# return self.User.user
class Job(models.Model):
userName=models.ForeignKey(UserProf,on_delete=models.CASCADE)
jobName=models.CharField(max_length=16)
jobDesc=models.CharField(max_length=16)
skillReq=models.CharField(max_length=16)
salary = models.CharField(max_length=10)
<file_sep>/user_login/views.py
from django.shortcuts import render
from . import forms
from user_login.forms import UserForm,UserProfileForm
from client_login.models import Job,UserProf
from user_login.models import UserProfile
from django.contrib.auth import views as auth_views
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
return render(request,'index.html')
def homepage(request):
return render(request,'index.html')
@login_required
def user_page(request):
allJobs = Job.objects.all()
allProf = UserProfile.objects.all()
context = {'allJobs':allJobs}
return render(request,'user_login/user.html',context)
def apply_page(request):
return render(request,'user_login/apply.html')
@login_required
def special(request):
return HttpResponse("Logged Out")
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data =request.POST)
# profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() :
# and profile_form.is_valid():
user = user_form.save()
user.set_password(<PASSWORD>)
user.save()
# profile = profile_form.save(commit=False)
# profile.user = user
# if'user_pic' in request.FILES:
# profile.user_pic=request.FILES['user_pic']
# profile.save()
registered=True
else:
print(user_form.errors)
else:
user_form=UserForm()
return render(request,'user_login/register.html',
{'user_form':user_form,
'registered':registered})
def user_login(request):
if request.method =='POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('user_login:user_page'))
else:
return HttpResponse("ACCOUNT NOT is_active")
else:
print("Tried Login and Failed")
print("Username:{} and password {}".format(username,password))
return HttpResponse("Invalid Login Details")
else:
return render(request,'user_login/login.html',{})
<file_sep>/client_login/forms.py
from django import forms
from client_login.models import UserProf
from client_login.models import Job
from django.contrib.auth.models import User
class ClientForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model=User
fields = ('username','first_name','last_name','email','password')
class ClientProfileForm(forms.ModelForm):
designation = forms.CharField(required=False)
class Meta():
model=UserProf
fields = ('designation',)
class JobForm(forms.ModelForm):
class Meta():
model = Job
fields = '__all__'
<file_sep>/user_login/urls.py
from django.conf.urls import url
from . import views
app_name = 'user_login'
urlpatterns =[
url(r'^register/$',views.register,name="register"),
url(r'^$',views.homepage,name="homepage"),
url(r'^user_login/$',views.user_login,name="user_login"),
url(r'^logout/$',views.user_logout,name="logout"),
url(r'^user/$',views.user_page,name="user_page"),
url(r'^user/$',views.apply_page,name="apply")
]<file_sep>/client_login/views.py
from django.shortcuts import render
from . import forms
from client_login.forms import ClientForm, ClientProfileForm
from django.contrib.auth import views as auth_views
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from user_login.models import Skills,UserProfile
from django.http import JsonResponse
# Create your views here.
def index(request):
return render(request,'index.html')
def homepage(request):
return render(request,'index.html')
@login_required
def user_page(request):
return render(request,'client_login/client.html')
@login_required
def special(request):
return HttpResponse("Logged Out")
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
def register(request):
registered = False
if request.method == "POST":
user_form = ClientForm(data =request.POST)
# profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() :
# and profile_form.is_valid():
user = user_form.save()
user.set_password(<PASSWORD>)
user.save()
# profile = profile_form.save(commit=False)
# profile.user = user
# if'user_pic' in request.FILES:
# profile.user_pic=request.FILES['user_pic']
# profile.save()
registered=True
else:
print(user_form.errors)
else:
user_form=ClientForm()
return render(request,'client_login/register.html',
{'user_form':user_form,
'registered':registered})
def user_login(request):
if request.method =='POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('client_login:user_page'))
else:
return HttpResponse("ACCOUNT NOT is_active")
else:
print("Tried Login and Failed")
print("Username:{} and password {}".format(username,password))
return HttpResponse("Invalid Login Details")
else:
return render(request,'client_login/login.html',{})
def ItemApi(request):
UserSkill = Skills.objects.all()
skillsList = []
for obj in UserSkill:
tempData={
"id" : obj.userName,
"skill1": obj.skill1,
"skill2":obj.skill2,
"skill3":obj.skill3,
"extra":obj.extraSkills
}
skillsList.append(tempData)
data = {}
data['success']=True
data['item'] = skillsList
return JsonResponse(data,safe=False)
<file_sep>/user_login/migrations/0001_initial.py
# Generated by Django 2.1.dev20180309075957 on 2018-03-17 19:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Skills',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('skill1', models.CharField(max_length=16)),
('skill2', models.CharField(max_length=16)),
('skill3', models.CharField(max_length=16)),
('extraSkills', models.CharField(max_length=264)),
],
),
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_pic', models.ImageField(upload_to='profile_pics')),
('user_name', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='skills',
name='userName',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_login.UserProfile'),
),
]
<file_sep>/client_login/apps.py
from django.apps import AppConfig
class ClientLoginConfig(AppConfig):
name = 'client_login'
| ce63c6576e3a4c62f42a7a53bb336be1b27cf112 | [
"Python"
] | 9 | Python | ashlyjustin/hackdUnhackd | 4e0b04e4be5638a242f79337c9d590b31af0a100 | 9de5d1fc2a9ece5a2eab35816b3b41087ef04445 |
refs/heads/main | <repo_name>AngusZhu/flaskdemo<file_sep>/README.md
# flaskdemo
flask recognition aws lambda
| 36fb95fd21dbd5678d7f69e9107e8d01a7056d80 | [
"Markdown"
] | 1 | Markdown | AngusZhu/flaskdemo | 49eeaf87769c3eab6df24e32588c0d0c5cb40250 | f8513dd06799fba9b836a6f1e9ddc26faa8c14e5 |
refs/heads/master | <repo_name>n36kasai/processing-python-typingWar<file_sep>/client/client.pyde
add_library("sound")
bgImage = None
friendImage = None
friendCastleImage = None
testChar01 = None
testChar02 = None
testChar03 = None
typingMng = None
soundMusic = None
def setup():
size(1366, 768)
global bgImage, friendCastleImage
global testChar01, testChar02, testChar03
global typingMng
global soundMusic
bgImage = loadImage("typingWar_background.png")
friendCastleImage = loadImage("typingWar_friendCastle.png")
testChar01 = CharatorFriend(1366-64-100, 768-160, 2, "aquorsChika")
testChar02 = CharatorFriend(1366-64-200, 768-160, 1, "aquorsMari")
testChar03 = CharatorFriend(1366-64-300, 768-160, 2, "aquorsChika")
typingMng = TypingManager()
# soundMusic = SoundFile(this, "Battle-forHonor_SNES.mp3")
soundMusic = SoundFile(this, "bgm03.mp3")
soundMusic.amp(0.3)
soundMusic.loop()
soundMusic.jump(4.35)
def keyPressed():
global typingMng
typingMng.keyPressed()
def draw():
background(0)
image(bgImage, 0, 0)
image(friendCastleImage, 1366-80, 768-256+32)
testChar01.display()
testChar02.display()
testChar03.display()
typingMng.display()
square(200, 200, 80)
class TypingManager():
def __init__(self):
self.x = 400
self.y = 100
self.fontHeight = 48
self.font = createFont("UDDigiKyokashoNK-R", self.fontHeight)
# self.font = createFont("JF-Dot-Ayu-18", self.fontHeight)
self.mondai = []
self.yomi = []
self.romazi = []
self.mondaiNo = 0
self.mondaiMax = 0
self.soundEffect = SoundFile(this, "key04.mp3")
self.textReader = createReader("mondai.txt")
self.input = ""
self.kaitou = ""
self.kaitouPos = 0
textFont(self.font)
self.soundEffect.amp(1)
# 問題ファイルの読み込み
buf = ""
record = ""
while buf <> None:
buf = self.textReader.readLine()
if buf <> None:
record = split(buf, ",");
self.mondai.append(record[0])
self.yomi.append(record[1])
self.romazi.append(record[2])
self.mondaiMax += 1
# 1問目準備
self.kaitou = str(self.romazi[self.mondaiNo]) #キャストしないとUnicodeオブジェクトのままで厄介
def keyPressed(self):
self.soundEffect.stop()
self.soundEffect.play()
if key == ENTER:
self.input = "EnTeR"
self.mondaiNo += 1
if self.mondaiNo >= self.mondaiMax:
self.mondaiNo = 0
else:
# タイピング大戦争形式
# if key == self.kaitou[0]:
# if len(self.kaitou) == 1:
# self.mondaiNo += 1
# if self.mondaiNo >= self.mondaiMax:
# self.mondaiNo = 0
# self.kaitou = self.romazi[self.mondaiNo]
# else:
# self.kaitou = self.kaitou[1:len(self.kaitou)]
if key == self.kaitou[self.kaitouPos]:
if self.kaitouPos >= len(self.kaitou) - 1:
self.mondaiNo += 1
self.kaitouPos = 0
if self.mondaiNo >= self.mondaiMax:
self.mondaiNo = 0
self.kaitou = self.romazi[self.mondaiNo]
else:
self.kaitouPos += 1
# elif "a" <= key <= "z" or "A" <= key <= "Z" or key == " ":
# self.input = self.input + key
def display(self):
# 問題文
textSize(self.fontHeight)
fill(255)
text(self.mondai[self.mondaiNo], self.x, self.y)
# ひらがな
textSize(self.fontHeight - 30)
fill(200)
text(self.yomi[self.mondaiNo], self.x, self.y + 24)
# ローマ字
textSize(self.fontHeight)
fill(255)
text(self.romazi[self.mondaiNo], self.x, self.y + 64)
# 解答欄(タイピング大戦争形式)
# text(self.kaitou, self.x, self.y + 120)
text(self.kaitou, self.x, self.y + 120)
fill(255, 100, 100)
text(self.kaitou[0:self.kaitouPos], self.x, self.y + 120)
# デバッグ
fill(255)
text(key, self.x, self.y + 400)
class CharatorFriend:
def __init__(self, x, y, fr, fileName):
self.charImages = list()
self.posX = x
self.posY = y
self.posFrame = 0
self.maxFrame = fr
self.nFrame = 0
for i in range(1, self.maxFrame+1):
na = "aquorsChika0" + str(i) + ".png"
self.charImages.append(loadImage(na))
def display(self):
image(self.charImages[self.nFrame], self.posX, self.posY - self.nFrame * 4)
if frameCount % 30 == 0:
self.posX = self.posX - 3
if self.posX < 0:
self.posX = width
if self.nFrame >= self.maxFrame - 1:
self.nFrame = 0
else:
self.nFrame = self.nFrame + 1
| f2956c008d1574ddac5ca9be5707a0a5934d0582 | [
"Python"
] | 1 | Python | n36kasai/processing-python-typingWar | ae49ca98503aaa972785590048c0014e96b28ca7 | 51d89d6818cc153c265d547604dd17d0af09fcf0 |
refs/heads/master | <repo_name>susanacadenas81/gestorClientes<file_sep>/ajax/ejercicio1/servidorXml.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=tienda_online', 'root');
$productos = R::getAll('SELECT * FROM tabla_productos');
echo"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
echo"<productos>";
foreach ($productos as $value) {
echo "<producto>";
echo "<nombre>";
echo $value["nombre"];
echo"</nombre>";
echo"<precio>";
echo $value["precio"];
echo"</precio>";
echo"<descripcion>";
echo $value["descripcion"];
echo"</descripcion>";
echo "<id>";
echo $value["id"];
echo "</id>";
echo"</producto>";
}
echo"</productos>";
?><file_sep>/ajax/ejercicioViajes/servidor.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=ofertas_viajes', 'root');
$viajes = R::getAll('SELECT * FROM tabla_viajes2');
echo json_encode($viajes);
?><file_sep>/ajax/JQUERY/jqueryAjax/miscript.js
var intervalo = setInterval(()=>{
$.getJSON("servidor.php",{operacion:"listar"},function(res){
//console.log(res);
$("#listadoMensajes").html("");
for(r of res){
$("#listadoMensajes").append(r.nombre+": "+r.texto+"\n");
}
});
},100);
$("#botonEnvioMensaje").click(function(){
var nombre = $("#campoNombre").val();
var texto = $("#campoTexto").val();
//$("<p>tu mensaje se está enviando</p>").appendTo('#advertencia');
$.post("servidor.php",{
operacion: "registrar",
nombre:nombre,
texto:texto
},function(res){
alert("He recibido del servidor "+res);
//obtenerMensajes();
$("#campoTexto").val("");
});
//var texto = $("#campoTexto").val("");
});
//obtenerMensajes();<file_sep>/ajax/ejercicio4registroPOST/servidor.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=ejercicio_registro_equipo', 'root');
$nombre = $_POST["nombre"];
$edad = $_POST["edad"];
$direccion = $_POST["direccion"];
$telefono = $_POST["telefono"];
//una vez recogidos los datos que han llegado por ajax
//deberiamos validar en servidor dichos valores
//parte de validacion...
//una vez validado todo registramos en bd
$apuntado = R::dispense( "apuntados" );
$apuntado->nombre = $nombre;
$apuntado->edad = $edad;
$apuntado->direccion = $direccion;
$apuntado->telefono = $telefono;
R::store($apuntado);
echo "OK";
?><file_sep>/ajax/templates/scripts/modulos/listarProductos.js
define(["jquery","underscore","text!html/listadoProductos.html"],function($,_,htmlListadoProductos){
return {
mostrarListado: function(){
$.getJSON("servidor.php",
{operacion:"listarProductos"},
function(res){
var template = _.template(htmlListadoProductos);
var resultadoTemplate = template({productos:res});
$("#contenedor").html(resultadoTemplate);
});
}
}//end return
})<file_sep>/ajax/subirArchivo/servidor.php
<?php
if(isset($_POST)==true){
$archivo = $_FILES["archivo"];
$nombre = $archivo["name"];
$rutaDestino = "subidas/".$nombre;
move_uploaded_file($archivo["tmp_name"],$rutaDestino);
echo "archivo subido correctamente";
}
else{
echo "no me ha llegado un post";
}
?><file_sep>/src/app/componentes/registrar-cliente/registrar-cliente.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-registrar-cliente',
templateUrl: './registrar-cliente.component.html',
styleUrls: ['./registrar-cliente.component.css']
})
export class RegistrarClienteComponent{
dni:string=""
nombre:String=""
direccion:String=""
edad:Number=0
residente:Boolean=false
constructor() { }
noresidente(){
this.residente=false;
}
reg(){
alert(this.residente);
}
}
<file_sep>/ajax/templates/scripts/main.js
//Primero hay que decir qué librerías vamos a usar
requirejs.config({
baseUrl: "scripts/modulos",
paths: {
jquery:"../jquery",
underscore:"../underscore",
text: "../text"
},
//las librerías que no repeten el diseño modular
//debemos decirles qué objeto queremos de ellas
shim:{
"underscore":{
exports: "_"
}
}
});//end config
//Nuestra aplicacion comienza en la siguiente línea
requirejs(["inicio"],function(inicio){
inicio.mostrarInicio();
})<file_sep>/ajax/templates/scripts/modulos/inicio.js
define(["jquery","listarProductos","registrarProducto","registrarUsuario","text!html/menu.html"],
function($,listarProductos,registrarProducto,registroUsuario,htmlMenu){
//CUANDO DESDE OTRO MODULO INCLUIDO EL DEL MAIN PIDA INICIO.JSO
//OBTENDRA EL OBJETO QUE DEVOLVEMOS A CONT
return {
mostrarInicio:function(){
$("#menu").html(htmlMenu);
$("#listarAnuncios").click(function(){
listarProductos.mostrarListado();
});
$("#registrarAnuncio").click(function(){
registrarProducto.mostrarRegistro();
});
$("#registrarUsuario").click(function(){
registroUsuario.mostrarRegistroUsuario();
});
$("#contenedor").html(listarProductos.mostrarListado());
}
};//end return
});<file_sep>/ajax/ejercicio2JSON/miscript.js
function pedirProductos(){
console.log("pidiendo productos al server");
//comienzo ajax
//a través del siguiente objeto me voy a comunicar con servidor.php
var xmlhttp = new XMLHttpRequest();
//lo primero que debo decirle al objeto es
//qué hacer cuando reciba información del servidor.php
xmlhttp.onreadystatechange = function (){
if(this.readyState == 4 && this.status == 200){
var productos=JSON.parse(this.responseText);
console.log(productos);
mostrarProductos(productos);
}
};
//ahora le digo con q comunicarse
xmlhttp.open("GET","servidor.php",true);
//q la lance
xmlhttp.send();
}
function mostrarProductos(producto){
for(var p of producto){
console.log("mostrar: ");
console.log(p);
document.getElementById("listadoProductos").innerHTML+=
"<div>"+
"nombre "+p.nombre+
" precio "+p.precio+
"<a href='#' onclick='mostrarProducto("+p.id+")'>ver detalles</a>"
"</div>";
}
}
function inicio(){
pedirProductos();
}
function mostrarProducto(productos){
var productos = pedirProductos();
var p = productos.find(function(p){return p.id==id;})
alert("mostrar el producto "+ p.nombre);
}
inicio();
//motor de plantillas = libreria de js para tener una plantilla de html(moustache.js) angular tiene tambien uno tambien hay otro que se llama require
<file_sep>/ajax/JQUERY/jqueryAjax/servidor.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=ejercicio_chat', 'root');
$operacion = $_REQUEST["operacion"];
if($operacion=="registrar"){
$nombre = $_POST["nombre"];
$texto = $_POST["texto"];
$hora = $_POST["hora"];
$asunto = $_POST["asunto"];
$mensaje = R::dispense("mensajes");
$mensaje->nombre = $nombre;
$mensaje->texto = $texto;
$mensaje->hora = $hora;
$mensaje->asunto = $asunto;
R::store($mensaje);
echo "ok";
}
elseif($operacion == "listar"){
$mensajes = R::getAll('SELECT * FROM mensajes');
echo json_encode($mensajes);
}
?><file_sep>/ajax/ejercicioRegistroListado/servidor2.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=ejercicio_registro_listado', 'root');
$apuntados = R::getAll('SELECT nombre FROM apuntados');
echo json_encode($apuntados);
?><file_sep>/ajax/COOKIES/servidor.php
<?php
echo "tengo acceso a todas las cookies:";
print_r($_COOKIE);
echo "te voy a agregar una cookie";
setcookie("cookiedesdeelservidor","valor desde el server");
echo "tengo acceso a todas las cookies:";
print_r($_COOKIE);
?><file_sep>/ajax/ejercicioViajes/miscript.js
function pedirViajes(){
console.log("pidiendo productos al server");
//comienzo ajax
//a través del siguiente objeto me voy a comunicar con servidor.php
var xmlhttp = new XMLHttpRequest();
//lo primero que debo decirle al objeto es
//qué hacer cuando reciba información del servidor.php
xmlhttp.onreadystatechange = function (){
if(this.readyState == 4 && this.status == 200){
var viajes=JSON.parse(this.responseText);
console.log(viajes);
mostrarViajes(viajes);
}
};
//ahora le digo con q comunicarse
xmlhttp.open("GET","servidor.php",true);
//q la lance
xmlhttp.send();
}
function mostrarViajes(viajes){
for(var v of viajes){
console.log("mostrar: ");
document.getElementById("listadoViajes").innerHTML+=
"<div>"+
"Título "+v.titulo+
" Destino "+v.destino+
" Fecha de caducidad "+v.caducidad+
" Descripcion "+v.descripcion+
" Precio "+v.precio+
"<a href='#' onclick='mostrarViaje("+v.id+")'>ver detalles</a>"
"</div>";
}
}
function inicio(){
pedirViajes();
}
function mostrarViaje(v){
alert("mostrar el producto "+ v);
}
inicio();
//motor de plantillas = libreria de js para tener una plantilla de html(moustache.js) angular tiene tambien uno tambien hay otro que se llama require
<file_sep>/ajax/ejercicio1/hola.php
<?php
$veces=10;
while($veces>0){
echo "hola desde php <br/>";
$veces--;
}
?><file_sep>/ajax/JQUERY/jqueryAjax/miscript2.js
function obtenerMensajes(){
$.getJSON("servidor.php",{operacion:"listar"},function(res){
$("#listadoMensajes").html("");
for(r of res){
$("#listadoMensajes").append("HORA: "+r.hora+"\n"+"ASUNTO: "+r.asunto+"\n");
$("#listadoMensajes").append(r.nombre+": "+r.texto+"\n");
salto();
}
});
}
$("#botonEnvioMensaje").click(function(){
var nombre = $("#campoNombre").val();
var texto = $("#campoTexto").val();
var hora = new Date().toLocaleTimeString();
var asunto = $("#asunto").val();
$("<p>tu mensaje se está enviando</p>").appendTo('#advertencia');
$.post("servidor.php",{
operacion: "registrar",
nombre:nombre,
texto:texto,
hora:hora,
asunto:asunto
},function(res){
obtenerMensajes();
$("#advertencia").html("");
$("#campoTexto").val("");
$("#asunto").val("");
});
//var texto = $("#campoTexto").val("");
});
function arrancarTimer(){
var timer = setInterval(obtenerMensajes,1000);
}
function salto(){
var elem = $('#listadoMensajes');
elem.scrollTop(elem[0].scrollHeight);
}
arrancarTimer();<file_sep>/ajax/ejercicioRegistroListado/servidor.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=ejercicio_registro_listado', 'root');
$nombre = $_POST["nombre"];
$direccion = $_POST["direccion"];
$poblacion = $_POST["poblacion"];
$telefono = $_POST["telefono"];
$email=$_POST["email"];
$fecha=$_POST["nacimiento"];
//una vez recogidos los datos que han llegado por ajax
//deberiamos validar en servidor dichos valores
//parte de validacion...
//una vez validado todo registramos en bd
$apuntado = R::dispense( "apuntados" );
$apuntado->nombre = $nombre;
$apuntado->direccion = $direccion;
$apuntado->poblacion = $poblacion;
$apuntado->telefono = $telefono;
$apuntado->email = $email;
$apuntado->nacimiento = $fecha;
R::store($apuntado);
echo "OK";
?><file_sep>/ajax/ejercicio2JSON/servidor.php
<?php
require "rb-mysql.php";
R::setup( 'mysql:host=localhost;dbname=tienda_online', 'root');
$productos = R::getAll('SELECT * FROM tabla_productos');
echo json_encode($productos);
?><file_sep>/ajax/ejercicioRegistroListado/miscript.js
function procesarRegistro(){
var nombre = document.getElementById("campoNombre").value;
var direccion = document.getElementById("campoDireccion").value;
var poblacion = document.getElementById("campoPoblacion").value;
var telefono = document.getElementById("campoTelefono").value;
var email = document.getElementById("campoEmail").value;
var fecha = document.getElementById("campoFecha").value;
if(!/^([a-z]{2,30})$/i.test(nombre)){
alert("nombre no válido");
document.getElementById("campoNombre").value="";
return false;
}
if(!/^([a-z]{2,60})$/i.test(direccion)){
alert("direccion no válida");
document.getElementById("campoDireccion").value="";
return false;
}
if(!/^([a-z]{2,30})$/i.test(poblacion)){
alert("poblacion no válida");
document.getElementById("campoPoblacion").value="";
return false;
}
if(!(/^([0-9]{1,9})$/i.test(telefono))){
alert("teléfono no válido");
document.getElementById("campoTelefono").value="";
return false;
}
if(!/^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i.test(email)){
alert("email no válido");
document.getElementById("campoEmail").value="";
return false;
}
/*if(!/^([0-9]{6,10})$/.test(fecha)){
alert("fecha no válida");
document.getElementById("campoFecha").value="";
return false;
}
*/
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "OK"){mostrarRegistroOk();}
}
}
xhttp.open("POST","servidor.php",true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xhttp.send("nombre="+nombre+"&edad="+edad+"&direccion="+direccion+"&telefono="+telefono);
xhttp.send(`nombre=${nombre}&direccion=${direccion}&poblacion=${poblacion}&telefono=${telefono}&email=${email}&nacimiento=${fecha}`);
//una vez lanzada la petición ocultamos el formulario para que el usuario no se registre
//de nuevo
ocultarFormulario();
return false;
}
function ocultarFormulario(){
//ocultamos e indicamos que se está procesando la petición
document.getElementById("contenedor").innerHTML="Procesando petición...";
}
function mostrarRegistroOk(){
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange=function() {
if(this.readyState==4 && this.status==200){
var apuntados=JSON.parse(this.responseText);
mostrarApuntados(apuntados);
}
}
xhttp2.open("GET","servidor2.php",true);
xhttp2.send();
return false;
}
function mostrarApuntados(apuntados){
for(var a of apuntados){
document.body.innerHTML+=
"Enhorabuena!!! alumno inscrito en el curso"+
"<div>"+
"Nombre "+a.nombre+
" direccion "+a.direccion+
" telefono "+a.telefono+
" poblacion "+a.poblacion+
"email "+a.email+
"fecha de nacimiento "+a.nacimiento+
"</div>";
}
}
| 00995859f4263c91e4864a80e9a159ee9a1d5292 | [
"JavaScript",
"TypeScript",
"PHP"
] | 19 | PHP | susanacadenas81/gestorClientes | 46a9ae2b42c5d67fa3d420559411711c1e72cae9 | 99d8889a3df58d4af8c688d07e06d8d0de03d136 |
refs/heads/master | <file_sep>class Dealer
def initialize
@cards = []
4.times do |mark|
(1..13).each do |card|
@cards.push card
end
end
@cards.shuffle!
end
def deal
#TODO shuffle baby
@cards.pop
end
end
<file_sep>require './player'
require './dealer'
class Game
def start
@player = Player.new('player')
@cpu = Player.new('cpu')
@dealer = Dealer.new
#カードを配る
2.times do
@player.takeCards @dealer.deal
@cpu.takeCards @dealer.deal
end
# Playerのループ
puts "SCORE:#{@player.score?} STAND? HIT? [1/2]"
while answer = STDIN.gets.strip
if answer == "1"
cpu_game
break
elsif answer == "2"
#カードを引く
@player.takeCards @dealer.deal
if @player.burst?
bursted
break
elsif @player.score? == 21
puts "Black Jack"
cpu_game
break
else
puts "手札:#{@player.hand?.join(',')} #{@player.score?}になりました"
end
else
puts "イカサマですね"
end
end
end
def cpu_game
#TODO マシンの番
while @cpu.score? <= 14
@cpu.takeCards @dealer.deal
if @cpu.burst?
end_game
end
end
judge
end
def bursted
puts "バーストしました(#{@player.score?})"
start
end
def judge
if @player.burst?
puts "You lose(#{@player.score?}:#{@cpu.score?})"
start
elsif @cpu.burst?
puts "You win (#{@player.score?}:#{@cpu.score?})"
start
elsif @player.score? == @cpu.score?
puts "引き分け"
start
elsif @player.score? > @cpu.score?
puts "You win (#{@player.score?}:#{@cpu.score?})"
start
else
puts "You lose(#{@player.score?}:#{@cpu.score?})"
start
end
end
def end_game
judge
end
end
<file_sep>class Player
def initialize(type)
@hand = []
@score = 0
end
def takeCards(card)
@hand.push card
calcScore
end
def hand?
@hand
end
def calcScore
#TODO 計算する
@score = 0
aces = 0
@hand.each do |h|
if h.to_i > 10
h = 10
end
if h.to_i == 1
h += 10
aces += 1
end
@score += h.to_i
while @score > 21 && aces > 0
@score -= 10
aces -= 1
end
end
@score
end
def burst?
#TODO 計算する
@score > 21
end
def score?
@score
end
end
| 1a2a90837b8f55a4190de4cbc481c551e830c80e | [
"Ruby"
] | 3 | Ruby | yagitoshiro/BlackJack | a19a264accd25f612ba0febcac454a8a38cf5bb3 | 9c924c6e3e4b984986bd1b4eb6a2036f21d49c88 |
refs/heads/master | <file_sep>Network Switcher
=========
Network Switcher allows you to enable/disable network interfaces using hotkeys. It is also possible to create groups of network interfaces to enable/disable multiple interfaces using one hotkey.
### Installation
[Download] the .zip, adjust config.yml to your needs and run `NetworkSwitcher.exe`.
To setup autostart check the [Wiki](../../wiki/Setup-autostart).
###Example Configuration

In this example we will configure 3 different hotkeys.
- **Ctrl + NumPad1:** WiFi only
- **Ctrl + NumPad2:** Ethernet only
- **Ctrl + NumPad3:** Wifi and Ethernet
config.yml:
```yml
- Name: Wi-Fi
Hotkey: Ctrl + NumPad1
Interfaces:
- Name: Wi-Fi
- Name: Ethernet
Hotkey: Ctrl + NumPad2
Interfaces:
- Name: Ethernet
- Name: Hybrid
Hotkey: Ctrl + NumPad3
Interfaces:
- Name: Wi-Fi
- Name: Ethernet
Metric: 500
```
> **Hotkey:** Add multiple modifiers seperated by a '+' (Ctrl + Alt...) followed by a key.
### Available modifiers
Ctrl, Alt, Shift, Win
### Available keys
See MSDN: [Keys]
### Note
When connected to a wired and a wireless network, Windows will automatically set a Metric value for both interfaces. The wired interface will have a lower Metric by default so that the main traffic goes over the wired interface. You can override the Metric value as it is in the example if you want your main traffic to go through the wireless interface. More information about [Metric].
### Disclaimer
Use at your own risk :-)
[keys]:http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx
[Download]:https://github.com/olibanjoli/network-switcher/blob/master/compiled/Debug.zip
[Metric]:http://support.microsoft.com/kb/299540
<file_sep>using System.Collections.Generic;
using System.IO;
using System.Reflection;
using YamlDotNet.Serialization;
namespace NetworkSwitcher
{
public class NetworkGroupManager
{
private readonly string configPath;
public List<NetworkGroup> NetworkGroups { get; set; }
public NetworkGroupManager()
{
configPath = Path.Combine(new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName, "config.yml");
}
public void LoadConfiguration()
{
var deserializer = new Deserializer();
TextReader textReader = File.OpenText(configPath);
this.NetworkGroups = deserializer.Deserialize<List<NetworkGroup>>(textReader);
}
}
}<file_sep>using System;
using System.Diagnostics;
using System.Linq;
using System.Management;
using ROOT.CIMV2.Win32;
namespace NetworkSwitcher
{
public class Network
{
public static void SetActiveNetworkGroup(NetworkGroup group)
{
var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
var objectSearcher = new ManagementObjectSearcher(wmiQuery);
foreach (var item in objectSearcher.Get().Cast<ManagementObject>())
{
var adapter = new NetworkAdapter(item);
var element = group.Interfaces.FirstOrDefault(p => p.Name == adapter.NetConnectionID);
if (element == null)
{
DisableNetworkInterface(adapter);
}
else
{
EnableNetworkInterface(adapter, element.Metric);
}
}
}
private static void DisableNetworkInterface(NetworkAdapter adapter)
{
Console.WriteLine("disabling interface " + adapter.NetConnectionID);
adapter.Disable();
}
private static void EnableNetworkInterface(NetworkAdapter adapter, uint? metric)
{
Console.WriteLine("enabling interface " + adapter.NetConnectionID);
var command = string.Format("/C netsh interface ipv4 set interface \"{0}\" metric={1}", adapter.NetConnectionID, metric.HasValue ? metric.Value.ToString() : "");
Debug.WriteLine(command);
var processStartInfo = new ProcessStartInfo("cmd.exe", command) { WindowStyle = ProcessWindowStyle.Hidden };
Process.Start(processStartInfo);
adapter.Enable();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace NetworkSwitcher
{
public class NetworkGroup
{
public string Name { get; set; }
public string Hotkey { get; set; }
public Interface[] Interfaces { get; set; }
public NetworkGroup()
{
this.Interfaces = new Interface[0];
}
public Hotkey GetHotkey()
{
var parts = this.Hotkey.Split(new[] { "+" }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
var modifiers = new List<Modifiers>();
var keys = new List<Keys>();
foreach (var part in parts)
{
Modifiers modifierValue;
Keys keyValue;
if (Enum.TryParse(part, true, out modifierValue))
{
modifiers.Add(modifierValue);
}
else if (Enum.TryParse(part, true, out keyValue))
{
keys.Add(keyValue);
}
}
return new Hotkey { Modifiers = modifiers.Cast<int>().Aggregate((x, y) => x | y), Key = keys.First() };
}
}
}
<file_sep>using System.Windows.Forms;
namespace NetworkSwitcher
{
public class Hotkey
{
public int Modifiers { get; set; }
public Keys Key { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace NetworkSwitcher
{
public partial class HiddenForm : Form
{
private readonly List<GlobalHotkey> _hotkeys = new List<GlobalHotkey>();
private readonly NetworkGroupManager manager;
public HiddenForm()
{
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
this.InitializeComponent();
this.Load += OnLoad;
manager = new NetworkGroupManager();
manager.LoadConfiguration();
foreach (var networkGroup in manager.NetworkGroups)
{
var hotkey = networkGroup.GetHotkey();
_hotkeys.Add(new GlobalHotkey(hotkey.Modifiers, hotkey.Key, this, manager.NetworkGroups.IndexOf(networkGroup)));
}
}
private void OnLoad(object sender, EventArgs args)
{
this._hotkeys.ForEach(e => e.Register());
}
protected override void WndProc(ref Message m)
{
if (m.Msg == Constants.WM_HOTKEY_MSG_ID)
{
HandleHotkey(m.WParam.ToInt32());
}
base.WndProc(ref m);
}
private void HandleHotkey(int id)
{
var networkGroup = this.manager.NetworkGroups[id];
Network.SetActiveNetworkGroup(networkGroup);
}
}
}
<file_sep>namespace NetworkSwitcher
{
public class Interface
{
public string Name { get; set; }
public uint? Metric { get; set; }
}
} | d3d9e5a70df3ed0b1bf2f3c1d17f23c13b7f8782 | [
"Markdown",
"C#"
] | 7 | Markdown | olibanjoli/network-switcher | 3aef2986ba37bb0dc1d18aac22373231e030c0cb | b6073466e17871b75bbfc9b5748cb75fc5f5d6cc |
refs/heads/main | <repo_name>ritika-123-19/React-widget<file_sep>/my-react-app/src/App.js
import "./App.css";
import aadhaar from './aadhaar.png';
import tick from './tick.jpg';
import ReactCardFlip from 'react-card-flip';
import React, { useState } from "react";
import ReactDOM from 'react-dom';
function App() {
return <CardFlip src="aadhaar.png" />;
}
export default App;
const CardFlip = () => {
const [isFlipped, setIsFlipped] = useState(false);
const handleClick = () => {
setIsFlipped(!isFlipped);
};
return (
<ReactCardFlip isFlipped={isFlipped} flipDirection="vertical">
<div className="container-center-horizontal">
<div className="frame-1">
<div className="selected-card">
<div className="image">
<h2>Upload Your Aadhaar Card</h2>
</div>
<div className="line1"></div>
<div className="container">
<div className="aadhaar">
<div className="aadhaar-image">
<img src={aadhaar} alt="Logo" />
</div>
</div>
<div className="frontimg">Front Side Image</div>
<label htmlFor="upload-button">
<span className="button1" value="Upload">
Upload
</span>
<span className="button2" value="Upload">
Upload
</span>
</label>
<input type="file" id="upload-button" style={{ display: "none" }} />
<div className="backimg">Back Side Image</div>
<button className="submit" onClick={handleClick}>
Continue
</button>
</div>
<div className="line2"></div>
<div className="alert">
<p>
<b>Attention:</b> Make sure the photo is clear.
</p>
</div>
</div>
</div>
</div>
<div className="frame-2">
<div className="success">
<img src={tick} alt="Logo" />
<h1>Awesome!</h1>
<h3>Your are ready to proceed using our website.</h3>
</div>
<div className="close">
<button onClick={handleClick} className="closebtn">Proceed</button>
</div>
</div>
</ReactCardFlip>
);
}
ReactDOM.render(<CardFlip />, document.getElementById('root'));
| 1cf66b66999425e3751cd0aa20167370282a2d6c | [
"JavaScript"
] | 1 | JavaScript | ritika-123-19/React-widget | f7f128be461d287906f647911a327d66e3818e18 | 53894346f108d9e1a163083059d6637d5ed3ba0f |
refs/heads/master | <repo_name>gugu/django-bitcoin<file_sep>/django_bitcoin/forms.py
# coding=utf-8
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
from django import forms
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.utils.translation import get_language_from_request, ugettext_lazy as _
from djangoextras.forms import CurrencyField
from django_bitcoin.models import BitcoinEscrow
class BitcoinEscrowBuyForm(ModelForm):
class Meta:
model=BitcoinEscrow
fields = ('buyer_address', 'buyer_phone', 'buyer_email')
<file_sep>/django_bitcoin/jsonrpc/__init__.py
from json import loads, dumps, JSONEncodeException, JSONDecodeException
from proxy import ServiceProxy, JSONRPCException
<file_sep>/django_bitcoin/admin.py
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8
from django.contrib import admin
from django_bitcoin import models
class TransactionAdmin(admin.ModelAdmin):
"""Management of ``Transaction`` - Disable address etc editing
"""
list_display = ('address', 'created_at', 'amount')
readonly_fields = ('address', 'created_at', 'amount')
class BitcoinAddressAdmin(admin.ModelAdmin):
"""Deal with ``BitcoinAddress``
No idea in being able to edit the address, as that would not
sync with the network
"""
list_display = ('address', 'label', 'created_at', 'least_received', 'active')
readonly_fields = ('address',)
class PaymentAdmin(admin.ModelAdmin):
"""Allow the edit of ``description``
"""
list_display = ('created_at', 'description', 'paid_at', 'address', 'amount', 'amount_paid', 'active')
readonly_fields = ('address', 'amount', 'amount_paid', 'created_at', 'updated_at', 'paid_at', 'withdrawn_total', 'transactions')
class WalletTransactionAdmin(admin.ModelAdmin):
"""Inter-site transactions
"""
list_display = ('created_at', 'from_wallet', 'to_wallet', 'to_bitcoinaddress', 'amount')
readonly_fields = ('created_at', 'from_wallet', 'to_wallet', 'to_bitcoinaddress', 'amount')
class WalletAdmin(admin.ModelAdmin):
"""Admin ``Wallet``
"""
addresses = lambda wallet: wallet.addresses.all()
addresses.short_description = 'Addresses'
list_display = ('created_at', 'label', 'updated_at')
readonly_fields = ('created_at', 'updated_at', addresses, 'transactions_with')
admin.site.register(models.Transaction, TransactionAdmin)
admin.site.register(models.BitcoinAddress, BitcoinAddressAdmin)
admin.site.register(models.Payment, PaymentAdmin)
admin.site.register(models.WalletTransaction, WalletTransactionAdmin)
admin.site.register(models.Wallet, WalletAdmin)
# EOF
<file_sep>/django_bitcoin/jsonrpc/proxy.py
from authproxy import AuthServiceProxy as ServiceProxy, JSONRPCException
<file_sep>/django_bitcoin/test_zero_confirmation.py
from django.core.management import setup_environ
import settings
setup_environ(settings)
# Tests only with internal transf
from decimal import Decimal
import unittest
from django_bitcoin import Wallet
class InternalChangesTest(unittest.TestCase):
def setUp(self):
self.origin = Wallet.objects.all()[0]
self.w1 = Wallet.objects.create()
self.w2 = Wallet.objects.create()
self.w3 = Wallet.objects.create()
self.w4 = Wallet.objects.create()
self.w5 = Wallet.objects.create()
self.w6 = Wallet.objects.create()
self.w7 = Wallet.objects.create()
def testTransactions(self):
# t1
self.origin.send_to_wallet(self.w1, Decimal('5'))
self.assertEquals(self.w1.balance(), (Decimal('0'), Decimal('5')))
# t2
self.w1.send_to_wallet(self.w2, Decimal('1'))
self.assertEquals(self.w1.balance(), (Decimal('0'), Decimal('4')))
self.assertEquals(self.w2.balance(), (Decimal('0'), Decimal('1')))
# t3
self.w1.send_to_wallet(self.w3, Decimal('2'))
self.assertEquals(self.w1.balance(), (Decimal('0'), Decimal('2')))
self.assertEquals(self.w3.balance(), (Decimal('0'), Decimal('2')))
# t1'
raw_input('Transfer 2 bitcoins to wallet %s' %
self.w1.static_receiving_address())
# t4
self.w1.send_to_wallet(self.w4, Decimal('4'))
self.assertEquals(self.w1.balance(), (Decimal('0'), Decimal('0')))
self.assertEquals(self.w4.balance(), (Decimal('2'), Decimal('2')))
# t2'
raw_input('Transfer 2 bitcoins to wallet %s' %
self.w3.static_receiving_address())
# t5
self.w3.send_to_wallet(self.w4, Decimal('4'))
self.assertEquals(self.w3.balance(), (Decimal('0'), Decimal('0')))
self.assertEquals(self.w4.balance(), (Decimal('4'), Decimal('4')))
# t3'
raw_input('Transfer 2 bitcoins to wallet %s' %
self.w4.static_receiving_address())
# t6
self.w4.send_to_wallet(self.w1, Decimal('10'))
self.assertEquals(self.w1.balance(), (Decimal('6'), Decimal('4')))
self.assertEquals(self.w4.balance(), (Decimal('0'), Decimal('0')))
# t7
self.w1.send_to_wallet(self.w5, Decimal('6'))
self.assertEquals(self.w1.balance(), (Decimal('4'), Decimal('0')))
self.assertEquals(self.w5.balance(), (Decimal('2'), Decimal('4')))
# t4'
raw_input('Transfer 2 bitcoins to wallet %s' %
self.w5.static_receiving_address())
# t8
self.w5.send_to_wallet(self.w6, Decimal('8'))
self.assertEquals(self.w5.balance(), (Decimal('0'), Decimal('0')))
self.assertEquals(self.w6.balance(), (Decimal('4'), Decimal('4')))
# t9
self.w6.send_to_wallet(self.w7, Decimal('4'))
self.assertEquals(self.w6.balance(), (Decimal('4'), Decimal('0')))
self.assertEquals(self.w7.balance(), (Decimal('0'), Decimal('4')))
# t5'
raw_input('Transfer 2 bitcoins to wallet %s' %
self.w7.static_receiving_address())
# t10
self.w7.send_to_wallet(self.w5, Decimal('6'))
self.assertEquals(self.w5.balance(), (Decimal('2'), Decimal('4')))
self.assertEquals(self.w7.balance(), (Decimal('0'), Decimal('0')))
# t11
self.w6.send_to_wallet(self.w5, Decimal('2'))
self.assertEquals(self.w5.balance(), (Decimal('4'), Decimal('4')))
self.assertEquals(self.w6.balance(), (Decimal('2'), Decimal('0')))
self.clear()
def clear(self):
self.w1.delete()
self.w2.delete()
self.w3.delete()
self.w4.delete()
self.w5.delete()
self.w6.delete()
self.w7.delete()
if __name__ == '__main__':
unittest.main()
<file_sep>/django_bitcoin/jsonrpc/json.py
json = __import__('json')
loads = json.loads
dumps = json.dumps
JSONEncodeException = TypeError
JSONDecodeException = ValueError
<file_sep>/django_bitcoin/migrations/0001_initial.py
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Transaction'
db.create_table('django_bitcoin_transaction', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('amount', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=16, decimal_places=8)),
('address', self.gf('django.db.models.fields.CharField')(max_length=50)),
))
db.send_create_signal('django_bitcoin', ['Transaction'])
# Adding model 'BitcoinAddress'
db.create_table('django_bitcoin_bitcoinaddress', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('address', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False)),
('least_received', self.gf('django.db.models.fields.DecimalField')(default='0', max_digits=16, decimal_places=8)),
))
db.send_create_signal('django_bitcoin', ['BitcoinAddress'])
# Adding model 'Payment'
db.create_table('django_bitcoin_payment', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('description', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('address', self.gf('django.db.models.fields.CharField')(max_length=50)),
('amount', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=16, decimal_places=8)),
('amount_paid', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=16, decimal_places=8)),
('active', self.gf('django.db.models.fields.BooleanField')(default=False)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('updated_at', self.gf('django.db.models.fields.DateTimeField')()),
('paid_at', self.gf('django.db.models.fields.DateTimeField')(default=None, null=True)),
('withdrawn_total', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=16, decimal_places=8)),
))
db.send_create_signal('django_bitcoin', ['Payment'])
# Adding M2M table for field transactions on 'Payment'
db.create_table('django_bitcoin_payment_transactions', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('payment', models.ForeignKey(orm['django_bitcoin.payment'], null=False)),
('transaction', models.ForeignKey(orm['django_bitcoin.transaction'], null=False))
))
db.create_unique('django_bitcoin_payment_transactions', ['payment_id', 'transaction_id'])
# Adding model 'WalletTransaction'
db.create_table('django_bitcoin_wallettransaction', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('from_wallet', self.gf('django.db.models.fields.related.ForeignKey')(related_name='sent_transactions', to=orm['django_bitcoin.Wallet'])),
('to_wallet', self.gf('django.db.models.fields.related.ForeignKey')(related_name='received_transactions', null=True, to=orm['django_bitcoin.Wallet'])),
('to_bitcoinaddress', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
('amount', self.gf('django.db.models.fields.DecimalField')(default='0.0', max_digits=16, decimal_places=8)),
('description', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
))
db.send_create_signal('django_bitcoin', ['WalletTransaction'])
# Adding model 'Wallet'
db.create_table('django_bitcoin_wallet', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('updated_at', self.gf('django.db.models.fields.DateTimeField')()),
('label', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
))
db.send_create_signal('django_bitcoin', ['Wallet'])
# Adding M2M table for field addresses on 'Wallet'
db.create_table('django_bitcoin_wallet_addresses', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('wallet', models.ForeignKey(orm['django_bitcoin.wallet'], null=False)),
('bitcoinaddress', models.ForeignKey(orm['django_bitcoin.bitcoinaddress'], null=False))
))
db.create_unique('django_bitcoin_wallet_addresses', ['wallet_id', 'bitcoinaddress_id'])
def backwards(self, orm):
# Deleting model 'Transaction'
db.delete_table('django_bitcoin_transaction')
# Deleting model 'BitcoinAddress'
db.delete_table('django_bitcoin_bitcoinaddress')
# Deleting model 'Payment'
db.delete_table('django_bitcoin_payment')
# Removing M2M table for field transactions on 'Payment'
db.delete_table('django_bitcoin_payment_transactions')
# Deleting model 'WalletTransaction'
db.delete_table('django_bitcoin_wallettransaction')
# Deleting model 'Wallet'
db.delete_table('django_bitcoin_wallet')
# Removing M2M table for field addresses on 'Wallet'
db.delete_table('django_bitcoin_wallet_addresses')
models = {
'django_bitcoin.bitcoinaddress': {
'Meta': {'object_name': 'BitcoinAddress'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'address': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'least_received': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '16', 'decimal_places': '8'})
},
'django_bitcoin.payment': {
'Meta': {'object_name': 'Payment'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'address': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'amount': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '16', 'decimal_places': '8'}),
'amount_paid': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '16', 'decimal_places': '8'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'paid_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True'}),
'transactions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['django_bitcoin.Transaction']", 'symmetrical': 'False'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {}),
'withdrawn_total': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '16', 'decimal_places': '8'})
},
'django_bitcoin.transaction': {
'Meta': {'object_name': 'Transaction'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'amount': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '16', 'decimal_places': '8'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'django_bitcoin.wallet': {
'Meta': {'object_name': 'Wallet'},
'addresses': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['django_bitcoin.BitcoinAddress']", 'symmetrical': 'False'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'transactions_with': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['django_bitcoin.Wallet']", 'through': "orm['django_bitcoin.WalletTransaction']", 'symmetrical': 'False'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {})
},
'django_bitcoin.wallettransaction': {
'Meta': {'object_name': 'WalletTransaction'},
'amount': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '16', 'decimal_places': '8'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'from_wallet': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sent_transactions'", 'to': "orm['django_bitcoin.Wallet']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'to_bitcoinaddress': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'to_wallet': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'received_transactions'", 'null': 'True', 'to': "orm['django_bitcoin.Wallet']"})
}
}
complete_apps = ['django_bitcoin']
<file_sep>/django_bitcoin/management/commands/GetHistoricalRates.py
from django.core.management.base import NoArgsCommand
from django.conf import settings
import os
import sys
import re
import codecs
import commands
import urllib2
import urllib
import json
import random
from time import sleep
import math
import datetime
from django_bitcoin.models import get_historical_price
import pytz # 3rd party
class Command(NoArgsCommand):
help = 'Create a profile object for users which do not have one.'
def handle_noargs(self, **options):
u = datetime.datetime.utcnow()
u = u.replace(tzinfo=pytz.utc)
print u, get_historical_price()
<file_sep>/django_bitcoin/mock_bitcoin_objects.py
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8
import decimal
import mock
from django_bitcoin import utils
## bitcoin mock objects
## Patch your test cases which access bitcoin with these decorators
## eg:
#@mock.patch('django_bitcoin.utils.bitcoind', new=mock_bitcoin_objects.mock_bitcoind)
#@mock.patch('django_bitcoin.models.bitcoind', new=mock_bitcoin_objects.mock_bitcoind)
#def test_wallet_received():
# ...
import random
import string
ADDR_CHARS = '%s%s' % (string.letters, string.digits)
ADDR_LEN = 34
def create_address(self):
return ''.join([random.choice(ADDR_CHARS) for i in xrange(ADDR_LEN)])
## FIRST
mock_bitcoind = mock.Mock(wraps=utils.bitcoind, spec=utils.bitcoind)
mock_received_123 = mock.Mock()
mock_received_123.return_value = decimal.Decimal(123)
mock_bitcoind.total_received = mock.mocksignature(utils.bitcoind.total_received, mock=mock_received_123)
mock_bitcoind.send = mock.mocksignature(utils.bitcoind.send)
mock_bitcoind_address = mock.Mock()
mock_bitcoind_address.side_effect = create_address
mock_bitcoind.create_address = mock.mocksignature(utils.bitcoind.create_address, mock=mock_bitcoind_address)
## SECOND
mock_bitcoind_other = mock.Mock(wraps=utils.bitcoind, spec=utils.bitcoind)
mock_received_65535 = mock.Mock()
mock_received_65535.return_value = decimal.Decimal(65535)
mock_bitcoind_other.total_received = mock.mocksignature(utils.bitcoind.total_received, mock=mock_received_65535)
mock_bitcoind_other.send = mock.mocksignature(utils.bitcoind.send)
mock_bitcoind_other_address = mock.Mock()
mock_bitcoind_other_address.side_effect = create_address
mock_bitcoind_other.create_address = mock.mocksignature(utils.bitcoind.create_address, mock=mock_bitcoind_other_address)
# EOF
<file_sep>/django_bitcoin/templatetags/currency_conversions.py
from django import template
from django_bitcoin import currency
import json
from decimal import Decimal
import urllib
from django.core.urlresolvers import reverse, NoReverseMatch
register = template.Library()
# currency conversion functions
@register.filter
def bitcoinformat(value):
# print "bitcoinformat", value
if value == None:
return None
if not (isinstance(value, float) or isinstance(value, Decimal)):
return str(value).rstrip('0').rstrip('.')
return ("%.8f" % value).rstrip('0').rstrip('.')
@register.filter
def currencyformat(value):
if value == None:
return None
if not (isinstance(value, float) or isinstance(value, Decimal)):
return str(value).rstrip('0').rstrip('.')
return ("%.2f" % value)
@register.filter
def btc2usd(value):
return (Decimal(value)*currency.exchange.get_rate('USD')).quantize(Decimal("0.01"))
@register.filter
def usd2btc(value):
return (Decimal(value)/currency.exchange.get_rate('USD')).quantize(Decimal("0.00000001"))
@register.filter
def btc2eur(value):
return (Decimal(value)*currency.exchange.get_rate('EUR')).quantize(Decimal("0.01"))
@register.filter
def eur2btc(value):
return (Decimal(value)/currency.exchange.get_rate('EUR')).quantize(Decimal("0.00000001"))
@register.filter
def btc2currency(value, other_currency="USD", rate_period="24h"):
if other_currency=="BTC":
return bitcoinformat(value)
return currencyformat(currency.btc2currency(value, other_currency, rate_period))
@register.filter
def currency2btc(value, other_currency="USD", rate_period="24h"):
if other_currency=="BTC":
return currencyformat(value)
return bitcoinformat(currency.currency2btc(value, other_currency, rate_period))
@register.simple_tag
def exchangerates_json():
return json.dumps(currency.get_rate_table())
@register.inclusion_tag('wallet_history.html')
def wallet_history(wallet):
return {'wallet': wallet}
@register.filter
def show_addr(address, arg):
'''
Display a bitcoin address with plus the link to its blockexplorer page.
'''
# note: i disapprove including somewhat unnecessary depencies such as this, especially since blockexplorer is unreliable service
link ="<a href='http://blockexplorer.com/%s/'>%s</a>"
if arg == 'long':
return link % (address, address)
else:
return link % (address, address[:8])
@register.inclusion_tag('wallet_tagline.html')
def wallet_tagline(wallet):
return {'wallet': wallet, 'balance_usd': btc2usd(wallet.total_balance())}
@register.inclusion_tag('bitcoin_payment_qr.html')
def bitcoin_payment_qr(address, amount=Decimal("0"), description='', display_currency=''):
currency_amount=Decimal(0)
if display_currency:
currency_amount=(Decimal(amount)*currency.exchange.get_rate(display_currency)).quantize(Decimal("0.01"))
try:
image_url = reverse('qrcode', args=('dummy',))
except NoReverseMatch,e:
raise ImproperlyConfigured('Make sure you\'ve included django_bitcoin.urls')
qr = "bitcoin:"+address+("", "?amount="+str(amount))[amount>0]
qr = urllib.quote(qr)
address_qrcode = reverse('qrcode', args=(qr,))
return {'address': address,
'address_qrcode': address_qrcode,
'amount': amount,
'description': description,
'display_currency': display_currency,
'currency_amount': currency_amount,
}
<file_sep>/django_bitcoin/views.py
# Create your views here.
from django.http import HttpResponseRedirect, HttpResponse
from django.core.cache import cache
import qrcode
import StringIO
def qrcode_view(request, key):
cache_key="qrcode:"+key
c=cache.get(cache_key)
if not c:
img = qrcode.make(key, box_size=4)
output = StringIO.StringIO()
img.save(output, "PNG")
c = output.getvalue()
cache.set(cache_key, c, 60*60)
return HttpResponse(c, mimetype="image/png")
<file_sep>/django_bitcoin/management/commands/ExtensiveWalletTest.py
from django.core.management.base import NoArgsCommand
from django.conf import settings
import os
import sys
import re
import codecs
import commands
import urllib2
import urllib
import json
import random
from time import sleep
import math
import datetime
from django_bitcoin import Wallet
from django_bitcoin.utils import bitcoind
from decimal import Decimal
import warnings
import twitter
class Command(NoArgsCommand):
help = 'Tweet with LocalBitcoins.com account.'
def handle_noargs(self, **options):
final_wallets = []
process_num = random.randint(0, 1000)
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=RuntimeWarning)
for i in range(0, 3):
w = Wallet.objects.create()
# print "starting w.id", w.id
addr = w.receiving_address()
# print "taddr", w.id, addr
final_wallets.append(w)
for w in final_wallets:
if w.total_balance_sql() > 0:
print str(process_num) + " error", w.id
raise Exception("damn!")
# print "final", w.id, w.static_receiving_address(), w.receiving_address()
print str(process_num) + " loading 0.001 to wallet #1", w1.static_receiving_address()
w1 = final_wallets[0]
w2 = final_wallets[1]
w3 = final_wallets[2]
bitcoind.send(w1.static_receiving_address(), Decimal("0.001"))
while w1.total_balance_sql() <= 0:
sleep(1)
w1 = Wallet.objects.get(id=w1.id)
# print w1.last_balance
print str(process_num) + " w1.last_balance " + str(w1.last_balance)
print str(process_num) + "loading"
w1.send_to_wallet(w2, Decimal("0.0002"))
w1.send_to_wallet(w3, Decimal("0.0005"))
w3.send_to_address(w1, Decimal("0.0004"))
print str(process_num) + " w1.last_balance " + str(w1.last_balance)
print str(process_num) + " w2.last_balance " + str(w2.last_balance)
print str(process_num) + " w3.last_balance " + str(w3.last_balance)
while w1.total_balance_sql() <= 0:
sleep(1)
w1 = Wallet.objects.get(id=w1.id)
print str(process_num) + "catching"
print str(process_num) + " w1.last_balance " + str(w1.last_balance)
print str(process_num) + " w2.last_balance " + str(w2.last_balance)
print str(process_num) + " w3.last_balance " + str(w3.last_balance)
<file_sep>/django_bitcoin/management/commands/FixLastBalancesConcurrency.py
from django.core.management.base import NoArgsCommand
from time import sleep, time
from django_bitcoin.utils import bitcoind
from django_bitcoin.models import BitcoinAddress
from django_bitcoin.models import Wallet
from django.conf import settings
from decimal import Decimal
class Command(NoArgsCommand):
help = """fix balances
"""
def handle_noargs(self, **options):
print "starting..."
for w in Wallet.objects.all():
w.last_balance = w.total_balance()
w.save()
<file_sep>/README.rst
Introduction
================
``django-bitcoin`` is a `Django web framework <http://djangoproject.com/>`_
application for building Bitcoin web apps.
.. contents ::
Features
============
* Simple Bitcoin wallet management
* Bitcoin payment processing
* Bitcoin market information
Installation
============
To install, just add the app to your settings.py INSTALLED_APPS like::
INSTALLED_APPS = [
...
'django_bitcoin',
...
]
Also you have to run a local bitcoind instance, and specify connection string in settings::
BITCOIND_CONNECTION_STRING = "http://bitcoinuser:password@localhost:8332"
Usage
=====
Tutorial
---------
`There is a small tutorial about how to use django-bitcoin to create your own instawallet <http://blog.kangasbros.fi/?p=85>`_.
Wallet websites, escrow services using the "Wallet"-model
------------------------------------------------------------
You can use the `Wallet` class to do different bitcoin-moving applications. Typical example would be a marketplace-style site, where there are multiple sellers and buyer. Or job freelance site, where escrow is needed. Or even an exchange could be done with this abstraction (a little extra classes would be needed however).
Note that while you move bitcoins between Wallet-objects, only bitcoin transactions needed are incoming and outgoing transactions.
Transactions between the system "Wallet"-objects don't generate "real" bitcoin transactions. Every transaction (except incoming transactions) is logged to `WalletTransaction` object to ease accounting.
This also means that outgoing bitcoin transactions are "mixed"::
from django_bitcoin import Wallet, currency
class Profile(models.Model):
wallet = ForeignKey(Wallet)
outgoing_bitcoin_address = CharField()
class Escrow(models.Model):
wallet = ForeignKey(Wallet)
buyer_happy = BooleanField(default=False)
buyer=Profile.objects.create()
seller=Profile.objects.create()
purchase=Escrow.objects.create()
AMOUNT_USD="9.99"
m=currency.Money(AMOUNT_USD, "USD")
btc_amount=currency.exchange(m, "BTC")
print "Send "+str(btc_amount)+" BTC to address "+buyer.wallet.receiving_address()
sleep(5000) # wait for transaction
if p1.wallet.total_balance()>=btc_amount:
p1.send_to_wallet(purchase, btc_amount)
sleep(1000) # wait for product/service delivery
if purchase.buyer_happy:
purchase.wallet.send_to_wallet(seller.wallet)
seller.wallet.send_to_address(seller.outgoing_bitcoin_address, seller.wallet.total_balance())
else:
print "WHY U NO HAPPY"
#return bitcoins to buyer, 50/50 split or something
Templatetags
----------------
To display transaction history and simple wallet tagline in your views, use the following templatetags::
{% load currency_conversions %}
<!-- display balance tagline, estimate in USD and received/sent -->
{% wallet_tagline profile.bitcoin_wallet %}
<!-- display list of transactions as a table -->
{% wallet_history profile.bitcoin_wallet %}
Easy way to convert currencies from each other: `btc2usd, usd2btc, eur2btc, btc2eur`
Also currency2btc, btc2currency for any currencies on bitcoincharts.com::
{% load currency_conversions %}
Hi, for the pizza: send me {{bitcoin_amount}}BTC (about {{ bitcoin_amount|btc2usd }}USD).
Display QR code of the bitcoin payment using google charts API::
{% load currency_conversions %}
Pay the following payment with your android bitcoin wallet:
{% bitcoin_payment_qr wallet.receiving_address bitcoin_amount %}.
The same but display also description and an estimate in EUR:
{% bitcoin_payment_qr wallet.receiving_address bitcoin_amount "One beer" "EUR" %}.
Transaction notifications
-----------------------------
To enable bitcoin transaction notifications, set the following flag in your ``settings.py``::
BITCOIN_TRANSACTION_SIGNALING = True
After that, you need to setup a *cron* job to run each minute, something like the following::
* * * * * (cd $APP_PATH && python manage.py python manage.py CheckTransactions >> $APP_PATH/logs/email_sends.log 2>&1)
After that you can define your balance_changed and balance_changed_confirmed signals::
from django_bitcoin.models import balance_changed, balance_changed_confirmed
from django.dispatch import receiver
@receiver(balance_changed)
def balance_changed_handler(sender, **kwargs):
pass
# try:
# print "balance changed", sender.id, kwargs["changed"], sender.total_balance()
@receiver(balance_changed_confirmed)
def balance_changed_confirmed_handler(sender, **kwargs):
pass
Community
==========
Currently ``django-bitcoin`` is used at production in
* `localbitcoins.com <http://localbitcoins.com>`_
* `bountychest.com <http://bountychest.com>`_
More to come!
If you have a site using django-bitcoin, drop me an email and I will link to it here.
Support and source code
=========================
`Issue tracker at Github.com <https://github.com/kangasbros/django-bitcoin>`_.
<file_sep>/django_bitcoin/management/commands/FlushBitcoin.py
from django.core.management.base import NoArgsCommand
from django.conf import settings
import os
import sys
import re
import codecs
import commands
import urllib2
import urllib
import json
import numpy
import random
from time import sleep
import math
from django_bitcoin.models import RefillPaymentQueue, UpdatePayments
class Command(NoArgsCommand):
help = 'Create a profile object for users which do not have one.'
def handle_noargs(self, **options):
RefillPaymentQueue()
UpdatePayments()
<file_sep>/django_bitcoin/management/commands/CreateInitialDepositTransactions.py
from django.core.management.base import NoArgsCommand, BaseCommand
from django.conf import settings
import os
import sys
import re
import codecs
import commands
import urllib2
import urllib
import json
import random
from time import sleep
import math
import datetime
from django_bitcoin.models import DepositTransaction, BitcoinAddress, WalletTransaction, Wallet
from django.db.models import Avg, Max, Min, Sum
from decimal import Decimal
from distributedlock import distributedlock, MemcachedLock, LockNotAcquiredError
from django.core.cache import cache
from django.db import transaction
from optparse import make_option
from django.contrib.auth.models import User
@transaction.commit_manually
def flush_transaction():
transaction.commit()
def CacheLock(key, lock=None, blocking=True, timeout=10):
if lock is None:
lock = MemcachedLock(key=key, client=cache, timeout=timeout)
return distributedlock(key, lock, blocking)
import pytz # 3rd party
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-u", "--users",
action='store', type="str", dest="users"),
)
help = 'This creates the revenue report for a specific month.'
def handle(self, *args, **options):
dt_now = datetime.datetime.now()
wallet_query = Wallet.objects.all()
if options['users']:
w_ids = []
for u in options['users'].split(","):
w_ids.append(User.objects.get(username=u).get_profile().wallet.id)
wallet_query = wallet_query.filter(id__in=w_ids)
for w in wallet_query:
for ba in BitcoinAddress.objects.filter(wallet=w).exclude(migrated_to_transactions=True):
original_balance = ba.wallet.last_balance
with CacheLock('query_bitcoind_'+str(ba.id)):
dts = DepositTransaction.objects.filter(address=ba, wallet=ba.wallet)
for dp in dts:
wt = WalletTransaction.objects.create(amount=dp.amount, to_wallet=ba.wallet, created_at=ba.created_at,
description=ba.address, deposit_address=ba)
DepositTransaction.objects.filter(id=dp.id).update(transaction=wt)
s = dts.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
if s < ba.least_received_confirmed and ba.least_received_confirmed > 0:
wt = WalletTransaction.objects.create(amount=ba.least_received_confirmed - s, to_wallet=ba.wallet, created_at=ba.created_at,
description=u"Deposits "+ba.address+u" "+ ba.created_at.strftime("%x") + u" - "+ dt_now.strftime("%x"),
deposit_address=ba)
dt = DepositTransaction.objects.create(address=ba, amount=wt.amount, wallet=ba.wallet,
created_at=ba.created_at, transaction=wt, confirmations=settings.BITCOIN_MINIMUM_CONFIRMATIONS,
description=u"Deposits "+ba.address+u" "+ ba.created_at.strftime("%x") + u" - "+ dt_now.strftime("%x"))
print dt.description, dt.amount
elif s > ba.least_received_confirmed:
print "TOO MUCH!!!", ba.address
elif s < ba.least_received_confirmed:
print "too little, address", ba.address, ba.least_received_confirmed, s
BitcoinAddress.objects.filter(id=ba.id).update(migrated_to_transactions=True)
flush_transaction()
wt_sum = WalletTransaction.objects.filter(deposit_address=ba).aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
if wt_sum != ba.least_received_confirmed:
raise Exception("wrong amount! "+str(ba.address))
w = Wallet.objects.get(id=ba.wallet.id)
if original_balance != w.total_balance_sql():
raise Exception("wrong wallet amount! "+str(ba.address))
tot_received = WalletTransaction.objects.filter(from_wallet=None).aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
tot_received_bitcoinaddress = BitcoinAddress.objects.filter(migrated_to_transactions=True)\
.aggregate(Sum('least_received_confirmed'))['least_received_confirmed__sum'] or Decimal(0)
if tot_received != tot_received_bitcoinaddress:
raise Exception("wrong total receive amount! "+str(ba.address))
print "Migrated, doing final check..."
tot_received = WalletTransaction.objects.filter(from_wallet=None).aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
tot_received_bitcoinaddress = BitcoinAddress.objects.filter(migrated_to_transactions=True)\
.aggregate(Sum('least_received_confirmed'))['least_received_confirmed__sum'] or Decimal(0)
if tot_received != tot_received_bitcoinaddress:
raise Exception("wrong total receive amount! "+str(ba.address))
print "Final check succesfull."
<file_sep>/django_bitcoin/urls.py
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('django_bitcoin.views',
url(r'^qrcode/(?P<key>.+)$','qrcode_view',name='qrcode'),
)
<file_sep>/CHANGES.rst
Changelog
===================
0.2 (2013-05-14)
----------------
- README.rst, change log and release process workflow updates [miohtama]
- Historical prices data handling [Jeremias Kangas]
0.1
----
- Initial release<file_sep>/django_bitcoin/context_processors.py
from django_bitcoin.models import bitcoinprice_eur, bitcoinprice_usd
def bitcoinprice(request):
return {'bitcoinprice_eur': bitcoinprice_eur(),
'bitcoinprice_usd': bitcoinprice_usd(),
}
<file_sep>/django_bitcoin/tasks.py
from __future__ import with_statement
import datetime
import random
import hashlib
import base64
from decimal import Decimal
from django.db import models
from django_bitcoin.utils import bitcoind
from django_bitcoin import settings
from django.utils.translation import ugettext as _
from django_bitcoin.models import DepositTransaction, BitcoinAddress
import django.dispatch
import jsonrpc
from BCAddressField import is_valid_btc_address
from django.db import transaction as db_transaction
from celery import task
from distributedlock import distributedlock, MemcachedLock, LockNotAcquiredError
from django.core.cache import cache
from django.core.mail import mail_admins
def NonBlockingCacheLock(key, lock=None, blocking=False, timeout=10000):
if lock is None:
lock = MemcachedLock(key=key, client=cache, timeout=timeout)
return distributedlock(key, lock, blocking)
@task()
def query_transactions():
with NonBlockingCacheLock("query_transactions_ongoing"):
blockcount = bitcoind.bitcoind_api.getblockcount()
max_query_block = blockcount - settings.BITCOIN_MINIMUM_CONFIRMATIONS - 1
if cache.get("queried_block_index"):
query_block = min(int(cache.get("queried_block_index")), max_query_block)
else:
query_block = blockcount - 100
blockhash = bitcoind.bitcoind_api.getblockhash(query_block)
# print query_block, blockhash
transactions = bitcoind.bitcoind_api.listsinceblock(blockhash)
# print transactions
transactions = [tx for tx in transactions["transactions"] if tx["category"]=="receive"]
print transactions
for tx in transactions:
ba = BitcoinAddress.objects.filter(address=tx[u'address'])
if ba.count() > 1:
raise Exception(u"Too many addresses!")
if ba.count() == 0:
print "no address found, address", tx[u'address']
continue
ba = ba[0]
dps = DepositTransaction.objects.filter(txid=tx[u'txid'], amount=tx['amount'], address=ba)
if dps.count() > 1:
raise Exception(u"Too many deposittransactions for the same ID!")
elif dps.count() == 0:
deposit_tx = DepositTransaction.objects.create(wallet=ba.wallet,
address=ba,
amount=tx['amount'],
txid=tx[u'txid'],
confirmations=int(tx['confirmations']))
if deposit_tx.confirmations >= settings.BITCOIN_MINIMUM_CONFIRMATIONS:
ba.query_bitcoin_deposit(deposit_tx)
else:
ba.query_unconfirmed_deposits()
elif dps.count() == 1 and not dps[0].under_execution:
deposit_tx = dps[0]
if int(tx['confirmations']) >= settings.BITCOIN_MINIMUM_CONFIRMATIONS:
ba.query_bitcoin_deposit(deposit_tx)
if int(tx['confirmations']) > deposit_tx.confirmations:
DepositTransaction.objects.filter(id=deposit_tx.id).update(confirmations=int(tx['confirmations']))
elif dps.count() == 1:
print "already processed", dps[0].txid, dps[0].transaction
else:
print "FUFFUFUU"
cache.set("queried_block_index", max_query_block)
import sys
from cStringIO import StringIO
@task()
def check_integrity():
from django_bitcoin.models import Wallet, BitcoinAddress, WalletTransaction, DepositTransaction
from django_bitcoin.utils import bitcoind
from django.db.models import Avg, Max, Min, Sum
from decimal import Decimal
import sys
from cStringIO import StringIO
backup = sys.stdout
sys.stdout = StringIO()
bitcoinaddress_sum = BitcoinAddress.objects.filter(active=True)\
.aggregate(Sum('least_received_confirmed'))['least_received_confirmed__sum'] or Decimal(0)
print "Total received, sum", bitcoinaddress_sum
transaction_wallets_sum = WalletTransaction.objects.filter(from_wallet__id__gt=0, to_wallet__id__gt=0)\
.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
print "Total transactions, sum", transaction_wallets_sum
transaction_out_sum = WalletTransaction.objects.filter(from_wallet__id__gt=0)\
.exclude(to_bitcoinaddress="").exclude(to_bitcoinaddress="")\
.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
print "Total outgoing, sum", transaction_out_sum
# for x in WalletTransaction.objects.filter(from_wallet__id__gt=0, to_wallet__isnull=True, to_bitcoinaddress=""):
# print x.amount, x.created_at
fee_sum = WalletTransaction.objects.filter(from_wallet__id__gt=0, to_wallet__isnull=True, to_bitcoinaddress="")\
.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
print "Fees, sum", fee_sum
print "DB balance", (bitcoinaddress_sum - transaction_out_sum - fee_sum)
print "----"
bitcoind_balance = bitcoind.bitcoind_api.getbalance()
print "Bitcoind balance", bitcoind_balance
print "----"
print "Wallet quick check"
total_sum = Decimal(0)
for w in Wallet.objects.filter(last_balance__lt=0):
if w.total_balance()<0:
bal = w.total_balance()
# print w.id, bal
total_sum += bal
print "Negatives:", Wallet.objects.filter(last_balance__lt=0).count(), "Amount:", total_sum
print "Migration check"
tot_received = WalletTransaction.objects.filter(from_wallet=None).aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
tot_received_bitcoinaddress = BitcoinAddress.objects.filter(migrated_to_transactions=True)\
.aggregate(Sum('least_received_confirmed'))['least_received_confirmed__sum'] or Decimal(0)
tot_received_unmigrated = BitcoinAddress.objects.filter(migrated_to_transactions=False)\
.aggregate(Sum('least_received_confirmed'))['least_received_confirmed__sum'] or Decimal(0)
if tot_received != tot_received_bitcoinaddress:
print "wrong total receive amount! "+str(tot_received)+", "+str(tot_received_bitcoinaddress)
print "Total " + str(tot_received) + " BTC deposits migrated, unmigrated " + str(tot_received_unmigrated) + " BTC"
print "Migration check #2"
dts = DepositTransaction.objects.filter(address__migrated_to_transactions=False).exclude(transaction=None)
if dts.count() > 0:
print "Illegal transaction!", dts
if WalletTransaction.objects.filter(from_wallet=None, deposit_address=None).count() > 0:
print "Illegal deposit transactions!"
print "Wallet check"
for w in Wallet.objects.filter(last_balance__gt=0):
lb = w.last_balance
tb_sql = w.total_balance_sql()
tb = w.total_balance()
if lb != tb or w.last_balance != tb or tb != tb_sql:
print "Wallet balance error!", w.id, lb, tb_sql, tb
print w.sent_transactions.all().count()
print w.received_transactions.all().count()
print w.sent_transactions.all().aggregate(Max('created_at'))['created_at__max']
print w.received_transactions.all().aggregate(Max('created_at'))['created_at__max']
# Wallet.objects.filter(id=w.id).update(last_balance=w.total_balance_sql())
# print w.created_at, w.sent_transactions.all(), w.received_transactions.all()
# if random.random() < 0.001:
# sleep(1)
print "Address check"
for ba in BitcoinAddress.objects.filter(least_received_confirmed__gt=0, migrated_to_transactions=True):
dts = DepositTransaction.objects.filter(address=ba, wallet=ba.wallet)
s = dts.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
if s != ba.least_received:
print "DepositTransaction error", ba.address, ba.least_received, s
print "BitcoinAddress check"
for ba in BitcoinAddress.objects.filter(migrated_to_transactions=True):
dts = ba.deposittransaction_set.filter(address=ba, confirmations__gte=settings.BITCOIN_MINIMUM_CONFIRMATIONS)
deposit_sum = dts.aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
wt_sum = WalletTransaction.objects.filter(deposit_address=ba).aggregate(Sum('amount'))['amount__sum'] or Decimal(0)
if wt_sum != deposit_sum or ba.least_received_confirmed != deposit_sum:
print "Bitcoinaddress integrity error!", ba.address, deposit_sum, wt_sum, ba.least_received_confirmed
# if random.random() < 0.001:
# sleep(1)
integrity_test_output = sys.stdout.getvalue() # release output
# ####
sys.stdout.close() # close the stream
sys.stdout = backup # restore original stdout
mail_admins("Integrity check", integrity_test_output)
<file_sep>/django_bitcoin/__init__.py
from django_bitcoin.models import Payment, new_bitcoin_payment
from django_bitcoin.models import Wallet, BitcoinAddress
from django_bitcoin.utils import generateuniquehash, int2base64, base642int, bitcoinprice, bitcoinprice_usd
| 37e54b3791fe78568b47eeb12ea8df32fb0364f1 | [
"Python",
"reStructuredText"
] | 21 | Python | gugu/django-bitcoin | 443382143422cd97b572c6dab478302d7ccfc524 | 4899ba40a312c4a2245f5521f9a1bd15b5371619 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler38
{
class Program
{
static void Main(string[] args)
{
int maxPan = 0;
foreach(int n in Enumerable.Range(1, 200000))
{
string s = n.ToString();
foreach(int p in Enumerable.Range(2, 8))
{
s += p * n;
if (s.Length < 9)
continue;
if (s.Length > 9)
break;
if (is9Pandigital(s))
{
int num = Convert.ToInt32(s, 10);
if (maxPan < num)
maxPan = num;
break;
}
}
}
Console.WriteLine(maxPan);
Console.ReadLine();
}
static bool is9Pandigital(string s)
{
char[] carr = s.ToCharArray();
Array.Sort(carr);
return "123456789" == new string(carr);
}
}
}
| 1f1dc755c76cc24521598aa99f6abdb78e817b1f | [
"C#"
] | 1 | C# | jeremygibbons/Euler38 | 8bb26c7e38e648e4534f684f56c1abf6a7310ffc | 44036dddb67f217a560094b818d8db0ed970dc1d |
refs/heads/master | <file_sep>import tweepy
import time
import datetime
import os
def auth():
#finding creditentials from a file and saving them in a list
creditentials = []
creditPath = 'D:\\misc\\currentTrendsFinder\\currentTrendsFinderCreds.txt'
with open (creditPath,'r') as f:
for i in f:
creditentials.append(i.split()[-1][1:-1]) #getting rid of the extra stuff on the row
auth = tweepy.OAuthHandler(creditentials[0], creditentials[1]) #consumer_key, consumer_secret
auth.set_access_token(creditentials[2], creditentials[3]) #access_token, access_secret
api = tweepy.API(auth)
return api
def getTrends():
api = auth()
trendsObject = api.trends_place(1)
#try to understand why this works, and simplify / optimize
data = trendsObject[0]
trendList = data['trends']
#get trends by "name"
trendNames = [name['name'] for name in trendList]
print(trendNames)
writeTrendsToFile(trendNames)
def writeTrendsToFile(trendNames):
fileExtension = getNewFilename() #get filename from datetime timestamp
filename = 'D:\\misc\\currentTrendsFinder\\trendTexts\\trends' + fileExtension +'.txt'
with open(filename,'w',encoding='utf8') as f:
for i in trendNames:
try:
f.write(f'{i}\n')
except:
#Should never enter here anymore, encoding with file from open
f.write(f'{i.encode("utf-8")}\n')
print(f'UTF-8 Encoding: {i}')
def getNewFilename():
fileExtension = str(datetime.datetime.now().date()) + '_'
#using strftime to dump datetime as str, and preserving the leading zeroes (eg 08 instead of 8)
fileExtension += str(datetime.datetime.now().strftime("%H")) + '-'
fileExtension += str(datetime.datetime.now().strftime("%M"))
return fileExtension
def sleepCycle():
cycles = 60 #cycles * timePerCycle = fullSleepTime
timePerCycle = 6
endTime = cycles * timePerCycle
print('*** SLEEP CYCLE START ***')
print('Seconds slept: 0 /', endTime, end='\r')
for i in range(cycles):
time.sleep(timePerCycle)
print('Seconds slept:', (i+1)*timePerCycle, '/', endTime, end='\r')
print('*** NEXT CYCLE *** NEXT CYCLE *** NEXT CYCLE ***')
while True:
getTrends()
sleepCycle()<file_sep># twitterGetTrends
Twitter API testing and learning.
<file_sep>import glob
import itertools
def getFilenames():
path = 'D:\\misc\\currentTrendsFinder\\trendTexts\\'
#with list comprehension
txtFiles = [txt for txt in glob.glob(path+'*.txt')]
#opened in for loop
txtFiles = []
for txt in glob.glob(path + '*.txt'):
txtFiles.append(txt)
return txtFiles
def readTrends(txtFiles):
trends = []
for filename in txtFiles:
if 'currentTrendsFinderCreds.txt' in filename:
continue
with open (filename,'r',encoding='utf8') as f:
for i in f:
try:
trends.append(i)
#print(i.strip())
except:
#redundant as of now, keeping it here as a reminder
print('***Exception***')
utfStr = bytes([ord(c) for c in i.split('\'')[1]])
print(utfStr.decode())
return trends
def formatTrends(trends):
trendNumbers = []
trends.sort() #sorting the list for use with groupby
#groupby from itertools to count number of occurences
for key, grouper in itertools.groupby(trends):
groupLength = len(list(grouper))
trendNumbers.append([key.strip(), groupLength])
#sort by second column
sortedTrends = sorted(trendNumbers, key=lambda x: x[1], reverse=True)
for i in sortedTrends:
print(i)
txtFiles = getFilenames()
trends = readTrends(txtFiles)
formatTrends(trends) | 2e584264efa564ef52b8ce199307aa3daae05f9f | [
"Markdown",
"Python"
] | 3 | Python | KoskiKari/twitterGetTrends | 66bcaedb4bb97de4a231cea4d5b5d9df0b953240 | 82bdec4354998fb344e9d13290c1b95bd4ea1cb1 |
refs/heads/master | <file_sep>package com.nepninja.tvprogram.utils
object StringUtils {
@JvmStatic
fun capitalizeCategory(category: String): String {
if (category.contains(",")) {
return category.split(",").joinToString(",") { it.capitalize() }
}
return category.capitalize()
}
}<file_sep>buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0"
}
}
ext {
archLifecycleVersion = '2.2.0'
coreTestingVersion = '2.1.0'
materialVersion = '1.1.0'
coroutines = '1.3.4'
koinVersion = '2.0.1'
navigationVersion = '2.2.0'
androidXAnnotations = '1.0.1'
retrofitVersion = '2.9.0'
pagingVersion = "3.0.0-alpha01"
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}<file_sep>package com.nepninja.tvprogram
import android.app.Application
import com.nepninja.tvprogram.data.remote.Api
import com.nepninja.tvprogram.deatil.DetailViewModel
import com.nepninja.tvprogram.help.FaqViewModel
import com.nepninja.tvprogram.main.MainViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.dsl.module
class App : Application() {
override fun onCreate() {
super.onCreate()
val appModule = module {
viewModel {
MainViewModel(get(), get())
}
viewModel {
DetailViewModel(get())
}
viewModel { FaqViewModel(get()) }
single { Api.retrofitService }
}
startKoin {
androidLogger()
androidContext(this@App)
modules(listOf(appModule))
}
}
}<file_sep>package com.nepninja.tvprogram.program
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.databinding.FragmentProgramDetailBinding
import com.nepninja.tvprogram.utils.setTitle
class ProgramDetailFragment : Fragment() {
lateinit var binding: FragmentProgramDetailBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentProgramDetailBinding.inflate(inflater)
val program = ProgramDetailFragmentArgs.fromBundle(arguments!!).program
binding.program = program
program.title?.let { setTitle(it) }
return binding.root
}
}<file_sep>package com.nepninja.tvprogram.main
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.GridLayoutManager
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.base.BaseFragment
import com.nepninja.tvprogram.base.NavigationCommand
import com.nepninja.tvprogram.databinding.FragmentMainBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
class MainFragment : BaseFragment() {
override val _viewModel: MainViewModel by viewModel()
private lateinit var binding: FragmentMainBinding
private lateinit var adapter: TvProgramPageListAdapter
private var firstLoad: Boolean = true
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
binding.viewModel = _viewModel
binding.lifecycleOwner = this
setHasOptionsMenu(true)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
adapter = TvProgramPageListAdapter(callback = {
_viewModel.navigationCommand.postValue(
NavigationCommand.To(
MainFragmentDirections.actionMainFragmentToDetailFragment(it)
)
)
})
binding.rvChannels.layoutManager = GridLayoutManager(activity, 3)
binding.rvChannels.addItemDecoration(ItemOffsetDecoration(resources.getDimensionPixelSize(R.dimen.grid_item_spacing)))
binding.rvChannels.adapter = adapter
binding.rvChannels.adapter = adapter.withLoadStateHeaderAndFooter(
header = TvProgramLoadStateAdapter { adapter.retry() },
footer = TvProgramLoadStateAdapter { adapter.retry() }
)
adapter.addLoadStateListener { loadState ->
binding.rvChannels.isVisible = loadState.refresh is LoadState.NotLoading
binding.progressBar.isVisible = loadState.refresh is LoadState.Loading
binding.retryButton.isVisible = loadState.refresh is LoadState.Error
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
Toast.makeText(
activity,
"\uD83D\uDE28 Wooops ${it.error}",
Toast.LENGTH_LONG
).show()
}
}
binding.retryButton.setOnClickListener { adapter.retry() }
lifecycleScope.launch {
_viewModel.getChannels().collectLatest {
adapter.submitData(it)
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.main_overflow_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.help_faq -> findNavController().navigate(MainFragmentDirections.actionMainFragmentToHelpFaqFragment())
R.id.about -> findNavController().navigate(MainFragmentDirections.actionMainFragmentToAboutUsFragment())
}
return true
}
}<file_sep>package com.nepninja.tvprogram.help
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.base.BaseFragment
import com.nepninja.tvprogram.databinding.FragmentHelpFaqBinding
import com.nepninja.tvprogram.utils.setup
import org.koin.androidx.viewmodel.ext.android.viewModel
class HelpFaqFragment : BaseFragment() {
override val _viewModel: FaqViewModel by viewModel()
private lateinit var binding: FragmentHelpFaqBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_help_faq, container, false)
binding.viewModel = _viewModel
binding.lifecycleOwner = this
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val adapter = HelpFaqAdapter {}
binding.rvFaq.setup(adapter)
}
}<file_sep>package com.nepninja.tvprogram
object Constants {
const val API_URL = "https://veusat-epg.azurewebsites.net/"
const val CHANNEL = "channel"
const val PROGRAMME = "programme"
const val ID = "id"
const val ID_NUMBER = "idNo"
const val DISPLAY_NAME ="display-name"
const val ICON = "icon"
const val SRC = "src"
const val START_TIME = "start"
const val STOP_TIME = "stop"
const val TITLE = "title"
const val SUBTITLE = "sub-title"
const val CATEGORY = "category"
const val DESCRIPTION = "desc"
}<file_sep>package com.nepninja.tvprogram.deatil
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.base.BaseRecyclerViewAdapter
import com.nepninja.tvprogram.data.model.Programme
class ProgrammeListAdapter(callBack: (programme: Programme) -> Unit) :
BaseRecyclerViewAdapter<Programme>(callBack) {
override fun getLayoutRes(viewType: Int) = R.layout.program_item
}<file_sep>package com.nepninja.tvprogram.help
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.base.BaseRecyclerViewAdapter
import com.nepninja.tvprogram.data.model.Faq
class HelpFaqAdapter(callBack: (faq: Faq) -> Unit) :
BaseRecyclerViewAdapter<Faq>(callBack) {
override fun getLayoutRes(viewType: Int) = R.layout.help_faq_item
}<file_sep>package com.nepninja.tvprogram.utils
import android.util.Log
import com.nepninja.tvprogram.Constants
import com.nepninja.tvprogram.data.model.Channel
import com.nepninja.tvprogram.data.model.Programme
import com.nepninja.tvprogram.data.model.TvProgram
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.SAXException
import java.io.InputStream
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
object TvProgrammeParser {
private val TAG = TvProgrammeParser::class.simpleName
fun getTvProgrammes(inputStream: InputStream): List<TvProgram> {
val builderFactory = DocumentBuilderFactory.newInstance()
val docBuilder = builderFactory.newDocumentBuilder()
val doc = docBuilder.parse(inputStream)
val channelNodes: NodeList = doc.getElementsByTagName(Constants.CHANNEL)
val programmeNodes: NodeList = doc.getElementsByTagName(Constants.PROGRAMME)
val channels = getChannels(channelNodes)
val programmes = getProgrammes(programmeNodes)
return mapToTvProgrammes(channels, programmes)
}
private fun getChannels(
channelNodes: NodeList
): List<Channel> {
val channels = arrayListOf<Channel>()
try {
for (i in 0 until channelNodes.length) {
if (channelNodes.item(0).nodeType == Node.ELEMENT_NODE) {
val element = channelNodes.item(i) as Element
val id = element.attributes.getNamedItem(Constants.ID).nodeValue
val idNo = element.attributes.getNamedItem(Constants.ID_NUMBER).nodeValue
val displayName =
element.getElementsByTagName(Constants.DISPLAY_NAME)
.item(0)?.childNodes?.item(0)?.nodeValue
val icon = element.getElementsByTagName(Constants.ICON)
.item(0).attributes.getNamedItem(Constants.SRC).nodeValue
channels.add(Channel(id = id, idNo = idNo, name = displayName, src = icon))
}
}
} catch (e: ParserConfigurationException) {
Log.e(TAG, "Channel ParseConfiguration exception ${e.localizedMessage}")
} catch (e: SAXException) {
Log.e(TAG, "Channel SAXException exception ${e.localizedMessage}")
}
return channels
}
private fun getProgrammes(programmeNodes: NodeList): List<Programme> {
val programmes = arrayListOf<Programme>()
try {
for (i in 0 until programmeNodes.length) {
val element = programmeNodes.item(i) as Element
val id = element.attributes.getNamedItem(Constants.ID_NUMBER).nodeValue
val channelId = element.attributes.getNamedItem(Constants.CHANNEL).nodeValue
val startDate =
DateUtils.strToDate(element.attributes.getNamedItem(Constants.START_TIME).nodeValue)
val stopDate =
DateUtils.strToDate(element.attributes.getNamedItem(Constants.STOP_TIME).nodeValue)
val title =
element.getElementsByTagName(Constants.TITLE)
.item(0)?.childNodes?.item(0)?.nodeValue
val subTitle =
element.getElementsByTagName(Constants.SUBTITLE)
.item(0)?.childNodes?.item(0)?.nodeValue
val category =
element.getElementsByTagName(Constants.CATEGORY)
.item(0)?.childNodes?.item(0)?.nodeValue
val desc =
element.getElementsByTagName(Constants.DESCRIPTION)
.item(0)?.childNodes?.item(0)?.nodeValue
val icon = element.getElementsByTagName(Constants.ICON)
.item(0).attributes.getNamedItem(Constants.SRC).nodeValue
programmes.add(
Programme(
startDate = startDate,
stopDate = stopDate,
channelId = channelId,
idNo = id,
title = title,
subTitle = subTitle,
description = desc,
category = getCategories(category),
src = icon
)
)
}
} catch (e: ParserConfigurationException) {
Log.e(TAG, "Programme ParserConfigurationException exception ${e.localizedMessage}")
} catch (e: SAXException) {
Log.e(TAG, "Programme SAXException exception ${e.localizedMessage}")
}
return programmes
}
private fun getCategories(category: String?): String {
if (category.isNullOrEmpty()) return ""
if (category.contains("[") && category.contains("]")) {
return category.substringBefore("]").substringAfter("[")
}
return ""
}
private fun mapToTvProgrammes(
channels: List<Channel>,
programmes: List<Programme>
): List<TvProgram> {
// 0(n^2) can reduce this complexity 0(n)
// Will focus on later
val tvProgrammes = arrayListOf<TvProgram>()
channels.forEach { channel ->
tvProgrammes.add(
TvProgram(
programmes = programmes.filter { channel.idNo == it.idNo }.toList(),
channel = channel
)
)
}
return tvProgrammes
}
}<file_sep>package com.nepninja.tvprogram.deatil
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.nepninja.tvprogram.base.BaseViewModel
import com.nepninja.tvprogram.data.model.Programme
class DetailViewModel(app: Application) : BaseViewModel(app) {
var programmes: MutableLiveData<List<Programme>> = MutableLiveData()
}<file_sep>package com.nepninja.tvprogram.main
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.data.model.TvProgram
import com.nepninja.tvprogram.databinding.ChannelItemBinding
import com.nepninja.tvprogram.databinding.LoadStateFooterViewItemBinding
class TvProgramPageListAdapter(private val callback: ((item: TvProgram) -> Unit)? = null) :
PagingDataAdapter<TvProgram, TvProgramViewHolder>(DIFF_UTIL) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TvProgramViewHolder {
val binding: ChannelItemBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.channel_item,
parent,
false
)
return TvProgramViewHolder(binding)
}
override fun onBindViewHolder(holder: TvProgramViewHolder, position: Int) {
holder.binding.item = getItem(position)
holder.itemView.setOnClickListener {
getItem(position)?.let { it1 -> callback?.invoke(it1) }
}
}
companion object {
private val DIFF_UTIL = object : DiffUtil.ItemCallback<TvProgram>() {
override fun areItemsTheSame(oldItem: TvProgram, newItem: TvProgram): Boolean {
return oldItem.channel.id == newItem.channel.id
}
override fun areContentsTheSame(oldItem: TvProgram, newItem: TvProgram): Boolean {
return oldItem == newItem
}
}
}
}
class TvProgramViewHolder(itemView: ChannelItemBinding) :
RecyclerView.ViewHolder(itemView.root) {
var binding: ChannelItemBinding = itemView
}
class LoadStateViewHolder(
private val binding: LoadStateFooterViewItemBinding,
retry: () -> Unit
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.retryButton.setOnClickListener { retry.invoke() }
}
fun bind(loadState: LoadState) {
if (loadState is LoadState.Error) {
binding.errorMsg.text = loadState.error.localizedMessage
}
binding.progressBar.isVisible = loadState is LoadState.Loading
binding.retryButton.isVisible = loadState !is LoadState.Loading
binding.errorMsg.isVisible = loadState !is LoadState.Loading
}
companion object {
fun create(parent: ViewGroup, retry: () -> Unit): LoadStateViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.load_state_footer_view_item, parent, false)
val binding = LoadStateFooterViewItemBinding.bind(view)
return LoadStateViewHolder(binding, retry)
}
}
}
class TvProgramLoadStateAdapter(private val retry: () -> Unit) :
LoadStateAdapter<LoadStateViewHolder>() {
override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
holder.bind(loadState)
}
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder {
return LoadStateViewHolder.create(parent, retry)
}
}
<file_sep>package com.nepninja.tvprogram.help
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.nepninja.tvprogram.base.BaseViewModel
import com.nepninja.tvprogram.data.model.Faq
class FaqViewModel(app: Application) : BaseViewModel(app) {
var faqs: MutableLiveData<List<Faq>> = MutableLiveData()
init {
var data = arrayListOf(
Faq(
" Where are your application development centers based?",
"We have development centers in several cities across Ireland, US, and few of european country including Norway"
),
Faq(
"How many development resources do you usually assign to a project?",
"The number of resources employed for a project depends entirely upon the scale and complexity of the project. For example - we allocate two developers, one tester and a part-time UI designer for a small project. In addition, each project will have a Technical Architect, Business Analyst and Project Manager. We can increase the number of resources depending upon the customer/project requirements."
),
Faq(
"Can you provide the summary of the experience and skills of each of your application development resources?",
"We are bound by the confidentiality agreement, and will be unable to share these details. A large number of full-time developers are a part of our pool, working on different in-house and client projects. At different times, the available resources are different and unique. You can be assured that only the best quality, trained and experienced resources will work on your project and meet your requirements."
),
Faq(
" Where are your application development centers based?",
"We have development centers in several cities across Ireland, US, and few of european country including Norway"
),
Faq(
"How many development resources do you usually assign to a project?",
"The number of resources employed for a project depends entirely upon the scale and complexity of the project. For example - we allocate two developers, one tester and a part-time UI designer for a small project. In addition, each project will have a Technical Architect, Business Analyst and Project Manager. We can increase the number of resources depending upon the customer/project requirements."
),
Faq(
"Can you provide the summary of the experience and skills of each of your application development resources?",
"We are bound by the confidentiality agreement, and will be unable to share these details. A large number of full-time developers are a part of our pool, working on different in-house and client projects. At different times, the available resources are different and unique. You can be assured that only the best quality, trained and experienced resources will work on your project and meet your requirements."
),
Faq(
" Where are your application development centers based?",
"We have development centers in several cities across Ireland, US, and few of european country including Norway"
),
Faq(
"How many development resources do you usually assign to a project?",
"The number of resources employed for a project depends entirely upon the scale and complexity of the project. For example - we allocate two developers, one tester and a part-time UI designer for a small project. In addition, each project will have a Technical Architect, Business Analyst and Project Manager. We can increase the number of resources depending upon the customer/project requirements."
),
Faq(
"Can you provide the summary of the experience and skills of each of your application development resources?",
"We are bound by the confidentiality agreement, and will be unable to share these details. A large number of full-time developers are a part of our pool, working on different in-house and client projects. At different times, the available resources are different and unique. You can be assured that only the best quality, trained and experienced resources will work on your project and meet your requirements."
)
)
faqs.postValue(data)
}
}<file_sep>package com.nepninja.tvprogram.utils
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
object DateUtils {
private const val APP_DATE_FORMAT = "yyyyMMddHHmmss"
private const val APP_DATE_DISPLAY_FORMAT = "EEE, d MMM hh:mm aa"
fun strToDate(date: String): Date? {
return try {
val format = SimpleDateFormat(APP_DATE_FORMAT)
format.parse(date)
} catch (e: ParseException) {
null
}
}
@JvmStatic
fun dateToStr(date: Date): String {
return try {
val dateFormat = SimpleDateFormat(APP_DATE_DISPLAY_FORMAT)
return dateFormat.format(date)
} catch (e: ParseException) {
""
}
}
}<file_sep>package com.nepninja.tvprogram.data.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.util.*
@Parcelize
data class TvProgram(val channel: Channel, val programmes: List<Programme>) : Parcelable
@Parcelize
data class Channel(val id: String?, val idNo: String?, val name: String?, val src: String?) :
Parcelable
@Parcelize
data class Programme(
val startDate: Date?,
val stopDate: Date?,
val channelId: String?,
val idNo: String,
val title: String?,
val subTitle: String?,
val description: String?,
val category: String?,
val src: String?
) : Parcelable
data class Faq(val question: String, val answer: String)
<file_sep>package com.nepninja.tvprogram.data.respository
import androidx.paging.PagingSource
import com.nepninja.tvprogram.data.model.TvProgram
import com.nepninja.tvprogram.data.remote.TvProgramService
import com.nepninja.tvprogram.utils.TvProgrammeParser
import org.xml.sax.SAXParseException
import retrofit2.HttpException
import java.io.IOException
private const val STARTING_POSITION = 1
class TvProgramDataSource(
private val service: TvProgramService
) : PagingSource<Int, TvProgram>() {
val TAG = TvProgramDataSource::class.simpleName
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, TvProgram> {
val position = params.key ?: STARTING_POSITION
return try {
val response = service.getProgrammesAsync(position, params.loadSize + position).await()
val tvPrograms = TvProgrammeParser.getTvProgrammes(response.byteStream())
LoadResult.Page(
tvPrograms,
prevKey = null,
nextKey = if (tvPrograms.isEmpty()) null else position + params.loadSize
)
} catch (exception: IOException) {
LoadResult.Error(exception)
} catch (exception: HttpException) {
LoadResult.Error(exception)
} catch (exception: SAXParseException) {
LoadResult.Error(exception)
}
}
}<file_sep>package com.nepninja.tvprogram.deatil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.nepninja.tvprogram.R
import com.nepninja.tvprogram.base.BaseFragment
import com.nepninja.tvprogram.base.NavigationCommand
import com.nepninja.tvprogram.databinding.FragmentDetailBinding
import com.nepninja.tvprogram.main.ItemOffsetDecoration
import com.nepninja.tvprogram.main.MainFragmentDirections
import com.nepninja.tvprogram.utils.setDisplayHomeAsUpEnabled
import com.nepninja.tvprogram.utils.setTitle
import com.nepninja.tvprogram.utils.setup
import org.koin.androidx.viewmodel.ext.android.viewModel
class DetailFragment : BaseFragment() {
lateinit var binding: FragmentDetailBinding
override val _viewModel: DetailViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDetailBinding.inflate(inflater)
val tvProgram = DetailFragmentArgs.fromBundle(arguments!!).tvprogram
tvProgram.channel.name?.let { setTitle(it) }
binding.viewModel = _viewModel
binding.lifecycleOwner = this
_viewModel.programmes.value = tvProgram.programmes
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setupRecyclerView()
}
private fun setupRecyclerView() {
val adapter = ProgrammeListAdapter {
_viewModel.navigationCommand.postValue(
NavigationCommand.To(
DetailFragmentDirections.actionDetailFragmentToProgramDetailFragment(it)
)
)
}
val layoutManager = GridLayoutManager(activity, 2)
binding.rvProgrammes.addItemDecoration(
ItemOffsetDecoration(
resources.getDimensionPixelSize(
R.dimen.grid_item_spacing
)
)
)
binding.rvProgrammes.layoutManager = layoutManager
binding.rvProgrammes.setup(adapter)
}
}<file_sep>package com.nepninja.tvprogram.main
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import com.nepninja.tvprogram.base.BaseViewModel
import com.nepninja.tvprogram.data.model.TvProgram
import com.nepninja.tvprogram.data.remote.TvProgramService
import com.nepninja.tvprogram.data.respository.TvProgramDataSource
import com.nepninja.tvprogram.utils.TvProgrammeParser
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
class MainViewModel(
app: Application,
private val api: TvProgramService
) : BaseViewModel(app) {
fun getChannels(): Flow<PagingData<TvProgram>> {
return Pager(
config = PagingConfig(pageSize = 10, enablePlaceholders = true, initialLoadSize = 15),
pagingSourceFactory = { TvProgramDataSource(api) }
).flow.cachedIn(viewModelScope)
}
}<file_sep>package com.nepninja.tvprogram.data.remote
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.nepninja.tvprogram.Constants.API_URL
import kotlinx.coroutines.Deferred
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query
fun getClient(): OkHttpClient {
val logger = HttpLoggingInterceptor()
logger.setLevel(HttpLoggingInterceptor.Level.BODY)
logger.setLevel(HttpLoggingInterceptor.Level.BASIC)
logger.setLevel(HttpLoggingInterceptor.Level.HEADERS)
val okHttpClient = OkHttpClient()
okHttpClient.newBuilder().addInterceptor(logger)
return okHttpClient
}
private val retrofit = Retrofit
.Builder()
.client(getClient())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(API_URL)
.build()
interface TvProgramService {
@GET("epg.php")
fun getProgrammesAsync(
@Query("fromID") from: Int,
@Query("toID") to: Int
): Deferred<ResponseBody>
}
object Api {
val retrofitService: TvProgramService by lazy { retrofit.create(TvProgramService::class.java) }
}
| f5e9e01bae04b4df402f70914e05633a50f80c6a | [
"Kotlin",
"Gradle"
] | 19 | Kotlin | khadkarajesh/tvprogram | 8af09448081cb6bd9129ac082d3c9ca4fcc2030a | cd901a668d9b9ffc43aabdc1a0cb5cefd4d59892 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.dataTest;
import com.mycompany.dentalclinic.data.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Eddy
*/
public class CustomerFileDaoTest {
public final CustomersDao dao;
public CustomerFileDaoTest() {
dao = new CustomerFileDao("");
}
@Test
public void testAddCustomer() throws Exception {
}
@Test
public void testFindAllCustomers() throws Exception {
}
@Test
public void testFindCustomerByFristName() throws Exception {
}
@Test
public void testFindCustomerByLastName() throws Exception {
}
@Test
public void testFindCustomerByDateOfBirth() throws Exception {
}
@Test
public void testFindCustomerByID() throws Exception {
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine.dto;
import java.math.BigDecimal;
import static java.math.RoundingMode.DOWN;
/**
*
* @author Eddy
*/
public class Change {
private int quarters;
private int dimes;
private int nickels;
private int pennies;
public Change(BigDecimal change) {
BigDecimal hundred = new BigDecimal("100");
BigDecimal moneyInPennies = change.multiply(hundred);
BigDecimal quarter = new BigDecimal("25");
BigDecimal dime = new BigDecimal("10");
BigDecimal nickel = new BigDecimal("5");
BigDecimal numberOfQuaters = moneyInPennies.divide(quarter, 0, DOWN);
BigDecimal moneyToSubtract = numberOfQuaters.multiply(quarter);
moneyInPennies = moneyInPennies.subtract(moneyToSubtract);
BigDecimal numberOfDimes = moneyInPennies.divide(dime, 0, DOWN);
moneyToSubtract = numberOfDimes.multiply(dime);
moneyInPennies = moneyInPennies.subtract(moneyToSubtract);
BigDecimal numberOfNickels = moneyInPennies.divide(nickel, 0, DOWN);
moneyToSubtract = numberOfNickels.multiply(nickel);
moneyInPennies = moneyInPennies.subtract(moneyToSubtract);
BigDecimal numberOfPennies = moneyInPennies;
quarters = numberOfQuaters.intValue();
dimes = numberOfDimes.intValue();
nickels = numberOfNickels.intValue();
pennies = numberOfPennies.intValue();
// this.quarters = numberOfQuaters.intValue();
// this.dimes = numberOfDimes.intValue();
// this.nickels = numberOfNickels.intValue();
// this.pennies = numberOfPennies.intValue();
}
public Change(Change change) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public int getQuarters() {
return quarters;
}
public void setQuarters(int quarters) {
this.quarters = quarters;
}
public int getDimes() {
return dimes;
}
public void setDimes(int dimes) {
this.dimes = dimes;
}
public int getNickels() {
return nickels;
}
public void setNickels(int nickels) {
this.nickels = nickels;
}
public int getPennies() {
return pennies;
}
public void setPennies(int pennies) {
this.pennies = pennies;
}
}
<file_sep>package com.mycompany.dentalclinic.ui;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class ConsoleIO {
private static final String INVALID_NUMBER
= "[INVALID] Enter a valid number.";
private static final String NUMBER_OUT_OF_RANGE
= "[INVALID] Enter a number between %s and %s.";
private static final String REQUIRED
= "[INVALID] Value is required.";
private final Scanner scanner = new Scanner(System.in);
public void print(String message) {
System.out.println(message);
}
public String readString(String prompt) {
print(prompt);
return scanner.nextLine();
}
public String readRequiredString(String prompt) {
while (true) {
String result = readString(prompt);
if (!result.isBlank()) {
return result;
}
print(REQUIRED);
}
}
public double readDouble(String prompt) {
while (true) {
try {
return Double.parseDouble(readRequiredString(prompt));
} catch (NumberFormatException ex) {
print(INVALID_NUMBER);
}
}
}
public double readDouble(String prompt, double min, double max) {
while (true) {
double result = readDouble(prompt);
if (result >= min && result <= max) {
return result;
}
print(String.format(NUMBER_OUT_OF_RANGE, min, max));
}
}
public int readInt(String prompt) {
while (true) {
try {
return Integer.parseInt(readRequiredString(prompt));
} catch (NumberFormatException ex) {
print(INVALID_NUMBER);
}
}
}
public int readInt(String prompt, int min, int max) {
while (true) {
int result = readInt(prompt);
if (result >= min && result <= max) {
return result;
}
print(String.format(NUMBER_OUT_OF_RANGE, min, max));
}
}
public boolean readBoolean(String prompt) {
while (true) {
String input = readRequiredString(prompt).toLowerCase();
if (input.equals("y")) {
return true;
} else if (input.equals("n")) {
return false;
}
print("[INVALID] Please enter 'y' or 'n'.");
}
}
public BigDecimal readBigDecimal(String prompt) {
String string;
print(prompt);
while(true) {
string = scanner.nextLine();
if(string.matches("\\d*\\.\\d{0,2}")) return new BigDecimal(string);
print("Enter money example: 'dollars.cents'");
}
}
public LocalTime readTime(String prompt) {
boolean valid = false;
LocalTime result = null;
do {
String value = null;
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
value = readString(prompt);
result = LocalTime.parse(value, formatter);
valid = true;
} catch (DateTimeParseException ex) {
System.out.println("Sorry, the input is not in the valid time format. (HH:mm)\n");
}
} while (!valid);
return result;
}
public LocalTime readLocalTime(String prompt) {
while (true) {
try {
LocalTime.parse(readRequiredString(prompt));
} catch (NumberFormatException ex){
print("[INVALID TIME]");
}
}
}
public LocalDate readLocalDate(String prompt) {
print(prompt);
boolean success = false;
while (!success) {
String userInput = scanner.nextLine();
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate parsedDate = LocalDate.parse(userInput, formatter);
success = true;
return parsedDate;
} catch (DateTimeParseException e) {
System.out.println("[INVALID DATE FORMAT]" + prompt);
}
}
return null;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.serviceTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Eddy
*/
public class AppointmentServiceTest {
public AppointmentServiceTest() {
}
@Test
public void testFindByProLastNameAndDate() throws Exception {
}
@Test
public void testUpDateAppointment() {
}
@Test
public void testCancelAppointment() {
}
@Test
public void testFindCustomerIdAndDate() {
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.models;
/**
*
* @author Eddy
*/
public enum SpecialtyType {
DENTIST(0, "DENTIST", 15, 300),
HYGIENIST(1, "HYGIENIST", 30, 300),
ORTHODONTIST(2, "ORTHODONTIST", 30, 300),
ORAL_SURGEON(3, "ORAL_SURGEON", 30, 600);
private int value;
private String name;
private int minVisit;
private int maxVisit;
private SpecialtyType(int value, String name, int minVisit, int maxVisit) {
this.value = value;
this.name = name;
this.minVisit = minVisit;
this.maxVisit = maxVisit;
}
@Override
public String toString() {
return this.name;
}
public int getMinVisit() {
return minVisit;
}
public int getMaxVisit() {
return maxVisit;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.data;
import com.mycompany.dentalclinic.models.Appointment;
import com.mycompany.dentalclinic.models.SpecialtyType;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Eddy
*/
public class AppointmentsFileDao extends FileDao<Appointment> implements AppointmentsDao {
private static final String HEADER = "customer_id,dental_pro_lastname,specialty,start_time,end_time,total_cost,notes";
// public AppointmentsFileDao(String FILE_PATH) {
// super(FILE_PATH, 7, true);
// }
public AppointmentsFileDao() {
super("", 7, true);
}
@Override
public List<Appointment> findByDate(LocalDate date) {
filePathStuff(date);
try {
List<Appointment> apptForDate = read(this::mapToAppointment).stream()
.collect(Collectors.toList());
for (Appointment a : apptForDate) {
a.setDate(date);
}
return apptForDate;
} catch (DataException ex) {
return new ArrayList<>();
}
}
@Override
public void addAppointment(Appointment appointment, LocalDate date) throws DataException {
filePathStuff(date);
List<Appointment> appointments = findByDate(date);
appointments.add(appointment);
// write((Collection<Appointment>)appointments, this::mapToString);
write(appointments, this::mapToString, HEADER);
// append(appointment, this::mapToString);
}
@Override
public boolean deleteAppointment(int customerId, LocalDate date, SpecialtyType type) throws DataException {
filePathStuff(date);
read(this::mapToAppointment);
List<Appointment> list = findByDate(date);
list.removeIf(a -> a.getCustomerId() == customerId && a.getType().equals(type));
write(list, (appointment) -> this.mapToString(appointment), "customer_id,dental_pro_lastname,specialty,start_time,end_time,total_cost,notes");
return true;
}
@Override
public boolean updateAppointment(Appointment appointment, LocalDate date) {
List<Appointment> appointments = findByDate(appointment.getDate());
int index = 0;
for (; index < appointments.size(); index++) {
Appointment current = appointments.get(index);
if (current.getCustomerId() == appointment.getCustomerId() && current.getType() == appointment.getType()) {
break;
}
}
if (index < appointments.size()) {
appointments.set(index, appointment);
try {
write(appointments, (appointment1) -> this.mapToString(appointment1), "customer_id,dental_pro_lastname,specialty,start_time,end_time,total_cost,notes");
} catch (DataException ex) {
}
return true;
}
return false;
}
// @Override
// public boolean updateAppointment(Appointment appointment) throws DataException {
//
// List<Appointment> allappointment = findByDate(appointment.getDate());
//
// int index = 0;
// for (; index < allappointment.size(); index++) {
// if (allappointment.get(index).getCustomerId() == appointment.getCustomerId()
// && allappointment.get(index).getType() == appointment.getType()) {
// allappointment.remove(index);
// write (allappointment, this::mapToString);
// return true;
// }
// }
// return false;
// }
@Override
public List<Appointment> findByDateAndSpecialty(LocalDate date, SpecialtyType type) {
return findByDate(date).stream()
.filter(s -> s.getType().equals(type))
.collect(Collectors.toList());
}
@Override
public List<Appointment> findByLocalDateAndProLast(LocalDate date, String lastName) {
filePathStuff(date);
try {
// tmp mean temp
List<Appointment> apptForDate = read(this::mapToAppointment).stream()
.filter((a) -> a.getDentalProLastname().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
for (Appointment a : apptForDate) {
a.getDate();
}
return apptForDate;
} catch (DataException ex) {
return new ArrayList<>();
}
}
@Override
public List<Appointment> findCustomerIdAndDate(int customerId, LocalDate date) throws DataException {
filePathStuff(date);
return findByDate(date).stream()
.filter((a) -> a.getCustomerId() == (customerId))
.collect(Collectors.toList());
}
private String mapToString(Appointment appointments) {
return String.format("%s,%s,%s,%s,%s,%s,%s",
appointments.getCustomerId(),
appointments.getDentalProLastname(),
appointments.getType(),
appointments.getStart(),
appointments.getEnd(),
appointments.getTotalCost(),
appointments.getNotes());
}
private Appointment mapToAppointment(String[] tokens) {
return new Appointment(
Integer.parseInt(tokens[0]),
tokens[1],
SpecialtyType.valueOf(tokens[2]),
LocalTime.parse(tokens[3]),
LocalTime.parse(tokens[4]),
new BigDecimal(tokens[5]),
tokens[6]);
}
public void filePathStuff(LocalDate date) {
// date.format()
DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("yyyyMMdd");
String dateToString = date.toString();
String[] dateArray = dateToString.split("-");
// // Remove whatever in the date
// dateToString = dateToString.replace("_", "");
// super.setFILE_PATH(String.format("My Path", dateToString));
super.setFILE_PATH("appointments" + "_" + date.format(formatDate) + ".txt");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.moviedatabase.controller;
import com.mycompany.moviedatabase.dao.DataException;
import com.mycompany.moviedatabase.dao.MovieDataBaseDao;
import com.mycompany.moviedatabase.dto.Movie;
import com.mycompany.moviedatabase.ui.MovieDataBaseView;
import com.mycompany.moviedatabase.ui.UserIO;
import com.mycompany.moviedatabase.ui.UserIOConsoleImpl;
import java.util.List;
/**
*
* @author Eddy
*/
public class MovieDataBaseController {
private final MovieDataBaseView view;
private final MovieDataBaseDao dao;
public MovieDataBaseController(MovieDataBaseView view, MovieDataBaseDao dao) {
this.view = view;
this.dao = dao;
}
private final UserIO io = new UserIOConsoleImpl();
public void run() throws DataException {
int menuSelection = 0;
do {
menuSelection = view.printMenuAndGetSelection();
switch (menuSelection) {
case 1:
addMovie();
break;
case 2:
deleteMovie();
break;
case 3:
editMovie();
break;
case 4:
viewMovieById();
break;
case 5:
displayAllMovies();
break;
case 6:
movieSearchByTitle();
break;
}
} while (menuSelection > 0);
view.sayGoodbye();
}
public void addMovie() {
Movie newMovie = view.createMovie();
try {
dao.create(newMovie);
} catch (DataException ex) {
view.errorMessage(ex);
}
view.displaySuccess(newMovie.getTitle() + " was added!");
}
private void displayAllMovies() {
try {
List<Movie> all = dao.getAllMovies();
view.displayMovies(all);
} catch (DataException ex) {
view.errorMessage(ex);
}
}
private void editMovie() {
int movieId = view.readMovieId("Edit Movie");
try {
Movie movie = dao.getMoviebyId(movieId);
if (movie == null) {
view.displayMessage("Movie Id " + movieId + " not found.");
return;
}
movie = view.updateMovie(movie);
if (dao.updateMovie(movie)) {
view.displayMessage(movie.getTitle() + " Update Completed!");
} else {
view.displayMessage("Movie Id " + movieId + " not found.");
}
} catch (DataException ex) {
view.errorMessage(ex);
}
}
private void movieSearchByTitle() {
try {
view.searchByTitleBanner();
String aTitle = view.getMovieSearched();
List<Movie> results = dao.searchByTitle(aTitle);
view.displayMovies(results);
} catch (DataException ex) {
view.errorMessage(ex);
}
}
private void deleteMovie() {
try {
int movieId = view.readMovieId("Delete Movie!");
if (dao.deleteMovie(movieId)) {
view.displayMessage("Movie Id " + movieId + " deleted.");
} else {
view.displayMessage("Movie Id " + movieId + " not found.");
}
} catch (DataException ex) {
view.errorMessage(ex);
}
}
private void viewMovieById() throws DataException {
int movieId = view.readMovieId("Movie Id Search");
Movie movie = dao.getMoviebyId(movieId);
view.displayMovie(movie);
}
}
<file_sep>
package com.mycompany.vendingmachine.dao;
import com.mycompany.vendingmachine.dto.VendingMachineItems;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class VendingMachineStubDao {
private final static String TEST_PATH = "test-inventory.txt";
VendingMachineDaoFileImpl dao = new VendingMachineDaoFileImpl(TEST_PATH);
public VendingMachineStubDao(){
}
@BeforeAll
public static void setup() throws IOException {
Files.copy(Paths.get("test-inventory.txt"),
Paths.get(TEST_PATH),
StandardCopyOption.REPLACE_EXISTING);
}
@Test
public void testGetAllItems() {
List<VendingMachineItems> all = dao.getAllItems();
assertEquals(6, all.size());
}
@Test
public void testGetItemById() {
VendingMachineItems v = dao.getItemById(1);
assertNotNull(v);
assertEquals("Ginger ale", v.getItemName());
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.moviedatabase.ui;
import com.mycompany.moviedatabase.dao.DataException;
import com.mycompany.moviedatabase.dto.Movie;
import java.util.List;
/**
*
* @author Eddy
*/
public class MovieDataBaseView {
private final UserIOConsoleImpl io;
public MovieDataBaseView(UserIOConsoleImpl io) {
this.io = io;
}
public int printMenuAndGetSelection() {
io.print("Main Menu");
io.print("==============");
io.print("1. Add New Movie!");
io.print("2. Remove a Movie.");
io.print("3. Edit the Information for an Existing Movie.");
io.print("4. Display information for a single Movie by movie ID.");
io.print("5. List all Movies in the database.");
io.print("6. Search Movies in the database by Title.");
io.print("0. Exit");
return io.readInt("Please select from the above choices.", 0, 6);
}
public void sayGoodbye() {
io.print("\nGoodbye");
}
// *************************************************************************
public void searchByTitleBanner(){
io.print("\nSearch Movie By Title");
io.print("========================");
}
public String getMovieSearched(){
String search = io.readString("Please enter movie title to begin search.");
return search;
}
// *************************************************************************
public Movie createMovie() {
io.print("\nAdd new Movie");
io.print("===============");
Movie newMovie = new Movie();
io.print("Please add new movie title.");
newMovie.setTitle(io.readString(""));
newMovie.setReleaseDate(io.readString("Please enter movie release date."));
newMovie.setMpaaRating(io.readString("Please enter movie MPAA Rating."));
newMovie.setDirectorsName(io.readString("Please enter directors Name."));
newMovie.setStudio(io.readString("Please enter movie studio's name."));
newMovie.setUserRating(io.readString("Please enter User Ratings"));
newMovie.setMovieId(io.readInt("Please enter movie ID"));
return newMovie;
}
public int readMovieId(String header) {
io.print("");
io.print(header);
io.print("================");
return io.readInt("Please enter Movie Id:");
}
public void displayMovies(List<Movie> all) {
io.print("");
io.print("\nAll Movies");
io.print("=================");
if (all.isEmpty()) {
io.print("No movies found");
return;
}
for (Movie m : all){
io.print(m.getMovieId() + ": " + m.getTitle() + ": " + m.getReleaseDate()
+ ": " + m.getMpaaRating() + ": " + m.getDirectorsName() + ": " + m.getStudio()
+ ": " + m.getUserRating());
}
}
public void displayMovie(Movie movie){
if (movie != null){
io.print(movie.getTitle());
io.print(movie.getReleaseDate());
io.print(movie.getMpaaRating());
io.print(movie.getDirectorsName());
io.print(movie.getStudio());
io.print(movie.getUserRating());
} else {
io.print("No movie found.");
}
io.readString("Please hit enter to continue.");
}
public void errorMessage(DataException ex) {
io.readString(ex.getMessage() + "\nPress enter to continue");
}
public void displaySuccess(String prompt) {
io.readString(prompt + "\nPress enter to continue");
}
public void displayMessage(String message) {
io.print(message);
}
public Movie updateMovie(Movie movie) {
String title = io.readString(
String.format("Please enter title (%s):", movie.getTitle()));
if (!title.isEmpty()){
movie.setTitle(title);
}
String releaseDate = io.readString(
String.format("Please enter release date (%s):", movie.getReleaseDate()));
if (!releaseDate.isEmpty()){
movie.setReleaseDate(releaseDate);
}
String mpaaRating = io.readString(
String.format("Please enter MPAA Rating (%s):", movie.getMpaaRating()));
if (!mpaaRating.isEmpty()){
movie.setMpaaRating(mpaaRating);
}
String directorsName = io.readString(
String.format("Please enter Directors Name (%s):", movie.getDirectorsName()));
if (!directorsName.isEmpty()){
movie.setDirectorsName(directorsName);
}
String studio = io.readString(
String.format("Please enter studio (%s):", movie.getStudio()));
if (!studio.isEmpty()){
movie.setStudio(studio);
}
String userRating = io.readString(
String.format("Please enter User Rating (%s):", movie.getUserRating()));
if(!userRating.isEmpty()){
movie.setUserRating(userRating);
}
return movie;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine.ui;
import com.mycompany.vendingmachine.dao.DataException;
import com.mycompany.vendingmachine.dto.VendingMachineItems;
import java.math.BigDecimal;
import java.util.List;
/**
*
* @author Eddy
*/
public class VendingMachineView {
private UserIO io;
public VendingMachineView(UserIO io) {
this.io = io;
}
public void displayItems(List<VendingMachineItems> all) {
io.print("=============================");
io.print("=====The Vending Machine=====");
io.print("========INVENTORY LIST=======");
io.print("=============================");
for (VendingMachineItems item : all) {
io.print(item.getItemName());
io.print("Vending ID:" + item.getItemId());
io.print("Price: " + item.getItemCost());
io.print("Total Inventory:" + item.getNumberOfItemsInInventory());
io.print("=============================");
}
}
public int printMenuAndGetSelection() {
io.print("========Main Menu==========");
io.print("1. Add Funds");
io.print("0. Exit");
io.print("============================");
return io.readInt("Please select from the main menu options.", 0, 1);
}
public BigDecimal addFunds() {
BigDecimal fundsAdded = io.readBigDecimal("Please enter funds:");
return fundsAdded;
}
public void sayGoodbye() {
io.print("\nGoodbye");
}
public void errorMessage(Exception ex) {
io.readString(ex.getMessage() + "\nPress enter to continue");
}
public int selectItem() {
int itemSelection = io.readInt("Please select an Item using the Vending ID: ");
return itemSelection;
}
public void changeToDisplay(int quarters, int dimes, int nickels, int pennies) {
io.print("Thank you for your purchase! ");
io.print("Please collect your change. ");
io.print(quarters + "-Quarters " + dimes + "-Dimes " + nickels + "-Nickels " + pennies + "-Pennies");
io.print("");
}
}
<file_sep>package com.mycompany.dentalclinic.data;
public class DataException extends Exception {
public DataException(String message) {
super(message);
}
public DataException(String message, Throwable innerEx) {
super(message, innerEx);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.serviceTest;
import com.mycompany.dentalclinic.service.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Eddy
*/
public class CustomerServiceTest {
public CustomerServiceTest() {
}
@Test
public void testAdd() {
}
@Test
public void testFindByLastNameStartingWith() {
}
@Test
public void testGetAllCustomers() {
}
@Test
public void testCustomerDuplicationCheck() {
}
}
<file_sep>package com.mycompany.dentalclinic.data;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
public abstract class FileDao<T> {
// change !final give it getter and setter
private String FILE_PATH;
private final int columnCount;
private final boolean hasHeaders;
public FileDao(String FILE_PATH, int columnCount, boolean hasHeaders) {
this.FILE_PATH = FILE_PATH;
this.columnCount = columnCount;
this.hasHeaders = hasHeaders;
}
// call
public String getFILE_PATH() {
return FILE_PATH;
}
public void setFILE_PATH(String FILE_PATH) {
this.FILE_PATH = FILE_PATH;
}
public List<T> read(Function<String[], T> mapper) throws DataException {
ArrayList<T> result = new ArrayList<>();
try ( BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
if (hasHeaders) { // throw out header...
reader.readLine();
}
String line;
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(",");
if (tokens.length == columnCount) {
T obj = mapper.apply(tokens);
if (obj != null) {
result.add(obj);
}
}
}
} catch (IOException ex) {
throw new DataException(ex.getMessage(), ex);
}
return result;
}
public void write(Collection<T> items, Function<T, String> mapper, String header) throws DataException {
try ( PrintWriter writer = new PrintWriter(FILE_PATH)) {
if (this.hasHeaders) {
writer.println(header);
}
for (T obj : items) {
if (obj != null) {
writer.println(mapper.apply(obj));
}
}
} catch (IOException ex) {
throw new DataException(ex.getMessage(), ex);
}
}
public void append(T item, Function<T, String> mapper) throws DataException {
try ( PrintWriter writer = new PrintWriter(new FileWriter(FILE_PATH, true))) {
writer.println(mapper.apply(item));
} catch (IOException ex) {
throw new DataException(ex.getMessage(), ex);
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine.controller;
import com.mycompany.vendingmachine.dao.DataException;
import com.mycompany.vendingmachine.dto.Change;
import com.mycompany.vendingmachine.dto.VendingMachineItems;
import com.mycompany.vendingmachine.service.InsufficientFundsException;
import com.mycompany.vendingmachine.service.NotFoundException;
import com.mycompany.vendingmachine.service.OutOfStockException;
import com.mycompany.vendingmachine.service.VendingMachineItemsService;
import com.mycompany.vendingmachine.ui.VendingMachineView;
import java.math.BigDecimal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Eddy
*/
public class VendingMachineController {
private final VendingMachineView view;
private final VendingMachineItemsService service;
public VendingMachineController(VendingMachineView view, VendingMachineItemsService service) {
this.view = view;
this.service = service;
}
public void run() {
int selection = 0;
do {
List<VendingMachineItems> all = service.getAllItems();
view.displayItems(all);
selection = view.printMenuAndGetSelection();
switch (selection) {
case 1:
buyItem();
break;
}
} while (selection > 0);
view.sayGoodbye();
}
private void buyItem() {
boolean hasErrors = false;
do{
BigDecimal addFunds = view.addFunds();
int selectItem = view.selectItem();
try {
BigDecimal changeMath = service.purchase(selectItem, addFunds);
returnChangeMath(changeMath);
hasErrors = false;
} catch(DataException ex) {
view.errorMessage(ex);
} catch (NotFoundException ex) {
view.errorMessage(ex);
} catch (OutOfStockException ex) {
view.errorMessage(ex);
} catch (InsufficientFundsException ex) {
view.errorMessage(ex);
}
} while (hasErrors);
}
private void returnChangeMath(BigDecimal money) {
Change change = new Change(money);
int quarters = change.getQuarters();
int dimes = change.getDimes();
int nickels = change.getNickels();
int pennies = change.getPennies();
view.changeToDisplay(quarters, dimes, nickels, pennies);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rockpaperscissors;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author Eddy
*/
public class RockPaperScissors {
public static void main(String[] args) {
int rock = 1;
int paper = 2;
int scissors = 3;
int gameRounds;
int userInput;
int cpuInput;
Scanner input = new Scanner(System.in);
Random number = new Random();
// Loop asking the user if they want to play again.
do {
// The Game
System.out.println("Rock, Paper, Scissors");
System.out.println("Please enter amount of rounds. Max: 10 Minimal: 1");
gameRounds = input.nextInt();
if (gameRounds <= 10 && gameRounds >= 1) {
int tied = 0;
int playerWins = 0;
int computerWins = 0;
for (int i = 1; i <= gameRounds; i++) {
// // Player
// do {
//
// System.out.println("Player one please enter input: Rock = 1: Paper = 2: Scissors = 3");
// userInput = input.nextInt();
// if ((userInput < 1 || userInput > 3)) {
// System.out.println("Player one please enter a valid input Rock = 1: Paper = 2: Scissors = 3");
// }
// } while (userInput < 1 || userInput > 3);
// Computer Player
cpuInput = number.nextInt(3) + 1;
System.out.println("Computer Player entered: " + cpuInput);
// Tied if statements
if (userInput == cpuInput) {
tied++;
System.out.println("Draw please try again");
} // Player one win if statements.
else if (userInput == rock && cpuInput == scissors || userInput == scissors && cpuInput == paper || userInput == paper && cpuInput == rock) {
playerWins++;
System.out.println("Player one wins!");
} // Computer Player win if statements.
else if (userInput == paper && cpuInput == rock || userInput == paper && cpuInput == scissors || userInput == rock && cpuInput == paper) {
computerWins++;
System.out.println("Computer Player wins!");
}
}
// Total Game Results
System.out.println("\nYour Rock, Paper, Scissors Total");
System.out.println("==================================");
System.out.println("Player One Score: " + playerWins);
System.out.println("Computer Player Score: " + computerWins);
System.out.println("Tied Games " + tied);
if (playerWins > computerWins) {
System.out.println("The Winner Of This Set Goes To Player One!");
} else if (playerWins == computerWins) {
System.out.println("Draw!");
} else {
System.out.println("The Winner Of This Set Goes To Computer Player!");
}
} else {
System.out.println("Invalid Entry: Game Over");
}
} while (getAnswer("Do you want to play again? [y/n]"));
System.out.println("Game Over!");
System.out.println("Thanks for playing!");
}
public static boolean getAnswer(String prompt) {
Scanner input = new Scanner(System.in);
System.out.println(prompt);
return input.nextLine().equalsIgnoreCase("y");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.models;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
/**
*
* @author Eddy
*/
public class Appointment {
private int customerId;
private String dentalProLastname;
private SpecialtyType type;
private LocalTime start;
private LocalTime end;
private BigDecimal totalCost;
private String notes;
private LocalDate date;
public Appointment (){
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Appointment(int customerId, String dentalProLastname, SpecialtyType type, LocalTime start, LocalTime end, BigDecimal totalCost, String notes) {
this.customerId = customerId;
this.dentalProLastname = dentalProLastname;
this.type = type;
this.start = start;
this.end = end;
this.totalCost = totalCost;
this.notes = notes;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getDentalProLastname() {
return dentalProLastname;
}
public void setDentalProLastname(String dentalProLastname) {
this.dentalProLastname = dentalProLastname;
}
public SpecialtyType getType() {
return type;
}
public void setType(SpecialtyType type) {
this.type = type;
}
public LocalTime getStart() {
return start;
}
public void setStart(LocalTime start) {
this.start = start;
}
public LocalTime getEnd() {
return end;
}
public void setEnd(LocalTime end) {
this.end = end;
}
public BigDecimal getTotalCost() {
return totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.dataTest;
import com.mycompany.dentalclinic.data.CustomersDao;
import com.mycompany.dentalclinic.data.DataException;
import com.mycompany.dentalclinic.models.Customer;
import java.time.LocalDate;
import java.util.List;
/**
*
* @author Eddy
*/
public class CustomerFileDaoTestStub implements CustomersDao{
@Override
public void addCustomer(Customer customer) throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Customer> findAllCustomers() throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Customer> findCustomerByFristName(String firstName) throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Customer> findCustomerByLastName(String lastName) throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Customer> findCustomerByDateOfBirth(LocalDate getDateOfBirth) throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Customer findCustomerByID(int customerId) throws DataException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>This is a Rock Paper Sissors game made in Java.
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.service;
import com.mycompany.dentalclinic.data.DataException;
import com.mycompany.dentalclinic.data.ProfessionalDao;
import com.mycompany.dentalclinic.models.Professional;
import com.mycompany.dentalclinic.models.SpecialtyType;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Eddy
*/
public class ProfessionalService {
private ProfessionalDao professionalDao;
public ProfessionalService(ProfessionalDao professionalDao) {
this.professionalDao = professionalDao;
}
// public List<Professional> findByProLastNameWith(String prefix) {
//
// }
public List<Professional> findByProLastNameStartingWith(String prefix) {
try {
return professionalDao.findByProfessionalLastName(prefix);
} catch (DataException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public List<Professional> getAllProfessionals() throws DataException{
return professionalDao.findAllProfessional();
}
public List<Professional> findByProLastName(String prefix){
try {
return professionalDao.findByProfessionalLastName(prefix);
} catch (DataException ex) {
Logger.getLogger(ProfessionalService.class.getName()).log(Level.SEVERE, null, ex);
}
return new ArrayList<>();
}
public List<Professional> searchAllProsBySpecialtyType(SpecialtyType type) {
try {
return professionalDao.findByProfessionalSpecialty(type);
} catch (DataException ex) {
Logger.getLogger(ProfessionalService.class.getName()).log(Level.SEVERE, null, ex);
}
return new ArrayList<>();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.data;
import java.util.List;
import com.mycompany.dentalclinic.models.Customer;
import java.time.LocalDate;
/**
*
* @author Eddy
*/
public interface CustomersDao {
void addCustomer (Customer customer) throws DataException;
List<Customer> findAllCustomers() throws DataException;
List<Customer> findCustomerByFristName(String firstName) throws DataException; // ???
List<Customer> findCustomerByLastName(String lastName) throws DataException;
List<Customer> findCustomerByDateOfBirth(LocalDate getDateOfBirth) throws DataException;
Customer findCustomerByID(int customerId) throws DataException;
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.data;
import com.mycompany.dentalclinic.models.Professional;
import com.mycompany.dentalclinic.models.SpecialtyType;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author Eddy
*/
public class ProfessionalFileDao extends FileDao<Professional> implements ProfessionalDao {
public ProfessionalFileDao(String path) {
super(path, 5, true);
}
@Override
public List<Professional> findAllProfessional() throws DataException {
return read(this::mapToProfessional).stream()
.collect(Collectors.toList());
}
@Override
public Professional findByProfessionalId(int professionalId) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getProfessionalId() == (professionalId))
.findFirst()
.orElse(null);
}
@Override
public List<Professional> findByProfessionalFirstName(String professionalFirstName) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getProfessionalFirstName().equals(professionalFirstName))
.collect(Collectors.toList());
}
@Override
public List<Professional> findByProfessionalLastName(String professionalLastName) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getProfessionalFirstName().startsWith(professionalLastName))
.collect(Collectors.toList());
}
@Override
public List<Professional> findByProfessionalSpecialty(SpecialtyType type) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getType().equals(type))
.collect(Collectors.toList());
}
@Override
public List<Professional> findByProfessionalHourlyRate(BigDecimal hourlyRate) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getHourlyRate().equals(hourlyRate))
.collect(Collectors.toList());
}
private String mapToString(Professional professional) {
return String.format("%s,%s,%s,%s,%s,",
professional.getProfessionalId(),
professional.getProfessionalFirstName(),
professional.getProfessionalLastName(),
professional.getType(),
professional.getHourlyRate());
}
private Professional mapToProfessional(String[] tokens) {
return new Professional(
Integer.parseInt(tokens[0]),
tokens[1],
tokens[2],
SpecialtyType.valueOf(tokens[3]),
new BigDecimal(tokens[4]));
}
@Override
public Professional findByProfessionalLastNameNumberTwo(String professionalLastName) throws DataException {
return findAllProfessional().stream()
.filter(p -> p.getProfessionalLastName().equalsIgnoreCase(professionalLastName))
.findFirst().orElse(null);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.models;
import java.time.LocalDate;
import java.util.Objects;
/**
*
* @author Eddy
*/
public class Customer {
private int customerId;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
public Customer() {
}
public Customer(String firstName, String lastName, LocalDate dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public Customer(int customerId, String firstName, String lastName, LocalDate dateOfBirth) {
this.customerId = customerId;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return this.firstName + " " + this.lastName + " " + this.dateOfBirth;
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + this.customerId;
hash = 67 * hash + Objects.hashCode(this.firstName);
hash = 67 * hash + Objects.hashCode(this.lastName);
hash = 67 * hash + Objects.hashCode(this.dateOfBirth);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Customer other = (Customer) obj;
if (this.customerId != other.customerId) {
return false;
}
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
if (!Objects.equals(this.lastName, other.lastName)) {
return false;
}
if (!Objects.equals(this.dateOfBirth, other.dateOfBirth)) {
return false;
}
return true;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine.dto;
import java.math.BigDecimal;
/**
*
* @author Eddy
*/
public class VendingMachineItems {
private int itemId;
private String itemName;
private BigDecimal itemCost;
private int numberOfItemsInInventory;
public VendingMachineItems(){
}
public VendingMachineItems (int itemId, String itemName, BigDecimal itemCost, int numberOfItemsInInventory) {
this.itemId = itemId;
this.itemName = itemName;
this.itemCost = itemCost;
this.numberOfItemsInInventory = numberOfItemsInInventory;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public BigDecimal getItemCost() {
return itemCost;
}
public void setItemCost(BigDecimal itemCost) {
this.itemCost = itemCost;
}
public int getNumberOfItemsInInventory() {
return numberOfItemsInInventory;
}
public void setNumberOfItemsInInventory(int numberOfItemsInInventory) {
this.numberOfItemsInInventory = numberOfItemsInInventory;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.ui;
import com.mycompany.dentalclinic.data.DataException;
import com.mycompany.dentalclinic.models.Appointment;
import com.mycompany.dentalclinic.models.Customer;
import com.mycompany.dentalclinic.models.Professional;
import com.mycompany.dentalclinic.models.SpecialtyType;
import com.mycompany.dentalclinic.service.AppointmentService;
import com.mycompany.dentalclinic.service.CustomerService;
import com.mycompany.dentalclinic.service.DentalClinicService;
import com.mycompany.dentalclinic.service.ProfessionalService;
import com.mycompany.dentalclinic.service.Response;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Eddy
*/
public class Controller {
private View view;
private CustomerService customerService;
private AppointmentService appointmentService;
private ProfessionalService professionalService;
private DentalClinicService dentalClinicService;
public Controller(View view,
CustomerService customerService,
AppointmentService appointmentService,
ProfessionalService professionalService,
DentalClinicService dentalClinicService) {
this.view = view;
this.customerService = customerService;
this.appointmentService = appointmentService;
this.professionalService = professionalService;
this.dentalClinicService = dentalClinicService;
}
public void run() throws DataException {
view.welcome();
MainMenuOption selection;
do {
selection = view.selectFromMainMenu();
switch (selection) {
case APPOINTMENTS_OPTIONS:
appointmentOptions();
break;
case CUSTOMER_OPTIONS:
customerOption();
break;
}
} while (selection != MainMenuOption.EXIT);
view.goodbye();
}
private Customer findAndListCustomer() {
Customer customer = findOrCreateCustomer("Enter a customer.");
if (customer != null) {
return customer;
}
return null;
}
private void customerOption() {
Customer customer = findAndListCustomer();
view.displayCustomer(customer);
}
private void appointmentOptions() throws DataException {
Appointment appointment = manageAppointment("Appointment Options");
if (appointment == null) {
// return appointment;
}
}
private Appointment scheduleAppointment() {
view.printHeader("Schedule Appointment");
// 1. Get existing customer name from view.
// 2. Get matching customers from service.
// 3. Select one customer using the view..
Customer customer = findAndListCustomer();
if (customer == null) {
return null;
} else{
view.displayCustomer(customer);
}
// 4. Get date from view.
LocalDate date = view.getDate("Please enter date:");
if (date == null) {
return null;
}
// 5. Get a Specialty from view.
SpecialtyType specialtyType = view.getType("Please enter Specialty Type");
if (specialtyType == null) {
return null;
}
// 6. Get all Pros with that specialty from service.
List<Professional> allProfessionalsBySpecialtyType = professionalService.searchAllProsBySpecialtyType(specialtyType);
if (allProfessionalsBySpecialtyType.isEmpty()) {
return null;
}
// 7. Select one pro using the view.
Professional professional = view.chooseProfessional(allProfessionalsBySpecialtyType);
if (professional == null) {
return null;
}
// 8. Get start and end time from view.
LocalTime startTime = view.getTime("Please enter Start Time: HH:mm");
LocalTime endTime = view.getTime("Please enter End Time: HH:mm");
// 9. Make an appointment from everything above. Save it (using service).
// Appointment appointment = dentalClinicService.searchOpenTimeSlots(date, professional, startTime, endTime);
Appointment appointment = new Appointment();
appointment.setDate(date);
appointment.setCustomerId(customer.getCustomerId());
appointment.setStart(startTime);
appointment.setEnd(endTime);
appointment.setType(specialtyType);
appointment.setDentalProLastname(professional.getProfessionalLastName());
appointment.setTotalCost(dentalClinicService.calculateCost(appointment));
view.displayUpdatedAppointment(appointment);
// {}
Response r = dentalClinicService.createNewAppointment(appointment);
if(!r.hasError()) {
view.displaySuccess();
} else {
view.displayErrors(r);
}
// try {
// dentalClinicService.createNewAppointment(appointment);
// } catch (DataException ex) {
// Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
// }
return null;
}
private Appointment updateAppointment() throws DataException {
view.printHeader("Update Appointment");
// Response response = new Response();
//Enter a date.
LocalDate date = view.getDate("Please enter date:");
if (date == null) {
return null;
}
//Choose a Customer.
Customer customer = findAndListCustomer();
if (customer == null) {
return null;
}
view.displayCustomer(customer);
if (customer == null) {
return null;
}
// Customer matchedsearched = customer;
//Choose an Appointment.
List<Appointment> searchedByIdAndDate = appointmentService.findCustomerIdAndDate(customer.getCustomerId(), date);
if (searchedByIdAndDate.isEmpty() == true) {
// response.addError("No Appointment Found For User.");
view.displayError("No Appointment Found For User.");
return null;
}
view.displaySearchedAppointments(searchedByIdAndDate);
Appointment updatedAppointment = view.updateAppointment(searchedByIdAndDate.get(0));
//Allow a Dental Professional or User to add notes to the Appointment or change its total cost.
Response updateAppointment = appointmentService.upDateAppointment(updatedAppointment, date);
if (updateAppointment == null) {
view.displayError("Data Error");
}
view.displaySuccess();
return null;
}
private void cancelAppointment() {
view.printHeader("Cancel Appointment");
Customer customer = findAndListCustomer();
if (customer == null) {
view.displayError("Data Error!");
}
LocalDate date = view.getDate("Please enter date:");
if (date == null) {
view.displayError("Date Error!");
}
view.displayCustomer(customer);
if (customer == null) {
view.displayError("Data Error!");
}
List<Appointment> searchedByIdAndDate = appointmentService.findCustomerIdAndDate(customer.getCustomerId(), date);
if (searchedByIdAndDate.isEmpty() == true) {
view.displayError("No Appointment Found For User.");
}
view.displaySearchedAppointments(searchedByIdAndDate);
Appointment cancelAppointment = searchedByIdAndDate.get(0);
boolean confirm = view.confirm("Would you like to cancel this Appointment?");
if (confirm) {
Response cancelAppointments = appointmentService.cancelAppointment(customer.getCustomerId(), date, cancelAppointment.getType());
if (cancelAppointments == null) {
view.displayError("Data Error");
}
view.displaySuccess();
}
// Appointment cancelAppointment = view.cancelAppointment();
// (searchedByIdAndDate.get(0));
}
private void searchAppointmentByDateAndPro() throws DataException {
view.printHeader("Search Appointment");
//Enter a date.
LocalDate date = view.getDate("Please enter date:");
//Select a Dental Professional.
Professional professional = findProfessional();
//Application displays all Appointments for that date and Dental Professional, or indicates there are none.
List<Appointment> appointments = appointmentService.findByProLastNameAndDate(date, professional.getProfessionalLastName());
if (appointments == null) {
view.displayError("No Professional Found For Search.");
}
view.displaySearchedAppointments(appointments);
// Test *
// serviceResponse<List<Appointment>> response = appointmentService.findByProLastNameAndDate(date, userInputLastName);
// if (!response.hasError()) {
// view.displaySearchedAppointments(response.getValue());
// } else {
// view.displayErrors(response);
// }
}
private void viewAppointment() {
//Enter a date.
LocalDate date = view.getDate("Please enter date:");
//Choose a Customer.
//get list of customers from customerService
//pass list of customers to view then have the method return the users choice of customer store the choice in **customerChoice**
//Application displays Appointments or indicates there are none.
// Call to the customerService and get all appointments that customer has on date
//Choose an Appointment.
// Pass list of appointments to view and have the method return an appointment
//Application displays full Appointment details.
//Pass appointment Object to view and the method will display all the details
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private Customer createCustomer() {
Customer c = view.makeCustomer();
if (view.confirm("Please verify information for: " + c + " Submit? ")) {
Response r = customerService.add(c);
if (r.hasError()) {
view.displayErrors(r);
return null;
} else {
view.displaySuccess("" + c + " was added");
return c;
}
}
return null;
}
// public void findProfessionalbyLastName() {
// String userInputLastName = view.getProfessionalbyLastName();
// List<Professional> professionalLastName = professionalService.findByProLastName(userInputLastName);
//
// }
private Professional findProfessional() {
String search = view.getProfessionalbyLastName();
List<Professional> professional = professionalService.findByProLastName(search);
if (professional.size() <= 0) {
view.displayNoProfessionalWarning(search);
return null;
}
return view.chooseProfessional(professional);
}
private Customer findCustomer() {
String search = view.getCustomerLastNameSearch();
List<Customer> customers = customerService.findByLastNameStartingWith(search);
if (customers.size() <= 0) {
view.displayNoCustomerWarning(search);
return null;
}
return view.chooseCustomer(customers);
}
private Customer findOrCreateCustomer(String header) {
boolean shouldCreate = view.shouldCreateCustomer(header);
if (shouldCreate) {
return createCustomer();
}
return findCustomer();
}
private Appointment manageAppointment(String header) throws DataException {
int optionAppointment;
do {
optionAppointment = view.shouldCreateAppointment(header);
switch (optionAppointment) {
case 1:
scheduleAppointment();
break;
case 2:
searchAppointmentByDateAndPro();
break;
case 3:
updateAppointment();
break;
case 4:
cancelAppointment();
// System.out.println("Cancel an existing appointment.");
break;
}
} while (optionAppointment > 0);
view.goodbye();
return null;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.moviedatabase;
import com.mycompany.moviedatabase.controller.MovieDataBaseController;
import com.mycompany.moviedatabase.dao.DataException;
import com.mycompany.moviedatabase.dao.MovieDataBaseDao;
import com.mycompany.moviedatabase.dao.MovieDataBaseDaoFileImpl;
import com.mycompany.moviedatabase.ui.MovieDataBaseView;
import com.mycompany.moviedatabase.ui.UserIOConsoleImpl;
/**
*
* @author Eddy
*/
public class App {
public static void main(String[] args) throws DataException {
UserIOConsoleImpl io = new UserIOConsoleImpl();
MovieDataBaseView view = new MovieDataBaseView(io);
MovieDataBaseDao dao = new MovieDataBaseDaoFileImpl();
MovieDataBaseController controller = new MovieDataBaseController(view, dao);
controller.run();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.dataTest;
import com.mycompany.dentalclinic.data.AppointmentsDao;
import com.mycompany.dentalclinic.data.AppointmentsFileDao;
import com.mycompany.dentalclinic.data.DataException;
import com.mycompany.dentalclinic.models.Appointment;
import com.mycompany.dentalclinic.models.SpecialtyType;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Eddy
*/
public class AppointmentsFileDaoTest {
AppointmentsFileDao dao = new AppointmentsFileDao();
public AppointmentsFileDaoTest() {
}
@Test
public void testFindByDate() {
}
@Test
public void testAddAppointment() throws Exception {
}
@Test
public void testDeleteAppointment() throws Exception {
}
@Test
public void testUpdateAppointment() {
}
@Test
public void testFindByDateAndSpecialty() {
LocalDate date = LocalDate.of(2019, Month.DECEMBER, 16);
List<Appointment> dateAndSpecialtyList = new ArrayList<>();
dateAndSpecialtyList = dao.findByDateAndSpecialty(date, SpecialtyType.ORAL_SURGEON);
assertEquals(1, dateAndSpecialtyList.size());
}
@Test
public void testFindByLocalDateAndProLast() throws DataException {
assertNotNull(dao.findByLocalDateAndProLast(LocalDate.of(2019, Month.DECEMBER, 16), "Buzek"));
dao.findByLocalDateAndProLast(LocalDate.of(2019, Month.DECEMBER, 30), "Murray");
}
@Test
public void testFindCustomerIdAndDate() throws Exception {
}
@Test
public void testFilePathStuff() {
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine;
import com.mycompany.vendingmachine.controller.VendingMachineController;
import com.mycompany.vendingmachine.dao.VendingMachineDao;
import com.mycompany.vendingmachine.dao.VendingMachineDaoFileImpl;
import com.mycompany.vendingmachine.service.InsufficientFundsException;
import com.mycompany.vendingmachine.service.NotFoundException;
import com.mycompany.vendingmachine.service.OutOfStockException;
import com.mycompany.vendingmachine.service.VendingMachineItemsService;
import com.mycompany.vendingmachine.ui.UserIO;
import com.mycompany.vendingmachine.ui.UserIOConsoleImpl;
import com.mycompany.vendingmachine.ui.VendingMachineView;
/**
*
* @author Eddy
*/
public class App {
public static void main(String[] args) throws NotFoundException, OutOfStockException, InsufficientFundsException {
UserIO myIo = new UserIOConsoleImpl();
VendingMachineView myView = new VendingMachineView(myIo);
VendingMachineDao myDao = new VendingMachineDaoFileImpl("inventory.txt");
VendingMachineItemsService myService = new VendingMachineItemsService(myDao);
VendingMachineController controller = new VendingMachineController(myView, myService);
controller.run();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.service;
import com.mycompany.dentalclinic.data.AppointmentsDao;
import com.mycompany.dentalclinic.data.CustomersDao;
import com.mycompany.dentalclinic.data.DataException;
import com.mycompany.dentalclinic.data.ProfessionalDao;
import com.mycompany.dentalclinic.models.Appointment;
import com.mycompany.dentalclinic.models.Professional;
import com.mycompany.dentalclinic.ui.Validations;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
*
* @author Eddy
*/
public class DentalClinicService {
private AppointmentsDao appointmentDao;
private ProfessionalDao professionalDao;
private CustomersDao customersDao;
public DentalClinicService(AppointmentsDao appointmentDao, ProfessionalDao professionalDao, CustomersDao customersDao) {
this.appointmentDao = appointmentDao;
this.professionalDao = professionalDao;
this.customersDao = customersDao;
}
// public Appointment searchOpenTimeSlots(LocalDate date, Professional professional, LocalTime startTime, LocalTime endTime) {
// TimeSlot hours = getDayHours(date);
// TimeSlot lunchTime = new TimeSlot(LocalTime.parse("12:30"), LocalTime.parse("13:00"));
// try {
// List<Appointment> allAppointments = findByProLastNameAndDate(date, professional.getProfessionalLastName()).getValue();
//
// List<TimeSlot> filledTimeSlots = allAppointments.stream()
// .map(a -> new TimeSlot(a.getStart(), a.getEnd()))
// .collect(Collectors.toList());
//
//
// List<TimeSlot> openTimeSlots = new ArrayList<>();
//
// //fully open day
// if (filledTimeSlots.isEmpty()) {
// openTimeSlots.add(new TimeSlot(hours.getStartTime(), lunchTime.getStartTime()));
// openTimeSlots.add(new TimeSlot(lunchTime.getEndTime(), hours.getEndTime()));
// // day with scheduling already.
// } else {
// TimeSlot prevTimeSlot = new TimeSlot(null, null);
// TimeSlot nextTimeSlot = new TimeSlot(null, null);
// if (hours != null) {
// filledTimeSlots.add(lunchTime);
// }
//
// filledTimeSlots = filledTimeSlots.stream()
// .sorted((a, b) -> a.getStartTime().compareTo(b.getStartTime()))
// .collect(Collectors.toList());
//
// for (TimeSlot filledTimeSlot : filledTimeSlots) {
// // get minutes between certain slots.
// long minutesBetween = Duration.between();
// if(minutesBetween >= professional.getType().getMinVisit()){
// openSlots.add()
// } else {
//
// // use for loop to go through filledTimeSlots
// i++;
// if(i < filledSlots.size()){
//
// }
// }
// }
//
// }
//
// } catch (DataException ex) {
// return null;
// }
// return null;
// }
public serviceResponse<List<Appointment>> findByProLastNameAndDate(LocalDate date, String lastName) throws DataException {
serviceResponse<List<Appointment>> response = new serviceResponse<>();
List<Appointment> readAppointments = appointmentDao.findByLocalDateAndProLast(date, lastName);
if (readAppointments.isEmpty()) {
response.addError("No Resulsts!");
}
return response;
}
private TimeSlot getDayHours(LocalDate date) {
DayOfWeek day = date.getDayOfWeek();
switch (day) {
case SATURDAY:
return new TimeSlot(LocalTime.parse("08:30"), LocalTime.parse("12:30"));
case SUNDAY:
return null;
default:
return new TimeSlot(LocalTime.parse("07:30"), LocalTime.parse("18:00"));
}
}
public BigDecimal calculateCost(Appointment apptToAdd) {
Response response = new Response();
LocalTime start = apptToAdd.getStart();
LocalTime end = apptToAdd.getEnd();
String lastName = apptToAdd.getDentalProLastname();
Professional professional = null;
try {
professional = professionalDao.findByProfessionalLastNameNumberTwo(lastName);
} catch (DataException ex) {
response.hasError();
}
if (start == null || end == null || professional == null) {
return BigDecimal.ZERO;
}
long m = start.until(end, ChronoUnit.MINUTES);
BigDecimal minutes = new BigDecimal(m);
BigDecimal hours = minutes.divide(BigDecimal.valueOf(m), 2, RoundingMode.HALF_UP);
return professional.getHourlyRate()
.multiply(hours)
.setScale(2, RoundingMode.HALF_UP);
}
public Response createNewAppointment(Appointment appointment) {
Response response = new Response();
if (Validations.appointmentInOfficeHours(appointment)) {
response.addError("Error: Please Check Appointment Office Hours!");
}
if (!Validations.lengthOfAppointmentCheck(appointment)) {
response.addError("Error: Please Check Length Of Appointment!");
}
if (!appointmentAlreadyExists(appointment)) {
response.addError("Error: Appointment Already Exists!");
}
if (response.hasError()) {
return response;
}
try {
appointmentDao.addAppointment(appointment, appointment.getDate());
} catch (DataException ex) {
response.hasError();
}
return response;
}
// Validation for if Appointment Already exist.
public boolean appointmentAlreadyExists(Appointment appointment) {
Response response = new Response();
boolean duplicate = true;
List<Appointment> allAppointments;
try {
allAppointments = appointmentDao.findByDate(appointment.getDate());
} catch (DataException ex) {
return response.hasError();
}
for (Appointment a : allAppointments) {
if (appointment.getCustomerId() == a.getCustomerId()
&& a.getDentalProLastname().equals(appointment.getDentalProLastname())
&& a.getDate().equals(appointment.getDate()))
// && a.getStart().compareTo(appointment.getStart()) != 0
// && a.getEnd().compareTo(appointment.getEnd()) != 0
// && a.getTotalCost().equals(appointment.getTotalCost())
// && a.getNotes().equals(appointment.getNotes()))
{
duplicate = false;
}
}
return duplicate;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rockpaperscissors;
import java.util.Scanner;
/**
*
* @author Eddy
*/
public class HumanPlayer implements Player {
Scanner input;
public HumanPlayer(Scanner scanner) {
input = scanner;
}
@Override
public int getChoice() {
int userInput;
do {
System.out.println("Player one please enter input: Rock = 1: Paper = 2: Scissors = 3");
userInput = input.nextInt();
if ((userInput < 1 || userInput > 3)) {
System.out.println("Player one please enter a valid input Rock = 1: Paper = 2: Scissors = 3");
}
} while (userInput < 1 || userInput > 3);
return userInput;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dentalclinic.serviceTest;
import com.mycompany.dentalclinic.dataTest.AppointmentsFileDaoTestStub;
import com.mycompany.dentalclinic.dataTest.CustomerFileDaoTestStub;
import com.mycompany.dentalclinic.dataTest.ProfessionalFileDaoTestStub;
import com.mycompany.dentalclinic.models.Appointment;
import com.mycompany.dentalclinic.models.Customer;
import com.mycompany.dentalclinic.models.Professional;
import com.mycompany.dentalclinic.models.SpecialtyType;
import static com.mycompany.dentalclinic.models.SpecialtyType.DENTIST;
import com.mycompany.dentalclinic.service.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Eddy
*/
public class DentalClinicServiceTest {
private DentalClinicService dentalClinicService = new DentalClinicService(new AppointmentsFileDaoTestStub(),
new ProfessionalFileDaoTestStub(), new CustomerFileDaoTestStub());
Appointment appointment1 = new Appointment(23, "Buzek", SpecialtyType.DENTIST, LocalTime.of(2, 30), LocalTime.of(3, 30), new BigDecimal("100.00"), "Test Data");
Appointment appointment2 = new Appointment(24, "Stebbing", SpecialtyType.HYGIENIST, LocalTime.of(7, 30), LocalTime.of(8, 30), new BigDecimal("150.00"), "Test Data");
Appointment appointment3 = new Appointment(25, "Robins", SpecialtyType.HYGIENIST, LocalTime.of(9, 30), LocalTime.of(10, 30), new BigDecimal("175.00"), "Test Data");
public DentalClinicServiceTest() {
}
@Test
public void testFindByProLastNameAndDate() throws Exception {
}
@Test
public void testCalculateCost() {
assertEquals(BigDecimal.valueOf(100.00), dentalClinicService.calculateCost(appointment1));
}
@Test
public void testCreateNewAppointment() {
try {
assertNotNull(dentalClinicService.createNewAppointment(appointment3));
fail();
} catch (IllegalArgumentException ex) {
// this is a good thing
}
}
@Test
public void testAppointmentAlreadyExists() {
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.vendingmachine.dao;
import com.mycompany.vendingmachine.dto.VendingMachineItems;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Eddy
*/
public class VendingMachineDaoFileImpl implements VendingMachineDao {
private ArrayList<VendingMachineItems> vendingMachineItems;
private final String FILE_PATH;
public VendingMachineDaoFileImpl(String FILE_PATH) {
this.FILE_PATH = FILE_PATH;
}
@Override
public List<VendingMachineItems> getAllItems() {
try {
load();
return new ArrayList<>(vendingMachineItems);
} catch (DataException ex) {
return new ArrayList<>();
}
}
@Override
public VendingMachineItems getItemById(int vendingItemsId) {
return getAllItems().stream()
.filter(v -> v.getItemId() == vendingItemsId)
.findAny()
.orElse(null);
}
private void load() throws DataException {
if (vendingMachineItems != null) {
return;
}
vendingMachineItems = new ArrayList<>();
try ( BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
String line;
reader.readLine();
while ((line = reader.readLine()) != null) {
VendingMachineItems vendingMachineItem = unmarshall(line);
if (vendingMachineItem != null) {
vendingMachineItems.add(vendingMachineItem);
}
}
} catch (IOException ex) {
throw new DataException(ex.getMessage(), ex);
}
}
@Override
public boolean update(VendingMachineItems v) throws DataException {
try {
load();
} catch (DataException ex) {
}
for (int i = 0; i < vendingMachineItems.size(); i++) {
if (vendingMachineItems.get(i).getItemId() == v.getItemId()) {
vendingMachineItems.set(i, v);
write();
return true;
}
}
return false;
}
private void write() throws DataException {
try (PrintWriter writer = new PrintWriter(FILE_PATH)) {
writer.print("Vending,Machine,Inventory");
for (VendingMachineItems v : vendingMachineItems) {
String line = marshall(v);
writer.println(line);
}
} catch (IOException ex) {
throw new DataException(ex.getMessage(), ex);
}
}
private VendingMachineItems unmarshall(String line) {
String[] tokens = line.split("::");
if (tokens.length != 4) {
return null;
}
VendingMachineItems vendingMachineItems = new VendingMachineItems();
vendingMachineItems.setItemId(Integer.parseInt(tokens[0]));
vendingMachineItems.setItemName(tokens[1]);
vendingMachineItems.setItemCost(new BigDecimal(tokens[2]));
vendingMachineItems.setNumberOfItemsInInventory(Integer.parseInt(tokens[3]));
return vendingMachineItems;
}
private String marshall(VendingMachineItems v) {
return String.format("%s::%s::%s::%s",
v.getItemId(),
v.getItemName(),
v.getItemCost(),
v.getNumberOfItemsInInventory()
);
}
}
| 0b03bbff3ada0eb920ca3cc0e79b0ff773f855f8 | [
"Markdown",
"Java"
] | 31 | Java | SeriousE2/Projects | 433cea06de4cab8aee1b41e59f14db780f9a9312 | a55be7ad087cef755914da609d5e9f1d6fda96b4 |
refs/heads/master | <file_sep>"""
Parser interface definition
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
class Parser(LEMSBase):
"""
Parser interface class
"""
def parse_file(self, filename):
"""
Parse a file and generate a LEMS model
@param filename: Path to the file to be parsed
@type filename: string
@return: LEMS model parsed from the input file
"""
return None
def parse_string(self, str):
return None
<file_sep>all: lems-code lems-doc
JLEMSPATH = ../jLEMS
JLEMSBIN = lemsio
TIME = /usr/bin/time -f '%E s'
BENCHFILE = ../NeuroML2/NeuroML2CoreTypes/LEMS_NML2_Ex2_Izh.xml
lems-code:
lems-doc:
mkdir -p doc/epydoc
epydoc -v -o doc/epydoc lems
clean:
find . -name "*.pyc" | xargs rm -f
find . -name "*.pyo" | xargs rm -f
find . -name "__pycache__" | xargs rm -rf
rm -rf doc/epydoc/*
example1:
./runlems.py examples/example1.xml
example2:
./runlems.py examples/example2.xml
example3:
./runlems.py examples/example3.xml
example4:
./runlems.py examples/example4.xml
example5:
./runlems.py examples/example5.xml
example6:
./runlems.py examples/example6.xml
example7:
./runlems.py examples/example7.xml
example8:
./runlems.py examples/example8.xml
example9:
./runlems.py examples/example9.xml
ex0:
./runlems.py examples/LEMS_NML2_Ex0.xml
nmlex0:
./runlems.py ../NeuroML2/NeuroML2CoreTypes/LEMS_NML2_Ex0_IaF.xml
nmlex1:
./runlems.py ../NeuroML2/NeuroML2CoreTypes/LEMS_NML2_Ex1_HH.xml
nmlex2:
./runlems.py ../NeuroML2/NeuroML2CoreTypes/LEMS_NML2_Ex2_Izh.xml
nmlex3:
./runlems.py ../NeuroML2/NeuroML2CoreTypes/LEMS_NML2_Ex3_Net.xml
run: example9
bench:
@echo "Java"
env LEMS_HOME=${JLEMSPATH} ${TIME} ${JLEMSPATH}/${JLEMSBIN} ${BENCHFILE} -nogui 2>&1 > /dev/null
@echo "CPython 2 (no optimizations)"
@${TIME} python runlems.py -nogui ${BENCHFILE} > /dev/null
@echo "CPython 2 (with optimizations)"
@${TIME} python -O runlems.py -nogui ${BENCHFILE} > /dev/null
@echo "PyPy"
@${TIME} pypy runlems.py -nogui ${BENCHFILE} > /dev/null
<file_sep>"""
Parameter storage
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import re
from lems.base.errors import ModelError
from lems.base.base import LEMSBase
class Parameter(LEMSBase):
"""
Stores a parameter.
"""
def __init__(self, name, dimension, fixed = False, value = None,
numeric_value = None):
"""
Constructor.
See instance variable documentation for more info on parameters.
"""
self.name = name
""" Parameter name.
@type: string """
self.dimension = dimension
""" Dimension for this parameter.
@type: string """
self.fixed = fixed
""" Set to True if this parameter has a fixed value.
@type: Boolean """
if fixed and value == None:
raise ModelError('A numeric value must be provided to fix' +
'this parameter')
self.value = value
""" Value for this parameter.
@type: string """
self.numeric_value = numeric_value
""" Numeric value of this parameter in terms of standard units.
@type: Number """
def fix_value(self, value):
"""
Fixes the value of this parameter.
@param value: Fixed value for this parameter.
For example, "30mV" or "45 kg"
@type value: string
@raise ModelError: Raised ModelError if the parameter is already
fixed.
"""
if self.fixed:
raise ModelError('Parameter already fixed.')
self.set_value(value)
self.fixed = True
def set_value(self, value):
"""
Sets the value of this parameter.
@param value: Value for this parameter. For example, "30mV" or "45 kg"
@type value: string
@raise ModelError: Raised ModelError if the parameter is already fixed.
"""
if self.fixed:
raise ModelError('Parameter already fixed.')
self.value = value
def __str__(self):
return '[Parameter - {0},{1},{2},{3}]'.format(
self.name,
self.dimension,
self.value,
self.fixed)
class DerivedParameter(LEMSBase):
"""
Storesa derived parameter. Consider merging with Parameter
"""
def __init__(self, name, dimension, value, select):
"""
Constructor.
See instance variable documentation for more info on parameters.
"""
self.name = name
""" Name of the parameter.
@type: string """
self.dimension = dimension
""" Dimension of the parameter. Used for type checking.
@type: string """
if (value and select) or (not value and not select):
raise ("Atleast one of 'value' and 'select' must be"
"specified for derived parameter '{0}'").format(name)
self.value = value
""" Expression for computing the Value of this parameter.
@type: string """
self.select = select
""" XPath selector
@type: string """
<file_sep>"""
Base class for runnable components.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.util import Stack
from lems.base.errors import SimBuildError
from lems.sim.recording import Recording
import ast
import sys
from math import *
#import math
#class Ex1(Exception):
# pass
#def exp(x):
# try:
# return math.exp(x)
# except Exception as e:
# print('ERROR performing exp({0})'.format(x))
# raise Ex1()
class Reflective(object):
def __init__(self):
self.instance_variables = []
self.derived_variables = []
self.array = []
#@classmethod
def add_method(self, method_name, parameter_list, statements):
code_string = 'def __generated_function__'
if parameter_list == []:
code_string += '():\n'
else:
code_string += '(' + parameter_list[0]
for parameter in parameter_list[1:]:
code_string += ', ' + parameter
code_string += '):\n'
if statements == []:
code_string += ' pass'
else:
for statement in statements:
code_string += ' ' + statement + '\n'
g = globals()
l = locals()
exec(compile(ast.parse(code_string), '<unknown>', 'exec'), g, l)
#setattr(cls, method_name, __generated_function__)
self.__dict__[method_name] = l['__generated_function__']
del l['__generated_function__']
def add_instance_variable(self, variable, initial_value):
self.instance_variables.append(variable)
code_string = 'self.{0} = {1}\nself.{0}_shadow = {1}'.format(\
variable, initial_value)
exec(compile(ast.parse(code_string), '<unknown>', 'exec'))
def add_derived_variable(self, variable):
self.derived_variables.append(variable)
code_string = 'self.{0} = {1}\nself.{0}_shadow = {1}'.format(\
variable, 0)
exec(compile(ast.parse(code_string), '<unknown>', 'exec'))
def add_text_variable(self, variable, value):
self.__dict__[variable] = value
def __getitem__(self, key):
return self.array[key]
def __setitem__(self, key, val):
self.array[key] = val
class Regime:
def __init__(self, name):
self.name = name
self.update_state_variables = None
self.update_derived_variables = None
self.run_startup_event_handlers = None
self.run_preprocessing_event_handlers = None
self.run_postprocessing_event_handlers = None
self.update_kinetic_scheme = None
class Runnable(Reflective):
uid_count = 0
def __init__(self, id_, component, parent = None):
Reflective.__init__(self)
self.uid = Runnable.uid_count
Runnable.uid_count += 1
self.id = id_
self.component = component
self.parent = parent
self.time_step = 0
self.time_completed = 0
self.time_total = 0
self.plastic = True
self.state_stack = Stack()
self.children = {}
self.uchildren = {}
self.recorded_variables = []
self.event_out_ports = []
self.event_in_ports = []
self.event_out_callbacks = {}
self.event_in_counters = {}
self.attachments = {}
self.new_regime = ''
self.current_regime = ''
self.last_regime = ''
self.regimes = {}
def add_child(self, id_, runnable):
self.uchildren[runnable.uid] = runnable
self.children[id_] = runnable
self.children[runnable.id] = runnable
self.__dict__[id_] = runnable
self.__dict__[runnable.id] = runnable
runnable.configure_time(self.time_step, self.time_total)
def add_child_to_group(self, group_name, child):
if group_name not in self.__dict__:
self.__dict__[group_name] = []
self.__dict__[group_name].append(child)
def make_attachment(self, type_, name):
self.attachments[type_] = name
self.__dict__[name] = []
def add_attachment(self, runnable):
component_type = runnable.component.context.lookup_component_type(
runnable.component.component_type)
for ctype in component_type.types:
if ctype in self.attachments:
name = self.attachments[ctype]
runnable.id = runnable.id + str(len(self.__dict__[name]))
self.__dict__[name].append(runnable)
return
raise SimBuildError('Unable to find appropriate attachment')
def add_event_in_port(self, port):
self.event_in_ports.append(port)
if port not in self.event_in_counters:
self.event_in_counters[port] = 0
def inc_event_in(self, port):
self.event_in_counters[port] += 1
def add_event_out_port(self, port):
self.event_out_ports.append(port)
if port not in self.event_out_callbacks:
self.event_out_callbacks[port] = []
def register_event_out_link(self, port, runnable, remote_port):
self.event_out_callbacks[port].append((runnable, remote_port))
def register_event_out_callback(self, port, callback):
if port in self.event_out_callbacks:
self.event_out_callbacks[port].append(callback)
else:
raise SimBuildError('No event out port \'{0}\' in '
'component \'{1}\''.format(port, self.id))
def add_regime(self, regime):
self.regimes[regime.name] = regime
def resolve_path(self, path):
if path == '':
return self
if path[0] == '/':
return self.parent.resolve_path(path)
elif path.find('../') == 0:
return self.parent.resolve_path(path[3:])
elif path.find('..') == 0:
return self.parent
else:
if path.find('/') >= 1:
(child, new_path) = path.split('/', 1)
else:
child = path
new_path = ''
idxbegin = child.find('[')
idxend = child.find(']')
if idxbegin != 0 and idxend > idxbegin:
idx = int(child[idxbegin+1:idxend])
child = child[:idxbegin]
else:
idx = -1
if child in self.children:
childobj = self.children[child]
if idx != -1:
childobj = childobj.array[idx]
elif child in self.component.context.parameters:
ctx = self.component.context
p = ctx.parameters[child]
return self.resolve_path('../' + p.value)
else:
raise SimBuildError('Unable to find child \'{0}\' in '
'\'{1}\''.format(child, self.id))
if new_path == '':
return childobj
else:
return childobj.resolve_path(new_path)
def add_variable_recorder(self, data_output, recorder):
self.add_variable_recorder2(data_output, recorder, recorder.quantity)
def add_variable_recorder2(self, data_output, recorder, path):
if path[0] == '/':
self.parent.add_variable_recorder2(data_output, recorder, path)
elif path.find('../') == 0:
self.parent.add_variable_recorder2(data_output, recorder, path[3:])
elif path.find('/') >= 1:
(child, new_path) = path.split('/', 1)
idxbegin = child.find('[')
idxend = child.find(']')
if idxbegin != 0 and idxend > idxbegin:
idx = int(child[idxbegin+1:idxend])
child = child[:idxbegin]
else:
idx = -1
if child in self.children:
childobj = self.children[child]
if idx == -1:
childobj.add_variable_recorder2(data_output,
recorder,
new_path)
else:
childobj.array[idx].add_variable_recorder2(data_output,
recorder,
new_path)
else:
raise SimBuildError('Unable to find child \'{0}\' in '
'\'{1}\''.format(child, self.id))
else:
self.recorded_variables.append(Recording(path, data_output, recorder))
def configure_time(self, time_step, time_total):
self.time_step = time_step
self.time_total = time_total
for cn in self.uchildren:
self.uchildren[cn].configure_time(self.time_step, self.time_total)
for c in self.array:
c.configure_time(self.time_step, self.time_total)
## for type_ in self.attachments:
## components = self.__dict__[self.attachments[type_]]
## for component in components:
## component.configure_time(self.time_step, self.time_total)
def reset_time(self):
self.time_completed = 0
for cid in self.uchildren:
self.uchildren[cid].reset_time()
for c in self.array:
c.reset_time()
## for type_ in self.attachments:
## components = self.__dict__[self.attachments[type_]]
## for component in components:
## component.reset_time()
def single_step(self, dt):
#return self.single_step2(dt)
# For debugging
try:
return self.single_step2(dt)
#except Ex1 as e:
# print self.rate
# print self.midpoint
# print self.scale
# print self.parent.parent.parent.parent.v
# # rate * exp((v - midpoint)/scale)
# sys.exit(0)
except Exception as e:
r = self
name = r.id
while r.parent:
r = r.parent
name = "{0}.{1}".format(r.id, name)
print("Error in '{0} ({2})': {1}".format(name, e,
self.component.component_type))
print(type(e))
keys = self.__dict__.keys()
keys.sort()
for k in keys:
print('{0} -> {1}'.format(k, self.__dict__[k]))
print('')
print('')
if isinstance(e, ArithmeticError):
print(('This is an arithmetic error. Consider reducing the '
'integration time step.'))
sys.exit(0)
def single_step2(self, dt):
for cid in self.uchildren:
self.uchildren[cid].single_step(dt)
for child in self.array:
child.single_step(dt)
## for type_ in self.attachments:
## components = self.__dict__[self.attachments[type_]]
## for component in components:
## component.single_step(dt)
if self.new_regime != '':
self.current_regime = self.new_regime
self.new_regime = ''
self.update_kinetic_scheme(self, dt)
if self.time_completed == 0:
self.run_startup_event_handlers(self)
self.run_preprocessing_event_handlers(self)
self.update_shadow_variables()
self.update_derived_variables(self)
self.update_shadow_variables()
self.update_state_variables(self, dt)
self.update_shadow_variables()
self.run_postprocessing_event_handlers(self)
self.update_shadow_variables()
if self.current_regime != '':
regime = self.regimes[self.current_regime]
regime.update_kinetic_scheme(self, dt)
#if self.time_completed == 0:
# self.run_startup_event_handlers(self)
regime.run_preprocessing_event_handlers(self)
self.update_shadow_variables()
regime.update_derived_variables(self)
self.update_shadow_variables()
regime.update_state_variables(self, dt)
self.update_shadow_variables()
regime.run_postprocessing_event_handlers(self)
self.update_shadow_variables()
self.record_variables()
self.time_completed += dt
if self.time_completed >= self.time_total:
return 0
else:
return dt
def record_variables(self):
for recording in self.recorded_variables:
recording.add_value(self.time_completed,
self.__dict__[recording.variable])
def push_state(self):
vars = []
for varname in self.instance_variables:
vars += [self.__dict__[varname],
self.__dict__[varname + '_shadow']]
self.state_stack.push(vars)
for cid in self.uchildren:
self.uchildren[cid].push_state()
for c in self.array:
c.push_state()
def pop_state(self):
vars = self.state_stack.pop()
for varname in self.instance_variables:
self.__dict_[varname] = vars[0]
self.__dict_[varname + '_shadow'] = vars[1]
vars = vars[2:]
for cid in self.uchildren:
self.uchildren[cid].pop_state()
for c in self.array:
c.pop_state()
def update_shadow_variables(self):
if self.plastic:
for var in self.instance_variables:
self.__dict__[var + '_shadow'] = self.__dict__[var]
for var in self.derived_variables:
self.__dict__[var + '_shadow'] = self.__dict__[var]
<file_sep>"""
LEMS base class.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import copy
class LEMSBase(object):
def copy(self):
return copy.deepcopy(self)
<file_sep>#! /usr/bin/env python
"""
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import sys
from pylems.main import main
main(sys.argv[1:])
<file_sep>"""
Model storage
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.errors import ModelError
from lems.model.context import Contextual
from lems.model.parameter import Parameter
from lems.parser.xpath import resolve_xpath
from lems.base.util import merge_dict
import re
import copy
class Model(Contextual):
"""
Store the model read from a LEMS file.
"""
def __init__(self):
"""
Constructor.
"""
super(Model, self).__init__('__model__')
self.targets = []
""" Names of simulations to run.
@type: string """
self.dimensions = None
""" Dictionary of references to dimensions defined in the model.
@type: dict(string -> lems.model.simple.Dimension) """
self.units = None
""" Dictionary of references to units defined in the model.
@type: dict(string -> lems.model.simple.Unit) """
self.context = None
""" Global (root) context.
@type: lems.model.context.Context """
self.next_free_id = -1
""" Number used to create a new ID.
@type: Integer """
def add_target(self, target):
"""
Add the name of the component to run to the list of components to
run by default.
@param target: Name of a simulation to run by default
@type target: string """
self.targets += [target]
def add_dimension(self, dimension):
"""
Adds a dimension to the list of defined dimensions.
@param dimension: Dimension to be added to the model.
@type dimension: lems.base.units.Dimension
@raise ModelError: Raised when the dimension is already defined.
"""
if self.dimensions == None:
self.dimensions = dict()
if dimension.name in self.dimensions:
d = self.dimensions[dimension.name]
if ((d.l != dimension.l) or
(d.m != dimension.m) or
(d.t != dimension.t) or
(d.i != dimension.i) or
(d.k != dimension.k) or
(d.c != dimension.c) or
(d.n != dimension.n)):
self.raise_error(("Incompatible redefinition of "
"dimension '{0}'").format(dimension.name),
self.context)
else:
self.dimensions[dimension.name] = dimension
def add_unit(self, unit):
"""
Adds a unit to the list of defined units.
@param unit: Unit to be added to the model.
@type unit: lems.base.units.Unit
@raise ModelError: Raised when the unit is already defined.
"""
if self.units == None:
self.units = dict()
if unit.symbol in self.units:
u = self.units[unit.symbol]
if u.dimension != unit.dimension or u.power != unit.power:
self.raise_error(("Incompatible redefinition of "
"unit '{0}'").format(unit.symbol),
self.context)
else:
self.units[unit.symbol] = unit
def resolve_parameter_value(self, parameter, context):
"""
Resolves the numeric value of a parameter based on the given value
in terms of the symbols and dimensions defined in the model.
@param parameter: Parameter object to be resolved.
@type parameter: lems.model.parameter.Parameter
@param context: Context containing the parameter
@type context: lems.model.context.Context
@raise ModelError: Raised when the value of the parameter is not set.
@raise ModelError: Raised when the unit symbol does not match the
parameter's dimension.
@raise ModelError: Raised when the unit symbol is undefined.
"""
if parameter.value == None:
self.raise_error('Parameter {0} not initialized'.format(\
parameter.name), context)
bitsnum = re.split('[_a-zA-Z]+', parameter.value)
bitsalpha = re.split('[^_a-zA-Z]+', parameter.value)
n = float(bitsnum[0].strip())
bitsnum = bitsnum[1:]
bitsalpha = bitsalpha[1:]
s = ''
l = max(len(bitsnum), len(bitsalpha))
for i in xrange(l):
if i < len(bitsalpha):
s += bitsalpha[i].strip()
if i < len(bitsnum):
s += bitsnum[i].strip()
#number = float(re.split('[_a-zA-Z]+', parameter.value)[0].strip())
#sym = re.split('[^_a-zA-Z]+', parameter.value)[1].strip()
number = n
sym = s
if sym == '':
parameter.numeric_value = number
else:
if sym in self.units:
unit = self.units[sym]
if parameter.dimension != unit.dimension:
if parameter.dimension == '*':
parameter.dimension = unit.dimension
else:
self.raise_error(('Unit symbol {0} cannot '
'be used for dimension {1}').format(\
sym, parameter.dimension),
context)
parameter.numeric_value = number * (10 ** unit.power)
else:
self.raise_error('Unknown unit symbol {0}'.format(sym),
context)
def resolve_extended_component_type(self, context, component_type):
"""
Resolves the specified component type's parameters from it's base
component type.
@param context: Context object containing the component type.
@type context: lems.model.context.Context
@param component_type: Component type to be resolved.
@type component_type: lems.model.component.ComponentType
@raise ModelError: Raised when the base component type cannot be
resolved.
@raise ModelError: Raised when a parameter in the base component type
is redefined in this component type.
"""
base_type = context.lookup_component_type(component_type.extends)
if base_type == None:
self.raise_error('Base type {0} not found for component type {1}'.
format(component_type.extends,
component_type.name),
context)
if base_type.extends:
self.resolve_extended_component_type(context, base_type)
this_context = component_type.context
base_context = base_type.context
this_context.merge(base_context, self)
component_type.types = component_type.types | base_type.types
component_type.extends = None
def resolve_extended_component(self, context, component):
"""
Resolves the specified component's parameters from it's base
component.
@param context: Context object containing the component.
@type context: lems.model.context.Context
@param component: Component to be resolved.
@type component: lems.model.component.Component
@raise ModelError: Raised when the base component cannot be
resolved.
@raise ModelError: Raised when a parameter in the base component
is redefined in this component.
@note: Consider changing Component.id to Component.name and merging
this method with resolve_extended_component_type.
"""
base = context.lookup_component(component.extends)
if base == None:
self.raise_error('Base component {0} not found for component {1}'.
format(component.extends,
component.id),
context)
if base.extends:
self.resolve_extended_component(context, base)
component.component_type = base.component_type
this_context = component.context
base_context = base.context
this_context.merge(base_context, self)
component.extends = None
def resolve_component_structure_from_type(self,
comp_context,
type_context,
component):
"""
Resolves the specified component's structure from component type.
@param comp_context: Component's context object.
@type comp_context: lems.model.context.Context
@param type_context: Component type's context object.
@type type_context: lems.model.context.Context
@param component: Component to be resolved.
@type component: lems.model.component.Component
@raise ModelError: Raised when the component type cannot be
resolved.
"""
comp_str = comp_context.structure
type_str = type_context.structure
comp_str.event_connections = type_str.event_connections
for c in type_str.single_child_defs:
if c in comp_context.component_refs:
comp_str.add_single_child_def(c)
else:
raise ModelError("Trying to multi-instantiate from an "
"invalid component reference '{0}'".format(\
c))
for c in type_str.multi_child_defs:
n = type_str.multi_child_defs[c]
if c in comp_context.component_refs:
component = comp_context.component_refs[c]
if n in comp_context.parameters:
number = int(comp_context.parameters[n].numeric_value)
comp_str.add_multi_child_def(component, number)
else:
raise ModelError("Trying to multi-instantiate using an "
"invalid number parameter '{0}'".\
format(n))
else:
raise ModelError("Trying to multi-instantiate from an "
"invalid component reference '{0}'".format(\
c))
comp_str.foreach = type_str.foreach
comp_str.with_mappings = type_str.with_mappings
def resolve_component_from_type(self, context, component):
"""
Resolves the specified component's parameters from component type.
@param context: Context object containing the component.
@type context: lems.model.context.Context
@param component: Component to be resolved.
@type component: lems.model.component.Component
@raise ModelError: Raised when the component type cannot be
resolved.
"""
component_type = context.lookup_component_type(
component.component_type)
if component_type == None:
self.raise_error('Type {0} not found for component {1}'.
format(component.component_type,
component.id),
context)
this_context = component.context
type_context = component_type.context
this_context.merge(type_context, self)
def resolve_simulation(self, context):
"""
Resolves simulation specifications in a component-type context.
@param context: Current context.
@type context: lems.model.context.Context
@raise ModelError: Raised when the quantity to be recorded is not a
path.
@raise ModelError: Raised when the color specified is not a text
entity.
"""
simulation = context.simulation
# Resolve <Record> statements
for idx in simulation.records:
record = simulation.records[idx]
if record.quantity in context.parameters:
qp = context.parameters[record.quantity]
record.quantity = qp.value
if qp.dimension != '__path__':
self.raise_error('<Record>: The quantity to be recorded'
'must be a path',
context)
if record.scale in context.parameters and \
record.color in context.parameters:
sp = context.parameters[record.scale]
cp = context.parameters[record.color]
if cp.dimension != '__text__':
self.raise_error('<Record>: The color to be used must be '
'a reference to a text variable',
context)
record.scale = sp.value
record.color = cp.value
record.numeric_scale = sp.numeric_value
# Resolve <DataDisplay> statements
for idx in simulation.data_displays:
display = simulation.data_displays[idx]
if display.title in context.parameters:
p = context.parameters[display.title]
display.title = p.value
def resolve_regime(self, context, regime):
"""
Resolves name references in the given dynamics regime to actual
objects.
@param context: Current context.
@type context: lems.model.context.Context
@param regime: Dynamics regime to be resolved.
@type regime: lems.model.dynamics.Dynamics
@raise ModelError: Raised when the quantity to be recorded is not a
path.
@raise ModelError: Raised when the color specified is not a text
entity.
"""
pass
def resolve_dynamics_profile(self, context, dynamics):
"""
Resolves name references in the given dynamics profile to actual
objects.
@param context: Current context.
@type context: lems.model.context.Context
@param dynamics: Dynamics profile to be resolved.
@type dynamics: lems.model.dynamics.Dynamics
"""
self.resolve_regime(context, dynamics.default_regime)
for rn in dynamics.regimes:
regime = dynamics.regimes[rn]
self.resolve_regime(context, regime)
def resolve_component_type(self, context, component_type):
"""
Resolves the specified component.
@param context: Context object containing the component type.
@type context: lems.model.context.Context
@param component_type: Component type to be resolved.
@type component_type: lems.model.component.Component
"""
self.resolve_context(component_type.context)
if component_type.extends:
self.resolve_extended_component_type(context, component_type)
this_context = component_type.context
for dpn in this_context.derived_parameters:
dp = this_context.derived_parameters[dpn]
if dp.select:
target = resolve_xpath(dp.select, this_context)
else:
print('TODO - Derived parameter value computation')
def resolve_component(self, context, component):
"""
Resolves the specified component.
@param context: Context object containing the component.
@type context: lems.model.context.Context
@param component: Component to be resolved.
@type component: lems.model.component.Component
@raise ModelError: Raised when the dimension for a parameter cannot
be resolved.
"""
self.resolve_context(component.context)
if component.extends:
self.resolve_extended_component(context, component)
self.resolve_component_from_type(context, component)
# GG: Reenable this once the NeuroML definitions are fixed.
## for pn in component.context.parameters:
## p = component.context.parameters[pn]
## if p.dimension == '__dimension_inherited__':
## self.raise_error(("The dimension for parameter '{0}' in "
## "component '{1}' ({2}) could not be resolved").\
## format(pn, component.id,
## component.component_type),
## component.context)
# Resolve dynamics
for dpn in component.context.dynamics_profiles:
dp = component.context.dynamics_profiles[dpn]
self.resolve_dynamics_profile(component.context, dp)
def resolve_child(self, context, child):
"""
Resolves the specified child component.
@param context: Context object containing the component.
@type context: lems.model.context.Context
@param child: Child component to be resolved.
@type child: lems.model.component.Component
@raise ModelError: Raised when the parent component cannot be
resolved.
@raise ModelError: Raised when the component type for the parent
component cannot be resolved.
"""
parent = context.lookup_component(context.name)
if parent == None:
self.raise_error('Unable to resolve component \'{0}\''.\
format(context.name))
parent_type = context.lookup_component_type(parent.component_type)
if parent_type == None:
self.raise_error('Unable to resolve component type \'{0}\''.\
format(parent.component_type))
ptctx = parent_type.context
if child.id in ptctx.child_defs:
if child.component_type == '__type_inherited__':
child.component_type = ptctx.child_defs[child.id]
#else:
# print child.id, child.component_type
# raise Exception('TODO')
context.add_component(child)
else:
for cdn in ptctx.children_defs:
cdt = ptctx.children_defs[cdn]
if child.id == cdt:
child.component_type = cdt
child.id = self.make_id()
context.add_component(child)
if cdn not in context.children_defs:
context.add_children_def(cdn, cdt)
break
elif child.component_type == cdt:
context.add_component(child)
if cdn not in context.children_defs:
context.add_children_def(cdn, cdt)
break
def resolve_context(self, context):
"""
Resolves name references in the given context to actual objects.
@param context: Context to be resolved.
@type context: lems.model.context.Context
@raise ModelError: Raised when the dimension for a parameter cannot
be resolved.
"""
# Resolve component-types
for ctn in context.component_types:
component_type = context.component_types[ctn]
self.resolve_component_type(context, component_type)
# Resolve children
if context.children:
for child in context.children:
self.resolve_child(context, child)
# Resolve components
for cid in context.components:
component = context.components[cid]
self.resolve_component(context, component)
self.resolve_simulation(component.context)
def resolve_model(self):
"""
Resolves name references in the model to actual objects.
@raise ModelError: Raised when the dimension for a given unit cannot
be resolved.
"""
# Verify dimensions for units
for symbol in self.units:
dimension = self.units[symbol].dimension
if dimension not in self.dimensions:
self.raise_error('Dimension {0} not defined for unit {1}'\
.format(dimension, symbol),
self.context)
# Resolve global context
self.resolve_context(self.context)
def raise_error(self, message, context):
s = 'Caught ModelError in lems'
context_name_stack = []
while context != None:
context_name_stack.insert(0, context.name)
context = context.parent
for context_name in context_name_stack:
s += '.' + context_name
s += ':\n ' + message
raise ModelError(s)
def make_id(self):
self.next_free_id = self.next_free_id + 1
return 'id__{0}'.format(self.next_free_id)
#####################################################################33
tab = ' '
def regime2str(self, regime, prefix):
s = ''
if regime.state_variables:
s += prefix + Model.tab + 'State variables:\n'
for svn in regime.state_variables:
sv = regime.state_variables[svn]
s += prefix + Model.tab*2 + sv.name
if sv.exposure:
s += ' (exposed as ' + sv.exposure + ')'
s += ': ' + sv.dimension + '\n'
if regime.time_derivatives:
s += prefix + Model.tab + 'Time derivatives:\n'
for tdv in regime.time_derivatives:
td = regime.time_derivatives[tdv]
s += prefix + Model.tab*2 + td.variable + ' = ' + td.value\
+ ' | ' + str(td.expression_tree) + '\n'
if regime.derived_variables:
s += prefix + Model.tab + 'Derived variables:\n'
for dvn in regime.derived_variables:
dv = regime.derived_variables[dvn]
s += prefix + Model.tab*2 + dv.name
if dv.value:
s += ' = ' + dv.value + ' | ' + str(dv.expression_tree) + '\n'
elif dv.select and dv.reduce:
s += ' = reduce.' + dv.reduce + ' over ' + dv.select + '\n'
else:
s += '\n'
if regime.event_handlers:
s += prefix + Model.tab + 'Event Handlers:\n'
for eh in regime.event_handlers:
s += prefix + Model.tab*2 + str(eh) + '\n'
if eh.actions:
s += prefix + Model.tab*3 + 'Actions:\n'
for a in eh.actions:
s += prefix + Model.tab*4 + str(a) + '\n'
if regime.kinetic_schemes:
s += prefix + Model.tab + 'Kinetic schemes:\n'
for ksn in regime.kinetic_schemes:
ks = regime.kinetic_schemes[ksn]
s += prefix + Model.tab*2
s += '{0}: ({1} {2}) ({3} {4} {5}) ({6} {7})\n'.format(
ks.name,
ks.nodes, ks.state_variable,
ks.edges, ks.edge_source, ks.edge_target,
ks.forward_rate, ks.reverse_rate)
return s
def dynamics2str(self, dynamics, prefix):
s = prefix
if dynamics.name != '':
s += name
else:
s += '*'
s += '\n'
if dynamics.default_regime:
s += prefix + Model.tab + 'Default regime:\n'
s += self.regime2str(dynamics.default_regime,
prefix + Model.tab)
return s
def structure2str(self, structure, prefix):
s = prefix + 'Structure:\n'
if structure.event_connections:
s += prefix + Model.tab + 'Event connections:\n'
for conn in structure.event_connections:
s += prefix + Model.tab*2 + '{0}:{1} -> {2}:{3}\n'.format(
conn.source_path, conn.source_port,
conn.target_path, conn.target_port)
if structure.single_child_defs:
s += prefix + Model.tab + 'Single child instantiations:\n'
for c in structure.single_child_defs:
s += prefix + Model.tab*2 + c + '\n'
if structure.multi_child_defs:
s += prefix + Model.tab + 'Multi child instantiations:\n'
for c in structure.multi_child_defs:
s += prefix + Model.tab*2 + '{0} * {1}\n'.format(\
c, structure.multi_child_defs[c])
if structure.foreach:
s += prefix + Model.tab + 'ForEach:\n'
for fe in structure.foreach:
s += prefix + Model.tab*2 + 'ForEach {0} as {1}\n'.format(\
fe.target, fe.name)
s += self.structure2str(fe, prefix + Model.tab*3)
return s
def simulation2str(self, simulation, prefix):
s = prefix + 'Simulation Specs:\n'
prefix = prefix + Model.tab
if simulation.runs:
s += prefix + 'Runs:\n'
for rn in simulation.runs:
r = simulation.runs[rn]
s += '{0}{1} {2} {3} {4}\n'.format(prefix + Model.tab,
r.component,
r.variable,
r.increment,
r.total)
if simulation.records:
s += prefix + 'Recordings:\n'
for q in simulation.records:
r = simulation.records[q]
s += '{0}{1} {2} {3}\n'.format(prefix + Model.tab,
r.quantity,
r.scale,
r.color)
if simulation.data_displays:
s += prefix + 'Data displays:\n'
for t in simulation.data_displays:
d = simulation.data_displays[t]
s += '{0}{1} {2}\n'.format(prefix + Model.tab,
d.title,
d.data_region)
if simulation.data_writers:
s += prefix + 'Data writers:\n'
for p in simulation.data_writers:
w = simulation.data_writers[p]
s += '{0}{1} {2}\n'.format(prefix + Model.tab,
w.path,
w.file_path)
return s
def context2str(self, context, prefix):
s = ''
prefix = prefix + Model.tab
if context.component_types:
s += prefix + 'Component types:\n'
for tn in context.component_types:
t = context.component_types[tn]
s += prefix + Model.tab + t.name
if t.extends:
s += ' (extends ' + t.extends + ')'
s += '\n'
s += self.context2str(t.context, prefix + Model.tab)
if context.components:
s += prefix + 'Components:\n'
for cn in context.components:
c = context.components[cn]
s += prefix + Model.tab + c.id
if c.component_type:
s += ': ' + c.component_type + '\n'
else:
s+= ' (extends ' + c.extends + ')' + '\n'
s += self.context2str(c.context, prefix + Model.tab)
if context.component_refs:
s += prefix + 'Component references:\n'
for cref in context.component_refs:
t = context.component_refs[cref]
s += prefix + Model.tab + cref + ': ' + t + '\n'
if context.child_defs:
s += prefix + 'Child definitions:\n'
for cref in context.child_defs:
t = context.child_defs[cref]
s += prefix + Model.tab + cref + ': ' + t + '\n'
if context.children_defs:
s += prefix + 'Children definitions:\n'
for cref in context.children_defs:
t = context.children_defs[cref]
s += prefix + Model.tab + cref + ': ' + t + '\n'
if context.children:
s += prefix + 'Children:\n'
for child in context.children:
s += prefix + Model.tab + child.id + ': ' + \
child.component_type + '\n'
s += self.context2str(child.context, prefix + Model.tab)
if context.parameters:
s += prefix + 'Parameters:\n'
for pn in context.parameters:
p = context.parameters[pn]
s += prefix + Model.tab + p.name
s += ': ' + p.dimension
if p.value:
s += ': ' + str(p.value)
if p.fixed:
s += ' (fixed)'
if p.numeric_value:
s += ' - ' + str(p.numeric_value)
s += '\n'
if context.exposures:
s += prefix + 'Exposures:\n'
for name in context.exposures:
s += prefix + Model.tab + name + '\n'
if context.requirements:
s += prefix + 'Requirements:\n'
for name in context.requirements:
s += prefix + Model.tab + name + '\n'
if context.texts:
s += prefix + 'Text variables:\n'
for name in context.texts:
value = context.texts[name]
s += prefix + Model.tab + name
if value:
s += ': ' + value + '\n'
else:
s += '\n'
if context.paths:
s += prefix + 'Path variables:\n'
for name in context.paths:
value = context.paths[name]
s += prefix + Model.tab + name
if value:
s += ': ' + value + '\n'
else:
s += '\n'
if context.dynamics_profiles:
s += prefix + 'Dynamics profiles:\n'
for name in context.dynamics_profiles:
dynamics = context.dynamics_profiles[name]
s += self.dynamics2str(dynamics, prefix + Model.tab)
if context.event_in_ports:
s += prefix + 'Event in ports:\n'
for port in context.event_in_ports:
s += prefix + Model.tab + port + '\n'
if context.event_out_ports:
s += prefix + 'Event out ports:\n'
for port in context.event_out_ports:
s += prefix + Model.tab + port + '\n'
if context.structure:
s += self.structure2str(context.structure, prefix)
if context.simulation.runs or context.simulation.records or context.simulation.data_displays:
s += self.simulation2str(context.simulation, prefix)
return s
def __str__(self):
s = ''
s += 'Targets:\n'
for run in self.targets:
s += Model.tab + run + '\n'
s += 'Dimensions:\n'
if self.dimensions != None:
for d in self.dimensions:
s += Model.tab + d + '\n'
s += 'Units:\n'
if self.units != None:
for u in self.units:
s += Model.tab + u + '\n'
if self.context:
s += 'Global context:\n'
s += self.context2str(self.context, '')
return s
<file_sep>"""
Context storage
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.errors import ModelError
from lems.model.dynamics import Dynamics
from lems.model.structure import Structure
from lems.model.simulation import Simulation
from lems.model.parameter import Parameter
from lems.base.util import merge_dict, merge_ordered_dict
class Context(LEMSBase):
"""
Stores the current type and variable context.
"""
GLOBAL = 0
""" Global context """
COMPONENT_TYPE = 1
""" Component type context """
COMPONENT = 2
""" Component context """
def __init__(self, name, parent = None, context_type = GLOBAL):
"""
Constructor
"""
self.name = name
""" Name identifying this context.
@type: string """
self.parent = parent
""" Reference to parent context.
@type: lems.model.context.Context """
self.context_type = context_type
""" Context type (Global, component type or component)
@type: enum(Context.GLOBAL, Context.COMPONENT_TYPE or
Context.COMPONENT_TYPE) """
self.component_types = {}
""" Dictionary of component types defined in this conext.
@type: dict(string -> lems.model.component.ComponentType) """
self.components = {}
""" Dictionary of components defined in this context.
@type: dict(string -> lems.model.component.Component) """
self.components_ordering = []
""" Ordering for components defined in this context.
@type: list(string) """
self.component_refs = {}
""" Dictionary of component references defined in this context.
@type: dict(string -> string) """
self.child_defs = {}
""" Dictionary of single-instance child object definitions in this
context.
@type: dict(string -> string) """
self.children_defs = {}
""" Dictionary of multi-instance child objects definitions in this
context.
@type: dict(string -> string) """
self.children = []
""" List of child objects defined in this context.
@type: list(lems.model.component.Component) """
self.parameters = {}
""" Dictionary of references to parameters defined in this context.
@type: dict(string -> lems.model.parameter.Parameter) """
self.derived_parameters = {}
""" Dictionary of references to derived parameters defined in
this context.
@type: dict(string -> lems.model.parameter.DerivedParameter) """
self.dynamics_profiles = {}
""" Stores the various dynamics profiles of the current object.
@type: dict(string -> lems.model.dynamics.Dynamics) """
self.selected_dynamics_profile = None
""" Name of the dynamics dynamics profile.
@type: lems.model.dynamics.Dynamics """
self.exposures = set()
""" List of names of exposed variables.
@type: set(string) """
self.requirements = {}
""" List of names of required variables.
@type: dict(string -> string) """
self.texts = {}
""" Dictionary of text parameters.
@type: dict(string -> string) """
self.paths = {}
""" Dictionary of path parameters.
@type: dict(string -> string) """
self.links = {}
""" Dictionary of link parameters.
@type: dict(string -> string) """
self.event_in_ports = set()
""" List of incoming event port names.
@type: set(string) """
self.event_out_ports = set()
""" List of outgoing event port names.
@type: set(string) """
self.structure = Structure()
""" Structure object detailing structural aspects of this component.
@type: lems.model.structure.Structure """
self.simulation = Simulation()
""" Simulation object detailing simulation-related aspects of this component.
@type: lems.model.simulation.Simulation """
self.attachments = dict()
""" Dictionary of attachments in this component-type
@type: dict(string -> string """
def add_component_type(self, component_type):
"""
Adds a component type to the list of defined component types in the
current context.
@param component_type: Component type to be added
@type component_type: lems.model.component.ComponentType
@raise ModelError: Raised when the component type is already defined
in the current context.
"""
if component_type.name in self.component_types:
raise ModelError("Duplicate component type '{0}'".format(\
component_type.name))
self.component_types[component_type.name] = component_type
def add_component(self, component):
"""
Adds a component to the list of defined components in the current
context.
@param component: Component to be added
@type component: lems.model.component.ComponentType
@raise ModelError: Raised when the component is already defined in the
current context.
"""
if component.id in self.components:
raise ModelError("Duplicate component '{0}'".format(component.id))
self.components[component.id] = component
self.components_ordering.append(component.id)
def add_component_ref(self, name, type):
"""
Adds a component reference to the list of defined component
references in the current context.
@param name: Name of the component reference.
@type name: string
@param type: Type of the component reference.
@type type: string
@raise ModelError: Raised when the component reference is already
defined in the current context.
"""
if name in self.component_refs:
raise ModelError("Duplicate component reference '{0}'".format(\
name))
self.component_refs[name] = type
def add_child(self, child):
"""
Adds a child object to the list of child objects in the
current context.
@param child: Child object.
@type child: lems.model.component.Component
@raise ModelError: Raised when a child is instantiated inside a
component type.
"""
if self.context_type == Context.COMPONENT_TYPE:
raise ModelError("Child definition '{0}' not permitted in "
"component type definition '{1}'".format(\
child.id, self.name))
self.children.append(child)
def add_child_def(self, name, type):
"""
Adds a child object definition to the list of single-instance child
object definitions in the current context.
@param name: Name of the child object.
@type name: string
@param type: Type of the child object.
@type type: string
@raise ModelError: Raised when the definition is already in the
current context.
"""
if name in self.child_defs:
raise ModelError("Duplicate child definition '{0}'".format(name))
self.child_defs[name] = type
def add_children_def(self, name, type):
"""
Adds a child object definition to the list of multi-instance child
object definitions in the current context.
@param name: Name of the child object.
@type name: string
@param type: Type of the child object.
@type type: string
@raise ModelError: Raised when the definition is already in the
current context.
"""
if name in self.children_defs:
raise ModelError("Duplicate children definition '{0}'".format(\
name))
self.children_defs[name] = type
def add_parameter(self, parameter):
"""
Adds a parameter to the list of defined parameters in the current
context.
@param parameter: Parameter to be added
@type parameter: lems.model.parameter.Parameter
@raise ModelError: Raised when the parameter is already defined in the
current context.
"""
if parameter.name in self.parameters:
raise ModelError("Duplicate parameter '{0}'".format(\
parameter.name))
self.parameters[parameter.name] = parameter
def add_derived_parameter(self, parameter):
"""
Adds a parameter to the list of defined parameters in the current
context.
@param parameter: Parameter to be added
@type parameter: lems.model.parameter.DerivedParameter
@raise ModelError: Raised when the parameter is already defined in the
current context.
"""
if parameter.name in self.derived_parameters:
raise ModelError("Duplicate derived parameter '{0}'".format(
parameter.name))
self.derived_parameters[parameter.name] = parameter
def add_dynamics_profile(self, name):
"""
Adds a dynamics profile to the current context.
@param name: Name of the dynamics profile.
@type name: string
"""
if name in self.dynamics_profiles:
raise ModelError("Duplicate dynamics profile '{0}'".format(name))
self.dynamics_profiles[name] = Dynamics(name)
self.select_dynamics_profile(name)
def select_dynamics_profile(self, name):
"""
Selects a dynamics profile by name.
@param name: Name of the dynamics profile.
@type name: string
@raise ModelError: Raised when the specified dynamics profile is
undefined in the current context.
"""
if name not in self.dynamics_profiles:
raise ModelError("Unknown dynamics profile '{0}'".format(name))
self.selected_dynamics_profile = self.dynamics_profiles[name]
def add_exposure(self, name):
"""
Adds a state variable exposure to the current context.
@param name: Name of the state variable being exposed.
@type name: string
@raise ModelError: Raised when the exposure name already exists
in the current context.
@raise ModelError: Raised when the exposure name is not
being defined in the context of a component type.
"""
if self.context_type != Context.COMPONENT_TYPE:
raise ModelError("Exposure names can only be defined in "
"a component type - '{0}'".format(name))
if name in self.exposures:
raise ModelError("Duplicate exposure name '{0}'".format(name))
self.exposures.add(name)
def add_requirement(self, name, dimension):
"""
Adds a parameter requirement to the current context.
@param name: Name of the variable being required.
@type name: string
@param dimension: Dimension of the variable being required.
@type dimension: string
@raise ModelError: Raised when the exposure name already exists
in the current context.
@raise ModelError: Raised when the exposure name is not
being defined in the context of a component type.
"""
if self.context_type != Context.COMPONENT_TYPE:
raise ModelError("Requirements can only be defined in "
"a component type - '{0}'".format(name))
if name in self.requirements:
raise ModelError("Duplicate requirement name '{0}'".format(name))
self.requirements[name] = dimension
def add_text_var(self, name, value = None):
"""
Adds a text variable to the current context.
@param name: Name of the text variable.
@type name: string
@param value: Value of the text variable.
@type value: string
@raise ModelError: Raised when the text variable already exists
in the current context.
"""
if self.context_type != Context.COMPONENT_TYPE:
raise ModelError("Text variables can only be defined in "
"a component type - '{0}'".format(name))
if name in self.texts:
raise ModelError("Duplicate text variable '{0}'".format(name))
self.texts[name] = value
def add_path_var(self, name, value = None):
"""
Adds a path variable to the current context.
@param name: Name of the path variable.
@type name: string
@param value: Value of the path variable.
@type value: string
@raise ModelError: Raised when the path variable already exists
in the current context.
"""
if self.context_type != Context.COMPONENT_TYPE:
raise ModelError("Path variables can only be defined in "
"a component type - '{0}'".format(name))
if name in self.paths:
raise ModelError("Duplicate path variable '{0}'".format(name))
self.paths[name] = value
def add_link_var(self, name, type = None):
"""
Adds a link variable to the current context.
@param name: Name of the link variable.
@type name: string
@param type: Type of the link variable.
@type type: string
@raise ModelError: Raised when the link variable already exists
in the current context.
"""
if self.context_type != Context.COMPONENT_TYPE:
raise ModelError("Link variables can only be defined in "
"a component type - '{0}'".format(name))
if name in self.links:
raise ModelError("Duplicate link variable '{0}'".format(name))
self.links[name] = type
def add_event_port(self, name, direction):
"""
Adds an event port to the list of event ports handled by this
component or component type.
@param name: Name of the event port.
@type name: string
@param direction: Event direction ('in' or 'out').
@type direction: string
@raise ModelError: Raised when the definition is already in the
current context.
"""
if name in self.event_in_ports or name in self.event_out_ports:
raise ModelError("Duplicate event '{0}'".format(name))
if direction == 'in':
self.event_in_ports.add(name)
else:
self.event_out_ports.add(name)
def add_attachment(self, name, type_):
"""
Adds an attachment to this component-type.
@param name: Name of the attachment.
@type name: string
@param type_: Type of the attachment.
@type type_: string
@raise ModelError: Raised when the attachment is already in the
current context.
"""
if name in self.attachments:
raise ModelError("Duplicate attachment '{0}'".format(name))
self.attachments[type_] = name
def lookup_component_type(self, name):
"""
Searches the current context and parent contexts for a component type
with the given name.
@param name: Name of the component type.
@type name: string
@return: Resolved component type object, or None on failure.
@rtype: lems.model.component.ComponentType
"""
if name in self.component_types:
return self.component_types[name]
elif self.parent:
return self.parent.lookup_component_type(name)
else:
return None
def lookup_component(self, name):
"""
Searches the current context and parent contexts for a component
with the given name.
@param name: Name of the component.
@type name: string
@return: Resolved component object, or None on failure.
@rtype: lems.model.component.Component
"""
if name in self.components:
return self.components[name]
elif self.parent:
return self.parent.lookup_component(name)
else:
return None
def lookup_component_ref(self, name):
"""
Searches the current context and parent contexts for a component
with the given name.
@param name: Name of the component.
@type name: string
@return: Resolved component object, or None on failure.
@rtype: lems.model.component.Component
"""
if name in self.component_refs:
cname = self.component_refs[name]
return self.lookup_component(cname)
elif self.parent:
return self.parent.lookup_component_ref(name)
else:
return None
def lookup_child(self, name):
"""
Searches the current context and parent contexts for a child
with the given name.
@param name: Name of the component.
@type name: string
@return: Component type for the child, or None on failure.
@rtype: string
"""
if name in self.child_defs:
return self.child_defs[name]
elif self.parent:
return self.parent.lookup_child(name)
else:
return None
def lookup_parameter(self, parameter_name):
"""
Looks up a parameter by name within this context.
@param parameter_name: Name of the parameter.
@type parameter_name: string
@return: Corresponding Parameter object or None if not found.
@rtype: lems.model.parameter.Parameter
"""
if parameter_name in self.parameters:
return self.parameters[parameter_name]
else:
return None
def lookup_path_parameter(self, path_name):
"""
Looks up a path parameter.
@param path_name: Name of the path parameter.
@type path_name: string
@return: Value of the path parameter
@rtype: string
"""
path_param = self.lookup_parameter(path_name)
if path_param == None or path_param.dimension != '__path__':
return None
else:
return path_param.value
def lookup_text_parameter(self, text_name):
"""
Looks up a text parameter.
@param text_name: Name of the text parameter.
@type text_name: string
@return: Value of the text parameter
@rtype: string
"""
text_param = self.lookup_parameter(text_name)
if text_param == None or text_param.dimension != '__text__':
return None
else:
return text_param.value
def merge(self, other, model):
"""
Merge another context (base or type context) into this one.
@param other: Base or type context to be merged in
@type other: lems.model.context.Context
"""
merge_dict(self.component_types, other.component_types)
merge_ordered_dict(self.components, self.components_ordering,
other.components, other.components_ordering)
merge_dict(self.component_refs, other.component_refs)
merge_dict(self.child_defs, other.child_defs)
merge_dict(self.children_defs, other.children_defs)
for child in other.children:
self.children.append(child)
if (self.context_type == other.context_type and
self.context_type in [Context.COMPONENT_TYPE, Context.COMPONENT]):
self.merge_extended_parameters(other)
elif (self.context_type == Context.COMPONENT and
other.context_type == Context.COMPONENT_TYPE):
self.merge_component_parameters_from_component_type(other, model)
merge_dict(self.dynamics_profiles, other.dynamics_profiles)
if not self.selected_dynamics_profile:
self.selected_dynamics_profile = other.selected_dynamics_profile
self.exposures |= other.exposures
merge_dict(self.requirements, other.requirements)
merge_dict(self.texts, other.texts)
merge_dict(self.paths, other.paths)
merge_dict(self.links, other.links)
self.event_in_ports |= other.event_in_ports
self.event_out_ports |= other.event_out_ports
if (self.context_type == Context.COMPONENT and
other.context_type == Context.COMPONENT_TYPE):
self.structure.merge_from_type(other.structure, self)
else:
self.structure.merge(other.structure)
self.simulation.merge(other.simulation)
merge_dict(self.attachments, other.attachments)
def merge_extended_parameters(self, other):
"""
Merge parameters from a base component or component type
into this one
@param other: Base or type context to be merged in
@type other: lems.model.context.Context
"""
for pn in other.parameters:
if pn in self.parameters:
pt = self.parameters[pn]
if pt.dimension == '__dimension_inherited__':
pb = other.parameters[pn]
self.parameters[pn] = Parameter(pt.name,
pb.dimension,
pt.fixed,
pt.value)
else:
raise ModelError(('Parameter {0} in {1} is redefined ' +
'in {2}').format(pn, other.name,
self.name))
else:
self.parameters[pn] = other.parameters[pn].copy()
def merge_component_parameters_from_component_type(self, type_context, model):
"""
Merge component parameters from a component type
definition.
@param type_context: Type context to be merged in
@type type_context: lems.model.context.Context
"""
for pn in type_context.parameters:
pt = type_context.parameters[pn]
if pn in self.parameters:
pc = self.parameters[pn]
if pc.value:
value = pc.value
else:
value = pt.value
if pc.dimension == '__dimension_inherited__':
if pt.fixed:
np = Parameter(pn, pt.dimension, pt.fixed, value)
else:
np = Parameter(pn, pt.dimension, pc.fixed, value)
self.parameters[pn] = np
else:
self.parameters[pn] = pt.copy()
model.resolve_parameter_value(self.parameters[pn],
self)
for pn in self.parameters:
pc = self.parameters[pn]
if pc.dimension == '__dimension_inherited__':
if pn in type_context.texts:
pc.dimension = '__text__'
self.texts[pn] = type_context.texts[pn]
elif pn in type_context.paths:
pc.dimension = '__path__'
self.paths[pn] = type_context.paths[pn]
elif pn in type_context.links:
pc.dimension = '__link__'
self.links[pn] = type_context.links[pn]
elif pn in type_context.component_refs:
pc.dimension = '__component_ref__'
cf = type_context.component_refs[pn]
self.component_refs[pn] = pc.value
class Contextual(LEMSBase):
"""
Base class for objects that need to store their own context.
"""
def __init__(self, name, parent = None, context_type = Context.GLOBAL):
"""
Constructor.
"""
self.context = Context(name, parent, context_type)
""" Context object.
@type: lems.model.context.Context """
def add_component_type(self, component_type):
"""
Adds a component type to the list of defined component types in the
current context.
@param component_type: Component type to be added
@type component_type: lems.model.component.ComponentType
"""
self.context.add_component_type(component_type)
def add_component(self, component):
"""
Adds a component to the list of defined components in the current
context.
@param component: Component to be added
@type component: lems.model.component.Component
"""
self.context.add_component(component)
def add_parameter(self, parameter):
"""
Adds a parameter to the list of defined parameters in the current
context.
@param parameter: Parameter to be added
@type parameter: lems.model.parameter.Parameter
"""
self.context.add_parameter(parameter)
def lookup_parameter(self, parameter_name):
"""
Lookup a parameter in this context by name.
@param parameter_name: Name of the parameter.
@type parameter_name: string
@return: Corresponding Parameter object or None if not found.
@rtype: lems.model.parameter.Parameter
"""
return self.context.lookup_parameter(parameter_name)
<file_sep>"""
Types for component types and components
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.errors import ModelError
from lems.model.context import Context,Contextual
from lems.model.parameter import Parameter
class ComponentType(Contextual):
"""
Stores the specification of a user-defined component type.
"""
def __init__(self, name, context, extends = None):
"""
Constructor
@param name: Name of this component type.
@type name: string
@param context: The context in which to create this component type.
@type context: lems.model.context.Context
@param extends: Base component type extended by this type.
@type extends: string
"""
Contextual.__init__(self, name, context, Context.COMPONENT_TYPE)
self.name = name
""" Name of this component type.
@type: string """
self.extends = extends
""" Base component type extended by this type.
@type: string """
self.types = set()
""" List of compatible type (base types).
@type: set(string) """
self.types.add(name)
if extends:
self.types.add(extends)
def fix_parameter(self, parameter_name, value_string, model):
"""
Fixes the value of a parameter to the specified value.
@param parameter_name: Name of the parameter to be fixed.
@type parameter_name: string
@param value_string: Value to which the parameter needs to be fixed to.
For example, "30mV" or "45 kg"
@type string
@param model: Model object storing the current model. (Needed to find
the dimension for the specified symbol)
@type model: lems.model.model.Model
@attention: Having to pass the model in as a parameter is a temporary
hack. This should fixed at some point of time, once PyLEMS is able to
run a few example files.
@raise ModelError: Raised when the parameter does not exist in this
component type.
"""
parameter = self.lookup_parameter(parameter_name)
if parameter == None:
raise ModelError('Parameter ' + value_string +
' not present in ' + self.name)
parameter.fix_value(value_string, model)
class Component(Contextual):
"""
Stores a single instance of a given component type.
"""
def __init__(self, id_, context, component_type, extends = None):
"""
Constructor
@param id_: Id/name for this component.
@type id_: string
@param context: The context in which to create this component.
@type context: lems.model.context.Context
@param component_type: Type of component.
@type component_type: string
@param extends: Component extended by this one.
@param extends: string
@note: Atleast one of component_type or extends must be valid.
"""
Contextual.__init__(self, id_, context, Context.COMPONENT)
self.id = id_
""" Globally unique name for this component.
@type: string """
self.component_type = component_type
""" Type of component.
@type: string """
if component_type == None and extends == None:
raise ModelError('Component definition requires a component type ' +
'or a base component')
self.extends = extends
""" Name of component extended by this component..
@type: string """
def is_type(self, component_type):
"""
Check if this component is an instance of the specified component
type.
@param component_type: Name of the component type.
@type component_type: string
@return: Returns True if this component is of the specified type,
otherwide False
@rtype: Boolean
"""
typeobj = self.context.lookup_component_type(self.component_type)
return component_type in typeobj.types
<file_sep>"""
Simulation.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.errors import SimError
import heapq
class Simulation(LEMSBase):
"""
Simulation class.
"""
def __init__(self):
"""
Constructor.
"""
self.runnables = {}
""" Dictionary of runnable components in this simulation.
@type: dict(string -> lems.sim.runnable.Runnable) """
self.run_queue = []
""" Priority of pairs of (time-to-next run, runnable).
@type: list((Integer, lems.sim.runnable.Runnable)) """
self.event_queue = []
""" List of posted events.
@type: list(lems.sim.sim.Event) """
def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimError('Duplicate runnable component {0}'.format(runnable.id))
self.runnables[runnable.id] = runnable
def init_run(self):
self.current_time = 0
for id in self.runnables:
heapq.heappush(self.run_queue, (0, self.runnables[id]))
def step(self):
current_time = self.current_time
if self.run_queue == []:
return False
(current_time, runnable) = heapq.heappop(self.run_queue)
time = current_time
while time == current_time:
next_time = current_time + runnable.single_step(\
runnable.time_step)
if next_time > current_time:
heapq.heappush(self.run_queue, (next_time, runnable))
if self.run_queue == []:
break
(time, runnable) = heapq.heappop(self.run_queue)
if time > current_time:
heapq.heappush(self.run_queue, (time, runnable))
self.current_time = current_time
if self.run_queue == []:
return False
else:
return True
def run(self):
"""
Runs the simulation.
"""
self.init_run()
while self.step():
pass
def push_state(self):
for id in self.runnables:
self.runnables[id].push_state()
def pop_state(self):
for id in self.runnables:
self.runnables[id].pop_state()
def enable_plasticity(self):
for id in self.runnables:
self.runnables[id].plastic = True
def disable_plasticity(self):
for id in self.runnables:
self.runnables[id].plastic = False
def dump_runnable(self, runnable, prefix = ''):
r = runnable
print('{0}{1} ({2})'.format(prefix, r.id, r.component.component_type))
#if r.instance_variables:
# print('{0} Instance variables'.format(prefix))
# for vn in r.instance_variables:
# print('{0} {1} = {2}'.format(prefix, vn, r.__dict__[vn]))
#if r.derived_variables:
# print('{0} Derived variables'.format(prefix))
# for vn in r.derived_variables:
# print('{0} {1} = {2}'.format(prefix, vn, r.__dict__[vn]))
if r.array:
for c in r.array:
self.dump_runnable(c, prefix + ' ')
if r.uchildren:
print('{0} Children'.format(prefix))
for cn in r.uchildren:
self.dump_runnable(r.uchildren[cn], prefix + ' ')
def dump(self):
print('Runnables:')
for id in self.runnables:
self.dump_runnable(self.runnables[id])
class Event:
"""
Stores data associated with an event.
"""
def __init__(self, from_id, to_id):
self.from_id = from_id
""" ID of the source runnable for this event.
@type: Integer """
self.to_id = to_id
""" ID of the destination runnable for this event.
@type: Integer """
<file_sep>"""
LEMS parser
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import os.path
from lems.model.simple import Dimension,Unit
from lems.base.parser import Parser
from lems.model.model import Model
from lems.base.errors import ParseError,ModelError
from lems.model.context import Context,Contextual
from lems.model.component import Component,ComponentType
from lems.model.parameter import Parameter,DerivedParameter
from lems.model.dynamics import *
#Dynamics,Regime,OnCondition,OnEvent,StateAssignment
import re
import xml.etree.ElementTree
def xmltolower(node):
"""
Converts the tag and attribute names in the given XML node and
child nodes to lower case. To convert the entire tree, pass in the
root.
@param node: Node in an XML tree.
@type node: xml.etree.Element
"""
node.lattrib = dict()
for key in node.attrib:
node.lattrib[key.lower()] = node.attrib[key]
for child in node:
xmltolower(child)
def open_file(filename, xslt_preprocessor_callback):
xmltext = open(filename).read()
# Cleanup LEMS file
xmltext = re.sub('<([Ll][Ee][Mm][Ss])[^>]*>', r'<\1>', xmltext, 0, re.DOTALL)
if xslt_preprocessor_callback:
return xml.etree.ElementTree.XML(xslt_preprocessor_callback(xmltext))
else:
return xml.etree.ElementTree.XML(xmltext).getroot()
class LEMSParser(Parser):
"""
Parser for LEMS files
"""
def push_context(self, context):
self.context_stack = [context] + self.context_stack
self.current_context = context
def pop_context(self):
if len(self.context_stack) == 0:
self.raise_error('Context stack underflow')
self.context_stack = self.context_stack[1:]
if len(self.context_stack) == 0:
self.current_context = None
else:
self.current_context = self.context_stack[0]
def push_component_type(self, component_type):
self.component_type_stack = [component_type] + \
self.component_type_stack
self.current_component_type = component_type
def pop_component_type(self):
if len(self.component_type_stack) == 0:
self.raise_error('Component_Type stack underflow')
self.component_type_stack = self.component_type_stack[1:]
if len(self.component_type_stack) == 0:
self.current_component_type = None
else:
self.current_component_type = self.component_type_stack[0]
def __init__(self, xslt_preprocessor_callback = None, include_dirs = [], alternate_root_element_tags = []):
"""
Constructor.
@param xslt_preprocessor_callback: XSLT preprocessor callback.
@type xslt_preprocessor_callback: fn
"""
self.base_path = '.'
""" Base path for the file being parsed
@type: string """
self.model = None
""" Model built during parsing
@type: lems.model.model.model """
self.tag_parse_table = None
""" Dictionary of xml tags to parse methods
@type: dict(string -> function) """
self.valid_children = None
""" Dictionary mapping each tag to it's list of valid child tags.
@type: dict(string -> string) """
self.context_stack = []
""" Stack of contexts used for handling nested contexts.
@type: list(lems.model.context.Context) """
self.current_context = None
""" Currently active (being parsed) context.
@type: lems.model.context.Context """
self.component_type_stack = []
""" Stack of component type objects used for handling nested
component types.
@type: list(lems.model.parameter.ComponentType) """
self.current_component_type = None
""" Component type object being parsed.
@type: lems.model.parameter.ComponentType """
self.current_dynamics_profile = None
""" Current dynamics profile being parsed.
@type: lems.model.dynamics.Dynamics """
self.current_regime = None
""" Current dynamics regime being parsed.
@type: lems.model.dynamics.Regime """
self.current_event_handler = None
""" Current event_handler being parsed.
@type: lems.model.dynamics.EventHandler """
self.current_simulation = None
""" Current simulation section being parsed.
@type: lems.model.simulation.Simulation """
self.current_structure = None
""" Current structure being parsed.
@type: lems.model.structure.Structure """
self.xml_node_stack = []
""" XML node stack.
@type: list(xml.etree.Element) """
self.xslt_preprocessor_callback = xslt_preprocessor_callback
""" XSLT preprocessor callback.
@type: fn """
self.include_dirs = include_dirs
""" List of directories to search for include files
@type: list(string) """
self.included_files = []
""" List of files already included.
@type: list(string) """
self.init_parser()
self.xml_root = None
""" Root element of current XML file
@type: xml.etree.Element """
self.alternate_root_element_tags = alternate_root_element_tags
""" List of alternate tag names to <LEMS> that can be accepted
as a root element name.
@type: list(string) """
def init_parser(self):
"""
Initializes the parser
"""
self.model = Model()
self.token_list = None
self.prev_token_lists = None
self.valid_children = dict()
self.valid_children['lems'] = ['component', 'componenttype',
'target', 'include',
'dimension', 'unit', 'assertion']
self.valid_children['componenttype'] = ['dynamics',
'child', 'children',
'componentreference',
'exposure', 'eventport',
'fixed', 'link', 'parameter',
'path', 'requirement',
'simulation', 'structure',
'text', 'attachments',
'constant', 'derivedparameter']
self.valid_children['dynamics'] = ['derivedvariable',
'oncondition', 'onentry',
'onevent', 'onstart',
'statevariable', 'timederivative',
'kineticscheme', 'regime']
self.valid_children['regime'] = ['derivedvariable',
'oncondition', 'onentry',
'onevent', 'onstart',
'statevariable', 'timederivative',
'kineticscheme', 'transition']
self.valid_children['oncondition'] = ['eventout', 'stateassignment']
self.valid_children['onentry'] = ['eventout', 'stateassignment']
self.valid_children['onevent'] = ['eventout', 'stateassignment']
self.valid_children['onstart'] = ['eventout', 'stateassignment']
self.valid_children['structure'] = ['childinstance',
'eventconnection',
'foreach',
'multiinstantiate']
self.valid_children['simulation'] = ['record', 'run',
'datadisplay', 'datawriter']
self.tag_parse_table = dict()
self.tag_parse_table['assertion'] = self.parse_assertion
self.tag_parse_table['attachments'] = self.parse_attachments
self.tag_parse_table['child'] = self.parse_child
self.tag_parse_table['childinstance'] = self.parse_child_instance
self.tag_parse_table['children'] = self.parse_children
self.tag_parse_table['component'] = self.parse_component
self.tag_parse_table['componentreference'] = self.parse_component_reference
self.tag_parse_table['componenttype'] = self.parse_component_type
self.tag_parse_table['constant'] = self.parse_constant
self.tag_parse_table['datadisplay'] = self.parse_data_display
self.tag_parse_table['datawriter'] = self.parse_data_writer
self.tag_parse_table['derivedparameter'] = self.parse_derived_parameter
self.tag_parse_table['derivedvariable'] = self.parse_derived_variable
self.tag_parse_table['dimension'] = self.parse_dimension
self.tag_parse_table['dynamics'] = self.parse_dynamics
self.tag_parse_table['eventconnection'] = self.parse_event_connection
self.tag_parse_table['eventout'] = self.parse_event_out
self.tag_parse_table['eventport'] = self.parse_event_port
self.tag_parse_table['exposure'] = self.parse_exposure
self.tag_parse_table['fixed'] = self.parse_fixed
self.tag_parse_table['foreach'] = self.parse_foreach
self.tag_parse_table['include'] = self.parse_include
self.tag_parse_table['kineticscheme'] = self.parse_kinetic_scheme
self.tag_parse_table['link'] = self.parse_link
self.tag_parse_table['multiinstantiate'] = \
self.parse_multi_instantiate
self.tag_parse_table['oncondition'] = self.parse_on_condition
self.tag_parse_table['onentry'] = self.parse_on_entry
self.tag_parse_table['onevent'] = self.parse_on_event
self.tag_parse_table['onstart'] = self.parse_on_start
self.tag_parse_table['parameter'] = self.parse_parameter
self.tag_parse_table['path'] = self.parse_path
self.tag_parse_table['record'] = self.parse_record
self.tag_parse_table['regime'] = self.parse_regime
self.tag_parse_table['requirement'] = self.parse_requirement
self.tag_parse_table['run'] = self.parse_run
self.tag_parse_table['show'] = self.parse_show
self.tag_parse_table['simulation'] = self.parse_simulation
self.tag_parse_table['stateassignment'] = self.parse_state_assignment
self.tag_parse_table['statevariable'] = self.parse_state_variable
self.tag_parse_table['structure'] = self.parse_structure
self.tag_parse_table['target'] = self.parse_target
self.tag_parse_table['text'] = self.parse_text
self.tag_parse_table['timederivative'] = self.parse_time_derivative
self.tag_parse_table['transition'] = self.parse_transition
self.tag_parse_table['unit'] = self.parse_unit
self.tag_parse_table['with'] = self.parse_with
def counter():
count = 1
while True:
yield count
count = count + 1
self.id_counter = counter()
""" Counter genertor for generating unique ids.
@type: int """
prefix = ''
def process_nested_tags(self, node):
"""
Process child tags.
@param node: Current node being parsed.
@type node: xml.etree.Element
@raise ParseError: Raised when an unexpected nested tag is found.
"""
#self.prefix += ' '
for child in node:
self.xml_node_stack = [child] + self.xml_node_stack
ctagl = child.tag.lower()
if ctagl in self.tag_parse_table:
self.tag_parse_table[ctagl](child)
else:
raise ParseError("Unrecognized tag '{0}'".format(ctagl))
#self.parse_component_by_typename(child, child.tag)
self.xml_node_stack = self.xml_node_stack[1:]
#self.prefix = self.prefix[2:]
def resolve_typename(self, typename):
"""
Resolves type name from the contex stack.
@param typename: Name of the type to be resolved.
@type typename: string
@return: Component type corresponding to the type name or None if
undefined.
@rtype: lems.model.component.ComponentType
"""
stack = self.context_stack
found = False
while stack != [] and (not found):
if typename in stack[0].component_types:
found = True
if found:
return stack[0].component_types[typename]
else:
return None
def resolve_component_name(self, component_name):
"""
Resolves component name from the context stack.
@param component_name: Name of the component to be resolved.
@type component_name: string
@return: Component corresponding to the name or None if undefined.
@rtype: lems.model.component.Component
"""
stack = self.context_stack
found = False
while stack != [] and (not found):
if component_name in stack[0].components:
found = True
if found:
return stack[0].components[component_name]
else:
return None
def raise_error(self, message):
s = 'Parser error in '
self.xml_node_stack.reverse()
if len(self.xml_node_stack) > 1:
node = self.xml_node_stack[0]
s += '<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
for node in self.xml_node_stack[1:]:
s += '.<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
s += ':\n ' + message
raise ParseError(s)
self.xml_node_stack.reverse()
def get_model(self):
"""
Returns the generated model.
@return: The generated model.
@rtype: lems.model.model.Model
"""
return self.model
def parse_assertion(self, node):
"""
Parses <Assertion>
@param node: Node containing the <Assertion> element
@type node: xml.etree.Element
"""
print('TODO - <Assertion>')
def parse_attachments(self, node):
"""
Parses <Attachments>
@param node: Node containing the <Attachments> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Attachments can only be made in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Attachments> must specify a name for the ' +
'attachment.')
if 'type' in node.lattrib:
type_ = node.lattrib['type']
else:
self.raise_error('<Attachment> must specify a type for the ' +
'attachment.')
self.current_context.add_attachment(name, type_)
def parse_child(self, node):
"""
Parses <Child>
@param node: Node containing the <Child> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Child definitions can only be made in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Child> must specify a name for the ' +
'reference.')
if 'type' in node.lattrib:
type_ = node.lattrib['type']
else:
self.raise_error('<Child> must specify a type for the ' +
'reference.')
self.current_context.add_child_def(name, type_)
def parse_child_instance(self, node):
"""
Parses <ChildInstance>
@param node: Node containing the <ChildInstance> element
@type node: xml.etree.Element
"""
if self.current_structure == None:
self.raise_error('Child instantiations can only be made within ' +
'a structure definition')
if 'component' in node.lattrib:
component = node.lattrib['component']
else:
self.raise_error('<ChildInstance> must specify a component '
'reference')
self.current_structure.add_single_child_def(component)
def parse_children(self, node):
"""
Parses <Children>
@param node: Node containing the <Children> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Children definitions can only be made in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Children> must specify a name for the ' +
'reference.')
if 'type' in node.lattrib:
type = node.lattrib['type']
else:
self.raise_error('<Children> must specify a type for the ' +
'reference.')
self.current_context.add_children_def(name, type)
def parse_component_by_typename(self, node, type):
"""
Parses components defined directly by component name.
@param node: Node containing the <Component> element
@type node: xml.etree.Element
@param type: Type of this component.
@type type: string
@raise ParseError: Raised when the component does not have an id.
"""
raise Exception(("Component initialized using typename "
"'{0}' as the XML tag").format(node.tag))
if self.current_context.context_type == Context.GLOBAL:
# Global component instatiation
if 'id' in node.lattrib:
id_ = node.lattrib['id']
else:
self.raise_error('Component must have an id')
type = node.tag
component = Component(id_, self.current_context, type, None)
self.current_context.add_component(component)
else:
# Child instantiation
if 'id' in node.lattrib:
id_ = node.lattrib['id']
type = node.tag
else:
id_ = node.tag
if 'type' in node.lattrib:
type = node.lattrib['type']
else:
type = '__type_inherited__'
component = Component(id_, self.current_context, type)
self.current_context.add_child(component)
for key in node.attrib:
if key.lower() not in ['extends', 'id', 'type']:
param = Parameter(key, '__dimension_inherited__')
param.set_value(node.attrib[key])
component.add_parameter(param)
self.push_context(component.context)
self.process_nested_tags(node)
self.pop_context()
def parse_component(self, node):
"""
Parses <Component>
@param node: Node containing the <Component> element
@type node: xml.etree.Element
"""
if 'id' in node.lattrib:
id_ = node.lattrib['id']
else:
#self.raise_error('Component must have an id')
id_ = self.model.make_id()
if 'type' in node.lattrib:
type = node.lattrib['type']
else:
type = None
if type == None:
if 'extends' in node.lattrib:
extends = node.lattrib['extends']
else:
self.raise_error('Component must have a type or must ' +
'extend another component')
else:
extends = None
if 'child' in node.lattrib:
child = node.lattrib['child']
id_ = child
else:
child = None
component = Component(id_, self.current_context, type, extends)
if child:
self.current_context.add_child(component)
else:
self.current_context.add_component(component)
for key in node.attrib:
if key.lower() not in ['extends', 'id', 'type', 'child']:
param = Parameter(key, '__dimension_inherited__')
param.set_value(node.attrib[key])
component.add_parameter(param)
self.push_context(component.context)
self.process_nested_tags(node)
self.pop_context()
def parse_component_reference(self, node):
"""
Parses <ComponentReference>
@param node: Node containing the <ComponentTypeRef> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Component references can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<ComponentReference> must specify a name for the ' +
'reference.')
if 'type' in node.lattrib:
type = node.lattrib['type']
else:
self.raise_error('<ComponentReference> must specify a type for the ' +
'reference.')
self.current_context.add_component_ref(name, type)
def parse_component_type(self, node):
"""
Parses <ComponentType>
@param node: Node containing the <ComponentType> element
@type node: xml.etree.Element
@raise ParseError: Raised when the component type does not have a
name.
"""
try:
name = node.lattrib['name']
except:
self.raise_error('Component type must have a name')
if 'extends' in node.lattrib:
extends = node.lattrib['extends']
else:
extends = None
component_type = ComponentType(name, self.current_context, extends)
self.current_context.add_component_type(component_type)
self.push_context(component_type.context)
self.process_nested_tags(node)
self.pop_context()
def parse_constant(self, node):
"""
Parses <Constant>
@param node: Node containing the <Constant> element
@type node: xml.etree.Element
@raise ParseError: Raised when the constant does not have a name.
@raise ParseError: Raised when the constant does not have a
dimension.
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Constants can only be defined in ' +
'a component type')
try:
name = node.lattrib['name']
except:
self.raise_error('Constant must have a name')
try:
dimension = node.lattrib['dimension']
except:
dimension = None
try:
value = node.lattrib['value']
except:
self.raise_error('Constant must have a value')
constant = Parameter(name, dimension, True, value)
self.current_context.add_parameter(constant)
def parse_data_display(self, node):
"""
Parses <DataDisplay>
@param node: Node containing the <DataDisplay> element
@type node: xml.etree.Element
"""
if self.current_simulation == None:
self.raise_error('<DataDisplay> must be defined inside a ' +
'simulation specification')
if 'title' in node.lattrib:
title = node.lattrib['title']
else:
self.raise_error('A data display must have a title')
if 'dataregion' in node.lattrib:
data_region = node.lattrib['dataregion']
else:
data_region = None
self.current_simulation.add_data_display(title, data_region)
def parse_data_writer(self, node):
"""
Parses <DataWriter>
@param node: Node containing the <DataWriter> element
@type node: xml.etree.Element
"""
if self.current_simulation == None:
self.raise_error('<DataWriter> must be defined inside a ' +
'simulation specification')
if 'path' in node.lattrib:
path = node.lattrib['path']
else:
self.raise_error('A data writer must have a path')
if 'filename' in node.lattrib:
file_path = node.lattrib['filename']
else:
self.raise_error('A data writer must have a file name')
self.current_simulation.add_data_writer(path, file_path)
def parse_derived_parameter(self, node):
"""
Parses <DerivedParameter>
@param node: Node containing the <DerivedParameter> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Dynamics must be defined inside a ' +
'component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A derived parameter must have a name')
if 'dimension' in node.lattrib:
dimension = node.lattrib['dimension']
else:
dimension = None
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
value = None
if 'select' in node.lattrib:
select = node.lattrib['select']
else:
select = None
self.current_context.add_derived_parameter(DerivedParameter(name, dimension,
value, select))
def parse_derived_variable(self, node):
"""
Parses <DerivedVariable>
@param node: Node containing the <DerivedVariable> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<DerivedVariable> must be defined inside a ' +
'dynamics profile or regime')
if 'name' in node.lattrib:
name = node.lattrib['name']
elif 'exposure' in node.lattrib:
name = node.lattrib['exposure']
else:
self.raise_error('A derived variable must have a name')
if 'exposure' in node.lattrib:
exposure = node.lattrib['exposure']
else:
exposure = None
if 'dimension' in node.lattrib:
dimension = node.lattrib['dimension']
else:
dimension = None
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
value = None
if 'select' in node.lattrib:
select = node.lattrib['select']
else:
select = None
if 'reduce' in node.lattrib:
reduce = node.lattrib['reduce']
else:
reduce = None
self.current_regime.add_derived_variable(name, exposure, dimension,
value, select, reduce)
def parse_dimension(self, node):
"""
Parses <Dimension>
@param node: Node containing the <Dimension> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or if the
dimension is not a signed integer.
"""
dim = list()
try:
name = node.lattrib['name']
for d in ['l', 'm', 't', 'i', 'k', 'c', 'n']:
dim.append(int(node.lattrib.get(d, 0)))
except:
self.raise_error('Invalid dimensionality format')
self.model.add_dimension(Dimension(name, dim[0], dim[1], dim[2],
dim[3], dim[4], dim[4], dim[6]))
def parse_dynamics(self, node):
"""
Parses <Dynamics>
@param node: Node containing the <Behaviour> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Dynamics must be defined inside a ' +
'component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
name = ''
self.current_context.add_dynamics_profile(name)
old_dynamics_profile = self.current_dynamics_profile
self.current_dynamics_profile = self.current_context.selected_dynamics_profile
old_regime = self.current_regime
self.current_regime = self.current_dynamics_profile.default_regime
self.process_nested_tags(node)
self.current_regime = old_regime
self.current_dynamics_profile = old_dynamics_profile
def parse_event_out(self, node):
"""
Parses <EventOut>
@param node: Node containing the <EventOut> element
@type node: xml.etree.Element
"""
if self.current_event_handler == None:
self.raise_error('<EventOut> must be defined inside an ' +
'event handler in a dynamics profile or regime')
if 'port' in node.lattrib:
port = node.lattrib['port']
else:
self.raise_error('\'port\' attribute not provided for ' +
'<StateAssignment>')
action = EventOut(port)
self.current_event_handler.add_action(action)
def parse_event_connection(self, node):
"""
Parses <EventConnection>
@param node: Node containing the <EventConnection> element
@type node: xml.etree.Element
"""
if self.current_structure == None:
self.raise_error('<EventConnection> must be defined inside a ' +
'structure definition')
if 'from' in node.lattrib:
from_ = node.lattrib['from']
else:
self.raise_error('\'from\' attribute not provided for ' +
'<EventConnection>')
if 'to' in node.lattrib:
to = node.lattrib['to']
else:
self.raise_error('\'to\' attribute not provided for ' +
'<EventConnection>')
source_port = node.lattrib.get('sourceport', '')
target_port = node.lattrib.get('targetport', '')
receiver = node.lattrib.get('receiver', '')
receiver_container = node.lattrib.get('receivercontainer', '')
self.current_structure.add_event_connection(from_, to,
source_port, target_port,
receiver, receiver_container)
def parse_event_port(self, node):
"""
Parses <EventPort>
@param node: Node containing the <EventPort> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Event ports can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error(('<EventPort> must specify a name for the '
'event port'))
if 'direction' in node.lattrib:
direction = node.lattrib['direction']
else:
self.raise_error(('<EventPort> must specify a direction for the '
'event port'))
direction = direction.lower()
if direction != 'in' and direction != 'out':
self.raise_error(('Event port direction must be \'in\' '
'or \'out\''))
self.current_context.add_event_port(name, direction)
def parse_exposure(self, node):
"""
Parses <Exposure>
@param node: Node containing the <Exposure> element
@type node: xml.etree.Element
@raise ParseError: Raised when the exposure name is not
being defined in the context of a component type.
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Exposure names can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
self.current_context.add_exposure(node.lattrib['name'])
def parse_fixed(self, node):
"""
Parses <Fixed>
@param node: Node containing the <Fixed> element
@type node: xml.etree.Element
@raise ParseError: Raised when
"""
try:
parameter = node.lattrib['parameter']
except:
self.raise_error('Parameter to be fixed must be specified')
try:
value = node.lattrib['value']
except:
self.raise_error('Value to be fixed must be specified')
if self.current_context.lookup_parameter(parameter) == None:
self.current_context.add_parameter(Parameter(
parameter, '__dimension_inherited__'))
self.current_context.lookup_parameter(parameter).fix_value(value)
def parse_foreach(self, node):
"""
Parses <ForEach>
@param node: Node containing the <ForEach> element
@type node: xml.etree.Element
"""
if self.current_structure == None:
self.raise_error('<ForEach> can only be made within ' +
'a structure definition')
if 'instances' in node.lattrib:
target = node.lattrib['instances']
else:
self.raise_error('<ForEach> must specify a reference to target'
'instances')
if 'as' in node.lattrib:
name = node.lattrib['as']
else:
self.raise_error('<ForEach> must specify a name for the '
'enumerated target instances')
old_structure = self.current_structure
self.current_structure = self.current_structure.add_foreach(\
name, target)
self.process_nested_tags(node)
self.current_structure = old_structure
def parse_include(self, node):
"""
Parses <Include>
@param node: Node containing the <Include> element
@type node: xml.etree.Element
"""
if 'file' not in node.lattrib:
self.raise_error('Include file must be specified.')
path = self.base_path + '/' + node.lattrib['file']
root = None
if path not in self.included_files:
self.included_files.append(path)
try:
root = open_file(path, self.xslt_preprocessor_callback)
except:
for include_dir in self.include_dirs:
path = include_dir + '/' + node.lattrib['file']
if path not in self.included_files:
try:
root = open_file(path, self.xslt_preprocessor_callback)
except:
pass
if root == None:
raise ParseError("Unable to find included file '{0}'".format(node.lattrib['file']))
xmltolower(root)
self.parse_root(root)
def parse_kinetic_scheme(self, node):
"""
Parses <KineticScheme>
@param node: Node containing the <KineticScheme> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<KineticScheme> must be defined inside a ' +
'dynamics profile or regime')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A name must be provided for <KineticScheme>')
if 'nodes' in node.lattrib:
nodes = node.lattrib['nodes']
else:
self.raise_error("The 'nodes' must be provided for <KineticScheme>")
if 'statevariable' in node.lattrib:
state_variable = node.lattrib['statevariable']
else:
self.raise_error("The 'stateVariable' must be provided for <KineticScheme>")
if 'edges' in node.lattrib:
edges = node.lattrib['edges']
else:
self.raise_error("The 'edges' must be provided for <KineticScheme>")
if 'edgesource' in node.lattrib:
edge_source = node.lattrib['edgesource']
else:
self.raise_error("The 'edgeSource' must be provided for <KineticScheme>")
if 'edgetarget' in node.lattrib:
edge_target = node.lattrib['edgetarget']
else:
self.raise_error("The 'edgeTarget' must be provided for <KineticScheme>")
if 'forwardrate' in node.lattrib:
forward_rate = node.lattrib['forwardrate']
else:
self.raise_error("The 'forwardRate' must be provided for <KineticScheme>")
if 'reverserate' in node.lattrib:
reverse_rate = node.lattrib['reverserate']
else:
self.raise_error("The 'reverseRate' must be provided for <KineticScheme>")
self.current_regime.add_kinetic_scheme(name, nodes, state_variable,
edges, edge_source, edge_target,
forward_rate, reverse_rate)
def parse_link(self, node):
"""
Parses <Link>
@param node: Node containing the <Link> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Link variables can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A name must be provided for <Link>')
if 'type' in node.lattrib:
type = node.lattrib['type']
else:
type = None
self.current_context.add_link_var(name, type)
def parse_multi_instantiate(self, node):
"""
Parses <MultiInstantiate>
@param node: Node containing the <MultiInstantiate> element
@type node: xml.etree.Element
"""
if self.current_structure == None:
self.raise_error('Child instantiations can only be made within ' +
'a structure definition')
if 'component' in node.lattrib:
component = node.lattrib['component']
else:
self.raise_error('<MultiInstantiate> must specify a component '
'reference')
if 'number' in node.lattrib:
number = node.lattrib['number']
else:
self.raise_error('<MultiInstantiate> must specify a number')
self.current_structure.add_multi_child_def(component, number)
def parse_on_condition(self, node):
"""
Parses <OnCondition>
@param node: Node containing the <OnCondition> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<OnCondition> must be defined inside a ' +
'dynamics profile or regime')
if 'test' in node.lattrib:
test = node.lattrib['test']
else:
self.raise_error('Test expression required for <OnCondition>')
event_handler = OnCondition(test)
self.current_event_handler = event_handler
self.current_regime.add_event_handler(event_handler)
self.process_nested_tags(node)
self.current_event_handler = None
def parse_on_entry(self, node):
"""
Parses <OnEntry>
@param node: Node containing the <OnEntry> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<OnEntry> must be defined inside a ' +
'dynamics profile or regime')
event_handler = OnEntry()
self.current_event_handler = event_handler
self.current_regime.add_event_handler(event_handler)
self.process_nested_tags(node)
self.current_event_handler = None
def parse_on_event(self, node):
"""
Parses <OnEvent>
@param node: Node containing the <OnEvent> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<OnEvent> must be defined inside a ' +
'dynamics profile or regime')
if 'port' in node.lattrib:
port = node.lattrib['port']
else:
self.raise_error('Port name required for <OnCondition>')
event_handler = OnEvent(port)
self.current_event_handler = event_handler
self.current_regime.add_event_handler(event_handler)
self.process_nested_tags(node)
self.current_event_handler = None
def parse_on_start(self, node):
"""
Parses <OnStart>
@param node: Node containing the <OnStart> element
@type node: xml.etree.Element
"""
if self.current_regime == None:
self.raise_error('<OnEvent> must be defined inside a ' +
'dynamics profile or regime')
event_handler = OnStart()
self.current_event_handler = event_handler
self.current_regime.add_event_handler(event_handler)
self.process_nested_tags(node)
self.current_event_handler = None
def parse_parameter(self, node):
"""
Parses <Parameter>
@param node: Node containing the <Parameter> element
@type node: xml.etree.Element
@raise ParseError: Raised when the parameter does not have a name.
@raise ParseError: Raised when the parameter does not have a
dimension.
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Parameters can only be defined in ' +
'a component type')
try:
name = node.lattrib['name']
except:
self.raise_error('Parameter must have a name')
try:
dimension = node.lattrib['dimension']
except:
self.raise_error('Parameter must have a dimension')
parameter = Parameter(name, dimension)
self.current_context.add_parameter(parameter)
def parse_path(self, node):
"""
Parses <Path>
@param node: Node containing the <Path> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Path variables can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A name must be provided for <Path>')
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
value = None
self.current_context.add_path_var(name, value)
def parse_record(self, node):
"""
Parses <Record>
@param node: Node containing the <Record> element
@type node: xml.etree.Element
"""
if self.current_simulation == None:
self.raise_error('<Record> must be only be used inside a ' +
'simulation specification')
if 'quantity' in node.lattrib:
quantity = node.lattrib['quantity']
else:
self.raise_error('\'quantity\' attribute required for <Record>')
if 'scale' in node.lattrib:
scale = node.lattrib['scale']
else:
scale = "1"
#self.raise_error('\'scale\' attribute required for <Record>')
if 'color' in node.lattrib:
color = node.lattrib['color']
else:
color = "#000000"
#self.raise_error('\'color\' attribute required for <Record>')
self.current_simulation.add_record(quantity, scale, color)
def parse_regime(self, node):
"""
Parses <Regime>
@param node: Node containing the <Behaviour> element
@type node: xml.etree.Element
"""
if self.current_dynamics_profile is None:
self.raise_error('Regime must be defined inside a dynamics profile')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
name = ''
if 'initial' in node.lattrib:
initial = (node.lattrib['initial'].strip().lower() == 'true')
else:
initial = False
old_regime = self.current_regime
self.current_dynamics_profile.add_regime(name, initial)
self.current_regime = self.current_dynamics_profile.regimes[name]
self.process_nested_tags(node)
self.current_regime = old_regime
def parse_requirement(self, node):
"""
Parses <Requirement>
@param node: Node containing the <Requirement> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Requirements can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('Name required for <Requirement>')
if 'dimension' in node.lattrib:
dimension = node.lattrib['dimension']
else:
self.raise_error('Dimension required for <Requirement>')
self.current_context.add_requirement(name, dimension)
def parse_run(self, node):
"""
Parses <Run>
@param node: Node containing the <Run> element
@type node: xml.etree.Element
"""
if self.current_simulation == None:
self.raise_error('<Run> must be defined inside a ' +
'simulation specification')
if 'component' in node.lattrib:
component = node.lattrib['component']
else:
self.raise_error('<Run> must specify a target component')
if 'variable' in node.lattrib:
variable = node.lattrib['variable']
else:
self.raise_error('<Run> must specify a state variable')
if 'increment' in node.lattrib:
increment = node.lattrib['increment']
else:
self.raise_error('<Run> must specify an increment for the ' +
'state variable')
if 'total' in node.lattrib:
total = node.lattrib['total']
else:
self.raise_error('<Run> must specify a final value for the ' +
'state variable')
self.current_simulation.add_run(component, variable, increment, total)
def parse_show(self, node):
"""
Parses <Show>
@param node: Node containing the <Show> element
@type node: xml.etree.Element
"""
pass
def parse_simulation(self, node):
"""
Parses <Simulation>
@param node: Node containing the <Simulation> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Simulation must be defined inside a ' +
'component type')
old_simulation = self.current_simulation
self.current_simulation = self.current_context.simulation
self.process_nested_tags(node)
self.current_simulation = old_simulation
def parse_state_assignment(self, node):
"""
Parses <StateAssignment>
@param node: Node containing the <StateAssignment> element
@type node: xml.etree.Element
"""
if self.current_event_handler == None:
self.raise_error('<StateAssignment> must be defined inside an ' +
'event handler in a dynamics profile or regime')
if 'variable' in node.lattrib:
variable = node.lattrib['variable']
else:
self.raise_error('\'variable\' attribute not provided for ' +
'<StateAssignment>')
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
self.raise_error('\'value\' attribute not provided for ' +
'<StateAssignment>')
action = StateAssignment(variable, value)
self.current_event_handler.add_action(action)
def parse_state_variable(self, node):
"""
Parses <StateVariable>
@param node: Node containing the <StateVariable> element
@type node: xml.etree.Element
@raise ParseError: Raised when the state variable is not
being defined in the context of a component type.
"""
if self.current_regime == None:
self.raise_error('<StateVariable> must be defined inside a ' +
'dynamics profile or regime')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A state variable must have a name')
if 'exposure' in node.lattrib:
exposure = node.lattrib['exposure']
else:
exposure = None
if 'dimension' in node.lattrib:
dimension = node.lattrib['dimension']
else:
self.raise_error('A state variable must have a dimension')
self.current_regime.add_state_variable(name, exposure, dimension)
def parse_structure(self, node):
"""
Parses <Structure>
@param node: Node containing the <Structure> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Structure must be defined inside a ' +
'component type')
old_structure = self.current_structure
self.current_structure = self.current_context.structure
self.process_nested_tags(node)
self.current_structure = old_structure
def parse_target(self, node):
"""
Parses <Target>
@param node: Node containing the <Target> element
@type node: xml.etree.Element
"""
self.model.add_target(node.lattrib['component'])
def parse_text(self, node):
"""
Parses <Text>
@param node: Node containing the <Text> element
@type node: xml.etree.Element
"""
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Text variables can only be defined in ' +
'a component type')
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('A name must be provided for <Text>')
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
value = None
self.current_context.add_text_var(name, value)
def parse_time_derivative(self, node):
"""
Parses <TimeDerivative>
@param node: Node containing the <TimeDerivative> element
@type node: xml.etree.Element
@raise ParseError: Raised when the time derivative is not
being defined in the context of a component type.
"""
if self.current_regime == None:
self.raise_error('<TimeDerivative> must be defined inside a ' +
'dynamics profile or regime')
if self.current_context.context_type != Context.COMPONENT_TYPE:
self.raise_error('Time derivatives can only be defined in ' +
'a component type')
if 'variable' in node.lattrib:
name = node.lattrib['variable']
else:
self.raise_error('The state variable being differentiated wrt ' +
'time must be specified')
if 'value' in node.lattrib:
value = node.lattrib['value']
else:
self.raise_error('The time derivative expression must be ' +
'provided')
self.current_regime.add_time_derivative(name, value)
def parse_transition(self, node):
"""
Parses <Transition>
@param node: Node containing the <Transition> element
@type node: xml.etree.Element
"""
"""
Parses <Transition>
@param node: Node containing the <Transition> element
@type node: xml.etree.Element
"""
if self.current_event_handler == None:
self.raise_error('<Transition> must be defined inside an ' +
'event handler in a dynamics profile or regime')
if 'regime' in node.lattrib:
regime = node.lattrib['regime']
else:
self.raise_error('\'regime\' attribute not provided for ' +
'<Transition>')
action = Transition(regime)
self.current_event_handler.add_action(action)
def parse_unit(self, node):
"""
Parses <Unit>
@param node: Node containing the <Unit> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or the unit
specfications are incorrect.
@raise ModelError: When the unit refers to an undefined dimension.
"""
try:
symbol = node.lattrib['symbol']
dimension = node.lattrib['dimension']
except:
self.raise_error('Unit must have a symbol and dimension.')
if 'power' in node.lattrib:
power = int(node.lattrib['power'])
else:
power = 0
self.model.add_unit(Unit(symbol, dimension, power))
def parse_with(self, node):
"""
Parses <With>
@param node: Node containing the <With> element
@type node: xml.etree.Element
"""
if self.current_structure == None:
self.raise_error('<With> can only be made within ' +
'a structure definition')
if 'instance' in node.lattrib:
target = node.lattrib['instance']
else:
self.raise_error('<With> must specify a reference to target'
'instance')
if 'as' in node.lattrib:
name = node.lattrib['as']
else:
self.raise_error('<With> must specify a name for the '
'target instance')
self.current_structure.add_with(name, target)
def parse_root(self, node):
"""
Parse the <lems> (root) element of a LEMS file
@param node: Node containing the <LEMS> element
@type node: xml.etree.Element
"""
self.xml_root = node
if node.tag.lower() != 'lems' and node.tag.lower() not in self.alternate_root_element_tags:
print node.tag.lower(), self.alternate_root_element_tags, node.attrib['type']
self.raise_error('Not a LEMS file')
self.xml_node_stack = [node] + self.xml_node_stack
self.process_nested_tags(node)
self.xml_node_stack = self.xml_node_stack[1:]
def parse_file(self, filename):
"""
Parse a LEMS file and generate a LEMS model
@param filename: Path to the LEMS file to be parsed
@type filename: string
"""
root = open_file(filename, self.xslt_preprocessor_callback)
xmltolower(root)
self.included_files.append(filename)
self.base_path = os.path.dirname(filename)
if self.base_path == '':
self.base_path = '.'
context = Context('__root_context__', self.current_context)
if self.model.context == None:
self.model.context = context
self.push_context(context)
self.parse_root(root)
self.pop_context()
def parse_string(self, str):
pass
<file_sep>"""
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
class Options:
"""
PyLEMS command line options
"""
def __init__(self):
"""
Constructor.
"""
self.source_files = []
""" List of source files to run.
@type: list(string) """
self.include_dirs = ['.']
""" List of directories that PyLEMS will search in addition to the
working directory for included LEMS files.
@type: list(string) """
self.xsl_include_dirs = ['.', './xsl']
""" List of directories that PyLEMS will search in addition to the
working directory for XSL files.
@type: list(string) """
self.nogui = False
""" Disable GUI (graphs).
@type: bool """
def add_source_file(self, source_file):
"""
Add a source file to the list of source files to run.
@param source_file: Path to the source file to run.
@type source_file: string
"""
self.source_files.append(source_file)
def add_include_directory(self, include_dir):
"""
Add a directory to the list of include directories for LEMS files.
@param include_dir: Directory to be included
@type include_dir: string
"""
if include_dir not in self.include_dirs:
self.include_dirs.append(include_dir)
def add_xsl_include_directory(self, include_dir):
"""
Add a directory to the list of include directories for XSL files.
@param include_dir: Directory to be included
@type include_dir: string
"""
if include_dir not in self.xsl_include_dirs:
self.xsl_include_dirs.append(include_dir)
def __str__(self):
return ('<{0}>'
'<{1}>'
'<{2}>').format(self.source_files,
self.include_dirs,
self.xsl_include_dirs)
options_param_count = {
'-nogui':0,
'-I':1,
'-include':1,
'-XI':1,
'-xsl-include':1
}
def parse_cmdline_options(argv):
options = Options()
while argv:
option = argv[0]
argv = argv[1:]
params = []
if option in options_param_count:
for i in xrange(options_param_count[option]):
if len(argv) > 0:
params.append(argv[0])
else:
raise Exception("Option '{0}' needs {1} parameters".format(
option, options_param_count[option]))
argv = argv[1:]
if option == '-I' or option == '-include':
options.add_include_directory(params[0])
elif option == '-XI' or option == '-xsl-include':
options.add_xsl_include_directory(params[0])
elif option == '-nogui':
options.nogui = True
else:
options.add_source_file(option)
return options
if __name__ == '__main__':
print parse_cmdline_options(['-I', 'path1',
'-XI', 'path2',
'-include', 'path3',
'-xsl-include', 'path4'])
<file_sep># PyLEMS - A LEMS/NeuroML simulator written in Python
## Usage
runlems.py [\<options\>] \<LEMS/NeuroML file\>
### Options
- -I/-include \<path\> - Adds a directory to the model file include search path
- -XI/-xsl-include \<path\> - Adds a directory to the XSL preprocessor include path
## Tasks
- Implement flattening
- Decouple events from runnables
- Perform dimension-checking on expressions.
- Simple LEMS API for creating, reading and writing LEMS model files.
- Implement LEMS API over lems.model.* (NeuroML API?)
- Interface with libNeuroML and Pyramidal to export Neuron MOD files
- Export C files (Interface? Steve Marsh’s project?)
- Assertions.
- XPath implementation.
## Examples
### LEMS examples
- example1 -- Running
- example2 -- Running
- example3 -- Running
- example4 -- Running
- example5 -- Not running
- example6 -- Running
- example7 -- Running
- example8 -- Running
- example9 -- Not running
### NeuroML examples
- Example 0 -- Running
- Example 1 -- Running
- Example 2 -- Running
- Example 3 -- Almost works (initial conditions) after disabling some model resolution checks.
- Example 4 -- Not working (I'm working on this)
- Example 5 -- Not running (XPath)
- Example 6 -- Not running
- Example 7 -- Not running
- Example 8 -- Not running
- Example 9 -- Not working
- Example 10 -- Not working. Too many spikes.
- Example 11 -- Not running (Symbol parsing error?)
- Example 12 -- XML preprecessing error in lxml
- Example 13 -- Not running (XPath)
- Example 14 -- No model!
- Example 15 -- Not running (XPath)
## LEMS elements that do not work
- XPath based parameters - DerivedParameter, PathParameter
- Assertions
<file_sep>"""
Types for basic LEMS objects (Dimensions, units, ...)
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
class Dimension(LEMSBase):
"""
Stores dimensionality of user-defined quantities in terms of the
seven fundamental SI units
"""
def __init__(self, name, *dims):
"""
Constructor
@param name: Name of the new dimension.
@type name: string
@param dims: Dimensionality for the seven fundamental SI units in
the order - length, mass, time, electric current, temperature,
luninous intensity and quantity.
@type dims: list (variable number of arguments)
"""
self.name = name
""" Name of the user-defined dimension
@type: string """
self.l = 0
""" Length (default unit - metre)
@type: int """
self.m = 0
""" Mass (default unit - kilogram)
@type: int """
self.t = 0
""" Time (default unit - second)
@type: int """
self.i = 0
""" Electric current (default unit - ampere)
@type: int """
self.k = 0
""" Temperature (default unit - kelvin)
@type: int """
self.c = 0
""" Luminous intensity (default unit - candela)
@type: int """
self.n = 0
""" Quantity (default unit - mole)
@type: int """
if len(dims) != 7:
raise Error
self.l = dims[0]
self.m = dims[1]
self.t = dims[2]
self.i = dims[3]
self.k = dims[4]
self.c = dims[5]
self.n = dims[6]
class Unit(LEMSBase):
"""
Stores definition of unit symbols (eg, mV, ug) in terms of
dimensions
"""
def __init__(self, symbol, dimension, power):
"""
Constructor
@param symbol: Symbol name
@type symbol: string
@param dimension: User-defined dimension for this symbol
@type dimension: lems.base.units.Dimension
@param power: Scaling factor in terms of powers of 10 relative
to the default dimensions for this unit
@type power: int
"""
self.symbol = symbol
""" Symbol used to define this unit.
@type: string """
self.dimension = dimension
""" Dimension of this unit.
@type: string """
self.power = power
""" Scaling factor in terms of powers of 10 relative to
the default dimensions for this unit.
@type: int """
<file_sep>"""
Simulation builder.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import copy
from lems.base.base import LEMSBase
from lems.base.errors import SimBuildError
from lems.sim.runnable import Runnable
from lems.sim.sim import Simulation
from lems.parser.expr import ExprNode
from lems.model.dynamics import EventHandler,Action
from lems.sim.runnable import Regime
import sys
class SimulationBuilder(LEMSBase):
"""
Simulation builder class.
"""
def __init__(self, model):
"""
Constructor.
@param model: Model upon which the simulation is to be generated.
@type model: lems.model.model.Model
"""
self.model = model
""" Model to be used for constructing the simulation.
@type: lems.model.model.Model """
self.sim = None
""" Simulation built from the model.
@type: lems.sim.sim.Simulation """
self.current_record_target = None
self.current_data_output = None
def build(self):
"""
Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation
"""
self.sim = Simulation()
for component_id in self.model.targets:
if component_id not in self.model.context.components:
raise SimBuildError('Unable to find component \'{0}\' to run'\
.format(component_id))
component = self.model.context.components[component_id]
runnable = self.build_runnable(component)
self.sim.add_runnable(runnable)
return self.sim
def build_runnable(self, component, parent = None, id_ = None):
"""
Build a runnable component from a component specification and add
it to the simulation.
@param component: Component specification
@type component: lems.model.component.Component
@param parent: Parent runnable component.
@type parent: lems.sim.runnable.Runnable
@param id_: Optional id for therunnable. If it's not passed in,
the runnable will inherit the id of the component.
@raise SimBuildError: Raised when a component reference cannot be
resolved.
"""
if id_ == None:
runnable = Runnable(component.id, component, parent)
else:
runnable = Runnable(id_, component, parent)
context = component.context
simulation = context.simulation
record_target_backup = self.current_record_target
data_output_backup = self.current_data_output
do = None
for d in simulation.data_displays:
do = simulation.data_displays[d]
if do == None:
for d in simulation.data_writers:
do = simulation.data_writers[d]
if do != None:
self.current_data_output = do
for pn in context.parameters:
p = context.parameters[pn]
if p.numeric_value != None:
runnable.add_instance_variable(p.name, p.numeric_value)
elif p.dimension in ['__link__', '__text__']:
runnable.add_text_variable(p.name, p.value)
for port in context.event_in_ports:
runnable.add_event_in_port(port)
for port in context.event_out_ports:
runnable.add_event_out_port(port)
if context.selected_dynamics_profile:
dynamics = context.selected_dynamics_profile
self.add_dynamics_1(component, runnable,
dynamics.default_regime, dynamics.default_regime)
for rn in dynamics.regimes:
regime = dynamics.regimes[rn]
self.add_dynamics_1(component, runnable, regime, dynamics.default_regime)
if regime.initial:
runnable.current_regime = regime.name
if rn not in runnable.regimes:
runnable.add_regime(Regime(rn))
r = runnable.regimes[rn]
suffix = '_regime_' + rn
r.update_state_variables = runnable.__dict__['update_state_variables'
+ suffix]
r.update_derived_variables = runnable.__dict__['update_derived_variables'
+ suffix]
r.run_startup_event_handlers = runnable.__dict__['run_startup_event_handlers'
+ suffix]
r.run_preprocessing_event_handlers = runnable.__dict__['run_preprocessing_event_handlers'
+ suffix]
r.run_postprocessing_event_handlers = runnable.__dict__['run_postprocessing_event_handlers'
+ suffix]
else:
runnable.add_method('update_state_variables', ['self', 'dt'],
[])
runnable.add_method('update_derived_variables', ['self'],
[])
runnable.add_method('run_startup_event_handlers', ['self'],
[])
runnable.add_method('run_preprocessing_event_handlers', ['self'],
[])
runnable.add_method('run_postprocessing_event_handlers', ['self'],
[])
self.process_simulation_specs(component, runnable, context.simulation)
#for cn in context.components:
for cn in context.components_ordering:
child = context.components[cn]
child_runnable = self.build_runnable(child, runnable)
runnable.add_child(child.id, child_runnable)
for cdn in context.children_defs:
cdt = context.children_defs[cdn]
#if cdt == child.component_type:
if child.is_type(cdt):
runnable.add_child_to_group(cdn, child_runnable)
for type_ in context.attachments:
name = context.attachments[type_]
runnable.make_attachment(type_, name)
self.build_structure(component, runnable, context.structure)
if context.selected_dynamics_profile:
dynamics = context.selected_dynamics_profile
self.add_dynamics_2(component, runnable,
dynamics.default_regime, dynamics.default_regime)
for rn in dynamics.regimes:
regime = dynamics.regimes[rn]
self.add_dynamics_2(component, runnable, regime, dynamics.default_regime)
if rn not in runnable.regimes:
runnable.add_regime(Regime(rn))
r = runnable.regimes[rn]
suffix = '_regime_' + rn
r.update_kinetic_scheme = runnable.__dict__['update_kinetic_scheme'
+ suffix]
else:
runnable.add_method('update_kinetic_scheme', ['self', 'dt'],
[])
self.add_recording_behavior(component, runnable)
self.current_data_output = data_output_backup
self.current_record_target = record_target_backup
return runnable
def build_structure(self, component, runnable, structure):
"""
Adds structure to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure
"""
context = component.context
# Process single-child instantiations
for c in structure.single_child_defs:
if c in context.component_refs:
cref = context.component_refs[c]
child = context.lookup_component(cref)
child_runnable = self.build_runnable(child, runnable)
runnable.add_child(c, child_runnable)
for cdn in context.children_defs:
cdt = context.children_defs[cdn]
if cdt == child.component_type:
runnable.add_child_to_group(cdn, child_runnable)
else:
raise SimBuildError('Unable to find component ref \'{0}\' '
'under \'{1}\''.format(\
c, runnable.id))
# Process multi-child instatiantions
for cparam in structure.multi_child_defs:
sparam = structure.multi_child_defs[cparam]
c1 = component
c2 = context.lookup_component(cparam)
template = self.build_runnable(context.lookup_component(cparam),
runnable)
for i in range(sparam):
instance = copy.deepcopy(template)
instance.id = "{0}__{1}__{2}".format(component.id,
template.id,
i)
runnable.array.append(instance)
# Process foreach statements
if structure.foreach:
self.build_foreach(component, runnable, structure)
# Process event connections
for event in structure.event_connections:
if True:
#try:
source_pathvar = structure.with_mappings[event.source_path]
target_pathvar = structure.with_mappings[event.target_path]
source_path = context.lookup_path_parameter(source_pathvar)
target_path = context.lookup_path_parameter(target_pathvar)
source = runnable.parent.resolve_path(source_path)
target = runnable.parent.resolve_path(target_path)
if event.receiver:
receiver_component = context.lookup_component_ref(event.receiver)
receiver_template = self.build_runnable(receiver_component,
target)
receiver = copy.deepcopy(receiver_template)
receiver.id = "{0}__{1}__".format(component.id,
receiver_template.id)
target.add_attachment(receiver)
target.add_child(receiver_template.id, receiver)
target = receiver
source_port = context.lookup_text_parameter(event.source_port)
target_port = context.lookup_text_parameter(event.target_port)
if source_port == None:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if target_port == None:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port "
"uniquely identifiable "
"in '{0}'").format(target.id))
#except Exception as e:
#raise e
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port))
def build_foreach(self, component, runnable, foreach, name_mappings = {}):
"""
Iterate over ForEach constructs and process nested elements.
@param component: Component model containing structure specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param foreach: The ForEach structure object to be used to add
structure code in the runnable component.
@type foreach: lems.model.structure.ForEach
"""
context = component.context
# Process foreach statements
for fe in foreach.foreach:
target_array = runnable.resolve_path(fe.target)
for target_runnable in target_array:
name_mappings[fe.name] = target_runnable
self.build_foreach(component, runnable, fe, name_mappings)
# Process event connections
for event in foreach.event_connections:
source = name_mappings[event.source_path]
target = name_mappings[event.target_path]
source_port = context.lookup_text_parameter(event.source_port)
target_port = context.lookup_text_parameter(event.target_port)
if source_port == None:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if target_port == None:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port uniquely"
"identifiable in '{0}'").format(target.id))
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port))
def add_dynamics_1(self, component, runnable, regime, default_regime):
"""
Adds dynamics to a runnable component based on the dynamics
specifications in the component model.
This method builds dynamics necessary for building child components.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param regime: The dynamics regime to be used to generate
dynamics code in the runnable component.
@type regime: lems.model.dynamics.Regime
@param default_regime: Shared dynamics specifications.
@type default_regime: lems.model.dynamics.Regime
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable.
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved.
"""
context = component.context
if regime.name == '':
suffix = ''
else:
suffix = '_regime_' + regime.name
if regime.initial:
runnable.new_regime = regime.name
# Process state variables
for svn in regime.state_variables:
sv = regime.state_variables[svn]
runnable.add_instance_variable(sv.name, 0)
# Process time derivatives
time_step_code = []
for tdn in regime.time_derivatives:
if tdn not in regime.state_variables and tdn not in default_regime.state_variables:
raise SimBuildError(('Time derivative for undefined state '
'variable {0}').format(tdn))
td = regime.time_derivatives[tdn]
exp = self.build_expression_from_tree(runnable,
context,
regime,
td.expression_tree)
time_step_code += ['self.{0} += dt * ({1})'.format(td.variable,
exp)]
runnable.add_method('update_state_variables' + suffix, ['self', 'dt'],
time_step_code)
# Process derived variables
derived_variable_code = []
try:
derived_variables_ordering = order_derived_variables(regime)
except:
print
print 'HELLO0', runnable.id, component.id, component.component_type
print 'HELLO1a', regime.state_variables
print 'HELLO1b', regime.derived_variables
print 'HELLO1c'
sys.exit(0)
for dvn in derived_variables_ordering: #regime.derived_variables:
dv = regime.derived_variables[dvn]
runnable.add_derived_variable(dv.name)
if dv.value:
derived_variable_code += ['self.{0} = ({1})'.format(
dv.name,
self.build_expression_from_tree(runnable,
context,
regime,
dv.expression_tree))]
elif dv.select:
if dv.reduce:
derived_variable_code += self.build_reduce_code(dv.name,
dv.select,
dv.reduce)
else:
derived_variable_code += ['self.{0} = (self.{1})'.format(
dv.name,
dv.select.replace('/', '.'))]
else:
raise SimBuildError(('Inconsistent derived variable settings'
'for {0}').format(dvn))
runnable.add_method('update_derived_variables' + suffix, ['self'],
derived_variable_code)
# Process event handlers
pre_event_handler_code = []
post_event_handler_code = []
startup_event_handler_code = []
for eh in regime.event_handlers:
if eh.type == EventHandler.ON_START:
startup_event_handler_code += self.build_event_handler(runnable,
context,
regime,
eh)
elif eh.type == EventHandler.ON_CONDITION:
post_event_handler_code += self.build_event_handler(runnable,
context,
regime,
eh)
else:
pre_event_handler_code += self.build_event_handler(runnable,
context,
regime,
eh)
runnable.add_method('run_startup_event_handlers' + suffix, ['self'],
startup_event_handler_code)
runnable.add_method('run_preprocessing_event_handlers' + suffix, ['self'],
pre_event_handler_code)
runnable.add_method('run_postprocessing_event_handlers' + suffix, ['self'],
post_event_handler_code)
def add_dynamics_2(self, component, runnable, regime, default_regime):
"""
Adds dynamics to a runnable component based on the dynamics
specifications in the component model.
This method builds dynamics dependent on child components.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param regime: The dynamics regime to be used to generate
dynamics code in the runnable component.
@type regime: lems.model.dynamics.Regime
@param default_regime: Shared dynamics specifications.
@type default_regime: lems.model.dynamics.Regime
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable.
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved.
"""
context = component.context
if regime.name == '':
suffix = ''
else:
suffix = '_regime_' + regime.name
# Process kinetic schemes
ks_code = []
for ksn in regime.kinetic_schemes:
ks = regime.kinetic_schemes[ksn]
try:
nodes = {node.id:node for node in runnable.__dict__[ks.nodes]}
edges = runnable.__dict__[ks.edges]
for edge in edges:
from_ = edge.__dict__[ks.edge_source]
to = edge.__dict__[ks.edge_target]
ks_code += [('self.{0}.{2} += dt * (-self.{3}.{4} * self.{0}.{2}_shadow'
' + self.{3}.{5} * self.{1}.{2}_shadow)').format(
from_, to, ks.state_variable, edge.id,
ks.forward_rate, ks.reverse_rate)]
ks_code += [('self.{1}.{2} += dt * (self.{3}.{4} * self.{0}.{2}_shadow'
' - self.{3}.{5} * self.{1}.{2}_shadow)').format(
from_, to, ks.state_variable, edge.id,
ks.forward_rate, ks.reverse_rate)]
ks_code += ['sum = 0']
for node in nodes:
nodes[node].__dict__[ks.state_variable] = 1.0 / len(nodes)
nodes[node].__dict__[ks.state_variable + '_shadow'] = 1.0 / len(nodes)
ks_code += ['sum += self.{0}.{1}'.format(node, ks.state_variable)]
for node in nodes:
ks_code += ['self.{0}.{1} /= sum'.format(node, ks.state_variable)]
for node in nodes:
ks_code += [('self.{0}.{1}_shadow = '
'self.{0}.{1}').format(node,
ks.state_variable)]
except Exception as e:
raise SimBuildError(("Unable to construct kinetic scheme '{0}' "
"for component '{1}' - {2}").format(ks.name,
component.id,
str(e)))
runnable.add_method('update_kinetic_scheme' + suffix, ['self', 'dt'],
ks_code)
def process_simulation_specs(self, component, runnable, simulation):
"""
Process simulation-related aspects to a runnable component based on the
dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param simulation: The simulation-related aspects to be implemented
in the runnable component.
@type simulation: lems.model.simulation.Simulation
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved.
"""
context = component.context
# Process runs
for rn in simulation.runs:
run = simulation.runs[rn]
c = context.lookup_component_ref(run.component)
if c != None:
#cid = c.id
#if c.id in self.sim.runnables:
# idx = 2
# cid = c.id + '_' + str(idx)
# while cid in self.sim.runnables:
# idx = idx + 1
# cid = c.id + '_' + str(idx)
cid = c.id + '_' + component.id
target = self.build_runnable(c, runnable, cid)
self.sim.add_runnable(target)
self.current_record_target = target
time_step = context.lookup_parameter(run.increment)
time_total = context.lookup_parameter(run.total)
if time_step != None and time_total != None:
target.configure_time(time_step.numeric_value,
time_total.numeric_value)
else:
raise SimBuildError(('Invalid component reference {0} in '
'<Run>').format(c.id))
def convert_op(self, op):
"""
Converts NeuroML arithmetic/logical operators to python equivalents.
@param op: NeuroML operator
@type op: string
@return: Python operator
@rtype: string
"""
if op == '.gt.':
return '>'
elif op == '.ge.' or op == '.geq.':
return '>='
elif op == '.lt.':
return '<'
elif op == '.le.':
return '<='
elif op == '.eq.':
return '=='
elif op == '.ne.':
return '!='
elif op == '^':
return '**'
elif op == '.and.':
return 'and'
elif op == '.or.':
return 'or'
else:
return op
def convert_func(self, func):
"""
Converts NeuroML arithmetic/logical functions to python equivalents.
@param func: NeuroML function
@type func: string
@return: Python operator
@rtype: string
"""
if func == 'ln':
return 'log'
else:
return func
def build_expression_from_tree(self, runnable, context, regime, tree_node):
"""
Recursively builds a Python expression from a parsed expression tree.
@param runnable: Runnable object to which this expression would be added.
@type runnable: lems.sim.runnable.Runnable
@param context: Context from which variables are to be resolved.
@type context: lems.model.context.Context
@param regime: Dynamics regime being built.
@type regime: lems.model.dynamics.Regime
@param tree_node: Root node for the tree from which the expression
is to be built.
@type tree_node: lems.parser.expr.ExprNode
@return: Generated Python expression.
@rtype: string
"""
default_regime = context.selected_dynamics_profile.default_regime
if tree_node.type == ExprNode.VALUE:
if tree_node.value[0].isalpha():
if tree_node.value == 't':
return 'self.time_completed'
elif tree_node.value in context.requirements:
var_prefix = 'self'
v = tree_node.value
r = runnable
while (v not in r.instance_variables and
v not in r.derived_variables):
var_prefix = '{0}.{1}'.format(var_prefix, 'parent')
r = r.parent
if r == None:
raise SimBuildError("Unable to resolve required "
"variable '{0}'".format(v))
return '{0}.{1}'.format(var_prefix, v)
elif (tree_node.value in regime.derived_variables or
tree_node.value in default_regime.derived_variables):
return 'self.{0}'.format(tree_node.value)
else:
return 'self.{0}_shadow'.format(tree_node.value)
else:
return tree_node.value
elif tree_node.type == ExprNode.FUNC1:
return '({0}({1}))'.format(\
self.convert_func(tree_node.func),
self.build_expression_from_tree(runnable,
context,
regime,
tree_node.param))
else:
return '({0}) {1} ({2})'.format(\
self.build_expression_from_tree(runnable,
context,
regime,
tree_node.left),
self.convert_op(tree_node.op),
self.build_expression_from_tree(runnable,
context,
regime,
tree_node.right))
def build_event_handler(self, runnable, context, regime, event_handler):
"""
Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string)
"""
if event_handler.type == EventHandler.ON_CONDITION:
return self.build_on_condition(runnable, context, regime, event_handler)
elif event_handler.type == EventHandler.ON_EVENT:
return self.build_on_event(runnable, context, regime, event_handler)
elif event_handler.type == EventHandler.ON_START:
return self.build_on_start(runnable, context, regime, event_handler)
elif event_handler.type == EventHandler.ON_ENTRY:
return self.build_on_entry(runnable, context, regime, event_handler)
else:
return []
def build_on_condition(self, runnable, context, regime, on_condition):
"""
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string)
"""
on_condition_code = []
on_condition_code += ['if {0}:'.format(\
self.build_expression_from_tree(runnable,
context,
regime,
on_condition.expression_tree))]
for action in on_condition.actions:
code = self.build_action(runnable, context, regime, action)
for line in code:
on_condition_code += [' ' + line]
return on_condition_code
def build_on_event(self, runnable, context, regime, on_event):
"""
Build OnEvent event handler code.
@param on_event: OnEvent event handler object
@type on_event: lems.model.dynamics.OnEvent
@return: Generated OnEvent code
@rtype: list(string)
"""
on_event_code = []
on_event_code += ['count = self.event_in_counters[\'{0}\']'.\
format(on_event.port),
'while count > 0:',
' count -= 1']
for action in on_event.actions:
code = self.build_action(runnable, context, regime, action)
for line in code:
on_event_code += [' ' + line]
on_event_code += ['self.event_in_counters[\'{0}\'] = 0'.\
format(on_event.port),]
return on_event_code
def build_on_start(self, runnable, context, regime, on_start):
"""
Build OnStart start handler code.
@param on_start: OnStart start handler object
@type on_start: lems.model.dynamics.OnStart
@return: Generated OnStart code
@rtype: list(string)
"""
on_start_code = []
for action in on_start.actions:
code = self.build_action(runnable, context, regime, action)
for line in code:
on_start_code += [' ' + line]
return on_start_code
def build_on_entry(self, runnable, context, regime, on_entry):
"""
Build OnEntry start handler code.
@param on_entry: OnEntry start handler object
@type on_entry: lems.model.dynamics.OnEntry
@return: Generated OnEntry code
@rtype: list(string)
"""
on_entry_code = []
on_entry_code += ['if self.current_regime != self.last_regime:']
on_entry_code += [' self.last_regime = self.current_regime']
for action in on_entry.actions:
code = self.build_action(runnable, context, regime, action)
for line in code:
on_entry_code += [' ' + line]
return on_entry_code
def build_action(self, runnable, context, regime, action):
"""
Build event handler action code.
@param action: Event handler action object
@type action: lems.model.dynamics.Action
@return: Generated action code
@rtype: string
"""
if action.type == Action.STATE_ASSIGNMENT:
return self.build_state_assignment(runnable, context, regime, action)
if action.type == Action.EVENT_OUT:
return self.build_event_out(action)
if action.type == Action.TRANSITION:
return self.build_transition(action)
else:
return ['pass']
def build_state_assignment(self, runnable, context, regime, state_assignment):
"""
Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string
"""
return ['self.{0} = {1}'.format(\
state_assignment.variable,
self.build_expression_from_tree(runnable,
context,
regime,
state_assignment.expression_tree))]
def build_event_out(self, event_out):
"""
Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string
"""
event_out_code = ['if "{0}" in self.event_out_callbacks:'.format(event_out.port),
' for c in self.event_out_callbacks[\'{0}\']:'.format(event_out.port),
' c()']
return event_out_code
def build_transition(self, transition):
"""
Build regime transition code.
@param transition: Transition object
@type transition: lems.model.dynamics.Transition
@return: Generated transition code
@rtype: string
"""
return ["self.new_regime = '{0}'".format(transition.regime)]
def build_reduce_code(self, result, select, reduce):
"""
Builds a reduce operation on the selected target range.
"""
select = select.replace('/', '.')
select = select.replace(' ', '')
if reduce == 'add':
reduce_op = '+'
acc_start = 0
else:
reduce_op = '*'
acc_start = 1
bits = select.split('[*]')
code = ['self.{0} = {1}'.format(result, acc_start)]
code += ['self.{0}_shadow = {1}'.format(result, acc_start)]
code += ['try:']
if len(bits) == 1:
target = select
code += [' self.{0} = {1}'.format(result, target)]
code += [' self.{0}_shadow = {1}'.format(result, target)]
elif len(bits) == 2:
array = bits[0]
ref = bits[1]
code += [' acc = {0}'.format(acc_start)]
code += [' for o in self.{0}:'.format(array)]
code += [' acc = acc {0} o{1}'.format(reduce_op, ref)]
code += [' self.{0} = acc'.format(result)]
code += [' self.{0}_shadow = acc'.format(result)]
else:
raise SimbuildError("Invalid reduce target - '{0}'".format(select))
code += ['except:']
code += [' pass']
return code
def add_recording_behavior(self, component, runnable):
"""
Adds recording-related dynamics to a runnable component based on
the dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.Component
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@raise SimBuildError: Raised when a target for recording could not be
found.
"""
context = component.context
simulation = context.simulation
for rn in simulation.records:
rec = simulation.records[rn]
if self.current_record_target == None:
raise SimBuildError('No target available for '
'recording variables')
self.current_record_target.add_variable_recorder(self.current_data_output, rec)
############################################################
def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
variables could not be found.
"""
ordering = []
dvs = []
dvsnoexp = []
maxcount = 5
for dv in regime.derived_variables:
if regime.derived_variables[dv].expression_tree == None:
dvsnoexp.append(dv)
else:
dvs.append(dv)
count = maxcount
while count > 0 and dvs != []:
count = count - 1
for dv1 in dvs:
exp_tree = regime.derived_variables[dv1].expression_tree
found = False
for dv2 in dvs:
if dv1 != dv2 and is_var_in_exp_tree(dv2, exp_tree):
found = True
if not found:
ordering.append(dv1)
del dvs[dvs.index(dv1)]
count = maxcount
break
if count == 0:
print 'HELLO5', ordering, dvs, dvsnoexp
raise SimBuildError(("Unable to find ordering for derived "
"variables in '{0}'").format(context.name))
#return ordering + dvsnoexp
return dvsnoexp + ordering
def is_var_in_exp_tree(var, exp_tree):
node = exp_tree
if node.type == ExprNode.VALUE:
if node.value == var:
return True
else:
return False
elif node.type == ExprNode.OP:
if is_var_in_exp_tree(var, node.left):
return True
else:
return is_var_in_exp_tree(var, node.right)
elif node.type == ExprNode.FUNC1:
return is_var_in_exp_tree(var, node.param)
else:
return False
<file_sep>"""
Component structure storage.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.errors import ModelError
from lems.base.util import merge_dict
class Structure(LEMSBase):
"""
Stores the structural characteristics for a component type.
"""
def __init__(self):
"""
Constructor.
"""
self.event_connections = []
""" List of event connections b/w components. The from and to
attributes are described as component:port
@type: list(lems.base.structure.EventConnection) """
self.single_child_defs = []
""" List of single-child instantiation definitions.
@type: list(string) """
self.multi_child_defs = {}
""" List of multi-child instantiation definitions.
@type: dict(string -> string) """
self.foreach = []
""" List of foreach declarations.
@type: lems.model.structure.ForEach """
self.foreach_mappings = {}
""" Accumulated name->target mappings for nested ForEach constructs.
@type: dict(string -> string) """
self.with_mappings = {}
""" With mappings for With specifications.
@type: dict(string -> string) """
def add_event_connection(self, source_path, target_path,
source_port = '', target_port = '',
receiver = '', receiver_container = ''):
"""
Adds an event connection to the structure.
@param source_path: Name (or mapped name) of the path variable
pointing to the source component.
@type source_path: string
@param target_path: Name (or mapped name) of the path variable
pointing to the target component.
@type target_path: string
@param source_port: Port name for the source component. Can be left empty if
there is only one output port defined in the component.
@type source_port: string
@param target_port: Port name for the target component. Can be left empty if
there is only one input port defined in the component.
@type target_port: string
@param receiver: Name of a component reference pointing to a component
acting as a receiver for the event.
@type receiver: string
@param receiver_container: TODO
@type receiver_container: string
"""
self.event_connections.append(EventConnection(source_path, target_path,
source_port, target_port,
receiver, receiver_container))
def add_single_child_def(self, component):
"""
Adds a single-child instantiation definition to this component type.
@param component: Name of component reference used as template for
instantiating the child.
@type component: string
"""
if component in self.single_child_defs:
raise ModelError("Duplicate child instantiation = '{0}'".format(\
component))
self.single_child_defs.append(component)
def add_multi_child_def(self, component, number):
"""
Adds a single-child instantiation definition to this component type.
@param component: Name of component reference used as template for
instantiating the child.
@type component: string
@param number: Number of objects to be instantiated.
@type number: string
"""
if component in self.single_child_defs:
raise ModelError("Duplicate child multiinstantiation = "
"'{0}'".format(component))
if self.multi_child_defs != {}:
raise ModelError("Only one multi-instantiation is permitted "
"per component type - '{0}'".format(component))
self.multi_child_defs[component] = number
def add_foreach(self, name, target):
"""
Adds a foreach structure nesting.
@param name: Name used to refer to the enumerated target references.
@type name: string
@param target: Path to thetarget references.
@type target: string
"""
foreach = ForEach(name, target)
for n in self.foreach_mappings:
t = self.foreach_mappings[n]
foreach.foreach_mappings[n] = t
foreach.foreach_mappings[name] = target
self.foreach.append(foreach)
return foreach
def add_with(self, name, target):
"""
Adds a with structure nesting.
@param name: Name used to refer to the enumerated target references.
@type name: string
@param target: Path to thetarget references.
@type target: string
"""
if name in self.with_mappings:
raise ModelError("Duplicate <With> specification for "
"'{0}'".format(component))
self.with_mappings[name] = target
def merge(self, other):
"""
Merge another set of structural characteristics
into this one.
@param other: structural characteristics
@type other: lems.model.structure.Structure
"""
self.event_connections += other.event_connections
self.single_child_defs += other.single_child_defs
merge_dict(self.multi_child_defs, other.multi_child_defs)
self.foreach += other.foreach
merge_dict(self.foreach_mappings, other.foreach_mappings)
merge_dict(self.with_mappings, other.with_mappings)
def merge_from_type(self, other, context):
"""
Merge another set of structural characteristics
into this one.
@param other: Structural characteristics
@type other: lems.model.structure.Structure
@param context: Context of the component
@type context: lems.model.context.Context
"""
self.event_connections += other.event_connections
for c in other.single_child_defs:
if c in context.component_refs:
self.add_single_child_def(c)
else:
raise ModelError("Trying to multi-instantiate from an "
"invalid component reference '{0}'".format(\
c))
for c in other.multi_child_defs:
n = other.multi_child_defs[c]
if c in context.component_refs:
component = context.component_refs[c]
if n in context.parameters:
number = int(context.parameters[n].numeric_value)
self.add_multi_child_def(component, number)
else:
raise ModelError("Trying to multi-instantiate using an "
"invalid number parameter '{0}'".\
format(n))
else:
raise ModelError("Trying to multi-instantiate from an "
"invalid component reference '{0}'".format(\
c))
self.foreach += other.foreach
merge_dict(self.foreach_mappings, other.foreach_mappings)
merge_dict(self.with_mappings, other.with_mappings)
class ForEach(Structure):
"""
Stores a <ForEach> statement and containing structures.
"""
def __init__(self, name, target):
"""
Constructor.
"""
Structure.__init__(self)
self.name = name
""" Name used to refer to the enumerated target instances.
@type: string """
self.target = target
""" Path to the target instances.
@type: string """
class EventConnection(LEMSBase):
"""
Stores specification of an event connection.
"""
def __init__(self, source_path, target_path,
source_port, target_port,
receiver, receiver_container):
"""
Constructor.
"""
self.source_path = source_path
""" Name (or mapped name) of the path variable
pointing to the source component.
@type: string """
self.target_path = target_path
""" Name (or mapped name) of the path variable
pointing to the target component.
@type: string """
self.source_port = source_port
""" Port name for the source component. Can be left empty if
there is only one output port defined in the component.
@type: string """
self. target_port = target_port
""" Port name for the target component. Can be left empty if
there is only one input port defined in the component.
@type: string """
self.receiver = receiver
""" Name of a component reference pointing to a component
acting as a receiver for the event.
@type: string """
self.receiver_container = receiver_container
""" TODO
@type: string """
<file_sep>"""
LEMS exceptions.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
class Error(Exception):
"""
Exception to signal errors in PyLEMS.
"""
def __init__(self, message):
"""
Constructor
@param message: Error message.
@type message: string
"""
self.message = message
""" Error message
@type: string """
def __str__(self):
"""
Returns the error message string.
@return: The error message
@rtype: string
"""
return self.message
class StackError(Error):
"""
Exception to signal errors in the PyLEMS Stack class.
"""
pass
class ParseError(Error):
"""
Exception to signal errors found during parsing.
"""
pass
class ModelError(Error):
"""
Exception to signal errors found during model generation.
"""
pass
class SimBuildError(Error):
"""
Exception to signal errors found while building simulation.
"""
pass
class SimError(Error):
"""
Exception to signal errors found while running simulation.
"""
pass
<file_sep>"""
Component dynamics storage.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.errors import ModelError,ParseError
from lems.parser.expr import ExprParser
from lems.base.util import merge_dict
class StateVariable(LEMSBase):
"""
Stores the definition of a state variable.
"""
def __init__(self, name, exposure, dimension):
"""
Constructor.
@param name: Name (internal) of the state variable.
@type name: string
@param exposure: Name (external) of the state variable.
@type exposure: string
@param dimension: Dimension of the state variable.
@type dimension: string
"""
self.name = name
""" Internal name of the state variable. This is the name used to
refer to this variable inside the <Dynamics> element.
@type: string """
self.exposure = exposure
""" Exposure name of the state variable. This is the name used to
refer to this variable from other objects.
@type: string """
self.dimension = dimension
""" Dimension of this state variable.
@type: string """
class TimeDerivative(LEMSBase):
"""
Stores the time derivative expression for a given state variable.
"""
def __init__(self, variable, value):
"""
Constructor.
@param variable: Name of the state variable
@type variable: string
@param value: Time derivative expression of the given state variable.
@type value: string
"""
self.variable = variable
""" State variable whose time derivative is stored in this object.
@type: string """
self.value = value
""" Time derivative expression for the state variable.
@type: string """
try:
self.expression_tree = ExprParser(value).parse()
""" Parse tree for the time derivative expression.
@type: lems.parser.expr.ExprNode """
except:
raise ParseError("Parse error when parsing value expression "
"'{0}' for derived variable {1}".format(\
self.value,
self.variable))
class DerivedVariable(LEMSBase):
"""
Stores the definition of a derived variable.
"""
def __init__(self, name, exposure, dimension, value, select, reduce):
"""
Constructor.
@param name: Name (internal) of the derived variable.
@type name: string
@param exposure: Name (external) of the derived variable.
@type exposure: string
@param dimension: Dimension of the derived variable.
@type dimension: string
@param value: Value expression for the derived variable.
@type value: string
@param select: Target component selection for reduction operations.
@type select: string
@param reduce: Reduce operation.
@type reduce: string
"""
self.name = name
""" Internal name of the derived variable. This is the name used to
refer to this variable inside the <Dynamics> element.
@type: string """
self.exposure = exposure
""" Exposure name of the derived variable. This is the name used to
refer to this variable from other objects.
@type: string """
self.dimension = dimension
""" Dimension of this derived variable.
@type: string """
self.value = value
""" Expression used for computing the value of the derived variable.
@type: string """
self.select = select
""" Selected target object for the reduce operation.
@type: string """
self.reduce = reduce
""" Reduce operation to be applied over the selected target.
@type: string """
if value != None:
try:
self.expression_tree = ExprParser(value).parse()
""" Parse tree for the time derivative expression.
@type: lems.parser.expr.ExprNode """
except:
raise ParseError("Parse error when parsing value expression "
"'{0}' for derived variable {1}".format(\
self.value,
self.name))
else:
self.expression_tree = None
class EventHandler(LEMSBase):
"""
Base class for event an handler.
"""
ON_START = 1
ON_ENTRY = 2
ON_EVENT = 3
ON_CONDITION = 4
def __init__(self, type):
"""
Constructor.
@param type: Type of event.
@type type: enum(EventHandler.ONSTART, EventHandler.ON_ENTRY,
EventHandler.ON_EVENT and EventHandler.ON_CONDITION)
"""
self.type = type
""" Type of event.
@type: enum(EventHandler.ONSTART, EventHandler.ON_ENTRY,
EventHandler.ON_EVENT and EventHandler.ON_CONDITION) """
self.actions = []
"List of actions to be performed on the occurence of the event."
def add_action(self, action):
"""
Adds an action to the list of actions.
@param action: Action to be performed.
@type action: lems.model.dynamics.Action
"""
self.actions += [action]
def check_for_event(self):
"""
Check for the event. If this function returns true, the corresponding
event actions will be executed.
@return: Check if the event has occurred.
@rtype: Boolean
@note: This function must be overridden. Maybe when building the
simulator?
"""
return False
class OnStart(EventHandler):
"""
Stores the parameters of an <OnStart> statement.
"""
def __init__(self):
"""
Constructor.
"""
EventHandler.__init__(self, EventHandler.ON_START)
def __str__(self):
""" Generates a string representation of this condition."""
return 'OnStart'
class OnEntry(EventHandler):
"""
Stores the parameters of an <OnEntry> statement.
"""
def __init__(self):
"""
Constructor.
"""
EventHandler.__init__(self, EventHandler.ON_ENTRY)
def __str__(self):
""" Generates a string representation of this condition."""
return 'OnEntry'
class OnEvent(EventHandler):
"""
Stores the parameters of an <OnEvent> statement.
"""
def __init__(self, port):
"""
Constructor.
@param port: The name of the event port to listen on.
@type port: string
"""
EventHandler.__init__(self, EventHandler.ON_EVENT)
self.port = port
""" The name of the event port to listen on.
@type: string """
def __str__(self):
""" Generates a string representation of this condition."""
return 'OnEvent: ' + self.port
class OnCondition(EventHandler):
"""
Event handler for a condition check.
"""
def __init__(self, test):
"""
Constructor.
@param test: Test expression.
@type test: string
"""
EventHandler.__init__(self, EventHandler.ON_CONDITION)
self.test = test
""" Test expression.
@type: string """
self.expression_tree = ExprParser(test).parse()
""" Parse tree for the test expression.
@type: lems.parser.expr.ExprNode """
def __str__(self):
""" Generates a string representation of this condition."""
return 'OnCondition: ' + self.test + ' | ' +\
str(self.expression_tree)
class Action(LEMSBase):
"""
Base class for an event action.
"""
STATE_ASSIGNMENT = 1
EVENT_OUT = 2
TRANSITION = 3
def __init__(self, type):
"""
Constructor.
@param type: Type of action.
@type type: enum(Action.STATEASSIGNMENT, Action.EVENT_OUT)
"""
self.type = type
""" Type of action.
@type: enum(Action.STATEASSIGNMENT, Action.EVENT_OUT) """
class StateAssignment(Action):
"""
Stores a state assignment expression.
"""
def __init__(self, variable, value):
"""
Constructor.
@param variable: Name of the state variable
@type variable: string
@param value: Assignment expression of the given state variable.
@type value: string
"""
Action.__init__(self, Action.STATE_ASSIGNMENT)
self.variable = variable
""" State variable whose assignment expression is stored in this
object.
@type: string """
self.value = value
""" Assignment expression for the state variable.
@type: string """
self.expression_tree = ExprParser(value).parse()
""" Parse tree for the assignment expression.
@type: lems.parser.expr.ExprNode """
def __str__(self):
""" Generates a string representation of this state assigment """
return self.variable + ' <- ' + self.value + ' | ' + \
str(self.expression_tree)
class EventOut(Action):
"""
Stores an event out operation.
"""
def __init__(self, port):
"""
Constructor.
@param port: Name of a port
@type port: string
"""
Action.__init__(self, Action.EVENT_OUT)
self.port = port
""" Name of the port to which the event needs to be sent.
@type: string """
def __str__(self):
""" Generates a string representation of this state assigment """
return 'Event -> ' + self.port
class Transition(Action):
"""
Stores an regime transition operation.
"""
def __init__(self, regime):
"""
Constructor.
@param regime: Name of a dynamics regime
@type regime: string
"""
Action.__init__(self, Action.TRANSITION)
self.regime = regime
""" Name of the dynamics regime to switch to.
@type: string """
def __str__(self):
""" Generates a string representation of this state assigment """
return 'Regime -> ' + self.regime
class KineticScheme(LEMSBase):
"""
Stores a kinetic scheme specification.
"""
def __init__(self, name, nodes, state_variable,
edges, edge_source, edge_target,
forward_rate, reverse_rate):
"""
Constructor.
See instance variable documentation for info on parameters.
"""
self.name = name
""" Name of the kinetic scheme.
@type: string """
self.nodes = nodes
""" Name of the children collection specifying the nodes
for the kinetic scheme.
@type: string """
self.state_variable = state_variable
""" Name of the state variable in the KS node specifying
the value of the scheme.
@type: string """
self.edges = edges
""" Name of the children collection specifying the edges
for the kinetic scheme.
@type: string """
self.edge_source = edge_source
""" Name of the link in a KS edge pointing to the source
node for the edge.
@type: string """
self.edge_target = edge_target
""" Name of the link in a KS edge pointing to the target
node for the edge.
@type: string """
self.forward_rate = forward_rate
""" Name of the state variable in a KS edge specifying
forward rate for the edge.
@type: string """
self.reverse_rate = reverse_rate
""" Name of the state variable in a KS edge specifying
reverse rate for the edge.
@type: string """
class Regime(LEMSBase):
"""
Store a dynamics regime for a component type.
"""
def __init__(self, name, initial = False):
"""
Constructor.
@param name: Name of the dynamics regime.
@type name: string
@param initial: Is this the initial regime? Default: False
@type initial: Boolean
"""
self.name = name
""" Name of this ehavior regime.
@type: string """
self.initial = initial
""" Is this an initial regime?
@type: Boolean """
self.state_variables = {}
""" Dictionary of state variables defined in this dynamics regime.
@type: dict(string -> lems.model.dynamics.StateVariable) """
self.time_derivatives = {}
""" Dictionary of time derivatives defined in this dynamics regime.
@type: dict(string -> lems.model.dynamics.TimeDerivative) """
self.derived_variables = {}
""" Dictionary of derived variables defined in this dynamics regime.
@type: dict(string -> lems.model.dynamics.DerivedVariable) """
self.event_handlers = []
""" List of event handlers defined in this dynamics regime.
@type: list(EventHandler) """
self.kinetic_schemes = {}
""" Dictionary of kinetic schemes defined in this dynamics regime.
@type: dict(string -> lems.model.dynamics.KineticScheme) """
def add_state_variable(self, name, exposure, dimension):
"""
Adds a state variable to the dynamics current object.
@param name: Name of the state variable.
@type name: string
@param exposure: Exposed name of the state variable.
@type exposure: string
@param dimension: Dimension ofthe state variable.
@type dimension: string
@raise ModelError: Raised when the state variable is already
defined in this dynamics regime.
"""
if name in self.state_variables:
raise ModelError('Duplicate state variable ' + name)
self.state_variables[name] = StateVariable(name, exposure, dimension)
def add_time_derivative(self, variable, value):
"""
Adds a state variable to the dynamics current object.
@param variable: Name of the state variable whose time derivative
is being specified.
@type variable: string
@param value: Time derivative expression.
@type value: string
@raise ModelError: Raised when the time derivative for this state
variable is already defined in this dynamics regime.
"""
if variable in self.time_derivatives:
raise ModelError('Duplicate time derivative for ' + variable)
self.time_derivatives[variable] = TimeDerivative(variable, value)
def add_derived_variable(self, name, exposure, dimension,
value, select, reduce):
"""
Adds a derived variable to the dynamics current object.
@param name: Name of the derived variable.
@type name: string
@param exposure: Exposed name of the derived variable.
@type exposure: string
@param dimension: Dimension ofthe derived variable.
@type dimension: string
@param value: Value expression for the derived variable.
@type value: string
@param select: Target component selection for reduction operations.
@type select: string
@param reduce: Reduce operation.
@type reduce: string
@raise ModelError: Raised when the derived variable is already
defined in this dynamics regime.
"""
if name in self.derived_variables:
raise ModelError("Duplicate derived variable '{0}'".format(name))
if value == None and select == None and reduce == None:
raise ModelError("Derived variable '{0}' must specify either a "
"value expression or a reduce "
"operation".format(name))
if value != None and (select != None or reduce != None):
raise ModelError("Derived variable '{0}' cannot specify both "
"value expressions or select/reduce "
"operations".format(name))
if select == None and reduce != None:
raise ModelError("Reduce target not specified for derived "
"variable '{0}'".format(name))
self.derived_variables[name] = DerivedVariable(name, exposure,
dimension, value,
select, reduce)
def add_event_handler(self, event_handler):
"""
Adds a state variable to the dynamics current object.
@param event_handler: Event handler object.
@type event_handler: lems.model.dynamics.EventHandler
"""
self.event_handlers += [event_handler]
def add_kinetic_scheme(self, name, nodes, state_variable,
edges, edge_source, edge_target,
forward_rate, reverse_rate):
"""
Constructor.
See KineticScheme documentation for info on parameters.
@raise ModelError: Raised if a kinetic scheme with the same
name already exists in this behavior regime.
"""
if name in self.kinetic_schemes:
raise ModelError('Duplicate kinetic scheme ' + name)
self.kinetic_schemes[name] = KineticScheme(name, nodes, state_variable,
edges, edge_source, edge_target,
forward_rate, reverse_rate)
def merge(self, regime):
"""
Merge another regime into this one.
@param regime: Regime to be merged in.
@type regime: lems.model.dynamics.Regime
"""
merge_dict(self.state_variables, regime)
merge_dict(self.time_derivatives, regime.time_derivatives)
merge_dict(self.derived_variables, regime.derived_variables)
self.event_handlers += regime.event_handlers
merge_dict(self.kinetic_schemes, regime.kinetic_schemes)
class Dynamics(LEMSBase):
"""
Stores the dynamic dynamics for a component type.
"""
def __init__(self, name):
"""
Constructor.
"""
self.name = name
""" Name of this dynamics profile.
@type: string """
self.default_regime = Regime('')
""" Default dynamics regime for this dynamics profile. This regime
is used to store dynamics object not defined within a named regime.
@type: lems.model.dynamics.Regime """
self.current_regime = None
""" Currently active dynamics regime for this dynamics profile.
@type: lems.model.dynamics.Regime """
self.regimes = {}
""" Dictionary of regimes in this dynamics profile.
@type: dict(string -> lems.model.dynamics.Regime) """
def add_regime(self, name, initial = False):
"""
Adds a dynamics regime to the list of regimes in this dynamics
profile.
@param name: Name of the dynamics regime.
@type name: string
@param initial: Is this the initial regime? Default: False
@type initial: Boolean
"""
if name in self.regimes:
raise ModelError('Duplicate regime ' + name)
if initial:
for rn in self.regimes:
if self.regimes[rn].initial:
raise('Cannot define two initial regimes in the same' +
' dynamics profile')
regime = Regime(name, initial)
if initial:
self.current_regime = regime
self.regimes[name] = regime
def merge(self, dynamics):
"""
Merge another dynamics profile into this one.
@param dynamics: Dynamics profile to be merged in.
@type dynamics: lems.model.dynamics.Dynamics
"""
self.default_regime.merge(dynamics.default_regime)
if not self.current_regime:
self.current_regime = dynamics.current_regime
for rn in dynamics.regimes:
if rn in self.regimes:
self.regimes[rn].merge(dynamics.regimes[rn])
else:
self.regimes[rn] = dynamics.regimes[rn]
<file_sep>"""
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
import sys
from xml.etree import ElementTree as xml
from lxml import etree as xml2
from options import Options,parse_cmdline_options
from lems.base.errors import ParseError,ModelError,SimBuildError,SimError
from lems.parser.LEMS import LEMSParser
from lems.sim.build import SimulationBuilder
from lems.model.simulation import DataOutput
import pylab
import numpy
xsl_preprocessor_file = 'canonical.xsl'
def main(argv):
try:
options = parse_cmdline_options(argv)
except Exception as e:
print("Caught exception when processing command line options: '{0}'".format(
str(e)))
sys.exit(-1)
xsl_pp_cb = make_xsl_preprocessor_callback(options)
if xsl_pp_cb == None:
print('Unable to find preprocessor file canonical.xsl. Try using -XI '
'or -xsl-include to specifiy additional include directories')
sys.exit(-1)
for source_file in options.source_files:
run(source_file, options, xsl_pp_cb)
def make_xsl_preprocessor_callback(options):
for xsl_include_dir in options.xsl_include_dirs:
xslpath = xsl_include_dir + '/' + xsl_preprocessor_file
try:
xsl = xml2.parse(xslpath)
xslt = xml2.XSLT(xsl)
def xsl_pp_cb(xmltext):
return str(xslt(xml2.XML(xmltext)))
return xsl_pp_cb
print xslpath
break
except:
pass
return None
def run(source_file, options, xsl_pp_cb):
try:
print('Parsing model file')
parser = LEMSParser(xsl_pp_cb, options.include_dirs,
['neuroml'])
parser.parse_file(source_file)
model = parser.get_model()
#print model
print('Resolving model')
model.resolve_model()
#print model
print('Building simulation')
sim = SimulationBuilder(model).build()
#sim.dump()
print('Running simulation')
sim.run()
process_simulation_output(sim, options)
except ParseError as e:
print('Caught ParseError - ' + str(e))
except ModelError as e:
print('Caught ModelError - ' + str(e))
#except SimBuildError as e:
#print('Caught SimBuildError - ' + str(e))
except SimError as e:
print('Caught SimError - ' + str(e))
fig_count = 0
def process_simulation_output(sim, options):
global fig_count
if not options.nogui:
print('Processing results')
rq = []
for rn in sim.runnables:
rq.append(sim.runnables[rn])
while rq != []:
runnable = rq[0]
rq = rq[1:]
for c in runnable.children:
rq.append(runnable.children[c])
for child in runnable.array:
rq.append(child)
if runnable.recorded_variables:
for recording in runnable.recorded_variables:
if recording.data_output.type == DataOutput.DISPLAY:
plot_recording(recording)
elif recording.data_output.type == DataOutput.FILE:
save_recording(recording)
else:
raise Exception("Invalid output type")
if fig_count > 0:
pylab.show()
displays = {}
def plot_recording(recording):
global fig_count
data_output = recording.data_output
recorder = recording.recorder
x = numpy.empty(len(recording.values))
y = numpy.empty(len(recording.values))
i = 0
for (xv, yv) in recording.values:
x[i] = xv
y[i] = yv / recorder.numeric_scale
i = i + 1
if data_output.title in displays:
fig = displays[data_output.title]
else:
fig_count = fig_count + 1
fig = fig_count
displays[data_output.title] = fig
f = pylab.figure(fig)
pylab.title(data_output.title)
pylab.figure(fig)
p = pylab.subplot(111)
p.patch.set_facecolor('#7f7f7f')
pylab.plot(x, y,
color=recorder.color,
label=recorder.quantity)
def save_recording(recording):
pass
<file_sep>"""
XPath parser
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.errors import ParseError
import os.path
def split_path(path):
nesting = 0
for i in xrange(len(path)):
if path[i] == '[':
nesting += 1
elif path[i] == ']':
nesting -= 1
elif path[i] == '/' and nesting == 0:
return [path[0:i], path[(i + 1):]]
return [path]
def seperate_predicate(selector):
sc = selector.count('[')
ec = selector.count('[')
if sc == 0 and ec == 0:
return [selector]
elif sc == 1 and ec == 1:
si = selector.index('[')
ei = selector.index(']')
return [selector[0:si], selector[(si + 1):ei]]
else:
return None
def get_root_ctx(context):
ctx = context
while ctx.parent is not None:
ctx = ctx.parent
return ctx
def resolve_xpath(xpath, context):
path = xpath.strip()
if path[0:2] == '//':
global_search = True
path = path[2:]
ctx = get_root_ctx(context)
elif path[0] == '/':
global_search = False
path= path[1:]
ctx = get_root_ctx(context)
else:
global_search = False
ctx = context
bits = split_path(path)
selector = bits[0]
path = bits[1] if len(bits) > 1 else None
bits = seperate_predicate(selector)
if bits == None:
raise ParseError("Error parsing XPath expression '{0}'".format(xpath))
selector = bits[0]
predicate = bits[1] if len(bits) > 1 else None
print xpath
print selector, predicate, path, global_search
print search_across_model(ctx, selector)
def search_across_model(ctx, name):
nodes = []
print ctx.name, name
<file_sep>"""
Component simulation-spec storage.
@author: <NAME>
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: <EMAIL>
"""
from lems.base.base import LEMSBase
from lems.base.errors import ModelError
from lems.base.util import merge_dict
class Run(LEMSBase):
"""
Stores the description of an object to be run according to an independent
variable (usually time).
"""
def __init__(self, component, variable, increment, total):
"""
Constructor.
See instance variable documentation for information on parameters.
"""
self.component = component
""" Name of the target component to be run according to the
specification given for an independent state variable.
@type: string """
self.variable = variable
""" The name of an independent state variable according to which the
target component will be run.
@type: string """
self.increment = increment
""" Increment of the state variable on each step.
@type: string """
self.total = total
""" Final value of the state variable.
@type: string """
class Record(LEMSBase):
"""
Stores the parameters of a <Record> statement.
"""
def __init__(self, quantity, scale, color):
"""
Constructor.
See instance variable documentation for information on parameters.
"""
self.quantity = quantity
""" Path to the quantity to be recorded.
@type: string """
self.scale = scale
""" Text parameter to be used for scaling the quantity before display.
@type: string """
self.color = color
""" Text parameter to be used to specify the color for display.
@type: string """
self.numeric_scale = None
class DataOutput(LEMSBase):
"""
Generic data output specification class.
"""
DISPLAY = 0
FILE = 1
def __init__(self, type_):
"""
Constuctor.
See instance variable documentation for information on parameters.
"""
self.type = type_
""" Type of output.
@type: string """
class DataDisplay(DataOutput):
"""
Stores specification for a data display.
"""
def __init__(self, title, data_region):
"""
Constuctor.
See instance variable documentation for information on parameters.
"""
DataOutput.__init__(self, DataOutput.DISPLAY)
self.title = title
""" Title for the display.
@type: string """
self.data_region = data_region
""" Display position
@type: string """
class DataWriter(DataOutput):
"""
Stores specification for a data writer.
"""
def __init__(self, path, file_path):
"""
Constuctor.
See instance variable documentation for information on parameters.
"""
DataOutput.__init__(self, DataOutput.FILE)
self.path = path
""" Path to the quantity to be saved to file.
@type: string """
self.file_path = file_path
""" Text parameter to be used for the path to the file for
saving this quantity
@type: string """
class Simulation(LEMSBase):
"""
Stores the simulation-related aspects for a component type.
"""
def __init__(self):
"""
Constructor.
See instance variable documentation for information on parameters.
"""
self.runs = {}
""" Dictionary of runs in this dynamics regime.
@type: dict(string -> lems.model.simulation.Run) """
self.records = {}
""" Dictionary of recorded variables in this dynamics regime.
@type: dict(string -> lems.model.simulation.Record """
self.data_displays = {}
""" Dictionary of data displays mapping titles to regions.
@type: dict(string -> string) """
self.data_writers = {}
""" Dictionary of recorded variables to data writers.
@type: dict(string -> lems.model.simulation.DataWriter """
def add_run(self, component, variable, increment, total):
"""
Adds a runnable target component definition to the list of runnable
components stored in this context.
@param component: Name of the target component to be run.
@type component: string
@param variable: Name of an indendent state variable used to control
the target component (usually time).
@type variable: string
@param increment: Value by which the control variable is to be
incremented in each step.
@type increment: string
@param total: End value for the control variable.
@type total: string
"""
if component in self.runs:
raise ModelError('Duplicate run for ' + component)
self.runs[component] = Run(component, variable, increment, total)
def add_record(self, quantity, scale, color):
"""
Adds a record objects to the list of record objects in this dynamics
regime.
@param quantity: Path to the quantity to be recorded
@type quantity: string
@param scale: Scale of the quantity to be recorded
@type scale: string
@param color: Color of the quantity to be recorded as a 24-bit hex
RGB value (#RRGGBB)
@type color: string
"""
if quantity in self.records:
raise ModelError('Duplicate record {0}'.format(quantity))
self.records[quantity] = Record(quantity, scale, color)
def add_data_display(self, title, data_region):
"""
Adds a data display to this simulation section.
@param title: Title of the display.
@type title: string
@param data_region: Region of the display used for the plot.
@type data_region: string
"""
if title in self.data_displays:
raise ModelError("Redefinition of data display '{0}'".format(title))
self.data_displays[title] = DataDisplay(title, data_region)
def add_data_writer(self, path, file_path):
"""
Adds a data writer to this simulation section.
@param path: Path to the quantity.
@type path: string
@param file_path: Path to the file to be used for recording the quantity.
@type file_path: string
"""
if path in self.data_writers:
raise ModelError("Redefinition of data writer '{0}'".format(path))
self.data_writers[path] = DataWriter(path, file_path)
def merge(self, other):
"""
Merge another set of simulation specs into this one.
@param other: Simulation specs
@type other: lems.model.simulation.Simulation
"""
merge_dict(self.runs, other.runs)
merge_dict(self.records, other.records)
merge_dict(self.data_displays, other.data_displays)
merge_dict(self.data_writers, other.data_writers)
| ed5aa5926e3c5022eac54f6e58ea0111d4f5732e | [
"Markdown",
"Python",
"Makefile"
] | 21 | Python | isaraj82/pylems | 7f06289c91e007f5e5b4d4911ac8b88905280a2c | 2bc0139babce13856ee5f1558318388a70d4a9fc |
refs/heads/master | <file_sep>Title: The Begginers's Guide
Url-title: the-beginner-guide-2
Description: description the-beginner-guide
Author: <NAME>
Date: 25 Juillet 2016
Image: 2743.jpg
Categories: Informatique, Ecologie
Sources: https://bidule.org
## TITLE (h2)
### SUB TITLE (h3)
> Citation
> Citation
```JavaScript
var code;
code = 1;
```
code indente
OU
`code`
-----
ligne
**mot important**
<http://link.fr>
OU
[texte du lien](http://exemple.fr "Description du lien")
image

OU
![texte de description][id]
[id]: http://www.abondance.com/Bin/hello-world.png "titre de l'image"
| First Header | Second Header | Third Header |
| ------------- | ------------: | :----------: |
| Content Cell | Content right-aligned | Content center-aligned |
| Content Cell | Content on two columns ||
<file_sep><?php include("header-1.php"); ?>
<meta name="description" content="Blog pour les feignants avec pleins d'articles super cool vous permettant d'apprendre plein de choses. (enfin, j'espère). Parce que le savoir, c'est le pouvoir !">
<title>The Lazy Sloth - Accueil</title>
<?php include("header-2.php");
$mysqli = mysqli_connect("localhost", "root", "Istiolorf3", "tls");
if (mysqli_connect_errno($mysqli)) {
echo "Echec lors de la connexion à MySQL : " . mysqli_connect_error();
}
$mysqli->query("SET NAMES 'utf8'");
?>
<section>
<?php
include("nav.php");
$pair = 0;
$old = 0;
$not_old = false;
if(isset($_GET['o']))
$old = $_GET['o'];
echo '<div class="col_article">';
$article_query = "";
if(isset($_GET['c']))
$article_query = "SELECT * FROM tls_categories JOIN tls_article_category JOIN tls_articles WHERE tls_categories.category_id = tls_article_category.ac_category_id AND tls_articles.article_id = tls_article_category.ac_article_id AND tls_categories.category_name = '" . $_GET['c'] . "' ORDER BY tls_articles.article_id DESC LIMIT " . $old * 5 . ", 5";
else
$article_query = "SELECT * FROM tls_articles ORDER BY article_id DESC LIMIT " . $old * 5 . ", 5";
if($res = $mysqli->query($article_query))
{
if($res->num_rows == 0)
$not_old = true;
while ($row = $res->fetch_assoc())
{
if($row['article_id'] == 1)
$not_old = true;
$cats_query = "SELECT * FROM tls_categories JOIN tls_article_category WHERE tls_categories.category_id = tls_article_category.ac_category_id AND tls_article_category.ac_article_id = " . $row['article_id'];
$comments_query = "SELECT * FROM tls_comments JOIN tls_articles WHERE tls_articles.article_id = " . $row['article_id'];
echo '<div class="index_article">';
$image;
$date;
if($pair%2)
{
$image = "index_article_image_right";
$date = "index_article_date_left";
}
else
{
$image = "index_article_image_left";
$date = "index_article_date_right";
}
echo '<a href="/article/' . $row['article_url_title'] . '"><h2 class="index_article_title">' . $row['article_title'] . '</h2></a>';
echo '<a href="/article/' . $row['article_url_title'] . '"><img src="/static/img/'.$row['article_image'] .'" class="' . $image . '" /></a>';
echo $row['article_resume'];
echo '<div class="index_article_date ' . $date . '">' . $row['article_date'] . ' - ';
if($res_cats = $mysqli->query($cats_query))
{
$b = true;
while($row_cat = $res_cats->fetch_assoc())
{
if(!$b)
echo ' / ';
echo '<a style="color: grey;" href="/categorie/' . $row_cat['category_url'] . '/0">' . $row_cat['category_name'] . '</a>';
$b = false;
}
$res_cats->free();
}
echo ' - ';
if($res_coms = $mysqli->query($comments_query))
echo $res_coms->num_rows . ' commentaire(s)';
echo '</div>';
echo '</div>';
$pair++;
}
if(!$not_old)
{
if(isset($_GET['c']))
echo '<a href="/categorie/' . $_GET['c'] . '/' . ($old+1) . '"><div class="index_article_old">Les anciens articles</div></a>';
else
echo '<a href="/archive/' . ($old+1) . '"><div class="index_article_old">Les anciens articles</div></a>';
}
echo '</div>';
$res->free();
}
$mysqli->close();
?>
<div class="bas"></div>
</section>
<?php include("footer.php"); ?>
<file_sep><?php
// Selection d'une phrase aléatoire BADASS
$sentence = "Boh... J'ai pas trouvé de phrase aujourd'hui :-(...";
$author = "The Lazy Sloth";
$badass_res;
$min = 1;
$max = 1;
if($badass_res = $mysqli->query("SELECT COUNT(*) FROM tls_badass"))
{
$max = $badass_res->fetch_assoc()["COUNT(*)"];
$aleat = rand($min, $max);
if($sentence_res = $mysqli->query("SELECT * FROM tls_badass WHERE badass_id = " . $aleat))
{
$row_badass = $sentence_res->fetch_assoc();
$sentence = $row_badass["badass_sentence"];
$author = $row_badass["badass_author"];
$sentence_res->free();
}
$badass_res->free();
}
?>
<div class="side">
<form>
<input class="side_search" type="text" name="search" placeholder="Rechercher..." disabled="disabled">
</form>
<div class="side_media">
<a href="https://www.facebook.com/The-Lazy-Sloth-528574410684335/"><img src="/static/img/facebook-icon.png" alt="Icone de facebook" title="Face de bouc" width="32" height="32"/></a>
<a href="https://twitter.com/TheLazySlothFR"><img src="/static/img/twitter-icon.png" alt="Icone de twitter" title="Le pigeon bleue" width="32" height="32"/></a>
<a href="https://github.com/The-Lazy-Sloth"><img src="/static/img/git-icon.png" alt="Icone de github" title="L'octocat de github" width="32" height="32"/></a>
<a href="/feed"><img src="/static/img/rss-icon.png" alt="Icone de flux RSS" title="Pour me stalker !" width="32" height="32"/></a>
</div>
<hr/>
<div class="side_categories">
<h4>Catégories</h4>
<ul>
<?php
// Selection de toutes les catégories
$categories_query = "SELECT * FROM tls_categories";
if($categories_res = $mysqli->query($categories_query))
{
while($row_cat = $categories_res->fetch_assoc())
echo '<a href="/categorie/' . $row_cat['category_url'] . '/0"><li>' . $row_cat['category_string'] . '</li></a>';
$categories_res->free();
}
?>
</ul>
</div>
<br />
<hr />
<div class="side_badass">
<p><?php echo '"' . $sentence . '"'; ?></p>
<p class="side_author"><?php echo $author; ?></p>
</div>
</div>
<file_sep><?php include("header-1.php"); ?>
<meta name="description" content="C'est ici que vous pouvez découvrir l'origine de tout. L'origine de ce blog et de ces articles (si vous avez vraiment du temps à perdre).">
<title>The Lazy Sloth - A propos</title>
<?php include("header-2.php"); ?>
<section>
<div id="about">
<h2>
À propos
</h2>
<p>
Voilà la page sur laquelle vous pourrez découvrir qui je suis, le pourquoi du comment de ce blog et tous les secrets qui l'entoure ! Enfin, quand j'en aurais envie... Pour l'instant j'ai... La flemme... zZzZzZZzzzZ...
</p>
</div>
</section>
<?php include("footer.php"); ?>
<file_sep><?php
//On déclare la fonction Php :
function update_fluxRSS()
{
/* Nous allons générer notre fichier XML d'un seul coup. Pour cela, nous allons stocker tout notre
fichier dans une variable php : $xml.
On commence par déclarer le fichier XML puis la version du flux RSS 2.0.
Puis, on ajoute les éléments d'information sur le channel. Notez que nous avons volontairement
omit quelques balises :
*/
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<rss version="2.0">';
$xml .= '<channel>';
$xml .= ' <title>The Lazy Sloth RSS</title>';
$xml .= ' <link>http://www.thelazysloth.fr</link>';
$xml .= ' <description> Suivez le flux RSS du blog The Lazy Sloth pour avoir les derniers articles en temps réel !</description>';
$xml .= ' <language>fr</language>';
$xml .= ' <copyright>TheLazysloth</copyright>';
$xml .= ' <generator>PHP/MySQL</generator>';
/* Maintenant, nous allons nous connecter à notre base de données afin d'aller chercher les
items à insérer dans le flux RSS.
*/
//on lit les 25 premiers éléments à partir du dernier ajouté dans la base de données
$index_selection = 0;
$limitation = 25;
//On se connecte à notre base de données (pensez à mettre les bons logins)
try {
$mysqli = mysqli_connect('localhost', 'root', 'Istiolorf3', 'tls');
}
catch(Exception $e) {die('Erreur : '.$e->getMessage());}
//On prépare la requête et on exécute celle-ci pour obtenir les informations souhaitées :
$reponse = $mysqli->query('SELECT * FROM tls_rss JOIN tls_articles WHERE article_id = rss_article_id ORDER BY rss_guid DESC LIMIT ' . $index_selection . ', ' . $limitation) or die(print_r($bdd->errorInfo()));
//Une fois les informations récupérées, on ajoute un à un les items à notre fichier
while ($donnees = $reponse->fetch_assoc())
{
$xml .= '<item>';
$xml .= '<title>'.stripcslashes($donnees['article_title']).'</title>';
$xml .= '<link>http://www.thelazysloth.fr/article/'.$donnees['article_url_title'].'</link>';
$xml .= '<guid isPermaLink="true">'.$donnees['rss_guid'].'</guid>';
$xml .= '<pubDate>'.(date("D, d M Y H:i:s O", strtotime($donnees['rss_guid']))).'</pubDate>';
$xml .= '<description>'.stripcslashes($donnees['article_desc']).'</description>';
$xml .= '</item>';
}
//Puis on termine la requête
$reponse->free();
//Et on ferme le channel et le flux RSS.
$xml .= '</channel>';
$xml .= '</rss>';
/* Tout notre fichier RSS est maintenant contenu dans la variable $xml.
Nous allons maintenant l'écrire dans notre fichier XML et ainsi mettre à jour notre flux.
Pour cela, nous allons utiliser les fonctions de php File pour écrire dans le fichier.
Notez que l'adresse URL du fichier doit être relative obligatoirement !
*/
//On ouvre le fichier en mode écriture
$fp = fopen('../static/rss/tls_rss.xml', 'w+');
//On écrit notre flux RSS
fputs($fp, $xml);
//Puis on referme le fichier
fclose($fp);
}
?>
<file_sep><?php include("header-1.php"); ?>
<meta name="description" content="Les projets en cours de développement par The Lazy Sloth. Contribuer, partager, donner vos avis, n'hésitez pas !">
<title>The Lazy Sloth - Projets</title>
<?php include("header-2.php"); ?>
<section>
</section>
<?php include("footer.php"); ?>
<file_sep><?php
require_once '../markdown-extended-master/src/bootstrap.php';
//On va chercher le fichier php qui contient le code pour mettre à jour le flux RSS
include_once("../update_rss.php");
if ($argc != 2)
{
echo 'Error: less or more args';
exit(1);
}
$file_name = $argv[1];
// SQL connect
$mysqli = new mysqli("localhost", "root", "Istiolorf3", "tls");
if ($mysqli->connect_errno)
{
echo "Echec lors de la connexion à MySQL : " . $mysqli->connect_error();
exit(1);
}
use \MarkdownExtended\MarkdownExtended;
$file_parsed = MarkdownExtended::parseSource($file_name);
$article_title = $file_parsed->getTitle();
$article_url_title = $file_parsed->getMetadata()['url-title'];
$article_desc = $file_parsed->getMetadata()['description'];
$article_author = $file_parsed->getMetadata()['author'];
$article_date = $file_parsed->getMetadata()['date'];
$article_image = $file_parsed->getMetadata()['image'];
$article_sources = $file_parsed->getMetadata()['sources'];
$article_body = $file_parsed->getBody();
$pos2 = strpos($file_parsed->getBody(), '<p>');
$pos = strpos($file_parsed->getBody(), '</p>');
$article_resume = substr($file_parsed->getBody(), $pos2, ($pos+3)-($pos2-1));
$article_resume = substr($article_resume, 0, 500);
if(strpos($article_resume, "</p>") === false)
$article_resume = substr_replace($article_resume, "</p>", -4);
$article_insert = "INSERT INTO tls_articles(article_title, article_url_title, article_desc, article_author, article_date, article_image, article_resume, article_content, article_sources) VALUES ('" .
$mysqli->real_escape_string($article_title) . "', '" .
$mysqli->real_escape_string($article_url_title) . "', '" .
$mysqli->real_escape_string($article_desc) . "', '" .
$mysqli->real_escape_string($article_author) . "', '" .
$mysqli->real_escape_string($article_date) . "', '" .
$mysqli->real_escape_string($article_image) . "', '" .
$mysqli->real_escape_string($article_resume) . "', '" .
$mysqli->real_escape_string($article_body) . "', '" .
$mysqli->real_escape_string($article_sources) . "')";
// Insertion dans la base
$mysqli->query($article_insert);
$id_article = $mysqli->insert_id;
// Parsage pour catégorie
$article_category = $file_parsed->getMetadata()['categories'];
$categories = explode(",",$article_category);
$categories_prepare = $mysqli->prepare("SELECT tls_categories.category_id FROM tls_categories WHERE tls_categories.category_name = ?");
$categories_prepare->bind_param('s', $cat_rdy);
// tab des id cat et id art
$tab_cat = array();
// supprime les spaces
foreach($categories as $cat)
{
$cat_rdy = trim($cat);
$categories_prepare->execute();
$categories_prepare->bind_result($id);
while($categories_prepare->fetch())
$tab_cat[] = $id;
}
foreach($tab_cat as $id)
{
$mysqli->query("INSERT INTO tls_article_category(ac_article_id, ac_category_id) VALUES(" . $id_article . ", " . $id . ")");
}
// Insertion du rss
// Définit le fuseau horaire par défaut à utiliser. Disponible depuis PHP 5.1
date_default_timezone_set('Europe/Paris');
$date_rfc = date("Y-m-d H:i:s");
$mysqli->query("INSERT INTO tls_rss(rss_article_id) VALUES(" . $id_article . ")");
//On appelle la fonction de mise à jour du fichier
update_fluxRSS();
?>
<file_sep>Title: [title]
Url-title: [url-title]
Description: [description < 200 mots]
Author: The Lazy Cat
Date: [01 Janvier 2010]
Image: [image.jpg/png]
Categories: [Informatique, Ecologie, Société]
Sources: [https://...., http://...., https://.....]
## TITLE (h2)
### SUB TITLE (h3)
> Citation
> Citation
~~~~
code
~~~~
OU
`code`
ligne
-----
**mot important**
<http://link.fr>
OU
[texte du lien](http://exemple.fr "Description du lien")
image

OU
![texte de description][id]
[id]: http://chemindelimage.fr "titre de l'image"
liste (3 ESPACES)
- elem 1
- elem 2
- sub elem 1
OU
1. elem 1
2. elem 2
1. sub elem 1
| First Header | Second Header | Third Header |
| ------------- | ------------: | :----------: |
| Content Cell | Content right-aligned | Content center-aligned |
| Content Cell | Content on two columns ||
<file_sep><?php
$mysqli = mysqli_connect("localhost", "root", "Istiolorf3", "tls");
if (mysqli_connect_errno($mysqli)) {
echo "Echec lors de la connexion à MySQL : " . mysqli_connect_error();
}
$mysqli->query("SET NAMES 'utf8'");
$n = $_GET['n'];
$row;
if($res = $mysqli->query("SELECT * FROM tls_articles WHERE tls_articles.article_url_title='" . $mysqli->real_escape_string($n) . "'"))
{
$row = $res->fetch_assoc();
$res->free();
}
include("header-1.php");
echo '<meta name="description" content="' . $row['article_desc'] . '">';
echo '<title>' . $row['article_title'] . '</title>';
echo '<link href="/static/css/prism.css" rel="stylesheet" />';
include("header-2.php");
?>
<section>
<div class="article">
<?php
echo '<h1 class="article_title">' . $row['article_title'] . '</h1>';
echo '<div class="article_sub">' . $row['article_date'] . '<br/>';
echo 'Catégorie(s) : ';
$categories_query = "SELECT * FROM tls_categories JOIN tls_article_category JOIN tls_articles WHERE article_id = ac_article_id AND category_id = ac_category_id AND article_id = " . $row['article_id'];
if($res_cat = $mysqli->query($categories_query))
{
while($row_cat = $res_cat->fetch_assoc())
echo ' <a style="color: grey" href="/categorie/' . $row_cat['category_url']. '/0">' . $row_cat['category_name'] . '</a>';
}
$res_cat->free();
echo '</div>';
echo $row['article_content'];
echo '<hr style="margin-top: 20px; margin-bottom: 10px;" />';
$sources = explode(",", $row['article_sources']);
echo '<div class="article_source">';
echo '<h3>Sources</h3>';
foreach($sources as $source)
{
echo '<a href="' . $source . '">' . $source . '</a><br />';
}
echo '<br />';
echo '</div>';
?>
</div>
<div class="ajouter_commentaire">
<?php
include ("commentaires.php");
?>
</div>
<div id="commentaires">
<?php
include ("afficher_commentaires.php");
?>
</div>
</section>
<script src="/static/js/prism.js"></script>
<?php include("footer.php"); $mysqli->close();?>
<file_sep><?php include("header-1.php"); ?>
<meta name="description" content="Envie de me contacter directement ? De critiquer un article ? De boire une bière avec moi ? C'est ici que tout devient possible.">
<title>The Lazy Sloth - Contact</title>
<?php include("header-2.php"); ?>
<section>
<?php
/*
********************************************************************************************
CONFIGURATION
********************************************************************************************
*/
// destinataire est votre adresse mail. Pour envoyer à plusieurs à la fois, séparez-les par une virgule
$destinataire = '<EMAIL>';
// copie ? (envoie une copie au visiteur)
$copie = 'oui';
// Action du formulaire (si votre page a des paramètres dans l'URL)
// si cette page est index.php?page=contact alors mettez index.php?page=contact
// sinon, laissez vide
$form_action = 'contact';
// Messages de confirmation du mail
$message_envoye = "Votre message à bien été envoyé ! Yaouu !";
$message_non_envoye = "L'envoi du mail a échoué, veuillez réessayer !";
// Message d'erreur du formulaire
$message_formulaire_invalide = "Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur.";
$message_final = "";
/*
********************************************************************************************
FIN DE LA CONFIGURATION
********************************************************************************************
*/
/*
* cette fonction sert à nettoyer et enregistrer un texte
*/
function Rec($text)
{
$text = htmlspecialchars(trim($text), ENT_QUOTES);
if (1 === get_magic_quotes_gpc())
{
$text = stripslashes($text);
}
$text = nl2br($text);
return $text;
};
/*
* Cette fonction sert à vérifier la syntaxe d'un email
*/
function IsEmail($email)
{
$value = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
return (($value === 0) || ($value === false)) ? false : true;
}
// formulaire envoyé, on récupère tous les champs.
$nom = (isset($_POST['nom'])) ? Rec($_POST['nom']) : '';
$email = (isset($_POST['email'])) ? Rec($_POST['email']) : '';
$objet = (isset($_POST['objet'])) ? Rec($_POST['objet']) : '';
$message = (isset($_POST['message'])) ? Rec($_POST['message']) : '';
// On va vérifier les variables et l'email ...
$email = (IsEmail($email)) ? $email : ''; // soit l'email est vide si erroné, soit il vaut l'email entré
$err = false; // sert pour remplir le formulaire en cas d'erreur si besoin
if (isset($_POST['envoi']))
{
if (($nom != '') && ($email != '') && ($objet != '') && ($message != ''))
{
// les 4 variables sont remplies, on génère puis envoie le mail
$headers = 'From:'.$nom.' <'.$email.'>' . "\r\n";
$headers .= 'Reply-To: '.$email. "\r\n" ;
$headers .= 'X-Mailer:PHP/'.phpversion();
// envoyer une copie au visiteur ?
if ($copie == 'oui')
{
$cible = $destinataire.','.$email;
}
else
{
$cible = $destinataire;
};
// Remplacement de certains caractères spéciaux
$message = str_replace("'","'",$message);
$message = str_replace("’","'",$message);
$message = str_replace(""",'"',$message);
$message = str_replace('<br>','',$message);
$message = str_replace('<br />','',$message);
$message = str_replace("<","<",$message);
$message = str_replace(">",">",$message);
$message = str_replace("&","&",$message);
// Envoi du mail
$num_emails = 0;
$tmp = explode(',', $cible);
foreach($tmp as $email_destinataire)
{
if (mail($email_destinataire, $objet, $message, $headers))
$num_emails++;
}
if ((($copie == 'oui') && ($num_emails == 2)) || (($copie == 'non') && ($num_emails == 1)))
$message_final = $message_envoye;
else
{
$err = true;
$message_final = $message_non_envoye;
}
}
else
{
// une des 3 variables (ou plus) est vide ...
$message_final = $message_formulaire_invalide;
$err = true;
};
}; // fin du if (!isset($_POST['envoi']))
?>
<form id="contact" method="post" action="contact">
<h2>
Contact
</h2>
<?php
if(strlen($message_final) > 0)
{
echo '<p class="';
if($err)
echo 'contact_err';
else
echo 'contact_ok';
echo '">';
echo $message_final;
echo '</p>';
}
?>
<p id="precontact">
Vous pouvez me contacter avec le formulaire ci-dessous en précisant bien votre email, ça me permet d'avoir la possibilité de vous répondre (Eh oui, c'est pas bête !). Vous pouvez aussi me contacter directement à l'adresse suivante : contact(at)thelazysloth.fr
</p>
<p><label for="nom">Nom</label><br /><input type="text" id="nom" name="nom" tabindex="1" /></p>
<p><label for="email">Email</label><br /><input type="text" id="email" name="email" tabindex="2" /></p>
<p><label for="objet">Objet</label><br /><input type="text" id="objet" name="objet" tabindex="2" /></p>
<p><label for="message">Message</label><br /><textarea id="message" name="message" tabindex="4" cols="50" rows="8"></textarea></p>
<div style="text-align:center;"><input type="submit" name="envoi" value="Envoyer" /></div>
</form>
</section>
<?php include("footer.php"); ?>
<file_sep>wget --no-check-certificate https://github.com/e-picas/markdown-extended/archive/master.tar.gz
tar -xvf master.tar.gz
rm master.tar.gz
<file_sep>CREATE DATABASE tls;
USE tls;
CREATE TABLE tls_articles (
article_id INT(11) AUTO_INCREMENT PRIMARY KEY,
article_title VARCHAR(150) NOT NULL,
article_url_title VARCHAR(40) UNIQUE NOT NULL,
article_desc VARCHAR(255) NOT NULL,
article_author VARCHAR(40) NOT NULL,
article_date VARCHAR(20) NOT NULL,
article_image VARCHAR(50) NOT NULL,
article_resume VARCHAR(500) NOT NULL,
article_content MEDIUMTEXT NOT NULL,
article_sources VARCHAR(500) NOT NULL
);
CREATE TABLE tls_categories (
category_id INT(11) AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(40) UNIQUE NOT NULL,
category_url VARCHAR(40) UNIQUE NOT NULL,
category_string VARCHAR(40) UNIQUE NOT NULL
);
CREATE TABLE tls_article_category (
ac_article_id INT(11) NOT NULL,
ac_category_id INT(11) NOT NULL,
CONSTRAINT pk_article_category PRIMARY KEY (ac_article_id,ac_category_id),
CONSTRAINT fk_article FOREIGN KEY (ac_article_id) REFERENCES tls_articles (article_id),
CONSTRAINT fk_category FOREIGN KEY (ac_category_id) REFERENCES tls_categories (category_id)
);
CREATE TABLE tls_comments (
comment_id INT(11) AUTO_INCREMENT PRIMARY KEY,
comment_date TIMESTAMP NOT NULL,
comment_author VARCHAR(40) NOT NULL,
comment_content TEXT NOT NULL,
comment_article_id INT(11) NOT NULL,
CONSTRAINT fk_article_comment FOREIGN KEY (comment_article_id) REFERENCES tls_articles (article_id)
);
CREATE TABLE tls_rss (
rss_id INT(11) AUTO_INCREMENT PRIMARY KEY,
rss_article_id INT(11) NOT NULL,
rss_guid TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_rss_article FOREIGN KEY (rss_article_id) REFERENCES tls_articles (article_id)
);
CREATE TABLE tls_badass (
badass_id INT(11) AUTO_INCREMENT PRIMARY KEY,
badass_sentence TEXT NOT NULL,
badass_author VARCHAR(50) NOT NULL
);
INSERT INTO tls_categories(category_name, category_url, category_string) VALUES ('Informatique', 'informatique', 'Geek zone (Informatique)');
INSERT INTO tls_categories(category_name, category_url, category_string) VALUES ('Ecologie', 'ecologie', 'Green Life (Ecologie)');
INSERT INTO tls_categories(category_name, category_url, category_string) VALUES ('Société', 'societe', 'Ô paisible monde (Société)');
INSERT INTO tls_badass(badass_sentence, badass_author) VALUES ('Je suis une phrase badass', 'Le plus grand');
INSERT INTO tls_badass(badass_sentence, badass_author) VALUES ('Je suis une phrase badass2', 'Le plus fort');
INSERT INTO tls_badass(badass_sentence, badass_author) VALUES ('Je suis une phrase badass3', 'Le plus beau');
<file_sep>Title: The Begginers's Guide
Url-title: article-6
Description: resume of article-6
Author: <NAME>
Date: 25 Juillet 2016
Image: 2743.jpg
Categories: Informatique, Ecologie
Sources: https://bidule.org
# The Beginner's Guide to Writing with MultiMarkdown
As a writer, I have tried just about every word processor ever invented. I first started with [WordStar][wordstar], moved onto [WordPerfect][wordperfect], then graduated to [Microsoft Word]. But when I started blogging, everything changed. Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla eeeeeeeeeeeeeee eeeeeeeeeeeeee eeeeeeeeeeeeeewwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwww eeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeee eeeeeeeeeeeeee eeeeeeeeeeeeeee eeeeeeeeeeeeeee eeeeeeeeeeeee eeeeeeeee eeeeeeeeee eeeeeeeeeeeeeee eee eeeeeeeeee eeeeeeeeeeeeeeee eeeeee eeee eeee eeeeeeee eeee eeee uuu uuu uuu uuu uuu uuu uuu uuu uuu uuu uuuu uuu uuu uuu uuu uu uuuu uuu uuuu uuu uu uu u
I ultimately learned HTML, but it is certainly not the most natural way to write. I have used a number of "blog processors," including [BlogJet][blogjet] and then [MarsEdit][marsedit]. But in the last few years, I have completely converted over to MultiMarkdown.
It a way of writing that turns minimally marked up plain text into well formatted documents, including rich text and HTML. You can even use it directly with [WordPress][wordpress]. If you are a writer, you owe it to yourself to explore MultiMarkdown.
[table caption]
| First Header | Second Header | Third Header |
| ------------- | ------------: | :----------: |
| Content Cell | Content right-aligned | Content center-aligned |
| Content Cell | Content on two columns ||
> This is my blockquote
> and a second line ...
****
A paragraph with the word HTML.
And, before your eyes glaze over, it is honestly the easiest way to write *anything.* The syntax is so simple, you already know it. If you can use an emoticon, you can write in MultiMarkd
`function ()`
~~~~
Hola
~~~~
| | Grouping ||
First Header | Second Header | Third header |
------------- | ------------: | :----------: |
Content Cell | *Long Cell* ||
Content Cell | **Cell** | **Cell** |
New section | More | Data |
And more | And more ||

[prototype *table*]
| | Grouping ||
First Header | Second Header | Third header |
First comment | Second comment | Third comment |
------------- | ------------: | :----------: |
Content Cell | *Long Cell* ||
Content Cell | **Cell** | **Cell** |
New section | More | Data |
And more | And more ||
And more || And more |
![myimage][]
*[HTML]: Hyper-Text Markup Language<file_sep> <h3>Commentaires</h3>
<br />
<?php
$requete_commentaires = "SELECT * FROM tls_comments WHERE tls_comments.comment_article_id = " . $row['article_id'];
if($res_coms = $mysqli->query($requete_commentaires))
{
while ($row_coms = $res_coms->fetch_assoc())
{
echo '<div class="commentaire">';
echo '<div class="titre_commentaire">' . $row_coms['comment_author'] . ' - ' . $row_coms['comment_date'] . '</div>';
echo '<div class="contenu_commentaire">' . $row_coms['comment_content'] . '</div>';
echo '</div>';
echo '<br />';
}
$res_coms->free();
}
?>
<br />
| 849a808178b9891ac14526fc7cadba2bf21b0cef | [
"Markdown",
"SQL",
"PHP",
"Shell"
] | 14 | Markdown | The-Lazy-Sloth/TheLazySloth | e642515701f8d3c33a80f6d6bb26e20e12a6b190 | 741ec4497830f1742821974b50aadcf6174763b2 |
refs/heads/master | <file_sep>import rospy
import tensorflow as tf
import numpy as np
from PIL import ImageDraw
from PIL import Image
from styx_msgs.msg import TrafficLight
"""
The following functions are have been adopted from CarND-Object-Detection-Lab by Udacity
(https://github.com/udacity/CarND-Object-Detection-Lab)
filter_boxes, draw_boxes, to_image_coord, load_graph
"""
class TLClassifier(object):
"""
NOTE: The job of the classifier is to provide only the state of the traffic light,
and not the bounding box. The boxes_tensor does not have to be evaluated and we
might remove it later.
"""
def __init__(self, graph_path, min_score=0.8):
# load classifier TF graph
self.tfgraph = self.load_graph(graph_path)
rospy.loginfo('Loaded inference graph at {}'.format(graph_path))
# pick out relevant tensors from the graph
self.input_tensor = self.tfgraph.get_tensor_by_name('image_tensor:0')
self.boxes_tensor = self.tfgraph.get_tensor_by_name('detection_boxes:0')
self.scores_tensor = self.tfgraph.get_tensor_by_name('detection_scores:0')
self.classes_tensor = self.tfgraph.get_tensor_by_name('detection_classes:0')
# start TF session
self.tfsess = tf.Session(graph=self.tfgraph)
rospy.loginfo('Session created.')
# minimum score for filtering out the detection boxes
self.MIN_SCORE = min_score
self.COLOR_LIST = ['red', 'yellow', 'green']
def get_classification(self, image, debug=False):
"""Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
# with tf.Session(graph=self.tfgraph) as sess:
# convert image to numpy array of uint8 and add an axis to the shape
image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)
# evaluate the tensors for boxes, scores and classes
boxes, scores, classes = self.tfsess.run(
[self.boxes_tensor, self.scores_tensor, self.classes_tensor],
feed_dict={self.input_tensor: image_np})
boxes = np.squeeze(boxes)
scores = np.squeeze(scores)
classes = np.squeeze(classes)
boxes, scores, classes = self.filter_boxes(boxes, scores, classes)
if debug:
image = Image.fromarray(image)
width, height = image.size
# rospy.loginfo('Image size: {}'.format(image_np.shape))
box_coords = self.to_image_coords(boxes, height, width)
self.draw_boxes(image, box_coords, classes)
return np.array(image)
else:
if classes: # if some traffic lights were detected
# decode class ID
class_id = classes[0]-1
if class_id == 0:
return TrafficLight.RED
elif class_id == 1:
return TrafficLight.YELLOW
elif class_id == 2:
return TrafficLight.GREEN
else:
return TrafficLight.UNKNOWN
else:
return TrafficLight.UNKNOWN
def filter_boxes(self, boxes, scores, classes):
"""Return boxes with a confidence >= `min_score`"""
n = len(classes)
idxs = []
for i in range(n):
if scores[i] >= self.MIN_SCORE:
idxs.append(i)
return boxes[idxs, ...], scores[idxs, ...], classes[idxs, ...]
@staticmethod
def to_image_coords(boxes, height, width):
"""
The original box coordinate output is normalized, i.e [0, 1].
This converts it back to the original coordinate based on the image
size.
"""
box_coords = np.zeros_like(boxes)
box_coords[:, 0] = boxes[:, 0] * height
box_coords[:, 1] = boxes[:, 1] * width
box_coords[:, 2] = boxes[:, 2] * height
box_coords[:, 3] = boxes[:, 3] * width
return box_coords
def draw_boxes(self, image, boxes, classes, thickness=4):
"""Draw bounding boxes on the image"""
draw = ImageDraw.Draw(image)
for i in range(len(boxes)):
bot, left, top, right = boxes[i, ...]
color = self.COLOR_LIST[int(classes[i]) - 1]
draw.line([(left, top), (left, bot), (right, bot), (right, top), (left, top)],
width=thickness, fill=color)
@staticmethod
def load_graph(graph_file):
"""Loads a frozen inference graph"""
graph = tf.Graph()
with graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(graph_file, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return graph<file_sep>import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import argparse
# modified: https://github.com/datitran/raccoon_dataset/blob/master/xml_to_csv.py
# parser = argparse.ArgumentParser()
# parser.add_argument('source_dir', help='directory containing image files and corresponding '
# 'annotations (labels) in VOC XML format')
# parser.add_argument('csv_filename', help='name of the CSV file to be created')
# args = parser.parse_args()
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(os.path.join(path, '*.xml')):
root = ET.parse(xml_file).getroot()
for member in root.findall('object'): # for all bounding boxes (objects)
value = (
root.find('filename').text,
int(root.find('size')[0].text), # image width and height
int(root.find('size')[1].text),
member[0].text, # image label
int(member[4][0].text), # bbox coordinates (xmin, ymin, xmax, ymax)
int(member[4][1].text),
int(member[4][2].text),
int(member[4][3].text)
)
xml_list.append(value)
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
def main():
for directory in ['train','test']:
image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
xml_df = xml_to_csv(image_path)
xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)
print('Successfully converted xml to csv.')
main()
# if __name__ == "__main__":
# xml_df = xml_to_csv(args.source_dir)
# xml_df.to_csv(args.csv_filename, index=None)
# print('Successfully converted xml to csv.')<file_sep>## Self-Driving Car Capstone Project - Team Dörnbach
*"Self-Driving Car Engineer Nanodegree? Dat war doch schon immer dein alter Jugendtraum!"*

This is the capstone project of [Udacity's Self-Driving Car Engineer Nanodegree](www.udacity.com/drive) in which the goal was to develop a software in a team of 5 students that runs on a real, self-driving car and is able to steer it through a test track, respecting the defined speed limit and to stop at traffic lights.
The operating system used for this task is called ROS (Robot Operating System), a very popular, modular system optimized for robotics which allows the synchronous and asynchronous communication between the single hard- and software components involved in this task such as the camera providing the image required for the traffic light detection, lidar or software services which for example provide already processed data in form of the current traffic light state or the next way points for the drive by wire system.


---
##  Team Dörnbach
*Nobody can develop a self-driving car alone and so it was really a huge pleasure to spend theses last 10 months together in Slack with this awesome team and to develop this final of the overall 14 projects with it:*
* [<NAME>](https://github.com/thelukasssheee) - <NAME>
* [<NAME>](https://github.com/alyxion) - Lead Engineer @ Zühlke Engineering GmbH
* [<NAME>](https://github.com/jacobnzw) - PhD candidate in cybernetics
* [<NAME>](https://github.com/weisurya) - Software Engineer @ Xendit
* [<NAME>](https://github.com/melihyazgan) - Engineer @ ITK Engineering GmbH
*"Self-Driving Car Engineer Nanodegree? Dat war doch schon immer dein alter Jugendtraum!"*
---


---
This repository contains the whole source code of this project and you are welcome to try it out yourself on your local machine. [Here](setup.md) you can find the detailed setup instructions to do so.
<file_sep>#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
from std_msgs.msg import Int32
from scipy.spatial import KDTree
from sensor_msgs.msg import Image
import cv2
import cv_bridge
import numpy as np
import time
import math
LOOP_HERTZ = 10
class DoernbachDebugView(object):
def __init__(self):
rospy.init_node('doernbach debug view')
rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
rospy.Subscriber('/traffic_waypoint', Int32, self.traffic_cb)
rospy.Subscriber('/obstacle_waypoint', Int32, self.obstacle_cb)
self.debug_view = rospy.Publisher('doernbach_debug_view', Image, queue_size=1)
self.start_time = time.time()
self.pose = None
self.base_waypoints = None
self.waypoints_2d = None
self.waypoint_tree = None
self.loop()
def loop(self):
"""
Initialize the debug view updater.
The frequency of this publishing loop is controlled by LOOP_HERTZ
"""
rate = rospy.Rate(LOOP_HERTZ)
while not rospy.is_shutdown():
self.update_debug_view()
rate.sleep()
def update_debug_view(self):
"""
Update the debug view's output
"""
scaling = 1
base_size = 256
dv_width = int(scaling*base_size)
dv_height = dv_width
image = np.zeros((dv_height, dv_width,3), np.uint8)
off = time.time()-self.start_time
tick_off = int(off*1000)
direction = math.pi*2*(tick_off%2000)/2000
text_size = 0.25 * scaling
if self.pose:
x = self.pose.pose.position.x
y = self.pose.pose.position.y
dir = self.pose.pose.orientation.z
y_off = 20*scaling
cv2.putText(image, "X: {:0.2f}".format(x), (10 * scaling, y_off), cv2.FONT_HERSHEY_SIMPLEX,
text_size, (255, 0, 0), 1 * scaling, cv2.LINE_AA)
cv2.putText(image, "Y: {:0.2f}".format(y), (60 * scaling, y_off), cv2.FONT_HERSHEY_SIMPLEX,
text_size, (255, 0, 0), 1 * scaling, cv2.LINE_AA)
cv2.putText(image, "Dir: {:0.2f}".format(dir), (110 * scaling, y_off), cv2.FONT_HERSHEY_SIMPLEX,
text_size, (255, 0, 0), 1 * scaling, cv2.LINE_AA)
cv2.line(image, (dv_width//2, dv_height//2), (int(dv_width//2+math.cos(direction)*dv_width/2), int(dv_height//2+math.sin(direction)*dv_height/2)), (255,0,0), 1)
img_msg = cv_bridge.CvBridge().cv2_to_imgmsg(image, "rgb8")
self.debug_view.publish(img_msg)
def pose_cb(self, msg):
"""
Retrieve the current location of car
"""
self.pose = msg
def waypoints_cb(self, waypoints):
"""
Get the waypoint values from /base_waypoints
"""
self.base_waypoints = waypoints
if not self.waypoints_2d:
self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] \
for waypoint in waypoints.waypoints]
self.waypoint_tree = KDTree(self.waypoints_2d)
def traffic_cb(self, msg):
pass
def obstacle_cb(self, msg):
pass
if __name__ == '__main__':
try:
DoernbachDebugView()
except rospy.ROSInterruptException:
rospy.logerr('Could not start Doenbach debug view node.')
<file_sep>#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped, TwistStamped
from styx_msgs.msg import Lane, Waypoint
from std_msgs.msg import Int32
from scipy.spatial import KDTree
import numpy as np
import math
from bisect import bisect_left
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
As mentioned in the doc, you should ideally first implement a version which does not care
about traffic lights or obstacles.
Once you have created dbw_node, you will update this node to use the status of traffic lights too.
Please note that our simulator also provides the exact location of traffic lights and their
current status in `/vehicle/traffic_lights` message. You can use this message to build this node
as well as to verify your TL classifier.
TODO (for Yousuf and Aaron): Stopline location for each traffic light.
'''
LOOKAHEAD_WPS = 40 # Number of waypoints we will publish. You can change this number
LOOP_HERTZ = 10
class WaypointUpdater(object):
def __init__(self):
rospy.init_node('waypoint_updater')
rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)
rospy.Subscriber('/current_velocity', TwistStamped, self.velocity_cb)
rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)
# TODO: Add a subscriber for /traffic_waypoint and /obstacle_waypoint below
rospy.Subscriber('/traffic_waypoint', Int32, self.traffic_cb)
rospy.Subscriber('/obstacle_waypoint', Int32, self.obstacle_cb)
self.final_waypoints_pub = rospy.Publisher('final_waypoints', Lane, queue_size=1)
# Get vehicle parameters from rospy server. Fallback to -5m/s^2, in case value is missing
self.decel_limit = rospy.get_param('~decel_limit',-5)
self.decel_slowdown = -1.0 # m/s^2 slowdown deceleration rate
# TODO: Add other member variables you need below
self.pose = None
self.velocity = None
self.velocity_curr = None
self.base_waypoints = None
self.waypoints_2d = None
self.waypoint_tree = None
self.WP_idx_traffic_light = -1
self.WP_idx_stop = -1
self.WP_idx_ego = None
self.WP_idx_brake = None
self.WP_idx_slowdown = None
self.ego_dist = None
self.brake_dist = None
self.slowdown_dist = None
self.distances = []
self.slowing_down = False
self.loop()
def loop(self):
"""
Initialize the waypoint updater. Only run while the DWB system is enabled
(automate throttle, brake, steering control system)
The frequency of this publishing loop is controlled by LOOP_HERTZ
"""
rate = rospy.Rate(LOOP_HERTZ)
while not rospy.is_shutdown():
if self.pose and self.waypoint_tree:
# Get closest waypoint
closest_waypoint_idx = self.get_closest_waypoint_idx()
self.WP_idx_ego = closest_waypoint_idx
# Set farthest waypoint. No wrap-around necessary here! This is done in next func
farthest_waypoint_idx = closest_waypoint_idx + LOOKAHEAD_WPS
# Publish waypoint
self.publish_waypoints(closest_waypoint_idx, farthest_waypoint_idx)
rate.sleep()
def get_closest_waypoint_idx(self):
"""
Find the closest waypoint index.
"""
# To understand this nested object, check `rosmsg info styx_msgs/Lane`
x = self.pose.pose.position.x
y = self.pose.pose.position.y
# Limit to only return 1 record, `[0]` is the position and `[1]` is the index
closest_idx = self.waypoint_tree.query([x, y], 1)[1]
# Check if closest is ahead or behind vehicle
closest_coord = self.waypoints_2d[closest_idx]
# Regular case: somewhere in between the waypoint list
if (closest_idx > 0):
prev_idx = closest_idx - 1
# Wrap-around case: closest waypoint equals zero (begin of list) --> wrap-around
elif (closest_idx == 0):
prev_idx = len(self.waypoints_2d)-1 # choose last index of list
# Warning case: negative number found
else:
prev_idx = closest_idx - 1
log_str = 'waypoint_updater.py: WARNING! closest_idx < 0, not plausible! '
log_str += 'prev_wp=' + str(prev_idx) + ', '
log_str += 'curr_wp=' + str(closest_idx)
rospy.logwarn(log_str)
# Extract coordinate from previous ID
prev_coord = self.waypoints_2d[prev_idx]
# Equation for hyperplane through closest_coords
cl_vect = np.array(closest_coord)
prev_vect = np.array(prev_coord)
pos_vect = np.array([x, y])
# Check if value is really ahead or behind ego vehicle
val = np.dot(cl_vect - prev_vect, pos_vect - cl_vect)
if val > 0:
closest_idx = (closest_idx + 1) % len(self.waypoints_2d)
# Return value
return closest_idx
def publish_waypoints(self, closest_idx, farthest_idx):
"""
Creating new lane object for the car. Includes acceleration/deceleration logic
"""
lane = Lane()
lane.header = self.base_waypoints.header
# Read waypoints to generate horizon including wrap-around
if (farthest_idx > closest_idx):
horizon_waypoints = self.base_waypoints.waypoints[closest_idx:farthest_idx]
else:
indices = range(closest_idx,farthest_idx)
horizon_waypoints = np.take(self.base_waypoints.waypoints,indices,mode='wrap')
# Check if traffic light signal and proximity to stop line require deceleration
if ((self.slowing_down == True) and \
((self.WP_idx_traffic_light == -1) or (self.WP_idx_traffic_light > self.WP_idx_stop))):
# Reset speed to target velocity if TL ahead is not yellow/red or too far away
# This step was necessary to get the car moving again after TL turns green
for j, wp in enumerate(horizon_waypoints):
horizon_waypoints[j].twist.twist.linear.x = self.velocity
lane.waypoints = horizon_waypoints
# Reset status bit for "slowing down"
self.slowing_down = False
else:
# Check once where slowdown/brake points are located
if self.slowing_down == False:
self.calc_slowdown_WPs()
# Update speed values of horizon waypoints
lane.waypoints = self.decelerate_waypoints(horizon_waypoints, closest_idx, farthest_idx)
# Update ego distance
self.ego_dist = self.distances[self.WP_idx_traffic_light] - self.distances[self.WP_idx_ego]
# Debug output
# if all(value is not None for value in [self.WP_idx_ego, self.WP_idx_slowdown,
# self.WP_idx_brake, self.velocity, lane.waypoints[0].twist.twist.linear.x,
# self.ego_dist, self.brake_dist, self.slowdown_dist]):
# str_out = 'EgoIDX=%i,SlwIDX=%i,BrkIDX=%i,StpIDX=%i. v_CC=%4.1f,v_cur=%4.1f,v_set=%4.1f,SlowDown=%r' % ( \
# self.WP_idx_ego,self.WP_idx_slowdown,self.WP_idx_brake,self.WP_idx_traffic_light, \
# self.velocity,self.velocity_curr,lane.waypoints[0].twist.twist.linear.x,self.slowing_down)
# rospy.logwarn(str_out)
# str_out = 'EgoDist=%4.1f,SlwDist=%4.1f,BrkDist=%4.1f. v_CC=%4.1f,v_cur=%4.1f,v_set=%4.1f,SlowDown=%r' % ( \
# self.ego_dist,self.slowdown_dist,self.brake_dist, \
# self.velocity,self.velocity_curr,lane.waypoints[0].twist.twist.linear.x,self.slowing_down)
# rospy.logwarn(str_out)
# Publish final lane waypoints to ROS
self.final_waypoints_pub.publish(lane)
pass
def decelerate_waypoints(self, waypoints, closest_idx, farthest_idx):
"""
Deceleration: adjust speed values of waypoints for slowing down
"""
WPs_temp = []
stop_idx = self.WP_idx_traffic_light # Index of traffic light
brake_dist = self.brake_dist # Distance necessary to stop in time
slowdown_dist = self.slowdown_dist # Distance for comfortably slowing down
base_vel = self.velocity # Target velocity, if undisturbed
# Walk through horizon waypoints and adjust speed values
for i, wp in enumerate(waypoints):
# p = Waypoint()
# p.pose = wp.pose
# p.twist = wp.twist
# Calculate distance of each horizon waypoint to stop line
dist = self.distances[stop_idx] - self.distances[i+closest_idx]
# Adjust speed, if waypoint is within distance necessary to stop in time
# New target velocity value, dependent on
# - target speed (e.g. cruise control set speed)
# - distance foreseen for decelerating
# - current distance of waypoint to traffic light stop line
vel_Brk = vel_SD = base_vel
if dist < brake_dist:
vel_Brk = 0.5 * self.velocity * (1.00 - 1.00*np.cos(np.pi/brake_dist * dist))
if dist < slowdown_dist:
vel_SD = 0.5 * self.velocity * (1.45 - 0.55*np.cos(np.pi/slowdown_dist * dist))
# Use smaller value of either current velocity or new target velocity
vel = min(vel_Brk, vel_SD) #, self.velocity_curr)
# Pull velocity down to zero if it becomes very small
if vel < 0.70:
vel = 0.
# If point is behind stop line
if dist < 0:
vel = 0.
# Update velocity value of waypoint
wp.twist.twist.linear.x = vel
# Update slow down status bit to true
self.slowing_down = True
# Add current waypoint to array
WPs_temp.append(wp)
# if i == 0 or i == 39:
# rospy.loginfo(' Horizon WP %02i: dist=%6.1f, v_targ=%4.1f' % (i,dist,wp.twist.twist.linear.x))
# Return updated horizon waypoints
return WPs_temp
def calc_slowdown_WPs(self):
"""
Calculate slow down waypoints: for strong braking and gentle velocity reduction (unused)
"""
WP_ego = self.WP_idx_ego
WP_stop = self.WP_idx_traffic_light
# Store stop position in variable that is not overriden by traffic light message
self.WP_idx_stop = WP_stop
# Calculate distance between ego and stop line
self.ego_dist = self.distances[self.WP_idx_traffic_light] - self.distances[self.WP_idx_ego]
# Calculate distance needed to stop (s = 0.5*a*t^2, t = v/a)
# Formula: s = 0.5*v^2/a with a=0.5*a_lim --> 0.5 cancels out
self.brake_dist = abs(self.velocity*self.velocity / self.decel_limit)
# Calculate waypoint idx, where braking should start
WP_dist_brake = self.distances[self.WP_idx_traffic_light] - self.brake_dist
self.WP_idx_brake = bisect_left(self.distances, WP_dist_brake)
# Optional: gentle slow-down
# Calculate distance useful to disengage trottle
self.slowdown_dist = abs(self.velocity*self.velocity / self.decel_slowdown)
# Calculate waypoint idx, where gentle slowdown should start
WP_dist_slowdown = self.distances[self.WP_idx_traffic_light] - self.slowdown_dist
self.WP_idx_slowdown = bisect_left(self.distances, WP_dist_slowdown)
# Check if vehicle is already within slow down area
if self.WP_idx_ego > self.WP_idx_slowdown:
# Update start of slowdown and distance with current position
self.WP_idx_slowdown = self.WP_idx_ego
self.slowdown_dist = self.ego_dist
# Return to calling function
pass
def distance(self, waypoints, wp1, wp2):
"""
Calculate distance between to waypoint idx which are further apart
"""
dist = 0.
dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)
for i in range(wp1, wp2+1):
dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position)
wp1 = i
return dist
def single_distance(self, waypoints, wp1, wp2):
"""
Calculate distance between to waypoint idx, which are only seperated by one index
"""
dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)
dist = dl(waypoints[wp1].pose.pose.position, waypoints[wp2].pose.pose.position)
return dist
def pose_cb(self, msg):
"""
Retrieve the current location of car
"""
# TODO: Implement
self.pose = msg
def velocity_cb(self, msg):
"""
Retrieve the current vehicle speed
"""
self.velocity_curr = msg.twist.linear.x
def waypoints_cb(self, waypoints):
"""
Get the waypoint values from /base_waypoints
Calculate distance array once and save CPU time during loop operation
"""
# TODO: Implement
self.base_waypoints = waypoints
if not self.waypoints_2d:
self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] \
for waypoint in waypoints.waypoints]
self.waypoint_tree = KDTree(self.waypoints_2d)
# Read out sample velocity
self.velocity = waypoints.waypoints[50].twist.twist.linear.x
# Create distance array in order to calculate distances just once for all waypoints and
# over and over with every time step
if not self.distances:
prev_WP = None
j = 0
for curr_WP in waypoints.waypoints:
if (j == 0):
self.distances.append(0.)
else:
dist_cum = self.single_distance(waypoints.waypoints, j-1, j) + self.distances[j-1]
self.distances.append(dist_cum)
prev_WP = curr_WP
j += 1
pass
def traffic_cb(self, msg):
"""
Get the traffic light information from /traffic_waypoint
"""
# Get traffic light index
self.WP_idx_traffic_light = msg.data
pass
def obstacle_cb(self, msg):
# TODO: Callback for /obstacle_waypoint message. We will implement it later
pass
def get_waypoint_velocity(self, waypoint):
return waypoint.twist.twist.linear.x
def set_waypoint_velocity(self, waypoints, waypoint, velocity):
waypoints[waypoint].twist.twist.linear.x = velocity
if __name__ == '__main__':
try:
WaypointUpdater()
except rospy.ROSInterruptException:
rospy.logerr('Could not start waypoint updater node.')
<file_sep>import os
import shutil
import glob
import xml.etree.ElementTree as et
from random import shuffle
import matplotlib.pyplot as plt
import argparse
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument('source_dir', help='directory containing image files and corresponding '
'annotations (labels) in VOC XML format')
parser.add_argument('target_dir', help='directory where the train and test subdirectories '
'will be placed')
parser.add_argument('--balance-classes', help='creates data set with balanced classes',
action='store_true')
args = parser.parse_args()
INVALID_LABEL = "tl_none"
RED = "tl_red"
YELLOW = "tl_yellow"
GREEN = "tl_green"
TEST_PERCENT = 10
def valid_xml_files():
"""
List of valid files, not containing `tl_none` label.
"""
valid = []
for xml_file in glob.glob(os.path.join(args.source_dir, '*.xml')):
if et.parse(xml_file).getroot().find('object/name').text != INVALID_LABEL:
valid.append(os.path.basename(xml_file))
return valid
def ryg_split(xml_list):
red_list, yellow_list, green_list = [], [], []
for xml in xml_list:
src_path = os.path.join(args.source_dir, xml)
label = et.parse(src_path).getroot().find('object/name').text
if label == RED:
red_list.append(xml)
if label == YELLOW:
yellow_list.append(xml)
if label == GREEN:
green_list.append(xml)
return red_list, yellow_list, green_list
def class_stats():
label_count = {'tl_red': 0, 'tl_yellow': 0, 'tl_green': 0}
for xml in xml_list:
label = et.parse(xml).getroot().find('object/name').text
label_count[label] += 1
return label_count
def create_train_test_dirs(train_list, test_list):
# create directories for train/test sets
train_path = os.path.join(args.target_dir, 'train')
test_path = os.path.join(args.target_dir, 'test')
print()
print("Creating train set in: {}".format(train_path))
os.mkdir(train_path)
for filename in tqdm(train_list):
src_path = os.path.join(args.source_dir, filename)
tgt_path = os.path.join(train_path, filename)
shutil.copy(src_path + '.jpg', tgt_path + '.jpg')
shutil.copy(src_path + '.xml', tgt_path + '.xml')
print()
print("Creating test set in: {}".format(test_path))
os.mkdir(test_path)
for filename in tqdm(test_list):
src_path = os.path.join(args.source_dir, filename)
tgt_path = os.path.join(test_path, filename)
shutil.copy(src_path + '.jpg', tgt_path + '.jpg')
shutil.copy(src_path + '.xml', tgt_path + '.xml')
# # plot class statistics
# label_count = class_stats(valid_xml_files())
# xt = [0, 1, 2]
# plt.bar(xt, list(label_count.values()), color=['red', 'yellow', 'green'])
# plt.xticks(xt, list(label_count.keys()))
# plt.show()
if args.balance_classes:
xml_files = valid_xml_files()
shuffle(xml_files)
red_files, yellow_files, green_files = ryg_split(xml_files)
last_ind = min([len(red_files), len(yellow_files), len(green_files)]) - 1
data_list = red_files[:last_ind] + yellow_files[:last_ind] + green_files[:last_ind]
shuffle(data_list)
test_ind = len(data_list) // TEST_PERCENT
test_list = [fn.split('.')[0] for fn in data_list[:test_ind]]
train_list = [fn.split('.')[0] for fn in data_list[test_ind:]]
else:
shuffled_xml_list = valid_xml_files()
shuffle(shuffled_xml_list)
test_ind = len(shuffled_xml_list) // TEST_PERCENT
test_list = [fn.split('.')[0] for fn in shuffled_xml_list[:test_ind]]
train_list = [fn.split('.')[0] for fn in shuffled_xml_list[test_ind:]]
create_train_test_dirs(train_list, test_list)<file_sep>from pid import PID
from lowpass import LowPassFilter
from yaw_controller import YawController
import rospy
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self, *args, **kwargs):
# Initialization of vehicle properties
vehicle_mass = kwargs['vehicle_mass']
fuel_capacity = kwargs['fuel_capacity']
self.brake_deadband = kwargs['brake_deadband']
self.decel_limit = kwargs['decel_limit']
self.accel_limit = kwargs['accel_limit']
wheel_radius = kwargs['wheel_radius']
wheel_base = kwargs['wheel_base']
steer_ratio = kwargs['steer_ratio']
max_lat_accel = kwargs['max_lat_accel']
max_steer_angle = kwargs['max_steer_angle']
# Yaw controller
min_speed = 0.1
self.yaw_controller = YawController(wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle)
# Speed throttle controller
throttle_kp = 1.6 # Proportional term
throttle_ki = 0.001 # Integral term
throttle_kd = 0.0 # Differential term
self.throttle_controller = PID(throttle_kp, throttle_ki, throttle_kd, self.decel_limit, self.accel_limit)
# Steering controller
steer_kp = 1.8 # Proportional term
steer_ki = 0.005 # Integral term
steer_kd = 0.4 # Differential term
self.steering_controller = PID(steer_kp, steer_ki, steer_kd, -max_steer_angle, max_steer_angle)
# Define low-pass filter settings
tau = 3 # 1/(2pi*tau) = cutoff frequency
ts = 1 # Sample time
# Filtering out all high frequency noise in the velocity
self.vel_lpf = LowPassFilter(tau,ts)
# Get current time stamp during initialization
self.last_time = rospy.get_time()
self.brake_torque = (vehicle_mass + fuel_capacity * GAS_DENSITY) * wheel_radius
def calcdeltasec(self):
curr_time = rospy.get_time()
delta = curr_time - self.last_time if self.last_time else 0.1
self.last_time = curr_time
return delta
def control(self, *args, **kwargs):
# TODO: Change the arg, kwarg list to suit your needs
# Return throttle, brake, steer
linear_vel = kwargs['linear']
angular_vel = kwargs['angular']
current_vel = kwargs['current']
#rospy.logwarn("Angular velocity: {0}".format(angular_vel))
#rospy.logwarn("Target velocity: {0}".format(linear_vel))
#rospy.logwarn("Target angular vel: {0}\n".format(angular_vel))
#rospy.logwarn("Current velocity: {0}".format(current_vel))
#rospy.logwarn("Filtered velocity: {0}".format(self.vel_lpf.get()))
vel_error = linear_vel - current_vel
sample_time = self.calcdeltasec()
unfiltered_step = self.throttle_controller.step(vel_error, sample_time)
velocity = self.vel_lpf.filt(unfiltered_step)
steering = self.yaw_controller.get_steering(linear_vel, angular_vel, current_vel)
steering = self.steering_controller.step(steering, sample_time)
throttle = 0.
brake = 0.
# Hard Brake
if linear_vel < 0.2:
steering = 0. # don't need yaw controller at low speeds
brake = abs(self.decel_limit) * self.brake_torque
else:
# speed up
if velocity > 0.:
throttle = velocity
# slow down
else:
velocity = abs(velocity)
# brake if outside deadband
if velocity > self.brake_deadband:
brake = velocity * self.brake_torque
# rospy.logwarn("Throttle: {0}".format(throttle))
# rospy.logwarn("Brake: {0}".format(brake))
# rospy.logwarn("Steering: {0}".format(steering))
# rospy.logwarn("Velocity error: {0}".format(vel_error))
return throttle, brake, steering
| 8536fd114a5e3565c7e9958ca668f243eb678f2e | [
"Markdown",
"Python"
] | 7 | Python | TeamDoernbach/SDCNanodegreeCapstone | 10bdc59dc1b8f56136bf3f6f4ab64c97082420bb | e235bb7154d2bef7cf9bd8b0328b22e3d24484d8 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/estilos-bitacora-consulta.css">
</head>
<?php
if(isset($_POST['boton-consulta'])){
require_once("conexion.php");
$desde = $_POST['km-salida-vehiculo'];
$hasta= $_POST['km-llegada-vehiculo'];
// echo "desde " . $desde . " hasta " . $hasta;
echo "
<div class='titulo-tabla'>
<strong>Nombre </strong>
<strong>Apellidos</strong>
<strong>Placa Vehículo</strong>
<strong>Actividad</strong>
<strong>Fecha Salida</strong>
<strong>Km Salida</strong>
<strong>Fecha Llegada</strong>
<strong>Km Llegada</strong>
<strong></strong>
</div>
";
$queryConsulta = "
select u.nombres, u.apellidos, b.placa_vehiculo, b.actividad, b.fecha_salida, b.km_salida, b.fecha_llegada, b.km_llegada
from usuarios u inner join bitacora b on u.codigo_usuario= b.codigo_usuario
where fecha_salida between '$desde' and '$hasta' order by fecha_salida desc";
$ejecucionConsulta = mysqli_query($con, $queryConsulta);
$numeroFilaConsulta = mysqli_num_rows($ejecucionConsulta);
if($numeroFilaConsulta >=1){
if($ejecucionConsulta){
$j=0;
while ($fila = mysqli_fetch_array($ejecucionConsulta)){
$nombre = $fila['nombres'];
$apellidos = $fila['apellidos'];
$correo = $fila['placa_vehiculo'];
$actividad = $fila['actividad'];
$fecha_salida = $fila['fecha_salida'];
$km_salida = $fila['km_salida'];
$fecha_llegada = $fila['fecha_llegada'];
$km_llegada = $fila['km_llegada'];
$j++;
// echo $nombre . " || " . $apellidos . " |" . $correo . " |" . $actividad
// . " " . $fecha_salida . " " . $km_salida . " " . $fecha_llegada . " " . $km_llegada
// . "</br>";
// echo $nombre . " || " . $apellidos . " |" . $correo . " |" . $actividad
// . " " . $fecha_salida . " " . $km_salida . " " . $fecha_llegada . " " . $km_llegada
// . "</br>";
echo "
<div class='contenido-tabla'>
<strong>$nombre </strong>
<strong>$apellidos</strong>
<strong>$correo</strong>
<strong>$actividad</strong>
<strong>$fecha_salida</strong>
<strong>$km_salida</strong>
<strong>$fecha_llegada</strong>
<strong>$km_llegada</strong>
<strong></strong>
</div>
";
}
}
}else{
$queryConsulta = "
select u.nombres, u.apellidos, b.placa_vehiculo, b.actividad, b.fecha_salida, b.km_salida, b.fecha_llegada, b.km_llegada
from usuarios u inner join bitacora b on u.codigo_usuario=b.codigo_usuario
order by fecha_salida desc limit 150 ";
$ejecucionConsulta = mysqli_query($con, $queryConsulta);
$j=0;
while ($fila = mysqli_fetch_array($ejecucionConsulta)){
$nombre = $fila['nombres'];
$apellidos = $fila['apellidos'];
$correo = $fila['placa_vehiculo'];
$actividad = $fila['actividad'];
$fecha_salida = $fila['fecha_salida'];
$km_salida = $fila['km_salida'];
$fecha_llegada = $fila['fecha_llegada'];
$km_llegada = $fila['km_llegada'];
$j++;
// echo $nombre . " || " . $apellidos . " |" . $correo . " |" . $actividad
// . " " . $fecha_salida . " " . $km_salida . " " . $fecha_llegada . " " . $km_llegada
// . "</br>";
echo "
<div class='contenido-tabla'>
<strong>$nombre </strong>
<strong>$apellidos</strong>
<strong>$correo</strong>
<strong>$actividad</strong>
<strong>$fecha_salida</strong>
<strong>$km_salida</strong>
<strong>$fecha_llegada</strong>
<strong>$km_llegada</strong>
<strong></strong>
</div>
";
}
}
}else{
// echo "";
}
?><file_sep><?php
if((isset($_POST['enviar']))){
if(!empty($_POST['correoForm']) && !empty($_POST['passwordForm'])){
require_once("conexion.php");
$correoForm = $_POST['correoForm'];
$passwordForm = $_POST['passwordForm'];
$query = "
SELECT * FROM usuarios where (correo = '$correoForm') and (contrasenia = '$passwordForm')";
$ejecutar = mysqli_query($con,$query);
$numeroFilas=mysqli_num_rows($ejecutar);
if($numeroFilas =1){
// echo "Hay registros";
// echo $correoForm . " " . $passwordForm;
if($ejecutar){
// header ('location: bitacora.php');
// echo "Bienvenido";
session_start();
$correo = $_POST['correoForm'];
echo $correo;
$_SESSION["correo"]= $correo;
if(isset($_SESSION["correo"])){
$i=0;
while($fila = mysqli_fetch_array($ejecutar)){
$nombre = $fila['nombres'];
$codigo_usuario = $fila['codigo_usuario'];
$i++;
echo " " . $nombre;
}
$_SESSION["nombre"]= $nombre;
$_SESSION["codigo_user"] = $codigo_usuario;
header('Location: http://localhost/gestionvehiculo/modelo/bitacora.php');
}else{
header('Location: http://localhost/gestionvehiculo');
}
}
else{
echo "Redirigir al index";
}
}else{
// echo "Usuario o contraseña no válidos";
echo "<script> alert('Usuario o contraseña no válidos');</script>";
}
}else{
// header ('location: ../index.php');
// echo " Error: los campos estan vacios";
echo "<script> alert('Los campos estan vacios');</script>";
}
}
?><file_sep><?php
if(isset($_POST['cerrar'])){
session_start();
session_destroy();
header('Location: http://localhost/gestionvehiculo');
}else{
echo "";
}
?>
<file_sep><?php
// session_start();
if(isset($_POST['boton-llegada-vehiculo'])){
if(!empty($_POST['km-llegada-vehiculo']) and !empty($_POST['observacion-vehiculo'])){
$km_llegada_vehiculo = $_POST['km-llegada-vehiculo'];
$observacion_vehiculo =$_POST['observacion-vehiculo'];
require_once("conexion.php");
$codigo_usuario_sesion = $_SESSION["codigo_user"];
$consulta_salida = "
select * from bitacora
where codigo_usuario = '$codigo_usuario_sesion'
and (fecha_salida is not null and fecha_llegada is null)
order by id_bitacora desc
limit 1
";
$ejecutar_codigo = mysqli_query($con, $consulta_salida);
$numero_fila_codigo = mysqli_num_rows($ejecutar_codigo);
if($numero_fila_codigo ==1){
$consulta_update = "
UPDATE bitacora
set fecha_llegada = NOW(), km_llegada = $km_llegada_vehiculo, observacion='$observacion_vehiculo' , km_recorrido=$km_llegada_vehiculo
where codigo_usuario = '$codigo_usuario_sesion'
and (fecha_salida is not null and fecha_llegada is null)
order by id_bitacora desc
limit 1
";
$ejecutar_update = mysqli_query ($con, $consulta_update);
if($ejecutar_update){
// echo "Datos insertados correctamente";
echo "<script> alert('Datos insertados correctamente');</script>";
}else{
// echo "Error al insertar los datos";
echo "<script> alert('Error al insertar los datos');</script>";
}
}else{
// echo "No puede llegar porque no ha salido";
echo "<script> alert('No puede LLEGAR porque no ha SALIDO');</script>";
// echo $numero_fila_codigo;
}
}else{
// echo "Los campo no puede estar vacio";
echo "<script> alert('Los campo no puede estar vacio');</script>";
}
}else {
// echo "No se ha presionado";
}
?><file_sep><?php
if(isset($_POST['boton-salida-vehiculo'])){
$placa = $_POST['placa-vehiculo'];
// $vehiculo = $_POST['nombre-vehiculo'];
$actividad = $_POST['actividad-vehiculo'];
$km_salida = $_POST['km-salida-vehiculo'];
if(!empty($_POST['placa-vehiculo'])
&& !empty($_POST['actividad-vehiculo']) && !empty($_POST['km-salida-vehiculo']))
{
if( strlen($placa) != 8){
echo "<script> alert('La placa debe tener 8 caracteres') </script>";
}else{
// echo "<script> alert('La placa CORRECTA') </script>";
$nombre = $_SESSION["nombre"];
$codigo_usuario_session = $_SESSION["codigo_user"];
require_once('conexion.php');
$consulta_fecha = "
select * from bitacora
where codigo_usuario = '$codigo_usuario_session'
and (fecha_salida is null or fecha_llegada is null)
order by id_bitacora desc
limit 1 ";
$ejecutar_codigo = mysqli_query($con, $consulta_fecha);
$numero_filas_codigo = mysqli_num_rows($ejecutar_codigo);
// echo "Numero de filas".$numero_filas_codigo . "Codigo usuarios" . $codigo_usuario_session;
if($numero_filas_codigo === 0){
// echo "Puede salir";
echo $numero_filas_codigo;
$consulta = "
INSERT INTO bitacora
(placa_vehiculo, conductor, actividad, fecha_salida, km_salida, codigo_usuario)
values ( '$placa' , '$nombre', '$actividad' , NOW() , $km_salida ,'$codigo_usuario_session')
";
$ejecutar = mysqli_query($con, $consulta);
if($ejecutar){
// echo "VEHÍCULO REGISTRADO CORRECTAMENTE";
echo "<script> alert('Registrado con éxito');</script>";
}else{
// echo "ERROR AL INGRESAR EL VEHÍCULO";
echo "<script> alert('Error al insgresar los datos');</script>";
}
}else{
// echo "No puede salir porque no ha llegado";
echo "<script> alert('No puede SALIR porque no ha llegado');</script>";
// echo $numero_filas_codigo;
}
}
// $nombre = $_SESSION["nombre"];
// $codigo_usuario_session = $_SESSION["codigo_user"];
// require_once('conexion.php');
// $consulta_fecha = "
// select * from bitacora
// where codigo_usuario = '$codigo_usuario_session'
// and (fecha_salida is null or fecha_llegada is null)
// order by id_bitacora desc
// limit 1 ";
// $ejecutar_codigo = mysqli_query($con, $consulta_fecha);
// $numero_filas_codigo = mysqli_num_rows($ejecutar_codigo);
// // echo "Numero de filas".$numero_filas_codigo . "Codigo usuarios" . $codigo_usuario_session;
// if($numero_filas_codigo === 0){
// // echo "Puede salir";
// echo $numero_filas_codigo;
// $consulta = "
// INSERT INTO bitacora
// (placa_vehiculo, conductor, actividad, fecha_salida, km_salida, codigo_usuario)
// values ( '$placa' , '$nombre', '$actividad' , NOW() , $km_salida ,'$codigo_usuario_session')
// ";
// $ejecutar = mysqli_query($con, $consulta);
// if($ejecutar){
// // echo "VEHÍCULO REGISTRADO CORRECTAMENTE";
// echo "<script> alert('Registrado con éxito');</script>";
// }else{
// // echo "ERROR AL INGRESAR EL VEHÍCULO";
// echo "<script> alert('Error al insgresar los datos');</script>";
// }
// }else{
// // echo "No puede salir porque no ha llegado";
// echo "<script> alert('No puede SALIR porque no ha llegado');</script>";
// // echo $numero_filas_codigo;
// }
}else{
// echo "Los campos no pueden estar vacios";
echo "<script> alert('Los campos no pueden estar vacios');</script>";
}
}else{
// echo "no se presionó";
}
function validaPlaca($placa){
if( strlen($placa) == 7){
echo "correcto";
}else{
echo "<script> alert('La placa debe tener 8 caracteres') </script>";
}
}
?><file_sep><?php
$server = "localhost";
$userHost = "root";
$passHost = "<PASSWORD>";
$dbHost = "gestionvehiculos";
$con = mysqli_connect($server, $userHost, $passHost, $dbHost)
or die ("Error al conectar");
?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/estilos-index.css">
<title> GESTIÓN VEHÍCULOS PG</title>
</head>
<body>
<div class="container">
<div class="formulario-login">
<form action="" method="post">
<div class="img-login">
<img src="img/login.png" alt="">
</div>
<input type="email" name="correoForm" placeholder=" Correo ">
<input type="<PASSWORD>" name="passwordForm" placeholder=" <PASSWORD> ">
<!-- <input type="text" name="nombreForm" placeholder="CI: "> -->
<input class="boton-login" type="submit" name="enviar" value="Ingresar">
<p>
<?php include_once("modelo/login.php"); ?>
</p>
</form>
</div>
</div>
</body>
</html><file_sep>-- MySQL dump 10.13 Distrib 8.0.22, for Win64 (x86_64)
--
-- Host: localhost Database: gestionvehiculos
-- ------------------------------------------------------
-- Server version 8.0.22
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `bitacora`
--
DROP TABLE IF EXISTS `bitacora`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `bitacora` (
`id_bitacora` int NOT NULL AUTO_INCREMENT,
`placa_vehiculo` varchar(8) NOT NULL,
`conductor` varchar(45) NOT NULL,
`actividad` varchar(400) NOT NULL,
`fecha_salida` datetime(6) NOT NULL,
`km_salida` int NOT NULL,
`fecha_llegada` datetime(6) DEFAULT NULL,
`km_llegada` int DEFAULT NULL,
`observacion` varchar(200) DEFAULT NULL,
`km_recorrido` int DEFAULT NULL,
`codigo_usuario` varchar(6) DEFAULT NULL,
PRIMARY KEY (`id_bitacora`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `bitacora`
--
LOCK TABLES `bitacora` WRITE;
/*!40000 ALTER TABLE `bitacora` DISABLE KEYS */;
INSERT INTO `bitacora` VALUES (1,'ASS-1234','DANIEL','VISITA CLIENTE','2020-11-12 13:18:09.000000',10000,'2020-11-12 13:18:09.000000',1200,'SIN NOVEDAD',1200,'PG0001'),(2,'AQQ-5675','JUAN','VISITA LABORATORIO','2020-11-19 12:34:50.000000',1300,'2020-11-19 12:34:50.000000',1400,'SIN NOVEDADES',1500,'PG0001'),(3,'AAA-1234','JUAN','VISTA','2020-11-19 13:03:50.000000',12345,'2020-11-20 12:45:01.000000',123456789,'Sin novedad',1111111,'PG0001'),(13,'11111111','DANIEL','11111111','2020-11-20 12:46:39.000000',11111111,'2020-11-20 12:46:52.000000',123456789,'Sin novedad',1111111,'PG0001'),(14,'4444','DANIEL','444','2020-11-20 12:49:37.000000',444,'2020-11-20 12:57:57.000000',123456789,'Sin novedad',1111111,'PG0001'),(15,'QAS-1255','DANIEL','visita a clientes','2020-11-20 13:04:15.000000',12345,'2020-11-20 13:04:32.000000',98756,'sin novedades',98756,'PG0001'),(16,'qqq','DANIEL','qqq','2020-11-20 13:06:03.000000',111,'2020-11-20 13:06:26.000000',111,'11',111,'PG0001');
/*!40000 ALTER TABLE `bitacora` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-11-27 12:21:41
<file_sep>
<?php
session_start();
// $correo = $_POST['correoForm'];
// echo $correo;
// if(isset($_SESSION["nombre"])){
// echo "Gestión de vehículos </br>";
// echo "Nombre del login: " . $_SESSION["nombre"] . "</br>";
// echo "Correo del login: " . $_SESSION["correo"] . "</br>";
// echo "Codigo del User: " . $_SESSION["codigo_user"] . "</br>";
// }else{
// header('Location: http://localhost/gestionvehiculo');
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="<KEY>" crossorigin="anonymous"/>
<link rel="stylesheet" href="../css/estilos-bitacora.css">
<title>Registro Vehículos</title>
</head>
<body>
<header>
<div class="formulario-cerrar-sesion">
<form action="" method="post">
<input class="boton-cerrar-sesion" type="submit" value="Cerrar Sesión" name="cerrar">
<?php
// if(isset($_POST['cerrar'])){
// session_start();
// session_destroy();
// header('Location: http://localhost/gestionvehiculo');
// }else{
// echo "No entró al if de cerrar";
// }
require_once('cerrar-sesion.php');
?>
</form>
</div>
</header>
<div class="titulo-bitacora">
<p>Gestión de Vehículos <i class="fas fa-car"></i> </p>
</div>
<div class="datos-session">
<?php
if(isset($_SESSION["nombre"])){
// echo "Gestión de vehículos </br>";
echo "<i class='fas fa-user-astronaut'></i> Bienvenid@: " . $_SESSION["nombre"] . "</br>";
// echo "Correo del login: " . $_SESSION["correo"] . "</br>";
// echo "Codigo del User: " . $_SESSION["codigo_user"] . "</br>";
}else{
header('Location: http://localhost/gestionvehiculo');
}
?>
</div>
<div class="datos-salida-entrada">
<div class="formulario-salida">
<p>DATOS DE SALIDA</p>
<form action="" method="POST">
<label for="">Placa</label>
<input class="placa" type="text" name="placa-vehiculo" placeholder="ABC-1234" >
<label for="">Actividad</label>
<textarea name="actividad-vehiculo" id="" placeholder="Motivo de salida"></textarea>
<label for="">Km de Salida</label>
<input class="km-salida" type="number" name="km-salida-vehiculo" placeholder="23254" >
<br>
<div class="btn-e-s">
<input class="boton-e-s" type="submit" name="boton-salida-vehiculo" value="Enviar" >
</div>
<?php
include_once ("datos-salida.php");
?>
</form>
</div>
<div class="formulario-llegada">
<p>DATOS DE LLEGADA</p>
<form action="" method="POST">
<label for="">Km de llegada</label>
<input class="km-llegada" type="number" name="km-llegada-vehiculo" placeholder="23254" >
<br>
<label for="">Observación</label>
<textarea name="observacion-vehiculo" id="" placeholder="Ingrese alguna novedad"></textarea>
<br>
<div class="btn-e-s">
<input class="boton-e-s" type="submit" name="boton-llegada-vehiculo" value="Enviar" >
</div>
<?php
include_once ("datos-llegada.php");
?>
</form>
</div>
</div>
<div class="consulta-historial">
<div class="mostrar-datos">
<form action="" method="post">
<div class="resultado-consulta">
<?php
include_once ("consultar-historico.php");
?>
</div>
<div class="container-consulta">
<input class="boton-consul" type="submit" name="boton-consulta" value="Consultar Historial" >
<label for="">Desde:</label>
<input type="date" name="km-salida-vehiculo">
<label for="">Hasta:</label>
<input type="date" name="km-llegada-vehiculo">
</div>
</form>
</div>
</div>
</body>
</html>
| a9318056d2928f8d679075a0762f06c6ad747098 | [
"SQL",
"PHP"
] | 9 | PHP | carpiordaniel/E-S-Vehiculos | 6a5524246f051cad72ccb1cfaf4a6a33b904a8e2 | a8c056ba6daed86a7f11aded5d64e165bba11d0f |
refs/heads/master | <repo_name>tomoh1r/make-clean.py<file_sep>/doc/Release.md
# Release
Setup.
```bat
> python3.X.exe -m venv --clear venv
> .\venv\Scripts\python.exe -m pip install -U setuptools pip
> .\venv\Scripts\python.exe -m pip install -e .[release]
```
Build it.
```bat
> .\venv\Scripts\python.exe setup.py sdist
```
Release it.
```bat
> .\venv\Scripts\python.exe -m twine upload -r testpypi dist/*
> .\venv\Scripts\python.exe -m twine upload dist/*
```
<file_sep>/test/test_make_clean.py
import os
import pytest
@pytest.mark.parametrize(
"ignores,is_exists",
[
# test for remove file
([], False),
# test for do not remove excluded file
(["example.txt"], True),
],
)
def test_remove_file(monkeypatch, make_clean, tmp_dir, ignores, is_exists):
dir_name = os.path.basename(tmp_dir)
monkeypatch.chdir(os.path.dirname(tmp_dir))
target_file = os.path.join(tmp_dir, "example.txt")
open(target_file, "w").close()
ignores = [os.path.join(dir_name, x) for x in ignores]
assert os.path.exists(target_file)
make_clean([dir_name], ignores=ignores)
assert os.path.exists(target_file) == is_exists
@pytest.mark.parametrize(
"files,ignores,is_exists",
[
# test for remove dir
([], [], False),
# test for do not remove not empty dir
(["example.txt"], [os.path.join("example", "example.txt")], True),
# test for do not remove excluded dir
([], ["example" + os.sep], True),
],
)
def test_remove_dir(monkeypatch, make_clean, tmp_dir, files, ignores, is_exists):
dir_name = os.path.basename(tmp_dir)
monkeypatch.chdir(os.path.dirname(tmp_dir))
target_dir = os.path.join(tmp_dir, "example")
os.mkdir(target_dir)
for fname in files:
target_file = os.path.join(target_dir, fname)
open(target_file, "w").close()
ignores = [os.path.join(dir_name, x) for x in ignores]
assert os.path.exists(target_dir)
make_clean([dir_name], ignores=ignores)
assert os.path.exists(target_dir) == is_exists
def test_donot_remove_dir_without_ossep_suffix(monkeypatch, make_clean, tmp_dir):
dir_name = os.path.basename(tmp_dir)
monkeypatch.chdir(os.path.dirname(tmp_dir))
target_dir = os.path.join(tmp_dir, "example")
os.mkdir(target_dir)
assert os.path.exists(target_dir)
make_clean([dir_name], ignores=[os.path.join(dir_name, "example")])
assert not os.path.exists(target_dir)
@pytest.mark.parametrize(
"prefix",
[
# test for remove file
(""),
# test for starts with slash
("/"),
],
)
def test_not_remove_exclude_file_from_file(monkeypatch, make_clean, tmp_dir, prefix):
dir_name = os.path.basename(tmp_dir)
monkeypatch.chdir(os.path.dirname(tmp_dir))
target_dir = os.path.join(tmp_dir, "example")
os.mkdir(target_dir)
target_file = os.path.join(target_dir, "example.txt")
open(target_file, "w").close()
with open(".cleanignore", "w") as fp:
fp.write(prefix + dir_name + "/example/example.txt")
assert os.path.exists(target_file)
make_clean([dir_name], ".cleanignore")
assert os.path.exists(target_file)
def test_clean_current_dir(monkeypatch, make_clean, tmp_dir):
monkeypatch.chdir(tmp_dir)
target_file = os.path.join(tmp_dir, "example.txt")
open(target_file, "w").close()
assert os.path.exists(tmp_dir)
assert os.path.exists(target_file)
make_clean(".")
assert os.path.exists(tmp_dir)
assert not os.path.exists(target_file)
def test_clean_dirs(monkeypatch, make_clean, tmp_dir):
dir_name = os.path.basename(tmp_dir)
monkeypatch.chdir(os.path.dirname(tmp_dir))
here = os.getcwd()
dir_names = [os.path.join(dir_name, x) for x in ["exmaple0", "example1"]]
for dname in dir_names:
os.mkdir(dname)
target_file = os.path.join(here, dname, "example.txt")
open(target_file, "w").close()
for dname in dir_names:
assert os.path.exists(os.path.join(here, dname, "example.txt"))
make_clean(dir_names)
for dname in dir_names:
assert not os.path.exists(os.path.join(here, dname, "example.txt"))
<file_sep>/.flake8
[flake8]
max-line-length = 99
ignore = E203,W503,W504
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist,venv
<file_sep>/test/linter/test_pylint.py
#
# Copyright (C) 2021, NAKAMURA, Tomohiro <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
from __future__ import absolute_import, unicode_literals
import os
from importlib import import_module
import pytest
@pytest.mark.linter
@pytest.mark.parametrize(
"dpath",
[
("setup.py"),
("make_clean.py"),
("test/conftest.py"),
("test/test_make_clean.py"),
("test/linter"),
],
)
def test_pylint(chdir_root_path, dpath):
fullpath = os.path.abspath(dpath)
cmd = "{} -j 6 --rcfile={} --score=no".format(fullpath, os.path.abspath(".pylintrc"))
stdout, stderr = import_module("pylint.epylint").py_run(cmd, return_std=True)
stdout, stderr = stdout.getvalue(), stderr.getvalue()
assert "" == stdout, stdout
<file_sep>/doc/Home.md
# Home
Welcome to the make-clean.py wiki!
<file_sep>/setup.py
# -*- coding: utf-8 -*-
from setuptools import setup
def _readme():
import os
here = os.path.dirname(os.path.abspath(__file__))
return open(os.path.join(here, "README.md")).read()
setup(
name="make-clean",
version=__import__("make_clean", fromlist=["__version__"]).__version__,
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/jptomo/make-clean.py",
description="A Cleanup Utility",
long_description=_readme(),
long_description_content_type="text/markdown",
py_modules=["make_clean"],
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
],
license="MIT License",
entry_points={"console_scripts": ["make-clean = make_clean:main"]},
extras_require={
"dev": ["setuptools", "pytest", "pytest-cov"],
'dev:python_version>="3.6"': ["flake8", "black", "isort[pyproject]", "pylint"],
"release": ["twine", "wheel"],
},
)
<file_sep>/doc/UnitTest.md
# UnitTest
I use [pytest](http://doc.pytest.org/en/latest/).
Setup.
```bat
> python3.X.exe -m venv --clear venv
> .\venv\Scripts\python.exe -m pip install -U setuptools pip
> .\venv\Scripts\python.exe -m pip install -e .[dev]
```
Test it.
```bat
> .\venv\Scripts\python.exe -m pytest
```
<file_sep>/README.md
# make-clean
Make clean your files. [](https://github.com/tomoh1r/make-clean.py/actions?query=workflow%3Atest)
---
If one'd like to make sphinx repository with github-pages sumodule, one shoud
exclude rm `_build/html/.git`.
`make-clean` package provide to keep `.git` file with it.
Switch `make.bat` file clean to below
```bat
if "%1" == "clean" (
.\path\to\make-clean.exe _build -i _build\html\.git _build\html\.gitignore
goto end
)
```
## Usage
This package has a `make-clean` command.
```bat
> .\venv\Scripts\make-clean.exe -h
usage: make-clean-script.py [-h] [--clean-ignore CLEAN_IGNORE]
[-i [IGNORE [IGNORE ...]]]
TARGET_DIR [TARGET_DIR ...]
clean target dir without ignores
positional arguments:
TARGET_DIR dir to remove recursively
optional arguments:
-h, --help show this help message and exit
--clean-ignore CLEAN_IGNORE
dir/file file to ignore from remove
-i [IGNORE [IGNORE ...]], --ignores [IGNORE [IGNORE ...]]
dir/file to ignore from remove
```
<file_sep>/make_clean.py
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
VERSION = (2, 0, 1)
__version__ = "{0:d}.{1:d}.{2:d}".format(*VERSION)
def make_clean(target_dirs, ignore_fname=None, ignores=None):
"""clean target_dir except ignores relatively
cleanup target directory except:
- file: is in ignores
- directory: is in ignores
Files and directories are referenced relatively.
:param str target_dir: target directory to cleanup
:param list ignores: not rm files or directories
"""
target_dirs = [os.path.abspath(x) for x in target_dirs]
ignore_dirs, ignore_files = parse_ignores(ignore_fname, ignores)
rm_files(target_dirs, ignore_dirs, ignore_files)
rm_dirs(target_dirs, ignore_dirs)
def parse_ignores(ignore_fname, ignore_patterns):
ignores = []
if ignore_fname:
if os.path.isfile(ignore_fname):
with open(ignore_fname) as fp:
for line in fp:
line = line.strip()
if not line.startswith("#"):
# lstrip / and replace / to os.sep
line = line.lstrip("/").replace("/", os.sep)
ignores.append(line)
if ignore_patterns:
# lstrip /
ignores.extend([x.lstrip("/") for x in ignore_patterns if x])
ignore_dirs = tuple(
os.path.abspath(x) for x in ignores if x and x.endswith(os.sep) and os.path.isdir(x)
)
ignore_files = {os.path.abspath(x) for x in ignores if x and os.path.isfile(x)}
return ignore_dirs, ignore_files
def rm_files(target_dirs, ignore_dirs, ignore_files):
"""Remove files."""
for dir_path in target_dirs:
for root, _, files in os.walk(dir_path):
for f in files:
fullpath = os.path.join(root, f)
if fullpath.startswith(ignore_dirs) or fullpath in ignore_files:
continue
os.remove(fullpath)
def rm_dirs(target_dirs, ignore_dirs):
"""Remove empty directories."""
ignore_dir_set = set(ignore_dirs)
for dir_path in target_dirs:
for root, _, _ in os.walk(dir_path):
if not is_empty_dir(root) or root in ignore_dir_set or root in target_dirs:
continue
shutil.rmtree(root)
def is_empty_dir(target_dir):
"""return is empty directory or not
:param str target_dir: target dir
"""
for root, _, files in os.walk(target_dir):
for f in files:
if os.path.isfile(os.path.join(root, f)):
return False
return True
def main():
parser = argparse.ArgumentParser(description=u"clean target dir without ignores")
parser.add_argument(
"target_dir", metavar="TARGET_DIR", nargs="+", help=u"dir to remove recursively "
)
parser.add_argument(
"--clean-ignore",
metavar="CLEAN_IGNORE",
help=u"dir/file file to ignore from remove",
default=".cleanignore",
)
parser.add_argument(
"-i",
"--ignores",
metavar="IGNORE",
help=u"dir/file to ignore from remove",
nargs="*",
default=[],
)
parser.set_defaults(
func=lambda args: make_clean(args.target_dir, args.clean_ignore, args.ignores)
)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
<file_sep>/test/conftest.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import platform
import shutil
import tempfile
import pytest
from pkg_resources import parse_version
def pytest_addoption(parser):
parser.addoption("--lint-code", action="store_true", help="To run linter.")
def pytest_configure(config):
config.addinivalue_line("markers", "linter: mark test lint code.")
def pytest_runtest_setup(item):
envnames = [mark for mark in item.iter_markers(name="linter")]
if envnames:
if parse_version(platform.python_version()) < parse_version("3.6"):
pytest.skip("lint code requires python3.6 or higher.")
if not item.config.getoption("--lint-code"):
pytest.skip("skip lint code.")
@pytest.fixture()
def root_path():
_here = os.path.dirname(os.path.abspath(__file__))
return os.path.dirname(_here)
@pytest.fixture()
def chdir_root_path(monkeypatch, root_path):
monkeypatch.chdir(root_path)
@pytest.fixture(scope="module")
def make_clean():
from make_clean import make_clean
return make_clean
@pytest.fixture(scope="function")
def tmp_dir(monkeypatch):
"""manage create and delete temporary directory
I need real directory, so I can't use tmpdir...
(or directory basename)
"""
try:
tmp_dir = tempfile.mkdtemp()
yield tmp_dir
finally:
# tmp_dir を削除するためにカレントディレクトリを移動
monkeypatch.chdir(os.path.dirname(tmp_dir))
shutil.rmtree(tmp_dir)
<file_sep>/test/linter/conftest.py
#
# Copyright (C) 2021, <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
import contextlib
import sys
from io import StringIO
import pytest
@pytest.fixture()
def capture():
@contextlib.contextmanager
def fn():
bk = sys.stdout, sys.stderr
try:
out = [StringIO(), StringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout, sys.stderr = bk
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
return fn
| 03df1224e8074896bd8effd70569c35fc3cdcd91 | [
"Markdown",
"Python",
"INI"
] | 11 | Markdown | tomoh1r/make-clean.py | e2a6f6be18b8f011f42b97a0acba51ae6a40688e | f3ed726ca9d2e92b17de7f845a85e467208a8102 |
refs/heads/master | <repo_name>SincemeTom/Yimengjianghu<file_sep>/Assets/Common/TextureChannelPacker/Editor/TextureChannelPackerWindow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public enum E_TextureChannel
{
R,
G,
B,
A
}
public class TextureInfo : System.IDisposable
{
public int Width = 512;
public int Height = 512;
public FilterMode filterMode = FilterMode.Bilinear;
public Texture Texture = null;
public string Name = "";
public string Path = "";
public bool[] PreviewChannel = { true, true, true, true };
public Vector4 GetChannalMask()
{
Vector4 v = Vector4.zero;
v.x = PreviewChannel[0] ? 1 : 0;
v.y = PreviewChannel[1] ? 1 : 0;
v.z = PreviewChannel[2] ? 1 : 0;
v.w = PreviewChannel[3] ? 1 : 0;
return v;
}
public Vector4 GetChannelRef()
{
Vector4 v = Vector4.zero;
if (!PreviewChannel[3])
v.w = 1f;
return v;
}
public TextureInfo(Texture texture)
{
Reset(texture);
}
public TextureInfo(int width, int height)
{
Width = width;
Height = height;
Texture = RenderTexture.GetTemporary(width, height);
}
public void Reset(Texture texture)
{
Dispose();
Texture = texture;
if (texture != null)
{
Width = texture.width;
Height = texture.height;
filterMode = texture.filterMode;
Name = texture.name;
Path = AssetDatabase.GetAssetPath(texture);
}
}
public void Reset(int width, int height)
{
if(width!=Width || height != Height)
{
Dispose();
Width = width;
Height = height;
Texture = RenderTexture.GetTemporary(width, height);
}
}
public void Dispose()
{
var rt = Texture as RenderTexture;
if(rt!=null)
{
RenderTexture.ReleaseTemporary(rt);
}
Texture = null;
}
}
public class ChannelInfo
{
public E_TextureChannel Channel;
public TextureInfo Source;
public bool Invert = false;
public ChannelInfo(E_TextureChannel channel,Texture tex)
{
Channel = channel;
Source = new TextureInfo(tex);
}
public Vector4 GetChannalMask()
{
Vector4 v = Vector4.zero;
float iv = Invert ? -1f : 1f;
switch(Channel)
{
case E_TextureChannel.R:
v.x = iv;
break;
case E_TextureChannel.G:
v.y = iv;
break;
case E_TextureChannel.B:
v.z = iv;
break;
case E_TextureChannel.A:
v.w = iv;
break;
}
return v;
}
public float GetChannelRef()
{
return Invert ? 1f : 0f;
}
}
[ExecuteInEditMode]
public class TextureChannelPacker : EditorWindow
{
public class ConstString
{
public static readonly string _Tex = "_Tex";
public static readonly string Mask = "Mask";
public static readonly string Ref = "Ref";
public static readonly string _SINGLE_CHANNEL = "_SINGLE_CHANNEL";
public static readonly string _RTex = "_RTex";
public static readonly string _GTex = "_GTex";
public static readonly string _BTex = "_BTex";
public static readonly string _ATex = "_ATex";
public static readonly string Mask_R = "Mask_R";
public static readonly string Mask_G = "Mask_G";
public static readonly string Mask_B = "Mask_B";
public static readonly string Mask_A = "Mask_A";
public static readonly string Ref_RGBA = "Ref_RGBA";
}
public class MyGUIStyles
{
public GUIStyle ToolbarButton;
public GUIStyle ToolbarButton_Disable;
public MyGUIStyles()
{
ToolbarButton = new GUIStyle(EditorStyles.toolbarButton);
ToolbarButton_Disable = new GUIStyle(EditorStyles.toolbarButton);
ToolbarButton_Disable.normal.textColor = new Color(0.5f, 0.5f, 0.5f, 0.3f);
}
}
public static TextureChannelPacker Window = null;
public List<TextureInfo> SourceTextures = new List<TextureInfo>();
public TextureInfo CanvasRT;
public ChannelInfo R { get { return Channels[0]; } }
public ChannelInfo G { get { return Channels[1]; } }
public ChannelInfo B { get { return Channels[2]; } }
public ChannelInfo A { get { return Channels[3]; } }
private ChannelInfo[] Channels = {
new ChannelInfo(E_TextureChannel.R, null),
new ChannelInfo(E_TextureChannel.G, null),
new ChannelInfo(E_TextureChannel.B, null),
new ChannelInfo(E_TextureChannel.A, null)
};
private RenderTexture[] previewRT = new RenderTexture[4];
private RenderTexture previewCanvas;
private Shader mShader = null;
private Material mMaterial = null;
private MyGUIStyles mStyles;
private string SaveName = "";
void OnEnable()
{
CanvasRT = new TextureInfo(512, 512);
mShader = Shader.Find("GEffect/TextureViewShader");
if(mShader)
{
mMaterial = new Material(mShader);
}
for(int i = 0;i<previewRT.Length;i++)
{
previewRT[i] = RenderTexture.GetTemporary(256, 256);
}
previewCanvas = RenderTexture.GetTemporary(512, 512);
}
private void OnDisable()
{
for (int i = 0; i < previewRT.Length; i++)
{
RenderTexture.ReleaseTemporary(previewRT[i]);
}
RenderTexture.ReleaseTemporary(previewCanvas);
}
[MenuItem("GEffect/TextureChannelPacker")]
static void AddWindow()
{
//if (Window != null)
// Window.Close();
Window = EditorWindow.GetWindow<TextureChannelPacker>(false, "TextureChannelPacker");
Window.minSize = new Vector2(350, 200);
Window.Show();
}
private Vector2 scroll;
private string[] ChannelNames = { "R", "G", "B", "A" };
public void OnGUI()
{
if(mStyles == null)
mStyles = new MyGUIStyles();
bool forceRefresh = false;
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.MaxWidth(2000));
{
GUILayout.Label("Open:", GUILayout.Width(50));
var texture = (Texture2D)EditorGUILayout.ObjectField(null, typeof(Texture2D), true, GUILayout.Width(150));
if (texture != null)
{
for (int i = 0; i < Channels.Length; i++)
{
Channels[i].Channel = (E_TextureChannel)i;
Channels[i].Source.Reset(texture);
}
CanvasRT.Reset(texture.width, texture.height);
SaveName = texture.name;
forceRefresh = true;
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Save as PNG", EditorStyles.toolbarButton))
{
Save(true);
}
GUILayout.Space(10);
if (GUILayout.Button("Save as JPG",EditorStyles.toolbarButton))
{
Save(false);
}
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(5);
bool needrefresh = false;
EditorGUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
for (int i = 0; i < Channels.Length; i++)
{
bool b = DrawChannelInfo(180,ChannelNames[i], Channels[i], previewRT[i],forceRefresh);
if (b)
needrefresh = true;
if(i!=Channels.Length - 1)
GUILayout.Space(20);
}
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(20);
//draw canvas button
GUI.changed = false;
EditorGUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
EditorGUILayout.BeginVertical();
{
EditorGUILayout.BeginHorizontal();
{
string s = CanvasRT.PreviewChannel[0] ? "R" : "R";
var style = CanvasRT.PreviewChannel[0] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
CanvasRT.PreviewChannel[0] = !CanvasRT.PreviewChannel[0];
}
s = CanvasRT.PreviewChannel[1] ? "G" : "G";
style = CanvasRT.PreviewChannel[1] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
CanvasRT.PreviewChannel[1] = !CanvasRT.PreviewChannel[1];
}
s = CanvasRT.PreviewChannel[2] ? "B" : "B";
style = CanvasRT.PreviewChannel[2] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
CanvasRT.PreviewChannel[2] = !CanvasRT.PreviewChannel[2];
}
s = CanvasRT.PreviewChannel[3] ? "A" : "A";
style = CanvasRT.PreviewChannel[3] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
CanvasRT.PreviewChannel[3] = !CanvasRT.PreviewChannel[3];
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
var style = R.Invert ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button("I", style, GUILayout.Width(20)))
{
R.Invert = !R.Invert;
}
style = G.Invert ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button("I", style, GUILayout.Width(20)))
{
G.Invert = !G.Invert;
}
style = B.Invert ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button("I", style, GUILayout.Width(20)))
{
B.Invert = !B.Invert;
}
style = A.Invert ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button("I", style, GUILayout.Width(20)))
{
A.Invert = !A.Invert;
}
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
GUILayout.FlexibleSpace();
EditorGUILayout.BeginVertical();
{
int width = CanvasRT.Width;
int height = CanvasRT.Height;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Width:", GUILayout.Width(50));
width = EditorGUILayout.DelayedIntField(CanvasRT.Width, GUILayout.Width(50));
GUILayout.Space(30);
EditorGUILayout.LabelField("Height:", GUILayout.Width(50));
height = EditorGUILayout.DelayedIntField(CanvasRT.Height, GUILayout.Width(50));
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
if (GUILayout.Button("128", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
width = height = 128;
}
if (GUILayout.Button("256", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
width = height = 256;
}
if (GUILayout.Button("512", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
width = height = 512;
}
if (GUILayout.Button("1024", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
width = height = 1024;
}
if (GUILayout.Button("2048", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
width = height = 2048;
}
}
EditorGUILayout.EndHorizontal();
if (width != CanvasRT.Width || height != CanvasRT.Height)
{
CanvasRT.Reset(width, height);
}
}
EditorGUILayout.EndVertical();
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
//draw canvas
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
var rect = EditorGUILayout.GetControlRect(GUILayout.MaxWidth(CanvasRT.Width), GUILayout.MaxHeight(CanvasRT.Height), GUILayout.ExpandHeight(false));
float w = rect.width;
float h = rect.height;
rect.height = Mathf.Min(rect.height, CanvasRT.Height * rect.width / CanvasRT.Width);
rect.width = Mathf.Min(rect.width, CanvasRT.Width * rect.height / CanvasRT.Height);
rect.x += (w - rect.width) * 0.5f;
rect.y += (h - rect.height) * 0.5f;
EditorGUI.DrawTextureTransparent(rect, previewCanvas);
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
if (GUI.changed || needrefresh)
{
DrawCombine();
DrawPreview(CanvasRT, previewCanvas);
}
}
private bool DrawChannelInfo(float width,string C, ChannelInfo info, RenderTexture rt, bool forceRefresh)
{
EditorGUILayout.BeginVertical(GUILayout.MaxWidth(width));
{
GUI.changed = false;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(C + ":", GUILayout.Width(30));
info.Channel = (E_TextureChannel)EditorGUILayout.EnumPopup(info.Channel, EditorStyles.toolbarDropDown, GUILayout.Width(width-33));
EditorGUILayout.EndHorizontal();
var texture = (Texture2D)EditorGUILayout.ObjectField(info.Source.Texture, typeof(Texture2D), true, GUILayout.Width(width));
if (texture != info.Source.Texture)
{
info.Source.Reset(texture);
}
var rect = EditorGUILayout.GetControlRect(GUILayout.Width(width), GUILayout.Height(width));
EditorGUI.DrawTextureTransparent(rect, rt);
EditorGUILayout.BeginHorizontal();
{
string s = info.Source.PreviewChannel[0] ? "R" : "R";
var style = info.Source.PreviewChannel[0] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
info.Source.PreviewChannel[0] = !info.Source.PreviewChannel[0];
}
s = info.Source.PreviewChannel[1] ? "G" : "G";
style = info.Source.PreviewChannel[1] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
info.Source.PreviewChannel[1] = !info.Source.PreviewChannel[1];
}
s = info.Source.PreviewChannel[2] ? "B" : "B";
style = info.Source.PreviewChannel[2] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
info.Source.PreviewChannel[2] = !info.Source.PreviewChannel[2];
}
s = info.Source.PreviewChannel[3] ? "A" : "A";
style = info.Source.PreviewChannel[3] ? mStyles.ToolbarButton : mStyles.ToolbarButton_Disable;
if (GUILayout.Button(s, style, GUILayout.Width(20)))
{
info.Source.PreviewChannel[3] = !info.Source.PreviewChannel[3];
}
}
EditorGUILayout.EndHorizontal();
if (GUI.changed || forceRefresh)
{
DrawPreview(info.Source, rt);
}
}
EditorGUILayout.EndVertical();
return GUI.changed || forceRefresh;
}
private void DrawPreview(TextureInfo info, RenderTexture rt)
{
if (rt != null && mMaterial != null)
{
mMaterial.SetTexture(ConstString._Tex, info.Texture);
var mask = info.GetChannalMask();
mMaterial.SetVector(ConstString.Mask, mask);
mMaterial.SetVector(ConstString.Ref, info.GetChannelRef());
if (Vector4.Dot( mask,Vector4.one) > 1.0f)
mMaterial.DisableKeyword(ConstString._SINGLE_CHANNEL);
else
mMaterial.EnableKeyword(ConstString._SINGLE_CHANNEL);
Graphics.Blit(null, rt, mMaterial, 1);
}
}
private void DrawCombine()
{
var rt = CanvasRT.Texture as RenderTexture;
if (rt != null && mMaterial != null)
{
mMaterial.SetTexture(ConstString._RTex, R.Source.Texture);
mMaterial.SetTexture(ConstString._GTex, G.Source.Texture);
mMaterial.SetTexture(ConstString._BTex, B.Source.Texture);
mMaterial.SetTexture(ConstString._ATex, A.Source.Texture);
mMaterial.SetVector(ConstString.Mask_R, R.GetChannalMask());
mMaterial.SetVector(ConstString.Mask_G, G.GetChannalMask());
mMaterial.SetVector(ConstString.Mask_B, B.GetChannalMask());
mMaterial.SetVector(ConstString.Mask_A, A.GetChannalMask());
Vector4 Ref = new Vector4(R.GetChannelRef(), G.GetChannelRef(), B.GetChannelRef(), A.GetChannelRef());
mMaterial.SetVector(ConstString.Ref_RGBA, Ref);
Graphics.Blit(null, rt, mMaterial, 0);
}
}
private void Save(bool isPng,string filePath = null)
{
//bool isPng = CanvasRT.PreviewChannel[3];
if (string.IsNullOrEmpty(filePath))
{
string ext = isPng ? "png" : "jpg";
filePath = EditorUtility.SaveFilePanel("Save localization data file", Application.streamingAssetsPath, SaveName, ext);
}
if (string.IsNullOrEmpty(filePath))
{
return;
}
int id = filePath.LastIndexOf("/");
if(id!=-1)
SaveName = filePath.Substring(id+1);
id = SaveName.LastIndexOf(".");
if (id != -1)
SaveName = SaveName.Substring(0, id);
var rt = CanvasRT.Texture as RenderTexture;
if (rt == null)
return;
RenderTexture prev = RenderTexture.active;
RenderTexture.active = rt;
Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
byte[] bytes;
if (isPng)
bytes = png.EncodeToPNG();
else
bytes = png.EncodeToJPG(100);
FileStream file = File.Open(filePath, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(png);
png = null;
RenderTexture.active = prev;
AssetDatabase.Refresh();
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/MeshConverter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Text;
namespace UnityEditor
{
public class MeshConverter : EditorWindow, ISerializationCallbackReceiver
{
class Styles
{
// public GUIContent m_WarningContent = new GUIContent(string.Empty, EditorGUIUtility.LoadRequired("Builtin Skins/Icons/console.warnicon.sml.png") as Texture2D);
public GUIStyle mPreviewBox = new GUIStyle("OL Box");
public GUIStyle mPreviewTitle = new GUIStyle("OL Title");
public GUIStyle mPreviewTitle1 = new GUIStyle("OL Box");
public GUIStyle mLoweredBox = new GUIStyle("TextField");
public GUIStyle mHelpBox = new GUIStyle("helpbox");
public GUIStyle mMiniLable = new GUIStyle("MiniLabel");
public GUIStyle mSelected = new GUIStyle("LODSliderRangeSelected");
public GUIStyle mOLTitle = new GUIStyle("OL Title");
public GUIStyle mHLine = new GUIStyle();
public GUIStyle mVLine = new GUIStyle();
public Styles()
{
mLoweredBox.padding = new RectOffset(1, 1, 1, 1);
mPreviewTitle1.fixedHeight = 0;
mPreviewTitle1.fontStyle = FontStyle.Bold;
mPreviewTitle1.alignment = TextAnchor.MiddleLeft;
mHLine.fixedHeight = 1f;
mHLine.margin = new RectOffset(0, 0, 0, 0);
mVLine.fixedWidth = 1f;
mVLine.stretchHeight = true;
mVLine.stretchWidth = false;
}
}
public static MeshConverter Window = null;
public static MeshViewer MeshViewerWindow = null;
public static RipImporter RipImporterWindow = null;
public Dictionary<string, MeshData> MeshMap = new Dictionary<string, MeshData>();
public Dictionary<string, ConvertStrategy> StrategyMap = new Dictionary<string, ConvertStrategy>();
public Dictionary<string, MeshPostConvert> PostConvertMap = new Dictionary<string, MeshPostConvert>();
public Dictionary<string, string> MeshPathMap = new Dictionary<string, string>();
string GetConfigFilePath()
{
string path = Application.dataPath;
int id = path.LastIndexOf("/");
if (id != -1)
{
path = path.Substring(0, id);
}
return path + "/ProjectSettings/MeshConverter.cfg";
}
private static Styles mStyles;
private ObjSerializer mObjReader = new ObjSerializer();
private RipSerializer mRipReader = new RipSerializer();
private string mOpenMeshPath = "";
private string mSaveMeshPath = "";
private string mNewMeshName = "";
private string newStrategyName = "NewStrategyName";
private List<string> MeshNames = new List<string>();
private List<string> PostConvertNames = new List<string>();
private Vector2 mMeshListScroll = new Vector2();
private Vector2 mStrategyListScroll = new Vector2();
[MenuItem("GEffect/MeshConverter")]
static void AddWindow()
{
if (Window != null)
Window.Close();
Window = EditorWindow.GetWindow<MeshConverter>(false, "MeshEditor");
Window.minSize = new Vector2(200, 200);
Window.Show();
}
public void ViewMeshData(MeshData mesh)
{
MeshViewerWindow = EditorWindow.GetWindow<MeshViewer>(false, "Mesh Viewer");
MeshViewerWindow.titleContent = new GUIContent(mesh.Name);
MeshViewerWindow.minSize = new Vector2(450, 400);
MeshViewerWindow.mMeshData = mesh;
MeshViewerWindow.Show();
}
private void AddMeshData(string name, MeshData mesh,string filePath = null)
{
MeshMap[name] = mesh;
string oldpath;
MeshPathMap.TryGetValue(name, out oldpath);
if(oldpath!=filePath)
MeshPathMap[name] = filePath;
RefreshMeshNameList();
}
private void RemoveMeshData(string key)
{
MeshPathMap.Remove(key);
MeshMap.Remove(key);
RefreshMeshNameList();
}
private void RefreshMeshNameList()
{
MeshNames.Clear();
MeshNames.AddRange(MeshPathMap.Keys);
}
private void LoadConfigDataFromFile(string filePath = null)
{
if (string.IsNullOrEmpty(filePath))
{
filePath = EditorUtility.OpenFilePanel("Select localization data file", Application.streamingAssetsPath, "json");
}
if (File.Exists(filePath))
{
string dataAsJson = File.ReadAllText(filePath);
InitByConfigData(dataAsJson);
}
}
private void InitByConfigData(string str)
{
if (string.IsNullOrEmpty(str))
return;
var serConfigMap = JsonUtility.FromJson<SerializationMap<string, string>>(str);
var configMap = serConfigMap.target;
string jsonStr;
if(configMap.TryGetValue("StrategyMap",out jsonStr))
{
var serStrategyMap = JsonUtility.FromJson<SerializationMap<string, ConvertStrategy>>(jsonStr);
foreach (var pair in serStrategyMap.target)
{
StrategyMap[pair.Key] = pair.Value;
}
}
if (configMap.TryGetValue("MeshPathMap", out jsonStr))
{
var serMeshPathMap = JsonUtility.FromJson<SerializationMap<string, string>>(jsonStr);
MeshPathMap = serMeshPathMap.target;
RefreshMeshNameList();
}
}
private string ToConfigData()
{
Dictionary<string, string> ConfigMap = new Dictionary<string, string>();
SerializationMap<string, ConvertStrategy> serStrategyMap = new SerializationMap<string, ConvertStrategy>(StrategyMap);
string StrategyMapStr = JsonUtility.ToJson(serStrategyMap);
ConfigMap["StrategyMap"] = StrategyMapStr;
SerializationMap<string, string> serMeshPathMap = new SerializationMap<string, string>(MeshPathMap);
string MeshPathMapStr = JsonUtility.ToJson(serMeshPathMap);
ConfigMap["MeshPathMap"] = MeshPathMapStr;
SerializationMap<string, string> serConfigMap = new SerializationMap<string, string>(ConfigMap);
string dataAsJson =JsonUtility.ToJson(serConfigMap);
return dataAsJson;
}
private void SaveConfigDataToFile(string filePath = null)
{
if (string.IsNullOrEmpty(filePath))
{
filePath = EditorUtility.SaveFilePanel("Save localization data file", Application.streamingAssetsPath, "", "json");
}
if (!string.IsNullOrEmpty(filePath))
{
string dataAsJson = ToConfigData();
File.WriteAllText(filePath, dataAsJson);
}
}
private void LoadMesh(string path)
{
if (File.Exists(path))
{
var mesh = mObjReader.Load(path);
if (mesh != null && mesh.IsValid())
{
AddMeshData(mesh.Name, mesh, path);
}
}
}
private void LoadRipFile(string path) {
if (File.Exists(path)) {
var rip = mRipReader.Load(path);
if(null != rip) {
RipImporterWindow = EditorWindow.GetWindow<RipImporter>(false, "Rip Importer");
RipImporterWindow.titleContent = new GUIContent(rip.meshName);
RipImporterWindow.minSize = new Vector2(450, 400);
RipImporterWindow.mRipData = rip;
RipImporterWindow.onMeshDataPrepared += (MeshData mesh) => {
AddMeshData(mesh.Name, mesh, path);
};
RipImporterWindow.Show();
}
}
}
private void OnGUI()
{
if (mStyles == null)
{
mStyles = new Styles();
}
//toolbar
EditorGUILayout.BeginHorizontal(mStyles.mPreviewBox, GUILayout.Height(22));
{
if (GUILayout.Button("加载obj文件", GUILayout.Width(80)))
{
string path = EditorUtility.OpenFilePanel("select obj file", mOpenMeshPath, "obj");
if (!string.IsNullOrEmpty(path))
{
int id = path.LastIndexOf("/");
mOpenMeshPath = path.Substring(0, id + 1);
LoadMesh(path);
}
}
if (GUILayout.Button("加载rip文件", GUILayout.Width(80))) {
string path = EditorUtility.OpenFilePanel("select rip file", mOpenMeshPath, "rip");
if (!string.IsNullOrEmpty(path)) {
int id = path.LastIndexOf("/");
mOpenMeshPath = path.Substring(0, id + 1);
LoadRipFile(path);
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("策略另存为"))
{
SaveConfigDataToFile();
}
GUILayout.Space(30);
if (GUILayout.Button("打开策略"))
{
LoadConfigDataFromFile();
}
GUILayout.Space(30);
newStrategyName = EditorGUILayout.TextField(newStrategyName, GUILayout.Width(100));
GUILayout.Space(5);
if (GUILayout.Button("新建策略", GUILayout.Width(80)))
{
if (!StrategyMap.ContainsKey(newStrategyName))
{
var strategy = new ConvertStrategy();
strategy.BufferInfos.Add(ESemantic.Position, new ConvertStrategy.BufferDataInfo(ESemantic.Position));
strategy.BufferInfos.Add(ESemantic.Normal, new ConvertStrategy.BufferDataInfo(ESemantic.Normal));
strategy.BufferInfos.Add(ESemantic.Coord0, new ConvertStrategy.BufferDataInfo(ESemantic.Coord0));
StrategyMap.Add(newStrategyName, strategy);
}
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(1);
//draw mesh list
EditorGUILayout.BeginVertical(mStyles.mPreviewBox, GUILayout.Width(155));
{
GUILayout.Space(2);
mMeshListScroll = EditorGUILayout.BeginScrollView(mMeshListScroll);
foreach (var p in MeshPathMap)
{
if (string.IsNullOrEmpty(p.Value) && !MeshMap.ContainsKey(p.Key))
{
RemoveMeshData(p.Key);
break;
}
EditorGUILayout.BeginHorizontal();
GUILayout.Space(2);
if (GUILayout.Button(p.Key, EditorStyles.toolbarButton, GUILayout.Width(120)))
{
MeshData mesh;
if(!MeshMap.TryGetValue(p.Key,out mesh))
{
LoadMesh(p.Value);
if(!MeshMap.TryGetValue(p.Key, out mesh))
{
Debug.LogWarning("无法打开文件:" + p.Value);
RemoveMeshData(p.Key);
break;
}
}
ViewMeshData(mesh);
}
if(GUILayout.Button("R",EditorStyles.toolbarButton,GUILayout.Width(30)))
{
RemoveMeshData(p.Key);
break;
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndVertical();
GUILayout.Space(0);
//draw strategy list
EditorGUILayout.BeginVertical();
{
mStrategyListScroll = EditorGUILayout.BeginScrollView(mStrategyListScroll);
foreach (var strategy in StrategyMap)
{
if (!DrawStrategy(strategy.Key, strategy.Value))
break;
}
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
}
private bool DrawStrategy(string name, ConvertStrategy strategy)
{
EditorGUILayout.BeginVertical(mStyles.mPreviewBox);
{
EditorGUILayout.BeginHorizontal(GUILayout.Height(25));
{
string newname = EditorGUILayout.DelayedTextField(name, EditorStyles.boldLabel, GUILayout.Width(200));
if(newname!=name)
{
if(!StrategyMap.ContainsKey(newname))
{
StrategyMap[newname] = strategy;
StrategyMap.Remove(name);
return false;
}
}
if(GUILayout.Button("删除策略",GUILayout.Width(80)))
{
StrategyMap.Remove(name);
return false;
}
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(2);
//draw slots
EditorGUILayout.BeginHorizontal();
{
DrawSlot(ref strategy.SlotA, "SlotA:");
GUILayout.Space(10);
DrawSlot(ref strategy.SlotB, "SlotB:");
GUILayout.Space(10);
DrawSlot(ref strategy.SlotC, "SlotC:");
GUILayout.Space(10);
DrawSlot(ref strategy.SlotD, "SlotD:");
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(10);
//draw buffer info
foreach (var p in strategy.BufferInfos)
{
if(!DrawBufferInfo(p.Key, p.Value))
{
strategy.BufferInfos.Remove(p.Key);
break;
}
GUILayout.Space(5);
}
GUILayout.Space(10);
//draw strategy function buttons
EditorGUILayout.BeginHorizontal(GUILayout.Height(25));
{
GUILayout.Label("添加buffer:", GUILayout.Width(80));
var s = (ESemantic)EditorGUILayout.EnumPopup(ESemantic.UnKnown, GUILayout.Width(80));
if (s != ESemantic.UnKnown)
{
if (!strategy.BufferInfos.ContainsKey(s))
{
strategy.BufferInfos.Add(s, new ConvertStrategy.BufferDataInfo(s));
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("检查", GUILayout.Width(50)))
{
int id = strategy.CheckValid();
Debug.Log(strategy.GetValidInfo(id));
}
if (GUILayout.Button("生成", GUILayout.Width(50)))
{
string path = EditorUtility.SaveFilePanel("save mesh file", mSaveMeshPath, mNewMeshName, "fbx");
if (!string.IsNullOrEmpty(path))
{
int id = path.LastIndexOf("/");
mNewMeshName = path.Substring(id + 1);
mSaveMeshPath = path.Substring(0, id + 1);
var newMesh = strategy.Convert(mNewMeshName);
if (newMesh != null)
{
MeshPostConvert postConvert;
if (PostConvertMap.TryGetValue(strategy.PostConvert, out postConvert))
{
if (postConvert != null)
postConvert.PostConvert(ref newMesh);
}
AddMeshData(newMesh.Name, newMesh);
FbxSerializer.WriteMeshFBX(newMesh, path);
}
}
}
GUILayout.Space(10);
}
EditorGUILayout.EndHorizontal();
DrawPostConvert(strategy);
}
EditorGUILayout.EndVertical();
// GUILayout.Space(5);
return true;
}
private void DrawPostConvert(ConvertStrategy strategy)
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label("Post Convert:", GUILayout.Width(90));
int id = PostConvertNames.IndexOf(strategy.PostConvert);
if (id <= 0)
id = 0;
int newid = EditorGUILayout.Popup(id, PostConvertNames.ToArray(), GUILayout.Width(70));
if (newid != id)
{
strategy.PostConvert = PostConvertNames[newid];
}
}
EditorGUILayout.EndHorizontal();
MeshPostConvert postConvert;
if (PostConvertMap.TryGetValue(strategy.PostConvert, out postConvert))
{
if (postConvert != null)
{
postConvert.OnGUI();
}
}
}
private void DrawSlot(ref MeshData slot, string slotlabel)
{
int id = -1;
if (slot != null)
{
id = MeshNames.IndexOf(slot.Name);
GUILayout.Label(slotlabel, EditorStyles.boldLabel, GUILayout.Width(50));
}
else
{
GUILayout.Label(slotlabel, GUILayout.Width(50));
}
int newid = EditorGUILayout.Popup(id, MeshNames.ToArray());
if (newid != id)
{
string n = MeshNames[newid];
if(!MeshMap.ContainsKey(n) && MeshPathMap.ContainsKey(n))
{
LoadMesh(MeshPathMap[n]);
}
slot = MeshMap[n];
}
}
private bool DrawBufferInfo(ESemantic s, ConvertStrategy.BufferDataInfo info)
{
EditorGUILayout.BeginHorizontal();
{
if(GUILayout.Button("R",EditorStyles.toolbarButton,GUILayout.Width(30)))
{
return false;
}
var slot = (ConvertStrategy.ESlot)EditorGUILayout.EnumPopup(ConvertStrategy.ESlot.None, GUILayout.Width(80));
if (slot != ConvertStrategy.ESlot.None)
{
info.X.Slot = slot;
info.Y.Slot = slot;
if ((int)s < (int)ESemantic.Coord0)
info.Z.Slot = slot;
if (s == ESemantic.Color)
info.W.Slot = slot;
}
var semantic = (ESemantic)EditorGUILayout.EnumPopup(ESemantic.UnKnown, GUILayout.Width(80));
if (semantic != ESemantic.UnKnown)
{
info.X.Semantic = semantic;
info.Y.Semantic = semantic;
info.Z.Semantic = semantic;
info.W.Semantic = semantic;
}
bool used = info.X.IsValid();
if (!used)
GUILayout.Label(s.ToString() + ":", GUILayout.Width(80));
else
GUILayout.Label(s.ToString() + ":", EditorStyles.boldLabel, GUILayout.Width(80));
DrawPassDataInfo(info.X, "X", used);
GUILayout.Space(20);
used &= info.Y.IsValid();
DrawPassDataInfo(info.Y, "Y", used);
GUILayout.Space(20);
used &= info.Z.IsValid();
DrawPassDataInfo(info.Z, "Z", used);
GUILayout.Space(20);
used &= info.W.IsValid();
DrawPassDataInfo(info.W, "W", used);
}
EditorGUILayout.EndHorizontal();
return true;
}
private void DrawPassDataInfo(ConvertStrategy.PassDataInfo pass, string label, bool used = true)
{
if (used)
GUILayout.Label(label, EditorStyles.boldLabel, GUILayout.Width(15));
else
GUILayout.Label(label, GUILayout.Width(15));
pass.Slot = (ConvertStrategy.ESlot)EditorGUILayout.EnumPopup(pass.Slot, EditorStyles.toolbarPopup, GUILayout.Width(50));
if (pass.Slot != ConvertStrategy.ESlot.None)
{
pass.Semantic = (ESemantic)EditorGUILayout.EnumPopup(pass.Semantic, EditorStyles.toolbarPopup, GUILayout.Width(70));
pass.Pass = (ConvertStrategy.EPass)EditorGUILayout.EnumPopup(pass.Pass, EditorStyles.toolbarPopup, GUILayout.Width(30));
}
else
{
GUILayout.Space(100);
}
}
public void OnBeforeSerialize()
{
SaveConfigDataToFile(GetConfigFilePath());
}
public void OnAfterDeserialize()
{
//内容转至OnEnable
}
private void OnEnable()
{
LoadConfigDataFromFile(GetConfigFilePath());
PostConvertMap.Clear();
PostConvertMap.Add("Nothing", null);
PostConvertMap.Add("HSMYJ", new MeshPostConvert_HSMYJ());
PostConvertMap.Add("Idol", new MeshPostConvert_Idol());
PostConvertMap.Add("BD", new MeshPostConvert_BD());
PostConvertNames.Clear();
PostConvertNames.AddRange(PostConvertMap.Keys);
}
private void OnDestroy()
{
SaveConfigDataToFile(GetConfigFilePath());
}
}
}<file_sep>/Assets/Common/MeshConverter/Editor/RipSerializer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Text;
namespace UnityEngine {
public class RipAttributeElement {
public string name;
public uint bytesOffset;
public uint dimension;
//设置的语意
public ESemantic sematic;
}
public class RipData {
public string meshName;
//顶点数据列表
public float[] vertexData;
//索引数据列表
public uint[] indexData;
//单个顶点数据大小
public uint vertexBytesSize;
//顶点数量
public uint vertexCount;
//索引数量
public uint indexCount;
//单个顶点属性种类
public uint attributeCountPerVertex;
//顶点属性
public RipAttributeElement[] elements;
//单个顶点元素数量
public uint dimensionPerVertex;
public string[] textureFiles;
public string[] shaderFiles;
public string GetInfo() {
StringBuilder sb = new StringBuilder();
sb.Append(meshName + "\n");
sb.AppendFormat("Vertex Count:{0}\n",vertexCount);
sb.AppendFormat("Tringle Count:{0}\n", indexCount / 3);
sb.AppendFormat("Attribute Count:{0}\n", attributeCountPerVertex);
sb.AppendFormat("Elements Count:{0}\n", dimensionPerVertex);
sb.Append("\nTexture Files:\n\n");
for(int i = 0; i < textureFiles.Length; ++i) {
sb.Append(textureFiles[i] + "\n");
}
sb.Append("\nShader Files:\n");
for (int i = 0; i < shaderFiles.Length; ++i) {
sb.Append(shaderFiles[i] + "\n");
}
return sb.ToString();
}
}
public class RipSerializer {
private const uint RipFileVersion = 4;
public RipData Load(string path) {
BinaryReader reader = null;
RipData ripData = null;
try {
if (string.IsNullOrEmpty(path))
return null;
reader = new BinaryReader(File.Open(path, FileMode.Open));
} catch (Exception e) {
if (null != reader) reader.Close();
Debug.LogError("打开文件失败:" + path + "\n" + e.Message);
return null;
}
int id = path.LastIndexOf("/");
string name = path.Substring(id + 1);
reader.ReadUInt32(); //signature
uint version = reader.ReadUInt32();
if (version == RipFileVersion) {
uint dwFacesCnt = reader.ReadUInt32();
uint dwVertexesCnt = reader.ReadUInt32();
uint vertexSize = reader.ReadUInt32();
uint textureFilesCnt = reader.ReadUInt32();
uint shaderFilesCnt = reader.ReadUInt32();
uint vertexAttributesCnt = reader.ReadUInt32();
List<uint> vertexAttribTypesArray = new List<uint>();
List<string> textureFiles = new List<string>();
List<string> shaderFiles = new List<string>();
//attributes
List<float> vertexArray = new List<float>();
List<uint> faceArray = new List<uint>();
List<RipAttributeElement> elements = new List<RipAttributeElement>();
for (int i = 0; i < vertexAttributesCnt; ++i) {
RipAttributeElement elem = new RipAttributeElement();
string semantic = ReadStr(reader);
uint semanticIndex = reader.ReadUInt32();
uint offset = reader.ReadUInt32();
uint size = reader.ReadUInt32();
uint typeMapElements = reader.ReadUInt32();
for (int j = 0; j < typeMapElements; ++j) {
uint typeElement = reader.ReadUInt32();
vertexAttribTypesArray.Add(typeElement);
}
elem.name = semantic + semanticIndex;
elem.bytesOffset = offset;
elem.dimension = size / 4;
elem.sematic = ESemantic.UnKnown;
elements.Add(elem);
}
//read textures
for (int i = 0; i < textureFilesCnt; ++i) {
textureFiles.Add(ReadStr(reader));
}
//read Shaders
for (int i = 0; i < shaderFilesCnt; ++i) {
shaderFiles.Add(ReadStr(reader));
}
//read indices
for (int i = 0; i < dwFacesCnt; ++i) {
faceArray.Add(reader.ReadUInt32());
faceArray.Add(reader.ReadUInt32());
faceArray.Add(reader.ReadUInt32());
}
//read vertexes
for (int i = 0; i < dwVertexesCnt; ++i) {
for (int j = 0; j < vertexAttribTypesArray.Count; ++j) {
uint elementType = vertexAttribTypesArray[j];
float z = 0.0f;
if (elementType == 0) { //float
z = reader.ReadSingle();
} else if (elementType == 1) { //uint
z = reader.ReadUInt32();
} else if (elementType == 2) { //int
z = reader.ReadInt32();
} else {
z = reader.ReadUInt32();
}
vertexArray.Add(Convert.ToSingle(z));
}
}
//构造rip文件
ripData = new RipData();
ripData.meshName = path.Substring(path.LastIndexOf("/") + 1);
ripData.vertexData = vertexArray.ToArray();
ripData.indexData = faceArray.ToArray();
ripData.vertexBytesSize = vertexSize;
ripData.vertexCount = dwVertexesCnt;
ripData.indexCount = dwFacesCnt * 3;
ripData.attributeCountPerVertex = vertexAttributesCnt;
ripData.dimensionPerVertex = Convert.ToUInt32(vertexAttribTypesArray.Count);
ripData.elements = elements.ToArray();
ripData.textureFiles = textureFiles.ToArray();
ripData.shaderFiles = shaderFiles.ToArray();
} else {
Debug.LogError("Rip文件:" + name + "版本错误");
}
return ripData;
}
private string ReadStr(BinaryReader br) {
string result = "";
while (true) {
int str = br.ReadByte();
if (str == 0) break;
result += Convert.ToChar(str);
}
return result;
}
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/MeshPostConvert.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
namespace UnityEditor
{
public class MeshPostConvert
{
public virtual void PostConvert(ref MeshData mesh)
{
}
public virtual void OnGUI()
{
}
}
public class MeshPostConvert_Idol : MeshPostConvert
{
public override void PostConvert(ref MeshData mesh)
{
MeshData.VBuffer normalBuf;
MeshData.VBuffer tangentBuf;
bool hasNormal = mesh.Buffers.TryGetValue(ESemantic.Normal, out normalBuf);
bool hasTangent = mesh.Buffers.TryGetValue(ESemantic.Tangent, out tangentBuf);
if(hasNormal && hasTangent)
{
int num = mesh.GetVertexCount();
int n = 0;
for (int i = 0; i < num; i++)
{
var oldN = normalBuf.mData[i];
var oldT = tangentBuf.mData[i];
var l = oldN - oldT;
if(l.SqrMagnitude()>0.0001)
{
n++;
}
}
Debug.Log("num of diff between normal and tangent:" + n + " / " + num);
}
}
}
public class MeshPostConvert_HSMYJ : MeshPostConvert
{
private string mSkeletonDataFileName = "";
private bool mUseSkeleton = false;
private List<Vector4> mSkeletonData = new List<Vector4>();
public override void PostConvert(ref MeshData mesh)
{
MeshData.VBuffer buff;
if(mesh.Buffers.TryGetValue(ESemantic.Normal,out buff))
{
var normals = buff.mData;
for(int i = 0;i< normals.Count;i++)
{
var normal = normals[i];
normals[i] = normal * 2 - new Vector4(1,1,1,0);
}
}
int num = mesh.Trangles.Count / 3;
for(int i = 0;i<num;i++)
{
int cache =mesh.Trangles[i * 3 + 1];
mesh.Trangles[i * 3 + 1] = mesh.Trangles[i * 3 + 2];
mesh.Trangles[i * 3 + 2] = cache;
}
if(mUseSkeleton)
UseSkeletonData(ref mesh);
}
public override void OnGUI()
{
base.OnGUI();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Skeleton Data:", GUILayout.Width(100));
mUseSkeleton = EditorGUILayout.Toggle(mUseSkeleton);
if (mUseSkeleton)
{
if (GUILayout.Button(mSkeletonDataFileName, EditorStyles.textField, GUILayout.Width(500)))
{
int id = mSkeletonDataFileName.LastIndexOf("/");
string path = mSkeletonDataFileName.Substring(0, id + 1);
path = EditorUtility.OpenFilePanel("select Skeleton Data file", path, "*");
if (!string.IsNullOrEmpty(path))
{
mSkeletonDataFileName = path;
}
LoadSkeletonData();
}
}
EditorGUILayout.LabelField(mSkeletonData.Count.ToString(), GUILayout.Width(50));
}
EditorGUILayout.EndHorizontal();
}
private void LoadSkeletonData()
{
mSkeletonData.Clear();
StreamReader reader = null;
try
{
if (string.IsNullOrEmpty(mSkeletonDataFileName))
return;
reader = File.OpenText(mSkeletonDataFileName);
}
catch (Exception e)
{
reader.Close();
Debug.LogError("打开文件失败:" + mSkeletonDataFileName + "\n" + e.Message);
return;
}
string line = reader.ReadLine();
char[] splits = { ' ', '\t' };
while (line != null)
{
string[] elements = line.Split(splits);
if (elements.Length == 4)
{
Vector4 v = new Vector4();
for (int i = 0; i < 4; i++)
{
v[i] = float.Parse(elements[i]);
}
mSkeletonData.Add(v);
}
line = reader.ReadLine();
}
reader.Close();
}
private bool UseSkeletonData(ref MeshData mesh)
{
MeshData.VBuffer posBuf;
MeshData.VBuffer normalBuf;
MeshData.VBuffer tangentBuf;
MeshData.VBuffer bnormalBuf;
MeshData.VBuffer idBuf;
MeshData.VBuffer weightBuf;
if (!mesh.Buffers.TryGetValue(ESemantic.Position, out posBuf))
return false;
if (!mesh.Buffers.TryGetValue(ESemantic.Coord1, out idBuf))
return false;
if (!mesh.Buffers.TryGetValue(ESemantic.Coord2, out weightBuf))
return false;
bool hasNormal = mesh.Buffers.TryGetValue(ESemantic.Normal, out normalBuf);
bool hasBnormal = mesh.Buffers.TryGetValue(ESemantic.BNormal, out bnormalBuf);
bool hasTangent = mesh.Buffers.TryGetValue(ESemantic.Tangent, out tangentBuf);
int num = mesh.GetVertexCount();
for(int i = 0;i<num;i++)
{
Vector4 pos = posBuf.mData[i];
Vector4 fid = idBuf.mData[i];
int[] id = { Mathf.RoundToInt(fid.x), Mathf.RoundToInt(fid.y), Mathf.RoundToInt(fid.z), Mathf.RoundToInt(fid.w) };
Vector4 wight = weightBuf.mData[i];
var m0 = wight.x * mSkeletonData[id[0] * 3]+ wight.y * mSkeletonData[id[1] * 3]
+ wight.z * mSkeletonData[id[2] * 3]+ wight.w * mSkeletonData[id[3] * 3];
var m1 = wight.x * mSkeletonData[id[0] * 3 + 1] + wight.y * mSkeletonData[id[1] * 3 + 1]
+ wight.z * mSkeletonData[id[2] * 3 + 1] + wight.w * mSkeletonData[id[3] * 3 + 1];
var m2 = wight.x * mSkeletonData[id[0] * 3 + 2] + wight.y * mSkeletonData[id[1] * 3 + 2]
+ wight.z * mSkeletonData[id[2] * 3 + 2] + wight.w * mSkeletonData[id[3] * 3 + 2];
Vector4 newpos = Vector4.one;
newpos.x = pos.x * m0.x + pos.y * m0.y + pos.z * m0.z + m0.w;
newpos.y = pos.x * m1.x + pos.y * m1.y + pos.z * m1.z + m1.w;
newpos.z = pos.x * m2.x + pos.y * m2.y + pos.z * m2.z + m2.w;
posBuf.mData[i] = newpos;
Vector4 oldV;
Vector4 newV;
if(hasNormal)
{
oldV = normalBuf.mData[i];
newV = Vector4.zero;
newV.x = oldV.x * m0.x + oldV.y * m0.y + oldV.z * m0.z + m0.w;
newV.y = oldV.x * m1.x + oldV.y * m1.y + oldV.z * m1.z + m1.w;
newV.z = oldV.x * m2.x + oldV.y * m2.y + oldV.z * m2.z + m2.w;
normalBuf.mData[i] = newV;
}
if (hasTangent)
{
oldV = tangentBuf.mData[i];
newV = Vector4.zero;
newV.x = oldV.x * m0.x + oldV.y * m0.y + oldV.z * m0.z + m0.w;
newV.y = oldV.x * m1.x + oldV.y * m1.y + oldV.z * m1.z + m1.w;
newV.z = oldV.x * m2.x + oldV.y * m2.y + oldV.z * m2.z + m2.w;
tangentBuf.mData[i] = newV;
}
if (hasBnormal)
{
oldV = bnormalBuf.mData[i];
newV = Vector4.zero;
newV.x = oldV.x * m0.x + oldV.y * m0.y + oldV.z * m0.z + m0.w;
newV.y = oldV.x * m1.x + oldV.y * m1.y + oldV.z * m1.z + m1.w;
newV.z = oldV.x * m2.x + oldV.y * m2.y + oldV.z * m2.z + m2.w;
bnormalBuf.mData[i] = newV;
}
}
mesh.Buffers.Remove(ESemantic.Coord1);
mesh.Buffers.Remove(ESemantic.Coord2);
return true;
}
}
}<file_sep>/Assets/Common/MeshConverter/Editor/FbxSerializer.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
public class FbxSerializer : MonoBehaviour {
public static void WriteMeshFBX(MeshData mesh, string path)
{
var timestamp = DateTime.Now;
using (StreamWriter FBXwriter = new StreamWriter(path))
{
StringBuilder fbx = new StringBuilder();
StringBuilder ob = new StringBuilder(); //Objects builder
StringBuilder cb = new StringBuilder(); //Connections builder
StringBuilder cb2 = new StringBuilder(); //and keep connections ordered
cb.Append("\n}\n");//Objects end
cb.Append("\nConnections: {");
//write connections here and Mesh objects separately without having to backtrack through their MEshFilter to het the GameObject ID
//also note that MeshFilters are not unique, they cannot be used for instancing geometry
cb2.AppendFormat("\n\n\t;Geometry::, Model::{0}", mesh.Name);
cb2.AppendFormat("\n\tC: \"OO\",3{0},1{1}", 2, 1);
#region write generic FBX data after everything was collected
fbx.Append("; FBX 7.1.0 project file");
fbx.Append("\nFBXHeaderExtension: {\n\tFBXHeaderVersion: 1003\n\tFBXVersion: 7100\n\tCreationTimeStamp: {\n\t\tVersion: 1000");
fbx.Append("\n\t\tYear: " + timestamp.Year);
fbx.Append("\n\t\tMonth: " + timestamp.Month);
fbx.Append("\n\t\tDay: " + timestamp.Day);
fbx.Append("\n\t\tHour: " + timestamp.Hour);
fbx.Append("\n\t\tMinute: " + timestamp.Minute);
fbx.Append("\n\t\tSecond: " + timestamp.Second);
fbx.Append("\n\t\tMillisecond: " + timestamp.Millisecond);
fbx.Append("\n\t}\n\tCreator: \"Unity Studio by Chipicao\"\n}\n");
fbx.Append("\nGlobalSettings: {");
fbx.Append("\n\tVersion: 1000");
fbx.Append("\n\tProperties70: {");
fbx.Append("\n\t\tP: \"UpAxis\", \"int\", \"Integer\", \"\",1");
fbx.Append("\n\t\tP: \"UpAxisSign\", \"int\", \"Integer\", \"\",1");
fbx.Append("\n\t\tP: \"FrontAxis\", \"int\", \"Integer\", \"\",2");
fbx.Append("\n\t\tP: \"FrontAxisSign\", \"int\", \"Integer\", \"\",1");
fbx.Append("\n\t\tP: \"CoordAxis\", \"int\", \"Integer\", \"\",0");
fbx.Append("\n\t\tP: \"CoordAxisSign\", \"int\", \"Integer\", \"\",1");
fbx.Append("\n\t\tP: \"OriginalUpAxis\", \"int\", \"Integer\", \"\",1");
fbx.Append("\n\t\tP: \"OriginalUpAxisSign\", \"int\", \"Integer\", \"\",1");
fbx.AppendFormat("\n\t\tP: \"UnitScaleFactor\", \"double\", \"Number\", \"\",{0}", 1);
fbx.Append("\n\t\tP: \"OriginalUnitScaleFactor\", \"double\", \"Number\", \"\",1.0");
//fbx.Append("\n\t\tP: \"AmbientColor\", \"ColorRGB\", \"Color\", \"\",0,0,0");
//fbx.Append("\n\t\tP: \"DefaultCamera\", \"KString\", \"\", \"\", \"Producer Perspective\"");
//fbx.Append("\n\t\tP: \"TimeMode\", \"enum\", \"\", \"\",6");
//fbx.Append("\n\t\tP: \"TimeProtocol\", \"enum\", \"\", \"\",2");
//fbx.Append("\n\t\tP: \"SnapOnFrameMode\", \"enum\", \"\", \"\",0");
//fbx.Append("\n\t\tP: \"TimeSpanStart\", \"KTime\", \"Time\", \"\",0");
//fbx.Append("\n\t\tP: \"TimeSpanStop\", \"KTime\", \"Time\", \"\",153953860000");
//fbx.Append("\n\t\tP: \"CustomFrameRate\", \"double\", \"Number\", \"\",-1");
//fbx.Append("\n\t\tP: \"TimeMarker\", \"Compound\", \"\", \"\"");
//fbx.Append("\n\t\tP: \"CurrentTimeMarker\", \"int\", \"Integer\", \"\",-1");
fbx.Append("\n\t}\n}\n");
fbx.Append("\nDocuments: {");
fbx.Append("\n\tCount: 1");
fbx.Append("\n\tDocument: 1234567890, \"\", \"Scene\" {");
fbx.Append("\n\t\tProperties70: {");
fbx.Append("\n\t\t\tP: \"SourceObject\", \"object\", \"\", \"\"");
fbx.Append("\n\t\t\tP: \"ActiveAnimStackName\", \"KString\", \"\", \"\", \"\"");
fbx.Append("\n\t\t}");
fbx.Append("\n\t\tRootNode: 0");
fbx.Append("\n\t}\n}\n");
fbx.Append("\nReferences: {\n}\n");
fbx.Append("\nDefinitions: {");
fbx.Append("\n\tVersion: 100");
fbx.AppendFormat("\n\tCount: {0}", 2);
fbx.Append("\n\tObjectType: \"GlobalSettings\" {");
fbx.Append("\n\t\tCount: 1");
fbx.Append("\n\t}");
fbx.Append("\n\tObjectType: \"Model\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 1);
fbx.Append("\n\t}");
fbx.Append("\n\tObjectType: \"NodeAttribute\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 0);
fbx.Append("\n\t\tPropertyTemplate: \"FbxNull\" {");
fbx.Append("\n\t\t\tProperties70: {");
fbx.Append("\n\t\t\t\tP: \"Color\", \"ColorRGB\", \"Color\", \"\",0.8,0.8,0.8");
fbx.Append("\n\t\t\t\tP: \"Size\", \"double\", \"Number\", \"\",100");
fbx.Append("\n\t\t\t\tP: \"Look\", \"enum\", \"\", \"\",1");
fbx.Append("\n\t\t\t}\n\t\t}\n\t}");
fbx.Append("\n\tObjectType: \"Geometry\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 1);
fbx.Append("\n\t}");
fbx.Append("\n\tObjectType: \"Material\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 0);
fbx.Append("\n\t}");
fbx.Append("\n\tObjectType: \"Texture\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 0);
fbx.Append("\n\t}");
fbx.Append("\n\tObjectType: \"Video\" {");
fbx.AppendFormat("\n\t\tCount: {0}", 0);
fbx.Append("\n\t}");
fbx.Append("\n}\n");
fbx.Append("\nObjects: {");
FBXwriter.Write(fbx);
#endregion
#region write Model nodes and connections
ob.AppendFormat("\n\tModel: 1{0}, \"Model::{1}\", \"Mesh\" {{", 1, mesh.Name);
ob.Append("\n\t\tVersion: 232");
ob.Append("\n\t\tProperties70: {");
ob.Append("\n\t\t\tP: \"InheritType\", \"enum\", \"\", \"\",1");
ob.Append("\n\t\t\tP: \"ScalingMax\", \"Vector3D\", \"Vector\", \"\",0,0,0");
ob.Append("\n\t\t\tP: \"DefaultAttributeIndex\", \"int\", \"Integer\", \"\",0");
//mb.Append("\n\t\t\tP: \"UDP3DSMAX\", \"KString\", \"\", \"U\", \"MapChannel:1 = UVChannel_1&cr;&lf;MapChannel:2 = UVChannel_2&cr;&lf;\"");
//mb.Append("\n\t\t\tP: \"MaxHandle\", \"int\", \"Integer\", \"UH\",24");
ob.Append("\n\t\t}");
ob.Append("\n\t\tShading: T");
ob.Append("\n\t\tCulling: \"CullingOff\"\n\t}");
cb.AppendFormat("\n\n\t;Model::{0}, Model::RootNode", mesh.Name);
cb.AppendFormat("\n\tC: \"OO\",1{0},0", 1);
#endregion
MeshFBX(mesh, "2", ob);
//write data 8MB at a time
if (ob.Length > (8 * 0x100000))
{ FBXwriter.Write(ob); }
cb.Append(cb2);
FBXwriter.Write(ob);
cb.Append("\n}");//Connections end
FBXwriter.Write(cb);
}
}
private static void MeshFBX(MeshData m_Mesh, string MeshID, StringBuilder ob)
{
int vertexNum = m_Mesh.GetVertexCount();
if (vertexNum > 0)//general failsafe
{
//StatusStripUpdate("Writing Geometry: " + m_Mesh.m_Name);
ob.AppendFormat("\n\tGeometry: 3{0}, \"Geometry::\", \"Mesh\" {{", MeshID);
ob.Append("\n\t\tProperties70: {");
var randomColor = RandomColorGenerator(m_Mesh.Name);
ob.AppendFormat("\n\t\t\tP: \"Color\", \"ColorRGB\", \"Color\", \"\",{0},{1},{2}", ((float)randomColor[0] / 255), ((float)randomColor[1] / 255), ((float)randomColor[2] / 255));
ob.Append("\n\t\t}");
#region Vertices
MeshData.VBuffer buff = m_Mesh.Buffers[ESemantic.Position];
ob.AppendFormat("\n\t\tVertices: *{0} {{\n\t\t\ta: ", vertexNum * 3);
int lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x, buff.mData[v].y, buff.mData[v].z);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t}");
#endregion
#region Indices
int indexNum = m_Mesh.GetIndexCount();
//in order to test topology for triangles/quads we need to store submeshes and write each one as geometry, then link to Mesh Node
ob.AppendFormat("\n\t\tPolygonVertexIndex: *{0} {{\n\t\t\ta: ", indexNum);
lineSplit = ob.Length;
for (int f = 0; f < indexNum / 3; f++)
{
ob.AppendFormat("{0},{1},{2},", m_Mesh.Trangles[f * 3], m_Mesh.Trangles[f * 3 + 1], (-m_Mesh.Trangles[f * 3 + 2] - 1));
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t}");
ob.Append("\n\t\tGeometryVersion: 124");
#endregion
#region Normals
if (m_Mesh.Buffers.TryGetValue(ESemantic.Normal,out buff))
{
ob.Append("\n\t\tLayerElementNormal: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tNormals: *{0} {{\n\t\t\ta: ", (vertexNum * 3));
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x, buff.mData[v].y, buff.mData[v].z);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region Binormals
if (m_Mesh.Buffers.TryGetValue(ESemantic.BNormal, out buff))
{
ob.Append("\n\t\tLayerElementBinormal: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tBinormals: *{0} {{\n\t\t\ta: ", (vertexNum * 3));
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
if (buff.mDimension == 3)
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x, buff.mData[v].y, buff.mData[v].z);
else
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x * buff.mData[v].w, buff.mData[v].y * buff.mData[v].w, buff.mData[v].z * buff.mData[v].w);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region Tangents
if (m_Mesh.Buffers.TryGetValue(ESemantic.Tangent, out buff))
{
ob.Append("\n\t\tLayerElementTangent: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tTangents: *{0} {{\n\t\t\ta: ", (vertexNum * 3));
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
if (buff.mDimension == 3)
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x, buff.mData[v].y, buff.mData[v].z);
else
ob.AppendFormat("{0},{1},{2},", buff.mData[v].x * buff.mData[v].w, buff.mData[v].y * buff.mData[v].w, buff.mData[v].z * buff.mData[v].w);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region Colors
if (m_Mesh.Buffers.TryGetValue(ESemantic.Color, out buff))
{
ob.Append("\n\t\tLayerElementColor: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"\"");
//ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
//ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByPolygonVertex\"");
ob.Append("\n\t\t\tReferenceInformationType: \"IndexToDirect\"");
ob.AppendFormat("\n\t\t\tColors: *{0} {{\n\t\t\ta: ", vertexNum * 4);
//ob.Append(string.Join(",", m_Mesh.m_Colors));
lineSplit = ob.Length;
if (buff.mDimension == 3)
{
for (int i = 0; i < vertexNum; i++)
{
ob.AppendFormat("{0},{1},{2},{3},", buff.mData[i].x, buff.mData[i].y, buff.mData[i].z, 1.0f);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
}
else
{
for (int i = 0; i < vertexNum; i++)
{
ob.AppendFormat("{0},{1},{2},{3},", buff.mData[i].x, buff.mData[i].y, buff.mData[i].z, buff.mData[i].w);
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}");
ob.AppendFormat("\n\t\t\tColorIndex: *{0} {{\n\t\t\ta: ", indexNum);
lineSplit = ob.Length;
for (int f = 0; f < indexNum / 3; f++)
{
ob.AppendFormat("{0},{1},{2},", m_Mesh.Trangles[f * 3], m_Mesh.Trangles[f * 3 + 1], (m_Mesh.Trangles[f * 3 + 2]));
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region UV1
//does FBX support UVW coordinates?
if (m_Mesh.Buffers.TryGetValue(ESemantic.Coord0, out buff))
{
ob.Append("\n\t\tLayerElementUV: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"UVChannel_1\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tUV: *{0} {{\n\t\t\ta: ", vertexNum * buff.mDimension);
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
for(int j = 0;j<buff.mDimension;j++)
{
ob.AppendFormat("{0},", buff.mData[v][j]);
}
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region UV2
if (m_Mesh.Buffers.TryGetValue(ESemantic.Coord1, out buff))
{
ob.Append("\n\t\tLayerElementUV: 1 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"UVChannel_2\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tUV: *{0} {{\n\t\t\ta: ", vertexNum * buff.mDimension);
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
for (int j = 0; j < buff.mDimension; j++)
{
ob.AppendFormat("{0},", buff.mData[v][j]);
}
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region UV3
if (m_Mesh.Buffers.TryGetValue(ESemantic.Coord2, out buff))
{
ob.Append("\n\t\tLayerElementUV: 2 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"UVChannel_3\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tUV: *{0} {{\n\t\t\ta: ", vertexNum * buff.mDimension);
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
for (int j = 0; j < buff.mDimension; j++)
{
ob.AppendFormat("{0},", buff.mData[v][j]);
}
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region UV4
if (m_Mesh.Buffers.TryGetValue(ESemantic.Coord3, out buff))
{
ob.Append("\n\t\tLayerElementUV: 3 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"UVChannel_4\"");
ob.Append("\n\t\t\tMappingInformationType: \"ByVertice\"");
ob.Append("\n\t\t\tReferenceInformationType: \"Direct\"");
ob.AppendFormat("\n\t\t\tUV: *{0} {{\n\t\t\ta: ", vertexNum * buff.mDimension);
lineSplit = ob.Length;
for (int v = 0; v < vertexNum; v++)
{
for (int j = 0; j < buff.mDimension; j++)
{
ob.AppendFormat("{0},", buff.mData[v][j]);
}
if (ob.Length - lineSplit > 2000)
{
ob.Append("\n");
lineSplit = ob.Length;
}
}
ob.Length--;//remove last comma
ob.Append("\n\t\t\t}\n\t\t}");
}
#endregion
#region Material
ob.Append("\n\t\tLayerElementMaterial: 0 {");
ob.Append("\n\t\t\tVersion: 101");
ob.Append("\n\t\t\tName: \"\"");
ob.Append("\n\t\t\tMappingInformationType: \"");
//if (m_Mesh.m_SubMeshes.Count == 1)
{ ob.Append("AllSame\""); }
//else { ob.Append("ByPolygon\""); }
ob.Append("\n\t\t\tReferenceInformationType: \"IndexToDirect\"");
ob.AppendFormat("\n\t\t\tMaterials: *{0} {{", 0);
ob.Append("\n\t\t\t\t");
//if (m_Mesh.m_SubMeshes.Count == 1)
{ ob.Append("0"); }
//else
//{
// lineSplit = ob.Length;
// for (int i = 0; i < m_Mesh.m_materialIDs.Count; i++)
// {
// ob.AppendFormat("{0},", m_Mesh.m_materialIDs[i]);
// if (ob.Length - lineSplit > 2000)
// {
// ob.Append("\n");
// lineSplit = ob.Length;
// }
// }
// ob.Length--;//remove last comma
//}
ob.Append("\n\t\t\t}\n\t\t}");
#endregion
#region Layers
ob.Append("\n\t\tLayer: 0 {");
ob.Append("\n\t\t\tVersion: 100");
if (m_Mesh.Buffers.ContainsKey(ESemantic.Normal))
{
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementNormal\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
}
if (m_Mesh.Buffers.ContainsKey(ESemantic.BNormal))
{
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementBinormal\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
}
if (m_Mesh.Buffers.ContainsKey(ESemantic.Tangent))
{
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementTangent\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
}
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementMaterial\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
//
/*ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementTexture\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementBumpTextures\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");*/
if (m_Mesh.Buffers.ContainsKey(ESemantic.Color))
{
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementColor\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
}
if (m_Mesh.Buffers.ContainsKey(ESemantic.Coord0))
{
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementUV\"");
ob.Append("\n\t\t\t\tTypedIndex: 0");
ob.Append("\n\t\t\t}");
}
ob.Append("\n\t\t}"); //Layer 0 end
if (m_Mesh.Buffers.ContainsKey(ESemantic.Coord1))
{
ob.Append("\n\t\tLayer: 1 {");
ob.Append("\n\t\t\tVersion: 100");
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementUV\"");
ob.Append("\n\t\t\t\tTypedIndex: 1");
ob.Append("\n\t\t\t}");
ob.Append("\n\t\t}"); //Layer 1 end
}
if (m_Mesh.Buffers.ContainsKey(ESemantic.Coord2))
{
ob.Append("\n\t\tLayer: 2 {");
ob.Append("\n\t\t\tVersion: 100");
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementUV\"");
ob.Append("\n\t\t\t\tTypedIndex: 2");
ob.Append("\n\t\t\t}");
ob.Append("\n\t\t}"); //Layer 2 end
}
if (m_Mesh.Buffers.ContainsKey(ESemantic.Coord3))
{
ob.Append("\n\t\tLayer: 3 {");
ob.Append("\n\t\t\tVersion: 100");
ob.Append("\n\t\t\tLayerElement: {");
ob.Append("\n\t\t\t\tType: \"LayerElementUV\"");
ob.Append("\n\t\t\t\tTypedIndex: 3");
ob.Append("\n\t\t\t}");
ob.Append("\n\t\t}"); //Layer 3 end
}
#endregion
ob.Append("\n\t}"); //Geometry end
}
}
private static byte[] RandomColorGenerator(string name)
{
int nameHash = name.GetHashCode();
System.Random r = new System.Random(nameHash);
//Random r = new Random(DateTime.Now.Millisecond);
byte red = (byte)r.Next(0, 255);
byte green = (byte)r.Next(0, 255);
byte blue = (byte)r.Next(0, 255);
return new byte[3] { red, green, blue };
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/SerializationMap.cs
// Serialization.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
[Serializable]
public class SerializationList<T>
{
[SerializeField]
List<T> target;
public List<T> ToList() { return target; }
public SerializationList(List<T> target)
{
this.target = target;
}
}
// Dictionary<TKey, TValue>
[Serializable]
public class SerializationMap<TKey, TValue> : ISerializationCallbackReceiver
{
[SerializeField]
List<TKey> keys;
[SerializeField]
List<TValue> values;
public Dictionary<TKey, TValue> target;
public Dictionary<TKey, TValue> ToDictionary() { return target; }
public SerializationMap(Dictionary<TKey, TValue> target)
{
this.target = target;
}
public void OnBeforeSerialize()
{
keys = new List<TKey>(target.Keys);
values = new List<TValue>(target.Values);
}
public void OnAfterDeserialize()
{
var count = Math.Min(keys.Count, values.Count);
target = new Dictionary<TKey, TValue>(count);
for (var i = 0; i < count; ++i)
{
target.Add(keys[i], values[i]);
}
}
}
// Dictionary<TKey, TValue>
[Serializable]
public class SerializationMap1 : ISerializationCallbackReceiver
{
[SerializeField]
List<ESemantic> keys;
[SerializeField]
List<ConvertStrategy.BufferDataInfo> values;
public Dictionary<ESemantic, ConvertStrategy.BufferDataInfo> target;
public Dictionary<ESemantic, ConvertStrategy.BufferDataInfo> ToDictionary() { return target; }
public SerializationMap1(Dictionary<ESemantic, ConvertStrategy.BufferDataInfo> target)
{
this.target = target;
}
public void OnBeforeSerialize()
{
keys = new List<ESemantic>(target.Keys);
values = new List<ConvertStrategy.BufferDataInfo>(target.Values);
}
public void OnAfterDeserialize()
{
var count = Math.Min(keys.Count, values.Count);
target = new Dictionary<ESemantic, ConvertStrategy.BufferDataInfo>(count);
for (var i = 0; i < count; ++i)
{
target.Add(keys[i], values[i]);
}
}
}<file_sep>/Assets/Common/MeshConverter/Editor/RipImporter.cs
using UnityEngine;
using UnityEditor;
namespace UnityEngine {
public class RipImporter : EditorWindow {
class Styles {
// public GUIContent m_WarningContent = new GUIContent(string.Empty, EditorGUIUtility.LoadRequired("Builtin Skins/Icons/console.warnicon.sml.png") as Texture2D);
public GUIStyle mPreviewBox = new GUIStyle("OL Box");
public GUIStyle mPreviewTitle = new GUIStyle("OL Title");
public GUIStyle mPreviewTitle1 = new GUIStyle("OL Box");
public GUIStyle mLoweredBox = new GUIStyle("TextField");
public GUIStyle mHelpBox = new GUIStyle("helpbox");
public GUIStyle mMiniLable = new GUIStyle("MiniLabel");
public GUIStyle mSelected = new GUIStyle("LODSliderRangeSelected");
public GUIStyle mOLTitle = new GUIStyle("OL Title");
public GUIStyle mHLine = new GUIStyle();
public GUIStyle mVLine = new GUIStyle();
public Styles() {
mLoweredBox.padding = new RectOffset(1, 1, 1, 1);
mPreviewTitle1.fixedHeight = 0;
mPreviewTitle1.fontStyle = FontStyle.Bold;
mPreviewTitle1.alignment = TextAnchor.MiddleLeft;
mHLine.fixedHeight = 1f;
mHLine.margin = new RectOffset(0, 0, 0, 0);
mVLine.fixedWidth = 1f;
mVLine.stretchHeight = true;
mVLine.stretchWidth = false;
}
}
private static Styles mStyles;
public float mMdlscaler = 1.0f;
public bool mFlipUV = false;
public System.Action<MeshData> onMeshDataPrepared;
public RipData mRipData;
Vector2 DataPanelScroll = new Vector2();
int current = 0;
void OnGUI() {
if (null == mRipData)
return;
if (null == mStyles) {
mStyles = new Styles();
}
int vertexNum = (int)mRipData.vertexCount;
float height = this.position.height - 20;
float width = 40;
int viewItemNum = Mathf.FloorToInt(height / 18 - 1);
current = (int)GUI.VerticalScrollbar(new Rect(0, 0, 20, height + 3), current, viewItemNum, 0, vertexNum);
int end = Mathf.Min(current + viewItemNum, vertexNum);
int start = Mathf.Max(0, end - viewItemNum);
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(20);
//draw id
EditorGUILayout.BeginVertical(mStyles.mPreviewBox, GUILayout.Width(width),GUILayout.Height(height));
{
EditorGUILayout.BeginHorizontal(mStyles.mOLTitle);
{
EditorGUILayout.LabelField(" id", EditorStyles.boldLabel, GUILayout.Width(width));
}
EditorGUILayout.EndHorizontal();
for (int i = start; i < end; ++i) {
EditorGUILayout.LabelField(i.ToString(), EditorStyles.boldLabel, GUILayout.Width(width));
}
}
EditorGUILayout.EndVertical();
GUILayout.Space(1);
//data
DataPanelScroll = EditorGUILayout.BeginScrollView(DataPanelScroll);
EditorGUILayout.BeginHorizontal();
{
for(int i = 0;i < mRipData.elements.Length; ++i) {
RipAttributeElement ele = mRipData.elements[i];
width = ele.dimension * 100;
EditorGUILayout.BeginVertical(mStyles.mPreviewBox, GUILayout.Width(width), GUILayout.Height(height));
{
EditorGUILayout.BeginHorizontal(mStyles.mOLTitle);
{
ele.sematic = (ESemantic)EditorGUILayout.EnumPopup(ele.sematic, GUILayout.Width(width));
}
EditorGUILayout.EndHorizontal();
for(int j = start; j < end; ++j) {
EditorGUILayout.BeginHorizontal();
for(int k = 0; k < ele.dimension; ++k) {
EditorGUILayout.LabelField(mRipData.vertexData[j * mRipData.dimensionPerVertex + k + ele.bytesOffset / 4].ToString(), GUILayout.Width(90));
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.EndVertical();
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
}
EditorGUILayout.BeginVertical();
{
GUILayout.Label(mRipData.GetInfo());
mMdlscaler = EditorGUILayout.FloatField("Scale:", mMdlscaler);
if (GUILayout.Button("确认导入")) {
onMeshDataPrepared(ConvertRipToMeshData(mRipData));
this.Close();
}
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
private MeshData ConvertRipToMeshData(RipData ripData) {
MeshData mesh = new MeshData(ripData.meshName);
for(int i = 0; i < ripData.indexCount; ++i) {
mesh.Trangles.Add((int)ripData.indexData[i]);
}
var buffers = mesh.Buffers;
for(int i = 0; i < ripData.elements.Length; ++i) {
RipAttributeElement ele = ripData.elements[i];
if (ele.sematic == ESemantic.UnKnown)
continue;
MeshData.VBuffer buff;
if (!buffers.TryGetValue(ele.sematic,out buff)) {
buff = new MeshData.VBuffer();
buffers.Add(ele.sematic, buff);
buff.mDimension = (int)ele.dimension;
for(int j = 0; j < ripData.vertexCount; ++j) {
var data = new Vector4();
for (int k = 0; k < ele.dimension; ++k) {
float val = mRipData.vertexData[j * mRipData.dimensionPerVertex + k + ele.bytesOffset / 4];
if(ele.sematic == ESemantic.Position) {
//val *= mMdlscaler;
}
data[k] = val;
}
buff.mData.Add(data);
}
}
}
return mesh;
}
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/ConvertStrategy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine
{
[Serializable]
public class ConvertStrategy : ISerializationCallbackReceiver
{
[System.Serializable]
public enum ESlot
{
None = 0,
SlotA = 1,
SlotB = 2,
SlotC = 3,
SlotD = 4
}
[System.Serializable]
public enum EPass
{
X = 0,
Y = 1,
Z = 2,
W = 3
}
[System.Serializable]
public class PassDataInfo
{
public ESlot Slot;
public ESemantic Semantic;
public EPass Pass;
public PassDataInfo()
{
Slot = ESlot.None;
Semantic = ESemantic.UnKnown;
Pass = EPass.W;
}
public PassDataInfo(ESlot slot, ESemantic s, EPass pass)
{
Slot = slot;
Semantic = s;
Pass = pass;
}
public bool IsValid()
{
return (Slot != ConvertStrategy.ESlot.None && Semantic != ESemantic.UnKnown);
}
}
[System.Serializable]
public class BufferDataInfo
{
//public ESemantic Semantic;
public PassDataInfo X;
public PassDataInfo Y;
public PassDataInfo Z;
public PassDataInfo W;
public BufferDataInfo(ESemantic s)
{
X = new PassDataInfo(ESlot.None, s, EPass.X);
Y = new PassDataInfo(ESlot.None, s, EPass.Y);
Z = new PassDataInfo(ESlot.None, s, EPass.Z);
W = new PassDataInfo(ESlot.None, s, EPass.W);
}
public PassDataInfo this[int index]
{
get
{
switch (index)
{
case 0:
return X;
case 1:
return Y;
case 2:
return Z;
case 3:
return W;
default:
return null;
}
}
set
{
switch(index)
{
case 0:
X = value;
break;
case 1:
Y = value;
break;
case 2:
Z = value;
break;
case 3:
W = value;
break;
default:
break;
}
}
}
}
public MeshData SlotA;
public MeshData SlotB;
public MeshData SlotC;
public MeshData SlotD;
public string PostConvert = "";
[SerializeField]
SerializationMap1 mSerBufferInfos = new SerializationMap1(null);
public Dictionary<ESemantic, BufferDataInfo> BufferInfos = new Dictionary<ESemantic, BufferDataInfo>();
public MeshData this[int index]
{
get
{
switch (index)
{
case 0:
return SlotA;
case 1:
return SlotB;
case 2:
return SlotC;
case 3:
return SlotD;
default:
return null;
}
}
set
{
switch (index)
{
case 0:
SlotA = value;
break;
case 1:
SlotB = value;
break;
case 2:
SlotC = value;
break;
case 3:
SlotD = value;
break;
default:
break;
}
}
}
public MeshData Convert(string newMeshName)
{
int id = CheckValid();
if(id != 0)
{
Debug.LogError("转换失败:"+ GetValidInfo(id));
return null;
}
MeshData newMesh = new MeshData(newMeshName);
MeshData slotmesh = SlotA == null ? SlotB : SlotA;
if (slotmesh == null)
{
slotmesh = SlotC;
if (slotmesh == null)
{
slotmesh = SlotD;
}
}
if (slotmesh == null)
return null;
int vertexNum = slotmesh.GetVertexCount();
foreach (var pair in BufferInfos)
{
BufferDataInfo buff = pair.Value;
ESemantic s = pair.Key;
Vector4[] data = new Vector4[vertexNum];
int dim = 0;
for (int i = 0; i < 4; i++)
{
var pass = buff[i];
if (pass.Slot == ESlot.None || pass.Semantic == ESemantic.UnKnown)
{
break;
}
var slot = this[(int)pass.Slot - 1];
for(int j = 0;j<vertexNum;j++)
{
data[j][i] = (slot.Buffers[pass.Semantic].mData[j])[(int)pass.Pass];
}
dim = i + 1;
}
if(dim > 0)
{
newMesh.AddDataRange(s, data, dim);
}
}
newMesh.AddTrangle(slotmesh.Trangles.ToArray());
return newMesh;
}
public int CheckValid()
{
bool useSlotA = false;
bool useSlotB = false;
bool useSlotC = false;
bool useSlotD = false;
//find slots that are used
foreach(var pair in BufferInfos)
{
var buff = pair.Value;
for(int i = 0;i<4;i++)
{
var slot = buff[i].Slot;
switch(slot)
{
case ESlot.SlotA:
useSlotA = true;
break;
case ESlot.SlotB:
useSlotB = true;
break;
case ESlot.SlotC:
useSlotC = true;
break;
case ESlot.SlotD:
useSlotD = true;
break;
}
}
}
//Check if slots are available
List<MeshData> list = new List<MeshData>();
if (useSlotA)
{
if (SlotA == null || !SlotA.IsValid())
return 1;
else
{
if (!list.Contains(SlotA))
list.Add(SlotA);
}
}
if (useSlotB)
{
if (SlotB == null || !SlotB.IsValid())
return 2;
else
{
if (!list.Contains(SlotB))
list.Add(SlotB);
}
}
if (useSlotC)
{
if (SlotC == null || !SlotC.IsValid())
return 3;
else
{
if (!list.Contains(SlotC))
list.Add(SlotC);
}
}
if (useSlotD)
{
if (SlotD == null || !SlotD.IsValid())
return 4;
else
{
if (!list.Contains(SlotD))
list.Add(SlotD);
}
}
//check if slots could be conbined
for(int i = 1;i<list.Count;i++)
{
bool b = CheckCombineAvailable(list[0], list[i]);
if (!b)
return 5;
}
foreach (var pair in BufferInfos)
{
var buff = pair.Value;
for (int i = 0; i < 4; i++)
{
var pass = buff[i];
if(!CheckPassAvailable(pass))
{
int id = 1000 + (int)pair.Key * 10 + i;
return id;
}
}
}
return 0;
}
private bool CheckCombineAvailable(MeshData a,MeshData b)
{
if(a.GetVertexCount() !=b.GetVertexCount() || a.GetIndexCount()!=b.GetIndexCount())
return false;
return true;
}
private bool CheckPassAvailable(PassDataInfo pass)
{
if (pass.Slot == ESlot.None || pass.Semantic == ESemantic.UnKnown)
return true;
var slot = this[(int)pass.Slot - 1];
if (slot == null)
return false;
var s = pass.Semantic;
MeshData.VBuffer buff;
if(slot.Buffers.TryGetValue(s,out buff))
{
if (buff.mDimension > (int)pass.Pass)
return true;
}
return false;
}
public string GetValidInfo(int i)
{
switch (i)
{
case 0:
return "OK";
case 1:
return "SlotA is not valid";
case 2:
return "SlotB is not valid";
case 3:
return "SlotC is not valid";
case 4:
return "SlotD is not valid";
case 5:
return "Vertex numbers or Index numbers are not match";
}
if (i > 1000)
{
i = i % 1000;
int semantic = i / 10;
int pass = i - semantic * 10;
return "Invalid pass info:" + (ESemantic)semantic+"."+((EPass)pass);
}
return "unknown";
}
public void OnAfterDeserialize()
{
BufferInfos = mSerBufferInfos.ToDictionary();
}
public void OnBeforeSerialize()
{
mSerBufferInfos.target = BufferInfos;
}
}
}<file_sep>/Assets/Common/UVPreviewer/Editor/UVPreviewWindow.cs
using UnityEngine;
using UnityEditor;
using System;
namespace UniyEngine {
public class UVPreviewWindow : EditorWindow {
protected static UVPreviewWindow uvPreviewWindow;
private int windowDefaultSize = 562; // 512 + (sideSpace*2)
private int ySpace = 95;
private int sideSpace = 25;
private Rect uvPreviewRect;
private Rect uvSpaceRect;
private float scale = 1;
private GameObject selectedObject = null;
private Mesh m = null;
private int[] tris;
private Vector2[] uvs;
private Rect screenCenter;
private bool isStarted;
private Texture2D fillTextureGray;
private Texture2D fillTextureDark;
private float xPanShift;
private float yPanShift;
private int gridStep = 16;
private bool canDrawView;
private bool mousePositionInsidePreview;
private int selectedUV = 0;
private string[] selectedUVStrings = new string[2];
private Material lineMaterial;
private Texture2D texture;
[MenuItem("GEffect/UV Preview")]
public static void Start() {
uvPreviewWindow = (UVPreviewWindow)EditorWindow.GetWindow(typeof(UVPreviewWindow));
uvPreviewWindow.titleContent = new GUIContent("UV Preview");
uvPreviewWindow.autoRepaintOnSceneChange = true;
uvPreviewWindow.minSize = new Vector2(512, 512);
}
void Update() {
if (!isStarted) {
screenCenter = new Rect(Screen.width / 2, Screen.height / 2, 1, 1);
uvPreviewWindow.position = new Rect(screenCenter.x, screenCenter.y, windowDefaultSize, windowDefaultSize + ySpace);
fillTextureGray = CreateFillTexture(1, 1, new Color(0, 0, 0, 0.1f));
fillTextureDark = CreateFillTexture(1, 1, new Color(0, 0, 0, 0.5f));
xPanShift = 0;
yPanShift = 0;
isStarted = true;
selectedUVStrings[0] = "UV";
selectedUVStrings[1] = "UV 2";
}
}
void OnSelectionChange() {
}
void OnGUI() {
Event e = Event.current;
selectedObject = Selection.activeGameObject;
if (selectedObject == null) {
GUI.color = Color.gray;
EditorGUILayout.HelpBox("请选择物件...", MessageType.Warning);
canDrawView = false;
} else {
if (selectedObject.GetComponent<MeshFilter>() != null | selectedObject.GetComponent<SkinnedMeshRenderer>() != null) {
GUI.color = Color.green;
EditorGUILayout.HelpBox("选择的物件: " + selectedObject.name, MessageType.None);
GUI.color = Color.white;
canDrawView = true;
if (selectedObject.GetComponent<SkinnedMeshRenderer>() == null) {
m = selectedObject.GetComponent<MeshFilter>().sharedMesh;
} else {
m = selectedObject.GetComponent<SkinnedMeshRenderer>().sharedMesh;
}
if (m != null) {
GUILayout.BeginHorizontal();
if (m.uv2.Length > 0) {
selectedUV = GUILayout.Toolbar(selectedUV, selectedUVStrings);
} else {
selectedUV = 0;
GUILayout.BeginHorizontal();
EditorGUILayout.HelpBox("Mesh没有第二套UV", MessageType.None);
if (GUILayout.Button("生成第二套UV")) {
Unwrapping.GenerateSecondaryUVSet(m);
EditorApplication.Beep();
EditorUtility.DisplayDialog("完成", "第二套UV已经生成!", "确认");
}
GUILayout.EndHorizontal();
}
tris = m.triangles;
if (selectedUV == 0) {
uvs = m.uv;
} else {
uvs = m.uv2;
}
}
} else {
GUI.color = Color.gray;
EditorGUILayout.HelpBox("物件必须有Mesh Filter/Skined Mesh Renderer组件", MessageType.Warning);
canDrawView = false;
}
}
if (e.mousePosition.x > uvPreviewRect.x & e.mousePosition.x < uvPreviewRect.width + sideSpace & e.mousePosition.y > uvPreviewRect.y & e.mousePosition.y < uvPreviewRect.height + sideSpace + ySpace) {
mousePositionInsidePreview = true;
} else {
mousePositionInsidePreview = false;
}
if (mousePositionInsidePreview) {
if (e.type == EventType.MouseDrag) {
xPanShift += e.delta.x;
yPanShift += e.delta.y;
}
if (e.type == EventType.ScrollWheel) {
scale += -(e.delta.y * 0.02f);
}
}
uvPreviewRect = new Rect(sideSpace, ySpace + sideSpace, uvPreviewWindow.position.width - (sideSpace * 2), uvPreviewWindow.position.height - ySpace - (sideSpace * 2));
uvSpaceRect = new Rect(sideSpace + xPanShift, (int)(-1 * scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize,
scale * windowDefaultSize, scale * windowDefaultSize);
GUI.DrawTexture(new Rect(0, 0, uvPreviewWindow.position.width, ySpace), fillTextureGray);
if (canDrawView) {
GUI.DrawTexture(uvPreviewRect, fillTextureDark);
//texture
if (texture != null) {
GUI.BeginGroup(uvPreviewRect);
EditorGUI.DrawPreviewTexture(new Rect(uvSpaceRect.x - uvPreviewRect.x, uvSpaceRect.y - uvPreviewRect.y,
uvSpaceRect.width, uvSpaceRect.height), texture);
GUI.EndGroup();
//GUI.DrawTexture(uvSpaceRect, texture);
}
//GRID
for (int i = 1; i < 4096; i += (int)(gridStep)) {
int x1h = (int)(uvPreviewRect.x - 1);
int x2h = (int)(uvPreviewRect.width + sideSpace);
int yh = i + (ySpace + sideSpace) - 1;
int y1v = ySpace + sideSpace;
int y2v = (int)(uvPreviewRect.height + ySpace + sideSpace);
int xv = i + sideSpace - 1;
if (yh < uvPreviewRect.height + ySpace + sideSpace) {
DrawLine(x1h, yh, x2h, yh, new Color(1, 1, 1, 0.15f));
}
if (xv < uvPreviewRect.width + sideSpace) {
DrawLine(xv, y1v, xv, y2v, new Color(1, 1, 1, 0.15f));
}
}
//UV
for (int i = 0; i < tris.Length; i += 3) {
int line1x1 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line1y1 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize;
int line1x2 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line1y2 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift + windowDefaultSize);
int line2x1 = (int)(uvs[tris[i + 1]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line2y1 = (int)(-uvs[tris[i + 1]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize;
int line2x2 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line2y2 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize;
int line3x1 = (int)(uvs[tris[i + 2]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line3y1 = (int)(-uvs[tris[i + 2]].y * (scale * windowDefaultSize) + ySpace + sideSpace + yPanShift) + windowDefaultSize;
int line3x2 = (int)(uvs[tris[i]].x * (scale * windowDefaultSize) + sideSpace + xPanShift);
int line3y2 = (int)(-uvs[tris[i]].y * (scale * windowDefaultSize) + sideSpace + ySpace + yPanShift) + windowDefaultSize;
Rect cropRect = new Rect(uvPreviewRect.x, uvPreviewRect.y, uvPreviewRect.width, uvPreviewRect.height);
DrawLine(line1x1, line1y1, line1x2, line1y2, new Color(0, 1, 1, 1), true, cropRect);
DrawLine(line2x1, line2y1, line2x2, line2y2, new Color(0, 1, 1, 1), true, cropRect);
DrawLine(line3x1, line3y1, line3x2, line3y2, new Color(0, 1, 1, 1), true, cropRect);
}
//uv clamp line
{
int lbx = (int)(sideSpace + xPanShift);
int lby = (int)(ySpace + sideSpace + yPanShift) + windowDefaultSize;
int rbx = (int)(scale * windowDefaultSize + sideSpace + xPanShift);
int rby = (int)(ySpace + sideSpace + yPanShift) + windowDefaultSize;
int ltx = (int)(+sideSpace + xPanShift);
int lty = (int)(-scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize;
int rtx = (int)(scale * windowDefaultSize + sideSpace + xPanShift);
int rty = (int)(-scale * windowDefaultSize + ySpace + sideSpace + yPanShift) + windowDefaultSize;
Rect cropRect = new Rect(uvPreviewRect.x, uvPreviewRect.y, uvPreviewRect.width, uvPreviewRect.height);
DrawLine(ltx, lty, rtx, rty, new Color(0, 1, 0, 1), true, cropRect);
DrawLine(ltx, lty, lbx, lby, new Color(0, 1, 0, 1), true, cropRect);
DrawLine(rtx, rty, rbx, rby, new Color(0, 1, 0, 1), true, cropRect);
DrawLine(lbx, lby, rbx, rby, new Color(0, 1, 0, 1), true, cropRect);
}
DrawLine(0, ySpace - 1, (int)uvPreviewWindow.position.width, ySpace - 1, Color.gray);
DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray);
DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 1);
DrawHollowRectangle((int)uvPreviewRect.x, (int)uvPreviewRect.y, (int)uvPreviewRect.width + sideSpace, (int)uvPreviewRect.height + ySpace + sideSpace, Color.gray, 2);
EditorGUIUtility.AddCursorRect(uvPreviewRect, MouseCursor.Pan);
// if(GUILayout.Button("Save To PNG")){
// UVSaveWindow uvSaveWindow = (UVSaveWindow)EditorWindow.GetWindow (typeof (UVSaveWindow));
// uvSaveWindow.title = "Save to PNG";
// uvSaveWindow.maxSize = new Vector2(256,125);
// uvSaveWindow.minSize = new Vector2(256,124);
// uvSaveWindow.uvsToRender = uvs;
// uvSaveWindow.trianglesToRender = tris;
// }
texture = (Texture2D)EditorGUILayout.ObjectField("选择纹理贴图:", texture, typeof(Texture2D),true);
GUILayout.EndHorizontal();
}
Repaint();
}
private Texture2D CreateFillTexture(int width, int height, Color fillColor) {
Texture2D texture = new Texture2D(width, height);
Color[] pixels = new Color[width * height];
for (int i = 0; i < pixels.Length; i++) {
pixels[i] = fillColor;
}
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
private void DrawLine(int x1, int y1, int x2, int y2, Color lineColor, bool isCrop = false, Rect crop = default(Rect)) {
if (!lineMaterial) {
lineMaterial = new Material(Shader.Find("Internal/DrawLine"));
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
}
lineMaterial.SetPass(0);
if (isCrop) {
// if(x1 < crop.x) x1 = (int)crop.x;
// if(x1 > crop.width) x1 = (int)crop.width;
// if(y1 < crop.y) y1 = (int)crop.y;
// if(y1 > crop.height) y1 = (int)crop.height;
// if(x2 < crop.x) x2 = (int)crop.x;
// if(x2 > crop.width) x2 = (int)crop.width;
// if(y2 < crop.y) y2 = (int)crop.y;
// if(y2 > crop.height) y2 = (int)crop.height;
CohenSutherlandClipLineDrawer.DrawLine(new Vector2(crop.x, crop.y), new Vector2(crop.x + crop.width, crop.y + crop.height),
new Vector2(x1, y1), new Vector2(x2, y2), lineColor);
} else {
GL.Begin(GL.LINES);
GL.Color(lineColor);
GL.Vertex3(x1, y1, 0);
GL.Vertex3(x2, y2, 0);
GL.End();
}
}
private void DrawHollowRectangle(int x, int y, int width, int height, Color rectangleColor, int expand = 0) {
DrawLine(x - expand, y - expand, width + expand, y - expand, rectangleColor);
DrawLine(x - expand, y - expand, x - expand, height + expand, rectangleColor);
DrawLine(width + expand, y - expand, width + expand, height + expand, rectangleColor);
DrawLine(x - expand, height + expand, width + expand, height + expand, rectangleColor);
}
}
class CohenSutherlandClipLineDrawer {
//区域码
private const int leftBitCode = 0x1;
private const int rightBitCode = 0x2;
private const int buttonBitCode = 0x4;
private const int topBitCode = 0x8;
static int inside(int code) {
return Convert.ToInt32(code == 0);
} //判断点是否在裁剪区内
static int reject(int code1, int code2) {
return Convert.ToInt32(code1 & code2);
} //判断能否完全排除一条线段
static int accept(int code1, int code2) {
return Convert.ToInt32((code1 | code2) == 0);
} //判断能否完全接受一条线段
static void swapPT(ref Vector2 a, ref Vector2 b) {
Vector2 t = a;
a = b;
b = t;
} //交换两个点
static void swapCode(ref int a, ref int b) {
int t = a;
a = b;
b = t;
} //交换两个区域码
//确定一个点所在位置的区域码
static int encode(ref Vector2 p, ref Vector2 winMin, ref Vector2 winMax) {
int code = 0x00;
if (p.x < winMin.x)
code |= leftBitCode;
if (p.x > winMax.x)
code |= rightBitCode;
if (p.y < winMin.y)
code |= buttonBitCode;
if (p.y > winMax.y)
code |= topBitCode;
return code;
}
public static void DrawLine(Vector2 winMin, Vector2 winMax, Vector2 lineBegin, Vector2 lineEnd, Color lineColor) {
int code1, code2; //保存两个端点的区域码
bool done = false, plotLine = false; //判断裁剪是否结束和是否要绘制直线
float k = 0; //斜率
while (!done) {
code1 = encode(ref lineBegin, ref winMin, ref winMax);
code2 = encode(ref lineEnd, ref winMin, ref winMax);
if (accept(code1, code2) != 0) { //当前直线能完全绘制
done = true;
plotLine = true;
} else {
if (reject(code1, code2) != 0) //当前直线能完全排除
done = true;
else {
if (inside(code1) != 0) { //若lineBegin端点在裁剪区内则交换两个端点使它在裁剪区外
swapPT(ref lineBegin, ref lineEnd);
swapCode(ref code1, ref code2);
}
//计算斜率
if (lineBegin.x != lineEnd.x)
k = (lineEnd.y - lineBegin.y) / (lineEnd.x - lineBegin.x);
//开始裁剪,以下与运算若结果为真,
//则lineBegin在边界外,此时将lineBegin移向直线与该边界的交点
if ((code1 & leftBitCode) != 0) {
lineBegin.y += (winMin.x - lineBegin.x) * k;
lineBegin.x = winMin.x;
} else if ((code1 & rightBitCode) != 0) {
lineBegin.y += (winMax.x - lineBegin.x) * k;
lineBegin.x = winMax.x;
} else if ((code1 & buttonBitCode) != 0) {
if (lineBegin.x != lineEnd.x)
lineBegin.x += (winMin.y - lineBegin.y) / k;
lineBegin.y = winMin.y;
} else if ((code1 & topBitCode) != 0) {
if (lineBegin.x != lineEnd.x)
lineBegin.x += (winMax.y - lineBegin.y) / k;
lineBegin.y = winMax.y;
}
}
}
}
if (plotLine) { //绘制裁剪好的直线
GL.Begin(GL.LINES);
GL.Color(lineColor);
GL.Vertex3(lineBegin.x, lineBegin.y, 0);
GL.Vertex3(lineEnd.x, lineEnd.y, 0);
GL.End();
}
}
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/MeshData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
namespace UnityEngine
{
[System.Serializable]
public enum ESemantic
{
UnKnown,
Position,
Color,
Normal,
Tangent,
BNormal,
Coord0,
Coord1,
Coord2,
Coord3,
Coord4
}
public class MeshData
{
public class VBuffer
{
public List<Vector4> mData = new List<Vector4>();
public int mDimension = 0;
};
public string Name;
public Dictionary<ESemantic, VBuffer> Buffers = new Dictionary<ESemantic, VBuffer>();
public List<int> Trangles = new List<int>();
public MeshData(string name)
{
Name = name;
}
public int GetVertexCount()
{
if (Buffers.Count == 0)
return 0;
var enu = Buffers.GetEnumerator();
enu.MoveNext();
int num = enu.Current.Value.mData.Count;
return num;
}
public int GetIndexCount()
{
return Trangles.Count;
}
public bool IsValid()
{
bool b = Trangles.Count > 0 && Buffers.Count > 0;
if (!b)
return false;
var enu = Buffers.GetEnumerator();
enu.MoveNext();
int num = enu.Current.Value.mData.Count;
while(enu.MoveNext())
{
if (num != enu.Current.Value.mData.Count)
return false;
}
return true;
}
public void AddData(ESemantic s, Vector4 data, int dimension = 4)
{
VBuffer buff;
if (!Buffers.TryGetValue(s, out buff))
{
buff = new VBuffer();
Buffers.Add(s, buff);
}
buff.mData.Add(data);
buff.mDimension = Mathf.Max(buff.mDimension, dimension);
}
public void AddDataRange(ESemantic s, IEnumerable<Vector4> datas,int dimension = 4)
{
VBuffer buff;
if (!Buffers.TryGetValue(s, out buff))
{
buff = new VBuffer();
Buffers.Add(s, buff);
}
buff.mData.AddRange(datas);
buff.mDimension = Mathf.Max(buff.mDimension, dimension);
}
public void AddTrangle(IEnumerable<int> collection)
{
Trangles.AddRange(collection);
}
public void Clear()
{
Trangles.Clear();
Buffers.Clear();
}
public string GetInfo()
{
StringBuilder sb = new StringBuilder();
sb.Append(Name+"\n");
sb.Append("Trangle num:" + Trangles.Count / 3 + "\n");
foreach (var p in Buffers)
{
var buff = p.Value;
if (buff.mData.Count > 0)
{
sb.Append(p.Key.ToString() + " num:" + buff.mData.Count + " dim:" + buff.mDimension + "\n");
}
}
return sb.ToString();
}
public Mesh ToMesh(bool inverseX = false)
{
Mesh mesh = new Mesh();
mesh.name = Name;
foreach(var pair in Buffers)
{
ESemantic s = pair.Key;
VBuffer buff = pair.Value;
switch (s)
{
case ESemantic.Position:
mesh.SetVertices(vector4to3(buff.mData,inverseX));
break;
case ESemantic.Normal:
mesh.SetNormals(vector4to3(buff.mData));
break;
case ESemantic.Color:
mesh.SetColors(vector4toColor(buff.mData));
break;
case ESemantic.Tangent:
mesh.SetTangents(buff.mData);
break;
case ESemantic.Coord0:
case ESemantic.Coord1:
case ESemantic.Coord2:
case ESemantic.Coord3:
case ESemantic.Coord4:
int c = (int)s - (int)ESemantic.Coord0;
switch(buff.mDimension)
{
case 2:
mesh.SetUVs(c, vector4to2(buff.mData));
break;
case 3:
mesh.SetUVs(c, vector4to3(buff.mData));
break;
case 4:
mesh.SetUVs(c, buff.mData);
break;
default:
Debug.LogWarning("buffer dimention warning:" + s + "-" + buff.mDimension);
break;
}
break;
default:
Debug.LogWarning("unsuport buffer:" + s);
break;
}
}
int[] triangles = new int[Trangles.Count];
for (int i = 0; i < Trangles.Count / 3; i++)
{
triangles[i * 3] = Trangles[i * 3];
if (inverseX)
{
triangles[i * 3 + 1] = Trangles[i * 3 + 2];
triangles[i * 3 + 2] = Trangles[i * 3 + 1];
}
else
{
triangles[i * 3 + 1] = Trangles[i * 3 + 1];
triangles[i * 3 + 2] = Trangles[i * 3 + 2];
}
}
mesh.SetTriangles(triangles, 0);
return mesh;
}
private List<Vector2> vector4to2(List<Vector4> vs)
{
Vector2[] vec2s = new Vector2[vs.Count];
for(int i = 0;i<vs.Count;i++)
{
vec2s[i].x = vs[i].x;
vec2s[i].y = vs[i].y;
}
List<Vector2> list = new List<Vector2>(vec2s);
return list;
}
private List<Vector3> vector4to3(List<Vector4> vs,bool inverseX = false)
{
Vector3[] vec3s = new Vector3[vs.Count];
for (int i = 0; i < vs.Count; i++)
{
if(inverseX)
vec3s[i].x = -vs[i].x;
else
vec3s[i].x = vs[i].x;
vec3s[i].y = vs[i].y;
vec3s[i].z = vs[i].z;
}
List<Vector3> list = new List<Vector3>(vec3s);
return list;
}
private List<Color> vector4toColor(List<Vector4> vs)
{
Color[] cs = new Color[vs.Count];
for (int i = 0; i < vs.Count; i++)
{
cs[i].r = vs[i].x;
cs[i].g = vs[i].y;
cs[i].b = vs[i].z;
cs[i].a = vs[i].w;
}
List<Color> list = new List<Color>(cs);
return list;
}
}
}<file_sep>/Assets/Common/MeshConverter/Editor/MeshViewer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MeshViewer : EditorWindow
{
class Styles
{
// public GUIContent m_WarningContent = new GUIContent(string.Empty, EditorGUIUtility.LoadRequired("Builtin Skins/Icons/console.warnicon.sml.png") as Texture2D);
public GUIStyle mPreviewBox = new GUIStyle("OL Box");
public GUIStyle mPreviewTitle = new GUIStyle("OL Title");
public GUIStyle mPreviewTitle1 = new GUIStyle("OL Box");
public GUIStyle mLoweredBox = new GUIStyle("TextField");
public GUIStyle mHelpBox = new GUIStyle("helpbox");
public GUIStyle mMiniLable = new GUIStyle("MiniLabel");
public GUIStyle mSelected = new GUIStyle("LODSliderRangeSelected");
public GUIStyle mOLTitle = new GUIStyle("OL Title");
public GUIStyle mHLine = new GUIStyle();
public GUIStyle mVLine = new GUIStyle();
public Styles()
{
mLoweredBox.padding = new RectOffset(1, 1, 1, 1);
mPreviewTitle1.fixedHeight = 0;
mPreviewTitle1.fontStyle = FontStyle.Bold;
mPreviewTitle1.alignment = TextAnchor.MiddleLeft;
mHLine.fixedHeight = 1f;
mHLine.margin = new RectOffset(0, 0, 0, 0);
mVLine.fixedWidth = 1f;
mVLine.stretchHeight = true;
mVLine.stretchWidth = false;
}
}
private static Styles mStyles;
public MeshData mMeshData;
Vector2 DataPanelScroll = new Vector2();
int current = 0;
public void OnGUI()
{
if (mMeshData == null)
return;
if (mStyles == null)
{
mStyles = new Styles();
}
int vertexNum = mMeshData.GetVertexCount();
float height = this.position.height - 20 ;
float width = 40;
int viewItemNum = Mathf.FloorToInt(height / 18 - 1);
//id scroll bar
current = (int)GUI.VerticalScrollbar(new Rect(0, 0, 20, height+3), current, viewItemNum, 0, vertexNum);
int end = Mathf.Min(current + viewItemNum, vertexNum);
int start = Mathf.Max(0, end - viewItemNum);
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(20);
//draw id
EditorGUILayout.BeginVertical(mStyles.mPreviewBox, GUILayout.Width(width), GUILayout.Height(height));
{
EditorGUILayout.BeginHorizontal(mStyles.mOLTitle);
{
EditorGUILayout.LabelField(" id", EditorStyles.boldLabel, GUILayout.Width(width));
}
EditorGUILayout.EndHorizontal();
for (int i = start; i < end; i++)
{
EditorGUILayout.LabelField(i.ToString(), EditorStyles.boldLabel, GUILayout.Width(width));
}
}
EditorGUILayout.EndVertical();
GUILayout.Space(1);
DataPanelScroll = EditorGUILayout.BeginScrollView(DataPanelScroll);
EditorGUILayout.BeginHorizontal();
{
foreach (var pair in mMeshData.Buffers)
{
ESemantic s = pair.Key;
MeshData.VBuffer buff = pair.Value;
width = buff.mDimension * 100;
EditorGUILayout.BeginVertical(mStyles.mPreviewBox, GUILayout.Width(width), GUILayout.Height(height));
{
EditorGUILayout.BeginHorizontal(mStyles.mOLTitle);
{
EditorGUILayout.LabelField(" " + s.ToString(), EditorStyles.boldLabel, GUILayout.Width(width));
}
EditorGUILayout.EndHorizontal();
for (int i = start; i < end; i++)
{
EditorGUILayout.BeginHorizontal();
for (int j = 0; j < buff.mDimension; j++)
{
EditorGUILayout.LabelField(buff.mData[i][j].ToString(), GUILayout.Width(90));
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.EndVertical();
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
}
GUILayout.Label(mMeshData.GetInfo());
EditorGUILayout.EndHorizontal();
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/ToolBox.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ToolBox : EditorWindow {
enum ModuleType
{
ColorConvert,
ObjectCache,
Misc,
Null
}
class Styles
{
// public GUIContent m_WarningContent = new GUIContent(string.Empty, EditorGUIUtility.LoadRequired("Builtin Skins/Icons/console.warnicon.sml.png") as Texture2D);
public GUIStyle mPreviewBox = new GUIStyle("OL Box");
public GUIStyle mPreviewTitle = new GUIStyle("OL Title");
public GUIStyle mPreviewTitle1 = new GUIStyle("OL Box");
public GUIStyle mLoweredBox = new GUIStyle("TextField");
public GUIStyle mHelpBox = new GUIStyle("helpbox");
public GUIStyle mMiniLable = new GUIStyle("MiniLabel");
public GUIStyle mSelected = new GUIStyle("LODSliderRangeSelected");
public GUIStyle mOLTitle = new GUIStyle("OL Title");
public GUIStyle mHLine = new GUIStyle();
public GUIStyle mVLine = new GUIStyle();
public Styles()
{
mLoweredBox.padding = new RectOffset(1, 1, 1, 1);
mPreviewTitle1.fixedHeight = 0;
mPreviewTitle1.fontStyle = FontStyle.Bold;
mPreviewTitle1.alignment = TextAnchor.MiddleLeft;
mHLine.fixedHeight = 1f;
mHLine.margin = new RectOffset(0, 0, 0, 0);
mVLine.fixedWidth = 1f;
mVLine.stretchHeight = true;
mVLine.stretchWidth = false;
}
}
private static Styles mStyles;
public static ToolBox Window = null;
private ModuleType currentModule = ModuleType.ObjectCache;
[MenuItem("GEffect/ToolBox")]
static void AddWindow()
{
//if (Window != null)
// Window.Close();
Window = EditorWindow.GetWindow<ToolBox>(false, "ToolBox");
Window.minSize = new Vector2(350, 200);
Window.Show();
}
int R = 0;
int G = 0;
int B = 0;
List<Object> mObjectList = new List<Object>();
private void test()
{
float t = Mathf.Atan(0.22f);
Debug.Log(t / 3.14 * 180);
}
private bool DrawModuleTitle(string title,ModuleType type)
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
{
bool b = currentModule == type;
string str = b ? "- " : "+ ";
if (GUILayout.Button(str + title, EditorStyles.label))
{
currentModule = b ? ModuleType.Null : type;
}
}
EditorGUILayout.EndHorizontal();
return currentModule == type;
}
private Vector2 scroll = Vector2.zero;
public void OnGUI()
{
if (mStyles == null)
{
mStyles = new Styles();
}
scroll = EditorGUILayout.BeginScrollView(scroll,mStyles.mPreviewBox);
{
if (DrawModuleTitle("ColorConvert", ModuleType.ColorConvert))
{
DrawColorPass("R", ref R);
DrawColorPass("G", ref G);
DrawColorPass("B", ref B);
EditorGUILayout.BeginHorizontal();
{
if (GUILayout.Button("Copy Int", GUILayout.Width(80)))
{
GUIUtility.systemCopyBuffer = R + "," + G + "," + B;
}
float r = R / 255.0f;
float g = G / 255.0f;
float b = B / 255.0f;
if (GUILayout.Button("Copy Float", GUILayout.Width(80)))
{
GUIUtility.systemCopyBuffer = r + "," + g + "," + b;
}
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(30);
}
if (DrawModuleTitle("ObjectCache", ModuleType.ObjectCache))
{
DrawCache();
GUILayout.Space(30);
}
if (DrawModuleTitle("Misc", ModuleType.Misc))
{
if (GUILayout.Button("Test", GUILayout.Width(40)))
{
test();
}
}
}
EditorGUILayout.EndScrollView();
}
private void DrawCache()
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(24);
var newobj = EditorGUILayout.ObjectField(null, typeof(Object), true, GUILayout.Width(150));
if (newobj != null)
{
mObjectList.Add(newobj);
}
}
EditorGUILayout.EndHorizontal();
for (int i = 0, n = mObjectList.Count;i<n;i++)
{
GUILayout.Space(5);
EditorGUILayout.BeginHorizontal();
{
var obj = mObjectList[i];
if (GUILayout.Button("R", EditorStyles.toolbarButton, GUILayout.Width(20)))
{
mObjectList.Remove(obj);
break;
}
var newobj = EditorGUILayout.ObjectField(obj, typeof(Object), true,GUILayout.Width(150));
if (newobj != obj)
{
if (newobj != null)
{
mObjectList[i] = newobj;
}
else
{
mObjectList.Remove(obj);
break;
}
}
}
EditorGUILayout.EndHorizontal();
}
}
private void DrawColorPass(string name, ref int value)
{
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField(name + ":", GUILayout.Width(20));
value = EditorGUILayout.IntSlider(value, 0, 255);
if(GUILayout.Button("C",GUILayout.Width (20)))
{
GUIUtility.systemCopyBuffer = value.ToString();
}
GUILayout.Space(20);
float v = value / 255.0f;
float v1 = EditorGUILayout.FloatField(v,GUILayout.Width(80));
v1 = Mathf.Clamp01(v1);
if (v1 != v)
{
value = Mathf.RoundToInt(v1 * 255);
}
if (GUILayout.Button("C", GUILayout.Width(20)))
{
GUIUtility.systemCopyBuffer = v1.ToString();
}
}
EditorGUILayout.EndHorizontal();
}
}
<file_sep>/Assets/Common/MeshConverter/Editor/ObjSerializer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
namespace UnityEngine
{
public class ObjSerializer
{
private MeshData mMesh;
public MeshData Load(string path)
{
StreamReader reader = null;
try
{
if (string.IsNullOrEmpty(path))
return null;
reader = File.OpenText(path);
}
catch (Exception e)
{
reader.Close();
Debug.LogError("打开文件失败:" + path + "\n" + e.Message);
return null;
}
int id = path.LastIndexOf("/");
string name = path.Substring(id+1);
mMesh = new MeshData(name);
string line = reader.ReadLine();
char[] splits = { ' ', '\t' };
while (line != null)
{
string[] elements = line.Split(splits);
if (elements.Length > 1)
{
switch (elements[0])
{
case "v":
AddData(ESemantic.Position, elements);
break;
case "vt":
AddData(ESemantic.Coord0, elements);
break;
case "vn":
AddData(ESemantic.Normal, elements);
break;
case "f":
AddTrangle(elements);
break;
default:
break;
}
}
line = reader.ReadLine();
}
reader.Close();
return mMesh;
}
private void AddData(ESemantic s, string[] elements)
{
Vector4 v = new Vector4();
for (int i = 1; i < elements.Length; i++)
{
if (i > 4)
break;
v[i - 1] = float.Parse(elements[i]);
}
mMesh.AddData(s, v, elements.Length - 1);
}
private void AddTrangle(string[] elements)
{
if (elements.Length != 4)
{
Debug.LogWarning("三角形解析错误!" + elements.ToString());
return;
}
int[] f = new int[3];
for (int i = 1; i < 4; i++)
{
string ele = elements[i];
int index = ele.IndexOf('/');
if (index > 0)
{
ele = ele.Substring(0, index);
//Debug.LogWarning("三角形解析错误!" + elements.ToString());
//return;
}
f[i - 1] = int.Parse(ele) - 1;
}
mMesh.AddTrangle(f);
}
}
}
<file_sep>/Docs/《一梦江湖》渲染分析.md
# 《一梦江湖》渲染分析
##0x00 前言
《一梦江湖》原名《楚留香》,在去IP化中渲染质量同时也进行了升级,为当前手游市场上同类型游戏渲染的代表作。本文从渲染管线,阴影,光照,GI,后处理等多个角度对本游戏PC和移动两个版本,结合Demo实例具体分析。(图为Demo还原角色)

## 0x01 准备
#### 解析工具
* GPA
* Snapdragon Profiler
PC版本使用GPA渲染分析工具截帧分析,移动平台为小米8手机(高通骁龙845),渲染分析工具为Snapdragon Profiler。
#### Demo 还原平台
* Unity 2018.3.5
研究过程中对游戏角色主要材质着色器在Unity3D引擎进行还原,为了通用性,并未使用SRP,而采样默认渲染管线。
##0x02 渲染管线分析

《一梦江湖》PC渲染流程如上图,为前向渲染管线。移动端中不绘制AO。且移动平台线性空间转Gamma空间在Opaque,Transparent个阶段中执行;而PC中颜色矫正在Combine Bloom阶段。
采用PreZ方式,第一次只写入深度,同时角色单独写入模板。在Opaque阶段ZTest Func 为Equal.
Transparent 绘制前先把ColorRT拷贝出来,然后先绘制如水面,角色眼睛角膜等对象,然后再绘制其余半透明渲染对象。
## 0x03 阴影和AO
《一梦江湖》Shadowmap渲染在3张1024的RT。其中角色Shadow每帧都更新,单独绘制在一张RT上,在光照阶段采样。场景Shadow近处和远处物体分别绘制,在ScreenSpaceShadow阶段分两个Pass采样计算SSShadow。
|Character Shadowmap|Scene Shadowmap 1| Scene Shadowmap2 |
|-|-|-|
||||
场景SSAO在场景ScreenSpaceShadow阶段之后绘制在降分辨率的一张纹理上,模糊之后写入场景ScreenSpaceShadow RT上另一个通道中。
|ScreenSpaceShadow| AO |Blend AO|
|-|-|-|
||||
## 0x04 光照
《一梦江湖》场景和角色受光照不同,主要差别在场景受烘焙GI影响,角色额外受动态GI和一个摄像机方向的虚拟光影响。
###1. 场景光照分析
场景光照主要由以下几部分构成:
* Directional light(Sun)
* Bake GI
* 环境光反射(IBL)
|Lighting |Sun Diffuse|Sun Specular|Bake GI Diffuse|Env Specular|
|-|-|-|-|-|
||||||
**Directional Light**
Lambert漫反射光照模型,GGX BRDF高光模型
**环境光反射**
环境光压缩在一张256 * 256 的纹理上,如图:

采样函数如下:
half3 GetIBLIrradiance(in half Roughness,in float3 R)
{
half3 sampleEnvSpecular=half3(0,0,0);
half MIP_ROUGHNESS=0.17;
half level=Roughness / MIP_ROUGHNESS;
half fSign= R.z > 0;
half fSign2 = fSign * 2 - 1;
R.xy /= (R.z * fSign2 + 1);
R.xy = R.xy * half2(0.25,-0.25) + 0.25 + 0.5 * fSign;
half4 srcColor;
srcColor = tex2Dlod (_EnvMap, half4(R.xy, 0, level));
sampleEnvSpecular= srcColor.rgb * (srcColor.a * srcColor.a * 16.0);
return sampleEnvSpecular;
}
###2. 角色光照分析
* Directional light
* Point light和Spot Light
* 环境光(IBL)
* 摄像机方向上的 Virtual Light
* Dynamic GI
|Sun Diffuse|Sun Specular|Virtual Lit Diffuse|Virtual Lit Specular|
|-|-|-|-|
|||||
|GI Diffuse|Env Specular|Skin Refraction|Lighting|
|-|-|-|-|-|
|||||
** Directional Light **
Directional Light 是游戏中主方向光,投射实时阴影。采用Lambert漫反射光照模型,GGX BRDF高光。
** Point Light **
游戏引擎支持点光源和聚光灯。游戏中在选择角色界面使用1个点光源。本次分析截帧的多个场景下未使用。
** 环境光反射 **
环境光反射与场景相同。
** Virtual Light **
Virtual Light 是游戏中从一个相机方向发出的只对角色作用的较弱的补光,也是平行光,不投射阴影。采用Lambert漫反射光照模型,GGX近似 BRDF高光模型。
** Dynamic GI **
游戏中使用预计算的实时GI,对角色影响。
** Other **
此外头发高光,皮肤,眼球等光照在下文中分别解读。
## 0x05 角色渲染
《一梦江湖》角色分为 身体,头部,头发,眼球(左右),角膜和泪腺,眉毛,睫毛等几个部分。其中身体,头部,眼球为不透明渲染;头发前后分别是镂空渲染和半透明渲染;眉毛和睫毛为半透明渲染,角膜和泪腺为半透明折射渲染。
其模型三角面数如下:
|Name|Body|Head|Eye|Corneal|Eyebrows|Eyelash|Hair mask|Hair Transparent|
|-|-|-|-|-|-|-|-|
|**Mesh**|||||| | | |
|**Triangles**|7066|5396|312|406|312|972|1545|5048|
### Body
角色身体皮肤和衣服并未分开,用Mask贴图区分开来,采用统一的光照。纹理大小为2048。
|Name|Base Color|Normal|Mask|Mix|
|-|-|-|-|-|
|Texture|||||
|Mobile Size|1024|512|512|1024|
|PC Size|2048|2048|512|2048|
* Normal 纹理A通道存储SSSmask.用于区分皮肤和其他部分
* BaseColor RGB为漫反射颜色,A通道为Mask
* Mix 纹理 R通道为Smoothness,G通道为 Metallic,B 通道为AO
* Mask 存储mask值区分布料和其他
* AliasingFactor 粗糙度反走样系数
* EnvStrength 环境光强度系数
* EnvInfo 环境系数,X通道控制雨水对粗糙度的影响,W通道控制环境光强度,Z控制雾影响
* EmissionScale W通道控制虚拟光强度
* VirtualLitColor 虚拟光颜色
* VirtualLitDir 虚拟光方向向量
### Head
1. 角色头部渲染采用Pre-intergrated Skin Shading
2. 妆容唇部采样Crystal纹理叠加高光晶状唇彩
3. NormalMap的A通道为毛孔细节法线遮罩
4. 平行光和GI的透射光,Mix纹理的R通道为通透度
|Name|Base Color|Normal|Detail Normal|Mix|Lut|Crystal|Crystal Mask|
|-|-|-|-|-|-|-|-|
|Texture||||||||
|Size|1024|1024|256|1024|256|512|1024|
|Size|2048|2048|256|2048|256|512|2048|
* BaseColor RGB为漫反射颜色,A通道为Roughness
* Normal 纹理A通道存储毛孔细节Mask.
* Mix 纹理 R通道为透射度,G通道为SSS计算采样Lut图所需的曲率Curvature,B通道为AO
* Lut 皮肤预积分烘焙纹理,采样uv = half2(0.5 * NdotL + 0.5,Curvature),Wrap Mode需设置成Clamp。
* Crystal 为妆容晶状高光纹理
* Crystal Mask 为妆容Mask,RGB通道分别控制眼部,脸颊,嘴唇。
* SSSColor 皮肤透射颜色
* Deail UV Scale 细节法线纹理缩放比例
* Pore Intensity 毛孔细节法线的强度
* SSS Intensity 次表面散射强度
* Roughness Offset BRDF计算采用两层Roughness的算法, RoughnessOffset为第二层roughness的相对第一层的偏移量
* Crystal Color 妆容晶状高光颜色
* Crystal Virtual Lit 妆容晶状高光受虚拟光的强度,0为不受虚拟光影响
* Crystal UVTile 妆容晶状高光纹理采样缩放比例
### Eye
1. 眼球和角膜分层,
2. 眼球Diffuse除了整体的Diffuse光照以外,瞳仁突起亮斑处叠加额外的Diffuse光照。
|Name|Base Color|Normal|Mask|
|-|-|-|-|
|Texture||||
|Mobile Size|128|256|256|
|PC Size|128|256|256|
* BaseColor A通道是瞳仁亮斑遮罩,第二层Diffuse光照对瞳仁亮斑影响。
* Mask G通道是AO,B通道是瞳仁遮罩
### Corneal
角膜和泪腺的着色在不透明渲染完Color Buffer拷贝之后,半透明渲染之前的阶段,采样ColorBuffer混合。
|Name|Base Color|Mix|
|-|-|-|-|
|Texture|||
|Mobile Size|512|512|
|PC Size|512|512|
* BaseColor A通道是角膜和泪腺的遮罩
* Mask R通道是AO,A通道是环境光反射遮罩
### Hair
1. 头发分开两部分,AlphaTest和AlphaBlend。
2. 除了各向同性BRDF以外,也有各向异性高光
3. Virtual Light各向异性高光计算结果叠加在BaseColor中,影响平行光和GI的Diffuse计算。
float virtualAniso = cAnisotropicScale * AnisoSpec(viewDir, viewDir, normalVec, VirtualLitNoL, i.world_tangent.xyz, i.world_binormal.xyz,Roughness_X, Roughness_Y );
BaseColor.rgb += virtualRadiance * virtualAniso;
|Name|Base Color|Normal|Mix|
|-|-|-|-|
|Texture||||
|Mobile Size|1024|1024|1024|
|PC Size|1024|1024|1024|
* BaseColor RGB为漫反射颜色,A通道为alpha
* Mix 纹理 R通道为Smoothness,G通道为 Metallic,B 通道为AO
* Mask 存储mask值区分布料和其他
* AnisotropicScale:各向异性高光强度
* RoughnessX:Tangent方向粗糙度
* RoughnessY:Binormal方向粗糙度
### EyeLash & Eyebrow
眉毛和睫毛为半透明渲染,仅受动态GI和平行光的漫反射光照。
|Name|Eyelash|Eyebrow|
|-|-|-|-|
|Texture|||
|Mobile Size|512|512|
|PC Size|512|512|
<file_sep>/Assets/Common/MeshConverter/Editor/MeshPostConvertClass/MeshPostConvert_BD.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
namespace UnityEditor
{
public class MeshPostConvert_BD : MeshPostConvert
{
private string mSkeletonDataFileName = "";
private bool mUseSkeleton = false;
private List<Vector4> mSkeletonData = new List<Vector4>();
public override void PostConvert(ref MeshData mesh)
{
//UV
MeshData.VBuffer UVBuffer;
if (mesh.Buffers.TryGetValue(ESemantic.Coord0, out UVBuffer))
{
var uvBuffers = UVBuffer.mData;
for (int i = 0; i < uvBuffers.Count; i++)
{
var uv = uvBuffers[i];
uvBuffers[i] = new Vector4(uv.x, 1.0f - uv.y, 0.0f, 0.0f);
//Debug.Log(UVBuffer.mData[i]);
}
}
else
{
Debug.Log("No UV channel can be found");
return;
}
//Normal ,BiNormal,Tangent
MeshData.VBuffer NormalBuffer;
bool hasNormal = mesh.Buffers.TryGetValue(ESemantic.Normal, out NormalBuffer);
if (!hasNormal)
{
Debug.Log("No Normal channel can be found");
return;
}
else
{
if (NormalBuffer.mDimension < 4)
{
Debug.Log("No Normal.w can be found");
return;
}
List<Vector4> normals = new List<Vector4>();
List<Vector4> tangents = new List<Vector4>();
List<Vector4> binormals = new List<Vector4>();
for (int i = 0; i < NormalBuffer.mData.Count; i++)
{
var normalData = NormalBuffer.mData[i];
Vector3 tan = new Vector3(0.0f, 0.0f, 0.0f),
bin = new Vector3(0.0f, 0.0f, 0.0f),
nor = new Vector3(0.0f, 0.0f, 0.0f);
DecodeTangentBinormal(normalData, ref tan, ref bin, ref nor);
normals.Add(new Vector4(nor.x, nor.y, nor.z, 0.0f));
tangents.Add(new Vector4(tan.x, tan.y, tan.z, 0.0f));
binormals.Add(new Vector4(bin.x, bin.y, bin.z, 0.0f));
}
NormalBuffer.mData = normals;
NormalBuffer.mDimension = 3;
MeshData.VBuffer TangentBuffer;
bool hasTangent = mesh.Buffers.TryGetValue(ESemantic.Tangent, out TangentBuffer);
if (!hasTangent)
{
TangentBuffer = new MeshData.VBuffer();
mesh.Buffers.Add(ESemantic.Tangent, TangentBuffer);
}
TangentBuffer.mData = tangents;
TangentBuffer.mDimension = 3;
MeshData.VBuffer BiNormalBuffer;
bool hasBiNormal = mesh.Buffers.TryGetValue(ESemantic.BNormal, out BiNormalBuffer);
if (!hasBiNormal)
{
BiNormalBuffer = new MeshData.VBuffer();
mesh.Buffers.Add(ESemantic.BNormal, BiNormalBuffer);
}
BiNormalBuffer.mData = binormals;
BiNormalBuffer.mDimension = 3;
}
//Position
MeshData.VBuffer posBuf;
if (!mesh.Buffers.TryGetValue(ESemantic.Position, out posBuf))
return;
for (int i = 0; i < posBuf.mData.Count; i++)
{
Vector4 pos = posBuf.mData[i];
pos.y += 2;
pos.w = 1;
posBuf.mData[i] = pos;
}
if (mUseSkeleton)
{
UseSkeletonData(ref mesh);
}
mesh.Buffers.Remove(ESemantic.Coord1);
mesh.Buffers.Remove(ESemantic.Coord2);
mesh.Buffers.Remove(ESemantic.Coord3);
mesh.Buffers.Remove(ESemantic.Coord4);
}
static void SinCosBuild(float Angle, out float _sinout, out float _cosout)
{
_sinout = Mathf.Sin(Angle);
_cosout = Mathf.Cos(Angle);
}
//
static public void DecodeTangentBinormal(Vector4 Tangents, ref Vector3 Tangent, ref Vector3 BiNormal, ref Vector3 Normal)
{
Vector4 Angles = Tangents * Mathf.PI * 2.0f - new Vector4(Mathf.PI, Mathf.PI, Mathf.PI, Mathf.PI);
float tLongSin = 0, tLongCos = 0, tLatSin = 0, tLatCos = 0,
bLongSin = 0, bLongCos = 0, bLatSin = 0, bLatCos = 0;
SinCosBuild(Angles.x, out tLongSin, out tLongCos);
SinCosBuild(Angles.y, out tLatSin, out tLatCos);
SinCosBuild(Angles.z, out bLongSin, out bLongCos);
SinCosBuild(Angles.w, out bLatSin, out bLatCos);
Tangent = new Vector3(Mathf.Abs(tLatSin) * tLongCos, Mathf.Abs(tLatSin) * tLongSin, tLatCos);
BiNormal = new Vector3(Mathf.Abs(bLatSin) * bLongCos, Mathf.Abs(bLatSin) * bLongSin, bLatCos);
Normal = Vector3.Cross(Tangent, BiNormal);
Vector3 tmp;
if (Angles.w > 0.0)
{
tmp = new Vector3(Normal.x, Normal.y, Normal.z);
}
else
{
tmp = new Vector3(-Normal.x, -Normal.y, -Normal.z);
}
Normal = tmp;
}
private bool LoadSkeletonData()
{
mSkeletonData.Clear();
StreamReader reader = null;
mSkeletonDataFileName = "D:/Unity Projects/BlackDesert_Demo/Assets/BlackDesert/BD_SkeletonB.txt";
try
{
if (string.IsNullOrEmpty(mSkeletonDataFileName))
return false;
reader = File.OpenText(mSkeletonDataFileName);
}
catch (Exception e)
{
reader.Close();
Debug.LogError("Open file :" + mSkeletonDataFileName + "\n" + e.Message);
return false;
}
string line = reader.ReadLine();
char[] splits = { ' ', '\t' };
while (line != null)
{
string[] elements = line.Split(splits);
if (elements.Length == 4)
{
Vector4 v = new Vector4();
for (int i = 0; i < 4; i++)
{
v[i] = float.Parse(elements[i]);
}
mSkeletonData.Add(v);
}
line = reader.ReadLine();
}
reader.Close();
return true;
}
public bool UseSkeletonData(ref MeshData mesh)
{
MeshData.VBuffer posBuf;
MeshData.VBuffer normalBuf;
MeshData.VBuffer tangentBuf;
MeshData.VBuffer bnormalBuf;
MeshData.VBuffer idBuf;
MeshData.VBuffer weightBuf;
if (!mesh.Buffers.TryGetValue(ESemantic.Position, out posBuf))
return false;
if (!mesh.Buffers.TryGetValue(ESemantic.Coord1, out idBuf))
return false;
if (!mesh.Buffers.TryGetValue(ESemantic.Coord2, out weightBuf))
return false;
bool hasNormal = mesh.Buffers.TryGetValue(ESemantic.Normal, out normalBuf);
bool hasBnormal = mesh.Buffers.TryGetValue(ESemantic.BNormal, out bnormalBuf);
bool hasTangent = mesh.Buffers.TryGetValue(ESemantic.Tangent, out tangentBuf);
int num = posBuf.mData.Count;
for (int i = 0; i < num; i++)
{
Matrix4x4 MSkin = Matrix4x4.zero;
Vector4 pos = posBuf.mData[i];
Vector4 blendIndex = idBuf.mData[i];
Vector4 blendWeight = weightBuf.mData[i];
int[] id = { Mathf.RoundToInt(blendIndex.x) * 3,
Mathf.RoundToInt(blendIndex.y) * 3,
Mathf.RoundToInt(blendIndex.z) * 3,
Mathf.RoundToInt(blendIndex.w) * 3};
Vector4 mSkinRow0 = GetData(id[0]) * blendWeight.x;
Vector4 mSkinRow1 = GetData(id[0] + 1) * blendWeight.x;
Vector4 mSkinRow2 = GetData(id[0] + 2) * blendWeight.x;
Vector4 mSkinRow3 = new Vector4(0, 0, 0, blendWeight.x);
mSkinRow0 += GetData(id[1]) * blendWeight.y;
mSkinRow1 += GetData(id[1] + 1) * blendWeight.y;
mSkinRow2 += GetData(id[1] + 2) * blendWeight.y;
mSkinRow3.w += blendWeight.y;
mSkinRow0 += GetData(id[2]) * blendWeight.z;
mSkinRow1 += GetData(id[2] + 1) * blendWeight.z;
mSkinRow2 += GetData(id[2] + 2) * blendWeight.z;
mSkinRow3.w += blendWeight.z;
mSkinRow0 += GetData(id[3] ) * blendWeight.w;
mSkinRow1 += GetData(id[3] + 1) * blendWeight.w;
mSkinRow2 += GetData(id[3] + 2) * blendWeight.w;
mSkinRow3.w += blendWeight.w;
MSkin.SetRow(0, mSkinRow0);
MSkin.SetRow(1, mSkinRow1);
MSkin.SetRow(2, mSkinRow2);
MSkin.SetRow(3, mSkinRow3);
//MSkin = MSkin.transpose;
Vector4 newpos = Vector4.one;
newpos = MSkin * pos;
posBuf.mData[i] = newpos;
Vector4 oldV;
Vector4 newV;
if (hasNormal)
{
oldV = normalBuf.mData[i];
newV = Vector4.zero;
newV = MSkin * oldV;
normalBuf.mData[i] = newV;
}
if (hasTangent)
{
oldV = tangentBuf.mData[i];
newV = Vector4.zero;
newV = MSkin * oldV;
tangentBuf.mData[i] = newV;
}
if (hasBnormal)
{
oldV = bnormalBuf.mData[i];
newV = Vector4.zero;
newV = MSkin * oldV;
bnormalBuf.mData[i] = newV;
}
}
Debug.Log("Vertex = " + posBuf.mData.Count);
return true;
}
private Vector4 GetData(int index)
{
Vector4 ret = new Vector4();
ret = mSkeletonData[index];
return ret;
}
public override void OnGUI()
{
base.OnGUI();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Skeleton Data:", GUILayout.Width(100));
mUseSkeleton = EditorGUILayout.Toggle(mUseSkeleton);
if (mUseSkeleton)
{
if (GUILayout.Button(mSkeletonDataFileName, EditorStyles.textField, GUILayout.Width(500)))
{
int id = mSkeletonDataFileName.LastIndexOf("/");
string path = mSkeletonDataFileName.Substring(0, id + 1);
path = EditorUtility.OpenFilePanel("select Skeleton Data file", path, "*");
if (!string.IsNullOrEmpty(path))
{
mSkeletonDataFileName = path;
}
LoadSkeletonData();
}
}
EditorGUILayout.LabelField(mSkeletonData.Count.ToString(), GUILayout.Width(50));
}
EditorGUILayout.EndHorizontal();
}
}
} | d2ab3f8bb7f48097c690dfe136f0a4f279d422f2 | [
"Markdown",
"C#"
] | 15 | C# | SincemeTom/Yimengjianghu | 69faa47485f09659ac19cd9a6bc99fdba18b6cad | 2cf41d6b63284f2d90771106b65b93b5a4dc5cae |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CarRequest
{
public partial class frmRentAdd : Form
{
Dictionary<string, string> _item = new Dictionary<string, string>();
Dictionary<string, string> _itemcar = new Dictionary<string, string>();
public void arabalistele()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Marka,Model,ID,IsAvailable FROM tblCar WHERE IsAvailable=1 ";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
_itemcar.Add(dr["ID"].ToString(), dr["Marka"].ToString());
//if (Convert.ToBoolean(_itemcar["IsAvailable"] == "0"))
comboBox14.Items.Add(dr["Marka"].ToString() + " " + dr["Model"].ToString());
}
conn.Close();
}
public void personListele()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Name,ID,LastName FROM tblPerson";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
_item.Add(dr["ID"].ToString(), dr["Name"].ToString());
comboBox2.Items.Add(dr["Name"].ToString() + " " + dr["LastName"].ToString());
// " " +dr["LastName"].ToString());
}
conn.Close();
}
public frmRentAdd()
{
InitializeComponent();
personListele();
arabalistele();
}
private void frm_fkPerson_TextChanged(object sender, EventArgs e)
{
}
private void ResetScreen()
{
comboBox14.Text = string.Empty;
comboBox2.Text = string.Empty;
frm_fkCar.Text = string.Empty;
frm_fkPerson.Text = string.Empty;
frm_fkIncident.Text = string.Empty;
frm_KM.Text = string.Empty;
frmStart_time.Text = string.Empty;
frmEnd_Time.Text = string.Empty;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
DBActions.AddRentt(int.Parse(frm_fkPerson.Text), Convert.ToDateTime(frmStart_time.Text), Convert.ToDateTime(frmEnd_Time.Text));
//int.Parse(frm_KM.Text), int.Parse(frm_fkCar.Text)
ResetScreen();
MessageBox.Show("TALEBİNİZ İLETİLMİŞTİR...");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void frm_fkIncident_TextChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void frmCombobox(object sender, EventArgs e)
{
}
public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//Person list
private void comboBox2_SelectedIndexChanged_1(object sender, EventArgs e)
{
foreach (var it in _item)
{
if (it.Value.Equals(comboBox2.Text.Split(' ')[0]))
{
frm_fkPerson.Text = it.Key.ToString();
}
}
}
private void frmRentAdd_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void frm_fkCar_TextChanged(object sender, EventArgs e)
{
}
// Car list
private void comboBox14_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var it in _itemcar)
{
if (it.Value.Equals(comboBox14.Text.Split(' ')[0]))
{
frm_fkCar.Text = it.Key.ToString();
}
}
}
private void frm_fkIncident_TextChanged_1(object sender, EventArgs e)
{
}
private void frm_KM_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarRequest
{
static class DBActions
{
// kolaylık olması bakımından tanımlanmış global değişkenler
static string connectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
internal static void AddRent(int v1, DateTime dateTime1, DateTime dateTime2)
{
throw new NotImplementedException();
}
//Kişileri veri tabanına ekleyen fonksiyon
public static void AddPerson(string name, string lastname, int persID, bool isadmin)
{
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//INSERT INTO tblPerson (Name,Lastname,PersID,IsAdmin) VALUES (@name,@lastname,@persid,@isadmin)
// Connect to DB
con = new SqlConnection(connectionString);
cmd = new SqlCommand("addPerson", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@lastname", lastname);
cmd.Parameters.AddWithValue("@persid", persID);
cmd.Parameters.AddWithValue("@isadmin", isadmin);
if (con.State != System.Data.ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
try
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Dispose();
}
}
catch (Exception)
{
}
}
}
//Kaza raporlarını veri tabanına giren fonksiyon
public static void AddAccident(string Description,bool RepairRequired,DateTime RepairTime)
{
SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = new SqlConnection(connectionString);
con.Open();
//INSERT INTO tblIncident (Description,RepairRequired,RepairTime) VALUES (@description,@repairrequired,@repairTime)
cmd = new SqlCommand("acientAdd",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@description", Description);
cmd.Parameters.AddWithValue("@repairrequired",RepairRequired );
cmd.Parameters.AddWithValue("@repairTime", RepairTime);
if (con.State != System.Data.ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
try
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Dispose();
}
}
catch (Exception)
{
}
}
}
// BOSS WROTE THİS PART.
internal static DataTable talepEtArama(int personID)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adp = null;
DataTable ret = null;
try
{
//SELECT * FROM tblRent WHERE fkPerson=@personID and KM IS NULL and fkCar IS NULL
con = new SqlConnection(connectionString);
cmd = new SqlCommand("talepEtArama", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@personID", personID);
ret = new DataTable("GenericTable");
adp = new SqlDataAdapter(cmd);
adp.Fill(ret);
}
catch (Exception ex)
{
//TODO
//Log hazırla
}
return ret;
}
internal static DataTable talepEtKaydet(DateTime StartDate,DateTime EndDate,int Km, int fkCar,int uniqueID)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adp = null;
DataTable ret = null;
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("talepEtKaydet", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StartDate",StartDate);
cmd.Parameters.AddWithValue("@EndDate", EndDate);
cmd.Parameters.AddWithValue("@Km", Km);
cmd.Parameters.AddWithValue("@fkCar", fkCar);
cmd.Parameters.AddWithValue("@uniqueID", uniqueID);
ret = new DataTable("GenericTable");
adp = new SqlDataAdapter(cmd);
adp.Fill(ret);
}
catch(Exception ex)
{
}
return ret;
}
internal static DataTable talepEtAraba(int carID)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adp = null;
DataTable ret = null;
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("talepEtAraba", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@carID", carID);
ret = new DataTable("GenericTable");
adp = new SqlDataAdapter(cmd);
adp.Fill(ret);
}
catch (Exception ex)
{
// MessageBox.Show("hob");
}
return ret;
}
//Eklenecek arabanın bilgilerini veritabanına giren fonksiyon
public static void AddCar(int fkPerson,string marka,string model,DateTime rentStart,DateTime rentEnd,string plaka,int lastKm,bool available )
{
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//INSERT INTO tblCar(fkPerson,Marka,Model,RentStart,RentEnd,Plaka,LastKM,IsAvailable) VALUES (@fkPerson,@marka,@model,@rentStart,@rentEnd,@plaka,@lastkm,@available)
con = new SqlConnection(connectionString);
cmd = new SqlCommand("addCar", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@fkPerson", fkPerson);
cmd.Parameters.AddWithValue("@marka", marka);
cmd.Parameters.AddWithValue("@model", model);
cmd.Parameters.AddWithValue("@rentStart", rentStart);
cmd.Parameters.AddWithValue("@rentEnd", rentEnd);
cmd.Parameters.AddWithValue("@plaka", plaka);
cmd.Parameters.AddWithValue("@lastkm", lastKm);
cmd.Parameters.AddWithValue("@available", available);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
catch(Exception)
{
throw;
}
finally
{
try
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Dispose();
}
}
catch (Exception)
{
}
}
}
// Talep etme formundaki comboBox'a gelen arabaları listeliyor.
// Talep edilen aracın bilgilerini veritabanına giren fonksiyon
public static void AddRentt(int fkPerson,DateTime StartDate,DateTime EndDate)
{
SqlConnection con = null;
SqlCommand cmd = null;
try
{
//INSERT INTO tblRent (fkPerson,StartDate,EndDate) VALUES (@fkPerson,@StartDate,@EndDate)
con = new SqlConnection(connectionString);
cmd = new SqlCommand("addRent", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@fkPerson", fkPerson);
cmd.Parameters.AddWithValue("@StartDate", StartDate);
cmd.Parameters.AddWithValue("@EndDate", EndDate);
if (con.State != System.Data.ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
try
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Dispose();
}
}
catch (Exception)
{
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarRequest
{
public partial class frmPersonAdd : Form
{
public frmPersonAdd()
{
InitializeComponent();
}
// Kayıt butonuna tıklandığında db actions dan add persona bağlanıp veritabanına veri giren buton
private void btnSave_Click(object sender, EventArgs e)
{
try
{
DBActions.AddPerson(txtName.Text, txtLastname.Text, int.Parse(txtPersID.Text), chkIsadmin.Checked);
ResetScreen();
MessageBox.Show("KİŞİ SİSTEME BAŞARIYLA EKLENMİŞİR...");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// veri tabanına
private void ResetScreen()
{
txtName.Text = string.Empty;
txtLastname.Text = string.Empty;
txtPersID.Text = string.Empty;
chkIsadmin.Checked = false;
}
private void txtName_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CarRequest
{
public partial class TalepOnayla : Form
{
// kolaylık olması bakımından tanımlanmış global değişkenler
static string connectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
Dictionary<string, string> _item = new Dictionary<string, string>();
Dictionary<string, string> _itemcar = new Dictionary<string, string>();
Dictionary<string, string> _itemOther = new Dictionary<string, string>();
Dictionary<string, string> _itemcarr = new Dictionary<string, string>();
SqlCommand cmd = new SqlCommand();
// Formumuzun çalıştığı ana fonksiyonumuz
public TalepOnayla()
{
InitializeComponent();
personListeleme();
arabalistele();
}
// talep etme formunda kullanılan arama yapan fonksiyon
//public void talepEtArama()
//{
// SqlConnection baglanti = new SqlConnection(connectionString);
// baglanti.Open();
// string arama = "SELECT * FROM tblRent WHERE fkPerson=@personID and KM IS NULL and fkCar IS NULL";
// SqlCommand komut = new SqlCommand(arama, baglanti);
// komut.Parameters.AddWithValue("@personID", textBox2.Text);
// komut.ExecuteNonQuery();
// SqlDataReader dr = komut.ExecuteReader();
// if (dr.Read())
// {
// dateTimePicker1.Text = dr["StartDate"].ToString();
// dateTimePicker2.Text = dr["EndDate"].ToString();
// textBox5.Text = dr["ID"].ToString();
// // Application.DoEvents();
// // comboBox1.Items.Remove(comboBox1.SelectedItem);
// }
// else
// MessageBox.Show("Arama TAMAMLANAMADI...");
// baglanti.Close();
//}
// talep etme formunda kullanılan arama yapan fonksiyon
public void talepEtArama()
{
DataTable dt = DBActions.talepEtArama(int.Parse(textBox2.Text));
dateTimePicker1.Text = dt.Rows[0]["StartDate"].ToString();
dateTimePicker2.Text = dt.Rows[0]["EndDate"].ToString();
textBox5.Text = dt.Rows[0]["ID"].ToString();
}
// talep etme formunda kullanılan kaydetmeye yarayan fonksiyon
public void talepEtKaydet()
{
DBActions.talepEtKaydet(Convert.ToDateTime(dateTimePicker1.Text),Convert.ToDateTime(dateTimePicker2.Text),int.Parse(kiloMetre.Text),int.Parse(textBox1.Text),int.Parse(textBox5.Text));
// DataTable dt =
//dateTimePicker1.Text = dt.Rows[0]["StartDate"].ToString();
//dateTimePicker2.Text = dt.Rows[0]["EndDate"].ToString();
//kiloMetre.Text = dt.Rows[0]["Km"].ToString();
//textBox1.Text = dt.Rows[0]["fkCar"].ToString();
//textBox5.Text = dt.Rows[0]["uniqueID"].ToString();
}
// talep etme kısmında araba vermeyi sağlayan fonksiyon
public void talepEtAraba()
{
DBActions.talepEtAraba(int.Parse(textBox1.Text));
// textBox1.Text = dt.Rows[0]["carID"].ToString();
}
// Arama butonunun çalıştığı fonksiyon
private void button1_Click_1(object sender, EventArgs e)
{
talepEtArama();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
// Person isimlerinin gözüktüğü ve seçilmenin yapıldığı ComboBox
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var it in _itemOther)
{
if (it.Value.Equals(comboBox1.Text.Split(' ')[0]))
{
textBox2.Text = it.Key.ToString();
}
}
}
public void talepEtArabaListele()
{
}
// Combobox ın gözüken arabaların veritabanından çekilmesini sağlayan fonksiyon
public void arabalistele()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Marka,Model,ID,IsAvailable,Plaka FROM tblCar WHERE IsAvailable=1 ";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
// cmd.Parameters.AddWithValue("@CarID", textBox1.Text);
while (dr.Read())
{
_itemcar.Add(dr["ID"].ToString(), dr["Model"].ToString());
// _itemcarr.Add(dr["ID"].ToString(), dr["Model"].ToString());
//if (Convert.ToBoolean(_itemcar["IsAvailable"] == "0"))
comboBox2.Items.Add(dr["Model"].ToString() + " - (" + dr["Marka"].ToString() + ") ---------" + dr["Plaka"].ToString());
}
conn.Close();
}
// Formlarda girilen bilgileri veritabanında güncelliyor.
private void button1_Click(object sender, EventArgs e)
{
talepEtAraba();
talepEtKaydet();
ResetScreen();
MessageBox.Show("TALEBİ ONAYLADINIZ ..!");
this.Refresh();
}
// Form kaydedildikten sonra formların içinin boşaltılmasını sağlıyor
private void ResetScreen()
{
comboBox1.Text = string.Empty;
comboBox2.Text = string.Empty;
textBox2.Text = string.Empty;
textBox1.Text = string.Empty;
kiloMetre.Text = string.Empty;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
}
private void txtBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
// arabaların içinde gözüktüğü combobox arabalisteleme fonksiyonunu kullanıyor
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var it in _itemcar)
{
if (it.Value.Equals(comboBox2.Text.Split(' ')[0]))
{
textBox1.Text = it.Key.ToString();
}
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void TalepOnayla_Load(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void comboBox1_SizeChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
this.Refresh();
foreach (var it in _itemOther)
{
if (it.Value.Equals(comboBox1.Text.Split(' ')[0]))
{
this.Refresh();
textBox2.Text = it.Key.ToString();
}
}
}
private void textBox2_TextChanged_1(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
// Combo box üzerindeki isimleri getiren textbox'a atan fonksiyon
public void personListeleme()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT DISTINCT Y.Name,Y.ID,Y.LastName,K.StartDate,K.EndDate,K.ID FROM tblRent K, tblPerson Y WHERE K.fkPerson = Y.ID and K.KM IS NULL ";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
var sdf = new SqlParameter("@PersonID", textBox2.Text.ToString());
cmd.Parameters.Add(sdf);
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
// _itemOther.Add(dr["ID"].ToString(), dr["Name"].ToString());
if (!_itemOther.ContainsKey(dr["ID"].ToString()))
{
_itemOther.Add(dr["ID"].ToString(), dr["Name"].ToString());
comboBox1.Items.Add(dr["Name"].ToString() + " " + dr["LastName"].ToString());
}
}
conn.Close();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged_1(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CarRequest
{
public partial class FrmCarAdd : Form
{
Dictionary<string, string> _item = new Dictionary<string, string>();
public FrmCarAdd()
{
InitializeComponent();
personelListele();
}
// veri tabanındaki insanların isimlerini listeleyen fonksiyon
public void personelListele()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Name,ID,Lastname FROM tblPerson";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
_item.Add(dr["ID"].ToString(), dr["Name"].ToString());
comboBox3.Items.Add(dr["Name"].ToString() + " " + dr["LastName"].ToString());
}
conn.Close();
}
private void label2_Click(object sender, EventArgs e)
{
}
// Form kayıt edildikten sonra textboxların içinin boşaltılmasını sağlayan fonksiyon
private void ResetScreen()
{
comboBox3.Text = string.Empty;
fkPerson.Text = string.Empty;
marka.Text = string.Empty;
model.Text = string.Empty;
rentStart.Text = string.Empty;
rentEnd.Text = string.Empty;
Plaka.Text = string.Empty;
lastKM.Text = string.Empty;
chckavailable.Checked = false;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void rentStart_ValueChanged(object sender, EventArgs e)
{
}
private void LastKM_TextChanged(object sender, EventArgs e)
{
}
private void Plaka_TextChanged(object sender, EventArgs e)
{
}
private void FrmCarAdd_Load(object sender, EventArgs e)
{
}
// Kayıt butonunun tıklandığında içinde yapılacakların belirlendiği fonksiyon
private void btnSave_Click(object sender, EventArgs e)
{
try
{
DBActions.AddCar(int.Parse(fkPerson.Text), marka.Text, model.Text, Convert.ToDateTime(rentStart.Text), Convert.ToDateTime(rentEnd.Text), Plaka.Text, int.Parse(lastKM.Text), chckavailable.Checked);
ResetScreen();
MessageBox.Show("ARAÇ BAŞARIYLA SİSTEME EKLENDİ...");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void fkPerson_TextChanged(object sender, EventArgs e)
{
}
private void fkPerson_TextChanged_1(object sender, EventArgs e)
{
}
// kişi listeleyen combobox
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var it in _item)
{
if (it.Value.Equals(comboBox3.Text.Split(' ')[0]))
{
fkPerson.Text = it.Key.ToString();
}
}
}
private void label5_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarRequest
{
public partial class mainForm : Form
{
frmPersonAdd frmP;
FrmCarAdd frmC;
frmIncıdentAdd frmA;
frmRentAdd frmR;
ListCar lstC;
ListPerson lstP;
TalepOnayla tlpO;
GelenAraçKaydet glnA;
public mainForm()
{
InitializeComponent();
}
private void miAddPerson_Click(object sender, EventArgs e)
{
if (frmP == null)
{
frmP = new frmPersonAdd();
frmP.MdiParent = this;
frmP.Show();
frmP.FormClosed += FrmP_FormClosed;
}
else
{
return;
}
}
private void miAddCar_Click(object sender, EventArgs e)
{
}
// Araba Eklemeyi sağlayan method
private void miAddCar_Click_1(object sender, EventArgs e)
{
if (frmC == null)
{
frmC = new FrmCarAdd();
frmC.MdiParent = this;
frmC.Show();
frmC.FormClosed += frmC_FormClosed;
}
else
{
return;
}
}
private void kazaEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (frmA == null)
{
frmA = new frmIncıdentAdd();
frmA.MdiParent = this;
frmA.Show();
frmA.FormClosed += frmA_FormClosed;
}
else
{
return;
}
}
private void işlemlerToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void miTalep_Click(object sender, EventArgs e)
{
if (frmR == null)
{
frmR = new frmRentAdd();
frmR.MdiParent = this;
frmR.Show();
frmR.FormClosed += FrmR_FormClosed;
}
else
{
return;
}
}
private void işlemlerToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void kişileriListeleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (lstP == null)
{
lstP = new ListPerson();
lstP.MdiParent = this;
lstP.Show();
lstP.ListePerson();
lstP.FormClosed += lstP_FormClosed;
}
else
{
return;
}
}
private void arabalarıListeleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (lstC == null)
{
lstC = new ListCar();
lstC.MdiParent = this;
lstC.Show();
lstC.FormClosed += lstC_FormClosed;
}
else
{
return;
}
}
private void mainForm_Load(object sender, EventArgs e)
{
}
//Talep onaylama formuna tıklanınca açılmasını sağlıyan method
private void miTalepApprove_Click(object sender, EventArgs e)
{
if (tlpO == null)
{
tlpO = new TalepOnayla();
tlpO.MdiParent = this;
tlpO.Show();
tlpO.FormClosed += tlpO_FormClosed;
}
else
{
return;
}
}
// Gelen araç kaydetme ..
private void miRecordIncoming_Click(object sender, EventArgs e)
{
if (glnA == null)
{
glnA = new GelenAraçKaydet();
glnA.MdiParent = this;
glnA.Show();
glnA.FormClosed += glnA_FormClosed;
}
else
{
return;
}
}
//Formlar açıldıktan sonra tekrar kapatılıp açılmasını sağlayan method
private void tlpO_FormClosed(object sender, FormClosedEventArgs e)
{
tlpO.Dispose();
tlpO = null;
}
private void frmC_FormClosed(object sender, FormClosedEventArgs e)
{
frmC.Dispose();
frmC = null;
}
private void frmA_FormClosed(object sender, FormClosedEventArgs e)
{
frmA.Dispose();
frmA = null;
}
public void FrmP_FormClosed(object sender, FormClosedEventArgs e)
{
frmP.Dispose();
frmP = null;
}
public void FrmR_FormClosed(object sender, FormClosedEventArgs e)
{
frmR.Dispose();
frmR = null;
}
private void lstP_FormClosed(object sender, FormClosedEventArgs e)
{
lstP.Dispose();
}
private void lstC_FormClosed(object sender, FormClosedEventArgs e)
{
lstC.Dispose();
}
private void glnA_FormClosed(object sender, FormClosedEventArgs e)
{
glnA.Dispose();
glnA = null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarRequest
{
public partial class GelenAraçKaydet : Form
{
static string connectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
Dictionary<string, string> _item = new Dictionary<string, string>();
Dictionary<string, string> _itemcar = new Dictionary<string, string>();
Dictionary<string, string> _itemOther = new Dictionary<string, string>();
Dictionary<string, string> _itemcarr = new Dictionary<string, string>();
SqlCommand cmd = new SqlCommand();
public GelenAraçKaydet()
{
InitializeComponent();
personListeleme();
}
public void personListeleme()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT DISTINCT Y.Name,Y.ID,Y.LastName,K.StartDate,K.EndDate,K.ID FROM tblRent K, tblPerson Y WHERE K.fkPerson = Y.ID and K.fkIncidents IS NULL ";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@PersonID", textBox1.Text.ToString());
// SqlCommand komut = "UPDATE tblRent SET EndDate=@now Where @PersonID=ID"
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
// _itemOther.Add(dr["ID"].ToString(), dr["Name"].ToString());
if (!_itemOther.ContainsKey(dr["ID"].ToString()))
{
_itemOther.Add(dr["ID"].ToString(), dr["Name"].ToString());
comboBox1.Items.Add(dr["Name"].ToString() + " " + dr["LastName"].ToString());
}
}
conn.Close();
}
private void frmdescription_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection baglanti = new SqlConnection(connectionString);
baglanti.Open();
string güncelleme = "UPDATE tblRent SET fkIncidents=@fkIncident WHERE ID=@rentID";
SqlCommand komut = new SqlCommand(güncelleme, baglanti);
komut.Parameters.AddWithValue("@fkIncident", textBox3.Text);
komut.Parameters.AddWithValue("@rentID", textBox2.Text);
komut.ExecuteNonQuery();
ResetScreen();
// komut.ExecuteNonQuery();
MessageBox.Show("BAŞARIYLA KAYDEDİLDİ....");
// ResetScreen();
baglanti.Close();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void repairTime_ValueChanged(object sender, EventArgs e)
{
}
private void repairCheck_CheckedChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var it in _itemOther)
{
if (it.Value.Equals(comboBox1.Text.Split(' ')[0]))
{
this.Refresh();
textBox1.Text = it.Key.ToString();
}
}
}
private void button1_Click(object sender, EventArgs e) {
SqlConnection baglanti = new SqlConnection(connectionString);
baglanti.Open();
string arama = "SELECT * FROM tblRent WHERE fkPerson=@personID and fkIncidents IS NULL";
SqlCommand komut = new SqlCommand(arama, baglanti);
komut.Parameters.AddWithValue("@personID", textBox1.Text);
komut.ExecuteNonQuery();
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["ID"].ToString();
}
else
MessageBox.Show("Arama TAMAMLANAMADI...");
baglanti.Close();
}
private void ResetScreen()
{
comboBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox1.Text = string.Empty;
frmdescription.Text = string.Empty;
repairTime.Text = string.Empty;
repairCheck.Text = string.Empty;
textBox3.Text = string.Empty;
}
private void GelenAraçKaydet_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
ResetScreen();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
DBActions.AddAccident(frmdescription.Text, repairCheck.Checked, Convert.ToDateTime(repairTime.Text));
SqlConnection baglanti = new SqlConnection(connectionString);
baglanti.Open();
string arama = "SELECT ID FROM tblIncident WHERE Description = @description";
SqlCommand komut = new SqlCommand(arama, baglanti);
komut.Parameters.AddWithValue("@description", frmdescription.Text);
// komut.ExecuteNonQuery();
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
textBox3.Text = dr["ID"].ToString();
}
else
MessageBox.Show("Arama TAMAMLANAMADI...");
// ResetScreen();
baglanti.Close();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void label8_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CarRequest
{
public partial class ListCar : Form
{
static string connectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
public ListCar()
{
InitializeComponent();
}
public void ListeCar()
{
SqlConnection con = new SqlConnection(connectionString);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tblCar", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
ListeCar();
}
}
}
<file_sep># CarRequest
Bu proje Staj dönemimde 18.06.2018-13.07.2018 arasında StackPole şirketinde veritabanı (Microsoft Server SQL) ve c# programlama dilinde kendimi geliştirmem adına
geliştirmekte olduğum bir projedir .
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarRequest
{
public partial class frmIncıdentAdd : Form
{
// static string connectionString = "Server=EPDI-4W68LX1\\SQLEXPRESS;Initial Catalog=CarRequest;Integrated Security=SSPI;";
Dictionary<string, string> _itemOther = new Dictionary<string, string>();
public frmIncıdentAdd()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void accidentId_TextChanged(object sender, EventArgs e)
{
}
private void resetScreen()
{
frmdescription.Text = string.Empty;
repairCheck.Checked = false;
repairTime.Text = string.Empty;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
DBActions.AddAccident(frmdescription.Text , repairCheck.Checked,Convert.ToDateTime(repairTime.Text));
resetScreen();
MessageBox.Show("GEÇMİŞ OLSUN");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void frmIncıdentAdd_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged_1(object sender, EventArgs e)
{
}
}
}
| 5eb5cb976298e0767a9ed805269f771a7f890005 | [
"Markdown",
"C#"
] | 10 | C# | sercangl/CarRequest | 351026dd121e1284c5e681eea9096729e3d09abd | c831a6aeac62e32e751f52b076fcfb3a6332654b |
refs/heads/master | <file_sep>using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
public float speed;
private Rigidbody rb;
private int score;
public Text countText;
private List<float[]> pos;
private int lives;
public Text livesText;
public Text gameOverText;
public Button playBtn;
private float timeLeft;
public Text timeLeftText;
private float _Time;
public AudioClip fail;
public AudioClip gameOver;
public AudioClip success;
void Start(){
rb = GetComponent<Rigidbody> ();
gameOverText.text = "Pill Game";
gameObject.SetActive(false);
playBtn.onClick.AddListener(delegate ()
{
AudioSource.PlayClipAtPoint(success, transform.position);
startGame();
});
}
void FixedUpdate(){
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other) {
if (lives == 0)
{
endGame();
}
else
{
if (other.gameObject.CompareTag("Pill"))
{
failedCollision();
AudioSource.PlayClipAtPoint(fail, transform.position);
takeLife();
}
else if (other.gameObject.CompareTag("Target"))
{
other.gameObject.SetActive(false);
score++;
setScore();
AudioSource.PlayClipAtPoint(success, transform.position);
foreach (GameObject gb in GameObject.FindGameObjectsWithTag("Pill"))
{
gb.transform.position = getRandomVector();
}
other.transform.position = getRandomVector();
other.gameObject.SetActive(true);
timeLeft = 10.0f;
}
else if (other.gameObject.CompareTag("Wall"))
{
failedCollision();
AudioSource.PlayClipAtPoint(fail, transform.position);
takeLife();
}
}
}
void setScore(){
countText.text = "Score: " + score.ToString();
}
Vector3 getRandomVector(){
if(pos.Count == 15) {
pos.Clear();
}
float x = Mathf.Floor(Random.Range(-8, 8));
float z = Mathf.Floor(Random.Range(-8, 8));
float[] xz = { x, z };
while (pos.Contains(xz)){
if(!(x == 0 && z == 0) && !(x == gameObject.transform.position.x && z == gameObject.transform.position.z)){
x = Mathf.Floor(Random.Range(-8, 8));
z = Mathf.Floor(Random.Range(-8, 8));
}
}
pos.Add(xz);
return new Vector3(x, 1, z);
}
void failedCollision() {
foreach(GameObject gb in GameObject.FindGameObjectsWithTag("Pill")) {
gb.transform.position = getRandomVector();
}
gameObject.transform.position = new Vector3(0, 0, 0);
}
void takeLife()
{
lives--;
livesText.text = "Lives: " + lives;
if(lives == 0)
{
endGame();
}
}
void startGame()
{
playBtn.gameObject.SetActive(false);
score = 0;
setScore();
pos = new List<float[]>();
lives = 1;
livesText.text = "Lives: " + lives;
gameOverText.text = "";
timeLeft = 10.0f;
timeLeftText.text = timeLeft.ToString();
failedCollision();
gameObject.SetActive(true);
}
void Update() {
if (timeLeft < 0) {
failedCollision();
takeLife();
} else {
// _Time = _Time + Time.deltaTime;
// float phase = Mathf.Sin(_Time / 2);
// GameObject.FindGameObjectWithTag("Ground").gameObject.transform.localRotation = Quaternion.Euler(new Vector3(phase * 5, 0, 0));
timeLeft -= Time.deltaTime;
timeLeftText.text = timeLeft.ToString();
}
}
void endGame()
{
AudioSource.PlayClipAtPoint(gameOver, transform.position);
gameOverText.text = "Game Over";
timeLeftText.text = "0";
gameObject.transform.position = new Vector3(0, 0, 0);
gameObject.SetActive(false);
playBtn.gameObject.SetActive(true);
}
}
<file_sep># PillGame
Simple 3D game built using Unity3D where the objective is to collect pills.
| f1887521fed6261b09694e54cf5db4283c8a55b3 | [
"Markdown",
"C#"
] | 2 | C# | mdnahian/PillGame | ceec5d73699424b6d57120393bd312f886858224 | 773ee4acb862c1dc69b0f46cd495e0a3704623c3 |
refs/heads/master | <repo_name>kolomoetsanvi/test_task<file_sep>/database/migrations/2019_11_12_182852_change_category_first_level.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeCategoryFirstLevel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('category_second_level', function (Blueprint $table) {
$table->bigInteger('category_first_level_id')->unsigned();
$table->foreign('category_first_level_id')->references('id')->on('category_first_level');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('category_second_level');
}
}
<file_sep>/database/seeds/SecondCategory.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class SecondCategory extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('category_second_level')->insert(
[
[
'title'=>'2-й уровень. Категория 1',
'category_first_level_id'=>'2',
'created_at'=>'2019-11-12'
],
[
'title'=>'2-й уровень. Категория 1',
'category_first_level_id'=>'3',
'created_at'=>'2019-11-12'
],
[
'title'=>'2-й уровень. Категория 2',
'category_first_level_id'=>'3',
'created_at'=>'2019-11-12'
]
]);
}
}
<file_sep>/database/seeds/FirstCategory.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class FirstCategory extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('category_first_level')->insert(
[
[
'title'=>'1-й уровень. Категория 1',
'created_at'=>'2019-11-12'
],
[
'title'=>'1-й уровень. Категория 2',
'created_at'=>'2019-11-12'
],
[
'title'=>'1-й уровень. Категория 3',
'created_at'=>'2019-11-12'
]
]);
}
}
<file_sep>/app/Category_third_level.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category_third_level extends Model
{
use SoftDeletes;
protected $table = 'category_third_level';
protected $primaryKey = 'id';
public $incrementing = TRUE;
public $timestamps = TRUE;
protected $dates = ['deleted_at'];
protected $fillable = ['title', 'category_second_level_id']; //разрешает поля к записи
protected $guarded = ['id']; //поля не доступные к записи
public function category_second_level(){
return $this->belongsTo('App\Category_second_level', 'category_second_level_id');
}
}
<file_sep>/database/seeds/ThirdCategory.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class ThirdCategory extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('category_third_level')->insert(
[
[
'title'=>'3-й уровень. Категория 1',
'category_second_level_id'=>'1',
'created_at'=>'2019-11-12'
],
[
'title'=>'3-й уровень. Категория 1',
'category_second_level_id'=>'2',
'created_at'=>'2019-11-12'
],
[
'title'=>'3-й уровень. Категория 2',
'category_second_level_id'=>'2',
'created_at'=>'2019-11-12'
],
[
'title'=>'3-й уровень. Категория 1',
'category_second_level_id'=>'3',
'created_at'=>'2019-11-12'
],
[
'title'=>'3-й уровень. Категория 2',
'category_second_level_id'=>'3',
'created_at'=>'2019-11-12'
],
[
'title'=>'3-й уровень. Категория 2',
'category_second_level_id'=>'3',
'created_at'=>'2019-11-12'
]
]);
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
//$this->call(FirstCategory::class);
//$this->call(SecondCategory::class);
// $this->call(ThirdCategory::class);
}
}
<file_sep>/database/migrations/2019_11_12_183514_change_category_third_level.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeCategoryThirdLevel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('category_third_level', function (Blueprint $table) {
$table->bigInteger('category_second_level_id')->unsigned();
$table->foreign('category_second_level_id')->references('id')->on('category_second_level');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('category_third_level');
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class HomeController extends Controller
{
protected $user; // данные зарегистрированного пользователя
protected $template; // шаблон
protected $vars; // данные для передачи в шаблон
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$this->user = Auth::user();
if ($this->user->role == 'admin'){
return view('pages/adminPage');
}
}
//
//
}
| ea19e1fd08fb7c40e98cea1e465c07da27879f36 | [
"PHP"
] | 8 | PHP | kolomoetsanvi/test_task | ca044009c2a19deec2422d67a0b7d3eda6df3fb3 | d039835b8a6b6975234abd3911df3ee3e408c711 |
refs/heads/master | <file_sep>package robson.lang.base;
import com.google.gson.annotations.SerializedName;
import robson.lang.environment.Scope;
import java.util.Arrays;
import java.util.Objects;
public class FunctionCall extends Expresion{
@SerializedName(value = "nazwa", alternate = {"name"})
private String name;
@SerializedName(value = "argumenty", alternate = {"args"})
private Expresion[] arguments;
@Override
public Value calculate(Scope scope) throws RuntimeException{
return scope.getFunction(name).call(scope, arguments);
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
FunctionCall that = (FunctionCall)o;
if(!Objects.equals(name, that.name))
return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(arguments, that.arguments);
}
@Override
public int hashCode(){
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + Arrays.hashCode(arguments);
return result;
}
@Override
public String prettyPrint(String prefix){
StringBuilder out = new StringBuilder();
out.append(name + "(");
for(Expresion arg : arguments){
out.append(arg.prettyPrint(prefix));
if(!arg.equals(arguments[arguments.length - 1]))
out.append(", ");
}
out.append(")");
return out.toString();
}
}
<file_sep>import robson.Robson;
import robson.exceptions.BladWykonania;
import robson.exceptions.NieprawidlowyProgram;
public class Main{
public static void main(String[] args){
try{
Robson script = new Robson();
script.fromJson("src/main/resources/recurency.json");
System.out.println(script);
for(int i = 0; i <= 11; i++)
System.out.println(script.wykonaj("szybkie_potegowanie", 2, i));
} catch(NieprawidlowyProgram | BladWykonania e){
e.printStackTrace();
} catch(StackOverflowError e){
System.err.println("Stack Overflow");
}
}
}
<file_sep>package robson.lang.operators;
import utils.TypeCheck;
public abstract class ArithmeticOperator extends TwoArgumentOperator{
protected abstract Number operation(Number e1, Number e2);
@Override
protected Number operation(Object e1, Object e2){
TypeCheck.assertType(e1, Number.class);
TypeCheck.assertType(e2, Number.class);
return operation((Number)e1, (Number)e2);
}
}
<file_sep>package robson.lang.operators;
import robson.lang.base.Value;
import robson.lang.environment.Scope;
import utils.TypeCheck;
public class Not extends OneArgumentOperator{
@Override
public Value calculate(Scope scope) throws RuntimeException{
Object v = arg.calculate(scope).getValue();
TypeCheck.assertType(v, Boolean.class);
return new Value(!((Boolean)v));
}
@Override
public String prettyPrint(String prefix){
return "!" + arg.prettyPrint(prefix);
}
}
<file_sep>package robson.lang.base;
import com.google.gson.annotations.SerializedName;
import robson.lang.environment.Scope;
import java.util.Objects;
public class Variable extends Expresion{
@SerializedName(value = "nazwa", alternate = {"name"})
private String name;
@Override
public Value calculate(Scope scope) throws RuntimeException{
return scope.getVariable(name);
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
Variable variable = (Variable)o;
return Objects.equals(name, variable.name);
}
@Override
public int hashCode(){
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String prettyPrint(String prefix){
return name;
}
}
<file_sep>package robson.lang.keywords;
import robson.lang.base.Expresion;
import robson.lang.base.Value;
import robson.lang.environment.Scope;
public class True extends Expresion{
@Override
public Value calculate(Scope scope) throws RuntimeException{
return new Value(Boolean.TRUE);
}
@Override
public String prettyPrint(String indent){
return "True";
}
}
<file_sep>package robson.lang.operators;
import utils.NumericalOperations;
public class Greater extends RelationalOperator{
@Override
protected Boolean operation(Number e1, Number e2){
return NumericalOperations.greater(e1, e2);
}
@Override
public String prettyPrint(String prefix){
return arg1.prettyPrint(prefix) + " > " + arg2.prettyPrint(prefix);
}
}
<file_sep>package robson.lang.operators;
import com.google.gson.annotations.SerializedName;
import robson.lang.base.Expresion;
import robson.lang.base.Value;
import robson.lang.environment.Scope;
import java.util.Objects;
public abstract class TwoArgumentOperator extends Expresion{
@SerializedName(value = "argument1", alternate = {"arg1"})
protected Expresion arg1;
@SerializedName(value = "argument2", alternate = {"arg2"})
protected Expresion arg2;
protected abstract Object operation(Object e1, Object e2);
@Override
public Value calculate(Scope scope) throws RuntimeException{
Value v1 = arg1.calculate(scope);
Value v2 = arg2.calculate(scope);
return new Value(operation(v1.getValue(), v2.getValue()));
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
TwoArgumentOperator that = (TwoArgumentOperator)o;
if(!Objects.equals(arg1, that.arg1))
return false;
return Objects.equals(arg2, that.arg2);
}
@Override
public int hashCode(){
int result = super.hashCode();
result = 31 * result + (arg1 != null ? arg1.hashCode() : 0);
result = 31 * result + (arg2 != null ? arg2.hashCode() : 0);
return result;
}
}
<file_sep>package robson.lang.environment;
import robson.lang.base.Function;
import robson.lang.base.Value;
import java.util.HashMap;
import java.util.Map;
public class Environment{
protected final Map<String, Value> variables = new HashMap<>();
protected final Map<String, Function> functions = new HashMap<>();
public Value getVariable(String name) throws RuntimeException{
if(!variables.containsKey(name))
throw new RuntimeException("variable " + name + " not found in the environment");
return variables.get(name);
}
public Function getFunction(String name) throws RuntimeException{
if(!functions.containsKey(name))
throw new RuntimeException("function " + name + " not found in the environment");
return functions.get(name);
}
public boolean containsVariable(String name){
return variables.containsKey(name);
}
public boolean containsFunction(String name){
return functions.containsKey(name);
}
public void add(String name, Value value){
variables.put(name, value);
}
public void add(String name, Function function){
functions.put(name, function);
}
public void clear(){
variables.clear();
functions.clear();
}
@Override
public String toString(){
return "Environment{" + "variables=" + variables + ", functions=" + functions + '}';
}
}
<file_sep>package robson.lang.operators;
import utils.TypeCheck;
public abstract class BinaryOperator extends TwoArgumentOperator{
protected abstract Boolean operation(Boolean e1, Boolean e2);
@Override
protected Boolean operation(Object e1, Object e2){
TypeCheck.assertType(e1, Boolean.class);
TypeCheck.assertType(e2, Boolean.class);
return operation((Boolean)e1, (Boolean)e2);
}
}
<file_sep>package robson.loader;
import com.google.gson.*;
import robson.lang.base.FunctionCall;
import robson.lang.base.Function;
import robson.lang.base.Value;
import robson.lang.base.Variable;
import robson.lang.base.Expresion;
import robson.lang.keywords.*;
import robson.lang.operators.*;
import java.lang.reflect.Type;
public class ExpresionDeserializer implements JsonDeserializer<Expresion>{
@Override
public Expresion deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException{
JsonObject jsonObject = jsonElement.getAsJsonObject();
String t;
if(jsonObject.has("typ"))
t = jsonObject.get("typ").getAsString();
else if(jsonObject.has("type"))
t = jsonObject.get("type").getAsString();
else
throw new JsonParseException("Invalid Expresion, type not found");
Class<?> c = switch(t){
case "Funkcja", "Function" -> Function.class;
case "Wywolanie", "Call" -> FunctionCall.class;
case "Liczba", "Wartosc", "Value" -> Value.class;
case "Zmienna", "Variable" -> Variable.class;
case "Przypisanie", "Assignment", "=" -> Assignment.class;
case "Wez", "Access" -> Access.class;
case "Blok", "Block" -> Block.class;
case "Jesli", "Jezeli", "If" -> If.class;
case "Dopoki", "While" -> While.class;
case "Falsz", "False" -> False.class;
case "Prawda", "True" -> True.class;
case "Plus", "Add", "+" -> Add.class;
case "Minus", "Subtract", "-" -> Subtract.class;
case "Razy", "Multiply", "*" -> Multiply.class;
case "Dzielenie", "Divide", "/" -> Divide.class;
case "Modulo", "%" -> Modulo.class;
case "I", "And", "&&" -> And.class;
case "Lub", "Or", "||" -> Or.class;
case "Nie", "Not", "!" -> Not.class;
case "<" -> Smaller.class;
case "<=" -> SmallerEqual.class;
case ">" -> Greater.class;
case ">=" -> GreaterEqual.class;
case "==" -> Equal.class;
default -> null;
};
if(c == null)
throw new JsonParseException("Unknown type: " + t);
return jsonDeserializationContext.deserialize(jsonElement, c);
}
}
<file_sep>package robson.lang.keywords;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.LinkedTreeMap;
import robson.lang.base.Expresion;
import robson.lang.base.Value;
import robson.lang.environment.Scope;
import utils.TypeCheck;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Access extends Expresion{
@SerializedName(value = "instrukcja", alternate = {"instruction"})
Expresion expresion;
@SerializedName(value = "nazwa", alternate = {"name", "field", "pole"})
String what;
@SerializedName(value = "indeks", alternate = {"index"})
Expresion id;
@Override
public Value calculate(Scope scope) throws RuntimeException{
if(id != null && what != null)
throw new RuntimeException("Cannot access from expresion, both index and field");
if(id == null && what == null)
throw new RuntimeException("Cannot access from expresion, index nor field not specified");
Object object = expresion.calculate(scope).getValue();
if(object.getClass().isArray()){
if(id == null)
throw new RuntimeException("Cannot access " + what + ", expresion is an array");
Value tmp = id.calculate(scope);
TypeCheck.isType(tmp.getValue(), Number.class);
int id = ((Number)tmp.getValue()).intValue();
int len = Array.getLength(object);
if(id < 0 || len <= id)
throw new RuntimeException("Cannot access " + id + " in an expresion, index out of bounds");
return new Value(Array.get(object, id));
}
else if(object instanceof List){
if(id == null)
throw new RuntimeException("Cannot access " + what + ", expresion is an array");
Value tmp = id.calculate(scope);
TypeCheck.isType(tmp.getValue(), Number.class);
int id = ((Number)tmp.getValue()).intValue();
ArrayList<?> arr = (ArrayList<?>)object;
if(id < 0 || arr.size() <= id)
throw new RuntimeException("Cannot access " + id + " in an expresion, index out of bounds");
return new Value(arr.get(id));
}
if(object instanceof LinkedTreeMap<?, ?>){
if(what == null)
throw new RuntimeException("Cannot access index " + id + ", expresion is not an array");
@SuppressWarnings("unchecked")
LinkedTreeMap<? extends String, ?> map = (LinkedTreeMap<? extends String, ?>)object;
return new Value(map.get(what));
}
throw new RuntimeException("Cannot access index or field: unexpected error");
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
Access access = (Access)o;
if(!Objects.equals(expresion, access.expresion))
return false;
if(!Objects.equals(what, access.what))
return false;
return Objects.equals(id, access.id);
}
@Override
public int hashCode(){
int result = super.hashCode();
result = 31 * result + (expresion != null ? expresion.hashCode() : 0);
result = 31 * result + (what != null ? what.hashCode() : 0);
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
@Override
public String prettyPrint(String prefix){
StringBuilder out = new StringBuilder();
out.append(expresion.prettyPrint(prefix));
if(id != null){
out.append("[");
out.append(id.prettyPrint(prefix));
out.append("]");
}
else{
out.append(".");
out.append(what);
}
return out.toString();
}
}
<file_sep>package robson.lang.base;
import com.google.gson.annotations.SerializedName;
import robson.lang.environment.Scope;
import java.util.Objects;
public class Value extends Expresion{
@SerializedName(value = "wartosc", alternate = {"value"})
private Object value;
@Override
public Value calculate(Scope scope) throws RuntimeException{
return this;
}
public Object getValue(){
return value;
}
public Value(){
}
public Value(Object value){
this.value = value;
}
@Override
public boolean equals(Object o){
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
Value value1 = (Value)o;
return Objects.equals(value, value1.value);
}
@Override
public int hashCode(){
int result = super.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String prettyPrint(String prefix){
return value.toString();
}
}
| b4902044ea17f068806ca894e06b59c205d259ca | [
"Java"
] | 13 | Java | capi1500/Robson | 0c559182f691fc746d48394a29edc5505869bb35 | 4d6fd0af86da6eb6eb18ac79161fd81dd99bbf32 |
refs/heads/master | <file_sep># this file is to download wechat image from wechat server
import urllib
from dao.server_config import ServerConfigDao
from dao.user_upload import UserUploadDao
from threading import Timer
import os
import traceback
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
print currentdir
targetDir = r'/home/huson/admin.51dingxiao.com/static/wx_temp'
def downloadByAccessTokenAndMediaId(accessToken,mediaId):
url = r'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s' % (accessToken, mediaId)
urllib.urlretrieve(url, "%s/%s.jpg" % (targetDir,mediaId))
def start_download():
try:
access_token = ServerConfigDao().get_access_token()
file = open(currentdir+'/current.id','r+')
# once 100 images
line = file.readline()
if line != '':
start = int(line)
else :
start = 0
# file.close()
# file = open('current.id','w+')
print('last end at id=%d'%start)
while True:
rows = UserUploadDao().selectByPage(start+1,100)
for row in rows:
media1Id = row.image1_id
if media1Id != '':
downloadByAccessTokenAndMediaId(access_token,media1Id)
media2Id = row.image2_id
if media2Id != '':
downloadByAccessTokenAndMediaId(access_token, media2Id)
media3Id = row.image3_id
if media3Id != '':
downloadByAccessTokenAndMediaId(access_token, media3Id)
file.seek(0,0)
file.write(str(row.id))
file.flush()
os.fsync(file)
if len(rows) < 100:
break
else:
start = row.id
file.close()
except:
traceback.print_exc()
#restart self every 30 seconds
Timer(1 * 1, start_download, ()).start()
if __name__ == '__main__':
start_download()
<file_sep># mysite_uwsgi.ini file
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /home/huson/wx.mmd666.cn
# Django's wsgi file
module = main:app
#wsgi-file = main.py
pidfile = /home/huson/wx.mmd666.cn/project-master.pid
# the virtualenv (full path)
#home = /path/to/virtuaddlenv
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 2
threads = 2
# the socket (use the full path to be safe
socket = /home/huson/wx.mmd666.cn/ProjectWx.sock
# ... with appropriate permissions - may be needed
chmod-socket = 666
# clear environment on exit
vacuum = true
buffer-size = 16384
#log-maxsize = 10
daemonize = /home/huson/logs/wx.mmd666.cn/ProjectWx.log
touch-reload = /home/huson/wx.mmd666.cn/touch-reload-file
<file_sep>
from util.class_decorator import singleton
import web
from config import Config
@singleton
class DbHelper(object):
def __init__(self):
config = Config()
print('init database %s' % config['dbname'])
self.db = web.database(host=config['host'],port=config['port'], dbn=config['dbn']
, user=config['username'], pw=config['password'], db=config['dbname'])
def select(self, *args, **kw):
return self.db.select(*args, **kw)
def insert(self,*args, **kw):
return self.db.insert(*args, **kw)
def update(self,*args, **kw):
return self.db.update(*args, **kw)
<file_sep>#this file is used for admin charge user money
import MySQLdb as mdb
from util.wx_algorithms import *
import sys
from dao.server_config import ServerConfigDao
reload(sys)
exec("sys.setdefaultencoding('utf-8')")
con = mdb.connect('localhost', 'xiaob', 'sk<PASSWORD>asdf', 'xiaob')
con.set_character_set('utf8')
cur = con.cursor()
cur.execute("SET NAMES utf8")
cur.execute('SET CHARACTER SET utf8;')
cur.execute('SET character_set_connection=utf8;')
con.commit()
print 'start create shop setting...'
shop_id = int(raw_input('shop_id: '))
shop_name = raw_input('shop_name(chinese): ')
cur.execute('Insert into shop_setting(shop_id, name,filter_orderid_flag) VALUES (%s,%s,1)',(shop_id,shop_name))
con.commit()
print 'finished!'
print 'start create shop admin user...'
user_name = raw_input('user name: ')
cur.execute('Insert into shop_user(shop_id, user_name,password,shop_name) VALUES (%s,%s,%s,%s)',
(shop_id,user_name,'e10adc3949ba59abbe56e057f20f883e',shop_name))
con.commit()
print 'finished! default password is <PASSWORD>'
print 'start create balance...'
cur.execute('Insert into shop_account(shop_id, balance) VALUES (%s,0)',(shop_id,))
con.commit()
print 'finished! balance is 0'
print 'start create lucky money amount...'
money = int(raw_input('lucky money amount(yuan): '))
money = money * 100
cur.execute('Insert into log_change_money(shop_id,money ) VALUES (%s,%s)',(shop_id,money))
con.commit()
print 'finished!'
print 'start create tag...'
tagid = createTag('shop_%d'%shop_id)
print 'finished! tag id : %d'%tagid
print 'save tag id'
cur.execute('Update shop_setting set wx_tag_id=%s where shop_id=%s',(tagid,shop_id))
con.commit()
con.close()
access_token = ServerConfigDao()['access_token']
print access_token<file_sep>import string
import random
import hashlib
from config import Config
from dao.server_config import ServerConfigDao
import web
import urllib
import json
import requests
def id_generator(size=16, chars=string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def js_signature(noncestr,jsapi_ticket,timestamp,url):
s = "jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s" %(jsapi_ticket,
noncestr,timestamp,url)
h = hashlib.sha1(s)
return h.hexdigest()
def oauth2(redictUrl,scope,state):
appId = ServerConfigDao().getAppId()
redictUrl = r'http://' + ServerConfigDao()['domin_name'] + redictUrl
scope = scope
state = state
target = r'https://open.weixin.qq.com/connect/oauth2/authorize?' \
r'appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#' \
r'wechat_redirect' % (appId, redictUrl, scope, state)
raise web.seeother(target)
def getOpenIdByCode(code):
appId = ServerConfigDao().getAppId()
secret = ServerConfigDao().getAppSecret()
url = r'https://api.weixin.qq.com/sns/oauth2/access_token?' \
r'appid=%s&secret=%s&code=%s&grant_type=authorization_code'%(appId,secret,code)
urlResp = urllib.urlopen(url)
t = urlResp.read()
urlResp = json.loads(t)
if 'openid' not in urlResp:
print t
return urlResp['openid']
def addShopTagToUser(open_id,shop_tag_id):
accessToken = ServerConfigDao().get_access_token()
target = r'https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=%s' % accessToken
data = {'openid_list':[open_id],'tagid':shop_tag_id}
payload = json.dumps(data)
s = requests.post(target,data=payload)
res = json.loads(s.text)
if res['errcode'] != 0:
print 'adding tag error:', s.text
def getUserTags(open_id):
accessToken = ServerConfigDao().get_access_token()
target = r'https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=%s' %accessToken
data = {'openid':open_id}
payload = json.dumps(data)
s = requests.post(target,data=payload)
res = json.loads(s.text)
if 'tagid_list' not in res:
print s.text
tags = res['tagid_list']
return tags
def deleteUserTag(open_id,tag):
accessToken = ServerConfigDao().get_access_token()
target = r'https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=%s' %accessToken
data = {'openid_list':[open_id],'tagid':tag}
payload = json.dumps(data)
s = requests.post(target,data=payload)
res = json.loads(s.text)
if res['errcode'] != 0:
print 'adding tag error:', s.text
def createTag(name):
accessToken = ServerConfigDao().get_access_token()
target = r'https://api.weixin.qq.com/cgi-bin/tags/create?access_token=%s' %accessToken
data = {'tag':{'name':name}}
payload = json.dumps(data)
s = requests.post(target,data=payload)
res = json.loads(s.text)
return res['tag']['id']
<file_sep><?php
$text = '红包发放失败,由于您的用户状态异常,使用常用的活跃的微信号可避免这种情况,请联系淘宝客服索取红包。';
$openid = '9PalwD2NwcxyuXNQXBWsq8Hf4tk';
$mysql_server_name='localhost'; //
$mysql_username='xiaob'; //
$mysql_password='<PASSWORD>'; //
$mysql_database='xiaob'; //
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password) or die("error connecting") ; //连接数据库
mysql_query("set names 'utf8'"); //UTF-8 国际标准编码.
mysql_select_db($mysql_database); //打开数据库
$sql = "select v from server_config where name_space='wx' and k='access_token'";
$result2 = mysql_query($sql,$conn);
$row = mysql_fetch_row($result2);
$access_token = $row[0];
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
$data_string = '{"touser":"'.$openid.'","msgtype":"text","text":{"content":"'.$text.'"}}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($data_string)));
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array($return_code, $return_content);
<file_sep># -*- coding: utf-8 -*-
# filename: main.py
import socket
import web
from util.log import Log
import config
from controller.handle import Handle
from controller.re_fund import Refund
from controller.re_fund import RefundSubmit
from controller.re_fund import RefundHistory
from controller.re_fund import RefundOauth
from controller.verify import VerifyXwpay
from controller.verify import VerifyGZChenlan
import sys
reload(sys)
sys.setdefaultencoding('utf8')
web.config.debug = config.debug
urls = (
'/wx', 'Handle',
'/MP_verify_xHfVRSc4XZjB8oTQ.txt', 'VerifyXwpay',
'/MP_verify_7DY5qAd936DYwWrL.txt', 'VerifyGZChenlan',
'/refund', 'Refund',
'/refund/submit', 'RefundSubmit',
'/refund/history', 'RefundHistory',
'/refund/oauth','RefundOauth',
)
app = web.application(urls, globals())
if not config.debug :
app = app.wsgifunc(Log)
# def session_hook():
# web.ctx.session = session
if __name__ == '__main__':
app.run(Log)
<file_sep>import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from dao.server_config import ServerConfigDao
from basic import Basic
import requests
import json
def flush_config_task():
sc = ServerConfigDao()
print('----start reflesh token----')
accessToken = Basic().get_access_token()
print(accessToken)
sc.set_access_token(accessToken)
print('----start reflesh jsapi_ticket')
url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
payload = {'access_token': accessToken, 'type': 'jsapi'}
resp = requests.get(url, params=payload)
r = json.loads(resp.content)
ticket = r['ticket']
print(ticket)
sc.set_jsapi_ticket(ticket)
if __name__ == "__main__":
flush_config_task()
<file_sep><?php
require 'wxpay.class.php';//数组参数
$mysql_server_name='localhost'; //
$mysql_username='xiaob'; //
$mysql_password='<PASSWORD>'; //
$mysql_database='xiaob'; //
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password) or die("error connecting") ; //连接数据库
mysql_query("set names 'utf8'"); //UTF-8 国际标准编码.
mysql_select_db($mysql_database); //打开数据库
$stopFlag = false;
$lastRow = 0;
while(! $stopFlag){
$config = array();
$sql = "select * from server_config where name_space='wx'";
$result2 = mysql_query($sql,$conn);
while($row = mysql_fetch_array($result2))
{
$config[$row['k']] = $row['v'];
}
$sql = 'select * from verify_refund where refund_flag=0 and del_flag=0 order by id asc limit 100';
$result = mysql_query($sql,$conn);
$stopFlag = true;
while($row = mysql_fetch_array($result))
{
$stopFlag = false;
if ($row['id'] <= $lastRow){
$stopFlag = true;
break;
}
$sql = 'select * from shop_setting where shop_id='.$row['shop_id'];
$result2 = mysql_query($sql,$conn);
$ss = mysql_fetch_row($result2);
$shop_name = $ss[1];
$order_id = $row['order_id'];
$open_id = $row['open_id'];
$money = $row['money'];
$sender = $shop_name;
$obj2 = array();
$obj2['wxappid'] = $config['app_id']; //appid
$obj2['mch_id'] = $config['pay_id'];//商户id
$obj2['mch_billno'] = $order_id;
$obj2['client_ip'] = '172.16.31.10';
$obj2['re_openid'] = $open_id;//接收红包openid
$obj2['total_amount'] = $money;
$obj2['total_num'] = 1;
$obj2['send_name'] = $shop_name;
$obj2['wishing'] = "感谢您的好评";
$obj2['act_name'] = $shop_name."的好评返现";
$obj2['remark'] = $shop_name."红包";
$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
$wxpay = new wxPay();
$res = $wxpay->pay($url, $obj2,$config['pay_key']);
if ($res){
$sql = 'update verify_refund set refund_flag=1 where id='.$row['id'] ;
mysql_query($sql);
}
$lastRow = $row['id'];
}
}
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
from util.memcache_util import Client
import config
@singleton
class ServerConfigDao(object):
def __init__(self):
self.table = 'server_config'
self.db = DbHelper()
self.nameSpace = 'wx'
self.client = Client(config.prefix)
def get_access_token(self):
return self.getValue('access_token')
def set_access_token(self,token):
return self.setValue('access_token',token)
def get_jsapi_ticket(self):
return self.getValue('jsapi_ticket')
def set_jsapi_ticket(self,jsTicket):
self.setValue('jsapi_ticket',jsTicket)
def getGlobalByKey(self,k):
val = {'name_space':self.nameSpace,'k':k}
row = self.db.select(self.table,where='name_space=$name_space and k=$k',vars=val)[0]
return row.v
def getAppId(self):
return self.getValue('app_id')
def getAppSecret(self):
return self.getValue('app_secret')
def __getitem__(self, key):
return self.getValue(key)
def setValue(self,key,value):
self.client.set(key,value)
val = {'name_space': self.nameSpace, 'k': key}
self.db.update(self.table, where='name_space=$name_space and k=$k', vars=val,
v=value)
def getValue(self,key):
value = self.client.get(key)
if not value:
value = self.getGlobalByKey(key)
self.client.set(key, value)
return value
<file_sep># -*- coding: utf-8 -*-
import web
from dao.server_config import ServerConfigDao
from util.wx_algorithms import *
import time
from config import Config
from dao.user_upload import UserUploadDao
from dao.verify_refund import VerifyRefundDao
from dao.order_ids import OrderIdsDao
from dao.shop_setting import ShopSettingDao
from dao.log_change_money import LogShopMoneyDao
from dao.shop_account import ShopAccountDao
from dao.user_belong import UserBelongDao
import json
render = web.template.render('templates/')
class Refund:
def __init__(self, ):
self.logger = web.ctx.env.get('wsgilog.logger')
self.logger.info("log test")
def GET(self):
appId = ServerConfigDao().getAppId()
jsapi_token = ServerConfigDao().get_jsapi_ticket()
noncestr = id_generator()
timestamp = int(time.time())
url = r'http://'+ServerConfigDao()['domin_name'] + web.ctx.fullpath
sign = js_signature(noncestr,jsapi_token,timestamp,url)
data = web.input()
code = data.code
# shopid = data.state
openid = getOpenIdByCode(code)
shopid = UserBelongDao().getShopIdByOpenId(openid)
if not shopid:
return u'请重新扫描二维码'
return render.refund(appId,sign,noncestr,timestamp,shopid,openid)
class RefundSubmit:
def POST(self):
data = web.input()
if len(data) == 0:
return 'Hello, this is submit'
data = json.loads(data.info);
serverIds = data['server_ids']
orderId = data['order_id'].replace(' ','')
shopId = data['shop_id']
openId = data['open_id']
userUploadDao = UserUploadDao()
shopSetting = ShopSettingDao().getSetting(shopid=shopId)
if shopSetting['filter_orderid_flag'] == 1:
# open filter function
if not OrderIdsDao().verifyByOrderID(orderId):
return 'wrong'
auto_pass = shopSetting['auto_pass_flag']
if auto_pass == 1:
#check money is enough
money = LogShopMoneyDao().getMoneyByShopId(shopid=shopId)
effectRows = ShopAccountDao().reduceMoney(shopid=shopId,money=money)
if effectRows >0:
# only save basic information
res = userUploadDao.insertAutoPass(shopId, openId, orderId)
if res:
# save pass record in another table
VerifyRefundDao().insertVerifyRefund(shopId,openId,orderId,money)
return 'true'
else:
#add money back
ShopAccountDao().addbackMoney(shopId,money)
return 'false'
else: # not enough money, can't auto pass
auto_pass = 0
if auto_pass == 0:
if len(serverIds) == 0:
res = userUploadDao.insert(shopId,openId, orderId)
elif len(serverIds) == 1:
res = userUploadDao.insert(shopId,openId, orderId, serverIds[0])
elif len(serverIds) == 2:
res = userUploadDao.insert(shopId,openId, orderId, serverIds[0], serverIds[1])
else:
res = userUploadDao.insert(shopId,openId, orderId, serverIds[0], serverIds[1], serverIds[2])
if res:
return 'true'
else:
return 'false'
class RefundHistory():
def GET(self):
data = web.input()
openId = data.openId
shopId = data.shopId
userUploadDao = UserUploadDao()
uploads = userUploadDao.selectByOpenId(shopId,openId)
return render.history(uploads)
class RefundOauth():
def GET(self):
data = web.input()
# shopid = data.shopid
oauth2('/refund','snsapi_base','state')
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
from util.memcache_util import Client
import config
@singleton
class AutoReplyDao(object):
def __init__(self):
self.table = 'auto_reply'
self.db = DbHelper()
self.client = Client(config.prefix)
def getAllReplys(self):
rows = self.client.get('auto_reply')
if not rows:
rows = list(self.db.select(self.table, where='enable_flag=1',order='id asc'))
self.client.set('auto_reply',rows)
return rows
def saveReplysToMc(self):
rows = self.db.select(self.table, where='enable_flag=1', order='id asc')
self.client.set('auto_reply', list(rows))
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class LogShopMoneyDao(object):
def __init__(self):
self.table = 'log_change_money'
self.db = DbHelper()
def getMoneyByShopId(self,shopid):
val = {'shopId': shopid}
rows = self.db.select(self.table, where='shop_id=$shopId', vars=val,order='create_time desc',limit=1)
return rows[0]['money']<file_sep>import imp
import config
try:
imp.find_module('pylibmc')
import pylibmc as mc
except ImportError:
import memcache as mc
class Client():
def __init__(self, prefix):
self.client = mc.Client(config.memcached_servers)
self.prefix = prefix
def set(self,key,value):
key = self.prefix + key
return self.client.set(key,value)
def get(self,key):
key = self.prefix + key
return self.client.get(key)
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class ShopAccountDao(object):
def __init__(self):
self.table = 'shop_account'
self.db = DbHelper()
def reduceMoney(self, shopid,money):
val = {'money': money,'shopid':shopid}
effectRows = self.db.db.query('update shop_account set balance=balance-$money where shop_id=$shopid and balance>=$money', vars= val)
return effectRows
def addbackMoney(self,shopid,money):
val = {'money': money, 'shopid': shopid}
effectRows = self.db.db.query(
'update shop_account set balance=balance+$money where shop_id=$shopid', vars=val)
return effectRows<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class UserBelongDao(object):
def __init__(self):
self.table = 'user_belong'
self.db = DbHelper()
def insertOnUpdate(self,open_id,shop_id):
try:
self.db.insert(self.table,open_id=open_id,shop_id=shop_id,create_time=None, update_time=None)
except :
vals = {'openId':open_id,'shopId':shop_id}
self.db.update(self.table,where="open_id=$openId and shop_id!=$shopId",vars=vals,shop_id=shop_id)
return True
def getShopIdByOpenId(self,open_id):
val = {'openId': open_id}
rows = self.db.select(self.table, where='open_id=$openId', vars=val)
if rows:
return rows[0]['shop_id']
return False<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class ShopSettingDao(object):
def __init__(self):
self.table = 'shop_setting'
self.db = DbHelper()
def getSetting(self, shopid):
val = {'shopId': shopid}
rows = self.db.select(self.table, where='shop_id=$shopId', vars=val)
return rows[0]<file_sep>import socket
from util.class_decorator import singleton
# from dao.server_config import ServerConfigDao
import logging
import platform
plt = platform.architecture()
syst = plt[1]
if syst == 'ELF':
debug = False
else :
debug = True
file = "logs/webpy.log"
logformat = "[%(asctime)s] %(filename)s:%(lineno)d(%(funcName)s): [%(levelname)s] %(message)s"
datefmt = "%Y-%m-%d %H:%M:%S"
loglevel = logging.INFO
interval = "d"
backups = 7
memcached_servers = ['127.0.0.1:11211']
prefix = 'chenlan_'
nsqd = '127.0.0.1:4151'
@singleton
class Config(object):
config_server = {
'dbn': 'mysql',
'username': 'xiaob',
'password': '<PASSWORD>',
'dbname': 'xiaob',
'host': '127.0.0.1',
'port': 3306,
}
config_develop = {
'dbn': 'mysql',
'username': 'xiaob',
'password': '<PASSWORD>',
'dbname': 'xiaob',
'host': '127.0.0.1',
'port': 3306,
}
def __init__(self):
myname = socket.getfqdn(socket.gethostname())
print('server is running on %s ... configurating..' % myname)
self.config = self.config_server
def __getitem__(self, key):
return self.config[key]
<file_sep># -*- coding: utf-8 -*-
from basic import Basic
import urllib
class Media(object):
def __init__(self):
pass
'''create temp media,
type: image, vocie, video ,thumb;
media: form-data中媒体文件标识,有filename、filelength、content-type等信息'''
def create_temp(self,media_type,media, ccess_token):
postUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
postData = r"""{
type:"""+media_type+","+"""
media:"""+media+"""
}"""
if isinstance(postData, unicode):
postData = postData.encode('utf-8')
urlResp = urllib.urlopen(url=postUrl, data=postData)
print urlResp.read()
def download_temp(self, access_token, media_id):
postUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"
urlResp = urllib.urlopen(url=postUrl)
return urlResp.read()
'''
#get the permantent media list
type:image,voice,video,news
count: 0-20
offset
'''
def get_media_list(self, access_token):
postUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s" % accessToken
postData = r"""
{
"type": "news",
"offset": 6,
"count":1
}
"""
if isinstance(postData, unicode):
postData = postData.encode('utf-8')
urlResp = urllib.urlopen(url=postUrl, data=postData)
mediaStr = urlResp.read()
print mediaStr
mediaDic = eval(mediaStr)
print mediaDic
if __name__ == '__main__':
myMedia=Media()
accessToken = Basic().get_access_token()
myMedia.get_media_list(accessToken)
<file_sep> # -*- coding: utf-8 -*-
from menu import Menu
from basic import Basic
myMenu = Menu()
postJson = """
{
"button":
[
{
"name": "好评返现",
"type": "view",
"url": "http://wx.mmd666.cn/refund/oauth?"
},
{
"name": "产品介绍",
"sub_button":
[
{
"type": "view",
"name": "非全屏钢化膜",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000045&idx=1&sn=44a2bee18c9fdb8cb41894f05c8c0e56&chksm=1fbacb9728cd4281a82d9e2e15f3b5f2747269cc399f5977d9cf1e5920e9bf4081b5254e1592#rd"
},
{
"type": "view",
"name": "全屏钢化膜",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000039&idx=1&sn=5e15b34b7e0a580b138278c9e893848c&chksm=1fbacb9d28cd428bdeb942f6e3c4d6d214d94200914d7fb0bec02e9c54767ca8e17e9e909c71#rd"
},
{
"type": "view",
"name": "抗蓝光钢化膜",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000048&idx=1&sn=3c723677364d0cb88f77b3e3b944ad98&chksm=1fbacb8a28cd429c4b071316d34da7f73700f97829b1479f7393cefabe8d293a4000236141cd#rd"
},
{
"type": "view",
"name": "3D曲面软边钢化膜",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000042&idx=1&sn=3d18408769a36e1b8cde93af972726d6&chksm=1fbacb9028cd42867b2d8fdd703f7288a1d84e37e93b3ae98991b0f35447cbc476c5c8f2403f#rd"
}
]
},
{
"name": "贴膜教学",
"sub_button":
[
{
"type": "view",
"name": "贴膜教学",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000050&idx=1&sn=c23aa0447bfef3f906f5ffb4dc9aefe0&chksm=1fbacb8828cd429e74af6131427db12e7e2be77144a22f87d8729009e7e9874cd79c6d421cfe#rd"
},
{
"type": "view",
"name": "白边修复方法",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000030&idx=1&sn=f2dc96f4000a4b9099be8e04fe7d736a&chksm=1fbacba428cd42b2b6c22dbb60d3da78c12c324d4cf34404db0838f67f7669dd23846c482b91#rd"
},
{
"type": "view",
"name": "贴后膜方法",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000027&idx=1&sn=924e4bd625478efb39e72e04d69fc605&chksm=1fbacba128cd42b708f7be016c6e6b7e1ca6117871698de973e37bb0a988a4db9d3bf05d369c#rd"
},
{
"type": "view",
"name": "贴膜后进灰尘修复方法",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000036&idx=1&sn=28f6066d170712a0607bd003743d76c2&chksm=1fbacb9e28cd428844dcdcf3460a25fea97ba3cdbf156562adef8913f36a8660749d819a3239#rd"
},
{
"type": "view",
"name": "贴膜后有气泡修复方法",
"url": "http://mp.weixin.qq.com/s?__biz=MzA3ODkxMzQ5Mw==&mid=100000033&idx=1&sn=8ab71afe95eba12030ed445de548fd4e&chksm=1fbacb9b28cd428d55bbf8a963e743b837b17f91a12401fa7dc93b8b08d28d0d49aecdfd5cf7#rd"
}
]
}
]
}"""
accessToken = Basic().get_access_token()
#myMenu.delete(accessToken)
myMenu.create(postJson, accessToken)
<file_sep>class VerifyXwpay(object):
def GET(self):
return 'xHfVRSc4XZjB8oTQ'
class VerifyGZChenlan(object):
def GET(self):
return '7DY5qAd936DYwWrL'
<file_sep>import requests
import config
import json
class NsqProducer():
def __init__(self,topic):
self.topic = topic
self.murl = u'http://' + config.nsqd+'/mpub?topic=' + topic
self.url = u'http://' + config.nsqd+'/pub?topic=' + topic
def produce(self,message):
m = json.dumps(message)
requests.post(self.url, data=m)
def produceList(self,messages):
payload = [json.dumps(m) for m in messages]
p = '\n'.join(payload)
requests.post(self.murl,data=p)<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class OrderIdsDao(object):
def __init__(self):
self.table = 'order_ids'
self.db = DbHelper()
def verifyByOrderID(self, orderid):
val = {'orderId': orderid}
rows = self.db.select(self.table, where='order_id=$orderId', vars=val)
if rows:
return True
else:
return False<file_sep><?php
require 'wxpay.class.php';//数组参数
$mysql_server_name = '127.0.0.1'; //
$mysql_username = 'xiaob'; //
$mysql_password = '<PASSWORD>'; //
$mysql_database = 'xiaob'; //
$conn = mysqli_connect($mysql_server_name, $mysql_username, $mysql_password, $mysql_database) or die("error connecting"); //连接数据库
$conn->query("set names 'utf8'"); //UTF-8 国际标准编码.
$stopFlag = false;
$lastRow = 0;
while (!$stopFlag) {
$config = array();
$sql = "select * from server_config where name_space='wx'";
$result2 = $conn->query($sql);
while ($row = $result2->fetch_assoc()) {
$config[$row['k']] = $row['v'];
}
$sql = 'select * from verify_refund where refund_flag=0 and del_flag=0 order by id asc limit 100';
$result = $conn->query($sql);
$stopFlag = true;
while ($row = $result->fetch_assoc()) {
$stopFlag = false;
if ($row['id'] <= $lastRow) {
$stopFlag = true;
break;
}
$sql = 'select * from shop_setting where shop_id=' . $row['shop_id'];
$result2 = $conn->query($sql);
$ss = $result2->fetch_all(MYSQLI_ASSOC)[0];
$shop_name = $ss['name'];
$order_id = $row['order_id'];
$open_id = $row['open_id'];
$money = $row['money'];
$sender = $shop_name;
$obj2 = array();
$obj2['wxappid'] = $config['app_id']; //appid
$obj2['mch_id'] = $config['pay_id'];//商户id
$obj2['mch_billno'] = $order_id;
$obj2['client_ip'] = '172.16.17.32';
$obj2['re_openid'] = $open_id;//接收红包openid
$obj2['total_amount'] = $money;
$obj2['total_num'] = 1;
$obj2['send_name'] = $shop_name;
$obj2['wishing'] = "感谢您的好评";
$obj2['act_name'] = $shop_name . "";
$obj2['remark'] = $shop_name . "红包";
$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
$wxpay = new wxPay();
$res = $wxpay->pay($url, $obj2, $config['pay_key']);
if ($res == 'SUCCESS') {
$sql = 'update verify_refund set refund_flag=1 where id=' . $row['id'];
$conn->query($sql);
} else if ($res == 'USER_ERROR') {
$sql = 'update verify_refund set del_flag=1 where id=' . $row['id'];
$conn->query($sql);
$url = 'http://127.0.0.1:4151/pub?topic=luckymoney_fail';
$data = array('open_id' => $open_id);
httpPost($url,$data);
}
$lastRow = $row['id'];
}
}
function httpPost($url, $data)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
<file_sep># -*- coding: utf-8 -*-
# filename: handle.py
import web
import xml.etree.ElementTree as ET
from dao.user_belong import UserBelongDao
from dao.shop_setting import ShopSettingDao
from util.wx_algorithms import *
from dao.auto_reply import AutoReplyDao
class Handle(object):
def __init__(self, ):
self.logger = web.ctx.env.get('wsgilog.logger')
self.logger.info("log test")
def POST(self):
data = web.data()
if len(data) == 0:
return 'hello, this is handle view'
else:
xml = ET.fromstring(data)
msgType = xml.find('MsgType').text
autoReply = AutoReplyDao().getAllReplys()
reply = None
if msgType == 'event':
Event = xml.find('Event').text
if Event != 'subscribe' and Event != 'SCAN':
return 'hello wx'
if Event == 'subscribe':
EventKey = xml.find('EventKey').text.split('|')[0]
shop_id = int(EventKey[8:])
reply = autoReply[0]
if Event == 'SCAN':
EventKey = xml.find('EventKey').text
shop_id = int(EventKey)
reply = autoReply[0]
shopSetting = ShopSettingDao().getSetting(shop_id)
FromUserName = xml.find('FromUserName').text
open_id = FromUserName
# add user to db
UserBelongDao().insertOnUpdate(open_id, shop_id)
tags = getUserTags(open_id)
for tag in tags:
deleteUserTag(open_id, tag)
# add tag to wx
addShopTagToUser(open_id, shopSetting['wx_tag_id'])
elif msgType == 'text':
messageContent = xml.find('Content').text
for row in autoReply[1:]:
if row['match_type'] == 0:
if messageContent == row['match_content']:
reply = row
break
elif row['match_type'] == 1:
if row['match_content'] in messageContent :
reply = row
break
else:
for row in autoReply[1:]:
if row['match_content'] == 'image':
reply = row
break
if reply is not None :
toUserName = xml.find('ToUserName').text
fromUserName = xml.find('FromUserName').text
createTime = xml.find('CreateTime').text
replyWx = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
%s
</xml>
'''%(
fromUserName,
toUserName,
createTime,
reply['message_type'],
reply['reply_content']
)
return replyWx
else :
return ''
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "<PASSWORD>" #请按照公众平台官网\基本配置中信息填写
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print "handle/GET func: hashcode, signature: ", hashcode, signature
if hashcode == signature:
return echostr
else:
return ""
except Exception, Argument:
return Argument
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class UserUploadDao(object):
def __init__(self):
self.table = 'user_upload'
self.db = DbHelper()
def insert(self, shopid, openId, orderId, imageId1='', imageId2='', imageId3=''):
try:
self.db.insert(self.table,shop_id=shopid,open_id=openId,order_id=orderId,
image1_id=imageId1, image2_id=imageId2,image3_id=imageId3,
create_time=None, update_time=None)
except :
return False
return True
def insertAutoPass(self,shopid, openId, orderId):
try:
self.db.insert(self.table,shop_id=shopid,open_id=openId,order_id=orderId,
verify_flag=1,accept_flag=0,create_time=None, update_time=None)
except :
return False
return True
def selectByOpenId(self,shopid,openId):
val = {'shopId':shopid,'openId':openId}
rows = self.db.select(self.table, where='shop_id=$shopId and open_id=$openId and del_flag=0 ',
vars=val, order='create_time desc',limit=10)
return rows
def selectByPage(self,start_idx,page_size):
val = {'startId':start_idx}
rows = self.db.select(self.table,where='verify_flag=0 and del_flag=0 and id>=$startId',vars=val,order='id asc',limit=page_size)
return rows
<file_sep>from db_helper import DbHelper
from util.class_decorator import singleton
@singleton
class VerifyRefundDao(object):
def __init__(self):
self.table = 'verify_refund'
self.db = DbHelper()
def selectByOpenId(self,shopid,openId):
# return 30 rows
val = {'shopId':shopid,'openId':openId}
rows = self.db.select(self.table,where='shop_id=$shopId and open_id=$openId',vars=val,order='update_time desc',limit=30)
return rows
def insertVerifyRefund(self,shopId,openId,orderId,money):
self.db.insert(self.table,shop_id=shopId,open_id=openId,order_id=orderId,money=money)
return True
def selectByPage(self,page_size):
rows = self.db.select(self.table,where='refund_flag=0 and del_flag=0',order='id asc',limit=page_size)
return rows
def setRefundFlag(self,id):
val = {'id':id}
self.db.update(self.table,where='id=$id',vars=val,refund_flag=1)<file_sep>from basic import Basic
import urllib
class Media(object):
def __init__(self):
pass
| 080cd35fc559348331470c6885caf94f94040317 | [
"Python",
"PHP",
"INI"
] | 28 | Python | horiebin/ProjectWx | 623287954042ce5d36e591fed89edf02dd0c3f11 | 29db264fe552062b75092558f09ef8e7369319bc |
refs/heads/master | <file_sep>
var database = firebase.database();
var ref = database.ref('products/product');
ref.once('value', gotData, errData);
function gotData(data) {
var data = data.val();
var keys = Object.keys(data);
console.log(keys[2])
console.log(data[keys[2]])
}
function errData(error){
console.log(error.message , error.code)
}
function quickview3() {
for (
var i = 0; i< Object.keys.length; i++){
var data = data.val();
var keys = Object.keys(data);
$(document).ready(function() {
h2.textContent = data[keys[0]].name;
p.textContent = data[keys[1]].name
img.setAttribute('src', 'data[keys[2]].name')
place.appendChild(D1);
});
}
};<file_sep>var D1 = document.createElement('div')
var D2 = document.createElement('div')
var D3 = document.createElement('div')
var D4 = document.createElement('div')
var img = document.createElement('img')
var h2 = document.createElement('h2')
var p = document.createElement('p')
D1.className = "none"
D2.className = "popup-inner"
D1.appendChild(D2)
D2.appendChild(D3)
D2.appendChild(D4)
D3.appendChild(img)
D4.appendChild(h2)
D4.appendChild(p)
var place = document.getElementById('place')
place.appendChild(D1);
place.onclick = function () { D1.className = "none";}
function quickview(info) {
}
function removeD1() {
D1.className = "none";
}
<file_sep>var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "el-motamyz.firebaseapp.com",
databaseURL: "https://el-motamyz.firebaseio.com",
projectId: "el-motamyz",
storageBucket: "el-motamyz.appspot.com",
messagingSenderId: "137501119962",
appId: "1:137501119962:web:15dcd29e9df46e25485ce3",
measurementId: "G-ZS8X5QPQ0R"
};
firebase.initializeApp(firebaseConfig);
var database = firebase.database();
var ref = database.ref('/' + 'products/');
ref.once('value', gotData, errData);
function gotData(data) {
var data = data.val();
var keys = Object.keys(data);
for (var i = 0; i< keys.length; i++){
var k = keys[i];
var img = data[k].img;
var info = {
ai: i,
k: keys[i],
img: data[k].img
};
var ia = document.createElement('a')
var img = document.createElement('img')
var row = document.getElementById('row')
var ianum = i;
ia.className += "box";
ia.id += 'box-' + i ;
ia.appendChild(img)
img.src = data[k].image;
row.appendChild(ia);
ia.onclick = function () {var -yuhqdocument.querySelector('ia').id;}
}
}
function errData(error) {
//console.log(error.message , error.code)
}
//*h2.textContent = data[k].header;p.textContent = data[k].content;img.src = data[k].image;//*
| e0b688be8f6e246210fe861afe7e89cc221a111c | [
"JavaScript"
] | 3 | JavaScript | SitanGuy17/elmotamyz | 7450bd9749296e57a5f8fb9d2a472b6b19e82408 | cb8c23be2e12642179acbc88db348c300c993603 |
refs/heads/master | <file_sep>/*
Copyright 2011 USGS WiM
*/
/*
Author: <NAME>
Created: December 14, 2011
*/
//var basemaps = [];
function createBaseMapGallery() {
var streetBasemapLayer = new esri.dijit.BasemapLayer({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
});
var streetBasemap = new esri.dijit.Basemap({
layers: [streetBasemapLayer],
id: "0",
title: "Street Basemap",
thumbnailUrl: "images/shield.png",
});
basemaps.push(streetBasemap);
var imageryBasemapLayer = new esri.dijit.BasemapLayer({
url: imageryBaseUrl,
});
var imageryBasemap = new esri.dijit.Basemap({
layers: [imageryBasemapLayer],
id: "1",
title: "Imagery Basemap",
thumbnailUrl: "images/satellite.png",
});
basemaps.push(imageryBasemap);
var topoBasemapLayer = new esri.dijit.BasemapLayer({ url: topoBaseUrl });
var topoBasemap = new esri.dijit.Basemap({
layers: [topoBasemapLayer],
id: "2",
title: "Topo Basemap",
thumbnailUrl: "images/mountain.png",
});
basemaps.push(topoBasemap);
basemapGallery = new esri.dijit.BasemapGallery({
showArcGISBasemaps: false,
basemaps: basemaps,
map: map,
});
basemapGallery.startup();
dojo.connect(basemapGallery, "onError", function (error) {
console.log(error);
});
dojo.forEach(basemapGallery.basemaps, function (basemap) {
var newListItem = document.createElement("li");
var newImage = document.createElement("img");
newImage.src = basemap.thumbnailUrl;
newImage.onClick = dojo.hitch(this, function () {
this.basemapGallery.select(basemap.id);
});
newListItem.appendChild(newImage);
//Add an icon button for each basemap
//dijit.byId("basemapBarList").addChild(newListItem);
});
return basemapGallery;
}
function basemapToggle(button, id) {
basemapGallery.select(id);
button.parent().siblings(".current").removeClass("current");
button.parent().addClass("current");
}
<file_sep>// 02.16.12 - NE - javascript file for template
/*
Copyright 2012 USGS WiM
*/
/*
Author: <NAME>
Created: February 16, 2012
*/
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.dijit.BasemapGallery");
dojo.require("esri.dijit.Scalebar");
dojo.require("esri.layers.FeatureLayer");
dojo.require("esri.map");
dojo.require("esri.tasks.Locator");
var mapLayers = [];
var basemaps = [];
var map;
var basemap;
var streetsBaseUrl =
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer";
var imageryBaseUrl =
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer";
var topoBaseUrl =
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer";
var floodQueryTask, floodQuery;
var siteSymSize;
var locator;
function init() {
//Check for mobile
var mobile =
/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(
navigator.userAgent.toLowerCase()
);
if (mobile) {
esri.config.defaults.map.slider = {
top: "105px",
left: "20px",
height: "150px",
width: null,
};
siteSymSize = 16;
$.getScript(
"https://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.1compact"
);
} else {
esri.config.defaults.map.slider = {
top: "105px",
left: "20px",
height: "200px",
width: null,
};
siteSymSize = 10;
}
//Initial zoom extent an map setup
var initExtent = new esri.geometry.Extent({
xmin: -15235725.666483294,
ymin: 2134628.3639278114,
xmax: -5852927.570423835,
ymax: 7178249.23829554,
spatialReference: { wkid: 102100 },
});
map = new esri.Map("map", {
slider: true,
wrapAround180: true,
logo: false,
extent: initExtent,
});
//Loading Screen
dojo.connect(map, "onUpdateStart", function () {
esri.show(dojo.byId("loadingStatus"));
});
dojo.connect(map, "onUpdateEnd", function () {
esri.hide(dojo.byId("loadingStatus"));
});
//Attempt to require
// require(["modules/geocoder", "modules/basemap", "dojo/domReady!"],
// function () {
// console.log('requirement worked?');
// });
//Basemap Toogle
basemapGallery = createBaseMapGallery();
dojo.connect(map, "onLoad", addLayers);
dojo.connect(map, "onLoad", function (theMap) {
//resize the map when the browser resizes
dojo.connect(dijit.byId("map"), "resize", map, map.resize);
});
dojo.connect(map, "onClick", getExtents);
// query for site results
floodQueryTask = new esri.tasks.QueryTask(
"https://wim.usgs.gov/ArcGIS/rest/services/FIMIMapper/fimi_flood_extents/MapServer/0"
);
floodQuery = new esri.tasks.Query();
floodQuery.where = "USGSID ==";
floodQuery.outFields = ["*"];
floodQuery.returnGeometry = true;
floodQuery.outSpatialReference = { wkid: 102100 };
dojo.connect(floodQueryTask, "onComplete", floodResult);
// add scalebar to bottom left of map
var scalebar = new esri.dijit.Scalebar({
map: map,
attachTo: "bottom-left",
});
// add draggable behavior to infoWindow
$("#infoWindow").dialog({ autoOpen: false });
function addLayers(map) {
var content = "<b>site no</b>: ${SITE_NO}";
var siteSym = new esri.symbol.SimpleMarkerSymbol(
esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE,
siteSymSize,
new esri.symbol.SimpleLineSymbol(
esri.symbol.SimpleLineSymbol.STYLE_SOLID,
new dojo.Color("white"),
1
),
new dojo.Color([0, 0, 0, 0.9])
);
var renderer = new esri.renderer.SimpleRenderer(siteSym);
var infoTemplate = new esri.InfoTemplate("Site no: ${SITE_NO}", content);
var fimiSites = new esri.layers.FeatureLayer(
"https://wim.usgs.gov/ArcGIS/rest/services/FIMIMapper/fimi_sites/MapServer/0",
{
mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
outFields: ["*"],
infoTemplate: infoTemplate,
}
);
fimiSites.setRenderer(renderer);
var nwisSWSiteParams = new esri.layers.ImageParameters();
nwisSWSiteParams.format = "PNG24";
var nwisSWSites = new esri.layers.ArcGISDynamicMapServiceLayer(
"https://172.16.17.32/ArcGIS/rest/services/NWIS/nwis_sw_sites/MapServer",
{ opacity: 0.9, imageParameters: nwisSWSiteParams }
);
map.addLayer(nwisSWSites);
map.addLayer(fimiSites);
map.infoWindow.resize(200, 150);
mapLayers.push(fimiSites); //this client side map layer is the maps graphics layer
}
function getExtents(event) {
//click = query.geometry = event.mapPoint;
//floodQueryTask.execute(floodQuery);
// put feature layer select features task in here
// to get the site, then pass site no to floodquerytask
// to get flood extents
}
function floodResult() {}
//Basemap JS
function createBaseMapGallery() {
var streetBasemapLayer = new esri.dijit.BasemapLayer({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
});
var streetBasemap = new esri.dijit.Basemap({
layers: [streetBasemapLayer],
id: "0",
title: "Street Basemap",
thumbnailUrl: "images/shield.png",
});
basemaps.push(streetBasemap);
var imageryBasemapLayer = new esri.dijit.BasemapLayer({
url: imageryBaseUrl,
});
var imageryBasemap = new esri.dijit.Basemap({
layers: [imageryBasemapLayer],
id: "1",
title: "Imagery Basemap",
thumbnailUrl: "images/satellite.png",
});
basemaps.push(imageryBasemap);
var topoBasemapLayer = new esri.dijit.BasemapLayer({ url: topoBaseUrl });
var topoBasemap = new esri.dijit.Basemap({
layers: [topoBasemapLayer],
id: "2",
title: "Topo Basemap",
thumbnailUrl: "images/mountain.png",
});
basemaps.push(topoBasemap);
basemapGallery = new esri.dijit.BasemapGallery({
showArcGISBasemaps: false,
basemaps: basemaps,
map: map,
});
basemapGallery.startup();
dojo.connect(basemapGallery, "onError", function (error) {
console.log(error);
});
dojo.forEach(basemapGallery.basemaps, function (basemap) {
var newListItem = document.createElement("li");
var newImage = document.createElement("img");
newImage.src = basemap.thumbnailUrl;
newImage.onClick = dojo.hitch(this, function () {
this.basemapGallery.select(basemap.id);
});
newListItem.appendChild(newImage);
//Add an icon button for each basemap
//dijit.byId("basemapBarList").addChild(newListItem);
});
return basemapGallery;
}
function basemapToggle(button, id) {
basemapGallery.select(id);
button.parent().siblings(".current").removeClass("current");
button.parent().addClass("current");
}
//Geocoder JS
locator = new esri.tasks.Locator(
"https://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Address_NA_10/GeocodeServer"
);
dojo.connect(locator, "onAddressToLocationsComplete", showResults);
function enterKeyLocate(e) {
var keynum;
if (window.event) {
// IE
keynum = e.keyCode;
} else if (e.which) {
// Netscape/Firefox/Opera
keynum = e.which;
}
if (keynum == 13) {
locate();
}
}
function locate() {
map.graphics.clear();
var address = { SingleLine: dojo.byId("geocode").value };
locator.outSpatialReference = map.spatialReference;
locator.addressToLocations(address, ["Loc_name"]);
}
function showResults(candidates) {
var candidate;
var symbol = new esri.symbol.SimpleMarkerSymbol();
var infoTemplate = new esri.InfoTemplate(
"Location",
"Address: ${address}<br />Score: ${score}<br />Source locator: ${locatorName}"
);
symbol.setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE);
symbol.setColor(new dojo.Color([153, 0, 51, 0.75]));
var geom;
dojo.every(candidates, function (candidate) {
if (candidate.score > 80) {
var attributes = {
address: candidate.address,
score: candidate.score,
locatorName: candidate.attributes.Loc_name,
};
geom = candidate.location;
var graphic = new esri.Graphic(geom, symbol, attributes, infoTemplate);
//add a graphic to the map at the geocoded location
map.graphics.add(graphic);
return false; //break out of loop after one candidate with score greater than 80 is found.
}
});
if (geom !== undefined) {
map.centerAndZoom(geom, 12);
}
}
}
dojo.addOnLoad(init);
function orientationChanged() {
console.log("Orientation changed: " + window.orientation);
if (map) {
map.reposition();
map.resize();
}
}
<file_sep>// 03.06.13 -ESM- Created.
// 03.11.13 -ESM- Added gif div within dijit to increase display speed.
/*
Copyright: 2013 WiM - USGS
Author: <NAME> USGS Wisconsin Internet Mapping
Created: March, 06 2013
*/
dojo.provide("wim.LoadingScreen");
dojo.require("dijit._Container");
dojo.require("dijit._TemplatedMixin");
dojo.require("dijit._WidgetBase");
dojo.declare("wim.LoadingScreen", [dijit._WidgetBase, dijit._Container, dijit._TemplatedMixin],
{
templatePath: dojo.moduleUrl("wim", "templates/LoadingScreen.html"),
baseClass: "loadingScreen",
attachedMapID: null,
constructor: function () {
dojo.create('img', {
id: 'loadingScreenGraphic',
src: 'images/LoadingOrange110.gif',
}, dojo.byId('loadingScreen'));
},
postCreate: function(){
}
});<file_sep>/*@preserve
Copyright 2012 USGS WiM
*/
/*@preserve
Author: <NAME>
Created: October 25, 2012
*/
// 06.19.13 - NE - Updated to include map scale in the latLngScaleBar wimjit. Reworked property so only the map object is needed.
dojo.provide("wim.LatLngScale");
dojo.require("dijit._Container");
dojo.require("dijit._TemplatedMixin");
dojo.require("dijit._WidgetBase");
dojo.require("esri.map");
dojo.declare("wim.LatLngScale", [dijit._WidgetBase, dijit._OnDijitClickMixin, dijit._Container, dijit._TemplatedMixin],
{
templatePath: dojo.moduleUrl("wim", "templates/LatLngScale.html"),
baseClass: "latLngScale",
map: null,
constructor: function () {
},
postCreate: function () {
if (this.map != null) {
//This code centers teh lat/lng box in the mapper after load due to different size screens.
var domNode = this;
var theMap = this.map;
var bodyWidth = dojo.getStyle(document.body, "width");
//Fires scale update on LatLngScale wimjit when zoom level is changed in map.
dojo.connect(theMap, "onZoomEnd", function(extent,zoomFactor,anchor,level) {
domNode._onScaleChange();
});
var center = dojo.style(theMap.container, "width") / 2;
var llsWidth = dojo.style(this.id, "width") / 2;
dojo.style(this.id, 'left', center - llsWidth + "px");
//Set initial scale value
domNode.containerNode.innerHTML = "Map Scale: 1:" + theMap.getScale().toFixed(0);
dojo.connect(dojo.byId(theMap.container.id), "onmousemove", function (evt) {
if (evt.mapPoint != null) {
var mp = esri.geometry.webMercatorToGeographic(evt.mapPoint);
domNode.textNode.innerHTML = "Lat: " + mp.y.toFixed(4) + ", Lng: " + mp.x.toFixed(4);
if (bodyWidth != dojo.getStyle(document.body, "width")) {
var center = dojo.style(theMap.container, "width") / 2;
var llsWidth = dojo.style(domNode.id, "width") / 2;
dojo.style(domNode.id, 'left', center - llsWidth + "px");
bodyWidth = dojo.getStyle(document.body, "width");
}
}
});
/*dojo.connect(document.body, "resize", function (evt) {
var center = dojo.style(theMap.container, "width") / 2;
var llsWidth = dojo.style(domNode.id, "width") / 2;
dojo.style(domNode.id, 'left', center - llsWidth + "px");
});*/
} else {
console.log('map property is null');
}
},
_onScaleChange: function () {
this.containerNode.innerHTML = "Map Scale: 1:" + this.map.getScale().toFixed(0);
}
});
<file_sep>
# Bad River Groundwater
The Bad River Groundwater Model Mapper contains three applications to support groundwater modeling in the Bad River watershed.
### Prerequisites
What things you need to install the software and how to install them
```
Give examples
```
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
### Installing
A step by step series of examples that tell you have to get a development env running
Say what the step will be
```
Give the example
```
And repeat
```
until finished
```
## Building and testing
Explain how to run the debugging 'watch' script for this repo, if applicable
Explain how to run unit tests, if applicable
## Deployment
Add additional notes about how to deploy this on a live system. **Do not include any credentials, IP addresses, or other sensitive information**
## Built With
- [Angular](https://angular.io/) - The main web framework used
- [Clarity UI](https://vmware.github.io/clarity/) - Top-level UI framework if you have one
- [NPM](https://www.npmjs.com/) - Dependency Management
- [Others](https://www.npmjs.com/) - Any other high-level dependencies
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us. Please read [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for details on adhering by the [USGS Code of Scientific Conduct](https://www2.usgs.gov/fsp/fsp_code_of_scientific_conduct.asp).
## Versioning
We use [SemVer](https://semver.org/) for versioning. For the versions available, see the [tags on this repository](../../tags).
Advance the version when adding features, fixing bugs or making minor enhancement. Follow semver principles. To add tag in git, type git tag v{major}.{minor}.{patch}. Example: git tag v2.0.5
To push tags to remote origin: `git push origin --tags`
\*Note that your alias for the remote origin may differ.
## Authors
- **[<NAME>](https://www.usgs.gov/staff-profiles/erik-s-myers)** - _Lead Developer_ - [USGS Web Informatics & Mapping](https://wim.usgs.gov/)
See also the list of [contributors](../../graphs/contributors) who participated in this project.
## License
This project is licensed under the Creative Commons CC0 1.0 Universal License - see the [LICENSE.md](LICENSE.md) file for details
## Suggested Citation
In the spirit of open source, please cite any re-use of the source code stored in this repository. Below is the suggested citation:
`This project contains code produced by the Web Informatics and Mapping (WIM) team at the United States Geological Survey (USGS). As a work of the United States Government, this project is in the public domain within the United States. https://wim.usgs.gov`
## Acknowledgments
- Hat tip to anyone who's code was used
- Inspiration Note
## About WIM
- This project authored by the [USGS WIM team](https://wim.usgs.gov)
- WIM is a team of developers and technologists who build and manage tools, software, web services, and databases to support USGS science and other federal government cooperators.
- WIM is a part of the [Upper Midwest Water Science Center](https://www.usgs.gov/centers/wisconsin-water-science-center).
| 91bdb309d1a0e1b86046c5666cd85ea4b7aa258b | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | USGS-WiM/BadRiverGroundwater | edea433545dddef99cf5356606663395d23d9119 | 6da946d70c4ff7613127227d6d900228a88d0a33 |
refs/heads/master | <repo_name>furkansoyturk/shufflebox<file_sep>/App.js
import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
votesJson = "VOTES";
playlistJson = "playlist";
this.state = {
Button1Text: "Song1",
Button2Text: "Song2",
Button3Text: "Song3",
Button4Text: "Song4",
Button5Text: "Song5",
Button6Text: "VOTES"
};
}
_onPressButton(event, buttonID) {
Alert.alert("Voted for song " + buttonID)
fetch('http://192.168.1.131:3000/sendvote', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
songid: buttonID,
}),
});
}
getVotesFromServer() {
fetch('http://192.168.1.131:3000/getinfo')
.then(function (response) {
return response.json();
})
.then(function (receivedJson) {
//console.log(JSON.stringify(myJson));
//console.log(myJson.votesForSong1);
//this.setState({titleText: myJson.votesForSong1});
votesJson = receivedJson;
});
this.setState({Button6Text: JSON.stringify(votesJson)});
//this.setState({titleText: ""+votesJson.votesForSong1});
console.log(votesJson.votesForSong1);
}
getPlaylistFromServer() {
fetch('http://192.168.1.131:3000/getplaylist')
.then(function (response) {
return response.json();
})
.then(function (receivedJson) {
//console.log(JSON.stringify(myJson));
//console.log(myJson.votesForSong1);
//this.setState({titleText: myJson.votesForSong1});
playlistJson = receivedJson;
});
//var trackname = playlistJson[0].track.name;
//this.setState({titleText: ""+trackname});
//console.log("TRACKNAME:"+trackname);
}
setButtonTexts() {
try {
var trackname = playlistJson[0].track.name;
this.setState({Button1Text: ""+trackname});
trackname = playlistJson[1].track.name;
this.setState({Button2Text: ""+trackname});
trackname = playlistJson[2].track.name;
this.setState({Button3Text: ""+trackname});
trackname = playlistJson[3].track.name;
this.setState({Button4Text: ""+trackname});
trackname = playlistJson[4].track.name;
this.setState({Button5Text: ""+trackname});
}
catch(err) {
console.log("ERROR!!!!!!!!!!!!!!!!")
}
}
componentDidMount() {
this.timer = setInterval(() => this.getVotesFromServer(), 1000)
this.timer = setInterval(() => this.getPlaylistFromServer(), 1000)
this.timer = setInterval(() => this.setButtonTexts(), 1000)
}
render() {
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button
onPress={(event) => this._onPressButton(event, '1')}
title={this.state.Button1Text}
color="#841584"
/>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={(event) => this._onPressButton(event, '2')}
title={this.state.Button2Text}
color="#841584"
/>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={(event) => this._onPressButton(event, '3')}
title={this.state.Button3Text}
color="#841584"
/>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={(event) => this._onPressButton(event, '4')}
title={this.state.Button4Text}
color="#841584"
/>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={(event) => this._onPressButton(event, '5')}
title={this.state.Button5Text}
color="#841584"
/>
</View>
<View style={styles.buttonContainer}>
<Button
title={this.state.Button6Text}
color="#841584"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
buttonContainer: {
margin: 20,
},
});
<file_sep>/Vote.js
import React, { Component } from 'react';
import { Alert, Button, Text, StyleSheet, View, Image, AppRegistry, ScrollView } from 'react-native';
import { CardSection, Card, } from './components/common';
class Vote extends Component {
constructor(props) {
super(props);
votesJson = "VOTES";
playlistJson = "playlist";
votablesJson = " ";
this.state = {
Button1Text: "Song1",
Button2Text: "Song2",
Button3Text: "Song3",
Button4Text: "Song4",
Button5Text: "Song5",
Button6Text: "VOTES",
Button7Text: "Winner",
Button8Text: "currentPlaying",
img1url: "img1",
img2url: "img2",
img3url: "img3",
img4url: "img4",
img5url: "img5",
img6url: "img6",
img7url: "img7"
};
}
_onPressButton(event, buttonID) {
Alert.alert("Voted for song " + buttonID)
fetch('http://192.168.0.128:3000/sendvote', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
songid: buttonID,
}),
});
}
getVotesFromServer() {
fetch('http://192.168.0.128:3000/getinfo')
.then(function (response) {
return response.json();
})
.then(function (receivedJson) {
//console.log(JSON.stringify(myJson));
//console.log(myJson.votesForSong1);
//this.setState({titleText: myJson.votesForSong1});
votesJson = receivedJson;
});
this.setState({Button6Text: JSON.stringify(votesJson)});
//this.setState({titleText: ""+votesJson.votesForSong1});
console.log(votesJson.votesForSong1);
}
getPlaylistFromServer() {
fetch('http://192.168.0.128:3000/getplaylist')
.then(function (response) {
return response.json();
})
.then(function (receivedJson) {
//console.log(JSON.stringify(myJson));
//console.log(myJson.votesForSong1);
//this.setState({titleText: myJson.votesForSong1});
playlistJson = receivedJson;
console.log(playlistJson[0].track.album.images[0].url);
});
//var trackname = playlistJson[0].track.name;
//this.setState({titleText: ""+trackname});
//console.log("TRACKNAME:"+trackname);
}
getVotablesFromServer() {
fetch('http://192.168.0.128:3000/getvotables')
.then(function (response) {
return response.json();
})
.then(function (receivedJson) {
//console.log(JSON.stringify(myJson));
//console.log(myJson.votesForSong1);
//this.setState({titleText: myJson.votesForSong1});
votablesJson = receivedJson;
console.log(votablesJson);
});
//var trackname = playlistJson[0].track.name;
//this.setState({titleText: ""+trackname});
//console.log("TRACKNAME:"+trackname);
}
setButtonTexts() {
try {
var trackname = playlistJson[votablesJson[0]].track.name;
this.setState({Button1Text: ""+trackname});
trackname = playlistJson[votablesJson[1]].track.name;
this.setState({Button2Text: ""+trackname});
trackname = playlistJson[votablesJson[2]].track.name;
this.setState({Button3Text: ""+trackname});
trackname = playlistJson[votablesJson[3]].track.name;
this.setState({Button4Text: ""+trackname});
trackname = playlistJson[votablesJson[4]].track.name;
this.setState({Button5Text: ""+trackname});
trackname = playlistJson[votesJson.lastWinner].track.name;
this.setState({Button7Text: ""+trackname});
trackname = votesJson.currentlyPlayingName;
this.setState({Button8Text: ""+trackname});
}
catch(err) {
console.log("ERROR!!!!!!!!!!!!!!!!")
}
}
setButtonImages() {
try {
var trackImage = playlistJson[votablesJson[0]].track.album.images[0].url;
this.setState({img1url: ""+trackImage});
var trackImage = playlistJson[votablesJson[1]].track.album.images[0].url;
this.setState({img2url: ""+trackImage});
var trackImage = playlistJson[votablesJson[2]].track.album.images[0].url;
this.setState({img3url: ""+trackImage});
var trackImage = playlistJson[votablesJson[3]].track.album.images[0].url;
this.setState({img4url: ""+trackImage});
var trackImage = playlistJson[votablesJson[4]].track.album.images[0].url;
this.setState({img5url: ""+trackImage});
var trackImage = playlistJson[votesJson.lastWinner].track.album.images[0].url;
this.setState({img6url: ""+trackImage});
var trackImage = votesJson.currentlyPlayingUrl;
this.setState({img7url: ""+trackImage});
}
catch(err) {
console.log("ERROR!!!!!!!!!!!!!!!!")
}
}
componentDidMount() {
this.timer = setInterval(() => this.getVotesFromServer(), 1000)
this.timer = setInterval(() => this.getVotablesFromServer(), 1000)
this.timer = setInterval(() => this.getPlaylistFromServer(), 1000)
this.timer = setInterval(() => this.setButtonTexts(), 1000)
this.timer = setInterval(() => this.setButtonImages(), 1000)
}
render() {
return (
<ScrollView>
<Card>
<CardSection>
<Image
source={{ uri: this.state.img1url }}
style={{ width: 50, height: 58 }}
/>
<Button
onPress={(event) => this._onPressButton(event, '1')}
title={this.state.Button1Text}
color="#841584"
testID="1"
/>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img2url }}
style={{ width: 50, height: 58 }}
/>
<Button
onPress={(event) => this._onPressButton(event, '2')}
title={this.state.Button2Text}
color="#841584"
testID="2"
/>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img3url }}
style={{ width: 50, height: 58 }}
/>
<Button
onPress={(event) => this._onPressButton(event, '3')}
title={this.state.Button3Text}
color="#841584"
testID="3"
/>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img4url }}
style={{ width: 50, height: 58 }}
/>
<Button
onPress={(event) => this._onPressButton(event, '4')}
title={this.state.Button4Text}
color="#841584"
testID="4"
/>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img5url }}
style={{ width: 50, height: 58 }}
/>
<Button
onPress={(event) => this._onPressButton(event, '5')}
title={this.state.Button5Text}
color="#841584"
testID="5"
/>
</CardSection>
<CardSection>
<Text style={{ fontSize: 50, textAlign: 'center', flex: 1, fontStyle: 'italic', color: 'pink' }}>
Next song
</Text>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img6url }}
style={{ width: 50, height: 58 }}
/>
<Button
title={this.state.Button7Text}
color="#841584"
/>
</CardSection>
<CardSection>
<Text style={{ fontSize: 25, textAlign: 'center', flex: 1, fontStyle: 'italic', color: 'pink' }}>
Currently Playing...
</Text>
</CardSection>
<CardSection>
<Image
source={{ uri: this.state.img7url }}
style={{ width: 50, height: 58 }}
/>
<Button
title={this.state.Button8Text}
color="#841584"
/>
</CardSection>
</Card>
</ScrollView>
);
}
}
export default Vote;
<file_sep>/README.md
# shufflebox
Spotify API OAuth scopes:
user-modify-playback-state,playlist-modify-public,playlist-modify-private,user-read-currently-playing
<file_sep>/spoti_test.js
var Spotify = require('node-spotify-api');
var spotify = new Spotify({
id: '<KEY>',
secret: '<KEY>'
});
spotify
.request('https://api.spotify.com/v1/playlists/3uZ0DcmMUUzola8ZC2HxRn/tracks')
.then(function(data) {
// data'da items diye bi array geliyor onun track objeleri var
//console.log(data);
console.log(data.items[1].track.name);
})
.catch(function(err) {
console.error('Error occurred: ' + err);
});
//spotify:user:11100316938:playlist:3uZ0DcmMUUzola8ZC2HxRn
spotify
.request('https://api.spotify.com/v1/playlists/3uZ0DcmMUUzola8ZC2HxRn/tracks')
.then(function(data) {
//console.log(data);
console.log(data.items[1].track.name);
})
.catch(function(err) {
console.error('Error occurred: ' + err);
});
| ba8615af0d17d9c8b1fbce5967df3b1319ad491a | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | furkansoyturk/shufflebox | 6f9b66770840dd89be5f616b5f8b6c3cc4ae5c7d | 188197662e610dedb5f728eecbd8248f56b4afe0 |
refs/heads/master | <file_sep>package br.ufsc.ine.agent;
import java.io.File;
import java.io.IOException;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import agent.AgentLexer;
import agent.AgentParser;
import br.ufsc.ine.parser.AgentWalker;
import br.ufsc.ine.parser.VerboseListener;
public class Main {
public static void main(String[] args) {
//String filename = getLastArgument(args);
// String filename="/home/valdirluiz/works/agent-project/examples/annotation";
String filename="/home/valdirluiz/works/agent-project/examples/ex1";
File file = new File(filename);
if (!file.exists()) {
System.out.println("File " + filename + " not found.");
return;
}
try {
CharStream stream = CharStreams.fromFileName(filename);
AgentLexer lexer = new AgentLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
AgentParser parser = new AgentParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new VerboseListener());
ParseTree tree = parser.agent();
ParseTreeWalker walker = new ParseTreeWalker();
AgentWalker agentWalker = new AgentWalker();
walker.walk(agentWalker, tree);
Agent agent = new Agent();
agent.run(agentWalker, null);
} catch (IOException e) {
System.out.println("I/O exception.");
}
}
private static String getLastArgument(String[] args) {
return args[args.length - 1];
}
}
<file_sep>package br.ufsc.ine.agent.context.custom;
import java.util.ArrayList;
import java.util.List;
import alice.tuprolog.InvalidTheoryException;
import alice.tuprolog.MalformedGoalException;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Theory;
import br.ufsc.ine.agent.bridgerules.Body;
import br.ufsc.ine.agent.bridgerules.BridgeRule;
import br.ufsc.ine.agent.bridgerules.Head;
import br.ufsc.ine.agent.context.ContextService;
import br.ufsc.ine.agent.context.beliefs.BeliefsContextService;
import br.ufsc.ine.agent.context.communication.CommunicationContextService;
import br.ufsc.ine.agent.context.desires.DesiresContextService;
import br.ufsc.ine.utils.PrologEnvironment;
public class CustomContext implements ContextService {
protected CustomContext instance;
protected String name;
protected PrologEnvironment prologEnvironment;
public CustomContext(String name){
instance = this;
this.name = name;
prologEnvironment = new PrologEnvironment();
}
@Override
public Theory getTheory() {
return prologEnvironment.getEngine().getTheory();
}
public List<BridgeRule> callRules() {
return null;
}
public void printBeliefs() {
System.out.println(this.getName()+":");
System.out.println(prologEnvironment.getEngine().getTheory().toString().trim().replaceAll("\\n\\n", "\n"));
System.out.println("\n");
}
@Override
public boolean verify(String fact) {
SolveInfo solveGoal;
try {
solveGoal = prologEnvironment.solveGoal(fact);
return solveGoal.isSuccess();
} catch (MalformedGoalException e) {
return false;
}
}
@Override
public void appendFact(String fact) {
try {
prologEnvironment.appendFact(fact);
} catch (InvalidTheoryException e) {
e.printStackTrace();
}
}
@Override
public void addInitialFact(String fact) throws InvalidTheoryException {
}
@Override
public String getName() {
return this.name;
}
}
| 8ee89fa8e68e8c11aabe56570692568b160902d6 | [
"Java"
] | 2 | Java | FelipeRFP/sigon-lang | 60a4ff89d2dc04730b904d6bdf2916221abd4d70 | 6b343c08c147427806be1364ea248bc5938e5547 |
refs/heads/master | <file_sep>import entryBuilder from "./entryHTML.js"
/*
Responsible for putting entries on the DOM
*/
const renderEntries = {
renderJournalEntries: (entries) => {
document.querySelector(".entry--Container").innerHTML += entryBuilder.makeJournal(entries);
},
renderSingleEntry: (entry) => {
document.querySelector(".edit--Container").innerHTML = entryBuilder.editJournal(entry);
}
}
export default renderEntries<file_sep>const API = {
// This method gets all entries from JSON
getJournalEntries: () => {
return fetch("http://localhost:3000/entries")
.then(response => response.json())
},
// Use `fetch` with the POST method to put entry in jSON
saveJournalEntry: (entryObject) => {
return fetch("http://localhost:3000/entries", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(entryObject)
})
.then(response => response.json())
},
// Use `fetch` with the DELETE method to remove entry JSON
deleteEntries: (id) => {
return fetch(`http://localhost:3000/entries/${id}`, {
method: "DELETE"
}).then(response => response.json())
},
editEntries: (id) => {
const entryUpdateObject = {
name: document.querySelector(".entry--Container").value
}
return fetch(`http://localhost:3000/entries/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(entryUpdateObject)
}).then(response => response.json())
},
getSingle: (entryId) => {
return fetch(`http://localhost:3000/entries/${entryId}`)
.then(response => response.json())
}
}
export default API
//Previous Code
/* import renderEntries from "./entriesDOM.js"
const API = {
getJournalEntries() {
return fetch("http://localhost:3000/entries")
.then(response => response.json())
// .then(res => console.log(res))
.then(res => renderEntries.renderJournalEntries(res))
},
// Use `fetch` with the POST method to add your entry to your API
saveJournalEntry(entryObject) {
return fetch("http://localhost:3000/entries", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(entryObject)
})
.then(response => response.json())
.then(res => {
})
}
}
export default API;
*/<file_sep>//import editForm from "./editEntry";
const entryBuilder = {
makeJournal: (entries) => {
return `
<div class="makejournal">
<h2 id="date">${entries.date}</h2>
<section id="concept">${entries.concept}</section>
<section id="entry">${entries.entry}</section>
<aside id="mood">${entries.mood}</aside>
<button type="button" id="deleteEntry--${entries.id}">
Delete Entry
</button>
<button type="button" id="btnEditEntry--${entries.id}">
Edit Entry
</button>
</div>
`
},
editJournal: (response) => {
const editTitle = response.concept;
const editDate = response.date;
const editEntry = response.entry;
const editMood = response.mood;
document.querySelector(".edit--Container").innerHTML =
`
<form>
<input id="concept" value="${editTitle}"/>
<input id="date" type="date" value="${editDate}"/>
<input id="entry" value="${editEntry}"/>
<select value="${editMood}">
<option value="Blissful">Blissful</option>
<option value="Cheerful">Cheerful</option>
<option value="Excited">Excited</option>
<option value="Mellow">Mellow</option>
<option value="Loving">Loving</option>
<option value="Energetic">Energetic</option>
<option value="Peaceful">Peaceful</option>
<option value="Silly">Silly</option>
<option value="Sympathetic">Sympathetic</option>
<option value="Angry">Angry</option>
<option value="Annoyed">Annoyed</option>
<option value="Apathetic">Apathetic</option>
<option value="Cranky">Cranky</option>
<option value="Guilty">Guilty</option>
<option value="Melancholy">Melancholy</option>
<option value="Rejected">Rejected</option>
<option value="Restless">Restless</option>
<option value="Sad">Sad</option>
<option value="Weird">Weird</option>
</select>
<button id="saveEntry">Save Entry</button>
</form>
`
}
}
export default entryBuilder;<file_sep># Daily-Journal-NSS
# Make Journal for NSS adding html, css, js over time
<file_sep>//Functions that builds the Journal Entry
const newJournalEntry = (date, concepts, entry, mood) => {
const newEntry = {
concept: concepts,
date: date,
entry: entry,
mood: mood
}
return newEntry
}
export default newJournalEntry<file_sep>import newJournalEntry from "./journal.js"
import API from "./dataAPIs.js"
import renderEntries from "./entriesDOM.js"
import entryBuilder from "./entryHTML.js"
//import editForm from "./editEntry.js"
// Renders previous journal entries
API.getJournalEntries().then((allEntries) => {
allEntries.forEach(entry => {
renderEntries.renderJournalEntries(entry)
})
})
//Event Listener to save Journal Entry to JSON and Put on DOM
document.querySelector("#btnSaveJournal").addEventListener("click", () => {
// Collected Form Field Values
const date = document.querySelector("#date").value;
const concepts = document.querySelector("#concepts").value;
const entry = document.querySelector("#entry").value;
const mood = document.querySelector("#mood").value;
/* Input validation
const validCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,(){}:;-!?"
const validateInputString = (string) => {
return string.split('').filter(character => validCharacters.includes(character)).join('');
}
validateInputString(concepts);
validateInputString(entry);
*/
if (date === "" || concepts === "" || entry === "" || mood === "") {
return alert("Nope to empty")
} else {
// Build New Journal Object
const entryObject = newJournalEntry(date, concepts, entry, mood)
// Clear inputs
document.querySelector("#date").value = "";
document.querySelector("#concepts").value = "";
document.querySelector("#entry").value = "";
document.querySelector("#mood").value = "";
// Save object to JSON
API.saveJournalEntry(entryObject)
// Send Entry to the DOM
renderEntries.renderJournalEntries(entryObject)
}
});
// Delete Entries & Edit Entries
const entriesContainer = document.querySelector(".entry--Container").addEventListener("click", (event) => {
if (event.target.id.startsWith("deleteEntry--")) {
// Extract entry id from the button's id attribute
document.querySelector(".entry--Container").innerHTML = "";
// Calls method to delete specified entries
API.deleteEntries(event.target.id.split("--")[1])
// Get all entries and post
.then(response => {
API.getJournalEntries().then((allEntries) => {
allEntries.forEach(entry => {
renderEntries.renderJournalEntries(entry)
})
})
})
} else if (event.target.id.startsWith("btnEditEntry--")) {
// Get specific entry
API.getSingle(event.target.id.split("--")[1])
.then(response => {
entryBuilder.editJournal(response)
})
}
})
// Save Entry Button
document.querySelector(".entry--Container").addEventListener("click", (event) => {
API.editEntries(document.querySelector("#entryId").value)
.then(response => {
document.querySelector("#entryId").value = "";
document.querySelector(".edit--Container").innerHTML = "";
})
}) | a962d0544c60889af48f8bd164053048fd9b1c30 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | DylPickle11/Daily-Journal-NSS | 1bf49d412bc384fba3d5ba4d24da35332ca2e1b7 | 077d63bdde72fbfa173a37689c54b1f5738ce8f4 |
refs/heads/master | <repo_name>Angrymos/react-chat-client<file_sep>/src/components/Avatar.js
import React from 'react';
import MUIAvatar from '@material-ui/core/Avatar';
import getColor from '../utils/color-from';
import titleInitials from '../utils/title-initial';
import { withStyles } from '@material-ui/core/styles';
const styles = {
row: {
display: 'flex',
justifyContent: 'center',
},
};
const Avatar = ({ classes, colorFrom, children, ...rest }) => (
<div className={classes.row}>
<MUIAvatar style={{ backgroundColor: getColor(colorFrom), margin: 10 }} {...rest}>
{titleInitials(children)}
</MUIAvatar>
</div>
);
export default withStyles(styles)(Avatar);
<file_sep>/src/pages/chatPage/Sidebar.js
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import TextField from '@material-ui/core/TextField';
import Divider from '@material-ui/core/Divider';
import Button from '@material-ui/core/Button';
import AddIcon from '@material-ui/icons/Add';
import Modal from '@material-ui/core/Modal';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
import RestoreIcon from '../../../node_modules/@material-ui/icons/Restore';
import Explore from '../../../node_modules/@material-ui/icons/Explore';
import ChatList from './sideBar/ChatList';
const styles = {
bottomNavigation: {
width: 319,
},
drawerPaper: {
position: 'absolute',
width: 320,
},
drawerHeader: {
paddingLeft: 24,
paddingRight: 24,
},
textField: {
paddingLeft: 24,
paddingRight: 24,
paddingBottom: 7,
width: '100%',
},
addButton: {
position: 'absolute',
left: 'auto',
right: 24,
bottom: 72,
},
modalWrapper: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
modal: {
width: '30%',
minWidth: '300px',
padding: 24,
},
};
class Sidebar extends React.Component {
state = {
isModalOpen: false,
title: '',
activeTab: 0,
searchValue: '',
};
handleOnToggleModal = () => {
this.setState({
isModalOpen: !this.state.isModalOpen,
});
};
handleOnChangeTitle = (event) => {
this.setState({
title: event.target.value,
});
};
handleOnChangeSearchValue = (event) => {
this.setState({
searchValue: event.target.value,
});
};
handleOnClickCreate = () => {
this.props.onClickCreateChat(this.state.title);
this.handleOnToggleModal();
};
handleOnChangeTab = (event, value) => {
this.setState({
activeTab: value,
});
};
filterChats = (chats) => {
const { searchValue } = this.state;
return chats
.filter(chat => chat.title.toLowerCase().includes(searchValue.toLowerCase()))
.sort((one, two) => (one.title.toLowerCase() <= two.title.toLowerCase() ? -1 : 1));
};
render() {
const { classes, chats, activeChat, setActiveChat, isConnected } = this.props;
const { isModalOpen, title, activeTab, searchValue } = this.state;
return (
<Drawer
variant='permanent'
classes={{ paper: classes.drawerPaper }}
>
<div className={classes.drawerHeader}>
<TextField
id='standard-with-placeholder'
placeholder='Search chats'
className={classes.textField}
margin='normal'
value={searchValue}
onChange={this.handleOnChangeSearchValue}
/>
</div>
<Divider />
<ChatList
disabled={!isConnected}
chats={this.filterChats(activeTab === 0 ? chats.my : chats.all)}
activeChat={activeChat}
setActiveChat={setActiveChat}
/>
<Button
variant='fab'
color='primary'
aria-label='Add'
onClick={this.handleOnToggleModal}
className={classes.addButton}
disabled={!isConnected}
>
<AddIcon />
</Button>
<Modal
open={isModalOpen}
className={classes.modalWrapper}
onClose={this.handleOnToggleModal}
>
<Paper className={classes.modal}>
<Typography variant='title' id='modal-title'>
Create new chat
</Typography>
<TextField
required
fullWidth
name='chatname'
label='New name'
type='text'
margin='normal'
value={title}
onChange={this.handleOnChangeTitle}
/>
<Button color='primary' onClick={this.handleOnClickCreate}>
Create
</Button>
</Paper>
</Modal>
<BottomNavigation
value={activeTab}
onChange={this.handleOnChangeTab}
showLabels
className={classes.root}
>
<BottomNavigationAction label='My Chats' icon={<RestoreIcon />} />
<BottomNavigationAction label='Explore' icon={<Explore />} />
</BottomNavigation>
</Drawer>
);
}
}
export default withStyles(styles)(Sidebar);
<file_sep>/src/pages/chatPage/chat/MessageInput.js
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Input from '@material-ui/core/Input';
import Paper from '@material-ui/core/Paper';
import Button from '../../../../node_modules/@material-ui/core/Button/Button';
const styles = theme => ({
messageInputWrapper: {
position: 'fixed',
left: 'auto',
right: 32,
bottom: 0,
width: 'calc(100% - 352px)',
padding: theme.spacing.unit * 3,
},
messageInput: {
padding: theme.spacing.unit * 2,
},
});
class MessageInput extends React.Component {
state = {
value: '',
};
handleOnChangeInput = (event) => {
this.setState({
value: event.target.value,
});
};
handleOnKeyPress = (event) => {
const { value } = this.state;
if (event.key === 'Enter' && value) {
this.props.sendMessage(value);
this.setState({ value: '' });
}
};
render() {
const { classes, onClickJoin, showJoinButton, disabled } = this.props;
return (
<div className={classes.messageInputWrapper}>
<Paper className={classes.messageInput} elevation={6}>
{showJoinButton ? (
<Button
disabled={disabled}
fullWidth
variant='raised'
color='primary'
onClick={onClickJoin}
>
Join
</Button>
) : (
<Input
disabled={disabled}
fullWidth
placeholder='Type your message…'
value={this.state.value}
onChange={this.handleOnChangeInput}
onKeyPress={this.handleOnKeyPress}
/>
)}
</Paper>
</div>
);
}
}
export default withStyles(styles)(MessageInput);
<file_sep>/src/redux/actions/users.js
import * as types from '../constants/users';
import callApi from '../../utils/call-api';
export const editUserInfo = ({ username, firstName, lastName }) => (dispatch, getState) => {
const state = getState();
const { isFetching } = state.services;
const { token } = state.auth;
if (isFetching.editUser) {
return Promise.resolve();
}
dispatch({
type: types.EDIT_USER_INFO_REQUEST,
});
return callApi('/users/me', token, { method: 'POST' }, {
data: { username, firstName, lastName },
})
.then(json => {
dispatch({
type: types.EDIT_USER_INFO_SUCCESS,
payload: json,
});
})
.catch(reason => dispatch({
type: types.EDIT_USER_INFO_FAILURE,
payload: reason,
}));
};
<file_sep>/src/pages/chatPage/sideBar/ChatListItem.jsx
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import moment from 'moment';
import ListItemText from '@material-ui/core/ListItemText';
import deepPurple from '../../../../node_modules/@material-ui/core/colors/deepPurple';
import Avatar from '../../../components/Avatar';
import { Link } from 'react-router-dom';
import ListItem from '../../../../node_modules/@material-ui/core/ListItem/ListItem';
import { Route } from 'react-router-dom';
const styles = theme => ({
purpleAvatar: {
margin: 10,
color: '#fff',
backgroundColor: deepPurple[500],
},
});
class ChatListItem extends React.Component {
handleOnClick = (history, chat) => () => {
if (this.props.disabled) return;
history.push(`/chat/${chat._id}`);
};
render() {
const { classes, value, active, chat } = this.props;
return (
<Route
render={({ history }) => (
<ListItem
button
component={Link}
to={`/chat/${chat._id}`}
className={active ? classes.activeItem : ''}
key={value}
onClick={this.handleOnClick(history, chat)}
>
<Avatar colorFrom={chat.title}>{chat.title}</Avatar>
<ListItemText primary={chat.title} secondary={moment(chat.createdAt).fromNow()} />
</ListItem>
)}
/>
);
};
}
export default withStyles(styles)(ChatListItem);
<file_sep>/src/redux/containers/ChatPage.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchAllChats, setActiveChat, fetchMyChats, deleteChat, createChat, joinChat, leaveChat } from '../actions/chats';
import { logout } from '../actions/auth';
import { editUserInfo } from '../actions/users';
import { sendMessage, mountChat, unmountChat, socketsConnect } from '../actions/sockets';
import * as chatsSelector from '../reducers/chats';
import * as usersSelector from '../reducers/index';
import ChatPage from '../../pages/ChatPage';
const mapStateToProps = state => {
const activeChat = chatsSelector.getById(state.chats, state.chats.activeId);
return {
isAuthenticated: state.auth.isAuthenticated,
chats: {
active: activeChat,
my: chatsSelector.getByIds(state.chats, state.chats.myIds),
all: chatsSelector.getByIds(state.chats, state.chats.allIds),
},
activeUser: {
...state.auth.user,
isMember: usersSelector.isMember(state, activeChat),
isChatMember: usersSelector.isChatMember(state, activeChat),
isCreator: usersSelector.isCreator(state, activeChat),
},
messages: state.messages,
error: state.services.errors.chat,
isConnected: state.services.isConnected,
};
};
const mapDispatchToProps = dispatch => bindActionCreators({
logout,
editUserInfo,
joinChat,
leaveChat,
deleteChat,
createChat,
fetchAllChats,
fetchMyChats,
setActiveChat,
sendMessage,
mountChat,
unmountChat,
socketsConnect
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ChatPage);
<file_sep>/src/pages/ChatPage.js
import React from 'react';
import ChatHeader from './chatPage/ChatHeader';
import Sidebar from './chatPage/Sidebar';
import Chat from './chatPage/Chat';
import ErrorMessage from '../components/ErrorMessage';
class ChatPage extends React.Component {
componentDidMount() {
const { match, fetchAllChats, fetchMyChats, socketsConnect, mountChat, setActiveChat } = this.props;
Promise.all([
fetchMyChats(),
fetchAllChats(),
])
.then(() => {
socketsConnect();
})
.then(() => {
const { chatId } = match.params;
if (chatId) {
setActiveChat(chatId);
mountChat(chatId);
}
});
}
componentWillReceiveProps(nextProps) {
const { match: { params }, setActiveChat, unmountChat, mountChat } = this.props;
const { params: nextParams } = nextProps.match;
if (nextParams.chatId && params.chatId !== nextParams.chatId) {
setActiveChat(nextParams.chatId);
unmountChat(params.chatId);
mountChat(nextParams.chatId);
}
}
render() {
const {
chats,
messages,
logout,
editUserInfo,
deleteChat,
createChat,
activeUser,
joinChat,
leaveChat,
setActiveChat,
sendMessage,
error,
isConnected,
} = this.props;
return (
<>
<ChatHeader
logout={logout}
editUserInfo={editUserInfo}
deleteChat={deleteChat}
leaveChat={leaveChat}
activeUser={activeUser}
activeChat={chats.active}
isConnected={isConnected}
/>
<Sidebar
chats={chats}
activeChat={chats.active}
onClickCreateChat={createChat}
setActiveChat={setActiveChat}
isConnected={isConnected}
/>
<Chat
messages={messages}
activeChat={chats.active}
activeUser={activeUser}
joinChat={joinChat}
sendMessage={sendMessage}
setActiveChat={setActiveChat}
isConnected={isConnected}
/>
<ErrorMessage error={error}/>
</>
);
}
};
export default ChatPage;
<file_sep>/src/pages/chatPage/Chat.js
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import MessageInput from './chat/MessageInput';
import ChatMessageList from './chat/ChatMessageList';
import Paper from '@material-ui/core/Paper/Paper';
import Typography from '@material-ui/core/Typography';
const styles = theme => ({
content: {
position: 'absolute',
left: 320,
top: 0,
right: 0,
bottom: 0,
overflowY: 'hidden',
backgroundColor: theme.palette.background.default,
},
toolbar: theme.mixins.toolbar,
});
const Chat = ({ classes, messages, activeChat, activeUser, joinChat, sendMessage, isConnected }) => {
return (
<>
<main className={classes.content}>
<div className={classes.toolbar} />
<ChatMessageList
messages={messages}
activeUser={activeUser}
activeChat={activeChat}
/>
{activeChat && <MessageInput
disabled={!isConnected}
sendMessage={sendMessage}
showJoinButton={!activeUser.isChatMember}
onClickJoin={() => joinChat(activeChat._id)}
activeUser={activeUser}
/>}
</main>
</>
);
};
export default withStyles(styles)(Chat);
<file_sep>/src/pages/chatPage/chat/ChatMessageList.js
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import ChatMessage from './ChatMessage';
import Paper from '@material-ui/core/Paper/Paper';
import Typography from '@material-ui/core/Typography';
const styles = theme => ({
messagesWrapper: {
top: 64,
bottom: 0,
paddingBottom: 120,
position: 'absolute',
width: '100%',
overflowY: 'scroll',
},
paper: {
padding: theme.spacing.unit * 3,
},
wrapper: {
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}
});
class ChatMessageList extends React.Component {
constructor(props) {
super(props);
this.messagesWrapper = React.createRef();
}
componentDidMount() {
this.scrollDownHistory();
}
componentDidUpdate() {
this.scrollDownHistory();
}
scrollDownHistory() {
const messagesWrapper = this.messagesWrapper.current;
if (messagesWrapper) {
messagesWrapper.scrollTop = messagesWrapper.scrollHeight;
}
}
render() {
const { classes, messages, activeUser, activeChat } = this.props;
if (!activeChat) {
return (
<div className={classes.wrapper}>
<Paper className={classes.paper}>
<Typography variant='display1' gutterBottom>
Start messaging…
</Typography>
<Typography variant='body1' gutterBottom>
Use <strong>Global</strong> to explore communities around here.
</Typography>
<Typography variant='body1' gutterBottom>
Use <strong>Recents</strong> to see your recent conversations.
</Typography>
</Paper>
</div>
);
}
return (
<div className={classes.messagesWrapper} ref={this.messagesWrapper}>
{messages && messages.map((message, index) => (
<ChatMessage
key={index}
activeUserId={activeUser._id}
message={message}
/>
))}
</div>
);
}
}
export default withStyles(styles)(ChatMessageList);
<file_sep>/src/redux/actions/services.js
import * as types from '../constants/services';
import history from '../../utils/history';
export const redirect = (to) => (dispatch) => {
history.push(to);
dispatch({
type: types.REDIRECT,
payload: { to },
});
};
| 7e961fe5062999999c45be86ecf3ae91db9c0e70 | [
"JavaScript"
] | 10 | JavaScript | Angrymos/react-chat-client | 76f340497fc52b50622ddfef383cf2b4a1d51568 | 620f63e5975c832b8d86a4b395eb936747ed6fc4 |
refs/heads/master | <repo_name>jackrizza/image-converter<file_sep>/image.py
from PIL import Image
import glob, os
import sys
class Image(filePath):
filePath = filePath
def __init__ (self) :
for file in glob.glob(filePath + "/*.*"):
filepath = os.path.realpath(file)
im = Image.open(file)
file = file.strip("../")
filepath = filepath.strip(file)
file = file.strip('.jpeg')
print(file)
if not os.path.exists(filepath + "output"):
os.makedirs(filepath + "output")
im.save(filepath + "output/" + file + ".jpg", "JPEG")
<file_sep>/README.md
# image-converter
imaging folder is the Python Image Library which can be seen here [PIL](http://www.pythonware.com/products/pil/)<file_sep>/main.py
from Tkinter import *
from ttk import Frame, Button, Style
from tkintertable import TableCanvas, TableModel
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
scrollbar = Scrollbar(self)
scrollbar.pack(side=RIGHT, fill=Y)
dirLabel = Label(self, text="Directory Path of all files",)
dirLabel.pack(side=TOP)
fileText = Entry(self, text="test", width=90)
fileText.pack(side=TOP)
outputLabel = Listbox(self, yscrollcommand=scrollbar.set, width=90)
outputLabel.pack(side=TOP)
var = StringVar(self)
var.set("format type") # initial value
menu = OptionMenu(self, var, "png", "jpg")
menu.pack(side=TOP)
self.parent.title("Bulk Image Converter")
self.style = Style()
#self.style.theme_use("clam")
frame = Frame(self, relief=RAISED)
frame.pack(fill=NONE, expand=True)
self.pack(fill=BOTH, expand=True)
def image (text, var) :
from PIL import Image
import glob, os
import sys
#/Users/augustus/Pictures/iep/
filepath = text
print('working....\n')
if not os.path.exists(filepath):
print('not a file path\n' + filepath)
for file in glob.glob(filepath + "/*.*"):
im = Image.open(file)
file = file.strip("../")
file = file.strip(".jpg")
file = file.strip(".jpeg")
file = file.strip(".png")
file = file.strip(".tiff")
file = file.strip(filepath)
if not os.path.exists(filepath + "output"):
os.makedirs(filepath + "output")
print(file)
outputLabel.insert(END, file)
if var == "jpg" :
im.save(filepath + "output/" + file + ".jpg", "JPEG")
elif var == "png" :
im.save(filepath + "output/" + file + ".png", "PNG")
else :
im.save(filepath + "output/" + file + ".jpg", "JPEG")
def fileTextDef () :
image(fileText.get(), var.get())
okButton = Button(self, text="OK", command=fileTextDef )
okButton.pack(side=RIGHT)
#closeButton = Button(self, text="cancel")
#closeButton.pack(side=RIGHT, padx=5, pady=5)
def main():
root = Tk()
def white(*args,**kwargs):
root.configure(background="white")
root.configure(background="white")
root.configure(bg='white')
root.geometry("350x350+300+300")
app = App(root)
#app.bind("okButton", image('/Users/Augsutus/Pictures/iep'))
root.mainloop()
if __name__ == '__main__':
main()
| 0483396d1914f85dd815246218dfa14f79206cd1 | [
"Markdown",
"Python"
] | 3 | Python | jackrizza/image-converter | aa306f2e917cbd79ffc9cbdb8513305bb11b126d | 9ba41bd4fc8d15dde8cf238eeda55a7a887fbba4 |
refs/heads/master | <repo_name>erugeri/oom-appengine-test<file_sep>/README.md
# oom-appengine-test
deploy + call appspot url
when free heap is near 0 -> 502 Bad Gateway - nginx
then in syslog:
```
[ 257.820460] Memory cgroup stats for /docker-daemon/docker/5a52738c0d660f108c46f64d906c1921a1513957b742d66ba0fc3ca86557896b: cache:92KB rss:3472KB rss_huge:0KB mapped_file:4KB writeback:0KB inactive_anon:8KB active_anon:3524KB inactive_file:28KB active_file:4KB unevictable:0KB
[ 257.849288] Memory cgroup stats for /docker-daemon/docker/4e4465a725b80e458bbc5f410a06ee7767907f45000cfa76a12920eb39c57458: cache:216KB rss:42904KB rss_huge:0KB mapped_file:4KB writeback:0KB inactive_anon:28KB active_anon:42964KB inactive_file:124KB active_file:4KB unevictable:0KB
[ 257.875948] [ pid ] uid tgid total_vm rss nr_ptes swapents oom_score_adj name
[ 257.884002] [ 2238] 0 2238 192897 8781 59 0 -900 docker
[ 257.892122] [ 3143] 0 3143 9877 200 14 0 0 memcachep
[ 257.900491] [ 3211] 0 3211 5017 75 16 0 0 jetty_run.sh
[ 257.909120] [ 3290] 0 3290 35531 6151 29 0 -900 exe
[ 257.917090] [ 3300] 0 3300 5014 65 15 0 0 start_nginx.sh
[ 257.925894] [ 3303] 0 3303 963738 650264 1490 0 0 java
[ 257.933836] [ 3321] 0 3321 22796 328 45 0 0 nginx
[ 257.941870] [ 3325] 65534 3325 23249 758 45 0 0 nginx
[ 257.949919] [ 3327] 0 3327 12965 2462 29 0 0 gunicorn
[ 257.958206] [ 3399] 0 3399 60190 8983 52 0 0 gunicorn
[ 257.966607] Memory cgroup out of memory: Kill process 3303 (java) score 979 or sacrifice child
[ 257.975329] Killed process 3303 (java) total-vm:3854952kB, anon-rss:2601056kB, file-rss:0kB
[ 258.288963] docker0: port 3(veth256dc82) entered disabled state
[ 258.320630] docker0: port 3(veth256dc82) entered forwarding state
```<file_sep>/src/main/java/com/test/GenerateOOM.java
package com.test;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
public class GenerateOOM {
private final static SecureRandom random = new SecureRandom();
private static class MyObject {
private List<String> list = new ArrayList<>();
public MyObject() {
for (int i=0; i<1_000; i++) {
list.add(new BigInteger(128, random).toString(512));
}
}
}
private final static List<MyObject> myObjectList = new ArrayList<>();
public static String generate() {
for (int i=0; i<500; i++) {
myObjectList.add(new MyObject());
}
long heapSize = Runtime.getRuntime().totalMemory() / (1024*1024);
long heapMaxSize = Runtime.getRuntime().maxMemory() / (1024*1024);
long heapFreeSize = Runtime.getRuntime().freeMemory() / (1024*1024);
return "nb MyObject in list:"+myObjectList.size()+"<br/>"
+ " heapSize="+heapSize+"mo<br/>"
+ " heapMaxSize="+heapMaxSize+"mo<br/>"
+ " heapFreeSize="+heapFreeSize+"mo<br/>";
}
}
| fab9699ea9988583104e89147a484ad38dbaadc1 | [
"Markdown",
"Java"
] | 2 | Markdown | erugeri/oom-appengine-test | 4b62728ed446dc48a29d42524ea2861a096de403 | 4022d58e2a5f43bd316dcffd50c2d76e53ef2526 |
refs/heads/master | <repo_name>id-007/TUSHAR---LETSUPGRADE-JS<file_sep>/#DAY 4/Fourth.js
console.log("Question 4")
//--------------------------------------------------------------------------------------------------------------\\
let num1 = prompt('enter a number') ;
// let cal = prompt('Enter operation');
let num2 = prompt('enter your second number');
function sum (num1 , num2) {
return num1 + num2 ;
}
function sub (num1 , num2) {
return num1 - num2 ;
}
function mul (num1 , num2) {
return num1 * num2 ;
}
function div (num1 , num2) {
return num1 / num2 ;
}
Math.sqrt(num1) ;
function per (num1 , per) {
return (num1/100)*per ;
}
function calc()
{
let
}
<file_sep>/#DAY 4/Second.js
console.log("Question 2");
//--------------------------------------------------------------------------------------------------\\
const student = {
name : "Helsinki" ,
age : 24 ,
projects : {
Dicegame : "Two player dice game using javascript"
}
}
// console.log(student.name);
let name = student.name;
let age = student.age;
let projects = student.projects;
let Dicegame = student.projects.Dicegame;
console.log(name);
console.log(age);
console.log(projects);
console.log(Dicegame); <file_sep>/#DAY 5/Second.js
console.log(`Question 2`);
class User {
constructor(name,age,email) {
this.name = name;
this.age = age;
this.email = email;
this.gcoins = 0;
this.courses = [];
}
login (){
console.log(`user ${this.name} has logged in`);
return this;
}
logut(){
console.log(`user ${this.name} has logged out`);
return this;
}
}
class Moderator extends User {
constructor(name,age,email,gcoins){
super (name,age,email);
this.gcoins = 0;
}
addCoins(){
this.gcoins++;
console.log(`user ${this.name} has ${this.gcoins} gcoins`)
return this;
}
deleteCoins(){
this.gcoins--;
console.log(`user ${this.name} has ${this.gcoins} gcoins`)
return this;
}
}
class Admin extends Moderator {
addCourse(user,course){
user.courses.push(course);
// console.log(user);
}
deleteCourse(user,course){
user.courses.pop(course);
}
}
let user1 = new User('Roger',23,'<EMAIL>');
let user2 = new User('Vadantitta',25,'<EMAIL>');
let mod = new Moderator('Rishi',25,'<EMAIL>');
let admin = new Admin('Boss',35,'<EMAIL>');
let users = [user1,user2,mod,admin];
users.forEach(el => {
console.table(el);
})
admin.addCourse(user1,'Django');
admin.addCourse(user1,'Hadoop');
admin.addCourse(user2,'React Js');
admin.deleteCourse(user1,'Django');
// user1.login();
// mod.addCoins();
// mod.addCoins();
// mod.addCoins();
// mod.deleteCoins();
// user1.logut();
<file_sep>/#DAY 3/second.js
console.log("Question 2");
let os = prompt("What is your os name and version");
let arr = [console.log(os)];
console.log(arr);
// let os1 = os.split(" ");
// console.log(os1);
// let version = parseFloat(os , 10);
// console.log(version);<file_sep>/#DAY 4/fifth.js
console.log("Question 5")
//---------------------------------------------------------------------------------------------------\\
let sales = prompt("Enter your sales of the year");
let comm;
if(sales > 0 && sales <= 5000 ) {
comm = sales / 100 * 2;
console.log(`your sales is ${sales} and commission is ${comm}`);
}
if(sales >= 5001 && sales <= 10000 ) {
comm = sales / 100 * 5;
console.log(`your sales is ${sales} and commission is ${comm}`);
}
if(sales >= 10001 && sales <= 20000 ) {
comm = sales / 100 * 7;
console.log(`your sales is ${sales} and commission is ${comm}`);
}
if(sales >= 20000) {
comm = sales / 100 * 10;
console.log(`your sales is ${sales} and commission is ${comm}`);
}
<file_sep>/#DAY 2/First.js
// console.log("Javascript question 1");
// let val = prompt("Enter your name");
// console.log(val); | 4c3befedc00ad4d081321dd8d22023833bfebef4 | [
"JavaScript"
] | 6 | JavaScript | id-007/TUSHAR---LETSUPGRADE-JS | a8109681fc17a224e77291c59b3974813e41f6ce | aa08e74b69667e094a1b063150f069f83bde2937 |
refs/heads/master | <repo_name>BruhWhyYouMad/MemeYoutubeVideoMaker<file_sep>/main.py
import praw
import os
import requests
from frame_to_Video import convert_frames_to_video
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
reddit = praw.Reddit(client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
user_agent = "Discord Meme Bot",
username = "fakebot3")
def get_meme_image():
subreddit = reddit.subreddit('memes')
top_5 = subreddit.top(limit = 5)
top_4 = subreddit.top(limit = 4)
top_3 = subreddit.top(limit = 3)
top_2 = subreddit.top(limit = 2)
top_1 = subreddit.top(limit = 1)
for submission in top_5:
meme_5 = submission
response = requests.get(meme_5.url)
file = open("frames/5.png", "wb")
file.write(response.content)
file.close()
for submission in top_4:
meme_4 = submission
response = requests.get(meme_4.url)
file = open("frames/4.png", "wb")
file.write(response.content)
file.close()
for submission in top_3:
meme_3 = submission
response = requests.get(meme_3.url)
file = open("frames/3.png", "wb")
file.write(response.content)
file.close()
for submission in top_2:
meme_2 = submission
response = requests.get(meme_2.url)
file = open("frames/2.png", "wb")
file.write(response.content)
file.close()
for submission in top_1:
meme_1 = submission
response = requests.get(meme_1.url)
file = open("frames/1.png", "wb")
file.write(response.content)
file.close()
#get_meme_image()
convert_frames_to_video('frames/', 'video', 1) | 3ff5b2a43db5b1623c5a37ba33ddd9d09b4707c8 | [
"Python"
] | 1 | Python | BruhWhyYouMad/MemeYoutubeVideoMaker | 7bacf7f8b30050ee11e562de8e8d5489dbb40a5d | 95f035f02507024e50de5ed5ac3a98ecb81d029a |
refs/heads/master | <file_sep>(function(){
angular.
module("WebAppMaker")
.factory("WebsiteService",WebsiteService);
function WebsiteService($http){
var api = {
findWebsitesForUser: findWebsitesForUser,
findWebsiteById: findWebsiteById,
createWebsite:createWebsite
};
return api;
function findWebsitesForUser(userId){
return $http.get("/api/user/"+userId+"/website");
}
function findWebsiteById(websiteId){
return $http.get("/api/website/"+websiteId);
}
function createWebsite(developerId,name,desc){
var website = {
name: name,
description:desc
};
console.log(developerId);
return $http.post("/api/user/"+developerId+"/website",website);
}
}
})();<file_sep>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var passport = require('passport');
var cookieParse = require('cookie-parser');
var session = require('express-session');
// app.use(cookieParse());
// app.use(session({secret:'mean<PASSWORD>'}));
// app.use(passport.initialize());
// app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname+"/public"));
var assignment = require("./assignment/app.js");
assignment(app);
app.listen(3001);<file_sep>(function(){
angular
.module("WebAppMaker")
.controller("EditWebsiteController",EditWebsiteController);
function EditWebsiteController($routeParams,WebsiteService){
var vm = this;
vm.userId = $routeParams.userId;
vm.websiteId = $routeParams.websiteId;
function init(){
WebsiteService
.findWebsiteById(vm.websiteId)
.then(function(response){
vm.website = response.data;
vm.name = response.data[0].name;
console.log(vm.name);
console.log(response.data);
// console.log(vm.website);
});
}
console.log("lp");
init();
console.log("success");
// console.log(vm.website);
}
})();<file_sep>module.exports = function(){
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/cs5610summer');
var models = {
userModel: require("./user/user_model_server.js")(),
websiteModel: require("./website/website_model_server.js")()
};
return models;
};<file_sep>(function(){
angular
.module("WebAppMaker")
.controller("LoginController",LoginController)
.controller("ProfileController",ProfileController);
// var users = [
// {_id: "123", username: "alice", password: "<PASSWORD>", firstName: "Alice", email:"<EMAIL>", lastName: "Wonder" },
// {_id: "234", username: "bob", password: "bob", firstName: "Bob", email:"<EMAIL>", lastName: "Marley" },
// {_id: "345", username: "charly", password: "<PASSWORD>", firstName: "Charly", email:"<EMAIL>", lastName: "Garcia" },
// {_id: "456", username: "jannunzi", password: "<PASSWORD>", firstName: "Jose", email:"<EMAIL>", lastName: "Annunzi" }
// ];
function ProfileController($routeParams){
var vm = this;
vm.updateUser = updateUser;
var id = $routeParams["id"];
var index = -1;
// console.log(id);
init();
function updateUser(){
var result = UserService.updateUser(id,vm.user);
if (result == true){
vm.success = "User sucessfully update";
}else{
vm.error = "User Not found";
}
// users[index].username = vm.user.username;
// users[index].firstName = vm.user.firstName;
// users[index].lastName = vm.user.lastName;
// users[index].email = vm.user.email;
}
function init(){
for (var i in users){
if(users[i]._id === id){
vm.user = angular.copy(users[i]);
index = i;
}
}
}
}
function LoginController($location){
var vm = this;
vm.login = function(username,password){
// for (var i in users ){
// if(users[i].username === username && users[i].password === <PASSWORD>){
// var id = users[i]._id;
// $location.url("/profile/" + id);
// }else{
// vm.error = "User not found!!!!";
// }
// }
};
}
})();<file_sep>module.exports = function (app,models){
var websiteModel = models.websiteModel;
var websites = [
{ "_id": "123", "name": "Facebook", "developerId": "456" },
{ "_id": "234", "name": "Tweeter", "developerId": "456" },
{ "_id": "456", "name": "Gizmodo", "developerId": "456" },
{ "_id": "567", "name": "<NAME>", "developerId": "123" },
{ "_id": "678", "name": "Checkers", "developerId": "123" },
{ "_id": "789", "name": "Chess", "developerId": "234" },
{"_id":"57b4ef98b5024eb3823c66ff","name":"facebook","developerId":"5<PASSWORD>"}
];
app.post("/api/user/:userId/website",createWebsite);
app.get("/api/user/:userId/website",findAllWebsitesForUser);
app.get("/api/website/:websiteId",findWebsiteById);
app.put("/api/website/:websiteId",updateWebsite);
app.delete("/api/website/:websiteId",deleteWebsite);
function createWebsite(req,res){
var userId = req.params.userId;
var website = req.body;
websiteModel
.createWebsite(userId,website)
.then(function(response){
res.json(website);
},
function(error){
res.statusCode(404).send(error);
});
}
function findAllWebsitesForUser(req,res){
var userId = req.params.userId;
websiteModel
.findAllWebsitesForUser(userId)
.then(function(websites){
console.log(websites);
res.json(websites);
},
function(error){
res.statusCode(404).send(error);
});
// console.log("lo");
// var result = [];
// for (var w in websites){
// if(websites[w].developerId === userId){
// result.push(websites[w]);
// }
// }
// res.send(result);
}
function findWebsiteById(req,res){
var websiteId = req.params["websiteId"];
console.log("gp");
websiteModel
.findWebsiteById(websiteId)
.then(
function(website){
console.log(website);
res.json(website);
},
function(error){
res.statusCode(404).send(error);
}
);
}
function updateWebsite(req,res){
}
function deleteWebsite(req,res){
}
};<file_sep>(function(){
angular
.module("WebAppMaker")
.controller("LoginController",LoginController);
// .controller("ProfileController",ProfileController);
// function ProfileController($routeParams){
// var vm = this;
// vm.updateUser = updateUser;
// var id = $routeParams["id"];
// var index = -1;
// // console.log(id);
// init();
// function updateUser(){
// vm.success = "User successfully update";
// users[index].username = vm.user.username;
// users[index].firstName = vm.user.firstName;
// users[index].lastName = vm.user.lastName;
// users[index].email = vm.user.email;
// console.log("success");
// }
// function init(){
// for (var i in users){
// if(users[i]._id === id){
// vm.user = angular.copy(users[i]);
// index = i;
// }
// }
// }
// }
function LoginController($location,UserService){
var vm = this;
vm.login = function(username,password){
UserService
.findUserByUsernameAndPassword(username,password)
.then(function(response){
console.log(response);
var user = response.data;
if(user != null){
var id = user._id;
$location.url("/profile/"+id);
}
else{
vm.error = "User not found";
}
});
// if (user){
// var id = user._id;
// $location.url("/profile/"+id);
// }
// else{
// vm.error = "User not found";
// }
};
}
})();<file_sep>(function(){
angular
.module("WebAppMaker")
.config(Config);
function Config($routeProvider){
$routeProvider
.when("/login",{
templateUrl:"/assignment/user/login.html",
controller:"LoginController",
controllerAs : "model"
})
.when("/flickr",{
templateUrl:"/assignment/widget/widget-flickr-search.html",
controller:"FlickImageSearchController",
controllerAs:"model"
})
.when("/register",{
templateUrl:"/assignment/user/register.html",
controller:"RegisterController",
controllerAs : "model"
})
.when("/profile/:id",{
templateUrl:"/assignment/user/profile.html",
controller:"ProfileController",
controllerAs : "model"
})
.when("/user/:userId/website",{
templateUrl:"/assignment/website/website-lists.html",
controller:"WebsiteListController",
controllerAs : "model"
})
.when("/user/:userId/website/:websiteId",{
templateUrl:"/assignment/website/website-edit.html",
controller:"EditWebsiteController",
controllerAs : "model"
})
.when("/user/:userId/websites/new",{
templateUrl:"/assignment/website/websie-new.html",
controller:"NewWebsiteController",
controllerAs : "model"
})
.when("/user/:userId/website/:websiteId/page/:pageId/widget",{
templateUrl:"/assignment/widget/widget-list.html",
controller:"WidgetListController",
controllerAs : "model"
})
.when("/user/:userId/website/:websiteId/page/:pageId/widget/:widgetId",{
templateUrl:"/assignment/widget/widget-edit.html",
controller:"WidgetEditController",
controllerAs : "model"
})
.when("/user/:userId/website/:websiteId/page/:pageId/widget/new",{
templateUrl:"/assignment/widget/widget-chooser.html",
controller:"WidgetChooserController",
controllerAs : "model"
})
.otherwise({
redirectTo:"/login"
});
}
})();
// /assignment/widget/widget-chooser.html<file_sep>(function(){
angular
.module("WebAppMaker")
.controller("WidgetListController",WidgetListController);
function WidgetListController($sce){
var vm = this;
vm .widgets = [
{ "_id": "123", "widgetType": "HEADER", "pageId": "321", "size": 2, "text": "GIZMODO"},
{ "_id": "234", "widgetType": "HEADER", "pageId": "321", "size": 4, "text": "Lorem ipsum"},
{ "_id": "345", "widgetType": "IMAGE", "pageId": "321", "width": "100%",
"url": "http://lorempixel.com/400/200/"},
{ "_id": "456", "widgetType": "HTML", "pageId": "321", "text": '<p>The <em>next</em> rumored iPhone in 2017 will supposedly come with much bigger changes, including an OLED display and an all-glass design. It’s the kind of update you’d usually expect from a “new number” iPhone. Which means it could be another year before we see the <em>real</em> iPhone 7.</p>'},
{ "_id": "567", "widgetType": "HEADER", "pageId": "321", "size": 4, "text": "Lorem ipsum"},
{ "_id": "678", "widgetType": "YOUTUBE", "pageId": "321", "width": "100%",
"url": "https://youtu.be/AM2Ivdi9c4E" },
{ "_id": "789", "widgetType": "HTML", "pageId": "321", "text": '<p>iPhone 7, right? But it’s not that simple. Although the iPhone commandment reads something like “thou shalt always be an S, and only an S, in betwixt two new iPhones,” things might be changing for 2016. A majority of earlier reports say that the new iPhone (all two/three variants) will be called the iPhone 7, iPhone 7 Plus, and iPhone 7 Pro (maybe). However, <a href="http://www.apfelpage.de/news/september-iphone-chinesische-hersteller-sprechen-von-iphone-6se/" rel="noopener" target="_blank">a report from a German gadget blog</a> says the device could be called the iPhone 6SE, a continuation of the moniker that debuted with the <a href="http://gizmodo.com/iphone-se-review-the-phone-that-proves-apple-is-out-of-1768638745">4-inch iPhone SE in March</a>, and the embracing of a major change to the iPhone naming scheme. Number to S to SE.</p>'}
];
vm.getTrustedUrl = getTrustedUrl;
vm.getTrustedHtml = getTrustedHtml;
function getTrustedUrl(widget){
var urlParts = widget.url.split("/");
var id = urlParts[urlParts.length - 1];
var url = "https://www.youtube.com/embed/"+id ;
console.log(url);
return $sce.trustAsResourceUrl(url);
}
function init(){
$(".container")
.sortable({
asix:'y'
});
}
init();
function getTrustedHtml(widget){
var html = $sce.trustAsHtml(widget.text);
return html;
}
}
})();<file_sep>import urllib.request
webpage=input('please input the website \n')
name=input('please input the img name~ \n')
name=name+'.jpg'
urllib.request.urlretrieve(webpage,name)
print("success!")<file_sep>module.exports = function(app,models){
var userModel = models.userModel;
users = [
{_id: "123", username: "alice", password: "<PASSWORD>", firstName: "Alice", lastName: "Wonder" },
{_id: "234", username: "bob", password: "bob", firstName: "Bob", lastName: "Marley" },
{_id: "345", username: "charly", password: "<PASSWORD>", firstName: "Charly", lastName: "Garcia" },
{_id: "456", username: "jannunzi", password: "<PASSWORD>", firstName: "Jose", lastName: "Annunzi" }
];
app.post("/api/user",createUser);
app.get("/api/user",getUsers);
app.get("/api/user/:userId",findUserById);
app.put("/api/user/:userId",updateUser);
app.delete("/api/user/:userId",deleteUser);
function deleteUser(req,res){
var id = req.params.userId;
userModel
.deleteUser(id)
.then(function(stats){
console.log(stats);
res.send(200);
},
function(error){
res.statusCode(404).send(error);
}
)
// for (var i in users){
// if (users[i]._id === id){
// users.splice(i,1);
// res.send(200);
// return;
// }
// }
// res.send(400);
}
function updateUser(req,res){
var id = req.params.userId;
var newUser = req.body;
userModel
.updateUser(id,newUser)
.then(function(stats){
console.log(stats);
},
function(error){
res.statusCode(404).send(error);
});
// for (var i in users){
// if(users[i]._id === id){
// users[i].firstName = newUser.firstName;
// users[i].lastName = newUser.lastName;
// res.send(202);
// return;
// }
// }
// res.send(400);
}
function createUser(req,res){
var user = req.body;
console.log(user);
userModel
.createUser(user)
.then(
function(user){
console.log("good");
res.send(user);
},
function(error){
res.statusCode(400).send(error);
});
// .then(
// function(user){
// cnosole.log(user);
// console.log("good");
// });
// user._id = (new Date()).getTime()+"";
// users.push(user);
// res.send(user);
// userModel
// .createUser(user)
// .then(function(user){
// console.log(user);
// res.json(user);
// },
// function(error){
// res.statusCode(400).send(error);
// });
}
function getUsers(req,res){
var username = req.query['username'];
var password = req.query['<PASSWORD>'];
console.log(username);
console.log(password);
if(username && password){
findUserByCredentials(username,password,res);
}else if(username ){
findUserByUsername(username,res);
}else{
res.send(users);
}
}
function findUserById(req,res){
var id = req.params.userId;
userModel
.findUserById(id)
.then(function(user){
res.send(user);
},
function(error){
res.statusCode(404).send(error);
});
// for (var i in users){
// if (users[i]._id === id){
// res.send(users[i]);
// return;
// }
// }
// res.send({});
}
function findUserByUsername(username,res){
for (var i in users){
if(users[i].username === username){
res.send(users[i]);
return;
}
}
res.send({});
}
function findUserByCredentials(username,password,res){
userModel
.findUserByCredentials(username,password)
.then(function(user){
res.json(user);
},
function(error){
res.statusCode(404).send(err);
});
// for (var i in users){
// if(users[i].username === username && users[i].password === <PASSWORD>){
// res.send(users[i]);
// return;
// }
// }
// res.send({});
}
};
<file_sep>module.exports = function(){
var mongoose = require("mongoose");
var UserSchema = mongoose.Schema({
username: {type:String,required:true},
password:<PASSWORD>,
firstName:String,
lastName:String,
dob:Date,
dateCreated:{type:Date,default:Date.now}
},{collection:"us"});
return UserSchema;
};<file_sep># this is test for readme.md#
this is for compare above language
## double check what is ##
```bash
# run python file method
# first input "pythonto get into the python environment"
python
```<file_sep>(function(){
angular
.module("WebAppMaker")
.factory("UserService",UserService);
function UserService($http){
var api = {
createUser: createUser,
findUserByUsernameAndPassword: findUserByUsernameAndPassword,
findUserById: findUserById,
updateUser: updateUser,
deleteUser: deleteUser
};
return api;
function createUser(username,password){
var user = {
username:username,
password:<PASSWORD>
};
return $http.post("/api/user/",user);
}
function deleteUser(id){
var url = "/api/user/"+id ;
return $http.delete(url);
}
function updateUser(id,newUser){
var url = "/api/user/"+ id;
return $http.put(url,newUser);
}
function findUserByUsernameAndPassword(username,password){
var url = "/api/user?username="+username+"&&password="+password;
return $http.get(url);
}
function findUserById(id){
var url = "/api/user/"+id;
return $http.get(url);
}
}
})
(); | 2fc9d611dad44f39a224743eb90b9cf4dc49297c | [
"JavaScript",
"Python",
"Markdown"
] | 14 | JavaScript | hangshang1992/summer_web | ae7717c5d84354fcdb6dccffed331586e6311a57 | 9b09d80b82f5958204ee88a0dd97f345dbb444d0 |
refs/heads/master | <repo_name>paulogpafilho/wlst-misc-scripts<file_sep>/README.md
# Weblogic WLST Miscellaneous Scripts
This is a repository of miscellaneous WLST scripts.
Scripts are examples on how to implement several tasks related to WLS monitoring, admin and configuration.
## Getting Started
Read the script comments for each description and requirements but as a general rule, scripts will be used by invoking WLST and passing the script as argument.
For example:
/home/oracle/MW_HOME/common/bin/wlst.sh SCRIPT_NAME
Some scripts will require additional files; others some environment variable to be set.
Additional required files will be provided with the script and the environment variable, if any, will be described in the script comments.
### Prerequisites
A valid Weblogic Server installation and/or additional Fusion Middleware components.
### Installing
Just copy the desired script and the additional required files to a folder and invoke WLST passing the script as argument.
For example:
```
/home/oracle/MW_HOME/common/bin/wlst.sh create_users.py
```
## Authors
* **<NAME>** - [LinkedIn](https://www.linkedin.com/in/paulogpafilho/)
## License
This project/code is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
<file_sep>/users-groups/edit_user_properties.py
"""
This is a python script to edit users properties in a Weblogic Domain that uses the embedded LDAP.
The script needs to connect to a running Weblogic Admin Server.
This script requires a comma-separated-values (csv) file containing the user's properties to be
edited in the following format:
username, c, departmentnumber, displayname, employeenumber, employeetype,
facsimiletelephonenumber, givenname, homephone, homepostaladdress, l, mail, mobile, pager,
postaladdress, postofficebox, preferredlanguage, st, street, telephonenumber, title
Username is the only required value, others are optional.
The script will try to use the follow default values:
- Csv file name: will match the script file name with .csv extension.
For example: edit_user_properties.csv. If not defined in the environment
variables, the script will try to look at the same location where the script is
running.
- Weblogic admin username: the weblogic admin user to connect to the admin server.
Default value: weblogic
- Weblogic admin user password: <PASSWORD> user password to connect to the admin server.
Default value: Welcome1
- Weblogic admin server URL: the admin server url and port, in the following format:
t3://HOSTNAME:PORT. Default value: t3://localhost:7001
You can override the defaults by setting the following environment variables to:
CSV_FILE - The full path to the csv file containing users
WLS_USER - The weblogic admin user used to connect to admin server
WLS_PASS - The weblogic admin user password
WLS_URL - The weblogic admin server URL.
To invoke this script, simply call WLST passing the script full path as argument.
For example:
/home/oracle/MW_HOME/common/bin/wlst.sh edit_user_properties.py
"""
import os, sys, fileinput
from weblogic.management.security.authentication import UserEditorMBean
print '---- WLST User Edit Start ----\n'
# Get the current path of the script and build the users cvs file name
# assuming they are in the same directory
dir_name = os.path.dirname(sys.argv[0])
file_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] + '.csv'
csv_file = os.path.join(dir_name, file_name)
# Location of the csv file, if not set will use users.csv
csv_file = os.environ.get('CSV_FILE', csv_file)
# Weblogic admin user, if not set will use weblogic
wls_user = os.environ.get('WLS_USER', 'weblogic')
# Weblogic admin password, if not set will use <PASSWORD>
wls_password = os.environ.get('WLS_PASS', '<PASSWORD>')
# Weblogic Admin Server URL, if not set will use t3://localhost:7001
wls_url = os.environ.get('WLS_URL', 't3://localhost:7001')
print 'Users file to process: \'' + csv_file + '\'\n'
# Connect to WLS Admin Server
connect(wls_user, wls_password, wls_url)
# Obtain the AuthenticatorProvider MBean
atnr = cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
props = ['c', 'departmentnumber', 'displayname', 'employeenumber', 'employeetype',
'facsimiletelephonenumber', 'givenname', 'homephone', 'homepostaladdress', 'l', 'mail', 'mobile', 'pager',
'postaladdress', 'postofficebox', 'preferredlanguage', 'st', 'street', 'telephonenumber', 'title']
username = ''
try:
print 'Starting users deletion \n'
# Read the csv file
for line in fileinput.input(csv_file):
# Split the file by comma
ln = line.split(',')
# get the username and trims the trailings spaces
username = ln[0].strip()
# Check if user exists in the LDAP
if atnr.userExists(username):
print 'Setting user \'' + username + '\' properties...'
try:
for j, jval in enumerate(props):
# Check if the property is not blank
if ln[j+1].strip() != '':
# Change the user property in the LDAP
atnr.setUserAttributeValue(username, jval, ln[j+1].strip())
except weblogic.management.utils.InvalidParameterException, ie:
print('Error while editing \'' + username + '\' properties')
print str(ie)
pass
print 'User \'' + username + '\' properties edited successfully!\n'
else:
print 'User \'' + username + '\' does not exist, skipping...\n'
except StandardError, e:
print 'Exception raised: ' + str(e)
print 'Terminating script...'
print '---- WLST User Edit End ----'<file_sep>/users-groups/add_users_to_groups.py
"""
This is a python script to add users to groups in a Weblogic Domain that uses the embedded LDAP.
The script needs to connect to a running Weblogic Admin Server.
This script requires a comma-separated-values (csv) file containing the users you wish to add
the groups, in the following format:
groupname, username
Both values are required.
The script will try to use the follow default values:
- Csv file name: will match the script file name with .csv extension.
For example: add_users_to_groups.csv. If not defined in the environment
variables, the script will try to look at the same location where the script is
running.
- Weblogic admin username: the weblogic admin user to connect to the admin server.
Default value: weblogic
- Weblogic admin user password: <PASSWORD> to connect to the admin server.
Default value: Welcome1
- Weblogic admin server URL: the admin server url and port, in the following format:
t3://HOSTNAME:PORT. Default value: t3://localhost:7001
You can override the defaults by setting the following environment variables to:
CSV_FILE - The full path to the csv file containing users
WLS_USER - The weblogic admin user used to connect to admin server
WLS_PASS - The weblogic <PASSWORD>
WLS_URL - The weblogic admin server URL.
To invoke this script, simply call WLST passing the script full path as argument.
For example:
/home/oracle/MW_HOME/common/bin/wlst.sh add_users_to_groups.py
"""
import os, sys, fileinput
from weblogic.management.security.authentication import GroupEditorMBean
print '---- WLST User-Group Assignment Start ----\n'
# Get the current path of the script and build the users cvs file name
# assuming they are in the same directory
dir_name = os.path.dirname(sys.argv[0])
file_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] + '.csv'
csv_file = os.path.join(dir_name, file_name)
# Location of the csv file, if not set will use users.csv
csv_file = os.environ.get('CSV_FILE', csv_file)
# Weblogic admin user, if not set will use weblogic
wls_user = os.environ.get('WLS_USER', 'weblogic')
# Weblogic admin password, if not set will use <PASSWORD>
wls_password = os.environ.get('WLS_PASS', '<PASSWORD>')
# Weblogic Admin Server URL, if not set will use t3://localhost:7001
wls_url = os.environ.get('WLS_URL', 't3://localhost:7001')
print 'Groups file to process: \'' + csv_file + '\'\n'
# Connects to WLS Admin Server
connect(wls_user, wls_password, wls_url)
# Obtains the AuthenticatorProvider MBean
atnr = cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
group = ''
username = ''
try:
print 'Starting user-group assignemt\n'
# Read the csv file
for line in fileinput.input(csv_file):
# Split the line by comma
i = line.split(',')
# Get the group name
group = i[0].strip()
# Get the username
username = i[1].strip()
# If group and user exist
if atnr.groupExists(group) and atnr.userExists(username):
print 'Adding user \'' + username + '\' to group \'' + group + '\'...'
try:
# Add user to group
atnr.addMemberToGroup(group, username)
except weblogic.management.utils.InvalidParameterException, ie:
print('Error while adding user to group')
print str(ie)
pass
print 'Adding user \'' + username + '\' to group \'' + group + '\' successfully!\n'
else:
print 'Group \'' + group + '\' or user \'' + username + '\' does not exist, skipping...\n'
except StandardError, e:
print 'Exception raised: ' + str(e)
print 'Terminating script...'
print '---- WLST User-Group Assignment End ----'<file_sep>/users-groups/create_users.py
"""
This is a python script to create users in a Weblogic Domain that uses the embedded LDAP.
The script needs to connect to a running Weblogic Admin Server.
This script requires a comma-separated-values (csv) file containing the users you wish to
create, in the following format:
username, password, description
Username and passoword are required.
Passwords must contain at least 8 characters and either one numeric or special character.
The script will try to use the follow default values:
- Csv file name: will match the script file name with .csv extension.
For example: create_users.csv. If not defined in the environment
variables, the script will try to look at the same location where the script is
running.
- Weblogic admin username: the weblogic admin user to connect to the admin server.
Default value: weblogic
- Weblogic admin user password: <PASSWORD> to connect to the admin server.
Default value: Welcome1
- Weblogic admin server URL: the admin server url and port, in the following format:
t3://HOSTNAME:PORT. Default value: t3://localhost:7001
You can override the defaults by setting the following environment variables to:
CSV_FILE - The full path to the csv file containing users
WLS_USER - The weblogic admin user used to connect to admin server
WLS_PASS - The weblogic admin user password
WLS_URL - The weblogic admin server URL.
To invoke this script, simply call WLST passing the script full path as argument.
For example:
/home/oracle/MW_HOME/common/bin/wlst.sh create_users.py
"""
import os, sys, fileinput
from weblogic.management.security.authentication import UserEditorMBean
print '---- WLST User Creating Start ----\n'
# Get the current path of the script and build the users cvs file name
# assuming they are in the same directory
dir_name = os.path.dirname(sys.argv[0])
file_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] + '.csv'
csv_file = os.path.join(dir_name, file_name)
# Location of the csv file, if not set will use users.csv
csv_file = os.environ.get('CSV_FILE', csv_file)
# Weblogic admin user, if not set will use weblogic
wls_user = os.environ.get('WLS_USER', 'weblogic')
# Weblogic admin password, if not set will use <PASSWORD>
wls_password = os.environ.get('WLS_PASS', '<PASSWORD>')
# Weblogic Admin Server URL, if not set will use t3://localhost:7001
wls_url = os.environ.get('WLS_URL', 't3://localhost:7001')
print 'Users file to process: \'' + csv_file + '\'\n'
# Connects to WLS Admin Server
connect(wls_user, wls_password, wls_url)
# Obtains the AuthenticatorProvider MBean
atnr = cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider("DefaultAuthenticator")
username = ''
password = ''
description = ''
try:
print 'Starting users creation\n'
# Read the csv file
for line in fileinput.input(csv_file):
# Split the line by comma
i = line.split(',')
# Get the username
username = i[0].strip()
# Get the password
password = i[1].strip()
# Get the description
description = i[2].strip()
# If user does not exist
if not atnr.userExists(username):
print 'Creating user \'' + username + '\'...'
try:
# Create user
atnr.createUser(username, password, description)
print 'User \'' + username + '\' created successfully!'
except weblogic.management.utils.InvalidParameterException, ie:
print('Error while creating the user\n')
print str(ie)
pass
else:
print 'User \'' + username + '\' already exists, skipping...\n'
except StandardError, e:
print 'Unexpected Exception raised: ' + str(e)
print 'Terminating script...'
print '---- WLST User Creating End ----' | b4f8b810cec58c3613df625fad1aa5aad57f4873 | [
"Markdown",
"Python"
] | 4 | Markdown | paulogpafilho/wlst-misc-scripts | 6ee6cefe3e9f32ea36df6d8c933adf058432759e | bc0bbef10f731aeee8cc91f5a1983ea34e050a75 |
refs/heads/master | <repo_name>Anjero/reader<file_sep>/src/main/java/net/anjero/reader/core/config/MyBatisConfig.java
package net.anjero.reader.core.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/9</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
@org.springframework.context.annotation.Configuration
@MapperScan("net.anjero.reader")
public class MyBatisConfig implements ConfigurationCustomizer{
Logger log = LoggerFactory.getLogger(MyBatisConfig.class);
@Override
public void customize(Configuration configuration) {
log.info("read mybatis config..");
}
}
<file_sep>/src/main/java/net/anjero/reader/module/account/service/AccountService.java
package net.anjero.reader.module.account.service;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import net.anjero.reader.module.account.pojo.Account;
import net.anjero.reader.module.account.mapper.AccountMapper;
@Service
public class AccountService{
@Resource
private AccountMapper accountMapper;
public int insert(Account pojo){
return accountMapper.insert(pojo);
}
public int insertSelective(Account pojo){
return accountMapper.insertSelective(pojo);
}
public int insertList(List<Account> pojos){
return accountMapper.insertList(pojos);
}
public int update(Account pojo){
return accountMapper.update(pojo);
}
}
<file_sep>/sql/reader.sql
CREATE SCHEMA `reader_db` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin ;
use reader_db;
<file_sep>/src/main/java/net/anjero/reader/core/json/Result.java
package net.anjero.reader.core.json;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/10</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
public class Result {
private int code;
private Object result;
private String description;
public Result() {
}
public Result(int code, Object result, String description) {
this.code = code;
this.result = result;
this.description = description;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
<file_sep>/src/main/java/net/anjero/reader/module/account/pojo/AccountTypeEnum.java
package net.anjero.reader.module.account.pojo;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/10</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
public enum AccountTypeEnum {
REGISTER(1),
WEIBO(2),
WECHAT(3),
QQ(4);
int type;
public int getType() {
return type;
}
AccountTypeEnum(int type) {
this.type = type;
}
}
<file_sep>/src/main/java/net/anjero/reader/module/global/common/TestErroController.java
package net.anjero.reader.module.global.common;
import net.anjero.reader.core.exception.ForbiddenJsonException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/16</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
@Controller
@RequestMapping("/test")
public class TestErroController {
@RequestMapping("/page")
public String errorPage() throws Exception {
throw new Exception("出错啦!!");
}
@GetMapping("json")
@ResponseBody
public String jsonError() throws ForbiddenJsonException {
throw new ForbiddenJsonException("error!!!");
}
}
<file_sep>/sql/Account.sql
-- auto Generated on 2017-05-10 16:00:09
-- DROP TABLE IF EXISTS `account`;
use reader_db;
CREATE TABLE `account`(
`id` INT (11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`avator` VARCHAR (50) NOT NULL DEFAULT '' COMMENT 'avator',
`username` VARCHAR (50) UNIQUE NOT NULL DEFAULT '' COMMENT 'username',
`password` VARCHAR (50) NOT NULL DEFAULT '' COMMENT 'password',
`nickname` VARCHAR (50) NOT NULL DEFAULT '' COMMENT 'nickname',
`in_time` DATETIME NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT 'inTime',
`sex` INT (2) NOT NULL DEFAULT -1 COMMENT 'sex',
`desc` VARCHAR (1000) NOT NULL DEFAULT '' COMMENT 'desc',
`type` INT (2) NOT NULL DEFAULT 0 COMMENT 'type',
INDEX(username),
INDEX(nickname),
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '`account`';
<file_sep>/src/main/java/net/anjero/reader/module/account/mapper/AccountMapper.java
package net.anjero.reader.module.account.mapper;
import net.anjero.reader.module.account.pojo.Account;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface AccountMapper {
int insert(@Param("pojo") Account pojo);
int insertSelective(@Param("pojo") Account pojo);
int insertList(@Param("pojos") List<Account> pojo);
int update(@Param("pojo") Account pojo);
List<Account> findByUsernameAndPassword(@Param("username")String username,@Param("password")String password);
}
<file_sep>/src/test/java/net/anjero/reader/module/user/UserDaoTest.java
package net.anjero.reader.module.user;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/10</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Before
public void setUp() throws Exception {
System.out.println("set up...");
}
@After
public void tearDown() throws Exception {
System.out.println("tearDown...");
}
@Test
public void insert() throws Exception {
userDao.insert(new User("newTest22","<EMAIL>"));
}
@Test
public void insertSelective() throws Exception {
}
@Test
public void insertList() throws Exception {
}
@Test
public void update() throws Exception {
}
@Test
public void find() throws Exception {
}
@Test
public void findById() throws Exception {
}
@Test
public void findByNameLike() throws Exception {
}
@Test
public void findByNameIn() throws Exception {
}
}<file_sep>/src/main/java/net/anjero/reader/module/folder/service/FoldersService.java
package net.anjero.reader.module.folder.service;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import net.anjero.reader.module.folder.pojo.Folders;
import net.anjero.reader.module.folder.mapper.FoldersMapper;
@Service
public class FoldersService{
@Resource
private FoldersMapper foldersMapper;
public int insert(Folders pojo){
return foldersMapper.insert(pojo);
}
public int insertSelective(Folders pojo){
return foldersMapper.insertSelective(pojo);
}
public int insertList(List<Folders> pojos){
return foldersMapper.insertList(pojos);
}
public int update(Folders pojo){
return foldersMapper.update(pojo);
}
}
<file_sep>/src/main/java/net/anjero/reader/module/account/controller/AccountController.java
package net.anjero.reader.module.account.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/10</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@GetMapping("/reg")
public String register() {
return "demo";
}
}
<file_sep>/src/main/java/net/anjero/reader/module/folder/enums/FileTypeEnum.java
package net.anjero.reader.module.folder.enums;
/**
* ///////////////////////////////////////
* <p>Create by 2017/5/24</p>
* <p>
* 作为一个真正的程序员,首先应该尊重编程,<br/>
* 热爱你所写下的程序,他是你的伙伴,而不是工具。
* </p>
* ///////////////////////////////////////
*
* @author :anjero
* @version :1.0
*/
public enum FileTypeEnum {
SOURCE(1)//源文件
, REFERENCE(2) //引用文件
;
int type;
FileTypeEnum(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
<file_sep>/src/main/java/net/anjero/reader/core/config/WebApplicationConfiguration.java
package net.anjero.reader.core.config;
import net.anjero.reader.core.interceptor.WebInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class WebApplicationConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private WebInterceptor webInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(webInterceptor).addPathPatterns("/**");
}
}
<file_sep>/README.md
# reader
reader rss
<file_sep>/src/main/java/net/anjero/reader/module/system/security/controller/AdminIndexController.java
package net.anjero.reader.module.system.security.controller;
import net.anjero.reader.core.spring.controller.BaseAdminController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* <p>cheshell Create by 14/12/16 上午10:12</p>
*
* @author :anjero by Cheshell Copyright (c) 2012
* @version :1.0
*/
@Controller
@RequestMapping("/admin")
public class AdminIndexController extends BaseAdminController {
@GetMapping(value = "/dashboard")
public String dashboard() {
return "dashboard";
}
@GetMapping("/page1")
public String page1() {
return "page1";
}
@GetMapping("/page2")
public String page2() {
return "page2";
}
@GetMapping("/page3")
public String page3() {
return "page3";
}
}
<file_sep>/src/main/java/net/anjero/reader/module/folder/mapper/FoldersMapper.java
package net.anjero.reader.module.folder.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import net.anjero.reader.module.folder.pojo.Folders;
@Mapper
public interface FoldersMapper {
int insert(@Param("pojo") Folders pojo);
int insertSelective(@Param("pojo") Folders pojo);
int insertList(@Param("pojos") List<Folders> pojo);
int update(@Param("pojo") Folders pojo);
}
<file_sep>/src/main/java/net/anjero/reader/core/spring/controller/BaseController.java
package net.anjero.reader.core.spring.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.anjero.reader.core.json.Result;
import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
//import com.ichefeng.data.module.agency.pojo.AgencyUser;
//import com.ichefeng.data.module.agency.pojo.AgencyUserToken;
//import com.ichefeng.data.module.agency.service.AgencyUserService;
//import com.ichefeng.data.module.agency.service.AgencyUserTokenService;
/**
* @author :Anjero
* @version :1.0
* @Title :BaseController.java
* @Description:
* @Datetime :2013-8-29
* @Copyright :Copyright (c) 2012
* @Company :Cheshell
*/
public class BaseController implements Serializable {
// @Resource
// private AgencyUserTokenService agencyUserTokenService;
// @Resource
// private AgencyUserService agencyUserService;
public static final String REDIRECT = "redirect:";
private static final long serialVersionUID = 7544640703613411536L;
/**
* 控制器LOG
*/
protected Logger LOG = Logger.getLogger("controller");
/**
* 用户session
*/
public static final String SESSION_ADMIN = "session_admin";
public static final String SESSEION_USER = "sesseion_user";
public static final String WECHAT_USER_SESSION = "wechat_user_session";
public static final String SESSEION_PRO = "sesseion_province";
protected String success(Object obj) {
Result result = new Result();
result.setCode(200);
result.setResult(obj);
result.setDescription("succuss");
try {
return new ObjectMapper().writeValueAsString(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//
// /**
// * 返回的json里有Date类型的属性时,将时间格式化成 pattern 类型
// *
// * @param obj
// * @param pattern ApplicationConstants 里有对应的属性
// * @return
// */
// protected String successWithDateTime(Object obj, String pattern) {
// Result result = new Result();
// result.setCode(200);
// result.setResult(obj);
// result.setDescription("succuss");
// try {
// return new ObjectMapper().writeValueAsString(result);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
protected String redirect(String location) {
return REDIRECT + location;
}
protected String success() {
return success(null);
}
protected Map<String, String> error() {
Map<String, String> map = new HashMap<String, String>();
map.put("code", "201");
return map;
}
protected String error(String message) {
Result result = new Result();
result.setCode(201);
result.setResult(null);
result.setDescription(message);
try {
return new ObjectMapper().writeValueAsString(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void addAlertMessage(Model model, String msg) {
model.addAttribute("msg", msg);
}
protected HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request;
}
protected void printWriterJSON(HttpServletResponse response, String result) {
response.setContentType("application/x-json;charset=UTF-8");
//response.setCharacterEncoding("UTF-8");
try {
PrintWriter out = response.getWriter();
out.println(result);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/net/anjero/reader/module/system/security/core/MyInvocationSecurityMetadataSource.java
package net.anjero.reader.module.system.security.core;
import net.anjero.reader.module.system.security.pojo.SecurityAuth;
import net.anjero.reader.module.system.security.service.AuthService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* 此类在初始化时,应该取到所有资源及其对应角色的定义
*
* @author Robin
*/
@Service
@Log4j
public class MyInvocationSecurityMetadataSource implements
FilterInvocationSecurityMetadataSource {
@Autowired
private AuthService authService;
private HashMap<String, Collection<ConfigAttribute>> map = null;
/**
* 加载资源,初始化资源变量
*/
public void loadResourceDefine() {
map = new HashMap<>();
Collection<ConfigAttribute> array;
ConfigAttribute cfg;
List<SecurityAuth> auths = authService.selectAll();
for (SecurityAuth auth : auths) {
array = new ArrayList<>();
cfg = new SecurityConfig(auth.getName());
array.add(cfg);
map.put(auth.getUrl(), array);
}
log.info("security info load sucess!!");
}
/**
* 根据路径获取访问权限的集合接口
*
* @param object
* @return
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object)
throws IllegalArgumentException {
if (map == null) {
loadResourceDefine();
}
HttpServletRequest request = ((FilterInvocation) object)
.getHttpRequest();
AntPathRequestMatcher matcher;
String resUrl;
for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next();
matcher = new AntPathRequestMatcher(resUrl);
if (matcher.matches(request)) {
return map.get(resUrl);
}
}
return null;
}
/**
* @return
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
/**
* @param clazz
* @return
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
<file_sep>/src/main/java/net/anjero/reader/core/spring/controller/BaseAdminController.java
package net.anjero.reader.core.spring.controller;
import net.anjero.reader.core.exception.ForbiddenJsonException;
import net.anjero.reader.module.system.security.pojo.SecurityAdmin;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
/**
* @author :Anjero
* @version :1.0
* @Title :BaseAdminController.java
* @Description:
* @Datetime :2013-8-23
* @Copyright :Copyright (c) 2012
* @Company :Cheshell
*/
@Controller
public class BaseAdminController extends BaseController {
public SecurityAdmin getAdmin() throws ForbiddenJsonException {
return adminUser();
}
public Integer getAdminId() throws ForbiddenJsonException {
if (getAdmin() != null) {
return getAdmin().getId();
}
throw new ForbiddenJsonException("未登录或超时,请重新登录!");
}
public String getAdminName() throws ForbiddenJsonException {
if (getAdmin() != null) {
return getAdmin().getRealName();
}
throw new ForbiddenJsonException("未登录或超时,请重新登录!");
}
public SecurityAdmin adminUser() throws ForbiddenJsonException {
try {
return (SecurityAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {
throw new ForbiddenJsonException("未登录或超时,请重新登录!", e);
}
}
}
| cf8d95f850be485c3fb844aa6f5311b55de0e1b9 | [
"Markdown",
"Java",
"SQL"
] | 19 | Java | Anjero/reader | f87a545cb4b25173ced15cf0906e87004745696e | d69e971cfea66ecf972b14c592355081dfc7ce33 |
refs/heads/master | <file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.ProfilePopupView = Backbone.View.extend({
template: Handlebars.compile($("#profile-template").html()),
model: null,
initialize: function(options){
var self = this;
self.model = new com.apress.model.Profile({ id:options.user });
self.render();
self.model.fetch();
self.listenTo(self.model, 'change', self.render);
},
render: function(){
var self = this;
if (self.model.get('screen_name')) {
var output = self.template({user: self.model.toJSON()});
BootstrapDialog.show({
title: '@'+self.model.get('screen_name') + 's Profile',
message: output,
});
}
return self;
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.ProfileView = Backbone.View.extend({
el: '#profile',
template: Handlebars.compile($("#profile-template").html()),
model: null,
initialize: function(options){
var self = this;
self.model = new com.apress.model.Profile({id:options.user});
self.model.fetch();
self.listenTo(self.model, 'change', self.render);
},
render: function(){
var self = this;
var output = self.template({user: self.model.toJSON()});
self.$el.html(output);
return self;
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.ResultsView = Backbone.View.extend({
el: '#results',
model: null,
template: Handlebars.compile($("#timeline-template").html()),
initialize: function(options){
var self = this;
self.model = options.model;
self.render();
},
render: function(){
var self = this,
output = self.template({tweet: self.model.get('statuses')});
BootstrapDialog.show({
title: 'Search Results',
message: output,
});
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.SearchView = Backbone.View.extend({
el: '#search',
model: null,
initialize: function(options){
var self = this;
self.model = options.model;
},
events: {
'click #searchbutton' : 'runSearch'
},
runSearch: function(e){
var self = this,
query = $('#searchbox').val();
// prevent the entire page from refreshing
e.preventDefault();
console.log('Run search against ' + query);
// a trick to force a reset of the attribute
self.model.set('query', '', {silent: true});
self.model.set('query',query);
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.TimelineView = Backbone.View.extend({
el: '#timeline',
template: Handlebars.compile($("#timeline-template").html()),
timeline: null,
initialize: function(options){
var self = this;
self.timeline = new com.apress.collection.Timeline();
self.render();
self.timeline.fetch({reset : true});
self.listenTo(self.timeline, 'reset', self.render);
},
render: function(){
var self = this;
if (self.timeline.models.length > 0) {
var output = self.template({tweet: self.timeline.toJSON()});
self.$el.append(output);
}
return self;
},
events: {
'click .profile' : 'showDialog'
},
showDialog: function(options){
var self = this,
$target = $(options.currentTarget),
username = $target.data('user');
var profileView = new com.apress.view.ProfilePopupView({user: username});
}
});<file_sep>$(function(){
var timeLineView = new com.apress.view.TimelineView(),
profileView = new com.apress.view.ProfileView({user:'spantons'}),
searchModel = new com.apress.model.Search(),
searchView = new com.apress.view.SearchView({model: searchModel});
appRouter = new com.apress.router.AppRouter({searchModel: searchModel});
Backbone.history.start();
});<file_sep>$(function(){
Handlebars.registerHelper('format', function(str){
if (str) {
// highliht the @part
str = str.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
var username = u.replace("@","");
return '<a href="#" data-user="' + username +'" class="profile">@'+username+'</a>';
});
// highliht email
str = str.replace(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi, function(u) {
return '<a href="mailto:'+ u +'" target="_blank">'+u+'</a>';
});
// highliht url
str = str.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(u) {
return '<a href="'+ u +'" target="_blank">'+u+'</a>';
});
return new Handlebars.SafeString(str);
} else {
return str;
}
});
});<file_sep>var express = require('express'),
path = require('path'),
http = require('http'),
fs = require('graceful-fs');
/*--------------------------------------------------------------------------------------------------------------*/
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.static(path.join(__dirname, 'public')));
});
var timeline = require(__dirname + '/public/data/timeline.json');
var profile = require(__dirname + '/public/data/profile.json');
var search = require(__dirname + '/public/data/search.json');
/*--------------------------------------------------------------------------------------------------------------*/
// Main page
app.get('/', function (req,res){
res.sendfile(__dirname + '/index.html');
});
/**
* Get the account settings for the user with the id provided.
**/
app.get('/profile/:id', function(request, response){
response.header('Access-Control-Allow-Origin', '*');
response.json(profile);
});
/**
* Runs a search given a query
**/
app.get('/search/:query', function (request, response) {
response.header('Access-Control-Allow-Origin', '*');
response.json(search);
});
/**
* Returns the twitter timeline for the current user
**/
app.get('/timeline', function (request, response) {
response.header('Access-Control-Allow-Origin', '*');
response.json(timeline);
});
/*--------------------------------------------------------------------------------------------------------------*/
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});<file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.view = com.apress.view || {};
com.apress.view.ProfilePopupView = Backbone.View.extend({
template: Handlebars.compile($("#profile-template").html()),
model: null,
initialize: function(options){
var self = this;
self.model = new com.apress.model.Profile({ id:options.user });
self.render();
self.model.fetch();
self.listenTo(self.model, 'change', self.render);
},
render: function(){
var self = this;
if (self.model.get('screen_name')) {
var output = self.template({user: self.model.toJSON()});
BootstrapDialog.show({
title: '@'+self.model.get('screen_name') + 's Profile',
message: output,
});
}
return self;
}
});<file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.model = com.apress.model || {};
com.apress.model.Profile = Backbone.Model.extend({
urlRoot: '/profile',
parse: function(model){
return model;
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.model = com.apress.model || {};
com.apress.model.Search = Backbone.Model.extend({
url: '/search',
sync: function(method, model, options){
if (this.get('query')) {
this.url = this.url + '/' + this.get('query');
}
Backbone.sync.call(this,method,model,options);
},
parse: function(model){
return model;
}
});
var com = com || {};
com.apress = com.apress || {};
com.apress.model = com.apress.model || {};
com.apress.model.Tweet = Backbone.Model.extend({
parse: function(model){
// model.created_at "Web Aug 28 06:32:07 +0000 2013"
var friendly = moment(model.created_at, "ddd MMM DD HH:mm:ss ZZ YYYY").fromNow();
model.friendlyDate = friendly;
return model;
}
});<file_sep>var express = require('express'),
path = require('path'),
http = require('http'),
connectToTwitter = require('./connectToTwitter')
;
/*--------------------------------------------------------------------------------------------------------------*/
var app = express(),
client = connectToTwitter.connect();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.static(path.join(__dirname, 'public')));
});
/*--------------------------------------------------------------------------------------------------------------*/
// Main page
app.get('/', function (req,res){
res.sendfile(__dirname + '/index.html');
});
/**
* Get the account settings for the user with the id provided.
**/
app.get('/profile/:id', function(request, response){
response.header('Access-Control-Allow-Origin', '*');
client.get('users/show', {screen_name: request.params.id}, function (err, reply) {
if(err){
console.log('Error: ' + err);
response.send(404);
}
if(reply){
// console.log('Reply: ' + reply);
response.json(reply);
}
});
});
/**
* Runs a search given a query
**/
app.get('/search/:query', function (request, response) {
response.header('Access-Control-Allow-Origin', '*');
//search term is
var searchTerm = request.params.query;
client.get('search/tweets', { q: searchTerm, count: 100 }, function(err, reply) {
if(err){
console.log('Error: ' + err);
response.send(404);
}
if(reply){
// console.log('Reply: ' + reply);
response.json(reply);
}
});
});
/**
* Returns the twitter timeline for the current user
**/
app.get('/timeline', function (request, response) {
response.header('Access-Control-Allow-Origin', '*');
client.get('statuses/home_timeline', { count: 100}, function (err, reply) {
if(err){
console.log('Error: ' + err);
response.send(404);
}
if(reply){
response.json(reply);
}
});
});
/*--------------------------------------------------------------------------------------------------------------*/
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});<file_sep>var Twit = require('twit');
exports.connect = function (){
client = new Twit({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
});
return client;
};<file_sep># Twitter-Backbone-Client
**Sample application to create a twitter client with backbone.js and RESTful server in node.jsava**
## What i need to run the app?
1. You must have installed node.js
2. Getting Set Up on Twitter
Utilize the Twitter API, go to https://dev.twitter.com/apps and set up authorization for the client.
3. Edit connectToTwitter.js file and set your data for
consumer_key: '...'
, consumer_secret: '...'
, access_token: '...'
, access_token_secret: '...'
## How run the app?
1. Open a terminal and node path_to_js_file.js
1. Open http://localhost:3000 in a browser
<file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.collection = com.apress.collection || {};
com.apress.collection.Timeline = Backbone.Collection.extend({
model: com.apress.model.Tweet,
url: '/timeline',
initialize: function(){
}
});
<file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.model = com.apress.model || {};
com.apress.model.Profile = Backbone.Model.extend({
urlRoot: '/profile',
parse: function(model){
return model;
}
});<file_sep>module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
css: ['dest/css','public/css/'],
js: ['dest/js','public/js/'],
},
copy: {
js: {
files: [
{src: ['assets/js/app/app.js'], dest: 'dest/js/all/7.js', filter: 'isFile'},
]
},
css: {
files: [
{expand: true, flatten: true, src: ['assets/css/**'], dest: 'dest/css/all/', filter: 'isFile'},
]
}
},
concat: {
vendor: {
src: ['assets/js/vendor/jquery-1.11.1.min.js','assets/js/vendor/underscore-min.js','assets/js/vendor/backbone-min.js','assets/js/vendor/moment.min.js','assets/js/vendor/handlebars.min.js','assets/js/vendor/bootstrap.min.js','assets/js/vendor/bootstrap-dialog.min.js'],
dest: 'dest/js/all/1.js'
},
app_utils: {
src: ['assets/js/app/util/*.js'],
dest: 'dest/js/all/2.js'
},
app_models: {
src: ['assets/js/app/model/*.js'],
dest: 'dest/js/all/3.js'
},
app_collections: {
src: ['assets/js/app/collection/*.js'],
dest: 'dest/js/all/4.js'
},
app_views: {
src: ['assets/js/app/view/*.js'],
dest: 'dest/js/all/5.js'
},
app_router: {
src: ['assets/js/app/router/*.js'],
dest: 'dest/js/all/6.js'
},
all: {
src: ['dest/js/all/*.js'],
dest: 'dest/js/concat/concat.js'
},
css: {
src: 'dest/css/all/*.css',
dest: 'dest/css/concat/concat.css'
}
},
uglify: {
my_target: {
files: {
'public/js/output.min.js': ['dest/js/concat/concat.js']
}
}
},
cssmin: {
minify: {
files: {
'public/css/output.min.css': ['dest/css/concat/concat.css']
}
}
},
watch: {
js: {
files: ['assets/js/app/**/*.js','assets/js/vendor/*.js'],
tasks: ['clean:js','copy:js','concat:vendor','concat:app_utils','concat:app_models','concat:app_collections','concat:app_views','concat:app_router','concat:all','uglify']
},
css: {
files: 'assets/css/*.css',
tasks: ['clean:css','copy:css','concat:css','cssmin']
},
},
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['clean','copy','concat','uglify','cssmin']);
};<file_sep>var com = com || {};
com.apress = com.apress || {};
com.apress.router = com.apress.router || {};
com.apress.router.AppRouter = Backbone.Router.extend({
searchModel: null,
initialize: function(options){
var self = this;
self.searchModel = options.searchModel;
self.listenTo(self.searchModel,'change:query', self.navigateToSearch);
self.searchModel.on('app:error', function(error){
alert(error.message);
});
},
navigateToSearch: function(model, options){
var url = 'search/' + model.get('query');
this.navigate(url, {trigger: true});
},
routes: {
'search/:query': 'search'
},
search: function(query){
var self = this;
console.log('search for ' + query);
if (self.searchModel.get('query') !== query) {
self.searchModel.set('query', query, {silent:true});
}
self.searchModel.fetch({
success: function(model){
var resultsView = new com.apress.view.ResultsView({model:model});
},
error: function(e){
alert('No result available');
}
});
}
}); | ff47b2f1776171dff9ea38ef1398699c4f2f4f2d | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | ifreddyrondon/Twitter-Backbone-Client | 263dc44043b5dd1fa0c29dc098e663c89f705bd6 | 0dcd4515be4cc4cbdf88256e3419d82a18f839bb |
refs/heads/master | <repo_name>semvoja/checkMailTest<file_sep>/src/com/company/Main.java
package com.company;
public class Main {
public static void main(String args[]) throws Exception {
WorkWithMail.setUserName("");
WorkWithMail.setPassword("");
WorkWithMail.setReceivingHost("imap.gmail.com");
WorkWithMail.loadFirstData();
MailCheckerThread thread=new MailCheckerThread();
new Thread(thread).start();
}
}
| 44252ff69ad2144714fa677e50df0c26874244c8 | [
"Java"
] | 1 | Java | semvoja/checkMailTest | 0ec6f346036500e94219f1ed396b4f0e9476ad4b | 672fb66459b33a8c93b967362863c7ba94dfda60 |
refs/heads/master | <repo_name>LucaDorinAnton/PPA-Assignment-3<file_sep>/README.md
# PPA-Assignment-3
Pair programming project: <NAME> & <NAME>
<file_sep>/src/Terrain.java
/**
* Abstract class Terrain - The terrain is an actor that does not move.
* It is still an actor because the classes that inherit from it may have
* different functionality (can be extended).
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public abstract class Terrain extends Actor
{
/**
* Abstract constructor for Terrain objects.
* @param field - the field.
* @param location - the location of the Terrain object.
* @param sim - the simulator that operates this actor.
*/
public Terrain(Field field, Location location, Simulator sim) {
super(field,location, sim);
}
}
<file_sep>/src/Animal.java
import java.util.List;
import java.util.Iterator;
import java.util.Random;
import java.util.LinkedList;
/**
* A class representing shared characteristics of animals.
* Abstract class - impemented through the specific hierarchy.
*
*
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public abstract class Animal extends Actor
{
// Whether the animal is alive or not.
private boolean alive;
// Age of the animal.
private int age;
// Current foodLevel of the animal.
private int foodLevel;
// Gender boolean variable.
private boolean isFemale;
private static final Random rand = Randomizer.getRandom();
/**
* Create a new animal at location in field.
*
* @param randomAge - if animal is a new born or not.
* @param field The field currently occupied.
* @param location The location within the field.
* @param simulator - the Simulator in which this animal operates.
*/
public Animal(boolean randomAge, Field field, Location location, Simulator sim)
{
super(field,location, sim);
alive = true;
this.isFemale = rand.nextBoolean();
if(randomAge) {
age = rand.nextInt(getMaxAge());
foodLevel = rand.nextInt(getMaxFoodLevel());
}
else {
age = 0;
foodLevel = getMaxFoodLevel();
}
}
/**
* Returns the current food level of the animal.
* @return int - the food level as an integer value.
*/
protected int getFoodLevel() {
return foodLevel;
}
/**
* Increases the food level of the animal.
* @param newFoodLevel - the food level which increase the current food level.
*/
protected void increaseFoodLevel(int newFoodLevel) {
foodLevel = (foodLevel + newFoodLevel)%getMaxFoodLevel();
}
/**
* Abstract method: Returns the maximum food level defined in each specific class.
*/
abstract protected int getMaxFoodLevel();
/**
* Abstract method: Returns the maximum age defined in each specific class.
*/
abstract protected int getMaxAge();
/**
* Check whether the animal is alive or not.
* @return true if the animal is still alive.
*/
protected boolean isAlive()
{
return alive;
}
/**
* Indicate that the animal is no longer alive.
* It is removed from the field.
*/
protected void setDead()
{
alive = false;
if(super.getLocation() != null) {
super.removeFromField();
}
}
/**
* Increments the hunger of the animal by decrementing the foodLevel.
* If the foodLevel is 0 then the animal dies of starvation.
*/
protected void incrementHunger()
{
foodLevel--;
if(foodLevel <= 0) {
setDead();
}
}
/**
* Increments the age of the animal.
* If the age exceets the MAX_AGE constant the animal will die.
* Note: the MAX_AGE constant is defined in each specific class and it may vary.
*/
protected void incrementAge()
{
age++;
if(age > getMaxAge()) {
setDead();
}
}
/**
* This method implemnts the act of giving birth to young.
* @return List<Animal> - the list of new born babies to be scattered around
* the breeeding couple in the simulator.
*/
protected List<Animal> giveBirth() {
List<Animal> newBorn = new LinkedList<>();
if (isFemale) {
Field field = getField();
List<Location> free = field.getFreeAdjacentLocations(getLocation());
for (Iterator<Location> it = free.iterator(); it.hasNext(); ) {
if ( !isInHabitat(it.next()) ) {
it.remove();
}
}
int births = breed();
for(int b = 0; b < births && free.size() > 0; b++) {
Location loc = free.remove(0);
newBorn.add(getNewAnimal(field, loc));
}
}
return newBorn;
}
/**
* Abstract method:
* Returns the habitat of the animal defined in specific classes to see if the
* animal is in the correct habitat.
* @param l - the current location of the animal.
* @return - boolean - true if the animal is in habitat / false if not.
*/
abstract protected boolean isInHabitat(Location l);
/**
* Abstract method:
*
* In order for the giveBirth method to remain abstract at this level
* this method provides the Animal type of the new baby that has been
* born.
*
* @param field - the current field.
* @loc - the current location of the animal.
*
* @return Animal - the new Animal at that location in field.
*/
abstract protected Animal getNewAnimal(Field field, Location loc);
/**
* Abstract method:
*
* Returns the breeding probability defined in specific classes to determine
* whether the couple will have babies or not.
*
* @return double - the probability (0% to 100%)
*/
abstract protected double getBreedingProbability();
/**
* Abstract method:
*
* Returns the maximum amount of young that a couple can have defined in specific
* classes.
*
* @return int - the maximum number of babies.
*/
abstract protected int getMaxSpawnSize();
/**
* This method calculates randomly how many young babies a couple can have
* and returns the number.
* @return births - the number of new born babies.
*/
private int breed()
{
int births = 0;
if(canBreed() && rand.nextDouble() <= getBreedingProbability()) {
births = rand.nextInt(getMaxSpawnSize()) + 1;
}
return births;
}
/**
* Abstract method:
*
* Not all animals have the same breeding age so this method is right to be
* defined as abstract. It retunrns the breeding age defined in the specific
* classes.
* @return int - the breeding age of the animal.
*/
abstract protected int getBreedingAge();
/**
* Returns if the animal is a female or not.
* @return boolean - isFemale.
*/
protected boolean isFemale() {
return isFemale;
}
/**
* Each animal that can breed must look nearby and find a oposit gender of
* the same specie. Then it can breed.
* @param boolean - true if if can breed / false if not.
*/
public boolean canBreed()
{
if (!isFemale){
return age >= getBreedingAge() && foodLevel >= getMaxFoodLevel()/2;
}
if (age >= getBreedingAge() && foodLevel >= getMaxFoodLevel()/2) {
List possibleMates = getField().getSurroundingObjects(getLocation());
for ( Object obj : possibleMates ) {
if ( obj.getClass().getSimpleName().equals(this.getClass().getSimpleName()) ) {
Animal mate = (Animal) obj;
if ( !mate.isFemale() ) {
if ( mate.canBreed() ) {
return true;
}
}
}
}
}
return false;
}
}
<file_sep>/src/Weather.java
import java.util.Random;
/**
* This class models the weather through our simulation.
* The weather of the simulation keeps going for a certain time
* then it changes. After changing it cannot change again for another
* certain number steps set by a constant variable.
*
* It has a single method that defines the next weather of the simulation.
*
* The default weather is NORMAL (meaning sunny/partly cloudy).
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public class Weather
{
/* Constant variables defined below */
/* Sets the basic amount of steps that needs to pass in order
for the current weather to change. */
private static final int OFFSET_DECISION_STEPS = 300;
// The new duration of the current weather can vary with this amount.
private static final int MAX_DECISION_OFFSET = 100;
// Constants defining the different states of the weather.
public static final int RAINING = -1;
public static final int NORMAL = 0;
public static final int DRY = 1;
/* Constant variables defined above */
private int currentWeather;
public int timeTillDecision; // Keeps the time unitil the weather changes.
private static final Random rand = Randomizer.getRandom();
/**
* Constructor for Weather type objects.
*/
public Weather() {
currentWeather = NORMAL;
timeTillDecision = OFFSET_DECISION_STEPS;
}
/**
* This method computes the next state of the weather based on random
* numbers. If the timeTillDecision is not yet done it just returns the
* current weather.
* @return int - the next state of the weather based on randomness.
*/
public int getWeather() {
if (timeTillDecision == 0) {
if ( rand.nextBoolean() ) {
timeTillDecision = OFFSET_DECISION_STEPS + rand.nextInt(MAX_DECISION_OFFSET);
}else {
timeTillDecision = OFFSET_DECISION_STEPS - rand.nextInt(MAX_DECISION_OFFSET);
}
int nextWeather = rand.nextInt(3);
if ( nextWeather == 0) {
currentWeather = DRY;
}else if (nextWeather ==1) {
currentWeather = NORMAL;
}else {
currentWeather = RAINING;
}
return currentWeather;
}else {
timeTillDecision --;
return currentWeather;
}
}
}
<file_sep>/src/Simulator.java
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Color;
/**
* A simple predator-prey simulator, based on a rectangular field
* containing rabbits and foxes.
*
* @author <NAME> and <NAME>
* @version 2016.02.29 (2)
*/
public class Simulator
{
// Constants representing configuration information for the simulation.
// The default width for the grid.
private static final int DEFAULT_WIDTH = 200;
// The default depth of the grid.
private static final int DEFAULT_DEPTH = 120;
private static final double SEAGULL_CREATION_PROBABILITY = 0.055;
private static final double SHARK_CREATION_PROBABILITY = 0.0025;
private static final double KILLERWHALE_CREATION_PROBABILITY = 0.0015;
private static final double COD_CREATION_PROBABILITY = 0.04;
private static final double MACKEREL_CREATION_PROBABILITY = 0.03;
private static final double ANCHOVY_CREATION_PROBABILITY = 0.06;
private static final double ALGAE_CREATION_PROBABILITY = 0.4;
private static final double PLANKTON_CREATION_PROBABILITY = 0.2;
private static final double ROCK_CREATION_PROBABILITY = 0.5;
private static final double SOIL_CREATION_PROBABILITY = 0.5;
private static final int MAX_TERRAIN_HEIGHT = 5;
private boolean testing = false;
// List of animals in the field.
private List<Actor> actors;
// The current state of the field.
private Field field;
// The current step of the simulation.
private int step;
// A graphical view of the simulation.
private SimulatorView view;
private DayNightCycle dnCycle;
private boolean continueSimulating;
private Weather weather;
private int currentWeather;
private static final Random rand = Randomizer.getRandom();
public static void main(String[] args) {
new Simulator();
}
/**
* Construct a simulation field with default size.
*/
public Simulator()
{
this(DEFAULT_DEPTH, DEFAULT_WIDTH);
}
/**
* Create a simulation field with the given size.
* @param depth Depth of the field. Must be greater than zero.
* @param width Width of the field. Must be greater than zero.
*/
public Simulator(int depth, int width)
{
if(width <= 0 || depth <= 0) {
System.out.println("The dimensions must be greater than zero.");
System.out.println("Using default values.");
depth = DEFAULT_DEPTH;
width = DEFAULT_WIDTH;
}
actors = new ArrayList<>();
field = new Field(depth, width);
dnCycle = new DayNightCycle(this);
weather = new Weather();
continueSimulating = false;
currentWeather = Weather.NORMAL;
// Create a view of the state of each location in the field.
view = new SimulatorView(depth, width, this);
view.setColor(Seagull.class,Seagull.getClassColor());
view.setColor(Shark.class,Shark.getClassColor());
view.setColor(KillerWhale.class,KillerWhale.getClassColor());
view.setColor(Cod.class,Cod.getClassColor());
view.setColor(Mackerel.class,Mackerel.getClassColor());
view.setColor(Anchovy.class,Anchovy.getClassColor());
view.setColor(Algae.class,Algae.getClassColor());
view.setColor(Plankton.class,Plankton.getClassColor());
view.setColor(Rock.class,Rock.getClassColor());
view.setColor(Soil.class,Soil.getClassColor());
// Setup a valid starting point.
reset();
}
/**
* Run the simulation from its current state for a reasonably long period,
* (4000 steps).
*/
public void runLongSimulation()
{
simulate(4000);
}
public int getStep() {
return step;
}
/**
* Run the simulation from its current state for the given number of steps.
* Stop before the given number of steps if it ceases to be viable.
* @param numSteps The number of steps to run for.
*/
public void simulate(int numSteps)
{
startSimulation();
for(int step = 1; step <= numSteps && view.isViable(field); step++) {
simulateOneStep();
if(!continueSimulating) {
step = numSteps + 2;
}
// delay(60); // uncomment this to run more slowly
}
}
private void startSimulation() {
continueSimulating = true;
}
public void stopSimulation() {
continueSimulating = false;
}
/**
* Run the simulation from its current state for a single step.
* Iterate over the whole field updating the state of each
* fox and rabbit.
*/
public void simulateOneStep()
{
step++;
currentWeather = weather.getWeather();
//System.out.println(weather.timeTillDecision + "- " + weatherNow);
// Provide space for newborn animals.
List<Actor> newActors = new ArrayList<>();
// Let all rabbits act.
//System.out.println(dnCycle.getPartOfDay());
for(Iterator<Actor> it = actors.iterator(); it.hasNext(); ) {
if(!continueSimulating) {
break;
}
Actor actor = it.next();
if(actor instanceof Animal) {
Animal animal = (Animal) actor;
if(!animal.isAlive()) {
it.remove();
}else {
actor.act(newActors);
}
}else if ( actor instanceof Plant ) {
Plant plant = (Plant) actor;
if ( !plant.isAlive() ) {
it.remove();
}else {
actor.act(newActors);
}
}else {
actor.act(newActors);
}
}
// Add the newly born foxes and rabbits to the main lists.
actors.addAll(newActors);
view.showStatus(step, field);
}
/**
* Reset the simulation to a starting position.
*/
public void reset()
{
step = 0;
actors.clear();
field = new Field(field.getDepth(), field.getWidth());
continueSimulating = false;
populate(testing);
view.resetStats();
//System.out.println(field.getObjectAt(2, 2).toString());
// Show the starting state in the view.
view.showStatus(step, field);
}
private void generateTerrain() {
for (int col = 0 ; col < field.getWidth() ; col ++ ) {
int colHeight = rand.nextInt(MAX_TERRAIN_HEIGHT) + 1;
for ( int row = field.getDepth() - 1 ; row >= field.getDepth() - colHeight ; row -- ) {
if (rand.nextDouble() <= ROCK_CREATION_PROBABILITY) {
Location location = new Location(row,col);
Rock rock = new Rock(field,location, this);
actors.add(rock);
}else {
Location location = new Location(row,col);
Soil soil = new Soil(field,location, this);
actors.add(soil);
}
}
}
}
private void populate(boolean testing) {
if (testing) {
//generateTerrain();
}else {
populate();
}
}
/**
* Randomly populate the field with foxes and rabbits.
*/
private void populate()
{
generateTerrain();
for (int row = 0 ; row < field.getDepth() ; row ++ ) {
for (int col = 0 ; col < field.getWidth() ; col ++ ) {
if ( field.getObjectAt(row,col) == null ) {
Location currentLocation = new Location(row,col);
int depth = field.getDepth();
Actor actor = null;
if ( rand.nextDouble() <= KILLERWHALE_CREATION_PROBABILITY && KillerWhale.isInHabitatStatic(currentLocation,this)){
actor = new KillerWhale(true,field,currentLocation, this);
}else if ( rand.nextDouble() <= SHARK_CREATION_PROBABILITY && Shark.isInHabitatStatic(currentLocation,this)) {
actor = new Shark(true,field,currentLocation, this);
}else if ( rand.nextDouble() <= SEAGULL_CREATION_PROBABILITY && Seagull.isInHabitatStatic(currentLocation,this)) {
actor = new Seagull(true,field,currentLocation, this);
}else if ( rand.nextDouble() <= COD_CREATION_PROBABILITY && Cod.isInHabitatStatic(currentLocation,this)) {
actor = new Cod(true,field,currentLocation, this);
}else if ( rand.nextDouble() <= MACKEREL_CREATION_PROBABILITY && Mackerel.isInHabitatStatic(currentLocation,this)) {
actor = new Mackerel(true,field,currentLocation, this);
}else if ( rand.nextDouble() <= PLANKTON_CREATION_PROBABILITY && Plankton.isInHabitatStatic(currentLocation,this)) {
actor = new Plankton(field,currentLocation, this);
}else if ( rand.nextDouble() <= ANCHOVY_CREATION_PROBABILITY && Anchovy.isInHabitatStatic(currentLocation,this)) {
actor = new Anchovy(true,field,currentLocation, this); // Ok
}
if ( actor != null ) {
actors.add(actor);
}
}
}
}
}
/**
* Pause for a given time.
* @param millisec The time to pause for, in milliseconds
*/
private void delay(int millisec)
{
try {
Thread.sleep(millisec);
}
catch (InterruptedException ie) {
// wake up
}
}
/**
* Returns the DayNightCycle object.
* @return DayNightCycle object.
*/
public DayNightCycle getDayNightCycle() {
return dnCycle;
}
/**
* Returns the current weather.
* @return int - currentWeather - the weather constant to be returned.
*/
public int getCurrentWeather() {
return currentWeather;
}
/**
* Returns the field of the simulator.
* @return field Field - the field to be returned.
*/
public Field getField() {
return field;
}
}
<file_sep>/src/DayNightCycle.java
/**
* This class models the Day-Night cycle that keeps track
* of the clock and the day-counter of the simulator.
*
* This class receives the current step of the simulation from
* a (Simulator) object reference and returns the clock and the day counter.
*
* It has methods such as getCurrentDay, getCurrentTimeString (clock) and
* getPartOfDay.
*
* @author <NAME> and <NAME>.
* @version v1.0
*/
public class DayNightCycle
{
/* Constats are defined for consistency through code*/
public static final int HOUR_LENGHT = 60; // One hour is 60 steps in simulation
private static final int DAY_LENGHT = 1440; // Inherently one day is 1440 steps
/* The day is made out of 4 quarters of 360 steps so the daylight
starts at the step 360: 6:00 AM. Between 00:00 and 6:00 is considered to be NIGHT*/
private static final int DAY_START = 360;
/* Day ends at 1080: 18:00 PM - from now on comes NIGHT*/
private static final int DAY_END = 1080;
// This constant defines the initial state of the simulator when it is opened.
private static final int DAY_START_OFFSET = 720;
// Two 'public' constants for the DAY and NIGHT to be referenced throughout the code.
public static final int NIGHT = 1212;
public static final int DAY = 2121;
/* ^ Constants are defined above ^ */
/* The simulator that provides the current step of the simulation */
private Simulator sim;
/**
* Constructor for class objects.
* @ param sim - Simulator reference needed for calculus.
*/
public DayNightCycle(Simulator sim) {
this.sim = sim;
}
/**
* This method returns the current day of the simulation based on the
* step and on the current DAY_START_OFFSET (which now is 720). This means
* that the simulation will start from 12:00 (Day 1) and will continue.
*
* @return int - Integer representing the day of the simulation.
*/
public int getCurrentDay() {
return ((sim.getStep() + DAY_START_OFFSET)/DAY_LENGHT) + 1;
}
/**
* Here the time string is returned based on the steps provided by the
* simulator.
* Constants defined above are used.
*
* @return String - the clock String that will be displayed at the bottom
* of the simulator GUI.
*/
public String getCurrentTimeString() {
int time = (sim.getStep() + DAY_START_OFFSET)%DAY_LENGHT;
int hour = time/HOUR_LENGHT;
int minute = time%HOUR_LENGHT;
String res;
if(hour <= 9) {
res = "0" + hour;
} else {
res = "" + hour;
}
if(minute <= 9) {
res += ":0" + minute;
} else {
res+= ":" +minute;
}
return res;
}
//*******************************************************
/**
* This method returns the current step of the day using the modulo
* operator. The timeInt is needed in order to maintain the day night
* cycle correct throught the gradient changing in the SimulatorView class.
* @return int - the step of the current day - starting from 0 to 1439.
*/
public int getCurrentTimeInt() {
return (sim.getStep() + DAY_START_OFFSET)%DAY_LENGHT;
}
/**
* This method returns the part of the day based on the steps and the DAY_START_OFFSED
* @return - int - constant value that could be either DAY or NIGHT.
*/
public int getPartOfDay() {
if((sim.getStep() + DAY_START_OFFSET)%DAY_LENGHT >= DAY_START && (sim.getStep() + DAY_START_OFFSET)%DAY_LENGHT < DAY_END){
return DayNightCycle.DAY;
} else {
return DayNightCycle.NIGHT;
}
}
}
<file_sep>/src/Actor.java
import java.util.List;
import java.awt.Color;
/**
* Abstract class Actor - Represents an abstract summary or all the existing
* entities in the Simulator.
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public abstract class Actor
{
// The animal's field.
private Field field;
// The animal's position in the field.
private Location location;
// Simulator object reference.
private Simulator sim;
/**
* Abstract constructor for Actor inherited type.
* @param field - the field is passed to the actor.
* @param location - the location of the actor in the field.
* @param sim - simulator object. (for extendibility we may have different simulators).
*/
public Actor(Field field, Location location, Simulator sim) {
this.field = field;
this.location = location;
this.sim = sim;
field.place(this,location);
}
/**
* Main method for acting throughout the simulation.
* @param newActors - The list of newBorn young after one step.
*/
abstract public void act(List<Actor> newActors);
/**
* Returns the location of the actor in the field.
* @return location - the location of the actor in the field.
*/
protected Location getLocation()
{
return location;
}
/**
* This method updates the location of the actor within the field.
* @param newLocation - the location to be set as new.
*/
protected void setLocation(Location newLocation)
{
if(location != null) {
field.clear(location);
}
location = newLocation;
field.place(this, newLocation);
}
/**
* This method removes the actor from the field.
* It clears the location and set all the references of the actor
* to null.
*/
protected void removeFromField() {
field.clear(location);
location = null;
field = null;
}
/**
* Sets the new field for the actor.
* @param newField - new field to be set.
*/
protected void setField(Field newField) {
field = newField;
}
/**
* This method returns the field of the actor.
* @return field - the field returned.
*/
protected Field getField()
{
return field;
}
/**
* Returns the simulator object reference.
* @param sim - the simulator of the current actor.
*/
protected Simulator getSim() {
return sim;
}
}
<file_sep>/src/SimulatorRunnable.java
/**
* A particular class that implements Runnable interface
* in order for the SimulatorThread to run in proper conditions.
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public class SimulatorRunnable implements Runnable
{
private Simulator simulator;
private SimulatorThread thread;
/**
* Constructor for SimulatorRunnable objects.
* @param simulator - Simulator object passed.
*/
public SimulatorRunnable(Simulator simulator) {
this.simulator = simulator;
}
/**
* Set the current thread.
* @param thread - SimulatorThread - the thread to be set.
*/
public void setThread(SimulatorThread thread) {
this.thread = thread;
}
/**
* Method implemented from the Runnable interface.
*/
public void run() {
simulator.simulate(thread.getSteps());
}
}<file_sep>/src/Plant.java
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
/**
* Abstract class Plant - Implements the abstract behaviour of
* the plants in this simulations.
*
* @author <NAME> and <NAME>
* @version v1.0
*/
public abstract class Plant extends Actor
{
// How much food a plant provides.
private int foodValue;
// Constants for providing the food value in a random way.
private static final double LOWER_FOOD_VALUE = 0.05;
private static final double HIGHER_FOOD_VALUE = 0.95;
private static final Random rand = Randomizer.getRandom();
// If the plant is alive or not.
private boolean isAlive;
/**
* Abstract constructor for Plant objects:
* @param field - the current field.
* @param location - the location of the plant.
* @param sim - the simulator that operates this plant actor.
*/
public Plant(Field field, Location location, Simulator sim) {
super(field,location, sim);
this.foodValue = getFoodValue();
isAlive = true;
if (rand.nextDouble() <= LOWER_FOOD_VALUE && foodValue >= 1) {
foodValue --;
}else if(rand.nextDouble() >= HIGHER_FOOD_VALUE) {
foodValue ++;
}
}
/**
* Abstract method:
* Returns the food value of the plant defined in specific classes.
*
* Each plant may have a different food value.
*/
abstract public int getFoodValue();
/**
* Set the state of the plant to dead.
*/
public void setDead() {
isAlive = false;
if (super.getLocation() != null) {
super.removeFromField();
}
}
/**
* Abstract method:
* Returns the habitat of the plant defined in specific classes to see if the
* plant is in the correct habitat.
* @param l - the current location of the plant.
* @return - boolean - true if the plant is in habitat / false if not.
*/
abstract protected boolean isInHabitat(Location loc);
/**
* Abstract method implemented:
* The plants will grow as defined in the abstract method grow.
* @param newActors - the new plants to be displayed.
*/
public void act(List<Actor> newActors) {
if(!isInHabitat(super.getLocation())) {
setDead();
return;
}
DayNightCycle cycle = super.getSim().getDayNightCycle();
if(cycle.getPartOfDay() == DayNightCycle.DAY) {
List<Plant> newPlants = new ArrayList<Plant>();
grow(newPlants);
for (Plant plant : newPlants) {
newActors.add(plant);
}
}
}
/**
* Abstract method:
*
* Implements the growth of the plant. As our plants have different behaviours
* when it comes to growing this method is meant to be abstract.
*
* @param newPlants - the new plants that will grow at the next step in simulation.
*/
abstract protected void grow(List<Plant> newPlants);
/**
* Checks if the plant is alive or not.
* @return boolean - true if the plant is alive / false if not.
*/
public boolean isAlive() {
return isAlive;
}
}
| 00e5a8ba4862c5a1f712ea6c0a7b3b1b26ef90b0 | [
"Markdown",
"Java"
] | 9 | Markdown | LucaDorinAnton/PPA-Assignment-3 | 069b7e100d74021d83001b18732bfc9c13621f01 | 34a409564f62a2f37dc361ac39c9c9d7383e36b3 |
refs/heads/master | <repo_name>crossdsection/irshaad-backend<file_sep>/db/data/16/dropUselessTables.sql
DROP TABLE state_reviews;
DROP TABLE details_reviews
<file_sep>/db/schema/wv_email_verification.sql
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 20, 2018 at 11:23 AM
-- Server version: 10.1.29-MariaDB-6
-- PHP Version: 7.0.29-1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `worldvoting`
--
-- --------------------------------------------------------
--
-- Table structure for table `email_verification`
--
CREATE TABLE `email_verification` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`token` varchar(36) COLLATE utf8_unicode_ci NOT NULL,
`code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`expirationtime` datetime NOT NULL,
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT 'Status disables after usage.',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Triggers `email_verification`
--
DELIMITER $$
CREATE TRIGGER `Set Expiration Time` BEFORE INSERT ON `email_verification` FOR EACH ROW BEGIN
SET NEW.expirationtime = NOW() + INTERVAL 5 HOUR;
END
$$
DELIMITER ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `email_verification`
--
ALTER TABLE `email_verification`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `email_verification`
--
ALTER TABLE `email_verification`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/db/data/1/wv_oauth.sql
-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jun 04, 2018 at 07:10 AM
-- Server version: 10.2.14-MariaDB-log
-- PHP Version: 5.6.36
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `worldvote2`
--
-- --------------------------------------------------------
--
-- Table structure for table `oauth`
--
CREATE TABLE `oauth` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`provider_id` varchar(512) NOT NULL,
`access_token` varchar(2048) NOT NULL,
`issued_at` datetime NOT NULL,
`expiration_time` datetime NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`modified` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `oauth`
--
INSERT INTO `oauth` (`id`, `user_id`, `provider_id`, `access_token`, `issued_at`, `expiration_time`, `created`, `modified`) VALUES
(1, 36, 'https://localhost', 'xwxLftFsFLyb3SxYSUhY8dJruOav/xjqX8CufTgig+o=', '2018-06-04 06:29:20', '2018-06-05 06:29:20', '2018-06-04 06:14:57', '2018-06-04 06:29:20');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `oauth`
--
ALTER TABLE `oauth`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `oauth`
--
ALTER TABLE `oauth`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/config/routes.php
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
/**
* The default class to use for all routes
*
* The following route classes are supplied with CakePHP and are appropriate
* to set as the default:
*
* - Route
* - InflectedRoute
* - DashedRoute
*
* If no call is made to `Router::defaultRouteClass()`, the class used is
* `Route` (`Cake\Routing\Route\Route`)
*
* Note that `Route` does not do any inflections on URLs which will result in
* inconsistently cased URLs when used with `:plugin`, `:controller` and
* `:action` markers.
*
* Cache: Routes are cached to improve performance, check the RoutingMiddleware
* constructor in your `src/Application.php` file to change this behavior.
*
*/
Router::defaultRouteClass(DashedRoute::class);
// Router::prefix('/auth', ['_namePrefix' => 'auth:'], function ($routes) {
// $routes->resources('User', [
// 'map' => ['login' => ['action' => 'login', 'method' => 'GET']]
// ]);
// });
Router::scope('/', function (RouteBuilder $routes) {
/**
* Here, we are connecting '/' (base path) to a controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, src/Template/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->post(
'/auth/login/*',
['controller' => 'User', 'action' => 'login']
);
$routes->post(
'/auth/signup/*',
['controller' => 'User', 'action' => 'signup']
);
$routes->post(
'/auth/recover',
['controller' => 'User', 'action' => 'forgotpassword']
);
$routes->post(
'/post/submit/*',
['controller' => 'Post', 'action' => 'add']
);
$routes->post(
'/files/submit/*',
['controller' => 'Fileuploads', 'action' => 'add']
);
$routes->post(
'/comments/submit/*',
['controller' => 'Comments', 'action' => 'new']
);
$routes->post(
'/favlocation/submit/*',
['controller' => 'FavLocation', 'action' => 'add']
);
$routes->post(
'/activity/submit/*',
['controller' => 'Activitylog', 'action' => 'add']
);
$routes->post(
'/polls/submit/*',
['controller' => 'UserPolls', 'action' => 'add']
);
$routes->post(
'/user/access/*',
['controller' => 'User', 'action' => 'updateaccess']
);
$routes->post(
'/user/update/*',
['controller' => 'User', 'action' => 'updateuserinfo']
);
$routes->post(
'/user/verify/*',
['controller' => 'User', 'action' => 'email_verification']
);
$routes->post(
'/user/changepicture/*',
['controller' => 'User', 'action' => 'changeProfilePicture']
);
$routes->post(
'/favlocation/remove/*',
['controller' => 'FavLocation', 'action' => 'delete']
);
$routes->post(
'/favlocation/default/*',
['controller' => 'FavLocation', 'action' => 'setDefault']
);
$routes->get(
'/auth/logout/*',
['controller' => 'User', 'action' => 'logout']
);
$routes->post(
'/user/getinfo/*',
['controller' => 'User', 'action' => 'getuserinfo']
);
$routes->get(
'/user/getinfo/*',
['controller' => 'User', 'action' => 'getuserinfo']
);
$routes->get(
'/post/get',
['controller' => 'Post', 'action' => 'getfeed']
);
$routes->post(
'/post/get/*',
['controller' => 'Post', 'action' => 'getfeed']
);
$routes->get(
'/countries/get/*',
['controller' => 'Countries', 'action' => 'get']
);
$routes->post(
'/post/getpost',
['controller' => 'Post', 'action' => 'getpost']
);
$routes->get(
'/comments/get/*',
['controller' => 'Comments', 'action' => 'get']
);
$routes->get(
'/favlocation/get/',
['controller' => 'FavLocation', 'action' => 'get']
);
$routes->get(
'/favlocation/exist/*',
['controller' => 'FavLocation', 'action' => 'checkExist']
);
$routes->get(
'/user/exist/*',
['controller' => 'User', 'action' => 'userexists' ]
);
$routes->get(
'/location/get/*',
['controller' => 'Localities', 'action' => 'get' ]
);
$routes->post(
'/user/follow/*',
['controller' => 'User', 'action' => 'follow' ]
);
$routes->post(
'/user/unfollow/*',
['controller' => 'User', 'action' => 'unfollow' ]
);
$routes->post(
'/user/getfollowers/*',
['controller' => 'User', 'action' => 'getFollowers' ]
);
$routes->post(
'/user/getfollowing/*',
['controller' => 'User', 'action' => 'getFollowings' ]
);
$routes->get(
'/user/getfollowers/*',
['controller' => 'User', 'action' => 'getFollowers' ]
);
$routes->get(
'/user/getfollowing/*',
['controller' => 'User', 'action' => 'getFollowings' ]
);
$routes->post(
'/post/getbookmarks/*',
['controller' => 'Activitylog', 'action' => 'getbookmarks' ]
);
$routes->post(
'/area/rate/*',
['controller' => 'AreaRatings', 'action' => 'rateArea' ]
);
$routes->get(
'/area/getratings/*',
['controller' => 'AreaRatings', 'action' => 'getdatewiseratings' ]
);
$routes->get(
'/post/getbookmarks/*',
['controller' => 'Activitylog', 'action' => 'getbookmarks' ]
);
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
/**
* Connect catchall routes for all controllers.
*
* Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for
* `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']);`
* `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']);`
*
* Any route class can be used with this method, such as:
* - DashedRoute
* - InflectedRoute
* - Route
* - Or your own route class
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks(DashedRoute::class);
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
<file_sep>/src/Controller/UserController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Utility\Hash;
use Cake\Routing\Router;
/**
* User Controller
*
* @property \App\Model\Table\UserTable $User
*
* @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class UserController extends AppController {
public $components = array('OAuth', 'Files');
public function userexists(){
$response = array( 'error' => 1, 'message' => '', 'data' => array() );
$getData = $this->request->query();
if( isset( $getData['email'] ) && $this->User->checkEmailExist( $getData['email'] ) ){
$response = array( 'error' => 0, 'message' => 'User Exists', 'data' => array( 'exist' => true, 'notExist' => false ) );
} else {
$response = array( 'error' => 0, 'message' => 'User Does not Exists', 'data' => array( 'exist' => false, 'notExist' => true ) );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Signup API
*/
public function signup() {
$response = array( 'error' => 1, 'message' => '', 'data' => array() );
$userData = array(); $continue = false;
$postKeys = array( 'email', '<PASSWORD>', 'firstName', 'lastName', 'latitude', 'longitude', 'gender', 'phone', 'certificate' );
$postData = $this->request->input( 'json_decode', true );
if( empty( $postData ) ){
$postData = $this->request->data;
}
if( isset( $postData['email'] ) && !$this->User->checkEmailExist( $postData['email'] ) ){
$continue = true;
}
if ( !empty( $postData ) && $continue ){
foreach( $postKeys as $postKey ){
if( isset( $postData[ $postKey ] ) && !empty( $postData[ $postKey ] ) ){
$newKey = strtolower( $postKey );
if( $postKey == 'certificate' ){
$file = $postData[ $postKey ];
$filePath = 'img' . DS . 'upload' . DS . $file['name'];
$fileUrl = WWW_ROOT . $filePath;
if( move_uploaded_file( $file['tmp_name'], $fileUrl ) ){
$userData[ $newKey ] = $filePath;
}
} else {
$userData[ $newKey ] = $postData[ $postKey ];
}
}
}
if( isset( $postData['birthDate'] ) ){
$userData['date_of_birth'] = date( 'Y-m-d', strtotime( $postData['birthDate'] ) );
}
$localityCheck = false;
$localityCheckArray = array( 'locality', 'city', 'latitude', 'longitude', 'state', 'country' );
$localityData = array();
foreach ( $localityCheckArray as $key => $value ) {
if( isset( $postData[ $value ] ) && ( $postData[ $value ] != '' or $postData[ $value ] != 0 ) ){
$localityData[ $value ] = $postData[ $value ];
$localityCheck = true;
} else {
$localityCheck = false;
break;
}
}
if( $localityCheck ){
$localeRes = $this->User->Cities->Localities->findLocality( $localityData );
if( $localeRes['error'] == 0 ){
foreach ( $localeRes['data'] as $key => $locale ) {
if( isset( $locale[0] ) && isset( $locale[0]['city_id'] ) )
$userData['city_id'] = $locale[0]['city_id'];
if( isset( $locale[0] ) && isset( $locale[0]['state_id'] ) )
$userData['state_id'] = $locale[0]['state_id'];
if( isset( $locale[0] ) && isset( $locale[0]['country_id'] ) )
$userData['country_id'] = $locale[0]['country_id'];
}
$res['data']['locale'] = $localeRes['data'];
}
}
if( !empty( $userData ) ){
$returnId = $this->User->add( $userData );
if( $returnId ){
$response = $this->User->EmailVerification->add( $returnId );
$baseUrl = Router::fullBaseUrl().'email/verify?token='.$response->token;
$emailData = array( 'action_url' => $baseUrl, 'code' => $response->code );
$result = $this->_sendMail( array( $userData['email'] ), 'Verification Email', 'emailVerification', $emailData );
$response = array( 'error' => 0, 'message' => 'Registration Successful', 'data' => array() );
} else {
$response = array( 'error' => 1, 'message' => 'Registration Failed', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Registration Failed', 'data' => array() );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Login API
*/
public function login() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( empty( $postData ) ){
$postData = $this->request->data;
}
if( isset( $postData['username'] ) && isset( $postData['password'] ) ){
$user = $this->User->find()->where([ 'email' => $postData['username'] ])->toArray();
if( !empty( $user ) && $this->User->checkPassword( $user[0]->password, $postData['password'] ) ){
$res = $this->OAuth->getAccessToken( $user[0]->id );
if( $res['error'] == 0 ){
$latitude = 0;
$longitude = 0;
if( isset( $postData['latitude'] ) && $postData['latitude'] != 0 ){
$latitude = $postData['latitude'];
}
if( isset( $postData['longitude'] ) && $postData['latitude'] != 0 ){
$longitude = $postData['longitude'];
}
$userData = array(
'user_id' => $user[0]->id,
'latitude' => $latitude,
'longitude'=> $longitude
);
$ret = $this->User->LoginRecord->saveLog( $userData );
$localityCheck = false;
$localityCheckArray = array( 'locality', 'city', 'latitude', 'longitude', 'state', 'country' );
$localityData = array();
foreach ( $localityCheckArray as $key => $value ) {
if( isset( $postData[ $value ] ) && ( $postData[ $value ] != '' or $postData[ $value ] != 0 ) ){
$localityData[ $value ] = $postData[ $value ];
$localityCheck = true;
} else {
$localityCheck = false;
break;
}
}
if( $localityCheck ){
$localeRes = $this->User->Cities->Localities->findLocality( $localityData );
if( $localeRes['error'] == 0 ){
foreach ( $localeRes['data'] as $key => $locale ) {
if( isset( $locale[0] ) && isset( $locale[0]['city_id'] ) )
$userData['city_id'] = $locale[0]['city_id'];
if( isset( $locale[0] ) && isset( $locale[0]['state_id'] ) )
$userData['state_id'] = $locale[0]['state_id'];
if( isset( $locale[0] ) && isset( $locale[0]['country_id'] ) )
$userData['country_id'] = $locale[0]['country_id'];
}
$res['data']['locale'] = $localeRes['data'];
}
}
}
$response = array( 'error' => $res['error'], 'message' => $res['message'], 'data' => $res['data'] );
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Login', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Login', 'data' => array() );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function logout() {
$response = array( 'error' => 1, 'message' => 'Invalid Request' );
$userId = null;
if( isset( $_GET['userId'] ) ){
$userId = $_GET['userId'];
}
if( $userId != null ){
$response = $this->OAuth->removeToken( $userId );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function getuserinfo() {
$response = array( 'error' => 1, 'message' => 'Invalid Request' );
$jsonData = $this->request->input('json_decode', true);
$getData = $this->request->query();
$postData = $this->request->getData();
$requestData = array_merge( $getData, $postData );
if( $jsonData )
$requestData = array_merge( $requestData, $jsonData );
if( !isset( $requestData['userId'] ) ){
$requestData['userId'] = $_POST['userId'];
$requestData['accessRoleIds'] = $_POST['accessRoleIds'];
}
if( !isset( $requestData['mcph'] ) ){
$requestData['mcph'] = $requestData['userId'];
}
if( !empty( $requestData ) ){
$data = $this->User->getUserInfo( array( $requestData['mcph'] ) );
if( !empty( $data ) ){
if( $requestData['mcph'] != $requestData['userId'] ){
$data[ $requestData['mcph'] ]['editable'] = false;
} else {
$data[ $requestData['mcph'] ]['editable'] = true;
}
$response = array( 'error' => 0, 'message' => 'Success!', 'data' => array_values( $data ) );
} else {
$response = array( 'error' => 0, 'message' => 'User Not Found', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function updateaccess() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['userId'] = $_POST['userId'];
$postData['accessRoleIds'] = $_POST['accessRoleIds'];
} else {
$postData = $this->request->getData();
}
if( isset( $postData['userIds'] ) && isset( $postData['access'] ) && !empty( $postData['access'] ) ){
$userData = $this->User->getUserList( $postData['userIds'], array( 'id', 'access_role_ids' ) );
$accessData = $this->User->AccessRoles->retrieveAccessRoleIds( $postData['access']['location'], array( $postData['access']['accessLevel'] ) );
$accessRoleIds = Hash::extract( $accessData, '{n}.id' );
$accessRoleIds = array_intersect( $accessRoleIds, $postData['accessRoleIds'] );
if( !empty( $accessRoleIds ) ){
foreach( $userData as $key => $user ){
$accessIds = json_decode( $userData[ $key ]['access_role_ids'] );
$accessIds = array_unique( array_merge( $accessIds, $accessRoleIds ) );
$userData[ $key ]['access_role_ids'] = json_encode( $accessIds );
}
$usersUpdated = $this->User->updateUser( $userData );
$userCount = count( $usersUpdated );
if( $userCount > 0 ){
$response = array( 'error' => 0, 'message' => $userCount.' users access have been updated.', 'data' => array() );
} else {
$response = array( 'error' => 0, 'message' => 'Update Failed.', 'data' => array() );
}
} else {
$response = array( 'error' => 0, 'message' => 'Forbidden Access.', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function updateuserinfo() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['id'] = $_POST['userId'];
} else {
$postData = $this->request->data;
}
if( !empty( $postData ) ){
$updatedUser = $this->User->updateUser( array( $postData ) );
$userCount = count( $updatedUser );
if( $userCount > 0 ){
$response = array( 'error' => 0, 'message' => 'User has been updated.', 'data' => array() );
} else {
$response = array( 'error' => 0, 'message' => 'Update Failed.', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function emailVerification() {
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( empty( $postData ) ){
$postData = $this->request->getData();
}
if( !empty( $postData ) ){
$countKeysPassed = 0;
$keyChecks = array( 'email', 'token', 'code' );
foreach( $keyChecks as $key ){
if( isset( $postData[ $key ] ) && !empty( $postData[ $key ] ) ){
$countKeysPassed++;
}
}
if( $countKeysPassed >= 2 ){
$response = $this->User->EmailVerification->verify( $postData );
if( $response['error'] == 0 ){
$res = $this->OAuth->getAccessToken( $response['data'][0] );
$response['data'] = $res['data'];
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function forgotpassword() {
$response = array( 'error' => 1, 'message' => 'Invalid Request' );
$postData = $this->request->input('json_decode', true);
if( empty( $postData ) ){
$postData = $this->request->getData();
}
if( !empty( $postData ) && isset( $postData['email'] ) ){
$users = $this->User->find('all')->where([ 'email' => $postData['email'] ])->toArray();
if( $users ){
$response = $this->User->EmailVerification->add( $users[0]->id );
$baseUrl = Router::fullBaseUrl().'resetpassword?email='.$postData['email'].'&token='.$response->token;
$emailData = array( 'action_url' => $baseUrl, 'code' => $response->code );
$result = $this->_sendMail( array( $postData['email'] ), 'Reset Password', 'forgotPassword', $emailData );
$response = array( 'error' => 0, 'message' => 'Reset Code Sent' );
} else {
$response = array( 'error' => 1, 'message' => 'User Not Found' );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function changeProfilePicture(){
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
if ($this->request->is('post')) {
$userId = null;
if( isset( $_POST['userId'] ) ){
$userId = $_POST['userId'];
}
$userData = array( $userId => array( 'id' => $userId ) );
if( !empty( $this->request->getData('profile') ) ){
$result = $this->Files->saveFile( $this->request->getData('profile') );
if( $result ){
$userData[ $userId ] = array( 'id' => $userId, 'profilepic' => $result['filepath'] );
}
$usersUpdated = $this->User->updateUser( $userData );
if ( !empty( $usersUpdated ) ) {
$response = array( 'error' => 0, 'message' => 'Profile Pic Changed', 'data' => array( 'profilepic' => $userData[ $userId ] ) );
} else {
$response = array( 'error' => 1, 'message' => 'Error', 'data' => array() );
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function follow(){
$response = array( 'error' => 1, 'message' => 'Invalid Request' );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['userId'] = $_POST['userId'];
$postData['accessRoleIds'] = $_POST['accessRoleIds'];
} else {
$postData = $this->request->getData();
}
if( !empty( $postData ) && isset( $postData['mcph'] ) ){
$data = array( 'user_id' => $postData['userId'], 'followuser_id' => $postData['mcph'] );
if( $this->User->UserFollowers->follow( $data ) ){
$response = array( 'error' => 0, 'message' => 'Follow Successful.' );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function unfollow(){
$response = array( 'error' => 1, 'message' => 'Invalid Request' );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['userId'] = $_POST['userId'];
$postData['accessRoleIds'] = $_POST['accessRoleIds'];
} else {
$postData = $this->request->getData();
}
if( !empty( $postData ) && isset( $postData['mcph'] ) ){
$data = array( 'user_id' => $postData['userId'], 'followuser_id' => $postData['mcph'] );
if( $this->User->UserFollowers->unfollow( $data ) ){
$response = array( 'error' => 0, 'message' => 'Follow Successful.' );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function getFollowers(){
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
$jsonData = $this->request->input('json_decode', true);
$getData = $this->request->query();
$postData = $this->request->getData();
$requestData = array_merge( $getData, $postData );
if( $jsonData )
$requestData = array_merge( $requestData, $jsonData );
if( !isset( $requestData['user_id'] ) ){
$requestData['user_id'] = $_POST['userId'];
}
if( !isset( $requestData['mcph'] ) ){
$requestData['mcph'] = $requestData['user_id'];
}
if( !empty( $requestData ) && isset( $requestData['page'] )){
$searchText = null;
if( isset( $requestData['searchKey'] ) ){
$searchText = $requestData['searchKey'];
}
$mcphData = $this->User->UserFollowers->getfollowers( $requestData['mcph'], $searchText )['data'];
$userData = $this->User->UserFollowers->getfollowing( $requestData['user_id'], $searchText )['data'];
$returnData = $this->User->UserFollowers->compareFollowStatus( $userData, $mcphData );
$response = array( 'error' => 0, 'message' => '', 'data' => $returnData );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function getFollowings(){
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
$jsonData = $this->request->input('json_decode', true);
$getData = $this->request->query();
$postData = $this->request->getData();
$requestData = array_merge( $getData, $postData );
if( $jsonData )
$requestData = array_merge( $requestData, $jsonData );
if( !isset( $requestData['user_id'] ) ){
$requestData['user_id'] = $_POST['userId'];
}
if( !isset( $requestData['mcph'] ) ){
$requestData['mcph'] = $requestData['user_id'];
}
if( !empty( $requestData ) && isset( $requestData['page'] ) ){
$searchText = null; $queryConditions = array();
$queryConditions['page'] = $requestData['page'];
if( isset( $requestData['offset'] ) ){
$queryConditions['offset'] = $requestData['offset'];
}
if( isset( $requestData['searchKey'] ) ){
$searchText = $requestData['searchKey'];
}
$mcphData = $this->User->UserFollowers->getfollowing( $requestData['mcph'], $searchText )['data'];
$userData = $this->User->UserFollowers->getfollowing( $requestData['user_id'], $searchText )['data'];
$returnData = $this->User->UserFollowers->compareFollowStatus( $userData, $mcphData );
$response = array( 'error' => 0, 'message' => '', 'data' => $returnData );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/src/Model/Behavior/GenericOpsBehavior.php
<?php
namespace App\Model\Behavior;
use Cake\ORM\Behavior;
use Cake\ORM\Table;
/**
* GenericOps behavior
*/
class GenericOpsBehavior extends Behavior
{
/**
* Default configuration.
*
* @var array
*/
protected $_defaultConfig = [];
function randomAlphanumeric( $minLength = 6 ) {
$alphabet = 'abcdefgh<KEY>';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
}
<file_sep>/db/data/12/alterTableFavLocation.sql
ALTER TABLE `fav_location` CHANGE `department_id` `department_id` INT(11) NOT NULL DEFAULT '0';
<file_sep>/db/schema/wv_polls.sql
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 16, 2018 at 01:42 PM
-- Server version: 10.1.29-MariaDB-6
-- PHP Version: 7.0.29-1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `worldvoting`
--
-- --------------------------------------------------------
--
-- Table structure for table `polls`
--
CREATE TABLE `polls` (
`id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`count` int(11) NOT NULL DEFAULT '0',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `polls`
--
ALTER TABLE `polls`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `polls`
--
ALTER TABLE `polls`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/db/data/10/restructuredActivityLog.sql
DROP TABLE activitylog;
CREATE TABLE `worldvoting`.`activitylog` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`user_id` INT(11) NOT NULL ,
`post_id` INT(11) NOT NULL ,
`upvote` BOOLEAN NOT NULL DEFAULT FALSE ,
`downvote` BOOLEAN NOT NULL DEFAULT FALSE ,
`bookmark` BOOLEAN NOT NULL DEFAULT FALSE ,
`shares` INT(11) NOT NULL DEFAULT 0 ,
`flag` BIT(1) NOT NULL DEFAULT 0 ,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)) ENGINE = InnoDB;
ALTER TABLE `activitylog` ADD `eyewitness` BOOLEAN NOT NULL AFTER `flag`;
ALTER TABLE `activitylog` CHANGE `flag` `flag` BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE `activitylog` ADD UNIQUE `unique_index`(`user_id`, `post_id`);
<file_sep>/db/data/2/alterPostTable.sql
ALTER TABLE `post` CHANGE `ministry_id` `department_id` INT(10) NOT NULL;
ALTER TABLE `post` CHANGE `total_likes` `total_likes` INT(10) NOT NULL DEFAULT '0';
ALTER TABLE `post` CHANGE `total_comments` `total_comments` INT(10) NOT NULL DEFAULT '0';
ALTER TABLE `post` CHANGE `location` `location` VARCHAR(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL;
ALTER TABLE `post` CHANGE `poststatus` `poststatus` TINYINT(1) NOT NULL DEFAULT '1';
ALTER TABLE `post` DROP `type_flag`;
ALTER TABLE `post` CHANGE `details` `details` VARCHAR(512) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL;
<file_sep>/src/Controller/LocalitiesController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Localities Controller
*
* @property \App\Model\Table\LocalitiesTable $Localities
*
* @method \App\Model\Entity\Locality[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class LocalitiesController extends AppController {
public function get(){
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
$getData = $this->request->query();
$userId = null;
if( isset( $_GET['userId'] ) ){
$userId = $_GET['userId'];
}
if( !empty( $getData ) ){
$response['error'] = 0; $response['message'] = '';
if( isset( $getData['level'] ) ){
switch( $getData['level'] ){
case 'locality' :
$localeRes = $this->Localities->findLocality( $getData )['data'];
$areaLevelId = $localeRes['localities'][0]['locality_id'];
$areaRating = $this->Localities->AreaRatings->getRatings( $getData['level'], $areaLevelId, $userId );
$response['data'] = array( 'location' => $localeRes, 'areaRating' => $areaRating );
break;
case 'city' :
$cityRes = $this->Localities->Cities->findCities( $getData )['data'];
$areaLevelId = $cityRes['cities'][0]['city_id'];
$areaRating = $this->Localities->AreaRatings->getRatings( $getData['level'], $areaLevelId, $userId );
$response['data'] = array( 'location' => $cityRes, 'areaRating' => $areaRating );
break;
case 'state' :
$stateRes = $this->Localities->Cities->States->findStates( $getData )['data'];
$areaLevelId = $stateRes['states'][0]['state_id'];
$areaRating = $this->Localities->AreaRatings->getRatings( $getData['level'], $areaLevelId, $userId );
$response['data'] = array( 'location' => $stateRes, 'areaRating' => $areaRating );
break;
case 'country' :
$countryRes = $this->Localities->Cities->States->Countries->findCountry( $getData )['data'];
$areaLevelId = $countryRes['countries'][0]['country_id'];
$areaRating = $this->Localities->AreaRatings->getRatings( $getData['level'], $areaLevelId, $userId );
$response['data'] = array( 'location' => $countryRes, 'areaRating' => $areaRating );
break;
case 'world' :
$areaRating = $this->Localities->AreaRatings->getRatings( $getData['level'], 0, $userId );
$response['data'] = array( 'location' => array(), 'areaRating' => $areaRating );
break;
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/db/schema/wv_area_ratings.sql
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Aug 11, 2018 at 11:25 AM
-- Server version: 10.1.29-MariaDB-6+b1
-- PHP Version: 7.2.4-1+b2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `worldvoting`
--
-- --------------------------------------------------------
--
-- Table structure for table `area_ratings`
--
CREATE TABLE `area_ratings` (
`id` int(11) NOT NULL,
`area_level` enum('world','country','state','city','locality','department') COLLATE utf8_unicode_ci NOT NULL,
`area_level_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`good` tinyint(4) NOT NULL DEFAULT '0',
`bad` tinyint(4) NOT NULL DEFAULT '0',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `area_ratings`
--
ALTER TABLE `area_ratings`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `area_level` (`area_level`,`area_level_id`,`user_id`),
ADD KEY `area_level_id` (`area_level_id`,`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `area_ratings`
--
ALTER TABLE `area_ratings`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/Model/Table/UserFollowersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* UserFollowers Model
*
* @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
* @property \App\Model\Table\FollowusersTable|\Cake\ORM\Association\BelongsTo $Followusers
*
* @method \App\Model\Entity\UserFollower get($primaryKey, $options = [])
* @method \App\Model\Entity\UserFollower newEntity($data = null, array $options = [])
* @method \App\Model\Entity\UserFollower[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\UserFollower|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\UserFollower|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\UserFollower patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\UserFollower[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\UserFollower findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class UserFollowersTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('user_followers');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'followuser_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('User', [
'foreignKey' => 'followuser_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
// $rules->add($rules->existsIn(['user_id'], 'Users'));
// $rules->add($rules->existsIn(['followuser_id'], 'Followusers'));
return $rules;
}
/**
* data['user_id']
* data['followuser_id']
*/
public function follow( $data ){
$return = false;
if( !empty( $data ) && isset( $data['user_id'] ) && isset( $data['followuser_id'] ) ){
$userFollowers = TableRegistry::get('UserFollowers');
$entity = $userFollowers->newEntity();
$entity = $userFollowers->patchEntity( $entity, $data );
$entity = $this->fixEncodings( $entity );
$record = $userFollowers->save( $entity );
if( isset( $record->id ) ){
$return = $record->id;
}
}
return $return;
}
/**
* data['user_id']
* data['followuser_id']
*/
public function unfollow( $data ){
$return = false;
if( !empty( $data ) && isset( $data['user_id'] ) && isset( $data['followuser_id'] ) ){
$userFollowers = TableRegistry::get('UserFollowers');
$entity = $userFollowers->find()->where([ 'user_id' => $data['user_id'], 'followuser_id' => $data['followuser_id'] ] )->toArray();
$entityIds = Hash::extract( $entity, '{n}.id');
$entityIds = $this->decodeHashid( $entityIds );
if( !empty( $entityIds ) ){
$return = $this->deleteAll([ 'id IN' => $entityIds ]);
}
}
return $return;
}
/**
* userId
*/
public function getfollowers( $userId = null, $searchText = null, $queryConditions = array() ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( $userId != null ){
$userFollowers = TableRegistry::get('UserFollowers');
$query = $userFollowers->find()->where([ 'followuser_id' => $userId ] );
if( isset( $queryConditions['page'] ) ){
$query = $query->page( $queryConditions['page'] );
}
if( isset( $queryConditions['offset'] ) ){
$query = $query->limit( $queryConditions['offset'] );
}
$entity = $query->toArray();
$followerIds = Hash::extract( $entity, '{n}.user_id' );
$userData = $this->User->getUserList( $followerIds, array( 'id', 'profilepic', 'firstname', 'lastname', 'about', 'tagline', 'address', 'profession' ) );
if( $searchText != null && strlen( $searchText ) > 0 ){
foreach( $userData as $key => $value ){
if( !(( stripos( $value['firstname'], $searchText ) !== false ) || ( stripos( $value['lastname'], $searchText ) !== false )) ){
unset( $userData[ $key ] );
}
}
}
$response['data'] = array_values( $userData );
}
return $response;
}
/**
* data['user_id']
*/
public function getfollowing( $userId = null, $searchText = null, $queryConditions = array() ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( $userId != null ){
$userFollowers = TableRegistry::get('UserFollowers');
$query = $userFollowers->find()->where([ 'user_id' => $userId ] );
if( isset( $queryConditions['page'] ) ){
$query = $query->page( $queryConditions['page'] );
}
if( isset( $queryConditions['offset'] ) ){
$query = $query->limit( $queryConditions['offset'] );
}
$entity = $query->toArray();
$followingIds = Hash::extract( $entity, '{n}.followuser_id' );
$userData = $this->User->getUserList( $followingIds, array( 'id', 'profilepic', 'firstname', 'lastname', 'about', 'tagline', 'address', 'profession' ) );
if( $searchText != null && strlen( $searchText ) > 0 ){
foreach( $userData as $key => $value ){
if( !(( stripos( $value['firstname'], $searchText ) !== false ) || ( stripos( $value['lastname'], $searchText ) !== false )) ){
unset( $userData[ $key ] );
}
}
}
$response['data'] = array_values( $userData );
}
return $response;
}
/**
*
*/
public function getfollowerCount( $userId = null ){
$response = null;
if( $userId != null ){
$userFollowers = TableRegistry::get('UserFollowers');
$totalFollowers = $userFollowers->find()->where([ 'followuser_id' => $userId ] )->count();
$response = $totalFollowers;
}
return $response;
}
/**
* data['user_id']
*/
public function getfollowingCount( $userId = null ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( $userId != null ){
$userFollowers = TableRegistry::get('UserFollowers');
$totalFollowing = $userFollowers->find()->where([ 'user_id' => $userId ] )->count();
$response = $totalFollowing;
}
return $response;
}
public function compareFollowStatus( $currentUserData = array(), $mcphUserData = array() ){
$returnData = array();
if( !empty( $mcphUserData ) ){
$currentUserIds = Hash::extract( $currentUserData, '{n}.id' );
$mcphUserIds = Hash::extract( $mcphUserData, '{n}.id' );
$currentUserDoesNotFollowIds = array_diff( $mcphUserIds, $currentUserIds );
foreach( $mcphUserData as $mcphUser ){
if( in_array( $mcphUser['id'], $currentUserDoesNotFollowIds ) ){
$mcphUser['follows'] = false;
} else {
$mcphUser['follows'] = true;
}
$returnData[] = $mcphUser;
}
}
return $returnData;
}
}
<file_sep>/db/data/3/alterFavLocationTable.sql
DROP TABLE `fav_location`;
CREATE TABLE `fav_location` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`department_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`locality_id` int(11) NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`modified` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `fav_location` ADD PRIMARY KEY (`id`);
ALTER TABLE `fav_location` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
<file_sep>/tests/TestCase/Model/Behavior/HashIdBehaviorTest.php
<?php
namespace App\Test\TestCase\Model\Behavior;
use App\Model\Behavior\HashIdBehavior;
use Cake\TestSuite\TestCase;
/**
* App\Model\Behavior\HashIdBehavior Test Case
*/
class HashIdBehaviorTest extends TestCase
{
/**
* Test subject
*
* @var \App\Model\Behavior\HashIdBehavior
*/
public $HashId;
/**
* setUp method
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->HashId = new HashIdBehavior();
}
/**
* tearDown method
*
* @return void
*/
public function tearDown()
{
unset($this->HashId);
parent::tearDown();
}
/**
* Test initial setup
*
* @return void
*/
public function testInitialization()
{
$this->markTestIncomplete('Not implemented yet.');
}
}
<file_sep>/src/Controller/CommentsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Utility\Hash;
/**
* Comments Controller
*
* @property \App\Model\Table\CommentsTable $Comments
*
* @method \App\Model\Entity\Comment[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class CommentsController extends AppController
{
/**
* View method
*
* @param string|null $id Comment id.
* @return \Cake\Http\Response|void
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function get($postId = null) {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$postId = $this->request->query('postId');
$parentId = $this->request->query('parentId');
if( !$parentId ){
$parentId = 0;
}
$wvComments = $this->Comments->find('all', [
'limit' => 200,
'fields' => array( 'id', 'user_id', 'post_id', 'text', 'created', 'modified', 'parent_id' ) ])->where([ 'post_id' => $postId, 'parent_id' => $parentId ]);
$fileuploadIds = array(); $userIds = array(); $commentIds = array(); $data = array();
if( !empty( $wvComments ) ){
foreach ( $wvComments as $key => $value ) {
$userIds[] = $value->user_id;
$commentIds[] = $value->id;
}
$userInfos = $this->Comments->User->getUserInfo( $userIds );
$parentCounts = $this->Comments->getReplyCounts( $commentIds );
$parentCounts = Hash::combine( $parentCounts, '{n}.parent_id', '{n}.count' );
foreach ( $wvComments as $key => $value ) {
if( isset( $parentCounts[ $value['id'] ] ) ){
$value['replyCounts'] = $parentCounts[ $value['id'] ];
} else {
$value['replyCounts'] = 0;
}
unset( $userInfos[ $value['user_id'] ]['accessRoles'] );
$value['user'] = $userInfos[ $value['user_id'] ];
unset( $value['user_id'] );
$data[] = $value;
}
$response['data'] = $data;
} else {
$response = array( 'error' => 0, 'message' => 'Invalid Param', 'data' => array() );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function new() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if ( $this->request->is('post') ) {
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
$importantKeys = array( 'post_id', 'user_id', 'text');
$saveData = array(); $continue = false;
foreach ( $importantKeys as $key ) {
if( isset( $postData[ $key ] ) ){
$saveData[ $key ] = $postData[ $key ];
$continue = true;
} else {
$continue = false;
break;
}
}
if( isset( $postData['parent_id'] ) ){
$saveData['parent_id'] = $postData['parent_id'];
}
if ( $continue ){
if ( $this->Comments->newComment( $saveData ) ) {
$response = array( 'error' => 0, 'message' => 'Comment Submitted', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Error', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/src/Model/Table/LocalitiesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* Localities Model
*
* @property \App\Model\Table\CitiesTable|\Cake\ORM\Association\BelongsTo $Cities
*
* @method \App\Model\Entity\Locality get($primaryKey, $options = [])
* @method \App\Model\Entity\Locality newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Locality[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Locality|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Locality|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Locality patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Locality[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Locality findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class LocalitiesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('localities');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', [ 'field' => array( 'city_id' ) ]);
$this->belongsTo('Cities', [
'foreignKey' => 'city_id',
'joinType' => 'INNER'
]);
$this->hasOne('AreaRatings', [
'foreignKey' => 'area_level_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
// ->requirePresence('id', 'create')
->notEmpty('id');
$validator
->scalar('locality')
->maxLength('locality', 100)
->requirePresence('locality', 'create')
->notEmpty('locality');
$validator
->boolean('active')
// ->requirePresence('active', 'create')
->notEmpty('active');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['city_id'], 'Cities'));
return $rules;
}
/*
* data['locality']
* data['city']
* data['latitude']
* data['longitude']
* data['country']
* response => ( 'locality_id', 'city_id', 'state_id', 'country_id' )
*/
public function findLocality( $data ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $data ) && isset( $data['locality'] ) && isset( $data['city'] ) && isset( $data['latitude'] ) && isset( $data['longitude'] ) ){
$localities = $this->find('all')->where([ 'locality LIKE' => '%'.$data['locality'].'%' ])->toArray();
$cityRes = $this->Cities->findCities( $data );
if( empty( $localities ) && !empty( $cityRes['data'] ) ){
unset( $data['city'] );
$data['city_id'] = $cityRes['data']['cities'][0]['city_id'];
$returnId = $this->addLocality( $data );
if ( $returnId != null ){
$response['data'] = $cityRes['data'];
$response['data']['localities'] = array( array( 'locality_id' => $returnId, 'locality_name' => $data['locality'], 'city_id' => $data['city_id'], 'latitude' => $data['latitude'], 'longitude' => $data['longitude'] ) );
} else {
$response['error'] = 1;
}
} else {
$response['data'] = $cityRes['data'];
$response['data']['localities'] = array();
foreach ($localities as $key => $locality) {
$response['data']['localities'][] = array(
'locality_id' => $locality['id'], 'locality_name' => $locality['locality'], 'city_id' => $locality['city_id'],
'latitude' => $locality['latitude'], 'longitude' => $locality['longitude']
);
}
}
} else {
$response['error'] = 1;
}
return $response;
}
/*
* locality_id
* response => ( 'locality', 'city', 'state', 'country' )
*/
public function findLocalityById( $localityIds ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $localityIds ) && isset( $localityIds ) ){
$localities = $this->find('all')->where([ 'id IN' => $localityIds ])->toArray();
$localityData = array();
if( !empty( $localities ) ){
$cityIds = array();
foreach ( $localities as $key => $value ) {
$localityData[] = array( 'locality_id' => $value['id'], 'locality_name' => $value['locality'], 'city_id' => $value->city_id );
$cityIds[] = $value->city_id;
}
$cityRes = $this->Cities->findCitiesById( $cityIds );
$response['data'] = $cityRes['data'];
$response['data']['localities'] = $localityData;
}
} else {
$response['error'] = 1;
}
return $response;
}
/*
* data['locality']
* data['city_id']
* data['latitude']
* data['longitude']
*/
public function addLocality( $data ){
$return = null;
if( !empty( $data ) ){
$locality = TableRegistry::get('Localities');
$entity = $locality->newEntity();
$entity = $locality->patchEntity( $entity, $data );
$record = $locality->save( $entity );
if( $record->id ){
$return = $this->encodeId( $record->id );
}
}
return $return;
}
}
<file_sep>/src/Model/Table/PostTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* Post Model
*
* @property |\Cake\ORM\Association\BelongsTo $Departments
* @property |\Cake\ORM\Association\BelongsTo $Users
* @property |\Cake\ORM\Association\BelongsTo $Countries
* @property |\Cake\ORM\Association\BelongsTo $States
* @property |\Cake\ORM\Association\BelongsTo $Cities
* @property |\Cake\ORM\Association\BelongsTo $Localities
*
* @method \App\Model\Entity\Post get($primaryKey, $options = [])
* @method \App\Model\Entity\Post newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Post[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Post|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Post|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Post patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Post[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Post findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class PostTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('post');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('ArrayOps');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'city_id', 'department_id', 'locality_id', 'country_id', 'state_id', 'locality_id' ) ]);
$this->belongsTo('Departments', [
'foreignKey' => 'department_id',
'joinType' => 'INNER'
]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Countries', [
'foreignKey' => 'country_id',
'joinType' => 'INNER'
]);
$this->belongsTo('States', [
'foreignKey' => 'state_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Cities', [
'foreignKey' => 'city_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Localities', [
'foreignKey' => 'locality_id',
'joinType' => 'INNER'
]);
$this->hasOne('Activitylog');
$this->hasOne('Polls');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->integer('user_id')
->notEmpty('user_id');
$validator
->integer('total_upvotes');
$validator
->integer('total_score');
$validator
->scalar('title')
->maxLength('title', 100)
->requirePresence('title', 'create')
->notEmpty('title');
$validator
->scalar('details')
// ->maxLength('details', 512)
->requirePresence('details', 'create')
->notEmpty('details');
$validator
->scalar('filejson')
->maxLength('filejson', 512)
->requirePresence('filejson', 'create')
->notEmpty('filejson');
$validator
->boolean('poststatus')
->notEmpty('poststatus');
$validator
->scalar('latitude')
->maxLength('latitude', 100)
->requirePresence('latitude', 'create')
->notEmpty('latitude');
$validator
->scalar('longitude')
->maxLength('longitude', 100)
->requirePresence('longitude', 'create')
->notEmpty('longitude');
$validator
->scalar('post_type')
->requirePresence('post_type', 'create')
->notEmpty('post_type');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
// $rules->add($rules->existsIn(['department_id'], 'Departments'));
// $rules->add($rules->existsIn(['user_id'], 'User'));
// $rules->add($rules->existsIn(['country_id'], 'Countries'));
// $rules->add($rules->existsIn(['state_id'], 'States'));
// $rules->add($rules->existsIn(['city_id'], 'Cities'));
// $rules->add($rules->existsIn(['locality_id'], 'Localities'));
return $rules;
}
public function savePost( $postData = array() ){
$return = false;
if( !empty( $postData ) ){
$post = TableRegistry::get('Post');
$entity = $post->newEntity();
$entity = $post->patchEntity( $entity, $postData );
$entity = $this->fixEncodings( $entity );
$record = $post->save( $entity );
if( isset( $record->id ) ){
$return = $record->id;
}
}
return $return;
}
public function allowAdmin( $wvPost, $accessRoleIds = array() ){
$return = false;
if( !empty( $wvPost ) ){
$locationTag = array( 'city_id' => array(), 'state_id' => array(), 'country_id' => array());
$localityCityMap = array(); $accessRoleArr = array();
if( $wvPost->locality_id != null ){
$localityRes = $this->Localities->findLocalityById( array( $wvPost->locality_id ) );
if( !empty( $localityRes['data']['cities'] )){
$localityCityMap = Hash::combine( $localityRes['data']['localities'], '{n}.locality_id', '{n}.city_id' );
$cityIds = Hash::extract( $localityRes['data']['cities'], '{n}.city_id' );
$locationTag['city_id'] = array_merge( $cityIds, $locationTag['city_id'] );
}
} else if( $wvPost->city_id != null ){
$locationTag['city_id'][] = $wvPost->city_id;
} else if( $wvPost->state_id != null ){
$locationTag['state_id'][] = $wvPost->state_id;
} else if( $wvPost->country_id != null ){
$locationTag['country_id'][] = $wvPost->country_id;
}
if( !empty( $locationTag['city_id'] ) || !empty( $locationTag['state_id'] ) || !empty( $locationTag['country_id'] ) ){
$accessData = $this->User->AccessRoles->retrieveAccessRoleIds( $locationTag );
$accessRoleArr = Hash::extract( $accessData, '{n}.id' );
// $accessData = $this->array_group_by( $accessData, 'area_level', 'area_level_id');
}
$allowedAccessRoles = array_intersect( $accessRoleArr, (array) $accessRoleIds );
if( !empty( $allowedAccessRoles ) ){
$return = true;
}
}
return $return;
}
public function retrievePostDetailed( $wvPost, $userId = null, $accessRoleIds = array() ){
$fileuploadIds = array(); $userIds = array(); $postIds = array();
$localityIds = array(); $localityCityMap = array();
$data = array();
if( !empty( $wvPost ) ){
$locationTag = array( 'city_id' => array(), 'state_id' => array(), 'country_id' => array());
foreach ( $wvPost as $key => $value ) {
$fileuploadIds = array_merge( $fileuploadIds, json_decode( $value['filejson'] ) );
$userIds[] = $value->user_id;
$postIds[] = $value->id;
if( $value->locality_id != null )
$localityIds[] = $value->locality_id;
if( $value->city_id != null )
$locationTag['city_id'][] = $value->city_id;
if( $value->state_id != null )
$locationTag['state_id'][] = $value->state_id;
if( $value->country_id != null )
$locationTag['country_id'][] = $value->country_id;
}
$this->Fileuploads = TableRegistry::get('Fileuploads');
$fileResponse = $this->Fileuploads->getfileurls( $fileuploadIds );
$userInfos = $this->User->getUserList( $userIds );
$postProperties = $this->Activitylog->getCumulativeResult( $postIds, $userId );
$postPolls = $this->Polls->getPolls( $postIds, $userId );
if( !empty( $localityIds ) ){
$localityRes = $this->Localities->findLocalityById( $localityIds );
if( !empty( $localityRes['data']['cities'] )){
$localityCityMap = Hash::combine( $localityRes['data']['localities'], '{n}.locality_id', '{n}.city_id' );
$cityIds = Hash::extract( $localityRes['data']['cities'], '{n}.city_id' );
$locationTag['city_id'] = array_merge( $cityIds, $locationTag['city_id'] );
}
}
if( !empty( $locationTag['city_id'] ) || !empty( $locationTag['state_id'] ) || !empty( $locationTag['country_id'] ) ){
$locationTag['city_id'] = array_unique( $locationTag['city_id'] );
$locationTag['state_id'] = array_unique( $locationTag['state_id'] );
$locationTag['country_id'] = array_unique( $locationTag['country_id'] );
$accessData = $this->User->AccessRoles->retrieveAccessRoleIds( $locationTag );
$accessData = $this->array_group_by( $accessData, 'area_level', 'area_level_id');
}
foreach ( $wvPost as $key => $value ) {
if( $value['user_id'] == null ){
continue;
}
$accessRoleId = 0; $accessRoleArr = array();
if( $value->locality_id != null ){
$cityId = $localityCityMap[ $value->locality_id ];
$accessRoleArr = $accessData['city'][ $cityId ];
} else if( $value->city_id != null ){
$accessRoleArr = $accessData['city'][ $value->city_id ];
} else if( $value->state_id != null ){
$accessRoleArr = $accessData['state'][ $value->state_id ];
} else if( $value->country_id != null ){
$accessRoleArr = $accessData['country'][ $value->country_id ];
}
$permission = array( 'userEnablePole' => false, 'adminEnableAccept' => false );
foreach( $accessRoleArr as $accessRole ){
if( $accessRole['id'] != null && in_array( $accessRole['id'], (array) $accessRoleIds ) ){
if( $accessRole['access_level'] >= 1 ){
$permission['userEnablePole'] = 1;
}
if( $accessRole['access_level'] == 2 ){
$permission['adminEnableAccept'] = 1;
break;
}
}
}
if( !empty( $fileResponse['data'] ) ){
$fileJSON = json_decode( $value->filejson );
$value['files'] = array( 'images' => array(), 'attachments' => array() );
foreach( $fileJSON as $key => $id ){
if( isset( $fileResponse['data'][ $id ] ) ){
if( strpos( $fileResponse['data'][ $id ]['filetype'], 'image' ) !== false ){
$value['files']['images'][] = $fileResponse['data'][ $id ];
} else {
$value['files']['attachments'][] = $fileResponse['data'][ $id ];
}
}
}
}
$value['props'] = array(); $value['polls'] = array();
if( isset( $postProperties[ $value['id'] ] ) ){
$value['props'] = $postProperties[ $value['id'] ];
}
if( isset( $postPolls[ $value['id'] ] ) ){
$value['polls'] = $postPolls[ $value['id'] ];
}
$value['permissions'] = $permission;
unset( $value['filejson'] );
$value['user'] = $userInfos[ $value['user_id'] ];
unset( $value['user_id'] );
$data[] = $value;
}
}
return $data;
}
public function changeUpvotes( $postId = null, $change = null ){
$response = false;
if( $postId != null && $change != null ){
$post = TableRegistry::get('Post');
$entity = $post->get( $postId );
$entity->total_upvotes = $entity->total_upvotes + $change;
if( $post->save( $entity ) ){
$response = true;
}
}
return $response;
}
public function getUserPostCount( $userId = null, $queryConditions = array() ){
$response = null;
if( $userId != null ){
$post = TableRegistry::get('Post');
$conditions = array( 'user_id' => $userId );
$query = $post->find();
if( !empty( $queryConditions ) ){
if( $queryConditions['poststatus'] == 0 ){
$conditions[] = array( 'poststatus' => 0 );
} else {
$conditions[] = array( 'poststatus' => 1 );
}
}
$query = $query->where( $conditions );
$totalPosts = $query->count();
$response = $totalPosts;
}
return $response;
}
}
<file_sep>/db/data/7/alterLocalitiesTable.sql
ALTER TABLE `localities` ADD PRIMARY KEY(`id`);
ALTER TABLE `localities` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
<file_sep>/src/Model/Table/FileuploadsTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* Fileuploads Model
*
* @method \App\Model\Entity\Fileupload get($primaryKey, $options = [])
* @method \App\Model\Entity\Fileupload newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Fileupload[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Fileupload|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Fileupload|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Fileupload patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Fileupload[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Fileupload findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class FileuploadsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('fileuploads');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('filepath')
->maxLength('filepath', 256)
->requirePresence('filepath', 'create')
->notEmpty('filepath');
$validator
->scalar('filetype')
->maxLength('filetype', 256)
->requirePresence('filetype', 'create')
->notEmpty('filetype');
return $validator;
}
public function saveFiles( $fileData = array() ){
$return = null;
if( !empty( $fileData ) ){
$wvFileUploads = TableRegistry::get('Fileuploads');
$wvFile = $wvFileUploads->newEntity();
$wvFile = $wvFileUploads->patchEntity( $wvFile, $fileData[0] );
$result = $wvFileUploads->save( $wvFile );
$result = $this->encodeResultSet( $result );
if ( isset( $result->id ) ) {
$return = $result->id;
}
}
return $return;
}
public function getfileurls( $fileUploadIds = array() ){
$response = array( 'error' => 0, 'data' => array() );
if( !empty( $fileUploadIds ) ){
$data = array();
$wvFiles = $this->find( 'all', [
'fields' => [ 'id', 'filepath', 'filetype' ]
])->where([ 'id IN' => $fileUploadIds ])->toArray();
foreach ( $wvFiles as $key => $file ) {
$data[ $file->id ] = array( 'filepath' => $file->filepath, 'filetype' => $file->filetype );
}
$response['data'] = $data;
}
return $response;
}
}
<file_sep>/src/Model/Table/UserTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* User Model
*
* @property |\Cake\ORM\Association\BelongsTo $Departments
* @property |\Cake\ORM\Association\BelongsTo $Countries
* @property |\Cake\ORM\Association\BelongsTo $States
* @property |\Cake\ORM\Association\BelongsTo $Cities
*
* @method \App\Model\Entity\User get($primaryKey, $options = [])
* @method \App\Model\Entity\User newEntity($data = null, array $options = [])
* @method \App\Model\Entity\User[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\User|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\User patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\User[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\User findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class UserTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('user');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', [ 'field' => array( 'default_location_id', 'department_id', 'country_id', 'state_id', 'city_id' ) ]);
$this->belongsTo('AccessRoles', [
'foreignKey' => 'access_role_ids',
'joinType' => 'INNER'
]);
$this->belongsTo('Departments', [
'foreignKey' => 'department_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Countries', [
'foreignKey' => 'country_id',
'joinType' => 'INNER'
]);
$this->belongsTo('States', [
'foreignKey' => 'state_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Cities', [
'foreignKey' => 'city_id',
'joinType' => 'INNER'
]);
$this->belongsTo('FavLocation', [
'foreignKey' => 'default_location_id',
'joinType' => 'INNER'
]);
$this->hasOne('LoginRecord');
$this->hasOne('EmailVerification');
$this->hasOne('Post');
$this->hasMany('UserFollowers');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('firstname')
->maxLength('firstname', 256)
->requirePresence('firstname', 'create')
->notEmpty('firstname');
$validator
->scalar('lastname')
->maxLength('lastname', 256)
->requirePresence('lastname', 'create')
->notEmpty('lastname');
$validator
->scalar('gender')
->maxLength('gender', 20)
->allowEmpty('gender');
$validator
->email('email')
->requirePresence('email', 'create')
->notEmpty('email')
->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
$validator
->scalar('password')
->maxLength('password', 256)
->requirePresence('password', 'create')
->notEmpty('password');
$validator
->scalar('phone')
->maxLength('phone', 256)
->allowEmpty('phone');
$validator
->scalar('address')
->maxLength('address', 256)
->allowEmpty('address');
$validator
->scalar('latitude')
->maxLength('latitude', 256)
->allowEmpty('latitude');
$validator
->scalar('longitude')
->maxLength('longitude', 256)
->allowEmpty('longitude');
$validator
->scalar('profilepic')
->maxLength('profilepic', 256)
->allowEmpty('profilepic');
$validator
->boolean('status')
// ->requirePresence('status', 'create')
->notEmpty('status');
$validator
->boolean('active')
// ->requirePresence('active', 'create')
->notEmpty('active');
$validator
->boolean('email_verified')
// ->requirePresence('email_verified', 'create')
->notEmpty('email_verified');
$validator
->integer('adhar_verified')
// ->requirePresence('adhar_verified', 'create')
->notEmpty('adhar_verified');
$validator
// ->requirePresence('authority_flag', 'create')
->notEmpty('authority_flag');
$validator
->scalar('access_role_ids')
->maxLength('access_role_ids', 1024)
// ->requirePresence('access_role_ids', 'create')
->notEmpty('access_role_ids');
$validator
->scalar('rwa_name')
->maxLength('rwa_name', 1024)
->allowEmpty('rwa_name');
$validator
->scalar('designation')
->maxLength('designation', 512)
// ->requirePresence('designation', 'create')
->notEmpty('designation');
$validator
->scalar('certificate')
->maxLength('certificate', 512)
// ->requirePresence('certificate', 'create')
->notEmpty('certificate');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
$rules->add($rules->existsIn(['department_id'], 'Departments'));
$rules->add($rules->existsIn(['country_id'], 'Countries'));
$rules->add($rules->existsIn(['state_id'], 'States'));
$rules->add($rules->existsIn(['city_id'], 'Cities'));
return $rules;
}
public function add( $userData = array() ){
$response = false;
if( !empty( $userData ) ){
if( isset( $userData['password'] ) ){
$users = TableRegistry::get('User');
$entity = $users->newEntity();
$entity = $users->patchEntity( $entity, $userData );
$record = $users->save( $entity );
if( isset( $record->id ) ){
$response = $record->id;
}
}
}
return $response;
}
public function checkPassword( $password, $storedPassword ){
$users = TableRegistry::get('User');
$entity = $users->newEntity();
$response = $entity->_checkPassword( $password, $storedPassword );
return $response;
}
public function getUserInfo( $userIds = array() ){
$response = array();
if( !empty( $userIds ) ){
$users = $this->find()->where([ 'id IN' => $userIds, 'status' => 1 ])->toArray();
foreach( $users as $index => $user ){
$tmpResponse = $user;
if( isset( $user['firstname'] ) && isset( $user['lastname'] ) ){
$tmpResponse['name'] = $user['firstname'].' '.$user['lastname'];
}
$tmpResponse[ 'profilepic' ] = ( !isset( $tmpResponse[ 'profilepic' ] ) or $tmpResponse[ 'profilepic' ] == null or $tmpResponse[ 'profilepic' ] == '' ) ? 'webroot' . DS . 'img' . DS . 'assets' . DS . 'profile-pic.png' : $tmpResponse[ 'profilepic' ];
if( isset( $user['access_role_ids'] ) ){
$accessRoles = $this->AccessRoles->getAccessData( json_decode( $user['access_role_ids'] ) );
$tmpResponse[ 'accessRoles' ] = $accessRoles;
unset( $tmpResponse['access_role_ids'] );
}
$tmpResponse['postCount'] = $this->Post->getUserPostCount( $user['id'] );
$tmpResponse['draftCount'] = $this->Post->getUserPostCount( $user['id'], array( 'poststatus' => 0 ) );
$tmpResponse['bookmarkCount'] = $this->Post->Activitylog->getBookMarkCount( $user['id'] );
$tmpResponse['followingCount'] = $this->UserFollowers->getfollowingCount( $user['id'] );
$tmpResponse['followerCount'] = $this->UserFollowers->getfollowerCount( $user['id'] );
$response[ $user->id ] = $tmpResponse;
}
}
return $response;
}
public function getUserList( $userIds = array(), $userKeys = array( 'id', 'profilepic', 'firstname', 'lastname' ) ){
$response = array();
if( !empty( $userIds ) ){
$professionFlag = false;
/*Just Dummy Key, remove as soon as possible*/
if( in_array( 'profession', $userKeys ) ){
$professionFlag = true;
$index = array_search( 'profession', $userKeys );
unset( $userKeys[ $index ] );
}
$users = $this->find('all')->select( $userKeys )->where([ 'id IN' => $userIds, 'status' => 1 ])->toArray();
foreach( $users as $index => $user ){
$tmpResponse = array();
if( isset( $user['firstname'] ) && isset( $user['lastname'] ) ){
$tmpResponse['name'] = $user['firstname'].' '.$user['lastname'];
}
foreach( $userKeys as $stringKey ){
if( $stringKey == 'profilepic' )
$tmpResponse[ 'profilepic' ] = ( $user[ 'profilepic' ] == null or $user[ 'profilepic' ] == '' ) ? 'webroot' . DS . 'img' . DS . 'assets' . DS . 'profile-pic.png' : $user[ 'profilepic' ];
else
$tmpResponse[ $stringKey ] = $user[ $stringKey ];
}
/*Just Dummy Key, remove as soon as possible*/
if( $professionFlag ){
$tmpResponse[ 'profession' ] = '';
}
$response[ $user->id ] = $tmpResponse;
}
}
return $response;
}
public function updateUser( $userDatas ){
$response = array();
if( !empty( $userDatas ) ){
$users = TableRegistry::get('User');
foreach( $userDatas as $user ){
$entity = $users->get( $user['id'] );
foreach( $user as $key => $value ){
if( $key != 'id' ){
if( $key != 'date_of_birth' ){
$entity->{$key} = $value;
} else {
$entity->{$key} = time( strtotime( $value ) );
}
}
}
$entity = $this->fixEncodings( $entity );
if( $users->save( $entity ) ){
$response[] = $user['id'];
}
}
}
return $response;
}
public function checkEmailExist( $email = null ){
$return = false;
if( $email != null ){
$user = TableRegistry::get('User');
$return = $user->exists( [ 'email' => $email ] );
return $return;
}
return $return;
}
}
<file_sep>/src/Controller/AppController.php
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.2.9
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Mailer\Email;
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @link https://book.cakephp.org/3.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller
{
/**
* Initialization hook method.
* @return void
*/
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
//$this->loadComponent('Security');
//$this->loadComponent('Csrf');
}
function _sendMail( $to, $subject, $template, $data = array() ) {
$this->Email = new Email();
$this->Email->setTransport('ssl');
$result = $this->Email->setTo( $to )
->setSubject( $subject )
->setViewVars( $data )
->setTemplate( $template )
->setEmailFormat( 'html' ) //Send as 'html', 'text' or 'both' (default is 'text')
->send();
if( isset( $result['headers'] ) ){
return true;
}
return false;
// $this->Email->bcc = array('<EMAIL>'); // copies
// $this->Email->replyTo = '<EMAIL>';
}
}
<file_sep>/src/Model/Table/FavLocationTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* FavLocation Model
*
* @property |\Cake\ORM\Association\BelongsTo $User
* @property |\Cake\ORM\Association\BelongsTo $Departments
* @property |\Cake\ORM\Association\BelongsTo $Countries
* @property |\Cake\ORM\Association\BelongsTo $States
* @property |\Cake\ORM\Association\BelongsTo $Cities
* @property |\Cake\ORM\Association\BelongsTo $Localities
*
* @method \App\Model\Entity\FavLocation get($primaryKey, $options = [])
* @method \App\Model\Entity\FavLocation newEntity($data = null, array $options = [])
* @method \App\Model\Entity\FavLocation[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\FavLocation|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\FavLocation|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\FavLocation patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\FavLocation[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\FavLocation findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class FavLocationTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('fav_location');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'city_id', 'department_id', 'locality_id', 'country_id', 'state_id', 'locality_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Departments', [
'foreignKey' => 'department_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Countries', [
'foreignKey' => 'country_id',
'joinType' => 'INNER'
]);
$this->belongsTo('States', [
'foreignKey' => 'state_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Cities', [
'foreignKey' => 'city_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Localities', [
'foreignKey' => 'locality_id',
'joinType' => 'INNER'
]);
$this->hasOne('User');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
// $rules->add($rules->existsIn(['user_id'], 'User'));
// $rules->add($rules->existsIn(['department_id'], 'Departments'));
// $rules->add($rules->existsIn(['country_id'], 'Countries'));
// $rules->add($rules->existsIn(['state_id'], 'States'));
// $rules->add($rules->existsIn(['city_id'], 'Cities'));
// $rules->add($rules->existsIn(['locality_id'], 'Localities'));
return $rules;
}
public function add( $postData ){
$return = false;
if( !empty( $postData ) ){
$favLocal = TableRegistry::get('FavLocation');
$entity = $favLocal->newEntity();
$entity = $favLocal->patchEntity( $entity, $postData );
$record = $favLocal->save( $entity );
$record = $this->encodeResultSet( $record );
return $record;
}
return $return;
}
public function traverseAndMatch( $data, $key, $value ){
$return = array();
foreach ( $data as $index => $singleton ) {
if( isset( $singleton[ $key ] ) && $singleton[ $key ] == $value ){
$return = $singleton;
break;
}
}
return $return;
}
public function buildDataForSearch( $wvFavLocations, $user = array() ){
$search = array( 'localityIds' => array(), 'cityIds' => array(), 'stateIds' => array(), 'countryIds' => array() );
if( !empty( $wvFavLocations ) ){
foreach ( $wvFavLocations as $key => $favLoc ) {
$isDefault = false;
if( !empty( $user ) && $user['default_location_id'] == $favLoc->id ){
$isDefault = true;
}
if( $favLoc->level == 'locality' ){
$search['localityIds'][ $favLoc->locality_id ] = array(
'locality_id' => $favLoc->locality_id, 'latitude' => $favLoc->latitude, 'longitude' => $favLoc->longitude,
'level' => $favLoc->level, 'is_default' => $isDefault, 'id' => $favLoc->id
);
} else if( $favLoc->level == 'city' ){
$search['cityIds'][ $favLoc->city_id ] = array(
'city_id' => $favLoc->city_id, 'latitude' => $favLoc->latitude, 'longitude' => $favLoc->longitude,
'level' => $favLoc->level, 'is_default' => $isDefault, 'id' => $favLoc->id
);
} else if( $favLoc->level == 'state' ){
$search['stateIds'][ $favLoc->state_id ] = array(
'state_id' => $favLoc->state_id, 'latitude' => $favLoc->latitude, 'longitude' => $favLoc->longitude,
'level' => $favLoc->level, 'is_default' => $isDefault, 'id' => $favLoc->id
);
} else if( $favLoc->level == 'country' ){
$search['countryIds'][ $favLoc->country_id ] = array(
'country_id' => $favLoc->country_id, 'latitude' => $favLoc->latitude, 'longitude' => $favLoc->longitude,
'level' => $favLoc->level, 'is_default' => $isDefault, 'id' => $favLoc->id
);
}
}
}
return $search;
}
public function retrieveAddresses( $search ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $search ) ){
$data = array();
if( !empty( $search['localityIds'] ) ){
$tmpArray = array_values( $search['localityIds'] );
$localityIds = Hash::extract( $tmpArray, '{n}.locality_id' );
$localityRes = $this->Localities->findLocalityById( $localityIds );
if( $localityRes['error'] == 0 ){
foreach ( $localityRes['data']['localities'] as $key => $locale ) {
$localityId = $locale['locality_id'];
$city = $this->traverseAndMatch( $localityRes['data']['cities'], 'city_id', $locale['city_id'] );
$state = $this->traverseAndMatch( $localityRes['data']['states'], 'state_id', $city['state_id'] );
$country = $this->traverseAndMatch( $localityRes['data']['countries'], 'country_id', $state['country_id'] );
$address = $locale['locality_name'].', '.$city['city_name'].', '.$state['state_name'].', '.$country['country_name'];
$data[] = array( 'address_string' => $address,
'favlocation_id' => $search['localityIds'][ $localityId ]['id'],
'latitude' => $search['localityIds'][ $localityId ]['latitude'],
'longitude' => $search['localityIds'][ $localityId ]['longitude'],
'level' => $search['localityIds'][ $localityId ]['level'],
'default' => $search['localityIds'][ $localityId ]['is_default'] );
}
}
}
if( !empty( $search['cityIds'] ) ){
$tmpArray = array_values( $search['cityIds'] );
$cityIds = Hash::extract( $tmpArray, '{n}.city_id' );
$cityRes = $this->Cities->findCitiesById( $cityIds );
if( $cityRes['error'] == 0 ){
foreach ( $cityRes['data']['cities'] as $key => $city ) {
$cityId = $city['city_id'];
$state = $this->traverseAndMatch( $cityRes['data']['states'], 'state_id', $city['state_id'] );
$country = $this->traverseAndMatch( $cityRes['data']['countries'], 'country_id', $state['country_id'] );
$address = $city['city_name'].', '.$state['state_name'].', '.$country['country_name'];
$data[] = array( 'address_string' => $address,
'favlocation_id' => $search['cityIds'][ $cityId ]['id'],
'latitude' => $search['cityIds'][ $cityId ]['latitude'],
'longitude' => $search['cityIds'][ $cityId ]['longitude'],
'level' => $search['cityIds'][ $cityId ]['level'],
'default' => $search['cityIds'][ $cityId ]['is_default'] );
}
}
}
if( !empty( $search['stateIds'] ) ){
$tmpArray = array_values( $search['stateIds'] );
$stateIds = Hash::extract( $tmpArray, '{n}.state_id' );
$stateRes = $this->States->findStateById( $stateIds );
if( $stateRes['error'] == 0 ){
foreach ( $stateRes['data']['states'] as $key => $state ) {
$stateId = $state['state_id'];
$country = $this->traverseAndMatch( $stateRes['data']['countries'], 'country_id', $state['country_id'] );
$address = $state['state_name'].', '.$country['country_name'];
$data[] = array( 'address_string' => $address,
'favlocation_id' => $search['stateIds'][ $stateId ]['id'],
'latitude' => $search['stateIds'][ $stateId ]['latitude'],
'longitude' => $search['stateIds'][ $stateId ]['longitude'],
'level' => $search['stateIds'][ $stateId ]['level'],
'default' => $search['stateIds'][ $stateId ]['is_default'] );
}
}
}
if( !empty( $search['countryIds'] ) ){
$tmpArray = array_values( $search['countryIds'] );
$countryIds = Hash::extract( $tmpArray, '{n}.country_id' );
$countryRes = $this->Countries->findCountryById( $countryIds );
if( !empty( $countryRes['data'] ) ){
foreach ( $countryRes['data']['countries'] as $key => $country ) {
$countryId = $country['country_id'];
$address = $country['country_name'];
$data[] = array( 'address_string' => $address,
'favlocation_id' => $search['countryIds'][ $countryId ]['id'],
'latitude' => $search['countryIds'][ $countryId ]['latitude'],
'longitude' => $search['countryIds'][ $countryId ]['longitude'],
'level' => $search['countryIds'][ $countryId ]['level'],
'default' => $search['countryIds'][ $countryId ]['is_default'] );
}
}
}
$response['data'] = $data;
}
return $response;
}
public function remove( $conditions ){
$ret = false;
if( !empty( $conditions ) ){
$favLoc = $this->find( 'all', [
'fields' => [ 'id' ]
])->where( $conditions )->toArray();
$favLocIds = Hash::extract( $favLoc, '{n}.id');
$favLocIds = $this->decodeHashid( $favLocIds );
if( !empty( $favLocIds ) ){
$ret = $this->deleteAll([ 'id IN' => $favLocIds ]);
}
}
return $ret;
}
public function exist( $conditions ){
$ret = false;
if( !empty( $conditions ) ){
$favLocT = TableRegistry::get('FavLocation');
return $favLocT->exists( $conditions );
}
return $ret;
}
}
<file_sep>/tests/Fixture/UserFixture.php
<?php
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
/**
* UserFixture
*
*/
class UserFixture extends TestFixture
{
/**
* Table name
*
* @var string
*/
public $table = 'user';
/**
* Fields
*
* @var array
*/
// @codingStandardsIgnoreStart
public $fields = [
'id' => ['type' => 'integer', 'length' => 10, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
'firstname' => ['type' => 'string', 'length' => 256, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'lastname' => ['type' => 'string', 'length' => 256, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'gender' => ['type' => 'string', 'length' => 20, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'email' => ['type' => 'string', 'length' => 256, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'password' => ['type' => 'string', 'length' => 256, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'phone' => ['type' => 'string', 'length' => 256, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'address' => ['type' => 'string', 'length' => 256, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'latitude' => ['type' => 'string', 'length' => 256, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'longitude' => ['type' => 'string', 'length' => 256, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'profilepic' => ['type' => 'string', 'length' => 256, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'status' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => '1', 'comment' => '', 'precision' => null],
'active' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null],
'email_verified' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null],
'adhar_verified' => ['type' => 'integer', 'length' => 10, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'authority_flag' => ['type' => 'tinyinteger', 'length' => 4, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '0 - Normal User, 1 - Authority ', 'precision' => null],
'access_role_ids' => ['type' => 'string', 'length' => 1024, 'null' => false, 'default' => '[]', 'collate' => 'latin1_swedish_ci', 'comment' => 'Will contain all types of access roles for write and answer in JSON Array', 'precision' => null, 'fixed' => null],
'rwa_name' => ['type' => 'string', 'length' => 1024, 'null' => true, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'department_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'designation' => ['type' => 'string', 'length' => 512, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'certificate' => ['type' => 'string', 'length' => 512, 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
'country_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'state_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'city_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => 'current_timestamp()', 'comment' => '', 'precision' => null],
'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => 'current_timestamp()', 'comment' => '', 'precision' => null],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
'email' => ['type' => 'unique', 'columns' => ['email'], 'length' => []],
],
'_options' => [
'engine' => 'InnoDB',
'collation' => 'latin1_swedish_ci'
],
];
// @codingStandardsIgnoreEnd
/**
* Init method
*
* @return void
*/
public function init()
{
$this->records = [
[
'id' => 1,
'firstname' => '<NAME>',
'lastname' => '<NAME>',
'gender' => 'Lorem ipsum dolor ',
'email' => 'Lorem ipsum dolor sit amet',
'password' => '<NAME>',
'phone' => 'Lorem ipsum dolor sit amet',
'address' => 'Lorem ipsum dolor sit amet',
'latitude' => 'Lorem ipsum dolor sit amet',
'longitude' => 'Lorem ipsum dolor sit amet',
'profilepic' => 'Lorem ipsum dolor sit amet',
'status' => 1,
'active' => 1,
'email_verified' => 1,
'adhar_verified' => 1,
'authority_flag' => 1,
'access_role_ids' => 'Lorem ipsum dolor sit amet',
'rwa_name' => '<NAME>',
'department_id' => 1,
'designation' => 'Lorem ipsum dolor sit amet',
'certificate' => 'Lorem ipsum dolor sit amet',
'country_id' => 1,
'state_id' => 1,
'city_id' => 1,
'created' => '2018-05-24 11:23:51',
'modified' => '2018-05-24 11:23:51'
],
];
parent::init();
}
}
<file_sep>/src/Controller/PostController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* Post Controller
*
* @property \App\Model\Table\PostTable $Post
*
* @method \App\Model\Entity\Post[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class PostController extends AppController
{
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if ( $this->request->is('post') ) {
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['userId'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
$saveData = array(); $continue = false;
$addressString = '';
if( isset( $postData['level'] ) ){
switch( $postData['level'] ){
case 'locality' :
$localeRes = $this->Post->Localities->findLocality( $postData )['data'];
if( !empty( $localeRes['localities'] ) ){
$saveData['locality_id'] = $localeRes['localities'][0]['locality_id'];
$addressString = $localeRes['localities'][0]['locality_name'].', '.$localeRes['cities'][0]['city_name'].', '.$localeRes['states'][0]['state_name'].', '.$localeRes['countries'][0]['country_name'];
$continue = true;
}
break;
case 'city' :
$cityRes = $this->Post->Cities->findCities( $postData )['data'];
if( !empty( $cityRes['cities'] ) ){
$saveData['city_id'] = $cityRes['cities'][0]['city_id'];
$addressString = $cityRes['cities'][0]['city_name'].', '.$cityRes['states'][0]['state_name'].', '.$cityRes['countries'][0]['country_name'];
$continue = true;
}
break;
case 'state' :
$stateRes = $this->Post->States->findStates( $postData )['data'];
if( !empty( $stateRes['states'] ) ){
$saveData['state_id'] = $stateRes['states'][0]['state_id'];
$addressString = $stateRes['states'][0]['state_name'].', '.$stateRes['countries'][0]['country_name'];
$continue = true;
}
break;
case 'country' :
$countryRes = $this->Post->Countries->findCountry( $postData )['data'];
if( !empty( $countryRes['countries'] ) ){
$saveData['country_id'] = $countryRes['countries'][0]['country_id'];
$addressString = $countryRes['countries'][0]['country_name'];
$continue = true;
}
break;
case 'department' :
if( isset( $postData['department_id'] ) && $postData['department_id'] != null ){
$saveData['department_id'] = $postData['department_id'];
$continue = true;
}
break;
}
}
$saveData['location'] = $addressString;
if( isset( $postData[ 'title' ] ) && !empty( $postData[ 'title' ] ) ){
$saveData[ 'title' ] = $postData[ 'title' ];
} else {
$continue = false;
}
if( isset( $postData[ 'userId' ] ) && !empty( $postData[ 'userId' ] ) ){
$saveData[ 'user_id' ] = $postData[ 'userId' ];
$tmp = $this->Post->User->LoginRecord->getLastLogin( $postData[ 'userId' ] );
$saveData[ 'latitude' ] = $tmp[ 'latitude' ];
$saveData[ 'longitude' ] = $tmp[ 'longitude' ];
} else {
$continue = false;
}
if( isset( $postData[ 'details' ] ) && !empty( $postData[ 'details' ] ) ){
$saveData[ 'details' ] = $postData[ 'details' ];
}
if( isset( $postData[ 'postType' ] ) && !empty( $postData[ 'postType' ] ) ){
$saveData[ 'post_type' ] = $postData[ 'postType' ];
if( $postData[ 'postType' ] == 'court' && !isset( $postData['polls'] ) ){
$continue = false;
}
}
$saveData[ 'filejson' ] = json_encode( array() );
if( !empty( $postData[ 'filejson' ] ) ){
$saveData[ 'filejson' ] = json_encode( $postData[ 'filejson' ] );
}
if( $postData[ 'anonymous' ] ){
$saveData[ 'anonymous' ] = $postData[ 'anonymous' ];
}
if( $postData[ 'draft' ] ){
$saveData[ 'poststatus' ] = false;
}
if ( $continue ){
$returnId = $this->Post->savePost( $saveData );
if ( $returnId ) {
if( $saveData[ 'post_type' ] == 'court' ){
$data = array( 'post_id' => $returnId, 'polls' => $postData['polls'] );
$return = $this->Post->Polls->savePolls( $data );
}
$response = array( 'error' => 0, 'message' => 'Post Submitted', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Error', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Feed method
*
* @param string|null $id Post id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function getpost()
{
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
$jsonData = $this->request->input('json_decode', true);
if( !isset( $jsonData['userId'] ) && isset( $_POST['userId'] ) ){
$jsonData['userId'] = $_POST['userId'];
$jsonData['accessRoleIds'] = $_POST['accessRoleIds'];
}
if( isset( $jsonData['postId'] ) ){
$wvPost = $this->Post->find('all')->where( [ 'id' => $jsonData['postId'] ]);
if( !empty( $wvPost ) ){
$response['error'] = 0;
$response['message'] = 'Success';
if( isset( $jsonData['userId'] ) ){
$response['data'] = $this->Post->retrievePostDetailed( $wvPost, $jsonData['userId'], $jsonData['accessRoleIds'] );
} else {
$response['data'] = $this->Post->retrievePostDetailed( $wvPost );
}
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Param', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* GetFeed method
*
* @param string|null $id Post id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function getfeed($id = null)
{
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$getData = $this->request->query();
$postData = $this->request->getData();
$requestData = array_merge( $getData, $postData );
if( !isset( $requestData['userId'] ) && isset( $_POST['userId'] ) ){
$requestData['userId'] = $_POST['userId'];
$requestData['accessRoleIds'] = $_POST['accessRoleIds'];
}
if( isset( $requestData['page'] ) ){
$conditions = array();
$orderBy = array();
if( isset( $requestData['posttype'] ) ){
$conditions[] = array( 'post_type' => $requestData['posttype'] );
}
if( isset( $requestData['mcph'] ) ){
$conditions[] = array( 'user_id' => $requestData['mcph'] );
}
if( isset( $requestData['draft'] ) && $requestData['draft'] == 1 && $requestData['mcph'] == $requestData['userId'] ){
$conditions[] = array( 'poststatus' => 0 );
} else {
$conditions[] = array( 'poststatus' => 1 );
}
if( isset( $requestData['most_upvoted'] ) && $requestData['most_upvoted'] == 1 ){
$orderBy[] = 'total_upvotes DESC';
}
if( isset( $requestData['sort_datetime'] ) && $requestData['sort_datetime'] == 1 ){
$orderBy[] = 'created ASC';
} else {
$orderBy[] = 'created DESC';
}
$query = $this->Post->find('all');
$wvPost = $query->page( $requestData['page'] );
if( !empty( $conditions ) ){
$wvPost = $query->where( $conditions );
}
if( isset( $requestData['offset'] ) ){
$wvPost = $query->limit( $requestData['offset'] );
} else {
$wvPost = $query->limit( 25 );
}
$wvPost = $query->order( $orderBy );
if( !empty( $wvPost ) ){
if( isset( $requestData['userId'] ) ){
$response['data'] = $this->Post->retrievePostDetailed( $wvPost, $requestData['userId'], $requestData['accessRoleIds'] );
} else {
$response['data'] = $this->Post->retrievePostDetailed( $wvPost );
}
} else {
$response = array( 'error' => 0, 'message' => 'Your Feed is Empty.', 'data' => array() );
}
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Request.', 'data' => array() );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/src/Model/Table/ActivitylogTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* Activitylog Model
*
* @property \App\Model\Table\UserTable|\Cake\ORM\Association\BelongsTo $User
* @property \App\Model\Table\PostTable|\Cake\ORM\Association\BelongsTo $Post
*
* @method \App\Model\Entity\Activitylog get($primaryKey, $options = [])
* @method \App\Model\Entity\Activitylog newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Activitylog[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Activitylog|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Activitylog|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Activitylog patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Activitylog[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Activitylog findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class ActivitylogTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('activitylog');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'post_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Post', [
'foreignKey' => 'post_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
// ->boolean('upvote')
// ->requirePresence('upvote', 'create')
->notEmpty('upvote');
$validator
// ->boolean('downvote')
// ->requirePresence('downvote', 'create')
->notEmpty('downvote');
$validator
// ->boolean('bookmark')
// ->requirePresence('bookmark', 'create')
->notEmpty('bookmark');
$validator
// ->integer('shares')
// ->requirePresence('shares', 'create')
->notEmpty('shares');
$validator
// ->scalar('flag')
// ->requirePresence('flag', 'create')
->notEmpty('flag');
$validator
// ->boolean('eyewitness')
// ->requirePresence('eyewitness', 'create')
->notEmpty('eyewitness');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['user_id'], 'User'));
$rules->add($rules->existsIn(['post_id'], 'Post'));
return $rules;
}
public function saveActivity( $postData = array() ){
$return = false;
if( !empty( $postData ) ){
$activity = TableRegistry::get('Activitylog');
if( isset( $postData['id'] ) && $postData['id'] != null ){
$entity = $activity->get( $postData['id'] );
} else {
$entity = $activity->newEntity();
}
$entity = $activity->patchEntity( $entity, $postData );
$entity = $this->fixEncodings( $entity );
$record = $activity->save( $entity );
if( $record->id ){
$return = true;
}
}
return $return;
}
public function getCumulativeResult( $postIds = array(), $userId = null ){
$data = array();
if( !empty( $postIds ) ){
$tableData = $this->find('all')->where([ 'post_id IN' => $postIds ])->toArray();
foreach( $tableData as $key => $value ){
if( !isset( $data[ $value->post_id ] ) ){
$data[ $value->post_id ] = array( 'upvoteCount' => 0, 'downvoteCount' => 0, 'eyewitnessCount' => 0, 'authorityFlagCount' => 0, 'userVoteStatus' => 0, 'userBookmarkStatus' => 0, 'userFlagStatus' => 0, 'userEyeWitnessStatus' => 0, 'authorityFlagStatus' => 0 );
}
if( $value->upvote > 0 )
$data[ $value->post_id ]['upvoteCount'] = $data[ $value->post_id ]['upvoteCount'] + 1;
if( $value->downvote > 0 )
$data[ $value->post_id ]['downvoteCount'] = $data[ $value->post_id ]['downvoteCount'] + 1;
if( $value->eyewitness > 0 )
$data[ $value->post_id ]['eyewitnessCount'] = $data[ $value->post_id ]['eyewitnessCount'] + 1;
if( $value->authority_flag > 0 )
$data[ $value->post_id ]['authorityFlagCount'] = $data[ $value->post_id ]['authorityFlagCount'] + 1;
if( $userId != null && $userId == $value->user_id ){
$data[ $value->post_id ]['userVoteStatus'] = ( $value->upvote > 0 ) ? 1 : $data[ $value->post_id ]['userVoteStatus'];
$data[ $value->post_id ]['userVoteStatus'] = ( $value->downvote > 0 ) ? -1 : $data[ $value->post_id ]['userVoteStatus'];
$data[ $value->post_id ]['userBookmarkStatus'] = ( $value->bookmark > 0 ) ? 1 : $data[ $value->post_id ]['userBookmarkStatus'];
$data[ $value->post_id ]['userFlagStatus'] = ( $value->flag > 0 ) ? 1 : $data[ $value->post_id ]['userFlagStatus'];
$data[ $value->post_id ]['userEyeWitnessStatus'] = ( $value->eyewitness > 0 ) ? 1 : $data[ $value->post_id ]['userEyeWitnessStatus'];
$data[ $value->post_id ]['authorityFlagStatus'] = ( $value->authority_flag > 0 ) ? 1 : $data[ $value->post_id ]['authorityFlagStatus'];
}
}
foreach( $postIds as $postId ){
if( !isset( $data[ $postId ] ) ){
$data[ $postId ] = array( 'upvoteCount' => 0, 'downvoteCount' => 0, 'eyewitnessCount' => 0, 'authorityFlagCount' => 0, 'userVoteStatus' => 0, 'userBookmarkStatus' => 0, 'userFlagStatus' => 0, 'userEyeWitnessStatus' => 0, 'authorityFlagStatus' => 0 );
}
}
}
return $data;
}
public function getProperties( $postId ){
$data = array();
if( $postId != 0 && $postId != null ){
$tableData = $this->find('all')->where([ 'post_id' => $postId ])->toArray();
$data = array( 'upvotes' => array( 'count' => 0, 'users' => array() ),
'downvotes' => array( 'count' => 0, 'users' => array() ),
'eyewitness' => array( 'count' => 0, 'users' => array() ) );
$upvoteUserIds = array(); $downvoteUserIds = array(); $eyewitnessUserIds = array();
foreach( $tableData as $key => $value ){
if( $value->upvote > 0 ){
$data['upvotes']['count'] = $data['upvotes']['count'] + 1;
$upvoteUserIds[] = $value->user_id;
}
if( $value->downvote > 0 ){
$data['downvotes']['count'] = $data['downvotes']['count'] + 1;
$downvoteUserIds[] = $value->user_id;
}
if( $value->eyewitness > 0 ){
$data['eyewitness']['count'] = $data['eyewitness']['count'] + 1;
$eyewitnessUserIds[] = $value->user_id;
}
}
$data['upvotes']['users'] = $this->User->getUserList( $upvoteUserIds );
$data['downvotes']['users'] = $this->User->getUserList( $downvoteUserIds );
$data['eyewitness']['users'] = $this->User->getUserList( $eyewitnessUserIds );
}
return $data;
}
public function compareAndReturn( $postData, $currentState ){
$data = array();
if( !empty( $postData ) && !empty( $currentState ) ){
if( isset( $postData['upvote'] ) || isset( $postData['downvote'] ) ){
$upvote = $currentState->upvote;
if( ( isset( $postData['upvote'] ) && $postData['upvote'] < 0 ) || ( isset( $postData['downvote'] ) && $postData['downvote'] > 0 ) ){
$upvote = 0;
} else if ( $postData['upvote'] > 0 ) {
$upvote = 1;
}
if( $currentState->upvote < $upvote ){
$res = $this->Post->changeUpvotes( $currentState->post_id, 1 );
} elseif ( $currentState->upvote > $upvote ){
$res = $this->Post->changeUpvotes( $currentState->post_id, -1 );
}
$currentState->upvote = $upvote;
if( ( isset( $postData['upvote'] ) && $postData['upvote'] > 0 ) || ( isset( $postData['downvote'] ) && $postData['downvote'] < 0 ) ){
$currentState->downvote = 0;
} else if ( $postData['downvote'] > 0 ) {
$currentState->downvote = 1;
}
}
$keys = array( 'bookmark', 'flag', 'eyewitness', 'authority_flag' );
foreach( $keys as $key ){
if( isset( $postData[ $key ] ) ){
if( $postData[ $key ] > 0 ){
$currentState[ $key ] = 1;
} else if( $postData[ $key ] < 0 ){
$currentState[ $key ] = 0;
}
}
}
if( isset( $postData['shares'] ) && $postData['shares'] > 0 ){
$currentState->shares = $currentState->shares + 1;
}
$data = array(
'id' => $currentState->id,
'user_id' => $currentState->user_id,
'post_id' => $currentState->post_id,
'upvote' => $currentState->upvote,
'downvote' => $currentState->downvote,
'bookmark' => $currentState->bookmark,
'flag' => $currentState->flag,
'eyewitness' => $currentState->eyewitness,
'authority_flag' => $currentState->authority_flag,
'shares' => $currentState->shares,
'modified' => date("Y-m-d H:i:s", time())
);
}
return $data;
}
public function conditionBasedSearch( $queryConditions = array() ){
$response = array();
if( !empty( $queryConditions ) ){
$activities = $this->find();
if( isset( $queryConditions['page'] ) )
$activities = $activities->page( $queryConditions['page'] );
if( isset( $queryConditions['offset'] ) )
$activities = $activities->limit( $queryConditions['offset'] );
if( isset( $queryConditions['conditions'] ) )
$activities = $activities->where( $queryConditions['conditions'] );
$activities = $activities->toArray();
if( !empty( $activities ) ){
$postIds = Hash::extract( $activities, '{n}.post_id' );
$wvPost = $this->Post->find()->where(['id IN' => $postIds ])->toArray();
$response = $wvPost;
}
}
return $response;
}
public function getBookMarkCount( $userId = null, $queryConditions = array() ){
$response = null;
if( $userId != null ){
$post = TableRegistry::get('Activitylog');
$conditions = array( 'user_id' => $userId );
$query = $post->find();
// if( !empty( $queryConditions ) ){
//
// }
$query = $query->where( $conditions );
$totalPosts = $query->count();
$response = $totalPosts;
}
return $response;
}
}
<file_sep>/db/data/10/addedParentIdInComments.sql
ALTER TABLE `comments` ADD `parent_id` INT NOT NULL DEFAULT '0' AFTER `post_id`;
<file_sep>/db/data/17/droppingIndexes.sql
ALTER TABLE `area_ratings` DROP INDEX area_level;
ALTER TABLE `area_ratings` DROP INDEX area_level_id;
<file_sep>/src/Model/Table/EmailVerificationTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;
use Cake\Utility\Text;
use Cake\Utility\Hash;
/**
* EmailVerification Model
*
* @property |\Cake\ORM\Association\BelongsTo $Users
*
* @method \App\Model\Entity\EmailVerification get($primaryKey, $options = [])
* @method \App\Model\Entity\EmailVerification newEntity($data = null, array $options = [])
* @method \App\Model\Entity\EmailVerification[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\EmailVerification|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\EmailVerification|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\EmailVerification patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\EmailVerification[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\EmailVerification findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class EmailVerificationTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('email_verification');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('GenericOps');
$this->addBehavior('HashId', ['field' => array( 'user_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('token')
->maxLength('token', 36)
->requirePresence('token', 'create')
->notEmpty('token');
$validator
->scalar('code')
->maxLength('code', 10)
->requirePresence('code', 'create')
->notEmpty('code');
//
// $validator
// ->dateTime('expirationtime')
// ->requirePresence('expirationtime', 'create')
// ->notEmpty('expirationtime');
//
// $validator
// ->requirePresence('status', 'create')
// ->notEmpty('status');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['user_id'], 'User'));
return $rules;
}
public function add( $userId = null ){
$response = null;
if( $userId != null ){
$data = array(
'user_id' => $userId,
'token' => Text::uuid(),
'code' => $this->randomAlphanumeric( 8 ),
);
$emailVerification = TableRegistry::get('EmailVerification');
$entity = $emailVerification->newEntity();
$entity = $emailVerification->patchEntity( $entity, $data );
$record = $emailVerification->save( $entity );
$response = $record;
}
return $response;
}
/*
* data[ code ]
* data[ token ]
* data[ userId ]
*/
public function verify( $data = array() ){
$response = array( 'error' => 1, 'message' => 'Verification Failed', 'data' => array() );
if( !empty( $data ) ){
$emailVerification = TableRegistry::get('EmailVerification');
$user = $this->User->find()->where( [ 'email' => $data['email'], 'status' => 1 ] )->toArray();
if( !empty( $user ) ){
$founds = $emailVerification->find()->where( [ 'user_id' => $user[0]->id, 'status' => 1 ] )->toArray();
if( !empty( $founds ) ){
$userVerified = false;
foreach( $founds as $found ){
if( isset( $data['token'] ) && $data['token'] == $found->token ){
$userVerified = true;
}
if( isset( $data['code'] ) && $data['code'] == $found->code ){
$userVerified = true;
}
if( $userVerified ){
$updateUser = array( $user[0]->id => array( 'id' => $user[0]->id, 'email_verified' => 1 ) );
$usersUpdated = $this->User->updateUser( $updateUser );
if( !empty( $usersUpdated ) ){
$entity = $emailVerification->get( $found->id );
$entity->status = 0;
$entity = $this->fixEncodings( $entity );
if( $emailVerification->save( $entity ) ){
$response = array( 'error' => 0, 'message' => 'Verification Successful', 'data' => array( $user[0]->id ) );
}
}
break;
}
}
} else {
$response = array( 'error' => 1, 'message' => 'Invalid Code' );
}
} else {
$response = array( 'error' => 1, 'message' => 'User not found' );
}
}
return $response;
}
}
<file_sep>/src/Model/Table/CitiesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* Cities Model
*
* @property \App\Model\Table\StatesTable|\Cake\ORM\Association\BelongsTo $States
*
* @method \App\Model\Entity\City get($primaryKey, $options = [])
* @method \App\Model\Entity\City newEntity($data = null, array $options = [])
* @method \App\Model\Entity\City[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\City|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\City patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\City[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\City findOrCreate($search, callable $callback = null, $options = [])
*/
class CitiesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('cities');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('HashId', [ 'field' => array( 'state_id' ) ]);
$this->belongsTo('States', [
'foreignKey' => 'state_id',
'joinType' => 'INNER'
]);
$this->hasMany('Localities');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('name')
->maxLength('name', 30)
->requirePresence('name', 'create')
->notEmpty('name');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['state_id'], 'States'));
// $rules->add($rules->existsIn(['city_id'], 'States'));
return $rules;
}
/*
* data['city']
* data['country']
* response => ( 'city_id', 'state_id', 'country_id' )
*/
public function findCities( $data ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $data ) && isset( $data['city'] ) ){
$city = $this->find('all')->where([ 'name LIKE' => '%'.$data['city'].'%' ])->toArray();
$cityData = array();
if( !empty( $city ) ){
$stateIds = array(); $tmpCityData = array();
$maxSimilarity = 0;
foreach ( $city as $key => $value ) {
$sim = similar_text( $data['city'], $value['name'] );
if( $sim >= $maxSimilarity ){
$maxSimilarity = $sim;
$tmpCityData[ $value->state_id ] = array( 'city_id' => $value['id'], 'city_name' => $value['name'], 'state_id' => $value->state_id );
$stateIds[] = $value->state_id;
}
}
$statesRes = $this->States->findStateById( $stateIds, $data );
$states = $statesRes['data']['states'];
$maxSimilarity = 0;
foreach ( $states as $key => $value ) {
$sim = similar_text( $data['state'], $value['state_name'] );
if( $sim >= $maxSimilarity ){
$maxSimilarity = $sim;
$cityData = array( $tmpCityData[ $value['state_id'] ] );
}
}
} else {
$statesRes = $this->States->findStates( $data );
if( !empty( $statesRes['data'] ) ){
$countries = $statesRes['data']['countries'];
$states = $statesRes['data']['states'];
foreach ( $states as $key => $value ) {
if( strpos( $value['state_name'], $data['state'] ) !== false ){
$saveCity = array( 'name' => $data['city'], 'state_id' => $value['state_id'] );
$cityId = $this->addCities( $saveCity );
$cityData[] = array( 'city_id' => $cityId, 'city_name' => $data['city'], 'state_id' => $value['state_id'] );
}
}
}
}
$response['data'] = $statesRes['data'];
$response['data']['cities'] = $cityData;
}
return $response;
}
public function findCitiesById( $cityIds, $data = array() ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $cityIds ) ){
$cities = $this->find('all')->where([ 'id IN' => $cityIds ])->toArray();
if( !empty( $cities ) ){
$stateIds = array();
foreach ( $cities as $key => $value ) {
$cityData[] = array( 'city_id' => $value['id'], 'city_name' => $value['name'], 'state_id' => $value->state_id );
$stateIds[] = $value->state_id;
}
$statesRes = $this->States->findStateById( $stateIds, $data );
$response['data'] = $statesRes['data'];
$response['data']['cities'] = $cityData;
}
}
return $response;
}
/*
* data['name']
* data['state_id']
*/
public function addCities( $data ){
$return = null;
if( !empty( $data ) ){
$city = TableRegistry::get('Cities');
$entity = $city->newEntity();
$entity = $city->patchEntity( $entity, $data );
$record = $city->save( $entity );
if( $record->id ){
$return = $this->encodeId( $record->id );
}
}
return $return;
}
}
<file_sep>/src/Model/Table/CountriesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Countries Model
*
* @method \App\Model\Entity\Country get($primaryKey, $options = [])
* @method \App\Model\Entity\Country newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Country[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Country|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Country patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Country[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Country findOrCreate($search, callable $callback = null, $options = [])
*/
class CountriesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('countries');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('HashId');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('country_code')
->maxLength('country_code', 3)
->requirePresence('country_code', 'create')
->notEmpty('country_code');
$validator
->scalar('name')
->maxLength('name', 150)
->requirePresence('name', 'create')
->notEmpty('name');
$validator
->integer('phonecode')
->requirePresence('phonecode', 'create')
->notEmpty('phonecode');
return $validator;
}
public function findCountryById( $countryIds, $data = array() ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $countryIds ) ){
$countryData = array();
$countries = $this->find('all')->where([ 'id IN' => $countryIds ])->toArray();
foreach ( $countries as $key => $value ) {
$countryData[] = array( 'country_id' => $value['id'], 'country_name' => $value['name'], 'country_code' => $value['country_code'] );
}
$response['data'] = array( 'countries' => $countryData );
}
return $response;
}
/*
* data['country']
* response => ( 'country_id' )
*/
public function findCountry( $data ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( !empty( $data ) && isset( $data['country_code'] ) ){
$country = $this->find('all')->where([ 'country_code' => $data['country_code'] ])->toArray();
if( !empty( $country ) ){
$countryData = array();
foreach ( $country as $key => $value ) {
$countryData[] = array( 'country_id' => $value['id'], 'country_name' => $value['name'], 'country_code' => $value->country_code );
}
$response['data']['countries'] = $countryData;
}
}
return $response;
}
}
<file_sep>/db/data/15/alterTableUser.sql
ALTER TABLE `user` CHANGE `access_role_ids` `access_role_ids` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '[]';
ALTER TABLE `user` ADD `about` VARCHAR(2048) NULL AFTER `default_location_id`, ADD `tagline` VARCHAR(128) NULL AFTER `about`;
ALTER TABLE `user` CHANGE `about` `about` VARCHAR(2048) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', CHANGE `tagline` `tagline` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '';
ALTER TABLE `user` CHANGE `address` `address` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT ''
<file_sep>/src/Model/Table/AccessRolesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* AccessRoles Model
*
* @property \App\Model\Table\AreaLevelsTable|\Cake\ORM\Association\BelongsTo $AreaLevels
*
* @method \App\Model\Entity\AccessRole get($primaryKey, $options = [])
* @method \App\Model\Entity\AccessRole newEntity($data = null, array $options = [])
* @method \App\Model\Entity\AccessRole[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\AccessRole|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\AccessRole|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\AccessRole patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\AccessRole[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\AccessRole findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class AccessRolesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('access_roles');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('ArrayOps');
$this->addBehavior('HashId', ['field' => array( 'id', 'area_level_id' ) ]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('area_level')
->requirePresence('area_level', 'create')
->notEmpty('area_level');
$validator
->integer('access_level')
->requirePresence('access_level', 'create')
->notEmpty('access_level');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
return $rules;
}
public $areaWiseModels = array( 'country' => 'Countries', 'city' => 'Cities', 'state' => 'States', 'department' => 'Department' );
public $locationKeyMap = array(
'country_id' => 'country', 'country' => 'country_id',
'state_id' => 'state', 'state' => 'state_id',
'city_id' => 'city', 'city' => 'city_id'
);
public function getAccessData( $roleIds ){
$data = array();
if( !empty( $roleIds ) ){
$accessRoles = $this->find('all')->where([ 'id IN' => $roleIds ])->toArray();
$accessLevels = array( '1' => 'w', '2' => 'a' );
$areaWiseModels = array( 'country' => 'Countries', 'city' => 'Cities', 'state' => 'States', 'department' => 'Department' );
foreach( $accessRoles as $accessRole ){
$areaLevel = $accessRole['area_level'];
$areaModel = TableRegistry::get( $this->areaWiseModels[ $areaLevel ] );
$return = $areaModel->find()->where( [ 'id' => $accessRole['area_level_id'] ] )->toArray();
$data[] = array( 'area' => $return[0]->name, 'access_level' => $accessLevels[ $accessRole['access_level'] ]);
}
}
return $data;
}
/*
* data[ country_id ]
* data[ city_id ]
* data[ state_id ]
*/
public function retrieveAccessRoleIds( $data, $accessLevel = array( 1, 2 ) ){
$response = array();
if( !empty( $data ) ){
$conditions = array( 'OR' => array() );
foreach( $data as $key => $ids ){
$areaLevel = $this->locationKeyMap[ $key ];
if( !empty( $ids ) ){
$conditions['OR'][] = array( 'area_level' => $areaLevel, 'area_level_id IN' => $ids, 'access_level IN' => $accessLevel );
}
}
$accessRoles = $this->find('all')
->where( $conditions )
->toArray();
$accessRolesFound = array();
$accessRoleKeysFound = array( 'city_id' => array(), 'country_id' => array(), 'state_id' => array());
foreach( $accessRoles as $key => $access ){
$dataKey = $this->locationKeyMap[ $access['area_level'] ];
if( in_array( $access['area_level_id'], $data[ $dataKey ] ) ){
$accessRolesFound[] = array( 'id' => $access['id'], 'area_level' => $access['area_level'],
'area_level_id' => $access['area_level_id'], 'access_level' => $access['access_level'] );
$accessRoleKeysFound[ $dataKey ][] = $access['area_level_id'];
}
}
$data['country_id'] = array_diff( $data['country_id'], $accessRoleKeysFound['country_id'] );
$data['state_id'] = array_diff( $data['state_id'], $accessRoleKeysFound['state_id'] );
$data['city_id'] = array_diff( $data['city_id'], $accessRoleKeysFound['city_id'] );
$returnData = $this->addAccess( $data, $accessLevel );
$response = array_merge( $accessRolesFound, $returnData );
}
return $response;
}
/*
* data[ country_id ]
* data[ city_id ]
* data[ state_id ]
*/
public function addAccess( $data = array(), $accessLevel = array( 1, 2 ) ){
$response = array();
if( !empty( $data ) ){
$accessData = array();
foreach( $data as $key => $access ){
$areaLevel = $this->locationKeyMap[ $key ];
foreach( $access as $locationIds ){
foreach ( $accessLevel as $key => $access ) {
$accessData[] = array( 'area_level' => $areaLevel, 'area_level_id' => $locationIds, 'access_level' => $access );
}
}
}
$accessRoles = TableRegistry::get('AccessRoles');
$accessData = $accessRoles->newEntities( $accessData );
$result = $accessRoles->saveMany( $accessData );
if( !empty( $result ) ){
foreach( $result as $data ){
$data = $this->encodeResultSet( $data );
$response[] = array( 'id' => $data['id'], 'area_level' => $data['area_level'],
'area_level_id' => $data['area_level_id'], 'access_level' => $data['access_level'] );
}
}
}
return $response;
}
public function getRelativeAccessRoles( $data = array(), $accessLevel = array( 1, 2 ) ){
$accessRoleIds = array();
if( !empty( $data ) ){
$cityModel = TableRegistry::get( $this->areaWiseModels[ 'city' ] );
$cityRes = $cityModel->findCitiesById( $data['city_id'] )['data'];
$cityMap = Hash::combine( $cityRes['cities'], '{n}.city_id', '{n}.state_id');
$stateMap = Hash::combine( $cityRes['states'], '{n}.state_id', '{n}.country_id');
$countries = Hash::extract( $cityRes['countries'], '{n}.country_id' );
$stateModel = TableRegistry::get( $this->areaWiseModels[ 'state' ] );
$stateRes = $stateModel->findStateById( $data['state_id'] )['data'];
$stateMap = array_merge( $stateMap, Hash::combine( $stateRes['states'], '{n}.state_id', '{n}.country_id') );
$countries = array_merge( $countries, Hash::extract( $stateRes['countries'], '{n}.country_id' ));
$countryModel = TableRegistry::get( $this->areaWiseModels[ 'country' ] );
$countryRes = $countryModel->findCountryById( $data['country_id'] )['data'];
$countries = array_merge( $countries, Hash::extract( $countryRes['countries'], '{n}.country_id' ));
$countries = array_unique( $countries );
$newAccessMap = array(
'countries' => array( 'key' => 'country', 'value' => 'country_id' ),
'states' => array( 'key' => 'state', 'value' => 'state_id' ),
'cities' => array( 'key' => 'city', 'value' => 'city_id' )
);
foreach( $newAccessMap as $index => $arr ){
$response = array();
if( isset( $cityRes[ $index ] ) ){
$response = $cityRes[ $index ];
}
if( isset( $stateRes[ $index ] ) ){
$response = $stateRes[ $index ];
}
if( isset( $countryRes[ $index ] ) ){
$response = $countryRes[ $index ];
}
foreach( $response as $data ){
$conditions['OR'][] = array( 'area_level' => $arr['key'], 'area_level_id' => $data[ $arr['value'] ], 'access_level IN' => $accessLevel );
}
}
$accessData = array();
$accessRoles = $this->find('all')
->where( $conditions )
->toArray();
foreach( $accessRoles as $key => $value ){
}
$accessData = $this->array_group_by( $accessRoles, 'area_level', 'area_level_id', 'id');
$accessRoleIds = Hash::extract( $accessRoles, '{n}.id');
pr( $accessRoleIds);
pr( $accessData );exit;
}
return $accessRoleIds;
}
}
<file_sep>/src/Model/Table/OauthTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Security;
use Cake\Core\Configure;
use Firebase\JWT\JWT;
/**
* Oauth Model
*
* @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
* @property \App\Model\Table\ProvidersTable|\Cake\ORM\Association\BelongsTo $Providers
*
* @method \App\Model\Entity\Oauth get($primaryKey, $options = [])
* @method \App\Model\Entity\Oauth newEntity($data = null, array $options = [])
* @method \App\Model\Entity\Oauth[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\Oauth|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Oauth|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\Oauth patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\Oauth[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\Oauth findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class OauthTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('oauth');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
// $this->belongsTo('Providers', [
// 'foreignKey' => 'provider_id',
// 'joinType' => 'INNER'
// ]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->integer('user_id')
->requirePresence('user_id', 'create')
->notEmpty('user_id');
$validator
->scalar('access_token')
->maxLength('access_token', 2048)
->requirePresence('access_token', 'create')
->notEmpty('access_token');
$validator
->requirePresence('expiration_time', 'create')
->notEmpty('expiration_time');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules) {
// $rules->add($rules->existsIn(['user_id'], 'User'));
// $rules->add($rules->existsIn(['provider_id'], 'Providers'));
return $rules;
}
public function matchAndRetrieve( $access_token ){
return true;
}
public function getUserToken( $userId ){
$result = array( 'error' => 0, 'data' => array());
if( $userId != null ){
$extractedData = $this->find()->where([ 'user_id' => $userId ])->toArray();
if( !empty( $extractedData ) && strtotime( $extractedData[0]['expiration_time'] ) > time() ){
$user = $this->User->find()->where( [ 'id' => $userId ] )->toArray();
$secretKey = Configure::read('jwt_secret_key');
$issuedAt = time();
$expire = $issuedAt + 86400;
$data = [
'issued_at' => $issuedAt, // Issued at: time when the token was generated
'access_token' => $extractedData[0]['access_token'], // Json Token Id: an unique identifier for the token
'provider_id' => $extractedData[0]['provider_id'], // Issuer
'expiration_time' => $expire, // Expire
'user_id' => $userId,
'access_roles' => json_decode( $user[0]->access_role_ids ),
];
$bearerToken = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
'HS512' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3
);
$oAuth = TableRegistry::get('Oauth');
$oEntity = $oAuth->get( $extractedData[0]->id );
$oEntity = $oAuth->patchEntity( $oEntity, $data );
if( $oAuth->save( $oEntity ) ){
$response = array(
'name' => $user[0]->firstname.' '.$user[0]->lastname,
'bearerToken' => $bearerToken
);
$result['data'] = $response;
} else {
$result['error'] = -1;
}
} else if( !empty( $extractedData ) ) {
$result['error'] = -1;
} else {
$result['error'] = 1;
}
} else {
$result['error'] = 1;
}
return $result;
}
public function createUserToken( $userId ){
$result = array( 'error' => 0, 'data' => array());
if( $userId != null ){
$user = $this->User->find()->where( [ 'id' => $userId ] )->toArray();
$serverName = Configure::read('App.fullBaseUrl');
$secretKey = Configure::read('jwt_secret_key');
$tokenId = base64_encode( Security::randomBytes( 32 ) );
$issuedAt = time();
$expire = $issuedAt + 86400;
$data = [
'issued_at' => $issuedAt, // Issued at: time when the token was generated
'access_token' => $tokenId, // Json Token Id: an unique identifier for the token
'provider_id' => $serverName, // Issuer
'expiration_time' => $expire, // Expire
'user_id' => $userId,
'access_roles' => json_decode( $user[0]->access_role_ids ),
];
$bearerToken = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
'HS512' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3
);
$oAuth = TableRegistry::get('Oauth');
$oEntity = $oAuth->newEntity();
$oEntity = $oAuth->patchEntity( $oEntity, $data );
if( $oAuth->save( $oEntity ) ){
$response = array(
'name' => $user[0]->firstname.' '.$user[0]->lastname,
'bearerToken' => $bearerToken
);
$result['data'] = $response;
} else {
$result['error'] = 1;
}
} else {
$result['error'] = 1;
}
return $result;
}
public function refreshAccessToken( $userId ){
$result = array( 'error' => 0, 'data' => array());
if( $userId != null ){
$user = $this->User->find()->where( [ 'id' => $userId ] )->toArray();
$extractedData = $this->find()->where([ 'user_id' => $userId ])->toArray();
$serverName = Configure::read('App.fullBaseUrl');
$secretKey = Configure::read('jwt_secret_key');
$tokenId = base64_encode( Security::randomBytes( 32 ) );
$issuedAt = time();
$expire = $issuedAt + 86400;
$data = [
'issued_at' => $issuedAt, // Issued at: time when the token was generated
'access_token' => $tokenId, // Json Token Id: an unique identifier for the token
'provider_id' => $serverName, // Issuer
'expiration_time' => $expire, // Expire
'user_id' => $userId,
'access_roles' => json_decode( $user[0]->access_role_ids ),
];
$bearerToken = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
'HS512' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3
);
$saveData = $data;
$saveData['modified'] = $data['issued_at'];
$oAuth = TableRegistry::get('Oauth');
$oEntity = $oAuth->get( $extractedData[0]->id );
$oEntity = $oAuth->patchEntity( $oEntity, $saveData );
$oEntity = $this->fixEncodings( $oEntity );
if( $oAuth->save( $oEntity ) ){
$response = array(
'name' => $user[0]->firstname.' '.$user[0]->lastname,
'bearerToken' => $bearerToken
);
$result['data'] = $response;
} else {
$result['error'] = 1;
}
} else {
$result['error'] = 1;
}
return $result;
}
public function validateToken( $token ){
$result = false;
if( !empty( $token ) && isset( $token->user_id ) && isset( $token->access_token ) && isset( $token->access_roles ) ){
$extractedData = $this->find()->where([ 'user_id' => $token->user_id, 'access_token' => $token->access_token ])->toArray();
if( !empty( $extractedData ) && $token->expiration_time >= time() ){
return true;
}
}
return $result;
}
public function deleteUserToken( $userId ){
$result = false;
if( $userId != null ){
$extractedData = $this->find()->where([ 'user_id' => $userId ])->toArray();
$oAuth = TableRegistry::get('Oauth');
$entity = $oAuth->get( $extractedData[0]->id );
$result = $oAuth->delete( $entity );
}
return $result;
}
}
<file_sep>/db/data/2/dropTableMinistryChangeName.sql
DROP TABLE `ministry`;
CREATE TABLE `departments` (
`id` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
`country_id` int(11) DEFAULT NULL,
`state_id` int(11) DEFAULT NULL,
`city_id` int(11) DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0 for world & 1 for country & 2 for state & 3 for city',
`head_profilepic` varchar(100) NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`modified` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `departments` ADD PRIMARY KEY( `id`);
ALTER TABLE `departments` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
<file_sep>/src/Controller/CountriesController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Countries Controller
*
* @property \App\Model\Table\CountriesTable $Countries
*
* @method \App\Model\Entity\Country[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class CountriesController extends AppController {
public function get(){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$response['data'] = $this->Countries->find('all',[
'fields' => [ 'id', 'country_code', 'name', 'phonecode' ]
]);
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/src/Controller/ActivitylogController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Activitylog Controller
*
* @property \App\Model\Table\ActivitylogTable $Activitylog
*
* @method \App\Model\Entity\Activitylog[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class ActivitylogController extends AppController
{
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add() {
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
if ( $this->request->is('post') ) {
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
$postData['accessRoleIds'] = $_POST['accessRoleIds'];
} else {
$postData = $this->request->getData();
}
$saveData = array();
if( isset( $postData['user_id'] ) && isset( $postData['post_id'] ) ){
$wvActivity = $this->Activitylog->find('all')->where(['user_id' => $postData['user_id'], 'post_id' => $postData['post_id'] ])->toArray();
$wvPost = $this->Activitylog->Post->get( $postData['post_id'] );
$allowAdmin = $this->Activitylog->Post->allowAdmin( $wvPost, $postData['accessRoleIds'] );
if( !$allowAdmin ){
$postData['authority_flag'] = -1;
}
if( empty( $wvActivity ) ){
$saveData = $postData;
if( ( isset( $saveData['upvote'] ) ) && $saveData['upvote'] > 0 ){
$res = $this->Activitylog->Post->changeUpvotes( $saveData['post_id'], 1 );
}
} else {
$saveData = $this->Activitylog->compareAndReturn( $postData, $wvActivity[0] );
}
if( !empty( $saveData ) ){
if ( $this->Activitylog->saveActivity( $saveData ) ) {
$result = $this->Activitylog->getCumulativeResult( array( $postData['post_id'] ), $postData['user_id'] );
$response = array( 'error' => 0, 'message' => 'Activity Submitted', 'data' => $result[ $postData['post_id'] ] );
}
} else {
$response = array( 'error' => -1, 'message' => 'Activity Failed', 'data' => array() );
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Edit method
*
* @param string|null $id Activitylog id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$Activitylog = $this->Activitylog->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$Activitylog = $this->Activitylog->patchEntity($Activitylog, $this->request->getData());
if ($this->Activitylog->save($Activitylog)) {
$this->Flash->success(__('The wv activitylog has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The wv activitylog could not be saved. Please, try again.'));
}
$users = $this->Activitylog->Users->find('list', ['limit' => 200]);
$posts = $this->Activitylog->Posts->find('list', ['limit' => 200]);
$this->set(compact('Activitylog', 'users', 'posts'));
}
public function getbookmarks( ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$getData = $this->request->query();
$postData = $this->request->getData();
$requestData = array_merge( $getData, $postData );
if( !isset( $requestData['userId'] ) ){
$requestData['userId'] = $_POST['userId'];
$requestData['accessRoleIds'] = $_POST['accessRoleIds'];
}
if( !isset( $requestData['mcph'] ) ){
$requestData['mcph'] = $requestData['userId'];
}
if( !empty( $requestData ) && isset( $requestData['page'] ) ){
$queryConditions = array();
$queryConditions['page'] = $requestData['page'];
if( isset( $requestData['offset'] ) ){
$queryConditions['offset'] = $requestData['offset'];
} else {
$queryConditions['offset'] = 10;
}
$queryConditions['conditions'] = array( 'bookmark' => 1, 'user_id' => $requestData['mcph'] );
$wvPost = $this->Activitylog->conditionBasedSearch( $queryConditions );
if( !empty( $wvPost ) ){
$response['data'] = $this->Activitylog->Post->retrievePostDetailed( $wvPost );
} else {
$response = array( 'error' => 0, 'message' => 'Your Feed is Empty.', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/db/data/14/alterUserTable.sql
ALTER TABLE `user` CHANGE `gender` `gender` ENUM('male','female','transgender') CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` ADD `date_of_birth` DATETIME NULL AFTER `status`;
ALTER TABLE `user` ADD `default_location_id` INT(11) NOT NULL DEFAULT '0' AFTER `longitude`;
<file_sep>/db/data/12/alterTableAccessRoles.sql
ALTER TABLE `access_roles` CHANGE `area_level` `area_level` ENUM('world','country','state','city','department') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'These will be prioritize as Wolrd > Country > State > City > Department';
ALTER TABLE `access_roles` DROP `name`;
<file_sep>/src/Controller/AreaRatingsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* AreaRatings Controller
*
* @property \App\Model\Table\AreaRatingsTable $AreaRatings
*
* @method \App\Model\Entity\AreaRating[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class AreaRatingsController extends AppController {
public function rateArea() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$jsonData = $this->request->input('json_decode', true);
if( !empty( $jsonData ) ){
$jsonData['userId'] = $_POST['userId'];
} else {
$jsonData = $this->request->getData();
}
if( !empty( $jsonData ) ){
$saveData = array();
$saveData['user_id'] = $jsonData['userId'];
if( isset( $jsonData['areaLevel'] ) ){
$saveData['area_level'] = $jsonData['areaLevel'];
}
if( isset( $jsonData['areaLevelId'] ) ){
$saveData['area_level_id'] = $jsonData['areaLevelId'];
}
if( isset( $jsonData['rating'] ) ){
$saveData['good'] = ( $jsonData['rating'] == 'good' ) ? 1 : 0;
$saveData['bad'] = ( $jsonData['rating'] == 'bad' ) ? 1 : 0;
}
if( !empty( $saveData ) ){
$result = $this->AreaRatings->saveratings( $saveData );
if( $result ){
$response['data'] = $result;
} else {
$response = array( 'error' => 1, 'message' => 'Failed!', 'data' => array() );
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function getdatewiseratings() {
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$getData = $this->request->query();
if( !empty( $jsonData ) ){
$getData['userId'] = $_GET['userId'];
}
if( !empty( $getData ) ){
$data = $this->AreaRatings->getDateWiseRatings( $getData );
if( !empty( $data ) ){
$response = array( 'error' => 0, 'message' => '', 'data' => $data );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/db/data/1/alterPostTable.sql
ALTER TABLE `post` DROP `cat_id`;
ALTER TABLE `post` DROP `subcat_id`;
ALTER TABLE `post` DROP `posttime`;
ALTER TABLE `post` CHANGE `filelink` `filejson` VARCHAR(512) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL;
ALTER TABLE `post` ADD `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `locality_id`, ADD `modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `created`;
<file_sep>/db/data/14/alterFavLocation.sql
ALTER TABLE `fav_location` ADD `level` ENUM('city','country','locality','state') NOT NULL AFTER `locality_id`;
ALTER TABLE `fav_location` CHANGE `country_id` `country_id` INT(11) NOT NULL DEFAULT '0', CHANGE `state_id` `state_id` INT(11) NOT NULL DEFAULT '0', CHANGE `city_id` `city_id` INT(11) NOT NULL DEFAULT '0', CHANGE `locality_id` `locality_id` INT(11) NOT NULL DEFAULT '0';
ALTER TABLE `fav_location` DROP `department_id`;
<file_sep>/db/data/16/setdefaultValueForEyewitnessColumn.sql
ALTER TABLE `activitylog` CHANGE `eyewitness` `eyewitness` TINYINT(1) NOT NULL DEFAULT '0';
<file_sep>/src/Model/Table/UserPollsTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Cake\Utility\Hash;
/**
* UserPolls Model
*
* @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
* @property \App\Model\Table\PollsTable|\Cake\ORM\Association\BelongsTo $Polls
* @property \App\Model\Table\PostsTable|\Cake\ORM\Association\BelongsTo $Posts
*
* @method \App\Model\Entity\UserPoll get($primaryKey, $options = [])
* @method \App\Model\Entity\UserPoll newEntity($data = null, array $options = [])
* @method \App\Model\Entity\UserPoll[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\UserPoll|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\UserPoll|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\UserPoll patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\UserPoll[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\UserPoll findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class UserPollsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('user_polls');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'poll_id', 'post_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Polls', [
'foreignKey' => 'poll_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Post', [
'foreignKey' => 'post_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['user_id'], 'User'));
$rules->add($rules->existsIn(['poll_id'], 'Polls'));
$rules->add($rules->existsIn(['post_id'], 'Post'));
return $rules;
}
public function saveUserPolls( $postData ){
$return = false;
if( !empty( $postData ) ){
$userPoll = TableRegistry::get('UserPolls');
$dataCheck = $this->find('all')->where([ 'user_id' => $postData['user_id'], 'post_id' => $postData['post_id'] ])->toArray();
$polls = $this->Polls->getPolls( array( $postData['post_id'] ) );
$pollIds = Hash::extract( $polls[ $postData[ 'post_id' ] ]['polls'], '{n}.id' );
if( empty( $dataCheck ) && !empty( $polls ) && in_array( $postData['poll_id'], $pollIds ) ){
$entity = $userPoll->newEntity();
$entity = $userPoll->patchEntity( $entity, $postData );
$record = $userPoll->save( $entity );
$incrementCounter = $this->Polls->newVote( $postData );
if( isset( $record->id ) && $incrementCounter ){
$return = $record->id;
}
}
}
return $return;
}
public function getUserlistPolled( $postIds = array() ){
$response = array();
if( !empty( $postIds ) ){
$pollData = $this->find('all')->select([ 'user_id', 'post_id' ])->where([ 'post_id IN' => $postIds ])->toArray();
foreach( $pollData as $poll ){
if( !isset( $response[ $poll->post_id ] ) ){
$response[ $poll->post_id ] = array();
}
$response[ $poll->post_id ][] = $poll->user_id;
}
}
return $response;
}
}
<file_sep>/db/data/1/dropTableLocalityReviewsAddedNew.sql
DROP TABLE `locality_reviews`;
CREATE TABLE `localities` (
`id` int(11) NOT NULL,
`locality` varchar(100) NOT NULL,
`city_id` int(11) NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT 1,
`created` datetime NOT NULL DEFAULT current_timestamp(),
`modified` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<file_sep>/src/Model/Behavior/HashIdBehavior.php
<?php
namespace App\Model\Behavior;
use ArrayObject;
use Cake\Collection\Collection;
use Cake\Core\Configure;
use Cake\Database\ExpressionInterface;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Query;
use Cake\ORM\Table;
use Hashids\Hashids;
/**
* HashId behavior
*/
class HashIdBehavior extends Behavior
{
const HID = 'hid';
/**
* @var array|string
*/
protected $_primaryKey;
/**
* @var array
*/
protected $_defaultConfig = [
'salt' => 'SayForExampleThisIsMySalt', // Please provide your own salt via Configure key 'Hashid.salt'
'field' => array(), // To populate upon find() and save(), false to deactivate
'debug' => false, // Auto-detect from Configure::read('debug')
'minHashLength' => 8, // You can overwrite the Hashid defaults
'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_', // You can overwrite the Hashid defaults
'recursive' => false, // Also transform nested entities
'findFirst' => false, // Either true or 'first' or 'firstOrFail'
'implementedFinders' => [
'hashed' => 'findHashed',
]
];
/**
* Constructor
*
* Merges config with the default and store in the config property
*
* Does not retain a reference to the Table object. If you need this
* you should override the constructor.
*
* @param \Cake\ORM\Table $table The table this behavior is attached to.
* @param array $config The config for this behavior.
*/
public function __construct(Table $table, array $config = []) {
parent::__construct($table, $config);
$this->_table = $table;
$this->_primaryKey = $table->getPrimaryKey();
if ($this->_config['salt'] === null) {
$this->_config['salt'] = Configure::read('Security.salt') ? sha1(Configure::read('Security.salt')) : null;
}
if ($this->_config['debug'] === null) {
$this->_config['debug'] = Configure::read('debug');
}
if ( empty( $this->_config['field'] )) {
$this->_config['field'][] = $this->_primaryKey;
}
}
/**
* @param \Cake\Event\Event $event
* @param \Cake\ORM\Query $query
* @param \ArrayObject $options
* @param bool $primary
* @return void
*/
public function beforeFind(Event $event, Query $query, ArrayObject $options ) {
$field = $this->_config['field'];
if( !in_array( $this->_primaryKey, $field ) ){
$field[] = $this->_primaryKey;
}
if ( empty( $field ) ) {
return;
}
if ( !empty( $field ) ) {
foreach( $field as $idField ){
$query->traverseExpressions(function (ExpressionInterface $expression) use ( $idField ){
if (method_exists($expression, 'getField')
&& ( $expression->getField() === $idField || $expression->getField() === $this->_table->alias() . '.' . $idField )
) {
/** @var \Cake\Database\Expression\Comparison $expression */
$expression->setValue( $this->decodeHashid( $expression->getValue() ) );
}
return $expression;
});
}
}
$query->find('hashed');
foreach ($this->_table->associations() as $association) {
if ($association->getTarget()->hasBehavior('Hashid') && $association->getFinder() === 'all') {
$association->setFinder('hashed');
}
}
}
/**
* @param \Cake\Event\Event $event The beforeSave event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return void
*/
// public function beforeRules( Event $event, EntityInterface $entity, ArrayObject $options ){
// }
/**
* @param \Cake\Event\Event $event The fixEncodings event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return void
*/
public function fixEncodings( EntityInterface $entity ) {
if( $entity->isNew() ){
return $entity;
}
$this->decode( $entity );
return $entity;
}
/**
* @param \Cake\Event\Event $event The fixEncodings event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return void
*/
public function encodeResultSet( EntityInterface $entity ) {
$field = $this->_config['field'];
if( !in_array( $this->_primaryKey, $field ) ){
$field[] = $this->_primaryKey;
}
foreach( $field as $key ){
if( isset( $entity[ $key ] ) ){
$entity[ $key ] = $this->encodeId( $entity[ $key ] );
}
}
return $entity;
}
/**
* @param \Cake\Event\Event $event The fixEncodings event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return void
*/
public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options){
if( $entity->isNew() ){
return $entity;
}
$this->decode( $entity );
}
/**
* @param \Cake\Event\Event $event The fixConditions event that was fired Manual Call to decode Conditions
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return void
*/
public function fixConditions( Array $conditions ) {
$field = $this->_config['field'];
if( !in_array( $this->_primaryKey, $field ) ){
$field[] = $this->_primaryKey;
}
if ( !empty( $field ) ) {
foreach( $field as $idField ){
if( isset( $conditions[ $idField ] ) && !is_numeric( $conditions[ $idField ] ) ){
$hashid = $conditions[ $idField ];
$id = $this->decodeHashid( $hashid );
$conditions[ $idField ] = $id;
}
}
}
return $conditions;
}
/**
* @param \Cake\Event\Event $event The beforeMarshal event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @param \ArrayObject $options
* @return void
*/
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) {
$field = $this->_config['field'];
if( !in_array( $this->_primaryKey, $field ) ){
$field[] = $this->_primaryKey;
}
if ( !empty( $field ) ) {
foreach( $field as $idField ){
if( isset( $data[ $idField ] ) && !is_numeric( $data[ $idField ] ) ){
$hashid = $data[ $idField ];
$id = $this->decodeHashid( $hashid );
$data[ $idField ] = $id;
}
}
}
}
/**
* Custom finder for hashids field.
*
* Options:
* - hid (required), best to use HashidBehavior::HID constant
* - noFirst (optional, to leave the query open for adjustments, no first() called)
*
* @param \Cake\ORM\Query $query Query.
* @param array $options Array of options as described above
* @return \Cake\ORM\Query
*/
public function findHashed(Query $query, array $options) {
$field = $this->_config['field'];
if( !in_array( $this->_primaryKey, $field ) ){
$field[] = $this->_primaryKey;
}
if ( empty( $field ) ) {
return $query;
}
$query->formatResults(function ( $results ) use ( $field ) {
$newResult = [];
$results->each( function ( $row, $key ) use ( $field, &$newResult ) {
foreach( $field as $idField ){
if ( !empty( $row[ $idField ] ) && is_numeric( $row[ $idField ] ) ) {
$row[ $idField ] = $this->encodeId( $row[ $idField ] );
if ( $row instanceof EntityInterface ) {
$row->setDirty( $idField, false );
}
} elseif ( is_string( $row ) ) {
$newResult[ $this->encodeId( $key ) ] = $row;
}
}
$newResult[] = $row;
});
return new Collection( $newResult );
});
if (!empty( $options[ static::HID ] ) ) {
$id = $this->decodeHashid( $options[ static::HID ] );
$query->where( [ $idField => $id ]);
}
$first = $this->_config['findFirst'] === true ? 'first' : $this->_config['findFirst'];
if ( !$first || !empty( $options['noFirst'] ) ) {
return $query;
}
return $query->first();
}
/**
* @param int $id
* @return string
*/
public function encodeId($id) {
if ($id < 0 || !is_numeric($id)) {
return $id;
}
$hashid = $this->_getHasher()->encode($id);
if ($this->_config['debug']) {
$hashid .= '-' . $id;
}
return $hashid;
}
/**
* Sets up hashid for model.
*
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @return bool True if save should proceed, false otherwise
*/
public function decode(EntityInterface $entity) {
$field = $this->_config['field'];
$field[] = $this->_primaryKey;
foreach( $field as $idField ){
$hashid = $entity->get( $idField );
if( $hashid && !is_numeric( $hashid ) ){
$id = $this->decodeHashid( $hashid );
$originalId = $entity->getOriginal( $idField );
$entity->set( $idField, $id);
if( $originalId == $id ){
$entity->setDirty( $idField, false );
} else {
$entity->setDirty( $idField, true );
}
}
}
}
/**
* @param string $hashid
* @return int
*/
public function decodeHashid($hashid) {
if ( is_array( $hashid ) ) {
foreach ($hashid as $k => $v) {
if( !is_numeric( $v ) ){
$hashid[ $k ] = $this->decodeHashid( $v );
}
}
return $hashid;
}
if ($this->_config['debug']) {
$hashid = substr($hashid, 0, strpos($hashid, '-'));
}
if( !is_numeric( $hashid ) ){
$ids = $this->_getHasher()->decode($hashid);
return array_shift($ids);
} else {
return $hashid;
}
}
/**
* @return \Hashids\Hashids
*/
protected function _getHasher() {
if (isset($this->_hashids)) {
return $this->_hashids;
}
if ( $this->_config['alphabet'] ) {
$this->_hashids = new Hashids($this->_config['salt'], $this->_config['minHashLength'], $this->_config['alphabet']);
} else {
$this->_hashids = new Hashids($this->_config['salt'], $this->_config['minHashLength']);
}
return $this->_hashids;
}
}
<file_sep>/src/Model/Entity/Post.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Post Entity
*
* @property int $id
* @property int $department_id
* @property int $user_id
* @property int $total_likes
* @property int $total_comments
* @property string $title
* @property string $details
* @property string $filejson
* @property bool $poststatus
* @property string $location
* @property string $latitude
* @property string $longitude
* @property string $country_id
* @property string $state_id
* @property string $city_id
* @property string $locality_id
* @property string $post_type
* @property \Cake\I18n\FrozenTime $created
* @property \Cake\I18n\FrozenTime $modified
*
* @property \App\Model\Entity\Department $department
* @property \App\Model\Entity\User $user
* @property \App\Model\Entity\Country $country
* @property \App\Model\Entity\State $state
* @property \App\Model\Entity\City $city
* @property \App\Model\Entity\Locality $locality
*/
class Post extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'department_id' => true,
'user_id' => true,
'total_upvotes' => true,
'total_score' => true,
'title' => true,
'details' => true,
'filejson' => true,
'poststatus' => true,
'location' => true,
'latitude' => true,
'longitude' => true,
'country_id' => true,
'state_id' => true,
'city_id' => true,
'locality_id' => true,
'post_type' => true,
'created' => true,
'modified' => true,
'department' => true,
'user' => true,
'country' => true,
'state' => true,
'city' => true,
'locality' => true
];
}
<file_sep>/src/Controller/FavLocationController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* FavLocation Controller
*
* @property \App\Model\Table\FavLocationTable $FavLocation
*
* @method \App\Model\Entity\FavLocation[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class FavLocationController extends AppController
{
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
if ( $this->request->is('post') ) {
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
$favLocationCheck = array();
if( isset( $postData['longitude'] ) && isset( $postData['latitude'] ) ){
$favLocationCheck = array( 'latitude' => $postData['latitude'], 'longitude' => $postData['longitude'], 'user_id' => $postData['user_id'], 'level' => $postData['level'] );
}
if( $this->FavLocation->exist( $favLocationCheck ) ){
$response = array( 'error' => 1, 'message' => 'Favourite Location Exists.', 'data' => array( 'exist' => true ) );
} else if( isset( $postData['longitude'] ) && isset( $postData['latitude'] ) ){
if( isset( $postData['countryShortName'] ) ){
$postData['country_code'] = $postData['countryShortName'];
unset( $postData['countryShortName'] );
}
$localeRes = array( 'error' => 1 );
if( !empty( $postData['locality'] ) ){
$localeRes = $this->FavLocation->Cities->Localities->findLocality( $postData );
} else if( !empty( $postData['city'] ) ){
$localeRes = $this->FavLocation->Cities->findCities( $postData );
} else if( !empty( $postData['state'] ) ){
$localeRes = $this->FavLocation->States->findStates( $postData );
} else if( !empty( $postData['country'] ) || !empty( $postData['country_code'] ) ){
$localeRes = $this->FavLocation->Countries->findCountry( $postData );
}
$saveData = array();
if( $localeRes['error'] == 0 ){
foreach ( $localeRes['data'] as $key => $locale ) {
if( isset( $locale[0] ) && isset( $locale[0]['locality_id'] ) )
$saveData['locality_id'] = $locale[0]['locality_id'];
if( isset( $locale[0] ) && isset( $locale[0]['city_id'] ) )
$saveData['city_id'] = $locale[0]['city_id'];
if( isset( $locale[0] ) && isset( $locale[0]['state_id'] ) )
$saveData['state_id'] = $locale[0]['state_id'];
if( isset( $locale[0] ) && isset( $locale[0]['country_id'] ) )
$saveData['country_id'] = $locale[0]['country_id'];
}
$saveData['user_id'] = $postData['user_id'];
if( isset( $postData[ 'latitude' ] ) )
$saveData[ 'latitude' ] = $postData[ 'latitude' ];
if( isset( $postData[ 'longitude' ] ) )
$saveData[ 'longitude' ] = $postData[ 'longitude' ];
if( isset( $postData[ 'level' ] ) )
$saveData[ 'level' ] = $postData[ 'level' ];
}
$return = $this->FavLocation->add( $saveData );
if( $return ){
$search = $this->FavLocation->buildDataForSearch( array( $return ) );
$result = $this->FavLocation->retrieveAddresses( $search );
$response = array( 'error' => 0, 'message' => 'Favourite Location Saved', 'data' => $result['data'] );
} else {
$response = array( 'error' => -1, 'message' => 'Please Try Again', 'data' => array() );
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
/**
* Edit method
*
* @param string|null $id Fav Location id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function get()
{
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
$userData = $this->FavLocation->User->getUserList( array( $_GET['userId'] ), array( 'id', 'default_location_id' ) );
$conditions = array( 'user_id' => $_GET['userId'] );
$isHome = $this->request->query('isHome');
if( $isHome ){
$conditions[] = array( 'id' => $userData[ $_GET['userId'] ]['default_location_id'] );
}
$wvFavLocations = $this->FavLocation->find('all', ['limit' => 200])->where( $conditions )->toArray();
if( !empty( $wvFavLocations ) ){
$search = $this->FavLocation->buildDataForSearch( $wvFavLocations, $userData[ $_GET['userId'] ] );
$ret = $this->FavLocation->retrieveAddresses( $search );
$response['data'] = $ret['data'];
} else {
$response = array( 'error' => 0, 'message' => 'No Favourite Locations', 'data' => array() );
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function delete(){
$response = array( 'error' => 1, 'message' => 'Request Failed', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
if( isset( $postData['latitude'] ) && isset( $postData['longitude'] ) && isset( $postData['level'] ) && $postData['latitude'] != 0 && $postData['longitude'] != 0 ){
if( $this->FavLocation->remove( array( $postData ) ) ){
$response = array( 'error' => 0, 'message' => 'Location Deleted Successfully.', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function checkExist(){
$response = array( 'error' => 1, 'message' => 'Request Failed', 'data' => array() );
$getData = $this->request->getQuery();
if( !empty( $getData ) ){
$getData['user_id'] = $_GET['userId'];
}
if( isset( $getData['latitude'] ) && isset( $getData['longitude'] ) && $getData['latitude'] != 0 && $getData['longitude'] != 0 ){
if( $this->FavLocation->exist( $getData ) ){
$response = array( 'error' => 0, 'message' => 'Exists', 'data' => array('exist' => true, 'notExist' => false) );
} else {
$response = array( 'error' => 0, 'message' => 'Does Not Exists', 'data' => array( 'exist' => false, 'notExist' => true) );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
public function setDefault(){
$response = array( 'error' => 1, 'message' => 'Request Failed', 'data' => array() );
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
$continue = false;
if( isset( $postData['latitude'] )
&& isset( $postData['longitude'] )
&& $postData['latitude'] != 0
&& $postData['longitude'] != 0 ){
$continue = true;
}
if( isset( $postData['favlocationId'] ) ){
$postData['id'] = $postData['favlocationId'];
unset( $postData['favlocationId'] );
$continue = true;
}
if( $continue ){
$record = $this->FavLocation->find()->where( $postData )->toArray();
if( !empty( $record ) && $record[0]->id ){
$search = $this->FavLocation->buildDataForSearch( $record );
$result = $this->FavLocation->retrieveAddresses( $search );
$user = array( 'id' => $postData['user_id'], 'default_location_id' => $record[0]->id, 'address' => $result['data'][0]['address_string'], 'latitude' => $result['data'][0]['latitude'], 'longitude' => $result['data'][0]['longitude'] );
$usersUpdated = $this->FavLocation->User->updateUser( array( $user ) );
if ( !empty( $usersUpdated ) ) {
$response = array( 'error' => 0, 'message' => 'Default Location Set', 'data' => array() );
}
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/db/schema/wv_fileuploads.sql
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jun 21, 2018 at 05:01 PM
-- Server version: 10.1.29-MariaDB-6
-- PHP Version: 7.0.29-1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `worldvoting`
--
-- --------------------------------------------------------
--
-- Table structure for table `fileuploads`
--
CREATE TABLE `fileuploads` (
`id` int(11) NOT NULL,
`filepath` varchar(256) NOT NULL,
`filetype` varchar(256) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `fileuploads`
--
INSERT INTO `fileuploads` (`id`, `filepath`, `filetype`, `created`, `modified`) VALUES
(5, '/var/www/worlvoting/webroot/img/upload/5a27990e44efe.jpg', 'image/jpeg', '2018-06-21 11:30:19', '2018-06-21 11:30:19'),
(6, '/var/www/worlvoting/webroot/img/upload/5a27990e44efe.jpg', 'image/jpeg', '2018-06-21 11:31:23', '2018-06-21 11:31:23');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `fileuploads`
--
ALTER TABLE `fileuploads`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `fileuploads`
--
ALTER TABLE `fileuploads`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/Middleware/AuthorizationMiddleware.php
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Cake\Core\Configure;
use Firebase\JWT\JWT;
use Cake\Core\Exception\Exception;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Exception\UnauthorizedException;
use Cake\ORM\TableRegistry;
/**
* Authorization middleware
*/
class AuthorizationMiddleware
{
/**
* Invoke method.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Message\ResponseInterface $response The response.
* @param callable $next Callback to invoke the next middleware.
* @return \Psr\Http\Message\ResponseInterface A response
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$flagAllow = false;
$allowedConActions = array();
$allowedConActions[] = array( 'controller' => 'User', 'action' => 'login' );
$allowedConActions[] = array( 'controller' => 'User', 'action' => 'signup' );
$allowedConActions[] = array( 'controller' => 'User', 'action' => 'forgotpassword' );
$allowedConActions[] = array( 'controller' => 'Post', 'action' => 'getfeed' );
$allowedConActions[] = array( 'controller' => 'Post', 'action' => 'getpost' );
$allowedConActions[] = array( 'controller' => 'User', 'action' => 'emailVerification' );
$allowedConActions[] = array( 'controller' => 'User', 'action' => 'userexists' );
$allowedConActions[] = array( 'controller' => 'Localities', 'action' => 'get' );
$allowedConActions[] = array( 'controller' => 'AreaRatings', 'action' => 'getdatewiseratings' );
foreach( $allowedConActions as $conActions ){
if( $conActions['controller'] == $request->getParam('controller') && $conActions['action'] == $request->getParam('action') ){
$flagAllow = true;
break;
}
}
$oauth = TableRegistry::get('Oauth');
$authHeader = $request->getHeader('authorization');
if( !$flagAllow || $authHeader ){
$errorRes = array( 'error' => 1, 'message' => '' );
if ($authHeader) {
list( $jwt ) = sscanf( $authHeader[0], ': Bearer %s' );
if ( $jwt ) {
try {
$secretKey = Configure::read( 'jwt_secret_key' );
$token = JWT::decode( $jwt, $secretKey, array('HS512') );
if( $oauth->validateToken( $token ) ){
$_POST['userId'] = $token->user_id;
$_POST['accessRoleIds'] = $token->access_roles;
$_GET['userId'] = $token->user_id;
$_GET['accessRoleIds'] = $token->access_roles;
$response = $next( $request, $response );
} else {
$error = new Exception(__('Token Expired'));
$error->responseHeader('Access-Control-Allow-Origin','*');
throw $error;
}
} catch (Exception $e) {
$error = new UnauthorizedException(__('Illegal Token'));
$error->responseHeader('Access-Control-Allow-Origin','*');
throw $error;
}
} else {
$error = new BadRequestException(__('Bad request'));
$error->responseHeader('Access-Control-Allow-Origin','*');
throw $error;
}
} else {
$error = new BadRequestException(__('Bad request'));
$error->responseHeader('Access-Control-Allow-Origin','*');
throw $error;
}
} else {
$response = $next($request, $response);
}
return $response;
}
}
<file_sep>/src/Controller/Component/FilesComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
/**
* Files component
*/
class FilesComponent extends Component
{
/**
* Default configuration.
*
* @var array
*/
protected $_defaultConfig = [];
function saveFile( $file = null ){
$retval = false;
if( $file != null ){
$filePath = 'img' . DS . 'upload' . DS . $file['name'];
$fileUrl = WWW_ROOT . DS . $filePath;
$localFileUrl = 'webroot' . DS . $filePath;
$fileArr = array(
'fileurl' => $filePath,
'filetype' => $file['type'],
'size' => $file['size']
);
if( move_uploaded_file( $file['tmp_name'], $fileUrl ) ){
$retval = array( 'filepath' => $localFileUrl, 'filetype' => $file['type'] );
}
}
return $retval;
}
}
<file_sep>/src/Controller/FileuploadsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Fileuploads Controller
*
* @property \App\Model\Table\FileuploadsTable $Fileuploads
*
* @method \App\Model\Entity\Fileupload[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class FileuploadsController extends AppController
{
public $components = array('Files');
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if ($this->request->is('post')) {
$fileData = array();
if( !empty( $this->request->getData('file') ) ){
$result = $this->Files->saveFile( $this->request->getData('file') );
if( $result ){
$fileData[] = $result;
}
}
$lastInsertId = $this->Fileuploads->saveFiles($fileData);
if ( $lastInsertId != null ) {
$response = array( 'error' => 0, 'message' => 'File Uploaded', 'data' => array( 'fileId' => $lastInsertId, 'filepath' => $result['filepath'] ) );
} else {
$response = array( 'error' => 1, 'message' => 'Error', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/db/data/11/postDropColoumns.sql
ALTER TABLE `post`
DROP `total_likes`,
DROP `total_comments`;
<file_sep>/src/Model/Behavior/ArrayOpsBehavior.php
<?php
namespace App\Model\Behavior;
use Cake\ORM\Behavior;
use Cake\ORM\Table;
/**
* ArrayOps behavior
*/
class ArrayOpsBehavior extends Behavior
{
/**
* Default configuration.
*
* @var array
*/
protected $_defaultConfig = [];
public function array_group_by( array $array, $key ) {
if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key) ) {
trigger_error('array_group_by(): The key should be a string, an integer, or a callback', E_USER_ERROR);
return null;
}
$func = (!is_string($key) && is_callable($key) ? $key : null);
$_key = $key;
// Load the new array, splitting by the target key
$grouped = [];
foreach ($array as $value) {
$key = null;
if (is_callable($func)) {
$key = call_user_func($func, $value);
} elseif (is_object($value) && isset($value->{$_key})) {
$key = $value->{$_key};
} elseif (isset($value[$_key])) {
$key = $value[$_key];
}
if ($key === null) {
continue;
}
$grouped[$key][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$params = array_merge([ $value ], array_slice($args, 2, func_num_args()));
// call_user_func_array('array_group_by', $params);
$grouped[$key] = $this->array_group_by( $params[0], $params[1] );
}
}
return $grouped;
}
}
<file_sep>/src/Model/Table/AreaRatingsTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;
use Cake\I18n\Time;
/**
* AreaRatings Model
*
* @property \App\Model\Table\AreaLevelsTable|\Cake\ORM\Association\BelongsTo $AreaLevels
* @property \App\Model\Table\UsersTable|\Cake\ORM\Association\BelongsTo $Users
*
* @method \App\Model\Entity\AreaRating get($primaryKey, $options = [])
* @method \App\Model\Entity\AreaRating newEntity($data = null, array $options = [])
* @method \App\Model\Entity\AreaRating[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\AreaRating|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\AreaRating|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\AreaRating patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\AreaRating[] patchEntities($entities, array $data, array $options = [])
* @method \App\Model\Entity\AreaRating findOrCreate($search, callable $callback = null, $options = [])
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class AreaRatingsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('area_ratings');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('HashId', ['field' => array( 'user_id', 'area_level_id' ) ]);
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('area_level')
->requirePresence('area_level', 'create')
->notEmpty('area_level');
$validator
->requirePresence('good', 'create')
->notEmpty('good');
$validator
->requirePresence('bad', 'create')
->notEmpty('bad');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
// $rules->add($rules->existsIn(['area_level_id'], 'AreaLevels'));
// $rules->add($rules->existsIn(['user_id'], 'Users'));
return $rules;
}
public function saveratings( $saveData = array() ){
$return = false;
if( !empty( $saveData ) ){
$areaRate = TableRegistry::get('AreaRatings');
$query = $areaRate->find('all')->where([
'user_id' => $saveData['user_id'],
'area_level_id' => $saveData['area_level_id'],
'area_level' => $saveData['area_level'],
'modified BETWEEN NOW() -INTERVAL 1 DAY AND NOW()'
]);
$entity = $query->first();
if( !empty( $entity ) ){
return $return;
} else {
$entity = $areaRate->newEntity();
$entity = $areaRate->patchEntity( $entity, $saveData );
$entity = $this->fixEncodings( $entity );
}
try {
$record = $areaRate->save( $entity );
if( isset( $record->id ) ){
$return = $this->encodeResultSet( $record );
}
} catch (\PDOException $e) {
return $return;
}
}
return $return;
}
public function getRatings( $areaLevel = null, $areaLevelId = null, $userId = null ){
$response = array( 'areaLevel' => $areaLevel, 'areaLevelId' => $areaLevelId, 'goodPercent' => 0, 'badPercent' => 0, 'userStatus' => false );
if( ( $areaLevelId != null && $areaLevel != null ) || ( $areaLevelId == 0 && $areaLevel == 'world' ) ){
$areaRating = $this->find('all')->where([
'area_level' => $areaLevel,
'area_level_id' => $areaLevelId,
'modified BETWEEN NOW() -INTERVAL 1 DAY AND NOW()'
]);
$totalCount = 0; $goodCount = 0; $badCount = 0; $userStatus = false;
$goodPercent = 0; $badPercent = 0;
foreach( $areaRating as $key => $rating ){
if( $rating->good > 0 ){
$goodCount++;
$totalCount++;
}
if( $rating->bad > 0 ){
$badCount++;
$totalCount++;
}
if( $userId == $rating->user_id )
$userStatus = true;
}
if( $totalCount != 0 ){
$goodPercent = round( $goodCount * 100 / $totalCount );
$badPercent = round( $badCount * 100 / $totalCount );
}
$response = array(
'areaLevel' => $areaLevel,
'areaLevelId' => $areaLevelId,
'goodPercent' => $goodPercent,
'badPercent' => $badPercent,
'userStatus' => $userStatus
);
}
return $response;
}
public function getDateWiseRatings( $param ){
$response = array();
if( ( $param['areaLevelId'] != null && $param['areaLevel'] != null ) || ( $param['areaLevelId'] == 0 && $param['areaLevel'] == 'world' ) ){
$areaRating = $this->find('all')->where([
'area_level' => $param['areaLevel'],
'area_level_id' => $param['areaLevelId'],
'modified BETWEEN NOW() - INTERVAL 7 DAY AND NOW()'
])->toArray();
if( !empty( $areaRating ) ){
foreach( $areaRating as $key => $areaRate ){
$created = $areaRate->created->i18nFormat('yyyy-MM-dd');
if( !isset( $response[ $created ] ) ){
$response[ $created ] = array( 'goodPercent' => 0, 'badPercent' => 0, 'goodCount' => 0, 'badCount' => 0, 'totalCount' => 0 );
}
if( $areaRate->good > 0 ){
$response[ $created ]['goodCount']++;
$response[ $created ]['totalCount']++;
}
if( $areaRate->bad > 0 ){
$response[ $created ]['badCount']++;
$response[ $created ]['totalCount']++;
}
if( $response[ $created ]['totalCount'] > 0 ){
$response[ $created ]['goodPercent'] = round( $response[ $created ]['goodCount'] * 100 / $response[ $created ]['totalCount'] );
$response[ $created ]['badPercent'] = round( $response[ $created ]['badCount'] * 100 / $response[ $created ]['totalCount'] );
}
}
}
}
return $response;
}
}
<file_sep>/src/Controller/UserPollsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* UserPolls Controller
*
* @property \App\Model\Table\UserPollsTable $UserPolls
*
* @method \App\Model\Entity\UserPoll[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class UserPollsController extends AppController
{
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$response = array( 'error' => 1, 'message' => 'Invalid Request', 'data' => array() );
if ( $this->request->is('post') ) {
$postData = $this->request->input('json_decode', true);
if( !empty( $postData ) ){
$postData['user_id'] = $_POST['userId'];
} else {
$postData = $this->request->getData();
}
if( !empty( $postData ) ){
if( $this->UserPolls->saveUserPolls( $postData ) ){
$polls = $this->UserPolls->Polls->getPolls( array( $postData['post_id'] ), $postData['user_id'] );
$polls = array_values( $polls );
$response = array( 'error' => 0, 'message' => 'Poll Submitted', 'data' => $polls );
}
} else {
$response = array( 'error' => 1, 'message' => 'Error', 'data' => array() );
}
}
$this->response = $this->response->withType('application/json')
->withStringBody( json_encode( $response ) );
return $this->response;
}
}
<file_sep>/tests/TestCase/Model/Table/LocalitiesTableTest.php
<?php
namespace App\Test\TestCase\Model\Table;
use App\Model\Table\LocalitiesTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
/**
* App\Model\Table\LocalitiesTable Test Case
*/
class LocalitiesTableTest extends TestCase
{
/**
* Test subject
*
* @var \App\Model\Table\LocalitiesTable
*/
public $Localities;
/**
* Fixtures
*
* @var array
*/
public $fixtures = [
'app.localities',
'app.cities'
];
/**
* setUp method
*
* @return void
*/
public function setUp()
{
parent::setUp();
$config = TableRegistry::getTableLocator()->exists('Localities') ? [] : ['className' => LocalitiesTable::class];
$this->Localities = TableRegistry::getTableLocator()->get('Localities', $config);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown()
{
unset($this->Localities);
parent::tearDown();
}
/**
* Test initialize method
*
* @return void
*/
public function testInitialize()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test validationDefault method
*
* @return void
*/
public function testValidationDefault()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test buildRules method
*
* @return void
*/
public function testBuildRules()
{
$this->markTestIncomplete('Not implemented yet.');
}
}
<file_sep>/db/data/7/modifiedCollationOfMysqlDB.sql
SET collation_connection = 'utf8_unicode_ci';
ALTER DATABASE `worldvoting` CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `access_roles` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `activitylog` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `cities` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `countries` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `departments` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `details_reviews` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `fav_location` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `fileuploads` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `localities` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `login_record` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `oauth` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `post` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `state_reviews` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `states` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `votes_reviews` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `user` CHANGE `firstname` `firstname` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `user` CHANGE `lastname` `lastname` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `user` CHANGE `gender` `gender` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `email` `email` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `user` CHANGE `password` `password` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `user` CHANGE `phone` `phone` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `address` `address` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `latitude` `latitude` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `longitude` `longitude` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `profilepic` `profilepic` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `access_role_ids` `access_role_ids` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `user` CHANGE `rwa_name` `rwa_name` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `designation` `designation` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CHANGE `certificate` `certificate` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER TABLE `user` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
<file_sep>/db/data/16/addAuthorityFlagInActivityLog.sql
ALTER TABLE `activitylog` ADD `authority_flag` TINYINT NOT NULL DEFAULT '0' AFTER `eyewitness`;
<file_sep>/src/Controller/Component/OAuthComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use Cake\ORM\TableRegistry;
/**
* OAuth component
*/
class OAuthComponent extends Component
{
/**
* Default configuration.
*
* @var array
*/
protected $_defaultConfig = [];
public function getAccessToken( $userId = null ){
$response = array( 'error' => 0, 'message' => '', 'data' => array() );
if( $userId != null ){
$this->Oauth = TableRegistry::get('Oauth');
$result = $this->Oauth->getUserToken( $userId );
if( $result['error'] == -1 ){
$result = $this->Oauth->refreshAccessToken( $userId );
} else if( $result['error'] == 1 ){
$result = $this->Oauth->createUserToken( $userId );
}
if( $result['error'] == 0 ){
$response['message'] = 'Access Token Generated';
$response['data'] = $result['data'];
} else {
$response['error'] = 1;
$response['message'] = 'Failed! Please Try Again.';
}
}
return $response;
}
public function removeToken( $userId = null ){
$response = array( 'error' => 0, 'message' => 'Invalid Request', 'data' => array() );
if( $userId != null ){
$this->Oauth = TableRegistry::get('Oauth');
$result = $this->Oauth->deleteUserToken( $userId );
if( $result )
$response = array( 'error' => 0, 'message' => 'Logout Successful', 'data' => array() );
else
$response = array( 'error' => 1, 'message' => 'Logout Failed', 'data' => array() );
}
return $response;
}
}
<file_sep>/src/Middleware/CorsMiddleware.php
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Cors middleware
*/
class CorsMiddleware
{
/**
* Invoke method.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Message\ResponseInterface $response The response.
* @param callable $next Callback to invoke the next middleware.
* @return \Psr\Http\Message\ResponseInterface A response
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) {
if( $request->is('options') ){
return $response->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Methods', 'DELETE, GET, OPTIONS, PATCH, POST, PUT')
->withHeader('Access-Control-Allow-Headers', 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Max-Age', '3600');
} else {
return $next($request, $response)->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Methods', 'DELETE, GET, OPTIONS, PATCH, POST, PUT')
->withHeader('Access-Control-Allow-Headers', 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token')
->withHeader('Access-Control-Expose-Headers', 'Authorization, Content-Type')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Max-Age', '3600');
}
}
}
| 45fe0ae5a96cf41397c5dc1a6b2deb7bb8271f4e | [
"SQL",
"PHP"
] | 61 | SQL | crossdsection/irshaad-backend | 93197cdef61056d2099e86e77d459c112b35c495 | 0e1330ce5d88cc1210c1c9aefc22a09443b060aa |
refs/heads/master | <repo_name>Sjhb/vuex-demo1<file_sep>/src/mock/product.js
const products = [
{
id: 1,
name: '童装/女童 袜子(2双装) 405454 优衣库UNIQLO',
source: '//g-search2.alicdn.com/img/bao/uploaded/i4/i3/196993935/TB1w4LVfaLN8KJjSZFmXXcQ6XXa_!!0-item_pic.jpg_360x360Q90.jpg_.webp',
price: '35.00',
brand: '优衣库'
},
{
id: 2,
name: '羊毛袜子浪莎秋冬款加厚袜子男短袜兔羊毛女袜中筒袜冬季保暖男袜',
source: '//g-search1.alicdn.com/img/bao/uploaded/i4/i1/272715291/O1CN011oxK3fJbsBD9Hmh_!!0-item_pic.jpg',
price: '59.00',
brand: '浪莎官方旗舰店'
},
{
id: 3,
name: '金利来袜子男士纯棉中筒棉袜秋冬全棉防臭吸汗薄棉袜长袜秋季短袜',
source: '//g-search3.alicdn.com/img/bao/uploaded/i4/i3/917226893/O1CN01voR4P820n2YZLrGIF_!!0-item_pic.jpg_460x460Q90.jpg_.webp',
price: '49.00',
brand: '金利来内衣旗舰店'
},
{
id: 4,
name: '【双十一】佳丽宝Kanebo连裤袜110D*3双装 日本进口保暖',
source: '//g-search2.alicdn.com/img/bao/uploaded/i4/i4/2575956766/O1CN011zqsFX7RtJWOqMe_!!0-item_pic.jpg_460x460Q90.jpg_.webp',
price: '129.00',
brand: '佳丽宝官方旗舰店'
},
{
id: 5,
name: 'GU男装秋冬保暖短袜松紧口袜子(3双装) 柔软舒适短袜297434极优',
source: '//g-search1.alicdn.com/img/bao/uploaded/i4/imgextra/i1/32888477/O1CN01ECV5vx2CUVvP9rtIM_!!0-saturn_solar.jpg_460x460Q90.jpg_.webp',
price: '39.00',
brand: 'gu官方旗舰店'
},
{
id: 6,
name: 'MONKI2018新款时尚女装舒适彩虹白色棉质袜子女 0382392',
source: '//g-search1.alicdn.com/img/bao/uploaded/i4/i4/2668714578/O1CN011jglf4wT9348eli_!!0-item_pic.jpg',
price: '39.00',
brand: 'monki官方旗舰店'
},
{
id: 7,
name: '七匹狼袜子男纯棉秋季中筒袜 冬季防臭棉袜 吸汗黑色长袜长筒男袜',
source: '//g-search1.alicdn.com/img/bao/uploaded/i4/i1/2257481247/O1CN011L5ALYUXOuXwZrX_!!2257481247.jpg',
price: '129.00',
brand: '佳丽宝官方旗舰店'
},
{
id: 8,
name: '【双十一】佳丽宝Kanebo连裤袜110D*3双装 日本进口保暖',
source: '//g-search1.alicdn.com/img/bao/uploaded/i4/imgextra/i1/32888477/O1CN01ECV5vx2CUVvP9rtIM_!!0-saturn_solar.jpg_460x460Q90.jpg_.webp',
price: '49.00',
brand: '未完待续125810'
}
]
export function getAllProduct () {
return new Promise((resolve) => {
setTimeout(() => {
resolve(products)
}, 1000)
})
}
<file_sep>/src/mock/index.js
export * from './product.js'
<file_sep>/tests/unit/example.spec.js
import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'
describe('Counter.vue', () => {
const wrapper = shallowMount(Counter, {
propsData: {
initNum: 3
}
})
const p = wrapper.find('p')
const buttons = wrapper.findAll('button')
it('render', () => {
expect(p.text()).to.equal('3')
expect(buttons.length).to.equal(2)
})
it('add', () => {
const addButton = buttons.at(0)
addButton.trigger('click')
expect(p.text()).to.equal('4')
})
it('reduce', () => {
const reduceButton = buttons.at(1)
reduceButton.trigger('click')
expect(p.text()).to.equal('3')
})
})
<file_sep>/src/router.js
import Vue from 'vue'
import Router from 'vue-router'
import prodList from './views/prodList.vue'
import prodDetail from './views/prodDetail.vue'
import cart from './views/cart.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'prodList',
component: prodList
},
{
path: '/prodDetail',
name: 'prodDetail',
component: prodDetail
},
{
path: '/cart',
name: 'cart',
component: cart
}
]
})
| 223adf7572ac656bb3d88a7758fab9805b5927bf | [
"JavaScript"
] | 4 | JavaScript | Sjhb/vuex-demo1 | f96bbb585111aa62f9635b3f2d3fafe479596a33 | ae551feb1ac762be03426f17298db97a95762f05 |
refs/heads/master | <repo_name>AdamJayPressel/space_invaders<file_sep>/asteroid.py
#!/usr/bin/python
import pygame
from pygame.locals import *
from colors import *
from random import *
WIDTH = 400
HEIGHT = 647
class Asteroid(pygame.sprite.Sprite):
#create asteroid object and give it initial position and velocity
def __init__(self):
super(Asteroid, self).__init__()
self.image = pygame.image.load('asteroid.png')
self.image = pygame.transform.scale(self.image, (50,50))
self.rect = self.image.get_rect()
self.rect.x = randrange(0,WIDTH)
self.rect.y = randrange(0,30)
self.vy = randint(1,5)
self.vx = randint(-1,1)
#create how asteroid will move with time
def update(self):
self.rect.x += self.vx
self.rect.y += self.vy
if (self.rect.x > WIDTH):
self.rect.x = 0
elif (self.rect.x < 0):
self.rect.x = WIDTH
elif (self.rect.y > HEIGHT):
self.rect.y = 0
def draw(self,surf):
surf.blit(self.image, self.rect)
def off_screen(self):
off = false
if(self.rect.centerx > WIDTH):
off = true
if(self.rect.centerx < 0):
off = true
if(self.rect.centery > HEIGHT):
off = true
return off
<file_sep>/serial_code/serial_code.ino
#define X_IN A2
#define Y_IN A1
#define butt 7
void setup(){
Serial.begin(9600);
pinMode(butt, INPUT);
}
void loop(){
int x,y,button;
char c;
//read pot voltages
x = analogRead(X_IN);
y = analogRead(Y_IN);
button = digitalRead(butt);
x = map(x, 0, 1023, 0, 10) - 5;
y = map(y, 0, 1023, 0, 10) - 5;
// if somebody wants the data
if(Serial.available()>0){
//send the r,g,b values
c = Serial.read();
if (c == 'p'){
Serial.print(x);
Serial.print(',');
Serial.print(y);
Serial.print(',');
Serial.println(button);
}
//finish the transimission with /n
}
}
<file_sep>/colors.py
BLACK = (20,20,20)
WHITE = (255,255,255)
ASTEROID_COLOR = (42, 42, 42)
<file_sep>/game.py
#!/usr/bin/python
import pygame, sys, time, random, serial
from pygame.locals import *
from colors import *
import stars, spaceship, asteroid
FPS = 30
HEIGHT = 647
WIDTH = 400
MAX_STARS = 20
MAX_ASTEROIDS = 4
LEVEL = 0.5
s = serial.Serial("/dev/ttyACM0", 9600, timeout = 0.5)
#s.open()
def main():
pygame.init()
fpsClock = pygame.time.Clock()
# Create Screen Object
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Space Invaders')
asteroid_group = pygame.sprite.Group()
dead = []
# Create Game Objects
liststars = []
for i in range(MAX_STARS):
star = stars.Star()
liststars.append(star)
#asteroid_list = pygame.sprite.Group()
the_ship = spaceship.Spaceship()
for i in range(MAX_ASTEROIDS):
the_asteroid = asteroid.Asteroid()
asteroid_group.add(the_asteroid)
while True:
#make asteroids
if(len(asteroid_group)<MAX_ASTEROIDS):
the_asteroid = asteroid.Asteroid()
asteroid_group.add(the_asteroid)
velocity = serial_in()
print(velocity)
the_ship.Vx = velocity[0]
the_ship.Vy = -1*velocity[1]
if (velocity[2] == 0):
dead = [1, 1]
# Process Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
the_ship.Vy -= 1
if the_ship.Vy < -5:
the_ship.Vy = -5
elif event.key == pygame.K_DOWN:
the_ship.Vy += 1
if the_ship.Vy > 5:
the_ship.Vy = 5
elif event.key == pygame.K_LEFT:
the_ship.Vx -= 1
if the_ship.Vx < -5:
the_ship.Vx = -5
elif event.key == pygame.K_RIGHT:
the_ship.Vx += 1
if the_ship.Vx > 5:
the_ship.Vx = 5
elif event.key == pygame.K_SPACE:
the_ship.fire()
if len(dead) > 0:
end_game(screen)
s.write('p')
pygame.quit
sys.exit()
else:
# Update game logic
map(lambda star: star.move(screen), liststars)
pygame.sprite.groupcollide(the_ship.phasor_list, asteroid_group, True, True)
for rock in asteroid_group:
if rock.off_screen:
rock.kill
dead = pygame.sprite.spritecollide(the_ship, asteroid_group, True)
#draw world
asteroid_group.update()
the_ship.update()
# Draw updated World
draw(screen)
the_ship.draw(screen)
asteroid_group.draw(screen)
pygame.display.update()
fpsClock.tick(FPS)
def end_game(surf):
draw(surf)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('GAME OVER', True, WHITE)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (WIDTH/2,HEIGHT/2)
surf.blit(textSurfaceObj, textRectObj)
pygame.display.update()
time.sleep(2.0)
def serial_in():
s.write('p')
l = s.readline()
if(len(l)>0):
data = [int(x) for x in l.split(',')]
else:
data = [0, 0, 1]
return data
def draw(surf):
#1 Draw the sky with a fill
surf.fill(BLACK)
#2 Add the game title
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('Space Invaders', True, WHITE)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (WIDTH/2,25)
surf.blit(textSurfaceObj, textRectObj)
main()
s.close()
<file_sep>/stars.py
import pygame, sys
from random import randrange
from pygame.locals import *
from colors import *
WIDTH = 400
HEIGHT = 648
class Star:
def __init__(self):
self.x = randrange(0,WIDTH - 1)
self.y = randrange(0,HEIGHT - 1)
self.vy = 2
self.star = (self.x,self.y)
def move(self, screen):
self.y += self.vy # just change star pixel position by vy
if(self.y >= HEIGHT):# Return the star if it crosses bottom border
self.y = 0
self.x = randrange(0,WIDTH-1)
self.star = (self.x,self.y)
screen.set_at(self.star,(WHITE))
pygame.display.update()
<file_sep>/spaceship.py
#!/usr/bin/python
import pygame
from pygame.locals import *
from colors import *
HEIGHT = 647
WIDTH = 400
class Spaceship(pygame.sprite.Sprite):
def __init__(self):
super(Spaceship, self).__init__() #call the parent class contructor
self.Vx = 0
self.Vy = 0
self.image = pygame.image.load('spaceship.png') #creates surface
self.image = pygame.transform.scale(self.image, (100, 100))
self.image.set_colorkey(WHITE) #set 'colorkey' of surface, this lets the black parts of the picture be transparent
self.rect = self.image.get_rect()
self.rect.center = (200, 600) #initializes center of the spaceship
self.phasor_list = pygame.sprite.Group() #creates a group for all phasor's
def update(self): #moves spaceship and phasors
if(self.rect.left > WIDTH):
self.rect.right = 0
elif(self.rect.right < 0):
self.rect.left = WIDTH
elif(self.rect.top > HEIGHT):
self.rect.bottom = 0
elif(self.rect.bottom < 0):
self.rect.top = HEIGHT
self.rect = self.rect.move(self.Vx, self.Vy)
def isHit(self):
#TODO
return false
def fire(self):
phasor = Phasor(self.rect.midtop) #instanciates a new phasor at the top/middle of the spaceship
self.phasor_list.add(phasor)
def draw(self, surf):
#draw image on surface
surf.blit(self.image, self.rect)
#update and draw phasors
for phasor in self.phasor_list:
phasor.move()
if phasor.rect.bottom < 10:
phasor.kill()
else:
surf.blit(phasor.image, phasor.rect)
#NOT FOR USER, PRIVATE CLASS TO SPACESHIP MODULE
class Phasor(pygame.sprite.Sprite):
def __init__(self, (x, y)): #pass in the top middle of the spaceship
super(Phasor, self).__init__()
self.image = pygame.image.load('phasor.png')
self.image = pygame.transform.scale(self.image, (5, 20))
self.rect = self.image.get_rect()
self.rect.midbottom = (x,y)
def move(self): #moves 3 pixels per call
self.rect.y -=25
| 110e4db687feb9d8b82dd11335a60e257bef5997 | [
"Python",
"C++"
] | 6 | Python | AdamJayPressel/space_invaders | b38e0851f171e3605706b309d93514bbccb9c95b | 681c45465a7e08dc1ad8f3e692bab550da879f00 |
refs/heads/master | <file_sep>using System;
using System.Collections;
namespace Balanced_Parenthesis
{
class Logic
{
ArrayList openbrackets;
ArrayList closebrackets;
public Logic()
{
openbrackets = new ArrayList();
openbrackets.Add('(');
openbrackets.Add('{');
openbrackets.Add('[');
openbrackets.Add('<');
closebrackets = new ArrayList();
closebrackets.Add(')');
closebrackets.Add('}');
closebrackets.Add(']');
closebrackets.Add('>');
}
public bool IsBalanced(string input)
{
Stack open = new Stack();
foreach(char x in input)
{
if (openbrackets.Contains(x))
{
open.Push(x);
}
if (closebrackets.Contains(x))
{
if(open.Count == 0)
{
return false;
}
if(!IsCombination((char)open.Pop(), x))
{
return false;
}
}
}
if(open.Count == 0)
{
return true;
}
else
{
return false;
}
}
public bool IsCombination(char a, char b)
{
switch(a)
{
case '(':
if (b.Equals(')'))
{
return true;
}
break;
case '[':
if (b.Equals(']'))
{
return true;
}
break;
case '{':
if (b.Equals('}'))
{
return true;
}
break;
case '<':
if (b.Equals('>'))
{
return true;
}
break;
default:
Console.WriteLine("Wrong Input");
break;
}
return false;
}
}
}
| 5a44d962dfc6e93d31803f021e86f0c19bb60228 | [
"C#"
] | 1 | C# | anandvadaje/Balanced-Parentheses | 416c220e72a947d16ef22fb67bfe79b5ac01c9d1 | fa7689e886009bda7335672f81a88c4a15aa0b4f |
refs/heads/main | <file_sep>function derivative(f) {
return x => {
let h = 0.000001
return (f(x + h) - f(x)) / h
}
}
[1.0, 2.0, 3.0, 4.0, 5.0].map(derivative(x => x * x))
[1.0, 2.0, 3.0, 4.0, 5.0].map(x => 2 * x) | e80c48f605d236c1be8a5baa16a3178752deeafc | [
"JavaScript"
] | 1 | JavaScript | Aemiii91/pp-exercises | 54338e2c8f972e6626c657a9873d322fd9d6acad | 0c6bec9ac725fc39960090774fe59cfebdf9f63d |
refs/heads/main | <repo_name>kilwa0/initrepo<file_sep>/github/repository.go
package github
import (
"context"
"github.com/google/go-github/v34/github"
"log"
"os"
"path/filepath"
)
const (
Separator = os.PathSeparator
ListSeparator = os.PathListSeparator
)
func CreateRepo(client *github.Client, org string) *github.Repository {
ctx := context.Background()
dir, err := os.Getwd()
if err != nil {
log.Printf("[ERROR] %s", err)
}
repoPath := filepath.Base(dir)
repo := &github.Repository{
Name: github.String(repoPath),
Private: github.Bool(false),
}
create, _, err := client.Repositories.Create(ctx, org, repo)
if err != nil {
log.Printf("[ERROR] %s", err)
}
return create
}
func DeleteRepo(client *github.Client, org string) *github.Response {
ctx := context.Background()
if org == "" {
user, _, err := client.Users.Get(ctx, "")
if err != nil {
log.Printf("[ERROR] %s", err)
}
org = *user.Login
}
dir, err := os.Getwd()
if err != nil {
log.Printf("[ERROR] %s", err)
}
repoPath := filepath.Base(dir)
del, err := client.Repositories.Delete(ctx, org, repoPath)
if err != nil {
log.Printf("[ERROR] %s", err)
}
return del
}
<file_sep>/README.md
# Initrepo
Quick and dirty create and initiates Github repo
## How to get it
git clone https://github.com/kilwa0/initrepo
### Prerequisites
You need go version 1.16 o higher \
also a github account
### Installation
```sh
go install github.com/kilwa0/initrepo
```
### Build
go build
<file_sep>/github/user.go
package github
import (
"context"
"github.com/google/go-github/v34/github"
"log"
)
func ListUserRepos(client *github.Client, user string, perpage int) []string {
ctx := context.Background()
opts := &github.RepositoryListOptions{
ListOptions: github.ListOptions{PerPage: perpage, Page: 1},
}
var allReposName []string
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.List(ctx, user, opts)
if err != nil {
log.Printf("[ERROR] %s", err)
}
allRepos = append(allRepos, repos...)
opts.Page = resp.NextPage
if resp.NextPage == 0 {
break
}
}
for index := range allRepos {
allReposName = append(allReposName, allRepos[index].GetFullName())
}
userLogin, _, err := client.Users.Get(ctx, "")
if err != nil {
log.Printf("[ERROR] %s", err)
}
for index, repoName := range allReposName {
if repoName == userLogin.GetLogin()+"/"+userLogin.GetLogin() {
allReposName[index] = allReposName[len(allReposName)-1]
allReposName[len(allReposName)-1] = ""
allReposName = allReposName[:len(allReposName)-1]
}
}
return allReposName
}
func GetUser(client *github.Client, user string) *github.User {
ctx := context.Background()
// var username string
userGet, _, err := client.Users.Get(ctx, user)
if err != nil {
log.Printf("[ERROR] %s", err)
}
return userGet
}
<file_sep>/github/connect.go
package github
import (
"context"
"github.com/google/go-github/v34/github"
"golang.org/x/oauth2"
"log"
)
func Connect(token string) *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
return client
}
func ConnectEnterprise(token string, url string) *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client, err := github.NewEnterpriseClient(url, url, tc)
if err != nil {
log.Printf("[ERROR] %s", err)
}
return client
}
<file_sep>/go.mod
module github.com/kilwa0/initrepo
go 1.16
require (
github.com/google/go-github/v34 v34.0.0
golang.org/x/oauth2 v0.0.0-20210413134643-5e61552d6c78
)
<file_sep>/main.go
package main
import (
"context"
"flag"
"fmt"
meta "github.com/google/go-github/v34/github"
"github.com/kilwa0/initrepo/github"
"log"
)
func main() {
var user, token, action, org, host string
flag.StringVar(&token, "token", "", "Github secret token")
flag.StringVar(&user, "user", "", "Github User")
flag.StringVar(&org, "organization", "", "Gihub Organization, if empty defaults to user")
flag.StringVar(&action, "action", "repositories", `usage:
[create, delete, repositories]`)
flag.StringVar(&host, "host", "", "Github Host")
flag.Parse()
ctx := context.Background()
var client *meta.Client
if host == "" {
client = github.Connect(token)
host = "github.com"
} else {
client = github.ConnectEnterprise(token, "https://"+host)
}
usr, _, err := client.Users.Get(ctx, "")
if err != nil {
log.Printf("[ERROR] %s", err)
}
switch action {
case "repositories":
var repositories []string
repositories = github.ListUserRepos(client, user, 10)
for index, reponame := range repositories {
fmt.Println(index+1, reponame)
}
case "create":
var repositories *meta.Repository
repositories = github.CreateRepo(client, org)
fmt.Printf(`
git init
git add -A
git commit -m "first commit"
git branch -M main
git remote add origin git@%s:%s/%s.git
git push -u origin main
`, host, *usr.Login, repositories.GetName())
case "delete":
var repositories *meta.Response
repositories = github.DeleteRepo(client, org)
if repositories.StatusCode == 204 {
fmt.Printf("Deleted\n")
}
}
}
| 0dfc3c9f3ed265d36f76d6b3dc2d321d05cdc6ef | [
"Markdown",
"Go Module",
"Go"
] | 6 | Go | kilwa0/initrepo | 5ce7926128d20d79df4495cd95552af4d6f0769e | 597f3eb1587910c3d6f5b2ce3fcd4ac86e1d88d1 |
refs/heads/master | <file_sep>import React, { Component, PropTypes } from 'react'
class LoginForm extends Component {
static propTypes = {
authorization: PropTypes.func
};
state = {
username: '',
password: ''
};
handleChange = field => ev => {
this.setState({
[field]: ev.target.value
})
};
handleSubmit = ev => {
ev.preventDefault();
this.props.authorization(this.state);
this.setState({
username: '',
password: ''
})
};
render () {
return (
<form onSubmit = {this.handleSubmit}>
<h2>Авторизуйтесь в bitbucket для подгрузки <NAME></h2>
<p>
<label>Ваш логин:<br/></label>
<input type="text" size="15" value={this.state.username} onChange = {this.handleChange('username')}/>
</p>
<p>
<label>Ваш пароль:<br/></label>
<input type="password" size="15" value={this.state.password} onChange = {this.handleChange('password')}/>
</p>
<p>
<input type="submit" value="Авторизоваться"/>
</p>
</form>
);
}
}
export default LoginForm<file_sep>import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from 'pages/App'
let container;
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Component/>
</AppContainer>,
container)
};
document.addEventListener('DOMContentLoaded', () => {
container = document.createElement('div');
document.getElementsByTagName('body')[0].appendChild(container);
render(App)
});
if (module.hot) {
module.hot.accept('pages/App', () => {
render(App)
})
}<file_sep>import React from 'react'
import Post from './Post'
export default function PostsList(props) {
const { posts } = props;
const postElements = posts.map(post => <li key = {post.id}><Post post = {post} /></li>);
return (
<div>
<h2>Список постов</h2>
<ul>
{postElements}
</ul>
</div>
)
}<file_sep>import React, { Component } from 'react'
import s from './Home.css'
class Home extends Component {
static propTypes = {};
static defaultProps = {};
render () {
return (
<h1 className={s.root}>Главная</h1>
)
}
}
export default Home<file_sep>import React, { PropTypes } from 'react'
function Comment(props) {
const { comment: { text, user } } = props;
return (
<div>
{text} <b>{user}</b>
</div>
)
}
Comment.propTypes = {
comment: PropTypes.shape({
text: PropTypes.string.isRequired,
user: PropTypes.string
})
};
export default Comment<file_sep>import React, { Component } from 'react'
import s from './Blog.css'
import {posts} from '../../fixtures'
import PostsList from './PostsList'
class Blog extends Component {
static propTypes = {};
static defaultProps = {};
render () {
return (
<div>
<h1>Блог</h1>
<PostsList posts = {posts} />
</div>
)
}
}
export default Blog<file_sep># React test app based on react-spa-starter ( https://github.com/techintouch/react-spa-starter )
You need execute:
1) npm i
2) cd simple_api && npm i
3) npm start
<file_sep>import React, { Component, PropTypes } from 'react'
class NewCommentForm extends Component {
static propTypes = {
addComment: PropTypes.func
};
state = {
text: '',
user: ''
};
handleChange = field => ev => {
this.setState({
[field]: ev.target.value
})
};
handleSubmit = ev => {
ev.preventDefault();
this.props.addComment(this.state);
this.setState({
user: '',
text: ''
})
};
render() {
return (
<form onSubmit = {this.handleSubmit}>
<h1>Добавить комментарий</h1>
Имя пользователя:<br/><input type="text" value={this.state.user} onChange = {this.handleChange('user')}/><br/><br/>
Комментарий:<br/><input type="text" value={this.state.text} onChange = {this.handleChange('text')}/><br/><br/>
<input type="submit"/>
</form>
)
}
}
export default NewCommentForm<file_sep>import React, { Component, PropTypes } from 'react'
import Comment from './Comment'
import NewCommentForm from './NewCommentForm'
class CommentList extends Component {
constructor() {
super();
this.state = {
comments: []
}
}
static propTypes = {
comments: PropTypes.array,
isOpen: PropTypes.bool,
toggleOpen: PropTypes.func
};
componentWillMount() {
this.setState({
comments: this.props.comments
});
}
render() {
return (
<div>
{this.getLink()}
{this.getBody()}
</div>
)
}
addComment = (comment) => {
comment.id = Math.floor(Math.random() * 1000);
let comments = this.state.comments;
comments.push(comment);
this.setState({
comments: comments
});
};
getLink() {
if (this.state.comments) {
return <a href="#" onClick = {this.props.toggleOpen}>
{(this.props.isOpen ? 'скрыть' : 'показать') + ' комментарии (' + this.state.comments.length + ')' }
</a>
} else {
return <a href="#" onClick = {this.props.toggleOpen}>
{(this.props.isOpen ? 'скрыть' : 'показать') + ' комментарии' }
</a>
}
}
getBody() {
const { comments, isOpen } = this.props;
if (!isOpen) return null;
const form = <NewCommentForm addComment={this.addComment} />;
if (!comments) return <div><p>Ещё никто не добавил комментариев</p>{form}</div>;
const commentItems = comments.map(comment => <li key = {comment.id}><Comment comment = {comment} /></li>);
return (
<div>
<ul>{commentItems}</ul>
{form}
</div>
)
}
}
export default CommentList | 4cf4df55584226412097c7d7b6e12cd358b82a5c | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | kickboxer/test-react | 83204b8226561162568b817f9f3e2d082821241e | c72ce03addb51b84316542c9a8679275a05a09e2 |
refs/heads/master | <file_sep>import sys
import os
import shutil
import csv
import math
def readDirFilesToDict(dictDir):
# parse the spam or ham folders' files into words corpus
def hasIllegalChars(str): # decide if a string is a legit word
if str == '' or str[0] == '-' or str[-1] == '-' or str[0] > 'z' or str[0] < 'A':
return True
for c in str:
if not (c >= 'a' and c <= 'z' or c >= 'A' and c <= 'Z' or c ==
'-'):
return True
if len(str) >= 50:
return True
return False
def removePunctuation(s): # there might be some punctuation at the end
s = s.replace('.', '')
s = s.replace(',', '')
s = s.replace(';', '')
s = s.replace('?', '')
s = s.replace('!', '')
return s
if dictDir[-1] != '/': # deal with folder path
dictDir = ''.join(dictDir + '/')
filenameList = os.listdir(dictDir) # find all files in the folder
dic = {} # dict of { filename: {word: 1} }
illegalChars = '?!.,:;_<>()[]{}+*/=#$%^&` \" \' \\ \n \t' # obselete
for filename in filenameList:
if filename != '.DS_Store': # Mac OS X auto created file
wordList = {}
csvfile = open(dictDir + filename, 'rb')
dat = csv.reader(csvfile, delimiter=' ')
for lineCtnt in dat:
for word in lineCtnt:
wordTmp = removePunctuation(word)
if not hasIllegalChars(wordTmp): # deal with illegal char
wordList[wordTmp.lower()] = 1
csvfile.close()
dic[filename] = wordList
# sys.stdout = open('ham_dict.txt', 'wb')
# print dic
return dic
def makedictionary(spam_directory, ham_directory, dictionary_filename):
# read spam and ham files from folders for training
spamMailDict = readDirFilesToDict(spam_directory)
hamMailDict = readDirFilesToDict(ham_directory)
spamMailNum = len(spamMailDict)
hamMailNum = len(hamMailDict)
# ham and spam {word: 1}, combining into total[word]
hamWordDict, spamWordDict, totalWordList = {}, {}, []
for doc in hamMailDict.values():
for word in doc:
hamWordDict[word] = 1
for doc in spamMailDict.values():
for word in doc:
spamWordDict[word] = 1
for word in hamWordDict.keys():
if spamWordDict.has_key(word):
totalWordList.append(word)
totalWordList.sort()
dictionary = [] # output to file, so it's alphabet ordered list
i = 0 # indicating progress
for word in totalWordList:
if i % 500 == 0: # show the progress
print 'calculating', i, 'of', len(totalWordList), 'words'
i += 1
spamCount, hamCount = 0, 0
for doc in spamMailDict.values():
if doc.has_key(word):
spamCount += 1
for doc in hamMailDict.values():
if doc.has_key(word):
hamCount += 1
spamRatio = 1.0 * spamCount / spamMailNum
hamRatio = 1.0 * hamCount / hamMailNum
dictionary.append([word, spamRatio, hamRatio])
dicfile = open(dictionary_filename, 'wb') # output to file
for item in dictionary:
dicfile.writelines(
item[0] + ' ' + str(item[1]) + ' ' + str(item[2]) + '\n')
def spamsort(mail_directory, spam_directory, ham_directory, dictionary_filename, spam_prior_probability):
# deal with folder path, create spam and ham folder if necessary
if mail_directory[-1] != '/':
mail_directory = ''.join(mail_directory + '/')
if not os.path.isdir(spam_directory):
os.makedirs(spam_directory)
if not os.path.isdir(ham_directory):
os.makedirs(ham_directory)
# read in the dictionary file
csvfile = open(dictionary_filename, 'rb')
dat = csv.reader(csvfile, delimiter=' ')
dictionary = []
for lineCtnt in dat:
dictionary.append(lineCtnt)
csvfile.close()
dictionaryDict = {}
for item in dictionary:
dictionaryDict[item[0]] = [
math.log(float(item[1])), math.log(float(item[2]))]
mailDict = readDirFilesToDict(mail_directory) # read in emails
for k, v in mailDict.items(): # k=filename, v={word:1} dict
probSpam = math.log(spam_prior_probability)
probHam = math.log(1 - spam_prior_probability)
for word in v.keys(): # add up the probabilities
if dictionaryDict.has_key(word):
probSpam += dictionaryDict[word][0]
probHam += dictionaryDict[word][1]
mailPath = mail_directory + k
if probSpam > probHam: # move emails
# shutil.copy2(mailPath, spam_directory)
shutil.move(mailPath, spam_directory)
else:
# shutil.copy2(mailPath, ham_directory)
shutil.move(mailPath, ham_directory)
if __name__ == "__main__":
makedictionary('./spam', './easy_ham', './dictionary.txt')
# spamsort('./mail', './out_spam', './out_ham', './dictionary.txt', 0.16415)
| 828e14ad9029b78ea8d0a9690898e95cca5abf1b | [
"Python"
] | 1 | Python | hangbinli/machine_learning_spamfilter | c34f401c5b0751af9a04355fcc5e02d324b5301a | f66ad5525b354de3aa9f54124104c9e1a074223e |
refs/heads/master | <repo_name>zzuspy/Server<file_sep>/Server2.0/log.h
#ifndef LOG_H
#define LOG_H
//找一个可写的日志文件(带滚动)
//滚动策略:先顺序找没有写满(没写)的日志文件
// 如果全部写满的话,就找创建时间最早的,删掉重写
int findlog();
//初始化,定位一个可写的日志文件
void initlog();
//写日志
void writelog(const char* content);
void log_destroy();
#endif
<file_sep>/Server1.0/log.c
#include "base.h"
#include "log.h"
char LOGFILE[100];//记录当前存储日志的文件
int LOG_CUR_SIZE = 0;//当前使用的日志文件的大小
const int LOG_MAX_SIZE = 1024 * 1024;//每一个日志文件的最大值
const int LOG_FILE_NUM = 99;//日志文件的最大数量
FILE *log_fp = NULL;
int findlog() {
struct stat file;
int i;
//顺序查找没写满或者没写的日志文件
for(i = 1; i <= LOG_FILE_NUM; i ++) {
char pos[4];
char filename[15] = "log/log_";
sprintf( pos, "%02d", i );
strcat( filename, pos );
if( stat(filename, &file) < 0 ) {
LOG_CUR_SIZE = 0;
return i;
}
//printf("%s size: %d\n", filename, ( int ) file.st_size);
if( ( int ) file.st_size < LOG_MAX_SIZE ) {
LOG_CUR_SIZE = ( int ) file.st_size;
//printf("hello\n");
return i;
}
}
//查找创建时间最早的日志文件
if(i >= LOG_FILE_NUM) {
int ret = 1;
stat("log/log_01", &file);
time_t tt = file.st_ctime;
for(i = 2; i <= LOG_FILE_NUM; i ++) {
char pos[4];
char filename[15] = "log/log_";
sprintf( pos, "%02d", i);
strcat( filename, pos );
stat( filename, &file );
if(file.st_ctime < tt) {
ret = i;
tt = file.st_ctime;
}
}
char pos[4];
char filename[15] = "log/log_";
sprintf( pos, "%02d", ret);
strcat( filename, pos);
remove(filename);
return ret;
}
}
void initlog() {
if(log_fp != NULL) fclose(log_fp);
LOG_CUR_SIZE = 0;
char filename[15] = "log/log_";
char pos[4];
sprintf(pos, "%02d", findlog());
strcat(filename, pos);
strcpy(LOGFILE, filename);
log_fp = fopen(LOGFILE, "a+");
//printf("%s\n", LOGFILE);
}
void writelog(const char *content) {
if(LOG_CUR_SIZE > LOG_MAX_SIZE) {
initlog();
}
log_fp = fopen(LOGFILE, "a+");
if(log_fp != NULL) {
time_t tt = time(NULL);
struct tm* curtime = localtime(&tt);
printf("log <- %s\n", content);
//printf("%s", LOGFILE);
fprintf(log_fp, "%04d_%02d_%02d %02d:%02d:%02d : %s\n", curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday,\
curtime->tm_hour, curtime->tm_min, curtime->tm_sec, content);
LOG_CUR_SIZE += strlen(content) + 22;
}
else {
perror("writelog");
exit(1);
}
fclose( log_fp );
}
void log_destroy() {
fclose( log_fp );
}
/*
int main() {
initlog();
for(int i = 0; i < 100; i ++)
writelog("HelloWorld");
return 0;
}
*/
<file_sep>/Server1.0/makefile
.PHONY : all
all : clean server client clear
log.o : log.h log.c
g++ -c log.c -o log.o
threadpool.o : threadpool.h threadpool.c
g++ -c threadpool.c -o threadpool.o
server : http.h log.o server.c base.h threadpool.o
g++ http.h log.o threadpool.o server.c -o server -pthread
client : client.c base.h
g++ client.c -o client
clean :
rm -rf server *.o *~
clear :
rm -rf *.o
<file_sep>/Server1.0/server.c
#include "base.h"
#include "log.h"
#include "threadpool.h"
//config
static char IP[25];
static int PORT = 0;
//server listen
const int BUFSIZE = 1024;
int sockfd;
static char buf[BUFSIZE];
struct sockaddr_in address;
socklen_t sin_size = sizeof( struct sockaddr_in);
struct sockaddr_in remote_addr;
//epoll
const int MAX_EVENTS = 100;
int epoll_fd;
struct epoll_event ev;
struct epoll_event events[MAX_EVENTS];
//log
char msg[200];
//thread
struct threadpool *tpool;
int arg[100000];
int stop = 0;
void handle_err( bool err, const char *str ) {
if( err ) {
perror(str);
exit(1);
}
}
void read_config() {
const char config[100] = "./.config";
char line[200], key[100], value[100];
FILE *fp;
if( ( fp = fopen(config, "r")) == NULL) {
perror("can't open config'");
exit(1);
}
while( fgets( line, sizeof(line), fp) != NULL) {
sscanf( line, "%s %s", key, value);
if( strcmp( key, "PORT" ) == 0 ) {
PORT = atoi( value );
}
else if( strcmp( key, "IP" ) == 0 ) {
strcpy(IP, value);
}
}
}
void listen_init() {
sockfd = socket( AF_INET, SOCK_STREAM, 0);
handle_err( sockfd < 0 , "sockfd");
memset( &address, 0, sizeof(address) );
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
address.sin_addr.s_addr = htonl( INADDR_ANY );
int ret = bind(sockfd, (struct sockaddr * ) &address, sizeof(address));
handle_err( ret < 0, "bind");
ret = listen(sockfd, 1000);
handle_err(ret < 0, "listen");
}
void epoll_init() {
epoll_fd = epoll_create(10000);
ev.data.fd = sockfd;
ev.events = EPOLLIN | EPOLLET;
int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &ev);
handle_err( ret < 0, "epoll_add" );
}
void global_init() {
read_config();
initlog();
listen_init();
epoll_init();
tpool = threadpool_init(200, 1000);
}
void global_destroy() {
log_destroy();
close( epoll_fd );
close( sockfd );
threadpool_destroy(tpool);
}
enum CHECK_STATE { CHECK_STATE_REQUESTLINE = 0, CHECK_STATE_HEADER, CHECK_STATE_CONTENT };
enum LINE_STATUS { LINE_OK = 0, LINE_BAD, LINE_OPEN };
enum HTTP_CODE { NO_REQUEST, GET_REQUEST, BAD_REQUEST, FORBIDDEN_REQUEST, INTERNAL_ERROR, CLOSED_CONNECTION };
static const char* szret[] = { "I get a correct result\n", "Something wrong\n" };
LINE_STATUS parse_line( char* buffer, int& checked_index, int& read_index ) {
char temp;
for ( ; checked_index < read_index; ++checked_index ) {
temp = buffer[ checked_index ];
if ( temp == '\r' ) {
if ( ( checked_index + 1 ) == read_index ) {
return LINE_OPEN;
}
else if ( buffer[ checked_index + 1 ] == '\n' ) {
buffer[ checked_index++ ] = '\0';
buffer[ checked_index++ ] = '\0';
return LINE_OK;
}
return LINE_BAD;
}
else if( temp == '\n' ) {
if( ( checked_index > 1 ) && buffer[ checked_index - 1 ] == '\r' ) {
buffer[ checked_index-1 ] = '\0';
buffer[ checked_index++ ] = '\0';
return LINE_OK;
}
return LINE_BAD;
}
}
return LINE_OPEN;
}
HTTP_CODE parse_requestline( char* szTemp, CHECK_STATE& checkstate ) {
char* szURL = strpbrk( szTemp, " \t" );
if ( ! szURL ) {
return BAD_REQUEST;
}
*szURL++ = '\0';
char* szMethod = szTemp;
if ( strcasecmp( szMethod, "GET" ) == 0 ) {
//printf( "The request method is GET\n" );
}
else {
return BAD_REQUEST;
}
szURL += strspn( szURL, " \t" );
char* szVersion = strpbrk( szURL, " \t" );
if ( ! szVersion ) {
return BAD_REQUEST;
}
*szVersion++ = '\0';
szVersion += strspn( szVersion, " \t" );
if ( strcasecmp( szVersion, "HTTP/1.1" ) != 0 ) {
return BAD_REQUEST;
}
if ( strncasecmp( szURL, "http://", 7 ) == 0 ) {
szURL += 7;
szURL = strchr( szURL, '/' );
}
if ( ! szURL || szURL[ 0 ] != '/' ) {
return BAD_REQUEST;
}
//URLDecode( szURL );
printf( "The request URL is: %s\n", szURL );
checkstate = CHECK_STATE_HEADER;
return NO_REQUEST;
}
HTTP_CODE parse_headers( char* szTemp ) {
if ( szTemp[ 0 ] == '\0' ) {
return GET_REQUEST;
}
else if ( strncasecmp( szTemp, "Host:", 5 ) == 0 ) {
szTemp += 5;
szTemp += strspn( szTemp, " \t" );
printf( "the request host is: %s\n", szTemp );
}
else {
printf( "I can not handle this header\n" );
}
return NO_REQUEST;
}
HTTP_CODE parse_content( char* buffer, int& checked_index, CHECK_STATE& checkstate, int& read_index, int& start_line ) {
LINE_STATUS linestatus = LINE_OK;
HTTP_CODE retcode = NO_REQUEST;
while( ( linestatus = parse_line( buffer, checked_index, read_index ) ) == LINE_OK ) {
char* szTemp = buffer + start_line;
start_line = checked_index;
switch ( checkstate ) {
case CHECK_STATE_REQUESTLINE: {
retcode = parse_requestline( szTemp, checkstate );
if ( retcode == BAD_REQUEST ) {
return BAD_REQUEST;
}
break;
}
case CHECK_STATE_HEADER: {
retcode = parse_headers( szTemp );
if ( retcode == BAD_REQUEST ) {
return BAD_REQUEST;
}
else if ( retcode == GET_REQUEST ) {
return GET_REQUEST;
}
break;
}
default: {
return INTERNAL_ERROR;
}
}
}
if( linestatus == LINE_OPEN ) {
return NO_REQUEST;
}
else {
return BAD_REQUEST;
}
}
void *deal(void *arg) {
struct epoll_event event = *( ( struct epoll_event * ) arg );
int connfd = event.data.fd;
//printf("connfd=%d\n", connfd);
memset( buf, '\0', BUFSIZE);
int data_read = 0;
int read_index = 0;
int checked_index = 0;
int start_line= 0;
CHECK_STATE checkstate = CHECK_STATE_REQUESTLINE;
while( 1 ) {
//printf("Hello");
data_read = recv( connfd, buf + read_index, BUFSIZE - read_index, 0);
if( data_read < 0 ) {
printf("reading failed\n");
break;
}
else if( data_read == 0 ) {
printf("remote client has closed the connection\n");
break;
}
read_index += data_read;
HTTP_CODE result = parse_content( buf, checked_index, checkstate, read_index, start_line );
if( result == NO_REQUEST ) {
continue;
//break;
}
else if( result == GET_REQUEST ) {
send( connfd, szret[0], strlen( szret[0] ), 0);
break;
}
else {
send( connfd, szret[1], strlen( szret[1] ), 0);
break;
}
}
int ret = epoll_ctl( epoll_fd, EPOLL_CTL_DEL, connfd, &event );
handle_err( ret < 0, "epoll_del" );
close(connfd);
//printf("connfd %d break_down\n", connfd);
}
int main() {
global_init();
printf("%s %d\n", IP, PORT);
int conn_cnt = 0;
while( !stop ) {
int i, nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if( nfds < 0 ) {
if( errno == EINTR ) continue;
handle_err( true, "epoll_wait" );
}
//printf("%d\n", nfds);
for( i = 0; i < nfds; i ++ ) {
if( events[i].data.fd == sockfd ) {
int connfd = accept( sockfd, (struct sockaddr *) &remote_addr, &sin_size);
handle_err( connfd < 0, "accept" );
//sprintf(msg, "accept client %s:%d .", inet_ntoa(remote_addr.sin_addr), ntohs( remote_addr.sin_port ) );
//writelog( msg );
conn_cnt ++;
ev.data.fd = connfd;
ev.events = EPOLLIN | EPOLLET;
int ret = epoll_ctl( epoll_fd, EPOLL_CTL_ADD, connfd, &ev );
handle_err( ret < 0, "epoll_add" );
}
else if( events[i].events & EPOLLIN ) {
arg[i] = i;
int connfd = events[i].data.fd;
//printf("i=%d conn_cnt=%d connfd=%d\n", i, conn_cnt, connfd);
threadpool_add_job(tpool, deal, &events[i]);
/*
memset( buf, '\0', BUFSIZE);
int data_read = 0;
int read_index = 0;
int checked_index = 0;
int start_line= 0;
CHECK_STATE checkstate = CHECK_STATE_REQUESTLINE;
while( 1 ) {
//printf("Hello");
data_read = recv( connfd, buf + read_index, BUFSIZE - read_index, 0);
if( data_read < 0 ) {
printf("reading failed\n");
break;
}
else if( data_read == 0 ) {
printf("remote client has closed the connection\n");
break;
}
read_index += data_read;
HTTP_CODE result = parse_content( buf, checked_index, checkstate, read_index, start_line );
if( result == NO_REQUEST ) {
continue;
//break;
}
else if( result == GET_REQUEST ) {
send( connfd, szret[0], strlen( szret[0] ), 0);
break;
}
else {
send( connfd, szret[1], strlen( szret[1] ), 0);
break;
}
}
epoll_ctl( epoll_fd, EPOLL_CTL_DEL, connfd, &ev );
close(connfd);
printf("%d ", conn_cnt);
//writelog("break down");
*/
/*
int len = read( connfd, &buf, BUFSIZE );
if( len < 0 ) {
close( connfd );
continue;
}
if( len == 0) {
epoll_ctl( epoll_fd, EPOLL_CTL_DEL, connfd, &ev );
close( connfd );
writelog("break down");
continue;
}
sprintf(msg, "get info %s", buf);
writelog(msg);
printf("%s\n", buf);
*/
}
else if( events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR ) ) {
int ret = epoll_ctl( epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &events[i] );
handle_err( ret < 0, "epoll_del" );
close( events[i].data.fd );
}
else {
//todo
}
}
}
global_destroy();
return 0;
}
<file_sep>/Server1.0/client.c
#include "base.h"
const int BUFSIZE = 1024;
const int PORT = 8888;
const char IP[15] = "127.0.0.1";
void handle( bool err, const char *str) {
if( err ) {
perror( str );
exit( 1 );
}
}
int main() {
int sockfd = socket( PF_INET, SOCK_STREAM, 0 );
handle( sockfd < 0, "socket" );
int len;
struct sockaddr_in remote_addr;
char buf[BUFSIZE];
memset( &remote_addr, 0, sizeof(remote_addr) );
remote_addr.sin_family = AF_INET;
remote_addr.sin_addr.s_addr = inet_addr( IP );
remote_addr.sin_port = htons( PORT );
int ret = connect( sockfd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr) );
handle( ret < 0, "connect");
while(1) {
scanf("%s", buf);
write( sockfd, buf, sizeof( buf ) );
}
close(sockfd);
return 0;
}
<file_sep>/Server2.0/threadpool.h
#pragma once
#define THREADS_LIMITS 55
#define QUEUE_LIMITS 55555
typedef struct threadpool_t threadpool_t;
typedef enum {
threadpool_invalid = -1,
threadpool_lock_failure = -2,
threadpool_queue_full = -3,
threadpool_shutdown = -4,
threadpool_thread_failure = -5
} threadpool_failure_t;
typedef enum {
threadpool_specific_way = 1
} threadpool_destroy_t;
threadpool_t *threadpool_create(int thread_count, int queue_size, int arg);
int threadpool_add(threadpool_t *pool, void (*function)(void *), void *arg, int args);
int threadpool_destroy(threadpool_t *pool, int arg);
| 1396030d334e8e260fbe2649b79e2fb657b04504 | [
"C",
"Makefile"
] | 6 | C | zzuspy/Server | 77ff73d49b584e7f897440453cbf76ececd1ba99 | 579e6368d3d23dcf5d255ceaccf310fea563a17c |
refs/heads/master | <repo_name>085astatine/lark_test<file_sep>/main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import lark
def main() -> None:
with open('./expr.lark') as file:
parser = lark.Lark(file.read(), start='expr')
tree = parser.parse(sys.argv[1])
print(tree)
if __name__ == '__main__':
main()
| 232a5e9cafff3ade0a4d3ddd761b5000eb2c06b8 | [
"Python"
] | 1 | Python | 085astatine/lark_test | 71e232df233fe1dd33cf677a2d99cafaa27aaeb8 | 14987e6596cb81d521ea52cbd02209ae6f824992 |
refs/heads/master | <file_sep>/*
* Copyright (c) 2013, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of this project.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <inttypes.h>
#include <unistd.h>
#include <fcntl.h>
#include <error.h>
#include <getopt.h>
#include <endian.h>
#include <byteswap.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <linux/fb.h>
#define NAME "ppmtofb"
/* ENDIANNESS */
#ifndef htobe32
static uint32_t _swap32(uint32_t v)
{
uint8_t *ptr = (void *)&v;
uint8_t tmp;
tmp = ptr[3];
ptr[3] = ptr[0];
ptr[0] = tmp;
tmp = ptr[2];
ptr[2] = ptr[1];
ptr[1] = tmp;
return v;
}
static uint16_t _swap16(uint16_t v)
{
uint8_t *ptr = (void *)&v;
uint8_t tmp;
tmp = ptr[1];
ptr[1] = ptr[0];
ptr[0] = tmp;
return v;
}
#if BYTE_ORDER == LITTLE_ENDIAN
#define htobe32 _swap32
#define be32toh _swap32
#define htobe16 _swap16
#define be16toh _swap16
#define htole32(x) (x)
#define le32toh(x) (x)
#define htole16(x) (x)
#define le16toh(x) (x)
#else
#define htobe32(x) (x)
#define be32toh(x) (x)
#define htobe16(x) (x)
#define be16toh(x) (x)
#define htole32 _swap32
#define le32toh _swap32
#define htole16 _swap16
#define le16toh _swap16
#endif
#endif
/* ARGUMENTS */
static const char help_msg[] =
NAME ": Convert between PPM and framebuffer (raw)\n"
"Usage : " NAME " [PPM [FBDEVICE]]\n"
" : " NAME " [FBDEVICE [PPM]]\n"
"\n"
"Options\n"
" -?, --help Show this help\n"
" -V, --version Show program version\n"
;
#ifdef _GNU_SOURCE
static const struct option long_opts[] = {
{ "help", no_argument, NULL, '?', },
{ "version", no_argument, NULL, 'V', },
{ },
};
#else
#define getopt_long(argc, argv, optstring, longopts, longindex) \
getopt((argc), (argv), (optstring))
#endif
static const char optstring[] = "?Vv";
static int verbose = 0;
int readallocfile(uint8_t **dat, const char *filename)
{
int ret, fd, done;
struct stat st;
if (!filename || !strcmp("-", filename)) {
fd = fileno(stdin);
} else {
fd = open(filename, O_RDONLY);
if (fd < 0)
error(1, errno, "open %s", filename);
}
fstat(fd, &st);
if (st.st_size) {
done = st.st_size;
*dat = realloc(*dat, done);
if (!*dat)
error(1, errno, "realloc %u", done);
ret = read(fd, *dat, done);
if (ret < 0)
error(1, errno, "read %s", filename);
} else {
#define BLK 1024
int size;
done = size = 0;
do {
size += BLK;
*dat = realloc(*dat, size);
ret = read(fd, (*dat)+done, BLK);
if (ret < 0)
error(1, errno, "read %s", filename);
done += ret;
} while (ret == BLK);
ret = done;
}
return ret;
}
/* interal pixel representation */
static inline uint32_t mkpixel(int r, int g, int b, int a)
{
return ((r & 0xff) << 16) | (( g & 0xff) << 8) | ((b & 0xff) << 0) | ((a & 0xff) << 24);
}
static inline uint8_t pixel_r(uint32_t pixel)
{
return (pixel >> 16) & 0xff;
}
static inline uint8_t pixel_g(uint32_t pixel)
{
return (pixel >> 8) & 0xff;
}
static inline uint8_t pixel_b(uint32_t pixel)
{
return (pixel >> 0) & 0xff;
}
static inline uint8_t pixel_a(uint32_t pixel)
{
return (pixel >> 24) & 0xff;
}
/* FB info */
struct fb_fix_screeninfo fix_info;
struct fb_var_screeninfo var_info;
uint16_t colormap_data[4][1 << 8];
struct fb_cmap colormap = {
0,
1 << 8,
colormap_data[0],
colormap_data[1],
colormap_data[2],
colormap_data[3],
};
static uint8_t *video;
static uint8_t *videocache;
static size_t videolen;
/* cached framebuffer bytes per pixel */
static int fbbypp;
/* FRAMEBUFFER CONFIG */
static int getfbinfo(int fd)
{
unsigned int i;
struct stat st;
if (fstat(fd, &st) < 0)
error(1, errno, "fstat %i", fd);
if (!S_ISCHR(st.st_mode))
return -1;
if (ioctl(fd, FBIOGET_FSCREENINFO, &fix_info)) {
if (errno == ENOTTY)
return -1;
error(1, errno, "FBIOGET_FSCREENINFO failed");
}
if (fix_info.type != FB_TYPE_PACKED_PIXELS)
error(1, 0, "framebuffer type is not PACKED_PIXELS (%i)", fix_info.type);
if (ioctl(fd, FBIOGET_VSCREENINFO, &var_info))
error(1, errno, "FBIOGET_VSCREENINFO failed");
if (var_info.red.length > 8 || var_info.green.length > 8 || var_info.blue.length > 8)
error(1, 0, "color depth > 8 bits per component");
switch (fix_info.visual) {
case FB_VISUAL_TRUECOLOR:
/* initialize dummy colormap */
for (i = 0; i < (1 << var_info.red.length); i++)
colormap.red[i] = i * 0xffff / ((1 << var_info.red.length) - 1);
for (i = 0; i < (1 << var_info.green.length); i++)
colormap.green[i] = i * 0xffff / ((1 << var_info.green.length) - 1);
for (i = 0; i < (1 << var_info.blue.length); i++)
colormap.blue[i] = i * 0xffff / ((1 << var_info.blue.length) - 1);
break;
case FB_VISUAL_DIRECTCOLOR:
case FB_VISUAL_PSEUDOCOLOR:
case FB_VISUAL_STATIC_PSEUDOCOLOR:
if (ioctl(fd, FBIOGETCMAP, &colormap) != 0)
error(1, errno, "FBIOGETCMAP failed");
break;
default:
error(1, 0, "unsupported visual (%i)", fix_info.visual);
}
fbbypp = (var_info.bits_per_pixel +7) /8;
if (verbose) {
error(0, 0, "framebuffer (%s) on %s", fix_info.id, fd ? "stdout" : "stdin");
error(0, 0, "%ux%u, bytes/pixel %i", var_info.xres, var_info.yres, fbbypp);
error(0, 0, "r %u/%u, g %u/%u, b %u/%u, a %u/%u",
var_info.red.length, var_info.red.offset,
var_info.green.length, var_info.green.offset,
var_info.blue.length, var_info.blue.offset,
var_info.transp.length, var_info.transp.offset);
}
return 0;
}
static void getvideomemory(int fd, int wr)
{
size_t offset;
offset = fix_info.line_length * var_info.yoffset;
videolen = fix_info.line_length * var_info.yres;
if (verbose)
error(0, 0, "mapping video memory +%uKB", videolen/1024);
video = mmap(NULL, videolen, wr ? PROT_WRITE : PROT_READ, MAP_SHARED, fd, offset);
if (video == MAP_FAILED)
error(1, errno, "mmap failed");
/* malloc cache, for faster dump */
#ifdef NOCACHE
videocache = video;
#else
videocache = malloc(videolen);
if (wr)
memset(videocache, 0, videolen);
else
memcpy(videocache, video, videolen);
#endif
}
static void putvideomemory(int wr)
{
#ifdef NOCACHE
#else
if (wr)
memcpy(videocache, video, videolen);
free(videocache);
#endif
munmap(video, videolen);
}
/* FRAMEBUFFER */
static inline uint8_t *getfbpos(int x, int y)
{
return videocache + (y+var_info.yoffset)*fix_info.line_length + (x+var_info.xoffset)*fbbypp;
}
static inline uint8_t getfbcolor(uint32_t pixel, const struct fb_bitfield *bitfield, const uint16_t *colormap)
{
return ((pixel >> bitfield->offset) & ((1 << bitfield->length)-1)) << (8 - bitfield->length);
return colormap[(pixel >> bitfield->offset) & ((1 << bitfield->length) - 1)] >> 8;
}
static inline uint32_t putfbcolor(uint32_t color, const struct fb_bitfield *bitfield, const uint16_t *colormap)
{
color >>= (8 - bitfield->length);
return color << bitfield->offset;
}
static uint32_t getfbpixel(int x, int y)
{
void *dat = getfbpos(x, y);
uint32_t pixel = 0;
switch (fbbypp) {
case 1:
pixel = *(uint8_t *)dat;
break;
case 2:
pixel = le16toh(*(uint16_t *)dat);
break;
case 3:
pixel = le32toh(*(uint32_t *)dat) & 0xffffff;
break;
case 4:
pixel = le32toh(*(uint32_t *)dat);
break;
}
return mkpixel(getfbcolor(pixel, &var_info.red, colormap.red),
getfbcolor(pixel, &var_info.green, colormap.green),
getfbcolor(pixel, &var_info.blue, colormap.blue),
getfbcolor(pixel, &var_info.transp, colormap.transp));
}
static void putfbpixel(int x, int y, uint32_t pixel)
{
void *dat = getfbpos(x, y);
uint32_t fbpixel;
fbpixel = putfbcolor(pixel_r(pixel), &var_info.red, colormap.red)
| putfbcolor(pixel_g(pixel), &var_info.green, colormap.green)
| putfbcolor(pixel_b(pixel), &var_info.blue, colormap.blue)
| putfbcolor(pixel_a(pixel), &var_info.transp, colormap.transp);
/* assume framebuffer is in Little Endian */
switch (fbbypp) {
case 1:
*(uint8_t *)dat = fbpixel;
break;
case 2:
*(uint16_t *)dat = htole16(fbpixel);
break;
case 3:
case 4:
*(uint32_t *)dat = htole32(fbpixel);
break;
}
}
/* PPM */
static uint32_t getppmpixel(const uint8_t *dat, int max)
{
if (max == 0xff)
return mkpixel(dat[0], dat[1], dat[2], 0);
else if (max == 0xffff)
return mkpixel(dat[0], dat[2], dat[4], 0);
else if (max > 255) {
const uint16_t *dat16 = (const void *)dat;
return mkpixel(be16toh(dat16[0])*255/max,
be16toh(dat16[1])*255/max,
be16toh(dat16[2])*255/max,
0);
} else
return mkpixel(dat[0]*255/max, dat[1]*255/max,
dat[2]*255/max, 0);
}
static void putppmpixel(uint32_t pixel)
{
pixel = htobe32(pixel << 8/* skip transp */);
if (fwrite(&pixel, 3/* only 3 bytes! */, 1, stdout) < 0)
error(1, errno, "writing pixels");
}
int main (int argc, char *argv[])
{
int opt, size, max;
int w, h, r, c;
/* argument parsing */
while ((opt = getopt_long(argc, argv, optstring, long_opts, NULL)) != -1)
switch (opt) {
case 'V':
fprintf(stderr, "%s %s\n", NAME, VERSION);
return 0;
case 'v':
++verbose;
break;
default:
fputs(help_msg, stderr);
exit(1);
break;
}
/* redir stdout/stdin */
if (argv[optind] && strcmp(argv[optind], "-")) {
int fd;
fd = open(argv[optind], O_RDONLY);
if (fd < 0)
error(1, errno, "open %s", argv[optind]);
dup2(fd, STDIN_FILENO);
close(fd);
}
if (argv[optind] && argv[optind+1] && strcmp(argv[optind+1], "-")) {
int fd;
fd = open(argv[optind+1], O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
error(1, errno, "open %s", argv[optind+1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
if (getfbinfo(STDOUT_FILENO) == 0) {
/* copy ppm to fb */
char *str;
int imgw, ppmbypp;
uint8_t *dat = NULL, *d8;
if (verbose)
error(0, 0, "PPM -> FB");
size = readallocfile(&dat, "-");
if (size <= 0)
error(1, errno, "read file %s", argv[optind] ?: "-");
str = (void *)dat;
if (strncmp(str, "P6", 2))
error(1, errno, "no PPM file");
imgw = w = strtoul(str+2, &str, 0);
h = strtoul(str, &str, 0);
max = strtoul(str, &str, 0);
++str;
if (h > var_info.yres)
h = var_info.yres;
if (w > var_info.xres)
w = var_info.xres;
getvideomemory(STDOUT_FILENO, 1);
d8 = (uint8_t *)str;
ppmbypp = (max > 255) ? 6 : 3;
for (r = 0; r < h; ++r) {
for (c = 0; c < w; ++c, d8 += ppmbypp)
putfbpixel(c, r, getppmpixel(d8, max));
if (imgw > var_info.xres)
d8 += (imgw - var_info.xres)*ppmbypp;
}
putvideomemory(1);
free(dat);
} else if (getfbinfo(STDIN_FILENO) == 0) {
/* copy fb to ppm */
if (verbose)
error(0, 0, "FB -> PPM");
getvideomemory(STDIN_FILENO, 0);
w = var_info.xres;
h = var_info.yres;
if (!w || !h)
error(1, 0, "width & height must be != 0");
/* PPM header */
printf("P6 %u %u 255\n", w, h);
for (r = 0; r < h; ++r) {
for (c = 0; c < w; ++c)
putppmpixel(getfbpixel(c, r));
}
putvideomemory(0);
} else {
error(1, errno, "no framebuffer on stdin or stdout?");
}
fflush(stdout);
return 0;
}
<file_sep># ppmtofb
## Building
$ make
$ make install
### Cross-Compiling
The Makefile includes config.mk when present.
This can modify the build in various ways:
* alter compiler flags
* change compiler
* change install path
Example config.mk for cross-compile:
CC=arm-cortex_a9-linux-gnueabi-gcc
## Using
ppmtofb addresses 2 usecases:
* put a ppm image into a framebuffer
* get an image from a framebuffer an save as ppm
The latter usecase is also addressed by the fbcat program.
<file_sep>PROGRAMS=ppmtofb
default: $(PROGRAMS)
CFLAGS = -Wall -g3 -O0
PREFIX = /usr/local
-include config.mk
VERSION = $(shell ./getlocalversion)
CPPFLAGS+= -DVERSION=\"$(VERSION)\"
clean:
rm -f ppmtofb $(wildcard *.o)
install: $(PROGRAMS)
install $(PROGRAMS) $(DESTDIR)$(PREFIX)/bin
| 6f52649362384e0e4f9eeb5e229948207e4ec51e | [
"Markdown",
"C",
"Makefile"
] | 3 | C | t0mac0/ppmtofb | 6780445a85a4d0fa6a6c118fb2d0b85db14afe85 | b0f8852fd06e10adf416bce8f931c5dbb80f3311 |
refs/heads/master | <repo_name>chuckharmston/universal-search-addon<file_sep>/src/lib/Transport.js
'use strict';
// transport wraps the WebChannel and is exposed via the main pubsub broker.
// The transport also knows how to transform events into the form expected by
// the iframe. This is a little weird, but keeps individual UI objects ignorant
// of the transport.
/* global Cc, Ci, Services, XPCOMUtils, WebChannel */
XPCOMUtils.defineLazyModuleGetter(this, 'WebChannel',
'resource://gre/modules/WebChannel.jsm');
function Transport() {
const prefBranch = Cc['@mozilla.org/preferences-service;1']
.getService(Ci.nsIPrefService)
.getBranch('');
this.frameBaseURL = prefBranch.getPrefType('services.universalSearch.baseURL') ?
prefBranch.getCharPref('services.universalSearch.baseURL') :
'https://d1fnkpeapwua2i.cloudfront.net';
this.port = null;
// channelId must be unique to each window (#64)
this.channelId = 'ohai-' + Math.floor(Math.random() * 100000);
this._lastAutocompleteSearchTerm = '';
this._lastSuggestedSearchTerm = '';
}
Transport.prototype = {
constructor: Transport,
init: function() {
// intentionally alphabetized
window.US.broker.subscribe('popup::autocompleteSearchResults',
this.onAutocompleteSearchResults, this);
window.US.broker.subscribe('popup::popupClose', this.onPopupClose, this);
window.US.broker.subscribe('popup::popupOpen', this.onPopupOpen, this);
window.US.broker.subscribe('popup::suggestedSearchResults',
this.onSuggestedSearchResults, this);
window.US.broker.subscribe('urlbar::navigationalKey',
this.onNavigationalKey, this);
this.port = new WebChannel(this.channelId,
Services.io.newURI(this.frameBaseURL, null, null));
this.port.listen(this.onContentMessage.bind(this));
},
shutdown: function() {
if (this.port) {
this.port.stopListening();
}
window.US.broker.unsubscribe('popup::autocompleteSearchResults',
this.onAutocompleteSearchResults, this);
window.US.broker.unsubscribe('popup::popupClose', this.onPopupClose, this);
window.US.broker.unsubscribe('popup::popupOpen', this.onPopupOpen, this);
window.US.broker.unsubscribe('popup::suggestedSearchResults',
this.onSuggestedSearchResults, this);
window.US.broker.unsubscribe('urlbar::navigationalKey',
this.onNavigationalKey, this);
},
onContentMessage: function(id, msg, sender) {
if (id !== this.channelId) { return; }
window.US.broker.publish('iframe::' + msg.type, msg.data);
},
// Dedupe sequential messages if the user input hasn't changed. See #18 and
// associated commit message for gnarly details.
//
// Note, there is some duplication in the deduping logic in these two fns.
// However, I'm not sure the result of functional decomposition (extracting
// the dedupe function into a memoize-like combinator) would actually yield
// more understandable or readable code than what we've got here. :-\
onAutocompleteSearchResults: function(msg) {
const currentInput = msg && msg.length && msg[0].text;
if (currentInput && currentInput === this._lastAutocompleteSearchTerm) {
return;
}
this._lastAutocompleteSearchTerm = currentInput;
this.sendMessage('autocomplete-search-results', msg);
},
onSuggestedSearchResults: function(msg) {
const currentInput = msg && msg.term;
if (currentInput && currentInput === this._lastSuggestedSearchTerm) {
return;
}
this._lastSuggestedSearchTerm = currentInput;
this.sendMessage('suggested-search-results', { results: msg });
},
onNavigationalKey: function(msg) {
this.sendMessage('navigational-key', msg);
},
onPopupOpen: function(msg) {
this.sendMessage('popupopen');
},
onPopupClose: function(msg) {
this.sendMessage('popupclose');
},
sendMessage: function(evt, data) {
const msg = {
type: evt,
data: data || null
};
console.log('sending the ' + evt + ' message to content:' + JSON.stringify(msg));
const ctx = {
browser: window.US.browser,
principal: Cc['@mozilla.org/systemprincipal;1']
.createInstance(Ci.nsIPrincipal)
};
this.port.send(msg, ctx);
}
};
<file_sep>/src/lib/ui/Popup.js
// popup event handlers on the chrome side
'use strict';
/* global Cc, Ci, Cu, Components, SearchSuggestionController, Services,
XPCOMUtils */
XPCOMUtils.defineLazyModuleGetter(this, 'SearchSuggestionController',
'resource://gre/modules/SearchSuggestionController.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Promise',
'resource://gre/modules/Promise.jsm');
function Popup() {
const prefBranch = Cc['@mozilla.org/preferences-service;1']
.getService(Ci.nsIPrefService)
.getBranch('');
this.frameURL = prefBranch.getPrefType('services.universalSearch.frameURL') ?
prefBranch.getCharPref('services.universalSearch.frameURL') :
'https://d1fnkpeapwua2i.cloudfront.net/index.html';
// setting isPinned to true will force the popup to stay open forever
this.isPinned = false;
}
Popup.prototype = {
constructor: Popup,
render: function(win) {
const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
this.popup = win.document.createElementNS(ns, 'panel');
this.popup.setAttribute('type', 'autocomplete-richlistbox');
this.popup.setAttribute('id', 'PopupAutoCompleteRichResultUnivSearch');
this.popup.setAttribute('noautofocus', 'true');
const oldPopup = win.document.getElementById('PopupAutoCompleteRichResult');
this.popupParent = oldPopup.parentElement;
this.popupParent.appendChild(this.popup);
// wait till the XBL binding is applied, then override this method
this.popup._appendCurrentResult = this._appendCurrentResult.bind(this);
// XXX For some bizarre reason I can't just use handleEvent to listen for
// the browser element's load event. So, falling back to .bind
this.onBrowserLoaded = this.onBrowserLoaded.bind(this);
this.popup.addEventListener('popuphiding', this);
this.popup.addEventListener('popupshowing', this);
window.US.broker.subscribe('iframe::autocomplete-url-clicked',
this.onAutocompleteURLClicked, this);
// XXX: The browser element is an anonymous XUL element created by XBL at
// an unpredictable time in the startup flow. We have to wait for the
// XBL constructor to set a pointer to the element. After that, we can
// set the 'src' on the browser element to point at our iframe. Once
// the iframe page loads, we can initialize a WebChannel and start
// communication.
this.waitForBrowser();
},
derender: function(win) {
// remove the load listener, in case uninstall happens before onBrowserLoaded fires
window.US.browser.removeEventListener('load', this.onBrowserLoaded, true);
this.popupParent.removeChild(this.popup);
this.popup.removeEventListener('popuphiding', this);
this.popup.removeEventListener('popupshowing', this);
delete window.US.browser;
window.US.broker.unsubscribe('iframe::autocomplete-url-clicked',
this.onAutocompleteURLClicked, this);
},
waitForBrowser: function() {
if (this.browserInitialized) { return; }
if ('browser' in window.US) {
this.browserInitialized = true;
// TODO: instead of waiting for load event, use an nsIWebProgressListener
window.US.browser.addEventListener('load', this.onBrowserLoaded, true);
window.US.browser.setAttribute('src', this.frameURL + '?cachebust=' + Date.now());
return;
}
setTimeout(() => this.waitForBrowser(), 0);
},
// when the iframe is ready, load up the WebChannel by injecting the content.js script
onBrowserLoaded: function() {
console.log('Popup: onBrowserLoaded fired');
window.US.browser.removeEventListener('load', this.onBrowserLoaded, true);
window.US.browser.messageManager.loadFrameScript('chrome://browser/content/content.js', true);
},
handleEvent: function(evt) {
const handlers = {
'popuphiding': this.onPopupHiding,
'popupshowing': this.onPopupShowing
};
if (evt.type in handlers) {
handlers[evt.type].call(this, evt);
} else {
console.log('handleEvent fired for unknown event ' + evt.type);
}
},
onAutocompleteURLClicked: function() {
this.popup.hidePopup();
},
onPopupShowing: function() {
window.US.broker.publish('popup::popupOpen');
},
onPopupHiding: function(evt) {
if (this.isPinned) {
return evt.preventDefault();
}
window.US.broker.publish('popup::popupClose');
},
_getImageURLForResolution: function(aWin, aURL, aWidth, aHeight) {
if (!aURL.endsWith('.ico') && !aURL.endsWith('.ICO')) {
return aURL;
}
const width = Math.round(aWidth * aWin.devicePixelRatio);
const height = Math.round(aHeight * aWin.devicePixelRatio);
return aURL + (aURL.contains('#') ? '&' : '#') +
'-moz-resolution=' + width + ',' + height;
},
_appendCurrentResult: function() {
const autocompleteResults = this._getAutocompleteSearchResults();
// TODO: refactor
this._getSearchSuggestions().then(function(searchSuggestions) {
window.US.broker.publish('popup::autocompleteSearchResults', autocompleteResults);
delete searchSuggestions.formHistoryResult;
window.US.broker.publish('popup::suggestedSearchResults',
searchSuggestions);
}, function(err) {
Cu.reportError(err);
window.US.broker.publish('popup::autocompleteSearchResults', autocompleteResults);
window.US.broker.publish('popup::suggestedSearchResults', []);
});
},
_getAutocompleteSearchResults: function() {
const controller = this.popup.mInput.controller;
const maxResults = 5;
let results = [];
// the controller's searchStatus is not a reliable way to decide when/what to send.
// instead, we'll just check the number of results and act accordingly.
if (controller.matchCount) {
results = [];
for (let i = 0; i < Math.min(maxResults, controller.matchCount); i++) {
const chromeImgLink = this._getImageURLForResolution(window, controller.getImageAt(i), 16, 16);
// if we have a favicon link, it'll be of the form "moz-anno:favicon:http://link/to/favicon"
// else, it'll be a chrome:// link to the default favicon img
const imgMatches = chromeImgLink.match(/^moz-anno\:favicon\:(.*)/);
results.push({
url: Components.classes['@mozilla.org/intl/texttosuburi;1'].
getService(Components.interfaces.nsITextToSubURI).
unEscapeURIForUI('UTF-8', controller.getValueAt(i)),
image: imgMatches ? imgMatches[1] : null,
title: controller.getCommentAt(i),
type: controller.getStyleAt(i),
text: controller.searchString.trim()
});
}
}
return results;
},
_getSearchSuggestions: function() {
//
// now, we also want to include the search suggestions in the output, via some separate signal.
// a lot of this code lifted from browser/modules/AboutHome.jsm and browser/modules/ContentSearch.jsm
// ( face-with-open-mouth-and-cold-sweat-emoji ), heh
//
// TODO: maybe just send signals to ContentSearch instead, the problem there is that I couldn't
// figure out which message manager to pass into ContentSearch, in order to get the response message back.
// it's possible all of this code was unnecessary and we could just fire a GetSuggestions message into
// the ether, and fully expect to get a Suggestions object back with the suggestions. /me shrugs
//
//var suggestionData = { engineName: engine.name, searchString: gURLBar.inputField.value, remoteTimeout: 5000 };
//ContentSearch._onMessageGetSuggestions(brow.messageManager, suggestionData);
const controller = this.popup.mInput.controller;
// it seems like Services.search.isInitialized is always true?
if (!Services.search.isInitialized) {
return;
}
const MAX_LOCAL_SUGGESTIONS = 3;
const MAX_SUGGESTIONS = 6;
const REMOTE_TIMEOUT = 500; // same timeout as in SearchSuggestionController.jsm
const isPrivateBrowsingSession = false; // we don't care about this right now
// searchTerm is the same thing as the 'text' item sent down in each result.
// maybe that's not a useful place to put the search term...
const searchTerm = controller.searchString.trim();
// unfortunately, the controller wants to do some UI twiddling.
// and we don't have any UI to give it. so it barfs.
const searchController = new SearchSuggestionController();
const engine = Services.search.currentEngine;
const ok = SearchSuggestionController.engineOffersSuggestions(engine);
searchController.maxLocalResults = ok ? MAX_LOCAL_SUGGESTIONS : MAX_SUGGESTIONS;
searchController.maxRemoteResults = ok ? MAX_SUGGESTIONS : 0;
searchController.remoteTimeout = REMOTE_TIMEOUT;
const suggestions = searchController.fetch(searchTerm, isPrivateBrowsingSession, engine);
// returns a promise for the formatted results of the search suggestion engine
return suggestions;
}
};
<file_sep>/src/lib/main.js
'use strict';
// TODO: bootstrapped extensions cache strings, scripts, etc forever.
// figure out when and how to cache-bust.
// bugs 918033, 1051238, 719376
/* global Components, CustomizableUI, Services, XPCOMUtils */
const { utils: Cu } = Components;
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Services',
'resource://gre/modules/Services.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'WebChannel',
'resource://gre/modules/WebChannel.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'console',
'resource://gre/modules/devtools/Console.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'CustomizableUI',
'resource:///modules/CustomizableUI.jsm');
const EXPORTED_SYMBOLS = ['Main']; // eslint-disable-line no-unused-vars
const onTabSelect = function() { console.log('onTabSelect'); };
const onTabOpen = function() { console.log('onTabOpen'); };
const onTabClose = function() { console.log('onTabClose'); };
const loadIntoWindow = function(win) {
console.log('loadIntoWindow start');
const document = win.document;
// set the app global per-window
if (win.US === undefined) {
Object.defineProperty(win, 'US', {configurable: true, value: {}});
} else {
win.US = win.US || {};
}
// hide the search bar, if it's visible; this will be null if not
const searchBarLocation = CustomizableUI.getPlacementOfWidget('search-container');
if (searchBarLocation) {
win.US.searchBarLocation = searchBarLocation;
CustomizableUI.removeWidgetFromArea('search-container');
}
// use Services.scriptloader.loadSubScript to load any addl scripts.
Services.scriptloader.loadSubScript('chrome://universalsearch-lib/content/Broker.js', win);
Services.scriptloader.loadSubScript('chrome://universalsearch-lib/content/Transport.js', win);
Services.scriptloader.loadSubScript('chrome://universalsearch-lib/content/ui/Popup.js', win);
Services.scriptloader.loadSubScript('chrome://universalsearch-lib/content/ui/Urlbar.js', win);
// load the CSS into the document. not using the stylesheet service.
const stylesheet = document.createElementNS('http://www.w3.org/1999/xhtml', 'h:link');
stylesheet.rel = 'stylesheet';
stylesheet.href = 'chrome://universalsearch-root/content/skin/binding.css';
stylesheet.type = 'text/css';
stylesheet.style.display = 'none';
document.documentElement.appendChild(stylesheet);
win.US.broker = win.Broker;
win.US.transport = new win.Transport();
win.US.transport.init();
win.US.popup = new win.Popup();
win.US.popup.render(win);
win.US.urlbar = new win.Urlbar();
win.US.urlbar.render(win);
win.US.gURLBar = win.gURLBar;
win.gBrowser.tabContainer.addEventListener('TabSelect', onTabSelect);
win.gBrowser.tabContainer.addEventListener('TabOpen', onTabOpen);
win.gBrowser.tabContainer.addEventListener('TabClose', onTabClose);
};
// basically reverse the loadIntoWindow function
const unloadFromWindow = function(win) {
console.log('unloadFromWindow start');
win.US.goButton.derender(win);
win.gBrowser.tabContainer.removeEventListener('TabSelect', onTabSelect);
win.gBrowser.tabContainer.removeEventListener('TabOpen', onTabOpen);
win.gBrowser.tabContainer.removeEventListener('TabClose', onTabClose);
win.US.urlbar.derender(win);
win.US.popup.derender(win);
win.US.transport.shutdown();
win.US.broker.shutdown();
// show the search bar, if it was visible originally
if (win.US.searchBarLocation) {
const loc = win.US.searchBarLocation;
CustomizableUI.addWidgetToArea('search-container', loc.area, loc.position);
}
// delete any dangling refs
delete win.US;
delete win.Broker;
// TODO: not sure these steps are technically necessary:
// remove stylesheet
// remove subscripts (not sure this is possible, can we just remove the app global?)
};
function onWindowNotification(win, topic) {
if (topic !== 'domwindowopened') { return; }
console.log('iterating windows');
win.addEventListener('load', function loader() {
win.removeEventListener('load', loader, false);
if (win.location.href === 'chrome://browser/content/browser.xul') {
loadIntoWindow(win);
}
}, false);
}
function load() {
const enumerator = Services.wm.getEnumerator('navigator:browser');
while (enumerator.hasMoreElements()) {
const win = enumerator.getNext();
try {
loadIntoWindow(win);
} catch (ex) {
console.log('load into window failed: ', ex);
}
}
Services.ww.registerNotification(onWindowNotification);
}
function unload() {
const enumerator = Services.wm.getEnumerator('navigator:browser');
while (enumerator.hasMoreElements()) {
const win = enumerator.getNext();
try {
unloadFromWindow(win);
} catch (ex) {
console.log('unload from window failed: ', ex);
}
}
Services.ww.unregisterNotification(onWindowNotification);
}
const Main = { load: load, unload: unload }; // eslint-disable-line no-unused-vars
| 56a439a66fa7b58462c1cbd1ae540e7c5066ba41 | [
"JavaScript"
] | 3 | JavaScript | chuckharmston/universal-search-addon | d39af6b305a13d49409e1ae24517d772ca5b0fa2 | 6c151991e95360bce3e8741c5f1f820a277b5392 |
refs/heads/master | <file_sep># Car_DB_mngmnt
high-level interface for accessing and modifying database + REST API
<file_sep>from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql.json import JSONB
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:coderslab@localhost:5432/cars_db'
db = SQLAlchemy(app)
class Brand(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(100), unique=True)
cars = db.relationship('Car', backref='car', cascade='all, delete-orphan', lazy='dynamic')
def __init__(self, name):
self.name = name
class Car(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
model = db.Column(db.String(100))
brand = db.Column(db.Integer, db.ForeignKey('brand.id'))
info = db.Column(JSONB)
def __init__(self, model, brand, info):
self.model = model
self.brand = brand
self.info = info
if __name__ == '__main__':
pass<file_sep>from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from models import Car, Brand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:coderslab@localhost:5432/cars_db'
db = SQLAlchemy(app)
class CarDB(object):
@app.route('/brand/new', methods=['POST'])
def crate_brand(self, name):
new_brand = Brand(name)
db.session.add(new_brand)
db.session.commit()
return jsonify(new_brand)
@app.route('/car/new', methods=['POST'])
def create_car(self, brand, model, **info):
new_car = Car(brand, model, **info)
db.session.add(new_car)
db.session.commit()
return jsonify(new_car)
@app.route('/car', methods=['GET'])
def get_all_cars(self):
cars = Car.query.all()
output = []
for car in cars:
car_data = {'id': car.id, 'model': car.model, 'brand': car.brand, 'info': car.info}
output.append(car_data)
return jsonify(output)
@app.route('/brand', methods=['GET'])
def get_all_brands(self):
brands = Brand.query.all()
output = []
for brand in brands:
brand_data = {'id': brand.id, 'name': brand.name}
output.append(brand_data)
return jsonify(output)
@app.route('/car/<int:car_id>', methods=['DELETE'])
def car_delete(car_id):
car = Car.query.get(car_id)
if car in None:
return '404'
db.session.delete(car)
db.session.commit()
return 'The car has been deleted'
@app.route('/car/<int:car_id>', methods=['PUT'])
def car_update(car_id):
car = Car.query.get(car_id)
if car is None:
return '404'
model = request.json['model']
brand = request.json['brand']
info = request.json['info']
car.model = model
car.brand = brand
car.info = info
db.session.commit()
return "The requested update has been made"
if __name__ == '__main__':
app.run(debug=True)
| 515aab77f6ed1d7f703eecd49186dbf04fdc10e8 | [
"Markdown",
"Python"
] | 3 | Markdown | majbog/Car_DB_mngmnt | 4b33336acae49458e3c4bd1be434ada2232c0ce2 | 8de1752d65963a71890ec8e6304b8a05a1ae1a5f |
refs/heads/master | <file_sep>import subprocess
import time
from typing import Any, List
import cli_ui as ui
import pkg_resources
class InvalidCommand(Exception):
pass
class Looper:
def __init__(
self,
*,
cmd: List[str],
max_tries: int,
stop_on_first_fail: bool,
capture: bool,
delay: float,
total_time: float,
):
if not cmd or not cmd[0]:
raise InvalidCommand("no command provided")
self.cmd = cmd
self.cmd_str = " ".join(self.cmd)
self.max_tries = max_tries
self.stop_on_first_fail = stop_on_first_fail
self.capture = capture
self.runs = 0
self.fails = 0
self.delay = delay
self.total_time = total_time
self.start = 0.0
self.duration = 0.0
self.run_durations: List[float] = list()
def run_cmd(self, **kwargs: Any) -> int:
run_start_time = time.time()
ui.info_2(f"run #{self.runs + 1}")
ui.info_2(self.cmd_str)
if self.capture:
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.PIPE
try:
process = subprocess.run(self.cmd, **kwargs)
except FileNotFoundError:
raise InvalidCommand(f"unkown command provided: {self.cmd[0]}")
self.runs += 1
if process.returncode:
self.fails += 1
if process.stdout:
ui.info_1(process.stdout.decode("utf-8"))
if process.stderr:
ui.error(process.stderr.decode("utf-8"))
end = time.time()
self.duration = end - self.start
self.run_durations.append(end - run_start_time)
return process.returncode
def _print_summary(self) -> None:
summary = (
f'command "{self.cmd_str}" failed {self.fails} times after {self.runs} '
+ f"tries in {self.duration:.2f} seconds"
)
if self.run_durations:
self.run_durations.sort()
max_time = self.run_durations[-1]
min_time = self.run_durations[0]
mean_time = sum(self.run_durations) / len(self.run_durations)
length = len(self.run_durations)
if length == 1:
med_time = self.run_durations[0]
else:
med_time = self.run_durations[length // 2 + 1]
if length % 2 == 0:
med_time = (self.run_durations[length // 2] + med_time) / 2
summary = f"{summary} max: {max_time:.2f}, min: {min_time:.2f}, mean: {mean_time:.2f}, median: {med_time:.2f}" # noqa: 501
ui.info_1(summary)
def loop(self) -> None:
self.start = time.time()
try:
while True:
if self.run_cmd():
if self.stop_on_first_fail:
break
if self.max_tries and self.runs >= self.max_tries:
break
if self.total_time:
ui.info_3(f"time elapsed: {self.duration:.2f} seconds")
if self.duration > self.total_time:
break
if self.delay:
ui.info_3(f"waiting for {self.delay:.2f} seconds")
time.sleep(self.delay)
except KeyboardInterrupt:
ui.info_2("Interrupted by user")
finally:
self._print_summary()
@classmethod
def version(cls) -> str:
return pkg_resources.require("py-loop")[0].version
<file_sep>import argparse
import sys
from typing import List, Optional
import cli_ui as ui
from py_loop.looper import Looper
ArgsList = Optional[List[str]]
def main(args: ArgsList = None) -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"cmd",
nargs=argparse.REMAINDER,
help="The command you want to run in a loop (at the end of the full command line)",
)
parser.add_argument(
"-m",
"--max-tries",
type=int,
default=100,
help="Maximum number of time running the command, 0 means no limit",
)
parser.add_argument(
"-s",
"--stop-on-first-fail",
action="store_true",
help="If set looper will stop on the first fail",
)
parser.add_argument(
"-c", "--no-capture", action="store_true", help="Don't capture output"
)
parser.add_argument("-v", "--version", action="store_true")
parser.add_argument(
"-d", "--delay", type=float, default=0, help="Delay between runs"
)
parser.add_argument(
"-t",
"--total-time",
type=float,
default=0,
help="Total time of the runs in seconds, O means no limit",
)
args_ns = parser.parse_args(args=args)
if args_ns.version:
ui.info_1(Looper.version())
return
if not args_ns.cmd or not args_ns.cmd[0]:
ui.error("no command provided")
sys.exit(1)
looper = Looper(
cmd=args_ns.cmd,
max_tries=args_ns.max_tries,
stop_on_first_fail=args_ns.stop_on_first_fail,
capture=(not args_ns.no_capture),
delay=args_ns.delay,
total_time=args_ns.total_time,
)
looper.loop()
<file_sep>[](https://opensource.org/licenses/MIT)
[](https://codecov.io/gh/jeremad/looper)
# Basic tool to run commands in loop
This tool was intended to help QA guy like me with flaky tests, buy either measuring the "flakyness" of the test, or run it until it fails to debug it.
## Usage
Let's say your test command is `run test`
### Debug
You want to run a test until it fails to debug it, and you know it may take a while:
`$ looper --max-tries 0 --stop-on-first-fail "run test"`
`max-tries` to 0, means that there is no limit to the number of times a test can sucessfully run
### Measure
You want to find the failing rate of a test of out 1000 runs:
`$ looper --max-tries 1000 "run test"`
At the end you will have a sumary
## Installation
`pip install --user py-loop`
<file_sep>from .looper import InvalidCommand, Looper # noqa
<file_sep>[tool.poetry]
name = "py-loop"
version = "0.4.1"
description = "Run commands until it fails"
authors = ["jerem <<EMAIL>>"]
[tool.poetry.dependencies]
python = ">=3.8.1,<4.0"
cli-ui = "^0.17.2"
[tool.poetry.dev-dependencies]
black = "23.3.0"
codecov = "^2.01.13"
flake8 = "6.0.0"
mypy = "1.2.0"
pytest = "^7.3.1"
pytest-cov = "^4.0.0"
types-setuptools = "^172.16.58.3"
isort = "^5.12.0"
[tool.poetry.group.dev.dependencies]
twine = "^4.0.2"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
[tool.poetry.scripts]
looper = 'py_loop.main:main'
<file_sep>import re
import pytest
import py_loop as looper
@pytest.mark.parametrize("max_tries", [1, 10, 100])
def test_max_success(max_tries: int) -> None:
cmd_looper = looper.Looper(
cmd=["ls"],
max_tries=max_tries,
stop_on_first_fail=False,
capture=False,
delay=0,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.runs == max_tries
assert cmd_looper.fails == 0
@pytest.mark.parametrize("max_tries", [1, 10, 100])
def test_max_fails(max_tries: int) -> None:
cmd_looper = looper.Looper(
cmd=["ls", "/plop"],
max_tries=max_tries,
stop_on_first_fail=False,
capture=False,
delay=0,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.runs == max_tries
assert cmd_looper.fails == max_tries
def test_stop_on_first_fail() -> None:
cmd_looper = looper.Looper(
cmd=["ls", "/plop"],
max_tries=10,
stop_on_first_fail=True,
capture=False,
delay=0,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.runs == 1
assert cmd_looper.fails == 1
def test_fail_and_std() -> None:
cmd_looper = looper.Looper(
cmd=["ls", "/plop"],
max_tries=1,
stop_on_first_fail=True,
capture=True,
delay=0,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.fails == 1
def test_wrong_cmd() -> None:
cmd_looper = looper.Looper(
cmd=["llllll"],
max_tries=10,
stop_on_first_fail=True,
capture=False,
delay=0,
total_time=0,
)
with pytest.raises(looper.InvalidCommand):
cmd_looper.loop()
assert cmd_looper.runs == 0
assert cmd_looper.fails == 0
def test_empty_cmd() -> None:
with pytest.raises(looper.InvalidCommand):
looper.Looper(
cmd=[""],
max_tries=10,
stop_on_first_fail=True,
capture=False,
delay=0,
total_time=0,
)
def test_stop_after_a_while() -> None:
cmd_looper = looper.Looper(
cmd=[
"python",
"-c",
"import time; import sys; sys.exit(not int(time.time() % 3))",
],
max_tries=10000000000,
stop_on_first_fail=True,
capture=False,
delay=0,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.fails == 1
def test_total_delay() -> None:
max_tries = 10
delay = 0.1
cmd_looper = looper.Looper(
cmd=["ls"],
max_tries=max_tries,
stop_on_first_fail=True,
capture=False,
delay=delay,
total_time=0,
)
cmd_looper.loop()
assert cmd_looper.fails == 0
assert cmd_looper.runs == max_tries
diff = cmd_looper.duration - (max_tries - 1) * delay
assert diff > 0
assert diff < 0.1
def test_total_time_even() -> None:
total_time = 1
max_tries = 100
delay = 0.1
cmd_looper = looper.Looper(
cmd=["ls"],
max_tries=max_tries,
stop_on_first_fail=True,
capture=False,
delay=delay,
total_time=total_time,
)
cmd_looper.loop()
assert cmd_looper.fails == 0
assert cmd_looper.runs <= (total_time / delay + 1)
diff = cmd_looper.duration - total_time
assert diff > 0
assert cmd_looper.duration - total_time < 0.1
def test_total_time_odd() -> None:
total_time = 1
max_tries = 101
delay = 0.1
cmd_looper = looper.Looper(
cmd=["ls"],
max_tries=max_tries,
stop_on_first_fail=True,
capture=False,
delay=delay,
total_time=total_time,
)
cmd_looper.loop()
assert cmd_looper.fails == 0
assert cmd_looper.runs <= (total_time / delay + 1)
diff = cmd_looper.duration - total_time
assert diff > 0
assert cmd_looper.duration - total_time < 0.1
def test_version() -> None:
pattern = re.compile(r"\d+\.\d+\.\d+")
version = looper.Looper.version()
assert pattern.match(version)
<file_sep>import pytest
import py_loop.main as looper_main
def test_version() -> None:
looper_main.main(["--version"])
def test_no_cmd() -> None:
with pytest.raises(SystemExit) as e:
looper_main.main([""])
assert e.value.code == 1
def test_cmd() -> None:
looper_main.main(["ls", "--max-tries", "1"])
looper_main.main(["--max-tries", "1", "ls"])
<file_sep>[run]
omit = looper/tests/*
<file_sep>#!/usr/bin/env sh
set -x
set -e
poetry build
poetry run twine upload dist/* --verbose
| eaa5be78e5a53db0c7a335ce234bb07cff0f03a9 | [
"Markdown",
"TOML",
"INI",
"Python",
"Shell"
] | 9 | Python | jeremad/looper | 56f2c504a43b09398bd296c283030506192ee946 | 569fd9487f7ce185dcd79bf4d12e4d946bafc23f |
refs/heads/main | <repo_name>RyanTakes/cedarrapids-ops-201d3-OPsChallenge4<file_sep>/README.md
# cedarrapids-ops-201d3-OPsChallenge4<file_sep>/array.sh
#!/bin/bash
dir1="dir1"
dir2="dir2"
dir3="dir3"
dir4="dir4"
arraydir=("/home/ryan/dir1" "/home/ryan/dir2" "/home/ryan/dir3" "/home/ryan/dir4")
echo ${arraydir[*]}
| d91b35ec19485eece0622da4a78e4046033f16b8 | [
"Markdown",
"Shell"
] | 2 | Markdown | RyanTakes/cedarrapids-ops-201d3-OPsChallenge4 | 3eace4fbf069fc76666a220b6ae216f740c1855d | 2641acb83953c2e810da572e61b9a3236547f7c9 |
refs/heads/main | <file_sep>DROP TABLE IF EXISTS measurement CASCADE;
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
) PARTITION BY RANGE (logdate);
DROP TABLE IF EXISTS measurement_y2006m02;
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01');
DROP TABLE IF EXISTS measurement_y2006m03;
CREATE TABLE measurement_y2006m03 PARTITION OF measurement
FOR VALUES FROM ('2006-03-01') TO ('2006-04-01');
CREATE INDEX measurement_logdate ON measurement (logdate);
CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
INSERT INTO measurement(
city_id, logdate, peaktemp, unitsales)
VALUES (1, '2006-02-02', 1, 1);
INSERT INTO measurement(
city_id, logdate, peaktemp, unitsales)
VALUES (1, '2006-03-02', 1, 1);
SELECT * FROM measurement;<file_sep>const mysql = require('mysql2/promise');
require('dotenv').config()
const env = process.env;
const tui = require('./tui.js');
const master = {
host: env.MYSQL_MASTER_HOST,
user: env.MYSQL_MASTER_USER,
pass: env.MYSQL_MASTER_PASSWORD
};
const slave1 = {
user: env.MYSQL_SLAVE1_USER,
pass: env.MYSQL_SLAVE1_PASSWORD,
host: env.MYSQL_SLAVE1_HOST,
rootUser: env.MYSQL_SLAVE1_ROOT_USER,
rootPass: env.MYSQL_SLAVE1_ROOT_PASS
}
const slave2 = {
user: env.MYSQL_SLAVE2_USER,
pass: env.MYSQL_SLAVE2_PASSWORD,
host: env.MYSQL_SLAVE2_HOST,
rootUser: env.MYSQL_SLAVE2_ROOT_USER,
rootPass: env.MYSQL_SLAVE2_ROOT_PASS
}
const DropUserIfExists = user => { return `DROP USER IF EXISTS '${user}'@'%'` }
const CreateUserForReplica = (user, password) => { return `CREATE USER '${user}'@'%' IDENTIFIED BY '${password}';` }
const ShowUsers = () => { return `SELECT HOST, USER FROM MYSQL.USER;` }
const GrantReplicationFor = (user) => { return `GRANT REPLICATION SLAVE ON *.* TO '${user}'@'%';` }
const FlushPrivileges = () => { return `FLUSH PRIVILEGES;` }
const ShowMasterStatus = () => { return `SHOW MASTER STATUS;` }
const ChangeMaster = (masterHost, masterUser, masterPass, masterLogFile, masterLogPos) => {
return `CHANGE MASTER TO MASTER_HOST = '${masterHost}',
MASTER_USER = '${masterUser}',
MASTER_PASSWORD = '${masterPass}',
MASTER_LOG_FILE = '${masterLogFile}',
MASTER_LOG_POS = ${masterLogPos};`;
}
const StartReplica = () => { return "START REPLICA;" };
const StopReplica = () => { return "STOP REPLICA;" }
const ShowReplicaStatus = () => { return "SHOW REPLICA STATUS;" }
const CreateBooksTable = () => {
return "CREATE TABLE IF NOT EXISTS `books`.`books`( `id` INT NOT NULL AUTO_INCREMENT , `name` TEXT NOT NULL , `author` TEXT NOT NULL , `year` INT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;";
}
const DropTableBooks = () => {
return "DROP TABLE IF EXISTS `books`.`book`;"
}
const ShowTables = () => { return "SHOW TABLES;"; }
const ShowBooksTable = () => { return "SELECT * FROM books;" }
const GrantPrivilegesToBooksDb = (user) => { return `GRANT ALL PRIVILEGES ON books.* TO '${user}'@'%';`; }
const InsertIntoBooks = (name, author, year) => {
return `INSERT INTO \`books\`(\`name\`, \`author\`, \`year\`) VALUES ('${name}','${author}','${year}');`
}
const DropYearColumn = () => { return `ALTER TABLE books DROP COLUMN year;` }
const DropNameColumn = () => { return `ALTER TABLE books DROP COLUMN name;` }
const GetConnection = async (host, user, pass, db) => {
return await mysql.createConnection({
host: host,
user: user,
password: <PASSWORD>,
database: db
});
}
(async () => {
let connection = null
const cm = async () => {
connection = await GetConnection(master.host, master.user, master.pass, env.MYSQL_DATABASE)
console.log('Connected to master')
}
const cs1 = async () => {
connection = await GetConnection(slave1.host, slave1.user, slave1.pass, env.MYSQL_DATABASE)
console.log('Connected to slave1')
}
const cs2 = async () => {
connection = await GetConnection(slave2.host, slave2.user, slave2.pass, env.MYSQL_DATABASE)
console.log('Connected to slave2')
}
const rs1 = async () => {
await cm();
const user = slave1.user;
const pass = <PASSWORD>;
await connection.execute(DropUserIfExists(user));
await connection.execute(CreateUserForReplica(user, pass));
await connection.execute(GrantReplicationFor(user));
await connection.execute(FlushPrivileges());
const log = await sms();
connection = await GetConnection(slave1.host, slave1.rootUser, slave1.rootPass, env.MYSQL_DATABASE)
await connection.execute(GrantPrivilegesToBooksDb(slave1.user));
await connection.execute(StopReplica());
await connection.execute(ChangeMaster(master.host, slave1.user, slave1.pass, log.file, log.pos));
await connection.execute(StartReplica());
}
const rs2 = async () => {
await cm();
const user = slave2.user;
const pass = <PASSWORD>;
await connection.execute(DropUserIfExists(user));
await connection.execute(CreateUserForReplica(user, pass));
await connection.execute(GrantReplicationFor(user));
await connection.execute(FlushPrivileges());
const log = await sms();
connection = await GetConnection(slave2.host, slave2.rootUser, slave2.rootPass, env.MYSQL_DATABASE)
await connection.execute(GrantPrivilegesToBooksDb(slave2.user));
await connection.execute(StopReplica());
await connection.execute(ChangeMaster(master.host, slave2.user, slave2.pass, log.file, log.pos));
await connection.execute(StartReplica());
}
const su = async () => {
const [rows, fields] = await connection.execute(ShowUsers());
console.log(rows)
}
const sms = async () => {
const [rows, fields] = await connection.execute(ShowMasterStatus());
const masterStatus = {
file: rows[0].File,
pos: rows[0].Position,
binlogdb: rows[0].Binlog_Do_DB
};
console.log(masterStatus);
return masterStatus;
}
const srs = async () => {
const [rows, fields] = await connection.execute(ShowReplicaStatus());
console.log({
Replica_IO_State: rows[0].Replica_IO_State,
Source_Host: rows[0].Source_Host,
Source_User: rows[0].Source_User,
Source_Log_File: rows[0].Source_Log_File,
Read_Source_Log_Pos: rows[0].Read_Source_Log_Pos,
Relay_Log_File: rows[0].Relay_Log_File,
Relay_Log_Pos: rows[0].Relay_Log_Pos,
Relay_Source_Log_File: rows[0].Relay_Source_Log_File,
Last_IO_Errno: rows[0].Last_IO_Errno,
Last_IO_Error: rows[0].Last_IO_Error,
Last_SQL_Errno: rows[0].Last_SQL_Errno,
Last_SQL_Error: rows[0].Last_SQL_Error
});
}
const ctb = async () => {
await connection.execute(DropTableBooks());
await connection.execute(CreateBooksTable());
}
const sb = async () => {
const [rows] = await connection.execute(ShowTables());
console.log(rows)
}
const stb = async () => {
const [rows] = await connection.execute(ShowBooksTable());
console.log(rows)
}
const ibm = async () => {
await connection.execute(InsertIntoBooks("<NAME>", "<NAME>", "1234"))
}
const ibmM = async () => {
connections = []
for (let index = 0; index < 50; index++) {
connections.push(await GetConnection(master.host, master.user, master.pass, env.MYSQL_DATABASE));
}
for (let outer = 0; outer < 100; outer++) {
promises = []
for (let index = 0; index < connections.length; index++) {
promises.push(connections[index].execute(InsertIntoBooks("<NAME>", "<NAME>", "1234")));
}
const awaitAll = async (promises) => {
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(() => {
resolve()
})
.catch((err) => {
reject(err)
})
})
}
await awaitAll(promises)
}
}
const dcy = async () => {
await connection.execute(DropYearColumn())
}
const dcn = async () => {
await connection.execute(DropNameColumn())
}
const t = new tui({
cm: {
description: "Connect to master",
callback: cm
},
cs1: {
description: "Connect to slave1",
callback: cs1
},
cs2: {
description: "Connect to slave2",
callback: cs2
},
rs1: {
description: "Configure replication for slave1",
callback: rs1
},
rs2: {
description: "Configure replication for slave2",
callback: rs2
},
su: {
description: "Show users",
callback: su
},
sms: {
description: "Show master status",
callback: sms
},
srs: {
description: "Show replicat status",
callback: srs
},
ctb: {
description: "Create table books [id, name, author, year]",
callback: ctb
},
st: {
description: "Show tables",
callback: sb
},
stb: {
description: "Show table `books`",
callback: stb
},
ibm: {
description: "Insert data into books table on master",
callback: ibm
},
ibmM: {
description: "Inserting data into books table on master 100 000",
callback: ibmM
},
dcy: {
description: "Drop year column from books",
callback: dcy
},
dcn: {
description: "Drop name column from books",
callback: dcn
}
}, (err) => {
console.error(err)
})
const args = process.argv.slice(2);
for (let index = 0; index < args.length; index++) {
console.log(args[index])
await t.CallManually(args[index]);
}
await t.Run()
})()
.then(() => process.exit(0))
.catch((err) => {
console.error(err)
process.exit(1)
})<file_sep># MySQL database replication
## Tasks:
1. Create 3 docker containers: mysql-m, mysql-s1, mysql-s2
2. Setup master slave replication (Master: mysql-m, Slave: mysql-s1, mysql-s2)
3. Write script that will frequently write data to database
4. Ensure, that replication is working
5. Try to turn off mysql-s1
6. Try to remove a column in database on slave node
## 1. Create 3 docker containers
Docker containers are described in [docker-compose.yml]
Before running mysql instances run
```sh
./scripts/clean.sh
```
[docker-compose.yml]: <https://github.com/ZaharBozhok/HL/blob/main/HW-18-db-replication/docker-compose.yml>
## 2. Setup master slave replication
Start all mysql instances using following script
```sh
./scripts/run-mysql-instances.sh
```
And make sure that all instances are initialized properly (I was checking using this command `docker-compose logs -f mysql-<x>`, simply it should stop printing logs after some time saying that it is ready to handle new connections).
Then run replication configuration script :
```sh
./scripts/configure-replication.sh
```
## 3. Frequently write data to database
NodeApp has a command to create 50 connections and send 100 inserts (per connection).
To insert 5000 rows run script:
```sh
./scripts/insert-books.sh
```
And if you want to see inserted data use following scripts:
```sh
# To see rows on master
./scripts/show-books-m.sh
# To see rows on slave1
./scripts/show-books-s1.sh
# To see rows on slave2
./scripts/show-books-s2.sh
```
## 4. Check that replication is working
To ensure that replicaton is working you can either insert rows using scripts from section 3, or run `docker-compose up -d phpMyAdmin`, open `localhost` in browser and connect to (`mysql-m`|`mysql-s1`|`mysql-s2`) and see that rows are inserted after inserting in master.
## 5. Turning off mysql-s1
To turn off mysql-s1 just run following:
```sh
docker-compose stop mysql-s1
```
And if you run it again it will download all needed data (if i'm not mistaken reading it from master's binlog). So after slave "reboot" not synced data will be replicated to the slave.
## 6. Removing a column on a slave db table
As for example following script removes column "name" from "books" table on slave1:
```sh
./scripts/drop-name-col-s1.sh
```
P.S. I tested dropping last column ("year") and it was still replicating good, but without last column. And when I dropped column in the middle of other columns (like "name") it inserted with shifting. Instead of not writing master's "name" to slave's "name" it writes to master's "name" to slave's "author".<file_sep>#!/bin/bash
docker-compose run nodeApp npm start -- cm rs1 srs cm rs2 srs cm su sms cm ctb ibm ibm stb cs1 stb cs2 stb exit
<file_sep>#!/bin/bash
docker-compose run nodeApp npm start -- cs1 stb exit<file_sep>#!/bin/bash
docker-compose run nodeApp npm start -- cm stb exit<file_sep>-- Should insert into foreign postgres_b1
INSERT INTO books(
id, category_id, author, title, year)
VALUES (1, 1, 'Cool author', 'Cool-book from `Cool Author`', 1999);
-- Should be empty, cause inserted only to postgres_b1
SELECT * FROM books;
-- Should have one row (1 from b1 and 0 from b2)
SELECT * FROM books_v;
-- Should insert into foreign postgres_b2
INSERT INTO books(
id, category_id, author, title, year)
VALUES (2, 2, 'Bad author', 'Bad-book from `Bad Author`', 1998);
-- Should have 2 rows (1 from b1 and 1 from b2)
SELECT * FROM books_v;
-- Should still be empty
SELECT * FROM books;
-- Insert 1.000.000 -- 3 min 59 sec
do
$$
declare
i record;
begin
for i in 1..500000 loop
INSERT into books
VALUES (i,1, 'Author', 'Title', 2000),
(i,2, 'Author', 'Title', 2000);
end loop;
end;
$$
;
-- Insert 100.000 -- 23 sec
do
$$
declare
i record;
begin
for i in 1..50000 loop
INSERT into books
VALUES (i,1, 'Author', 'Title', 2000),
(i,2, 'Author', 'Title', 2000);
end loop;
end;
$$
;<file_sep>#!/bin/bash
mkdir -p master-data slave1-data slave2-data
docker-compose up -d mysql-m mysql-s1 mysql-s2<file_sep># HL
Learning tricks for highload
<file_sep>DROP TABLE IF EXISTS measurement CASCADE;
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
);
DROP TABLE IF EXISTS measurement_y2006m02;
CREATE TABLE measurement_y2006m02 (
CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
) INHERITS (measurement);
DROP TABLE IF EXISTS measurement_y2006m03;
CREATE TABLE measurement_y2006m03 (
CHECK ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
) INHERITS (measurement);
CREATE INDEX measurement_logdate ON measurement (logdate);
CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
CREATE RULE measurement_insert_y2006m02 AS
ON INSERT TO measurement WHERE
( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
DO INSTEAD
INSERT INTO measurement_y2006m02 VALUES (NEW.*);
CREATE RULE measurement_insert_y2006m03 AS
ON INSERT TO measurement WHERE
( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
DO INSTEAD
INSERT INTO measurement_y2006m03 VALUES (NEW.*);
CREATE RULE measurement_insert AS
ON INSERT TO measurement
DO INSTEAD NOTHING;
INSERT INTO measurement(
city_id, logdate, peaktemp, unitsales)
VALUES (1, '2006-02-02', 1, 1);
INSERT INTO measurement(
city_id, logdate, peaktemp, unitsales)
VALUES (1, '2006-03-02', 1, 1);
SELECT * FROM measurement;<file_sep>-- Creating table books on shard1 for WHERE category_id == 1
DROP TABLE IF EXISTS books_cat1 CASCADE;
CREATE TABLE books_cat1 (
id bigint not null,
category_id int not null,
CONSTRAINT category_id_check CHECK ( category_id = 1 ),
author character varying not null,
title character varying not null,
year int not null
);
CREATE INDEX books_category_id_idx ON books_cat1 USING btree(category_id);<file_sep># docker-compose.yml
version: "3.9"
services:
mysql-m:
image: mysql:8.0
platform: linux/x86_64
container_name: "mysql-m"
env_file:
- ./master.env
volumes:
- ./master.conf:/etc/mysql/conf.d/mysql.conf.cnf
- ./master-data:/var/lib/mysql
expose:
- '3306'
mysql-s1:
image: mysql:8.0
platform: linux/x86_64
container_name: "mysql-s1"
env_file:
- ./slave1.env
volumes:
- ./slave1.conf:/etc/mysql/conf.d/mysql.conf.cnf
- ./slave1-data:/var/lib/mysql
expose:
- '3306'
depends_on:
- mysql-m
mysql-s2:
image: mysql:8.0
platform: linux/x86_64
container_name: "mysql-s2"
env_file:
- ./slave2.env
volumes:
- ./slave2.conf:/etc/mysql/conf.d/mysql.conf.cnf
- ./slave2-data:/var/lib/mysql
expose:
- '3306'
depends_on:
- mysql-m
phpMyAdmin:
image: phpmyadmin/phpmyadmin
container_name: "phpMyAdmin"
ports:
- "80:80"
environment:
- PMA_ARBITRARY=1
- MYSQL_ROOT_PASSWORD=<PASSWORD>
- MYSQL_USER=master_2021
- MYSQL_PASSWORD=<PASSWORD>
depends_on:
- mysql-m
- mysql-s1
- mysql-s2
nodeApp:
image: node:16
container_name: "nodeApp"
environment:
- NODE_ENV=production
volumes:
- ./nodeApp:/home/node/app
working_dir: /home/node/app
command: "npm start"<file_sep>const mysql = require('mysql2');
require('dotenv').config()
const env = process.env;
const master = {
host: env.MYSQL_MASTER_HOST,
user: env.MYSQL_MASTER_ROOT_USER,
pass: env.MYSQL_MASTER_ROOT_PASSWORD
}
const replications = [
{
user: env.MYSQL_SLAVE1_USER,
pass: env.MYSQL_SLAVE1_PASSWORD,
host: env.MYSQL_SLAVE1_HOST
},
{
user: env.MYSQL_SLAVE2_USER,
pass: env.MYSQL_SLAVE2_PASSWORD,
host: env.MYSQL_SLAVE2_HOST
}
];
const DropUserIfExists = user => { return `DROP USER IF EXISTS '${user}'@'%'` }
const CreateUserForReplica = (user, password) => { return `CREATE USER '${user}'@'%' IDENTIFIED BY '${password}';` }
const ShowUsers = () => { return `SELECT HOST, USER FROM MYSQL.USER;` }
(async () => {
const connection = await mysql.createConnection({
host: master.host,
user: master.user,
password: <PASSWORD>,
database: env.MYSQL_DATABASE
});
for await (replica of replications) {
const drop = await connection.execute(
DropUserIfExists(replica.user)
)
const create = await connection.execute(
CreateUserForReplica(replica.user, replica.pass)
)
}
console.log(await connection.execute(ShowUsers()))
})().then(() => console.log('Bye!'))
<file_sep>#!/bin/bash
docker-compose stop
rm -rf ./master-data/* ./slave1-data/* ./slave2-data/*
<file_sep>const readline = require('readline');
class tui {
constructor(callbacks, onError) {
this.terminal = null
this.internalCallbacks = {}
this.needToExit = false
this.ConstructInteralCallbacks(callbacks)
this.onError = onError
}
ConstructInteralCallbacks(callbacks) {
for (const [key, value] of Object.entries(callbacks)) {
this.internalCallbacks[key] = value
}
this.internalCallbacks['exit'] = {
description: "Stops IO processing and stops all companies",
callback: async () => {
this.needToExit = true
if ('exit' in callbacks) {
await callbacks['exit'].callback()
}
}
}
}
CreateTerminalIfNeeded() {
if (this.terminal) { return }
this.terminal = readline.createInterface({
input: process.stdin,
output: process.stdout
});
}
async CallManually(input) {
if (input in this.internalCallbacks) {
try {
await this.internalCallbacks[input].callback()
} catch (error) {
this.onError(error)
}
}
else {
this.terminal.write(`Unknown value \"${input}\"\r\n`)
for (const [key, value] of Object.entries(this.internalCallbacks)) {
this.terminal.write(` \"${key}\"\r\n Description : ${value.description}\r\n`)
}
}
}
async AskOnce() {
return new Promise((resolve, reject) => {
this.terminal.question('$ ', (input) => {
resolve(input)
})
})
}
async Run() {
this.CreateTerminalIfNeeded()
while (!this.needToExit) {
const input = await this.AskOnce()
if (input.length != 0) {
if (input in this.internalCallbacks) {
try {
await this.internalCallbacks[input].callback()
} catch (error) {
this.onError(error)
}
}
else {
this.terminal.write(`Unknown value \"${input}\"\r\n`)
for (const [key, value] of Object.entries(this.internalCallbacks)) {
this.terminal.write(` \"${key}\"\r\n Description : ${value.description}\r\n`)
}
}
}
}
this.terminal.close()
}
}
module.exports = tui<file_sep>-- Creating books table on master server
DROP TABLE IF EXISTS books CASCADE;
CREATE TABLE books (
id bigint not null,
category_id int not null,
author character varying not null,
title character varying not null,
year int not null
);
CREATE INDEX books_category_id_idx ON books USING btree(category_id);
-- Configuring shards
DROP EXTENSION IF EXISTS postgres_fdw CASCADE;
CREATE EXTENSION postgres_fdw;
CREATE RULE books_insert AS ON INSERT TO books
DO INSTEAD NOTHING;
CREATE RULE books_update AS ON UPDATE TO books
DO INSTEAD NOTHING;
CREATE RULE books_delete AS ON DELETE TO books
DO INSTEAD NOTHING;
-- Shard1 configuration "postgres_b1"
CREATE SERVER postgres_b1
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'postgres-b1', port '5432', dbname 'postgres');
CREATE USER MAPPING FOR postgres
SERVER postgres_b1
OPTIONS (user 'postgres', password '<PASSWORD>');
IMPORT FOREIGN SCHEMA public LIMIT TO (books_cat1)
FROM SERVER postgres_b1 INTO public;
-- Configure redirect rule from local to "postgres_b1"
CREATE RULE books_insert_cat1 AS
ON INSERT TO books
WHERE ( category_id = 1 )
DO INSTEAD
INSERT INTO books_cat1 VALUES (NEW.*);
-- Shard2 configuration "postgres_b2"
CREATE SERVER postgres_b2
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'postgres-b2', port '5432', dbname 'postgres');
CREATE USER MAPPING FOR postgres
SERVER postgres_b2
OPTIONS (user 'postgres', password '<PASSWORD>');
IMPORT FOREIGN SCHEMA public LIMIT TO (books_cat2)
FROM SERVER postgres_b2 INTO public;
-- Configure redirect rule from local to "postgres_b2"
CREATE RULE books_insert_cat2 AS
ON INSERT TO books
WHERE ( category_id = 2 )
DO INSTEAD
INSERT INTO books_cat2 VALUES (NEW.*);
-- "Gathering" view for all tables
CREATE VIEW books_v AS
SELECT * FROM books_cat1
UNION ALL
SELECT * FROM books_cat2<file_sep># PostgreSQL database sharding
## Tasks:
1. Create 3 docker containers: postgresql-b, postgresql-b1, postgresql-b2
2. Setup horizontal sharding as it’s described in this lesson
3. Insert 1 000 000 rows into books
4. Measure performance
5. Do the same without sharding
6. Compare performance
## 1. Create 3 docker containers
Docker containers are described in [docker-compose.yml]
[docker-compose.yml]: <https://github.com/ZaharBozhok/HL/blob/main/HW-19-db-sharding/docker-compose.yml>
## 2. Setup horizontal sharding
To configure horizontal sharding you first have to run all instances
```sh
docker-compose up -d
```
And then you can do all further actions in pgadmin on localhost in your browser.
Connect to `postgres-b1`, and run following script
`sql-scripts/horizontal-sharding/init-shard1.sql`.
Connect to `postgres-b2`, and run following script:
`sql-scripts/horizontal-sharding/init-shard2.sql`.
And finally connect to `postgres-b`, and run following script
`sql-scripts/horizontal-sharding/horizontal-sharding.sql`.
## 3. Insert 1 000 000 rows into books
To test insertion time with horizontal sharding run:
`sql-scripts/tests/test-horizontal-sharding.sql`.
## 4. Measure performance
Pgadmin automatically shows how much time took any operation
## 5. Do the same without sharding
To test insertion time without sharding run:
`sql-scripts/tests/test-no-sharding.sql`
## 6. Compare performance
On my Macbook air m1 2020 insertion of 1.000.000 rows with horizontal sharding took about 4 minutes, while insertion without sharding about 3 seconds. But it seems like it isn't honest test because docker adds to much impact on interacting with filesystem.
P.S. Most helpful links:
https://www.postgresql.org/docs/10/ddl-partitioning.html
https://www.postgresql.org/docs/9.5/postgres-fdw.html<file_sep>-- Creating books table on master server
DROP TABLE IF EXISTS books CASCADE;
CREATE TABLE books (
id bigint not null,
category_id int not null,
author character varying not null,
title character varying not null,
year int not null
);
CREATE INDEX books_category_id_idx ON books USING btree(category_id);
-- Insert 1.000.000 -- 3 sec
do
$$
declare
i record;
begin
for i in 1..500000 loop
INSERT into books
VALUES (i,1, 'Author', 'Title', 2000),
(i,2, 'Author', 'Title', 2000);
end loop;
end;
$$
;<file_sep>-- Creating table books on shard2 for WHERE category_id == 2
DROP TABLE IF EXISTS books_cat2 CASCADE;
CREATE TABLE books_cat2 (
id bigint not null,
category_id int not null,
CONSTRAINT category_id_check CHECK ( category_id = 2 ),
author character varying not null,
title character varying not null,
year int not null
);
CREATE INDEX books_category_id_idx ON books_cat2 USING btree(category_id); | e2a5e429edeb9c4a59d5d53a62b2d393a7ad620e | [
"SQL",
"YAML",
"JavaScript",
"Markdown",
"Shell"
] | 19 | SQL | ZaharBozhok/HL | a518e2f688368980fc894fa7786967914de046a9 | acacb6e3faf1f07567d41f0596193b8a9fc6d2af |
refs/heads/master | <file_sep>#include <Bounce2.h>
#include "EEPROMAnything.h"
//#include <MemoryFree.h>
#include <NewPing.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define motorPinUp 3
#define motorPinDown 2
#define sonarPongPin 4
#define sonarPingPin 5
#define buttonDownPin 6
#define buttonUpPin 7
#define beeperPin 12
LiquidCrystal_I2C lcd(0x27,8,2);
enum directions { none, up, down, setUp, setDown, checking, moving };
const unsigned int floorOffset = 935-280;
const unsigned int maxSafeHeight = 410;
const unsigned int minSafeHeight = 48;
const unsigned int buttonHoldTime = 2000;
const unsigned int setButtonTimeout = 5000;
const unsigned int sonarTimeout = 50;
const unsigned int screenTimeout = 10000;
directions operationMode = none;
unsigned int topHeight = 390;
unsigned int bottomHeight = 50;
unsigned int targetHeight;
unsigned int lastMeasuredHeight = 0;
unsigned int reportedHeight = 0;
unsigned int heightAccuracy = 1;
unsigned long beepEndTime = 0;
unsigned long buttonPushTime = 0;
unsigned long lastMeasuredTime = 0;
unsigned long screenLastUpdatedTime = 0;
NewPing sonar(sonarPingPin, sonarPongPin);
Bounce upDebounce = Bounce();
Bounce downDebounce = Bounce();
void setup() {
Serial.begin(115200);
Serial.println();
lcd.init();
resetScreen();
pinMode(motorPinUp, OUTPUT);
pinMode(motorPinDown, OUTPUT);
pinMode(beeperPin, OUTPUT);
pinMode(sonarPongPin, INPUT);
pinMode(sonarPingPin, OUTPUT);
pinMode(buttonUpPin, INPUT_PULLUP);
pinMode(buttonDownPin, INPUT_PULLUP);
digitalWrite(motorPinUp, LOW);
digitalWrite(motorPinDown, LOW);
upDebounce.attach(buttonUpPin);
upDebounce.interval(5);
downDebounce.attach(buttonDownPin);
downDebounce.interval(5);
Serial.println(F("================ Deskbot 1.2 ================"));
loadSettings();
if (topHeight > maxSafeHeight) {
topHeight = maxSafeHeight;
saveSettings();
}
if (bottomHeight < minSafeHeight || bottomHeight > topHeight) {
bottomHeight = minSafeHeight;
saveSettings();
}
reportVitals();
beep(50);
}
void loop() {
beep();
upDebounce.update();
downDebounce.update();
if (millis() > screenLastUpdatedTime + screenTimeout) resetScreen();
if (!upDebounce.read() && !downDebounce.read()) operationMode = none; // if both pressed, then abort
switch (operationMode) {
case checking:
if (millis() < buttonPushTime + buttonHoldTime) {
if (upDebounce.rose()) {
operationMode = moving;
targetHeight = topHeight;
}
else if (downDebounce.rose()){
operationMode = moving;
targetHeight = bottomHeight;
}
} else {
if (!upDebounce.read()) operationMode = setUp;
else if (!downDebounce.read()) operationMode = setDown;
buttonPushTime = millis();
beep(50);
}
break;
case moving:
if (!upDebounce.read() || !downDebounce.read()) { // abort if any button pressed
motorDirection(none); //redundant - safety
operationMode = none;
beep(100);
Serial.println(F("Stop."));
resetScreen();
break;
}
if (moveDesk(targetHeight)) operationMode = none;
break;
case setUp:
operationMode = none;
// if (!upDebounce.read() && !downDebounce.read()) { // abort if both buttons pressed
// motorDirection(none); //redundant - safety
// operationMode = none;
// Serial.println(F("Stop."));
// break;
// }
// if (millis() < buttonPushTime + setButtonTimeout) {
// if(upDebounce.fell() || downDebounce.fell()) {
// buttonPushTime = millis();
// if(upDebounce.fell()) settingHeight = measureHeight() + 1;
// if(downDebounce.fell()) settingHeight = measureHeight() - 1;
// Serial.println(F("Setting height: ") + String(settingHeight));
// moveDesk(settingHeight);
// }
// } else {
// topHeight = settingHeight;
// saveSettings();
// Serial.println("New top height set: " + String(topHeight));
// operationMode = none;
// }
break;
case setDown:
operationMode = none;
break;
default:
motorDirection(none);
if ((upDebounce.fell() && !downDebounce.fell()) || (!upDebounce.fell() && downDebounce.fell())) {
buttonPushTime = millis();
operationMode = checking;
beep(10);
}
break;
}
}
void motorDirection(directions motorDirection) {
switch (motorDirection) {
case up:
digitalWrite(motorPinUp, HIGH);
digitalWrite(motorPinDown, LOW);
break;
case down:
digitalWrite(motorPinUp, LOW);
digitalWrite(motorPinDown, HIGH);
break;
default:
digitalWrite(motorPinUp, LOW);
digitalWrite(motorPinDown, LOW);
break;
}
}
bool moveDesk(int newHeight) {
int currentHeight = measureHeight();
if (reportedHeight != currentHeight) {
Serial.println("Current height: " + String(currentHeight) + ". Target height: " + String(newHeight) + ".");
lcd.setCursor(0,0);
lcd.print(F("At: "));
lcd.print(currentHeight);
lcd.print(F(" "));
lcd.setCursor(0,1);
lcd.print(F("To: "));
lcd.print(newHeight);
lcd.print(F(" "));
reportedHeight = currentHeight;
}
// if ((currentHeight > maxSafeHeight) || (currentHeight < minSafeHeight)) {
// beep(500);
// operationMode = none;
// motorDirection(none);
// Serial.println("Out of safe operating range");
// lcd.setCursor(0,0);
// lcd.print(F("Out of R"));
// lcd.setCursor(0,1);
// lcd.print(F("ange. "));
// return false;
// }
if ( currentHeight > newHeight + heightAccuracy ) {
motorDirection(down);
return false;
} else if ( currentHeight < newHeight - heightAccuracy ) {
motorDirection(up);
return false;
} else {
motorDirection(none);
Serial.println("Target height reached: " + String(newHeight) + "mm.");
lcd.setCursor(0,0);
lcd.print(F("Height: "));
lcd.setCursor(0,1);
lcd.print(newHeight);
lcd.print(F("mm "));
screenLastUpdatedTime = millis();
return true;
}
}
void resetScreen() {
lcd.setCursor(0,0);
lcd.print(F(" Desk"));
lcd.setCursor(0,1);
lcd.print(F("bot! "));
screenLastUpdatedTime = millis();
}
void beep() {
if ( beepEndTime - millis() > 10000 ) {
beepEndTime = millis();
} else if (millis() < beepEndTime) {
digitalWrite(beeperPin, HIGH);
} else {
digitalWrite(beeperPin, LOW);
}
}
void beep(int beepLength) {
beepEndTime = millis() + beepLength;
}
int measureHeight() {
if ((millis() - lastMeasuredTime >= sonarTimeout) || (lastMeasuredTime == 0)) {
lastMeasuredTime = millis();
lastMeasuredHeight = sonar.ping_cm() * 10;
}
return lastMeasuredHeight;
}
void saveSettings() {
int eepromAddress = 0;
eepromAddress += EEPROM_writeAnything(eepromAddress, topHeight);
eepromAddress += EEPROM_writeAnything(eepromAddress, bottomHeight);
Serial.println(" Saved Top: " + String(topHeight));
Serial.println("Saved Bottom: " + String(bottomHeight));
}
void loadSettings() {
int eepromAddress = 0;
eepromAddress += EEPROM_readAnything(eepromAddress, topHeight);
eepromAddress += EEPROM_readAnything(eepromAddress, bottomHeight);
Serial.println(" Loaded Top: " + String(topHeight) + "mm");
Serial.println(" Loaded Bottom: " + String(bottomHeight) + "mm");
}
void reportVitals() {
Serial.print(F(" Top height: "));
Serial.print(topHeight);
Serial.println(F("mm"));
Serial.print(F(" Bottom height: "));
Serial.print(bottomHeight);
Serial.println(F("mm"));
Serial.print(F("Current Height: "));
Serial.print(measureHeight());
Serial.println(F("mm"));
// Serial.print(F(" Free Memory: "));
// Serial.print(freeMemory());
// Serial.println(F(" thingies."));
Serial.println(F("============================================="));
}
| ee52a942da0d7e41a41375314fcd61d8bf6d9c31 | [
"C++"
] | 1 | C++ | jameswood/Deskbot | a26f361b6c74da3c60141187d0c18e939b6a1f6f | 4f06e3d510b2138f4f394d26b4e78e7fbf0eb0cc |
refs/heads/master | <repo_name>dependon/myStudy<file_sep>/QImage/cvtest/avltree.h
/*
* Copyright (C) 2019 ~ 2020 Deepin Technology Co., Ltd.
*
* Author: <NAME><<EMAIL>>
*
* Maintainer: <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <QString>
#include <QPointer>
#define MAXSIZE 512
struct test {
char a: 4;
char b: 4;
unsigned short c: 8;
unsigned long d;
};
class AVLTreeNode
{
public:
AVLTreeNode();
~AVLTreeNode();
bool isEmpty();
bool insertNode(int argKey, QString argValue);
bool deleteNode(int argKey);
int getDepth();
int getDepth(AVLTreeNode *argNode);
int getBalance();
void singleRotateRight(AVLTreeNode *argNode);
void singleRotateLeft(AVLTreeNode *argNode);
void rotateRL(AVLTreeNode *argNode);
void rotateLR(AVLTreeNode *argNode);
unsigned int getCount() const
{
return m_i;
}
public:
int key;
QString value;
AVLTreeNode *LeftChild;
AVLTreeNode *RightChild;
private:
unsigned int m_i;
int m_balanceFactor;
};
<file_sep>/x11/x11windowTestOpacity/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMap>
#include <QWindow>
struct strucWindow {
int wid = 0;
QString name = "";
QWindow *window{nullptr};
double opacity{1.0};
};
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void setIdTransparent(const QString &name);
void setNameTransparent(const QString &id);
void updateTableWidget();
private slots:
void on_slider_valueChanged(int value);
void on_idBtn_clicked();
void on_nameBtn_clicked();
void on_pushButton_clicked();
void on_tableWidget_cellChanged(int row, int column);
private:
QWindow *m_currentWidnow{nullptr};
Ui::MainWindow *ui;
QList <QWindow *> m_windowList;
QMap <int, strucWindow> m_windowVec;
};
#endif // MAINWINDOW_H
<file_sep>/QImage/getOpacityQImageDemo/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QImage image(64, 64, QImage::Format_ARGB32);
QPainter painter(&image);
painter.setOpacity(0);
painter.setBrush(QColor(0, 0, 0));
painter.drawRect(0, 0, 64, 64);
image.save("/home/lmh/Desktop/mycx/1.png", "PNG");
}
MainWindow::~MainWindow()
{
delete ui;
}
<file_sep>/x11/xwindow-opacity-tool/application.h
#ifndef APPLICATION_H
#define APPLICATION_H
class Application
{
public:
Application();
};
#endif // APPLICATION_H<file_sep>/QImage/opencvContrast/README.md
## opencvContrast
this is a use opencv demo . Contrast and brightness
### Dependencies
<file_sep>/x11/x11windowTestOpacity/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWindow>
#include <QDebug>
#include "setdesktop.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// auto display = XOpenDisplay(nullptr);
// auto root_window = DefaultRootWindow(display);
// Window root_return, parent_return;
// Window *child_list = nullptr;
// unsigned int child_num = 0;
// XQueryTree(display, root_window, &root_return, &parent_return, &child_list, &child_num);
// for (unsigned int i = 0; i < child_num; ++i) {
// Window window = child_list[i];
//// XWindowAttributes attrs;
//// XGetWindowAttributes(display, window, &attrs);
// QWindow *windowq = QWindow::fromWinId((unsigned long)window);
// if (windowq) {
// windowq->setOpacity(0.8);
// }
// qDebug() << window;
// m_windowList.push_back(windowq);
// }
// qDebug() << child_num;
// XFree(child_list);
// XCloseDisplay(display);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setNameTransparent(const QString &name)
{
char *str = NULL;
QByteArray ba = name.toLatin1();
str = (char *)malloc(ba.length() + 1);
memset(str, 0, ba.length());
memcpy(str, ba.data(), ba.length());
str[ba.length()] = '\0';
//设置desktop透明
int pid_t[128];
find_pid_by_name(str, pid_t);
int pid = pid_t[0];
Display *display = XOpenDisplay(0);
WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);
const list<Window> &result = match.result();
for (Window id : result) {
QWindow *window = QWindow::fromWinId((unsigned long)id);
if (window != nullptr) {
int value = ui->slider->value();
double a = (double)value;
double o = a / 100.0;
window->setOpacity(o);
m_currentWidnow = window;
strucWindow st;
st.window = window;
st.wid = id;
st.name = name;
st.opacity = o;
m_windowVec.insert(id, st);
// ui->listWidget->addItem(name + QString::number(id));
}
}
updateTableWidget();
}
void MainWindow::updateTableWidget()
{
ui->tableWidget->clear();
ui->tableWidget->setRowCount(m_windowVec.count());
for (int index = 0; index < ui->tableWidget->rowCount(); index++) {
strucWindow tmpst = m_windowVec[m_windowVec.keys().at(index)];
QTableWidgetItem *itemWid = new QTableWidgetItem();
itemWid->setText(QString::number(tmpst.wid));
QTableWidgetItem *itemName = new QTableWidgetItem();
itemName->setText(tmpst.name);
QTableWidgetItem *itemOpacity = new QTableWidgetItem();
itemOpacity->setText(QString::number(tmpst.opacity));
ui->tableWidget->setItem(index, 0, itemWid);
ui->tableWidget->setItem(index, 1, itemName);
ui->tableWidget->setItem(index, 2, itemOpacity);
}
}
void MainWindow::on_slider_valueChanged(int value)
{
// if (m_currentWidnow) {
// double a = (double)value;
// double o = a / 100.0;
// m_currentWidnow->setOpacity(o);
// }
}
void MainWindow::setIdTransparent(const QString &id)
{
}
void MainWindow::on_idBtn_clicked()
{
qDebug() << "test";
QString id = ui->idEdit->text();
}
void MainWindow::on_nameBtn_clicked()
{
qDebug() << "test";
QString name = ui->nameEdit->text();
setNameTransparent(name);
}
void MainWindow::on_pushButton_clicked()
{
for (auto structwindow : m_windowVec) {
if (structwindow.window) {
int value = ui->slider->value();
double a = (double)value;
double o = a / 100.0;
structwindow.window->setOpacity(o);
structwindow.opacity = o;
m_windowVec.insert(structwindow.wid, structwindow);
}
}
updateTableWidget();
}
void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
if (2 == column) {
double opacity = ui->tableWidget->item(row, column)->text().toDouble();
int key = ui->tableWidget->item(row, 0)->text().toInt();
strucWindow stWindow = m_windowVec.value(key);
if (stWindow.window) {
stWindow.window->setOpacity(opacity);
stWindow.opacity = opacity;
m_windowVec.insert(stWindow.wid, stWindow);
}
}
}
<file_sep>/QImage/cvtest/mainwindow.cpp
/*
* Copyright (C) 2019 ~ 2020 Deepin Technology Co., Ltd.
*
* Author: <NAME><<EMAIL>>
*
* Maintainer: <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QImageReader>
#include <QDebug>
void elbp(Mat &src, Mat &dst, int radius, int neighbors)
{
for (int n = 0; n < neighbors; n++) {
// 采样点的计算
float x = static_cast<float>(-radius * sin(2.0 * CV_PI * n / static_cast<double>(neighbors)));
float y = static_cast<float>(radius * cos(2.0 * CV_PI * n / static_cast<double>(neighbors)));
// 上取整和下取整的值
int fx = static_cast<int>(floor(x));
int fy = static_cast<int>(floor(y));
int cx = static_cast<int>(ceil(x));
int cy = static_cast<int>(ceil(y));
// 小数部分
float ty = y - fy;
float tx = x - fx;
// 设置插值权重
float w1 = (1 - tx) * (1 - ty);
float w2 = tx * (1 - ty);
float w3 = (1 - tx) * ty;
float w4 = tx * ty;
// 循环处理图像数据
for (int i = radius; i < src.rows - radius; i++) {
for (int j = radius; j < src.cols - radius; j++) {
// 计算插值
float t = static_cast<float>(w1 * src.at<uchar>(i + fy, j + fx) + w2 * src.at<uchar>(i + fy, j + cx) + w3 * src.at<uchar>(i + cy, j + fx) + w4 * src.at<uchar>(i + cy, j + cx));
// 进行编码
dst.at<uchar>(i - radius, j - radius) += ((t > src.at<uchar>(i, j)) || (std::abs(t - src.at<uchar>(i, j)) < std::numeric_limits<float>::epsilon())) << n;
}
}
}
}
void elbp1(Mat &src, Mat &dst)
{
// 循环处理图像数据
for (int i = 1; i < src.rows - 1; i++) {
for (int j = 1; j < src.cols - 1; j++) {
uchar tt = 0;
int tt1 = 0;
uchar u = src.at<uchar>(i, j);
if (src.at<uchar>(i - 1, j - 1) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i - 1, j) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i - 1, j + 1) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i, j + 1) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i + 1, j + 1) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i + 1, j) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i + 1, j - 1) > u) {
tt += 1 << tt1;
}
tt1++;
if (src.at<uchar>(i - 1, j) > u) {
tt += 1 << tt1;
}
tt1++;
dst.at<uchar>(i - 1, j - 1) = tt;
}
}
}
template <typename _tp>
void getCircularLBPFeatureOptimization(InputArray _src, OutputArray _dst, int radius, int neighbors)
{
Mat src = _src.getMat();
//LBP特征图像的行数和列数的计算要准确
_dst.create(src.rows - 2 * radius, src.cols - 2 * radius, CV_8UC1);
Mat dst = _dst.getMat();
dst.setTo(0);
for (int k = 0; k < neighbors; k++) {
//计算采样点对于中心点坐标的偏移量rx,ry
float rx = static_cast<float>(radius * cos(2.0 * CV_PI * k / neighbors));
float ry = -static_cast<float>(radius * sin(2.0 * CV_PI * k / neighbors));
//为双线性插值做准备
//对采样点偏移量分别进行上下取整
int x1 = static_cast<int>(floor(rx));
int x2 = static_cast<int>(ceil(rx));
int y1 = static_cast<int>(floor(ry));
int y2 = static_cast<int>(ceil(ry));
//将坐标偏移量映射到0-1之间
float tx = rx - x1;
float ty = ry - y1;
//根据0-1之间的x,y的权重计算公式计算权重,权重与坐标具体位置无关,与坐标间的差值有关
float w1 = (1 - tx) * (1 - ty);
float w2 = tx * (1 - ty);
float w3 = (1 - tx) * ty;
float w4 = tx * ty;
//循环处理每个像素
for (int i = radius; i < src.rows - radius; i++) {
for (int j = radius; j < src.cols - radius; j++) {
//获得中心像素点的灰度值
_tp center = src.at<_tp>(i, j);
//根据双线性插值公式计算第k个采样点的灰度值
float neighbor = src.at<_tp>(i + x1, j + y1) * w1 + src.at<_tp>(i + x1, j + y2) * w2 \
+ src.at<_tp>(i + x2, j + y1) * w3 + src.at<_tp>(i + x2, j + y2) * w4;
//LBP特征图像的每个邻居的LBP值累加,累加通过与操作完成,对应的LBP值通过移位取得
dst.at<uchar>(i - radius, j - radius) |= (neighbor > center) << (neighbors - k - 1);
}
}
}
}
Mat QImageToMat(QImage image)
{
Mat mat;
switch (image.format()) {
case QImage::Format_ARGB32:
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
mat = Mat(image.height(), image.width(), CV_8UC4, (void *)image.constBits(), static_cast<size_t>(image.bytesPerLine()));
break;
case QImage::Format_RGB888:
mat = Mat(image.height(), image.width(), CV_8UC3, (void *)image.constBits(), static_cast<size_t>(image.bytesPerLine()));
cvtColor(mat, mat, COLOR_BGR2RGB);
break;
case QImage::Format_Indexed8:
mat = Mat(image.height(), image.width(), CV_8UC1, (void *)image.constBits(), static_cast<size_t>(image.bytesPerLine()));
break;
default:
break;
}
return mat;
}
QImage MatToQImage(const Mat &mat)
{
// 8-bits unsigned, NO. OF CHANNELS = 1
if (mat.type() == CV_8UC1) {
QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
// Set the color table (used to translate colour indexes to qRgb values)
image.setColorCount(256);
for (int i = 0; i < 256; i++) {
image.setColor(i, qRgb(i, i, i));
}
// Copy input Mat
uchar *pSrc = mat.data;
for (int row = 0; row < mat.rows; row ++) {
uchar *pDest = image.scanLine(row);
memcpy(pDest, pSrc, static_cast<size_t>(mat.cols));
pSrc += mat.step;
}
return image;
}
// 8-bits unsigned, NO. OF CHANNELS = 3
else if (mat.type() == CV_8UC3) {
// Copy input Mat
const uchar *pSrc = static_cast<const uchar *>(mat.data);
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_RGB888);
return image.rgbSwapped();
} else if (mat.type() == CV_8UC4) {
qDebug() << "CV_8UC4";
// Copy input Mat
const uchar *pSrc = mat.data;
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_ARGB32);
return image.copy();
} else {
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
}
void RuiHua(Mat src)
{
using namespace cv;
Mat dst;
int kernel_size = 1;
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
Mat imageEnhance;
Mat kernel = (Mat_<float>(3, 3) << 0, 1, 0, 1, -4, 1, 0, 1, 0);
filter2D(src, imageEnhance, CV_8UC3, kernel);
// GaussianBlur( src, src, Size(3, 3), 0, 0, BORDER_DEFAULT );
// cvtColor( src, src_gray, COLOR_BGR2GRAY ); // Convert the image to grayscale
Mat abs_dst;
Laplacian( src, dst, ddepth, kernel_size, scale, delta, BORDER_DEFAULT );
// converting back to CV_8U
convertScaleAbs( dst, abs_dst );
imshow("ruihua", abs_dst);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::checkMat()
{
return !m_mat.empty();
}
void MainWindow::verfilter(int sigema)
{
using namespace cv;
Size s(1, sigema);
Mat outMat;
GaussianBlur(m_mat, outMat, s, 0, sigema);
imshow("verfilter", outMat);
}
void MainWindow::horfilter(int sigema)
{
using namespace cv;
Size s(sigema, 1);
Mat outMat;
GaussianBlur(m_mat, outMat, s, sigema, 0);
imshow("horfilter", outMat);
}
void MainWindow::gauss(int sigema)
{
using namespace cv;
Size s(sigema, sigema);
Mat outMat1, imageEnhance;
GaussianBlur(m_mat, outMat1, s, sigema);
// Mat kernel = (Mat_<float>(3, 3) << 0, -1, 0, 0, 4, 0, 0, -1, 0);
// filter2D(outMat1, imageEnhance, CV_8UC3, kernel);
// Laplacian(outMat1,outMat2,32);
imshow("result", outMat1);
}
void MainWindow::sobel()
{
using namespace cv;
Mat out;
Mat src_gray, binmary, grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
cvtColor(m_mat, src_gray, COLOR_RGB2GRAY);
Scharr(src_gray, grad_x, CV_16S, 1, 0);
Scharr(src_gray, grad_y, CV_16S, 0, 1);
// Sobel(src_gray, grad_x, CV_16S, 1, 0);
// Sobel(src_gray, grad_y, CV_16S, 0, 1);
convertScaleAbs(grad_x, abs_grad_x);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, out);
// Canny(src_gray, out, 0, 0);
imshow("sobel", out);
}
void MainWindow::lbp()
{
Mat out;
getCircularLBPFeatureOptimization<float>(m_mat, out, 3, 8);
imshow("normal", out);
}
void MainWindow::classicalfilter()
{
Mat img;
m_mat.copyTo(img);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<Vec3b>(i, j)[1] = saturate_cast<uchar>(0.349 * img.at<Vec3b>(i, j)[2] + 0.686 * img.at<Vec3b>(i, j)[1] + 0.168 * img.at<Vec3b>(i, j)[0]); // green
img.at<Vec3b>(i, j)[2] = saturate_cast<uchar>(0.393 * img.at<Vec3b>(i, j)[2] + 0.769 * img.at<Vec3b>(i, j)[1] + 0.189 * img.at<Vec3b>(i, j)[0]); // red
img.at<Vec3b>(i, j)[0] = saturate_cast<uchar>(0.272 * img.at<Vec3b>(i, j)[2] + 0.534 * img.at<Vec3b>(i, j)[1] + 0.131 * img.at<Vec3b>(i, j)[0]); // blue
}
}
imshow("oldfilter", img);
}
void MainWindow::disorderColor()
{
Mat img;
m_mat.copyTo(img);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
for (int k = 0; k < 3; k++) {
img.at<Vec3b>(i, j)[k] = 255 - img.at<Vec3b>(i, j)[k];
}
}
}
imshow("disorderColor", img);
}
void MainWindow::simpleColor(int color)
{
Mat img;
m_mat.copyTo(img);
switch (color) {
case 0: {
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<Vec3b>(i, j)[1] = 0;// green
img.at<Vec3b>(i, j)[2] = 0;// red
}
}
}
break;
case 1: {
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<Vec3b>(i, j)[0] = 0;// blue
img.at<Vec3b>(i, j)[2] = 0;// red
}
}
}
break;
case 2: {
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<Vec3b>(i, j)[0] = 0;// blue
img.at<Vec3b>(i, j)[1] = 0;// green
}
}
}
break;
default:
break;
}
imshow("simpleColor", img);
}
void MainWindow::on_pushButton_clicked()
{
QFileDialog d;
d.exec();
QString res = d.selectedFiles().first();
m_mat = imread(res.toStdString());
ui->label->setText(res);
imshow("import", m_mat);
}
void MainWindow::on_pushButton_2_clicked()
{
horfilter(15);
}
void MainWindow::on_pushButton_3_clicked()
{
verfilter(15);
}
void MainWindow::on_pushButton_4_clicked()
{
sobel();
}
void MainWindow::on_pushButton_5_clicked()
{
HistogramND hist;
hist.setImage(m_mat);
hist.splitChannels();
hist.getHistogram();
hist.displayHisttogram();
}
void MainWindow::on_pushButton_6_clicked()
{
Mat structureElement = getStructuringElement(MORPH_RECT, //矩形
Size(3, 3),//核的尺寸
Point(-1, -1));//锚点的位置
Mat out_dilate, out_erode;
dilate(m_mat, out_dilate, structureElement);
erode(m_mat, out_erode, structureElement);
imshow("dilate", out_dilate);
imshow("erode", out_erode);
}
void MainWindow::on_pushButton_7_clicked()
{
gauss(15);
}
void MainWindow::on_pushButton_8_clicked()
{
lbp();
}
void MainWindow::on_pushButton_9_clicked()
{
disorderColor();
}
void MainWindow::on_pushButton_10_clicked()
{
simpleColor(1);
}
void MainWindow::on_pushButton_11_clicked()
{
classicalfilter();
}
<file_sep>/QImage/cvtest/avltree.cpp
/*
* Copyright (C) 2019 ~ 2020 Deepin Technology Co., Ltd.
*
* Author: <NAME><<EMAIL>>
*
* Maintainer: <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "avltree.h"
AVLTreeNode::AVLTreeNode()
{
LeftChild = nullptr;
RightChild = nullptr;
}
AVLTreeNode::~AVLTreeNode()
{
}
bool AVLTreeNode::isEmpty()
{
if (key) {
return false;
} else {
return true;
}
}
bool AVLTreeNode::insertNode(int argKey, QString argValue)
{
AVLTreeNode *tempNode = new AVLTreeNode;
tempNode->key = argKey;
tempNode->value = argValue;
if (key > argKey) {
insertNode(argKey, argValue);
if (getBalance() > 1) {
rotateRL(this);
}
}
//todo
return false;
}
int AVLTreeNode::getDepth()
{
return getDepth(this);
}
int AVLTreeNode::getDepth(AVLTreeNode *argNode)
{
if (!argNode) {
return 0;
}
int lHeight = getDepth(argNode->LeftChild);
int rHeight = getDepth(argNode->RightChild);
int nMaxHeight = lHeight > rHeight ? lHeight : rHeight;
nMaxHeight++;
return nMaxHeight;
}
int AVLTreeNode::getBalance()
{
return getDepth(LeftChild) - getDepth(RightChild);
}
/** AVLTree Rotate Rules
*
* Node's left child
*
* (1)k2 (2)k1 * (1)k2 (2)k1
* / / \ * / / \
* (2)k1 (4) (1) * (2)k1 (4) (1)
* / * / \ /
* (4) * (4) (3) (3)
*
* choose parent and grandparent Node , get mid Node to set as root
*/
void AVLTreeNode::singleRotateRight(AVLTreeNode *argNode)
{
}
void AVLTreeNode::rotateRL(AVLTreeNode *argNode)
{
}
<file_sep>/README.md
# myStudy
my Study
Record every bit of my growth
Recorded some learning demo, most about QT and Linux
## QImage/getOpacityQImageDemo
this demo is Get a transparent PNG image through QT
## QImage/cvtest
this is a use opencv demo . Some filters are used
## QImage/opencvContrast
this is a use opencv demo . Contrast and brightness
## x11/x11windowTestOpacity
this demo is Find the X11 window by name and make it transparent (0-100) through QT X11
<file_sep>/QImage/cvtest/mainwindow.h
/*
* Copyright (C) 2019 ~ 2020 Deepin Technology Co., Ltd.
*
* Author: <NAME><<EMAIL>>
*
* Maintainer: <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>
#include <QDebug>
using namespace cv;
namespace Ui {
class MainWindow;
}
void elbp(Mat &src, Mat &dst, int radius, int neighbors);
void elbp1(Mat &src, Mat &dst);
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
bool checkMat();
void verfilter(int sigema);
void horfilter(int sigema);
void gauss(int sigema);
void sobel();
void lbp();
void classicalfilter();
void disorderColor();
void simpleColor(int color);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
void on_pushButton_5_clicked();
void on_pushButton_6_clicked();
void on_pushButton_7_clicked();
void on_pushButton_8_clicked();
void on_pushButton_9_clicked();
void on_pushButton_10_clicked();
void on_pushButton_11_clicked();
private:
Ui::MainWindow *ui;
QImage m_image;
Mat m_mat;
};
class HistogramND
{
private:
Mat image;//源图像
int hisSize[1], hisWidth, hisHeight;//直方图的大小,宽度和高度
float range[2];//直方图取值范围
const float *ranges;
Mat channelsRGB[3];//分离的BGR通道
MatND outputRGB[3];//输出直方图分量
public:
HistogramND()
{
hisSize[0] = 256;
hisWidth = 400;
hisHeight = 400;
range[0] = 0.0;
range[1] = 255.0;
ranges = &range[0];
}
//导入图片
bool importImage(QString path)
{
image = imread(path.toStdString());
if (!image.data)
return false;
return true;
}
void setImage(Mat m)
{
image = m;
}
//分离通道
void splitChannels()
{
split(image, channelsRGB);
}
//计算直方图
void getHistogram()
{
calcHist(&channelsRGB[0], 1, nullptr, Mat(), outputRGB[0], 1, hisSize, &ranges);
calcHist(&channelsRGB[1], 1, nullptr, Mat(), outputRGB[1], 1, hisSize, &ranges);
calcHist(&channelsRGB[2], 1, nullptr, Mat(), outputRGB[2], 1, hisSize, &ranges);
//输出各个bin的值
for (int i = 0; i < hisSize[0]; ++i) {
qDebug() << i << " B:" << outputRGB[0].at<float>(i);
qDebug() << " G:" << outputRGB[1].at<float>(i);
qDebug() << " R:" << outputRGB[2].at<float>(i);
}
}
//显示直方图
void displayHisttogram()
{
Mat rgbHist[3];
for (int i = 0; i < 3; i++) {
rgbHist[i] = Mat(hisWidth, hisHeight, CV_8UC3, Scalar::all(0));
}
normalize(outputRGB[0], outputRGB[0], 0, hisWidth - 20, NORM_MINMAX);
normalize(outputRGB[1], outputRGB[1], 0, hisWidth - 20, NORM_MINMAX);
normalize(outputRGB[2], outputRGB[2], 0, hisWidth - 20, NORM_MINMAX);
for (int i = 0; i < hisSize[0]; i++) {
int val = saturate_cast<int>(outputRGB[0].at<float>(i));
rectangle(rgbHist[0], Point(i * 2 + 10, rgbHist[0].rows), Point((i + 1) * 2 + 10, rgbHist[0].rows - val), Scalar(0, 0, 255), 1, 8);
val = saturate_cast<int>(outputRGB[1].at<float>(i));
rectangle(rgbHist[1], Point(i * 2 + 10, rgbHist[1].rows), Point((i + 1) * 2 + 10, rgbHist[1].rows - val), Scalar(0, 255, 0), 1, 8);
val = saturate_cast<int>(outputRGB[2].at<float>(i));
rectangle(rgbHist[2], Point(i * 2 + 10, rgbHist[2].rows), Point((i + 1) * 2 + 10, rgbHist[2].rows - val), Scalar(255, 0, 0), 1, 8);
}
cv::imshow("R", rgbHist[0]);
imshow("G", rgbHist[1]);
imshow("B", rgbHist[2]);
imshow("image", image);
}
};
#endif // MAINWINDOW_H
<file_sep>/QImage/opencvContrast/main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Mat g_srcImage,g_dstImage;
int g_nContrast,g_nBright;
void On_ContrastAndBright(int,void*)
{
namedWindow("原始图",1);
for (int a = 0;a<g_srcImage.rows;a++) {
for (int b=0;b < g_srcImage.cols; b++) {
for (int c=0;c<3;c++) {
g_dstImage.at<Vec3b>(a,b)[c] = saturate_cast<uchar>((g_nContrast*0.01)*(g_srcImage.at<Vec3b>(a,b)[c])+g_nBright);
}
}
}
imshow("原始图",g_srcImage);
imshow("效果图",g_dstImage);
}
int main(int argc, char *argv[])
{
// QApplication a(argc, argv);
// MainWindow w;
// w.show();
// return a.exec();
// Mat srcImage = imread("/home/shuwenzhi/Pictures/桌面测试图片/1.bmp");
// Mat element =getStructuringElement(MORPH_RECT,Size(15,15));
// Mat dstImage;
// erode(srcImage,dstImage,element);
// imshow("原始图",dstImage);
g_srcImage=imread("/data/home/lmh/1030/1/Camera/IMG_20190707_202427.jpg",IMREAD_REDUCED_COLOR_4);
g_dstImage=Mat::zeros(g_srcImage.size(),g_srcImage.type());
g_nContrast = 80;
g_nBright = 80;
namedWindow("效果图",1);
createTrackbar("对比度","效果图",&g_nContrast,300,On_ContrastAndBright);
createTrackbar("亮 度","效果图",&g_nBright,300,On_ContrastAndBright);
On_ContrastAndBright(g_nContrast,0);
On_ContrastAndBright(g_nBright,0);
while (char(waitKey(1)) != 'q') {
}
//cvtColor(srcImage,dstImage,COLOR_BGR2Lab);
// imshow("效果图",srcImage);
// waitKey(0);
return 0;
}
<file_sep>/x11/x11windowTestOpacity/README.md
### x11windowTestOpacity
linux set x11window Opacity demo
### Dependencies
<file_sep>/QImage/cvtest/README.md
### cvtest
this is a use opencv demo . Some filters are used
### Dependencies
<file_sep>/QImage/getOpacityQImageDemo/README.md
### getOpacityQImageDemo
get one pic opacity png demo
### Dependencies
| f8253b036de4e5d8f0a7e568695d08ba6d94ff67 | [
"Markdown",
"C++"
] | 14 | C++ | dependon/myStudy | acbf3729609b7fbdd8d346dbce32a749ee8dbf1a | 27315ee287416327cb71c9a89a86fe9fd71f9f10 |
refs/heads/master | <file_sep>$(document).ready(function () {
$("#boy").click(function () {
$('#new').modal('show');
setTimeout(function () {
$('#new').modal('hide');
}, 2200);
setTimeout(yesItsBoy, 2300);
});
$("#girl").click(function () {
$('#new').modal('show');
setTimeout(function () {
$('#new').modal('hide');
}, 2200);
setTimeout(noItsBoy, 2300);
});
$(".boy").click(function () {
$('#new').modal('show');
setTimeout(function () {
$('#new').modal('hide');
}, 2200);
setTimeout(yesItsBoy, 2300);
});
$(".girl").click(function () {
$('#new').modal('show');
setTimeout(function () {
$('#new').modal('hide');
}, 2200);
setTimeout(noItsBoy, 2300);
});
});
function yesItsBoy() {
$('.card-body').empty().html(`
<h5 class="text-center">
<img src="https://media.giphy.com/media/1QjzdzQd2D3Qpxn29P/giphy.gif" style="width:7rem;">
<img src="https://media.giphy.com/media/ZyupJv9fpknluc04os/giphy.gif" style="width:7rem;">
<img src="https://media.giphy.com/media/VaqR08nDfj4tGHPyTX/giphy.gif" style="width:13rem;">
</h5>
`);
}
function noItsBoy() {
$('.card-body').empty().html(`
<h5 class="text-center">
<img src="https://media.giphy.com/media/xT9Igpm06uM5OJ5lVS/giphy.gif" style="width:3rem;">
<img src="https://media.giphy.com/media/xT9Igpm06uM5OJ5lVS/giphy.gif" style="width:3rem;">
<img src="https://media.giphy.com/media/VaqR08nDfj4tGHPyTX/giphy.gif" style="width:13rem;">
</h5>
`);
}
| 8c9e3dc37f337b60d370f179fdc0442a4bdde13c | [
"JavaScript"
] | 1 | JavaScript | jobscode2020/revelacaodanieleidiane | 5180dc35e5bb6b6f14e2553f17f95c6d1f06067b | 4d8cb9f88e3094b6912b536c7629d0b00ab9487e |
refs/heads/master | <repo_name>imagine1331/test-project<file_sep>/springStarterProejct-2/src/main/java/com/example/test/mapper/TestDao.java
package com.example.test.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.example.test.model.Member;
@Repository
@Mapper
public interface TestDao {
int saveMember(Member member);
}
<file_sep>/springStarterProejct-2/src/main/java/com/example/test/service/TestService.java
package com.example.test.service;
import com.example.test.model.Member;
public interface TestService {
public void saveMember(Member member) throws Exception;
}
| 2cbeb392a3eb3f6638bf7a584506328731220c22 | [
"Java"
] | 2 | Java | imagine1331/test-project | 3542b9ce1d043d0a0cdf0b3f74fb29905cce9ab5 | 03745518bce4d2683d7aea271fb827c10d310c2e |
refs/heads/master | <repo_name>ArLEquiN64/biboro_angularjs_v2<file_sep>/src/app/base/base.service.js
class BaseService {
constructor($http, dispatcher) {
this._dispatcher = dispatcher;
this._http = $http;
}
createCallback(apiName){
// example: apiName=fetchedAll
// this.FETCHEDALL_CALLBACK = "FETCHEDALL_CALLBACK";
// this.registerFetchedAllCallback(callback){
// this._dispatcher.register(FETCHEDALL_CALLBACK, callback);
// }
this[apiName.toUpperCase()+'_CALLBACK'] = apiName.toUpperCase() + '_CALLBACK';
this['register'+apiName.charAt(0).toUpperCase()+apiName.slice(1)+'_CALLBACK'] = function(callback) {
this._dispatcher.register(apiName.toUpperCase()+'_CALLBACK',callback);
};
}
createApi(apiName, method, path, result){
var methods = [];
methods.get = this._http.get;
methods.post = this._http.post;
methods.put = this._http.put;
methods.delete= this._http.delete;
var merge = function (obj1, obj2) {
if (!obj2) {
obj2 = {};
}
for (var attrname in obj2) {
if (obj2.hasOwnProperty(attrname)) {
obj1[attrname] = obj2[attrname];
}
}
};
createApi(apiName);
this[apiName] = methods[method](path)
.success(function(data){
var obj = result.success.func(data);
this._dispatcher.dispatch(apiName.toUpperCase()+'_CALLBACK', merge({"success":true,"result":result.success.message}, obj));
})
.error(function(data){
var obj = result.error.func(data);
this._dispatcher.dispatch(apiName.toUpperCase()+'_CALLBACK', merge({"success":true,"result":result.error.message}, obj));
})
}
}
<file_sep>/src/app/routes.js
import PlaygroundController from '../app/components/myplayground/playground.controller';
import SnippetController from '../app/components/snippet/snippet.controller';
export default function ($stateProvider, $urlRouterProvider) {
'ngInject';
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainController',
controllerAs: 'main',
})
.state('test', {
url: '/test',
controller: PlaygroundController,
controllerAs: 'p',
template: '<acme-navbar /><div ng-bind="p.hello"></div><div ng-bind="myscope"></div>',
})
.state('snippet', {
url: '/snippet',
controller: SnippetController,
controllerAs: 'p',
template: '<acme-navbar /><div ng-bind="p.hello"></div><div ng-bind="myscope"></div>',
})
.state('snippet.detail', {
url: '/:snippetId',
controller: SnippetController,
controllerAs: 'p',
template: '<acme-navbar /><div ng-bind="p.hello"></div><div ng-bind="myscope"></div>',
});
$urlRouterProvider.otherwise('/');
}<file_sep>/src/app/base/dispatcher.js
class Dispatcher{
constructor () {
this.listeners = [];
}
register(action ,callback) {
this.listeners.push({
action: action,
callback: callback,
});
}
dispatch(action, parameters) {
this.listeners.forEach((payload) => {
if(payload.action === action) {
payload.callback(parameters);
}
});
}
}
export default Dispatcher;<file_sep>/src/app/components/account/account.controller.js
import AccountAction from "./account.action";
class AccountController {
constructor($scope, $http, Account ,Dispatcher) {
this.snippet = new SnippetStore($http,Dispatcher);
this.snippet.registerFetchedAllCallback(this.fetchedAllCallback.bind(this));
this.hello = "loading for data...";
this.initialize();
}
initialize() {
this.snippet.fetchAll();
}
fetchedAllCallback(parameters) {
if(parameters.success){
this.hello = "success";
console.log(parameters.data);
}else{
this.hello = "fail";
}
}
}
export default AccountController;
<file_sep>/src/app/components/account/account.action.js
class AccountAction {
constructor($http,dispatcher) {
this.ACCOUNT_LOGINED = "ACCOUNT_LOGINED";
this.ACCOUNT_LOGOUT = "ACCOUNT_LOGOUT";
this._dispatcher = dispatcher;
this._http = $http;
this.account = null;
}
registerFetchedLoginedAccountCallback(callback) {
this._dispatcher.register(this.ACCOUNT_FETCHED_LOGINED_ACCOUNT,callback);
}
fetchLoginedAccount() {
var self = this;
self._http.get('/api/v1/account/userinfo/user.json')
.success(function(data){
self.account = data;
self._dispatcher.dispatch(self.ACCOUNT_FETCHED_LOGINED_ACCOUNT, {"success":true,"result":"success","data":self.account});
})
.error(function(){
console.log("Fail to get account data");
self._dispatcher.dispatch(self.ACCOUNT_FETCHED_LOGINED_ACCOUNT, {"success":false,"result":"fail to fetch user info."});
});
}
}
export default AccountStore;
<file_sep>/src/app/index.js
/* jshint browser: true */
/* global malarkey:false, toastr:false, moment:false */
import Dispatcher from './base/dispatcher';
import AccountService from '../app/components/account/account.service';
import SnippetService from '../app/components/snippet/snippet.service';
import WorkbookService from '../app/components/workbook/workbook.service';
import MainController from './main/main.controller';
import WebDevTecService from '../app/components/webDevTec/webDevTec.service';
import NavbarDirective from '../app/components/navbar/navbar.directive';
import MalarkeyDirective from '../app/components/malarkey/malarkey.directive';
import routeConfig from './routes';
angular.module('biboroAngular', [
'ngAnimate',
'ngCookies',
'ngSanitize',
'ngResource',
'ui.router',
])
.constant('malarkey', malarkey)
.constant('toastr', toastr)
.constant('moment', moment)
.config(routeConfig)
.service('SnippetService', SnippetService)
.service('WorkbookService', WorkbookService)
.service('AccountService', AccountService)
.factory('Dispatcher', () => new Dispatcher())
.service('webDevTec', WebDevTecService)
.controller('MainController', MainController)
.directive('acmeNavbar', () => new NavbarDirective())
.directive('acmeMalarkey', () => new MalarkeyDirective(malarkey));
<file_sep>/src/app/components/workbook/workbook.service.js
class WorkbookService extends BaseService{
constructor($http,dispatcher) {
super($http,dispatcher);
var obj = {
"success":{
"func":function(data){
},
"message":"success"
},
"error":{
"message":"fail to fetchworkbooks."
}
}
super.createApi('fetchAll', 'get', '/api/v1/workbook/index.json', obj);
}
}
WorkbookService.$inject = ["$http", "Dispatcher"];
export default WorkbookService;
<file_sep>/src/app/components/snippet/snippet.service.js
class SnippetService {
constructor($http,dispatcher) {
this.SNIPPET_FETCHEDALL_CALLBACK = "SNIPPET_FETCHEDALL_CALLBACK";
this.SNIPTET_STORE_CALLBACK = "SNIPPET_STORE_CALLBACK";
this.SNIPPET_SHOW_CALLBACK = "SNIPPET_SHOW_CALLBACK";
this.SNIPPET_UPDATE_CALLBACK = "SNIPPET_UPDATE_CALLBACK";
this.SNIPPET_DESTROY_CALLBACK = "SNIPPET_DESTROY_CALLBACK";
this._dispatcher = dispatcher;
this._http = $http;
this.snippets = [];
}
registerFetchedAllCallback(callback) {
this._dispatcher.register(this.SNIPPET_FETCHEDALL_CALLBACK,callback);
}
registerStoreCallback(callback) {
this._dispatcher.register(this.SNIPPET_STORE_CALLBACK,callback);
}
registerShowCallback(callback) {
this._dispatcher.register(this.SNIPPET_SHOW_CALLBACK,callback);
}
registerUpdateCallback(callback) {
this._dispatcher.register(this.SNIPPET_UPDATE_CALLBACK,callback);
}
registerDestroyAllCallback(callback) {
this._dispatcher.register(this.SNIPPET_DESTROY_CALLBACK,callback);
}
fetchAll() {
var self = this;
self._http.get('/api/v1/snippet/index.json')
.success(function(data){
self.snippets = data;
self._dispatcher.dispatch(self.SNIPPET_FETCHEDALL_CALLBACK, {"success":true,"result":"success","data":self.getSnippets()});
})
.error(function(){
console.log("error in snippet.strore.js");
self._dispatcher.dispatch(self.SNIPPET_FETCHEDALL_CALLBACK, {"success":false,"result":"fail to fetch snippets."});
});
}
store(){
var self= this;
self._http.post('/api/v1/snippet/index.json')
.success(function(){
self._dispatcher.dispatch(self.SNIPPET_STORE_CALLBACK, {"success":true,"result":"success"});
})
.error(function(){
self._dispatcher.dispatch(self.SNIPPET_STORE_CALLBACK, {"success":false,"result":"fail to store snippets."});
});
}
show(){
var self= this;
self._http.get('/api/v1/snippet/{id}/index.json')
.success(function(data){
self.snippets = data;
self._dispatcher.dispatch(self.SNIPPET_SHOW_CALLBACK, {"success":true,"result":"success","data":self.getSnippets()});
})
.error(function(){
self._dispatcher.dispatch(self.SNIPPET_SHOW_CALLBACK, {"success":false,"result":"fail to show snippets."});
});
}
update(){
var self= this;
self._http.put('/api/v1/snippet/{id}/index.json')
.success(function(){
self._dispatcher.dispatch(self.SNIPPET_UPDATE_CALLBACK, {"success":true,"result":"success"});
})
.error(function(){
self._dispatcher.dispatch(self.SNIPPET_UPDATE_CALLBACK, {"success":false,"result":"fail to update snippets."});
});
}
destroy(){
var self= this;
self._http.delete('/api/v1/snippet/{id}/index.json')
.success(function(){
self._dispatcher.dispatch(self.SNIPPET_DESTROY_CALLBACK, {"success":true,"result":"success"});
})
.error(function(){
self._dispatcher.dispatch(self.SNIPPET_DESTROY_CALLBACK, {"success":false,"result":"fail to destroy snippets."});
});
}
getSnippets(){
return this.snippets;
}
}
SnippetService.$inject = ["$http", "Dispatcher"];
export default SnippetService;
<file_sep>/src/app/components/myplayground/playground.controller.js
import PlaygroundStore from "./playground.store";
class PlaygroundController {
constructor($scope, $http, Dispatcher) {
console.log("initialize");
this.mystore = new PlaygroundStore($http,Dispatcher);
this.mystore.registerGetCallback(this.getCallback.bind(this));
this.mystore.dispatchGetAction();
this.hello="ready";
this._scope = $scope;
}
getCallback(parameters) {
console.log("yes");
this.hello = "yes";
this._scope.$apply();
}
}
PlaygroundController.$inject = ['$scope','$http','Dispatcher'];
export default PlaygroundController;
| 7dff1c990716d5d028892156161e186272b1ea88 | [
"JavaScript"
] | 9 | JavaScript | ArLEquiN64/biboro_angularjs_v2 | d6bd8d0132008912e3164995679bba6dab209f10 | 5fbde92806e505089c5c4a6b56aff3c68348055f |
refs/heads/master | <file_sep>package com.rec.flows
import com.google.common.collect.ImmutableList
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.rec.flows.FlowTestHelpers.assertHasSourceInVault
import com.rec.flows.FlowTestHelpers.assertHasStatesInVault
import com.rec.flows.FlowTestHelpers.createFrom
import com.rec.flows.FlowTestHelpers.prepareMockNetworkParameters
import com.rec.flows.FlowTestHelpers.toPair
import com.rec.states.EnergySource
import net.corda.testing.node.MockNetwork
import net.corda.testing.node.StartedMockNode
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class IssueFlowsTest {
private val network: MockNetwork = MockNetwork(prepareMockNetworkParameters)
private val alice: StartedMockNode
private val bob: StartedMockNode
private val carly: StartedMockNode
private val dan: StartedMockNode
private val source: EnergySource = EnergySource.values()[0]
@Before
fun setup() {
network.runNetwork()
}
@After
fun tearDown() {
network.stopNodes()
}
@Test
@Throws(Exception::class)
fun `signed transaction picked the preferred notary`() {
val flow = IssueFlows.Initiator(bob.info.legalIdentities[0], 10L, source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
Assert.assertEquals("O=App Notary, L=London, C=GB", tx.notary!!.name.toString())
}
@Test
@Throws(Exception::class)
fun `signed transaction returned by the flow is signed by the issuer`() {
val flow: IssueFlows.Initiator = IssueFlows.Initiator(bob.info.legalIdentities[0], 10L, source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
tx.verifyRequiredSignatures()
}
@Test
@Throws(Exception::class)
fun `flow records a transaction in issuer and holder transaction storage only`() {
val flow: IssueFlows.Initiator = IssueFlows.Initiator(bob.info.legalIdentities[0], 10L, source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
// We check the recorded transaction in both transaction storage
for (node in ImmutableList.of(alice, bob)) {
Assert.assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
for (node in ImmutableList.of(carly, dan)) {
Assert.assertNull(node.services.validatedTransactions.getTransaction(tx.id))
}
}
@Test
@Throws(Exception::class)
fun `flow records a transaction in issuer and both holder transaction storage`() {
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
Pair(bob.info.legalIdentities[0], 10L),
Pair(carly.info.legalIdentities[0], 20L)), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
// We check the recorded transaction in transaction storage.
for (node in ImmutableList.of(alice, bob, carly)) {
Assert.assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
Assert.assertNull(dan.services.validatedTransactions.getTransaction(tx.id))
}
@Test
@Throws(Exception::class)
fun `recorded transaction has no inputs and a single output the fungible RECToken`() {
val expected: FungibleToken = createFrom(alice, bob, 10L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(
expected.holder, expected.amount.quantity, source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
// We check the recorded transaction in both vaults.
for (node in listOf(alice, bob)) {
val recordedTx = node.services.validatedTransactions.getTransaction(tx.id)
Assert.assertNotNull(recordedTx)
Assert.assertTrue(recordedTx!!.tx.inputs.isEmpty())
val txOutputs = recordedTx.tx.outputs
Assert.assertEquals(1, txOutputs.size.toLong())
Assert.assertEquals(expected, txOutputs[0].data)
}
}
@Test
@Throws(Exception::class)
fun `there is one correct recorded state`() {
val expected: FungibleToken = createFrom(alice, bob, 10L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(
expected.holder, expected.amount.quantity, source)
val future = alice.startFlow(flow)
network.runNetwork()
future.get()
// We check the recorded state in both vaults.
assertHasStatesInVault(alice, ImmutableList.of(expected))
assertHasStatesInVault(bob, ImmutableList.of(expected))
}
@Test
@Throws(Exception::class)
fun `recorded state has correct source`() {
val expected: FungibleToken = createFrom(alice, bob, 10L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(
expected.holder, expected.amount.quantity, source)
val future = alice.startFlow(flow)
network.runNetwork()
future.get()
// We check the recorded state in both vaults have the correct source.
assertHasSourceInVault(alice, listOf(source))
assertHasSourceInVault(bob, listOf(source))
}
@Test
@Throws(Exception::class)
fun `recorded transaction has no inputs and many outputs the fungible RECTokens`() {
val expected1: FungibleToken = createFrom(alice, bob, 10L, source)
val expected2: FungibleToken = createFrom(alice, carly, 20L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
expected1.toPair(),
expected2.toPair()), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
// We check the recorded transaction in the 3 vaults.
for (node in ImmutableList.of(alice, bob, carly)) {
val recordedTx = node.services.validatedTransactions.getTransaction(tx.id)
Assert.assertNotNull(recordedTx)
Assert.assertTrue(recordedTx!!.tx.inputs.isEmpty())
val txOutputs = recordedTx.tx.outputs
Assert.assertEquals(2, txOutputs.size.toLong())
Assert.assertEquals(expected1, txOutputs[0].data)
Assert.assertEquals(expected2, txOutputs[1].data)
}
}
@Test
@Throws(Exception::class)
fun `there are two correct states recorded by relevance`() {
val expected1: FungibleToken = createFrom(alice, bob, 10L, source)
val expected2: FungibleToken = createFrom(alice, carly, 20L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
expected1.toPair(),
expected2.toPair()), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
future.get()
// We check the recorded state in the 4 vaults.
assertHasStatesInVault(alice, ImmutableList.of(expected1, expected2))
// Notice how bob did not save carly's state.
assertHasStatesInVault(bob, ImmutableList.of(expected1))
assertHasStatesInVault(carly, ImmutableList.of(expected2))
assertHasStatesInVault(dan, emptyList())
}
@Test
@Throws(Exception::class)
fun `recorded state both have correct source`() {
val expected1: FungibleToken = createFrom(alice, bob, 10L, source)
val expected2: FungibleToken = createFrom(alice, carly, 20L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
expected1.toPair(),
expected2.toPair()), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
future.get()
// We check the recorded state in both vaults have the correct source.
assertHasSourceInVault(alice, listOf(source, source))
assertHasSourceInVault(bob, listOf(source))
assertHasSourceInVault(carly, listOf(source))
}
@Test
@Throws(Exception::class)
fun `recorded transaction has no inputs and two outputs of same holder`() {
val expected1: FungibleToken = createFrom(alice, bob, 10L, source)
val expected2: FungibleToken = createFrom(alice, bob, 20L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
expected1.toPair(),
expected2.toPair()), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
val tx = future.get()
// We check the recorded transaction in both vaults.
for (node in ImmutableList.of(alice, bob)) {
val recordedTx = node.services.validatedTransactions.getTransaction(tx.id)
Assert.assertNotNull(recordedTx)
Assert.assertTrue(recordedTx!!.tx.inputs.isEmpty())
val txOutputs = recordedTx.tx.outputs
Assert.assertEquals(2, txOutputs.size.toLong())
Assert.assertEquals(expected1, txOutputs[0].data)
Assert.assertEquals(expected2, txOutputs[1].data)
}
}
@Test
@Throws(Exception::class)
fun `there are two correct recorded states again`() {
val expected1: FungibleToken = createFrom(alice, bob, 10L, source)
val expected2: FungibleToken = createFrom(alice, bob, 20L, source)
val flow: IssueFlows.Initiator = IssueFlows.Initiator(listOf(
expected1.toPair(),
expected2.toPair()), source = source)
val future = alice.startFlow(flow)
network.runNetwork()
future.get()
// We check the recorded state in the 4 vaults.
assertHasStatesInVault(alice, ImmutableList.of(expected1, expected2))
assertHasStatesInVault(bob, ImmutableList.of(expected1, expected2))
assertHasStatesInVault(carly, emptyList())
assertHasStatesInVault(dan, emptyList())
}
init {
alice = network.createNode()
bob = network.createNode()
carly = network.createNode()
dan = network.createNode()
}
}<file_sep>package com.rec
import com.rec.flows.FlowTestHelpers
import net.corda.client.rpc.CordaRPCClient
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.getOrThrow
import net.corda.testing.core.TestIdentity
import net.corda.testing.driver.DriverDSL
import net.corda.testing.driver.DriverParameters
import net.corda.testing.driver.NodeHandle
import net.corda.testing.driver.driver
import net.corda.testing.node.NotarySpec
import net.corda.testing.node.User
import java.util.concurrent.Future
class DriverTestHelpers {
companion object {
infix fun TestIdentity.withUsers(users: List<User>): Pair<TestIdentity, List<User>> = this to users
// Runs a test inside the Driver DSL, which provides useful functions for starting nodes, etc.
fun withDriver(test: DriverDSL.() -> Unit) = driver(
DriverParameters(
isDebug = true,
startNodesInProcess = true,
networkParameters = FlowTestHelpers.prepareMockNetworkParameters.networkParameters,
cordappsForAllNodes = FlowTestHelpers.prepareMockNetworkParameters.cordappsForAllNodes,
notarySpecs = FlowTestHelpers.prepareMockNetworkParameters.notarySpecs.map { NotarySpec(it.name) }
)
) { test() }
fun DriverDSL.startNodes(vararg identities: Pair<TestIdentity, List<User>>): List<NodeHandle> =
identities
.map { startNode(providedName = it.first.name, rpcUsers = it.second) }
.waitForAll()
private fun <T> List<Future<T>>.waitForAll(): List<T> = map { it.getOrThrow() }
fun NodeHandle.getProxy(username: String, password: String): CordaRPCOps =
CordaRPCClient(this.rpcAddress).start(username, password).proxy
}
}<file_sep>package com.rec.flows
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.contracts.utilities.heldBy
import com.r3.corda.lib.tokens.contracts.utilities.issuedBy
import com.r3.corda.lib.tokens.contracts.utilities.of
import com.rec.states.EnergySource
import com.rec.states.RECToken
import com.rec.states.RECToken.Companion.recToken
import net.corda.core.contracts.Amount
import net.corda.core.contracts.StateAndRef
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.CordaX500Name
import com.r3.corda.lib.tokens.workflows.types.PartyAndAmount
import net.corda.testing.node.*
import java.io.File
import java.util.*
import kotlin.test.assertEquals
object FlowTestHelpers {
private fun propertiesFromConf(pathname: String): Map<String, String> {
val tokenProperties = Properties()
File(pathname).inputStream().let { tokenProperties.load(it) }
return tokenProperties.entries
.associateBy(
{ it.key as String },
{
(it.value as String)
.removeSurrounding("\"")
.removeSurrounding("\'")
})
}
private val tokensConfig = propertiesFromConf("res/tokens-workflows.conf")
val prepareMockNetworkParameters: MockNetworkParameters = MockNetworkParameters()
.withNotarySpecs(listOf(
MockNetworkNotarySpec(CordaX500Name.parse("O=Unwanted Notary,L=London,C=GB")),
MockNetworkNotarySpec(CordaX500Name.parse(
tokensConfig["notary"]
?: error("no notary given in tokens-workflows.conf")))
))
.withCordappsForAllNodes(listOf(
TestCordapp.findCordapp("com.r3.corda.lib.tokens.contracts"),
TestCordapp.findCordapp("com.r3.corda.lib.tokens.workflows")
.withConfig(tokensConfig),
TestCordapp.findCordapp("com.r3.corda.lib.tokens.money"),
TestCordapp.findCordapp("com.r3.corda.lib.tokens.selection"),
TestCordapp.findCordapp("com.rec.states"),
TestCordapp.findCordapp("com.rec.flows"))
)
fun createFrom(
issuer: StartedMockNode,
holder: StartedMockNode,
quantity: Long,
source: EnergySource
): FungibleToken = quantity of
RECToken(source) issuedBy
issuer.info.legalIdentities.first() heldBy
holder.info.legalIdentities.first()
fun FungibleToken.toPair() = Pair(this.holder, this.amount.quantity)
fun assertHasStatesInVault(node: StartedMockNode, tokenStates: List<FungibleToken>) {
val vaultTokens = node.transaction {
node.services.vaultService.queryBy(FungibleToken::class.java).states
}
assertEquals(tokenStates.size, vaultTokens.size)
tokenStates.indices.forEach {
assertEquals(vaultTokens[it].state.data, tokenStates[it])
}
}
fun assertHasSourceInVault(node: StartedMockNode, source: List<EnergySource>) {
val vaultTokens = node.transaction {
node.services.vaultService.queryBy(FungibleToken::class.java).states
}
vaultTokens.indices.forEach {
assertEquals(vaultTokens[it].state.data.recToken.source, source[it])
}
}
data class NodeHolding(val holder: StartedMockNode, val quantity: Long) {
fun toPair(): Pair<AbstractParty, Long> {
return Pair(holder.info.legalIdentities[0], quantity)
}
}
fun issueTokens(node: StartedMockNode, network: MockNetwork, nodeHoldings: Collection<NodeHolding>, source: EnergySource): List<StateAndRef<FungibleToken>> {
val flow = IssueFlows.Initiator(nodeHoldings.map { it.toPair() }, source)
val future = node.startFlow(flow)
network.runNetwork()
val tx = future.get()
return tx.toLedgerTransaction(node.services).outRefsOfType(FungibleToken::class.java)
}
fun partyAndAmountOf(source: EnergySource, vararg nodeHoldings: NodeHolding): List<PartyAndAmount<TokenType>> =
nodeHoldings.map { it.holder withAmount (it.quantity of RECToken(source)) }
private infix fun StartedMockNode.withAmount(amount: Amount<TokenType>): PartyAndAmount<TokenType> =
PartyAndAmount(this.info.legalIdentities.single(), amount)
}<file_sep>package com.rec.states
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.contracts.utilities.getAttachmentIdForGenericParam
import net.corda.core.crypto.SecureHash
data class RECToken(val source: EnergySource) : TokenType(IDENTIFIER, FRACTION_DIGITS) {
companion object {
const val IDENTIFIER = "REC"
const val FRACTION_DIGITS = 0
val FungibleToken.recToken: RECToken
get() = this.tokenType as RECToken
}
}
<file_sep>package com.rec.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.workflows.flows.rpc.MoveFungibleTokens
import com.r3.corda.lib.tokens.workflows.types.PartyAndAmount
import net.corda.core.flows.FlowException
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.InitiatingFlow
import net.corda.core.flows.StartableByRPC
import net.corda.core.transactions.SignedTransaction
object MoveFlows {
@InitiatingFlow
@StartableByRPC
class Initiator(private val partiesAndAmounts: List<PartyAndAmount<TokenType>>) : FlowLogic<SignedTransaction>() {
@Suspendable
@Throws(FlowException::class)
override fun call(): SignedTransaction = subFlow(MoveFungibleTokens(partiesAndAmounts))
}
}<file_sep>package com.rec.states
import net.corda.core.serialization.CordaSerializable
@CordaSerializable
enum class EnergySource {
/* Must always have at least one value */
SOLAR,
WIND,
HYDRO,
TIDAL,
GEOTHERMAL,
BIOMASS,
}<file_sep>package com.rec.flows
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.workflows.flows.move.MoveTokensFlowHandler
import com.r3.corda.lib.tokens.workflows.types.PartyAndAmount
import com.rec.flows.FlowTestHelpers.NodeHolding
import com.rec.flows.FlowTestHelpers.assertHasSourceInVault
import com.rec.flows.FlowTestHelpers.issueTokens
import com.rec.flows.FlowTestHelpers.partyAndAmountOf
import com.rec.flows.FlowTestHelpers.prepareMockNetworkParameters
import com.rec.flows.MoveFlows.Initiator
import com.rec.states.EnergySource
import com.rec.states.RECToken.Companion.recToken
import net.corda.testing.node.MockNetwork
import net.corda.testing.node.StartedMockNode
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.function.Consumer
import kotlin.test.assertEquals
import kotlin.test.assertNull
class MoveFlowsTest {
private val network: MockNetwork = MockNetwork(prepareMockNetworkParameters)
private val alice: StartedMockNode = network.createNode()
private val bob: StartedMockNode = network.createNode()
private val carly: StartedMockNode = network.createNode()
private val dan: StartedMockNode = network.createNode()
private val source: EnergySource = EnergySource.values()[0]
init {
listOf(alice, bob, carly, dan).forEach(Consumer { it.registerInitiatedFlow(Initiator::class.java, MoveTokensFlowHandler::class.java) })
}
@Before
fun setup() {
network.runNetwork()
}
@After
fun tearDown() {
network.stopNodes()
}
@Test
@Throws(Throwable::class)
fun `can move tokens from bob to dan`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L), NodeHolding(dan, 20L)), source)
val flow = Initiator(partyAndAmountOf(source, NodeHolding(dan, 10L)))
val future = bob.startFlow(flow)
network.runNetwork()
future.get()
}
@Test
@Throws(Throwable::class)
fun `signed transaction returned by the flow is signed by the holder`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(partyAndAmountOf(source, NodeHolding(carly, 10L)))
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
tx.verifySignaturesExcept(listOf(
alice.info.legalIdentities[0].owningKey,
carly.info.legalIdentities[0].owningKey))
}
@Test
@Throws(Throwable::class)
fun `flow records a transaction in holder transaction storage only`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(partyAndAmountOf(source, NodeHolding(carly, 10L)))
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in both transaction storage.
for (node in listOf(bob, carly)) {
assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
for (node in listOf(alice, dan)) {
assertNull(node.services.validatedTransactions.getTransaction(tx.id))
}
}
@Test
@Throws(Throwable::class)
fun `both states all have the correct source`() {
val issuedTokens1 = issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val issuedTokens = issuedTokens1 + issueTokens(carly, network, listOf(NodeHolding(bob, 20L)), source)
val expectedOutput1: List<PartyAndAmount<TokenType>> = partyAndAmountOf(source, NodeHolding(dan, 10L))
val expectedOutput2: List<PartyAndAmount<TokenType>> = partyAndAmountOf(source, NodeHolding(dan, 20L))
val flow = Initiator(expectedOutput1 + expectedOutput2)
val future = bob.startFlow(flow)
network.runNetwork()
future.get()
// We check the states in vaults have the correct source.
assertHasSourceInVault(alice, listOf(issuedTokens[0].state.data.recToken.source))
assertHasSourceInVault(bob, emptyList())
assertHasSourceInVault(carly, listOf(issuedTokens[1].state.data.recToken.source))
assertHasSourceInVault(dan, listOf(source, source))
}
}<file_sep>package com.rec.states
import com.r3.corda.lib.tokens.contracts.types.TokenType
import org.junit.Test
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
class RECTokenTest {
@Test
fun `similar sources are equal RECToken`() {
assertEquals(RECToken(EnergySource.WIND), RECToken(EnergySource.WIND))
}
@Test
fun `different sources are not equal RECToken`() {
assertNotEquals(RECToken(EnergySource.WIND), RECToken(EnergySource.SOLAR))
}
@Test
fun `hash code is constant`() {
assertEquals(RECToken.hashCode(), RECToken.hashCode())
}
@Test
fun `equals is ok with same`() {
assertEquals(RECToken, RECToken)
}
@Test
fun `equals is different with null`() {
assertNotEquals(RECToken, null)
}
@Test
fun `equals is different with other TokenType`() {
assertNotEquals(RECToken, TokenType(RECToken.IDENTIFIER, RECToken.FRACTION_DIGITS))
}
}<file_sep>package com.rec.states
import java.util.*
data class Issuance(
val production: EnergyProduction,
val date: Date,
val country: Locale
)
<file_sep>package com.rec.contracts
import net.corda.core.contracts.Contract
import net.corda.core.transactions.LedgerTransaction
class RECTokenContract: Contract {
companion object {
// Used to identify our contract when building a transaction.
val contractId: String = this::class.java.enclosingClass.canonicalName
}
override fun verify(tx: LedgerTransaction) {
return
}
}<file_sep>package com.rec.states
import java.util.*
data class EnergyProduction(
val source: EnergySource,
val megawattHour: Long,
val startDate: Date,
val endDate: Date,
val relatedToElectricity: Boolean
)
<file_sep>package com.rec.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.workflows.flows.redeem.RedeemTokensFlow
import com.r3.corda.lib.tokens.workflows.flows.redeem.RedeemTokensFlowHandler
import com.r3.corda.lib.tokens.workflows.flows.rpc.RedeemFungibleTokens
import net.corda.core.contracts.Amount
import net.corda.core.contracts.StateAndRef
import net.corda.core.flows.*
import net.corda.core.identity.Party
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.ProgressTracker
object RedeemFlows {
@InitiatingFlow
@StartableByRPC
class Initiator(private val amount: Amount<TokenType>, private val issuer: Party) : FlowLogic<SignedTransaction>() {
@Suspendable
@Throws(FlowException::class)
override fun call(): SignedTransaction = subFlow(RedeemFungibleTokens(amount, issuer))
}
}<file_sep>package com.rec.flows
import com.r3.corda.lib.tokens.contracts.utilities.of
import com.r3.corda.lib.tokens.workflows.flows.redeem.RedeemTokensFlowHandler
import com.rec.flows.FlowTestHelpers.NodeHolding
import com.rec.flows.FlowTestHelpers.assertHasStatesInVault
import com.rec.flows.FlowTestHelpers.createFrom
import com.rec.flows.FlowTestHelpers.issueTokens
import com.rec.flows.FlowTestHelpers.prepareMockNetworkParameters
import com.rec.flows.RedeemFlows.Initiator
import com.rec.states.EnergySource
import com.rec.states.RECToken
import net.corda.core.contracts.ContractState
import net.corda.testing.node.MockNetwork
import net.corda.testing.node.StartedMockNode
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.util.function.Consumer
class RedeemFlowsTest {
private val network: MockNetwork = MockNetwork(prepareMockNetworkParameters)
private val alice: StartedMockNode = network.createNode()
private val bob: StartedMockNode = network.createNode()
private val carly: StartedMockNode = network.createNode()
private val dan: StartedMockNode = network.createNode()
private val source: EnergySource = EnergySource.values()[0]
init {
listOf(alice, bob, carly, dan).forEach(Consumer { it.registerInitiatedFlow(Initiator::class.java, RedeemTokensFlowHandler::class.java) })
}
@Before
fun setup() {
network.runNetwork()
}
@After
fun tearDown() {
network.stopNodes()
}
@Test
@Throws(Throwable::class)
fun `signed transaction returned by the flow is signed by both the issuer and the holder`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
tx.verifySignaturesExcept(bob.info.legalIdentities[0].owningKey)
tx.verifySignaturesExcept(alice.info.legalIdentities[0].owningKey)
}
@Test
@Throws(Throwable::class)
fun `signed transaction returned by the flow is signed by both issuers and the holder`() {
val tokens1 = issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
tokens1 + issueTokens(carly, network, listOf(NodeHolding(bob, 20L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
tx.verifySignaturesExcept(listOf(
bob.info.legalIdentities[0].owningKey,
carly.info.legalIdentities[0].owningKey))
tx.verifySignaturesExcept(listOf(
alice.info.legalIdentities[0].owningKey,
carly.info.legalIdentities[0].owningKey))
tx.verifySignaturesExcept(listOf(
alice.info.legalIdentities[0].owningKey,
bob.info.legalIdentities[0].owningKey))
}
@Test
@Throws(Throwable::class)
fun `flow records a transaction in issuer and holder transaction storage only`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in both transaction storage.
for (node in listOf(alice, bob)) {
assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
for (node in listOf(carly, dan)) {
assertNull(node.services.validatedTransactions.getTransaction(tx.id))
}
}
@Test
@Throws(Throwable::class)
fun `flow records a transaction in both issuers and holder transaction storage only`() {
val tokens1 = issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
tokens1 + (issueTokens(carly, network, listOf(NodeHolding(bob, 20L)), source))
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in both transaction storage.
for (node in listOf(alice, bob)) {
assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
assertNull(dan.services.validatedTransactions.getTransaction(tx.id))
}
@Test
@Throws(Throwable::class)
fun `flow records a transaction in issuer and both holder transaction storage`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L), NodeHolding(carly, 20L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in transaction storage.
for (node in listOf(alice, bob)) {
assertEquals(tx, node.services.validatedTransactions.getTransaction(tx.id))
}
assertNull(dan.services.validatedTransactions.getTransaction(tx.id))
}
@Test
@Throws(Throwable::class)
fun `recorded transaction has a single input the fungible RECToken and no outputs`() {
val expected = createFrom(alice, bob, 10L, source)
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in both vaults.
for (node in listOf(alice, bob)) {
val recordedTx = node.services.validatedTransactions.getTransaction(tx.id)
val txInputs = recordedTx!!.tx.inputs
assertEquals(1, txInputs.size.toLong())
assertEquals(expected, node.services.toStateAndRef<ContractState>(txInputs[0]).state.data)
assertTrue(recordedTx.tx.outputs.isEmpty())
}
}
@Test
@Throws(Throwable::class)
fun `there is no recorded state after redeem`() {
issueTokens(alice, network, listOf(NodeHolding(bob, 10L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
future.get()!!
// We check the state was consumed in both vaults.
assertHasStatesInVault(alice, emptyList())
assertHasStatesInVault(bob, emptyList())
}
@Test
@Throws(Throwable::class)
fun `recorded transaction has many inputs the fungible RECTokens and no outputs`() {
val expected = createFrom(alice, bob, 10L, source)
issueTokens(alice, network, listOf(NodeHolding(bob, 10L), NodeHolding(carly, 20L)), source)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
val tx = future.get()!!
// We check the recorded transaction in the 3 vaults.
for (node in listOf(alice, bob)) {
val recordedTx = node.services.validatedTransactions.getTransaction(tx.id)
val txInputs = recordedTx!!.tx.inputs
assertEquals(1, txInputs.size.toLong())
assertEquals(expected, node.services.toStateAndRef<ContractState>(txInputs[0]).state.data)
assertTrue(recordedTx.tx.outputs.isEmpty())
}
}
@Test
@Throws(Throwable::class)
fun `there are no recorded states after redeem`() {
val expected = createFrom(alice, carly, 20L, source)
val tokens = issueTokens(
alice, network, listOf(
NodeHolding(bob, 10L),
NodeHolding(carly, 20L)), source
)
val flow = Initiator(10L of RECToken(source), alice.info.legalIdentities.single())
val future = bob.startFlow(flow)
network.runNetwork()
future.get()!!
// We check the recorded state in the 4 vaults.
assertHasStatesInVault(alice, listOf(expected))
assertHasStatesInVault(bob, emptyList())
assertHasStatesInVault(carly, listOf(expected))
assertHasStatesInVault(dan, emptyList())
}
}<file_sep>package com.rec
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.r3.corda.lib.tokens.contracts.types.TokenType
import com.r3.corda.lib.tokens.contracts.utilities.of
import com.r3.corda.lib.tokens.workflows.flows.rpc.MoveFungibleTokensHandler
import com.r3.corda.lib.tokens.workflows.flows.rpc.RedeemFungibleTokensHandler
import com.r3.corda.lib.tokens.workflows.types.PartyAndAmount
import com.rec.DriverTestHelpers.Companion.getProxy
import com.rec.DriverTestHelpers.Companion.startNodes
import com.rec.DriverTestHelpers.Companion.withDriver
import com.rec.DriverTestHelpers.Companion.withUsers
import com.rec.flows.IssueFlows
import com.rec.flows.MoveFlows
import com.rec.flows.RedeemFlows
import com.rec.states.EnergySource
import com.rec.states.RECToken
import com.rec.states.RECToken.Companion.recToken
import net.corda.core.contracts.Amount
import net.corda.core.contracts.StateAndRef
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.messaging.vaultQueryBy
import net.corda.core.messaging.vaultTrackBy
import net.corda.core.node.services.Vault
import net.corda.core.utilities.getOrThrow
import net.corda.node.services.Permissions.Companion.invokeRpc
import net.corda.node.services.Permissions.Companion.startFlow
import net.corda.testing.core.TestIdentity
import net.corda.testing.core.expect
import net.corda.testing.core.expectEvents
import net.corda.testing.core.singleIdentity
import net.corda.testing.node.User
import org.junit.Test
import rx.Observable
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
class DriverBasedTest {
private val prosumer = TestIdentity(CordaX500Name("Prosumer", "", "FR"))
private val utilityProvider = TestIdentity(CordaX500Name("Utility Provider", "", "GB"))
private val aliceUser = User("aliceUser", "<PASSWORD>", permissions = setOf(
startFlow<IssueFlows.Initiator>(),
startFlow<MoveFlows.Initiator>(),
startFlow<MoveFungibleTokensHandler>(),
startFlow<RedeemFlows.Initiator>(),
startFlow<RedeemFungibleTokensHandler>(),
invokeRpc("vaultTrackBy"),
invokeRpc("vaultQueryBy")
))
private val bobUser = User("bobUser", "<PASSWORD>", permissions = setOf(
startFlow<MoveFlows.Initiator>(),
startFlow<MoveFlows.Initiator>(),
startFlow<MoveFungibleTokensHandler>(),
startFlow<RedeemFlows.Initiator>(),
startFlow<RedeemFungibleTokensHandler>(),
invokeRpc("vaultTrackBy"),
invokeRpc("vaultQueryBy")
))
@Test
fun `issue integration test`() = withDriver {
val (alice, bob) = startNodes(
prosumer withUsers listOf(aliceUser),
utilityProvider withUsers listOf(bobUser)
)
val aliceProxy: CordaRPCOps = alice.getProxy("aliceUser", "<PASSWORD>")
val bobProxy: CordaRPCOps = bob.getProxy("bobUser", "<PASSWORD>")
val aliceVaultUpdates: Observable<Vault.Update<FungibleToken>> = aliceProxy.vaultTrackBy<FungibleToken>().updates
// val bobVaultUpdates: Observable<Vault.Update<FungibleToken>> = bobProxy.vaultTrackBy<FungibleToken>().updates
// issue
aliceProxy.startFlowDynamic(
IssueFlows.Initiator::class.java,
alice.nodeInfo.singleIdentity(),
10L,
EnergySource.WIND
).returnValue.getOrThrow()
aliceVaultUpdates.expectEvents {
expect { update ->
val produced: FungibleToken = update.produced.first().state.data
assertEquals(alice.nodeInfo.legalIdentities.single(), produced.holder)
assertEquals(RECToken(EnergySource.WIND), produced.recToken)
assertEquals(10L, produced.amount.quantity)
}
}
}
@Test
fun `move integration test`() = withDriver {
val (alice, bob) = startNodes(
prosumer withUsers listOf(aliceUser),
utilityProvider withUsers listOf(bobUser)
)
val aliceProxy: CordaRPCOps = alice.getProxy("aliceUser", "<PASSWORD>")
val bobProxy: CordaRPCOps = bob.getProxy("bobUser", "<PASSWORD>")
val aliceVaultUpdates: Observable<Vault.Update<FungibleToken>> = aliceProxy.vaultTrackBy<FungibleToken>().updates
val bobVaultUpdates: Observable<Vault.Update<FungibleToken>> = bobProxy.vaultTrackBy<FungibleToken>().updates
// issue
aliceProxy.startFlowDynamic(
IssueFlows.Initiator::class.java,
alice.nodeInfo.singleIdentity(),
10L,
EnergySource.WIND
).returnValue.getOrThrow()
// move
val input: List<StateAndRef<FungibleToken>> = aliceProxy.vaultQueryBy<FungibleToken>().states
val halfQuantity = input.map { it.state.data.amount.quantity }.sum() / 2
val source = input.map { it.state.data.recToken.source }.single()
val partiesAndAmounts: List<PartyAndAmount<TokenType>> = listOf(PartyAndAmount(bob.nodeInfo.singleIdentity(), halfQuantity of RECToken(source)))
aliceProxy.startFlowDynamic(
MoveFlows.Initiator::class.java,
partiesAndAmounts
).returnValue.getOrThrow()
bobVaultUpdates.expectEvents {
expect { update ->
val produced: FungibleToken = update.produced.first().state.data
assertEquals(bob.nodeInfo.legalIdentities.single(), produced.holder)
assertEquals(RECToken(EnergySource.WIND), produced.recToken)
assertEquals(5L, produced.amount.quantity)
}
}
// this doesn't make sense..
// TODO: figure out how to test properly
aliceVaultUpdates.expectEvents {
expect { update ->
val produced: FungibleToken = update.produced.first().state.data
assertEquals(alice.nodeInfo.legalIdentities.single(), produced.holder)
assertEquals(RECToken(EnergySource.WIND), produced.recToken)
assertEquals(10L, produced.amount.quantity)
}
}
}
@Test
fun `redeem integration test`() = withDriver {
val (alice, bob) = startNodes(
prosumer withUsers listOf(aliceUser),
utilityProvider withUsers listOf(bobUser)
)
val aliceProxy: CordaRPCOps = alice.getProxy("aliceUser", "<PASSWORD>")
val bobProxy: CordaRPCOps = bob.getProxy("bobUser", "<PASSWORD>")
// val aliceVaultUpdates: Observable<Vault.Update<FungibleToken>> = aliceProxy.vaultTrackBy<FungibleToken>().updates
val bobVaultUpdates: Observable<Vault.Update<FungibleToken>> = bobProxy.vaultTrackBy<FungibleToken>().updates
// issue
aliceProxy.startFlowDynamic(
IssueFlows.Initiator::class.java,
alice.nodeInfo.singleIdentity(),
10L,
EnergySource.WIND
).returnValue.get(10L, TimeUnit.SECONDS)
// move
val input: List<StateAndRef<FungibleToken>> = aliceProxy.vaultQueryBy<FungibleToken>().states
val halfQuantity = input.map { it.state.data.amount.quantity }.sum() / 2
val source = input.map { it.state.data.recToken.source }.single()
val partiesAndAmounts: List<PartyAndAmount<TokenType>> = listOf(PartyAndAmount(bob.nodeInfo.singleIdentity(), halfQuantity of RECToken(source)))
aliceProxy.startFlowDynamic(
MoveFlows.Initiator::class.java,
partiesAndAmounts
).returnValue.getOrThrow()
// need to wait until the token actually moves. Takes some time, could do Thread.sleep(2000L).
bobVaultUpdates.expectEvents {
expect { update ->
val produced: FungibleToken = update.produced.first().state.data
assertEquals(bob.nodeInfo.legalIdentities.single(), produced.holder)
assertEquals(RECToken(EnergySource.WIND), produced.recToken)
assertEquals(5L, produced.amount.quantity)
}
}
// make sure you wait long enough otherwise bob's vault will be empty.
// redeem
val issuer: Party = alice.nodeInfo.legalIdentities.single()
val bobVaultQuery: List<StateAndRef<FungibleToken>> = bobProxy.vaultQueryBy<FungibleToken>().states
val amount: Amount<TokenType> = bobVaultQuery.map { it.state.data.amount.quantity }.sum() of bobVaultQuery.map { it.state.data.tokenType }.single()
bobProxy.startFlowDynamic(
RedeemFlows.Initiator::class.java,
amount,
issuer
).returnValue.getOrThrow()
}
}<file_sep>package com.rec.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.tokens.contracts.states.FungibleToken
import com.r3.corda.lib.tokens.contracts.utilities.heldBy
import com.r3.corda.lib.tokens.contracts.utilities.issuedBy
import com.r3.corda.lib.tokens.contracts.utilities.of
import com.r3.corda.lib.tokens.workflows.flows.rpc.IssueTokens
import com.rec.states.EnergySource
import com.rec.states.RECToken
import net.corda.core.flows.FlowException
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.InitiatingFlow
import net.corda.core.flows.StartableByRPC
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.Party
import net.corda.core.node.StatesToRecord
import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.ProgressTracker
object IssueFlows {
/**
* Started by the [FungibleToken.issuer] to issue multiple states where it is the only issuer.
* It is not an [InitiatingFlow] because it does not need to, it is [IssueTokens] that is initiating.
* It may contain a given [Party] more than once, so that we can issue multiple states to a given holder.
*/
@StartableByRPC
class Initiator(
private val heldQuantities: List<Pair<AbstractParty, Long>>,
private val source: EnergySource,
override val progressTracker: ProgressTracker = tracker()
) : FlowLogic<SignedTransaction>() {
/**
* The only constructor that can be called from the CLI.
* Started by the issuer to issue a single state.
*/
constructor(holder: AbstractParty, quantity: Long, source: EnergySource) : this(listOf(Pair(holder, quantity)), source)
@Suspendable
@Throws(FlowException::class)
override fun call(): SignedTransaction {
progressTracker.currentStep = PREPARING_TO_PASS_ON
// It is a design decision to have this flow initiated by the issuer.
val outputTokens: List<FungibleToken> = heldQuantities.map { (holder, quantity) ->
quantity of RECToken(source) issuedBy ourIdentity heldBy holder
}
progressTracker.currentStep = PASSING_TO_SUB_ISSUE
val notarised = subFlow(IssueTokens(outputTokens))
// We want our issuer to have a trace of the amounts that have been issued, whether it is a holder or not,
// in order to know the total supply. Since the issuer is not in the participants, it needs to be done
// manually. We do it after the sub flow as this is the better way to do, after notarisation, even if
// here there is no notarisation.
serviceHub.recordTransactions(StatesToRecord.ALL_VISIBLE, listOf(notarised))
return notarised
}
companion object {
private val PREPARING_TO_PASS_ON = ProgressTracker.Step("Preparing to pass on to Tokens issue flow.")
private val PASSING_TO_SUB_ISSUE = ProgressTracker.Step("Passing on to Tokens issue flow.")
fun tracker(): ProgressTracker {
return ProgressTracker(PREPARING_TO_PASS_ON, PASSING_TO_SUB_ISSUE)
}
}
}
}<file_sep># Recorda
It is a truth universally acknowledged that a single plant in possession of a renewable MWh must be in want of a REC
## Why should we use FungibleRECTokens instead of FungibleTokens
There are two useful git tags: **fungibleRECToken** and **fungibleToken**.
Both are built on top of the RECToken TokenType.
#### fungibleRECToken tag
You can find functioning code that uses a customised FungibleToken.
You can run contract code in FungibleRECTokenContract.
Move takes a list of input and list of output tokens.
Redeem takes a list of tokens to redeem.
It is harder to work with as you must provide both the input and output tokens.
However, it gives you a lot more flexibility in what you can actually do!
In the future, a good idea would be to write subFlows that would mimic the FungibleToken flows.
However, change the logic so that it does what one expects it to do.
For example, you could make Move take a party to whom to move tokens to, a quantity to move,
a list of EnergySource and a boolean. The list of energy source would be the source of tokens you
want to prioritise moving. The boolean would specify whether you can only move those tokens or whether you may
move others as well, should you run out of the tokens from the source specified in the list.
For example, [WIND] and false would throw an exception if you try to move 10 but you only have 5 in your vault.
But [WIND] and true would not throw an exception if you had only 5 tokens from WIND but also 10 tokens from SOLAR,
it would take 5 more from SOLAR and move those. However, it will take 5 from WIND first and only when running out of WIND
would take SOLAR tokens.
#### fungibleToken tag
This code uses FungibleTokens only. It is very limiting.
If you want to move 5 tokens from WIND and 5 tokens from SOLAR, then you must execute two flows on corda.
Each will execute a move. In terms of complexity, it is worse than using a FungibleRECToken.
The flow code is much simpler, in fact Move and Redeem are one line long.
However, there is a trade-off as it means the engineer in charge of writing the call to the flow,
the client or backend logic, will have to initiate multiple flows to execute the move.
Furthermore, the example discussed above, where you would provide arguments such as [WIND] and true,
would still have to be written, but as a separate function. All in all, apart from a one liner, there is not much to gain
from using a FungibleToken. Looking back at the Move and Redeem flow code for FungibleRECToken, those two flows were only a few
lines long.
I will leave this tag available for future engineers interested in playing around with this.
However, I believe it is better and ultimately simpler, to use FungibleRECTokens. | 8f19da9ce196af8547284672c1cf1c422c4cf9fc | [
"Markdown",
"Kotlin"
] | 16 | Kotlin | cyprienroche/recorda | abf574bad119577c445e5c573446d762b394095a | f5057a4f6b7ff2ad5fa5230317e137f638b86617 |
refs/heads/main | <repo_name>Sultan-75/node_expres_project_1<file_sep>/public/js/main.js
const cityName = document.getElementById("cityName");
const city_name = document.getElementById("city_name");
const searchBtn = document.getElementById('searchBtn');
const temp = document.getElementById('temp');
const temp_status = document.getElementById('temp_status');
const data_hide = document.querySelector('.middle_layer');
const getinfo = async (event) =>{
event.preventDefault();
let cityVal = cityName.value;
if(cityVal === ""){
city_name.innerHTML=`<p style="color: #FF5733 ;">Please type a name before search</p>`;
data_hide.classList.add('data_hide');
}else{
try {
let url = `http://api.openweathermap.org/data/2.5/weather?q=${cityVal}&units=metric&appid=2b5dd4ffebaa968b80a977d535f1174d`;
const response = await fetch(url);
const data = await response.json();
const arrdata = [data];
city_name.innerHTML=
`
${arrdata[0].name} , ${arrdata[0].sys.country}
`;
temp.innerHTML=arrdata[0].main.temp;
const tempMod = arrdata[0].weather[0].main;
if (tempMod == 'clear'){
weathercon.innerHTML = `<i class="fas fa-sun" style="color: #eccc68;"></i>`
}
if (tempMod == 'Sunny'){
temp_status.innerHTML = `<i class="fa fa-sun" style="color: #f1f2f6;"></i>`
} else if (tempMod == 'Clouds') {
temp_status.innerHTML = `<i class="fa fa-cloud" style="color: #dfe4ea;"></i>`
}
else if (tempMod == 'Rainy'){
temp_status.innerHTML = `<i class="fa fa-cloud-rain" style="color: #a4bobe;"></i>`
}else{
temp_status.innerHTML = `<i class="fa fa-cloud" style="color: #eccc68;"></i>`
}
data_hide.classList.remove('data_hide');
} catch (error) {
city_name.innerHTML="Please type a valid name";
data_hide.classList.add('data_hide');
}
}
}
searchBtn.addEventListener('click',getinfo);
//
const getcurrentDay = () =>{
var weekday = new Array(7);
weekday[0] = "Sun";
weekday[1] = "Mon";
weekday[2] = "Tue";
weekday[3] = "Wed";
weekday[4] = "Thu";
weekday[5] = "Fri";
weekday[6] = "Sat";
let currentTime = new Date();
let days = weekday[currentTime.getDay()];
let day = document.getElementById('day');
day.innerText = days;
};
getcurrentDay();
//
const getcurrentTime = () =>{
monts=[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sept",
"Oct",
"Nov",
"Dec",
];
let nowtime = new Date();
var month = monts[nowtime.getMonth()];
var date = nowtime.getDate() ;
let toady_data = document.getElementById('toady_data');
toady_data.innerText = `${date}th ${month}`;
};
getcurrentTime(); | 8c8ffb1b26a87a6b125da06feedc4d4fa8f2a9c3 | [
"JavaScript"
] | 1 | JavaScript | Sultan-75/node_expres_project_1 | 11010b824bb958559e62f4d36467dcac5ee4f683 | 98ef81a3a7fa651d3b8aea11deed5aaf3b2c68b5 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Product } from './product';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class ProductService {
private productsUrl = 'http://localhost:8080/api/products'; // URL to web api
constructor(
private http: HttpClient
) { }
getProducts(_category): Observable<Product[]>{
//const params = new HttpParams().set('params', category);
return this.http.get<Product[]>(this.productsUrl, {params:{ cat: _category }})
}
getProduct(id: number): Observable<Product> {
const url = `${this.productsUrl}/${id}`;
return this.http.get<Product>(url);
}
addProduct (product: Product): Observable<Product> {
return this.http.post<Product>(this.productsUrl, product, httpOptions);
}
deleteProduct (product: Product | number): Observable<Product> {
const id = typeof product === 'number' ? product : product.id;
const url = `${this.productsUrl}/${id}`;
return this.http.delete<Product>(url, httpOptions);
}
updateProduct (product: Product): Observable<any> {
return this.http.put(this.productsUrl, product, httpOptions);
}
}<file_sep>import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ProductService } from '../product.service';
import { ShoppingCartService } from '../shopping-cart.service';
import { __core_private_testing_placeholder__ } from '@angular/core/testing';
import { CartItem } from '../cart-item';
import { Product } from '../product';
@Component({
selector: 'app-shopping',
templateUrl: './shopping-cart.component.html',
styleUrls: ['./shopping-cart.component.css']
})
export class ShoppingCartComponent implements OnInit {
products: any = 0;
totalItems: any = 0;
totalPrice: any = 0;
constructor(private productService: ProductService,
private cartService: ShoppingCartService) {}
ngOnInit() {
this.refresh();
}
refresh(){
this.totalItems = 0;
this.totalPrice = 0;
this.cartService.productsRef.subscribe((_items)=>{
this.products = _items;
for(var i = 0; i<this.products.length;i++) {
this.totalItems += this.products[i].total;
this.totalPrice += (this.products[i].total * this.products[i].item.price);
}
});
}
removeFromCart(_product: Product){
this.cartService.removeFromCart(_product)
this.refresh();
}
}
<file_sep>import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Product } from '../product';
import { ProductService } from '../product.service';
import { ShoppingCartService } from '../shopping-cart.service';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
products: Product[] = [];
constructor(private productService: ProductService,
private cartService: ShoppingCartService) {}
ngOnInit(): void {
//this.getProducts('All');
this.productService.getProducts('All')
.subscribe(
(_products) => {
console.log(_products);
this.products = _products
}
);
}
getProducts(_category: string) {
console.log('Cat: ' + _category);
return this.productService.getProducts(_category)
.subscribe(
(_products) => {
this.products = _products
}
);
}
addToCart(_product){
this.cartService.addToCart(_product);
};
onCategoryChanged(_event){
let value = _event.target.value;
this.getProducts(value);
console.log(value);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { Product } from './product';
import { CartItem } from './cart-item';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
productsRef = new BehaviorSubject<CartItem[]>([]);
products : any = [];
constructor() {
this.productsRef.next(this.products);
}
getCartProduct(){
return this.products.asObservable;
}
addToCart(_product: Product){
//Check if product already added to array
if(this.products.filter(p => p.item.id === _product.id).length > 0) {
this.products.forEach((p)=>{
if(p.item.id === _product.id ) {
p.total += 1;
}
})
}else{
this.products.push(
{ item: _product, total: 1 }
);
}
this.productsRef.next(this.products);
}
removeFromCart(_product: Product){
this.products = this.products.filter(e => e.item.id !== _product.id);
this.productsRef.next(this.products);
}
}<file_sep>import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ShoppingCartService } from './shopping-cart.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
cartItems: any = 0;
constructor(private cartService: ShoppingCartService) {}
ngOnInit() {
this.cartService.productsRef.subscribe((_items)=>{
this.cartItems = _items;
});
}
title = 'app';
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Product } from '../product';
import { ProductService } from '../product.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { ShoppingCartService } from '../shopping-cart.service';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
product = new Product() ;
submitted = false;
message: string;
constructor(
private productService: ProductService,
private route: ActivatedRoute,
private location: Location,
private cartService: ShoppingCartService
) {}
ngOnInit(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.productService.getProduct(id)
.subscribe(_product => {
console.log(_product);
this.product = _product
});
}
addToCart(_product){
this.cartService.addToCart(_product);
};
goBack(): void {
this.location.back();
}
} | 4a746eed167d4844e1762e7323d579134d59deed | [
"TypeScript"
] | 6 | TypeScript | ramv133/ShoppingCart-client | 981744c7e36d631f4901f6edc0389d427c8c3e03 | f7bc0b8ec35f2cb1c063ac6e5be86586cf0b6981 |
refs/heads/master | <repo_name>lgaalves/core-periphery-detection<file_sep>/cpalgorithm/Cucuringu.py
import _cpalgorithm as _cp
from scipy.sparse import diags
from scipy.sparse.linalg import eigs
from .CPAlgorithm import *
class LowRankCore(CPAlgorithm):
"""LowRankCore algorithm.
LowRankCore algorithm introduced in Ref.~ [1]
Parameters
----------
beta : float
Minimum fraction of core or peripheral nodes.
This parameter ensures :math:`\\beta \\leq \\frac{Nc}{N_c + N_p}, \\frac{Np}{N_c + N_p}`, where
:math:`N_c` and :math:`N_p` are the number of core and peripheral nodes, respectively. (optional, default: 0.1)
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> lrc = cpa.LowRankCore()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> lrc.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = lrc.get_pair_id()
Retrieve the coreness:
>>> coreness = lrc.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
The algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
.. rubric:: Reference
[1] <NAME>, <NAME>, <NAME>, and <NAME>. Porter Detection of core-periphery structure in networks using spectral methods and geodesic paths. Euro. J. Appl. Math., 27:846–887, 2016.
"""
def __init__(self, beta = 0.1):
self.beta = beta
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G)
"""
self.c_, self.x_ = self._low_rank_core(G)
self.Q_ = self._score(G, self.c_, self.x_)
self.qs_ = self.Q_
def _score(self, G, c, x):
N = nx.number_of_nodes(G)
A = nx.to_scipy_sparse_matrix(G)
xx = np.zeros((N,1))
for idx, nd in enumerate(G.nodes()):
xx[idx] = x[nd]
Mcc = np.dot(xx.T * A, xx)/2
Mcp = np.dot(xx.T * A, (1-xx))
Mpp = np.dot(xx.T * A, xx)/2
i = np.sum(xx)
if i <2 or i >N-2:
return [0.0]
q = Mcc/float(i*(i-1)/2) + Mcp/float(i*(N-i)) - Mpp / float((N-i)*((N-i)-1)/2)
return [q[0,0]]
def _find_cut(self, G, score, b):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
M = nx.number_of_edges(G)
A = nx.to_scipy_sparse_matrix(G)
qc = np.zeros(N)
qp = np.zeros(N)
od = (-score).argsort()
for i in range(b, N-b):
x = np.zeros((N,1))
x[od[0:i]] = 1
Mcc = np.dot(x.T * A, x)[0,0]/2
Mcp = np.dot(x.T * A, (1-x))[0,0]
Mpp = np.dot((1-x).T * A, (1-x))[0,0]/2
qc[i] = Mcc/float(i*(i-1)/2) + Mcp/float(i*(N-i)) - Mpp / float((N-i)*((N-i)-1)/2)
qp[i] = Mcp/float(i*(N-i)) + Mpp / float((N-i)*((N-i)-1)/2) - Mcc/float(i*(i-1)/2)
idx_c = np.argmax(qc)
idx_p = np.argmax(qp)
if qc[idx_c] > qp[idx_p]:
Q = qc[idx_c]
x = np.zeros(N)
x[od[0:idx_c]] = 1
else:
Q = qc[idx_p]
x = np.ones(N)
x[od[0:idx_p]] = 0
Q = Q/N
c = dict(zip( [id2node[i] for i in range(N)], np.zeros(N).astype(int)))
x = dict(zip( [id2node[i] for i in range(N)], x.astype(int).tolist()))
return c, x
def _low_rank_core(self, G):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
M = nx.number_of_edges(G)
A = nx.to_scipy_sparse_matrix(G).asfptype()
d, v = eigs(A, k=2, which='LM');
At = (np.dot(v * diags(d), v.T)>0.5).astype(int)
score = At.sum(axis=0)
c, x = self._find_cut(G, score, int(np.round(N * self.beta)) )
return c, x
class LapCore(CPAlgorithm):
"""LapCore algorithm.
LapCore algorithm introduced in Ref.~ [1]
Parameters
----------
beta : float
Minimum fraction of core or peripheral nodes.
This parameter ensures :math:`\\beta \\leq \\frac{Nc}{N_c + N_p}, \\frac{Np}{N_c + N_p}`, where
:math:`N_c` and :math:`N_p` are the number of core and peripheral nodes, respectively. (optional, default: 0.1)
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> lc = cpa.LapCore()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> lc.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = lc.get_pair_id()
Retrieve the coreness:
>>> coreness = lc.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
Also, the algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
.. rubric:: Reference
[1] <NAME>, <NAME>, <NAME>, and <NAME>. Porter Detection of core-periphery structure in networks using spectral methods and geodesic paths. Euro. J. Appl. Math., 27:846–887, 2016.
"""
def __init__(self, beta = 0.1):
self.beta = beta
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lc = cp.LapCore()
>>> lc.detect(G)
"""
self.c_, self.x_ = self._lap_core(G)
self.Q_ = self._score(G, self.c_, self.x_)
self.qs_ = self.Q_
def _score(self, G, c, x):
N = nx.number_of_nodes(G)
A = nx.to_scipy_sparse_matrix(G)
xx = np.zeros((N,1))
for idx, nd in enumerate(G.nodes()):
xx[idx] = x[nd]
Mcc = np.dot(xx.T * A, xx)/2
Mcp = np.dot(xx.T * A, (1-xx))
Mpp = np.dot(xx.T * A, xx)/2
i = np.sum(xx)
if i <2 or i >N-2:
return [0.0]
q = Mcc/float(i*(i-1)/2) + Mcp/float(i*(N-i)) - Mpp / float((N-i)*((N-i)-1)/2)
return [q[0,0]]
def _find_cut(self, G, score, b):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
M = nx.number_of_edges(G)
A = nx.to_scipy_sparse_matrix(G)
qc = np.zeros(N)
qp = np.zeros(N)
od = (-score).argsort()
for i in range(b, N-b):
x = np.zeros((N,1))
x[od[0:i]] = 1
Mcc = np.dot(x.T * A, x)[0,0]/2
Mcp = np.dot(x.T * A, (1-x))[0,0]
Mpp = np.dot((1-x).T * A, (1-x))[0,0]/2
qc[i] = Mcc/float(i*(i-1)/2) + Mcp/float(i*(N-i)) - Mpp / float((N-i)*((N-i)-1)/2)
qp[i] = Mcp/float(i*(N-i)) + Mpp / float((N-i)*((N-i)-1)/2) - Mcc/float(i*(i-1)/2)
idx_c = np.argmax(qc)
idx_p = np.argmax(qp)
if qc[idx_c] > qp[idx_p]:
Q = qc[idx_c]
x = np.zeros(N)
x[od[0:idx_c]] = 1
else:
Q = qc[idx_p]
x = np.ones(N)
x[od[0:idx_p]] = 0
Q = Q/N
c = dict(zip( [id2node[i] for i in range(N)], np.zeros(N).astype(int)))
x = dict(zip( [id2node[i] for i in range(N)], x.astype(float).tolist()))
return c, x
def _lap_core(self, G):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
M = nx.number_of_edges(G)
A = nx.to_scipy_sparse_matrix(G)
deg = np.array([d[1] for d in G.degree()])
denom = np.zeros(N)
denom[deg>0] = 1.0 / (deg[deg>0] + 1.0)
T = diags(denom) * A -diags(np.ones(N))
d, v = eigs(T, k=1, which='SR')
c, x = self._find_cut(G, v.T[0], int(np.round(N * self.beta)) )
return c, x
class LapSgnCore(CPAlgorithm):
"""LowSgnCore algorithm.
LapSgnCore algorithm introduced in Ref.~ [1]
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> lsc = cpa.LapSgnCore()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> lsc.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = lsc.get_pair_id()
Retrieve the coreness:
>>> coreness = lsc.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
Also, the algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
.. rubric:: Reference
[1] <NAME>, <NAME>, <NAME>, and <NAME>. Porter Detection of core-periphery structure in networks using spectral methods and geodesic paths. Euro. J. Appl. Math., 27:846–887, 2016.
"""
def __init__(self):
self.beta = 0.1
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lsc = cp.LapSgnCore()
>>> lsc.detect(G)
"""
self.c_, self.x_ = self._lapsgn_core(G)
self.Q_ = self._score(G, self.c_, self.x_)
self.qs_ = self.Q_
def _score(self, G, c, x):
N = nx.number_of_nodes(G)
A = nx.to_scipy_sparse_matrix(G)
xx = np.zeros((N,1))
for idx, nd in enumerate(G.nodes()):
xx[idx] = x[nd]
Mcc = np.dot(xx.T * A, xx)/2
Mcp = np.dot(xx.T * A, (1-xx))
Mpp = np.dot(xx.T * A, xx)/2
i = np.sum(xx)
if i <2 or i >N-2:
return [0.0]
q = Mcc/float(i*(i-1)/2) + Mcp/float(i*(N-i)) - Mpp / float((N-i)*((N-i)-1)/2)
return [q[0,0]]
def _lapsgn_core(self, G):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
M = nx.number_of_edges(G)
A = nx.to_scipy_sparse_matrix(G)
deg = np.array([d[1] for d in G.degree()])
denom = np.zeros(N)
denom[deg>0] = 1.0 / (deg[deg>0] + 1.0)
T = diags(denom) * A -diags(np.ones(N))
d, v = eigs(T, k=1, which='SR');
v = np.sign(v);
c = dict(zip( [id2node[i] for i in range(N)], np.zeros(N).astype(int)))
xp = dict(zip( [id2node[i] for i in range(N)], (v.T>0).astype(float).tolist()[0]))
xn = dict(zip( [id2node[i] for i in range(N)], (v.T<0).astype(float).tolist()[0]))
if self._score(G, c, xn) < self._score(G, c, xp):
x = xp
else:
x = xn
return c, x
<file_sep>/requirements.txt
pybind11>=2.2
networkx>=2.0
numpy>=1.14.2
scipy>=1.1.0
simanneal
<file_sep>/cpalgorithm/CPAlgorithm.py
from abc import ABCMeta, abstractmethod
import abc
import networkx as nx
import numpy as np
class CPAlgorithm(metaclass=ABCMeta):
def __init__(self):
self.x_ = []
self.c_ = []
self.Q_ = []
self.qs_ = []
@abstractmethod
def detect(self):
""" Private """
pass
@abstractmethod
def _score(self, G, c, x):
""" Private """
pass
def get_pair_id(self):
"""Get core-periphery pair ID of each node.
Returns
-------
c : dict
Key: Node name
Value: IDs of core-periphery pair to which it belongs.
"""
return self.c_
def get_coreness(self):
"""Get the coreness of each node"""
return self.x_
def score(*args):
"""Get score of core-periphery pairs.
Parameters
----------
G : Graph object.
c : Dict object, the keys and values of which are the name of node and its ID of belonging core-periphery pair.
Returns
-------
q : List. q[i] is the quality of core-periphery pair i.
"""
self = args[0]
if len(args) ==1:
return self.qs_
else:
G = args[1]
c = args[2]
x = args[3]
return self._score(G, c, x)
def _to_edge_list(self, G):
"""Transform NetworkX object to an edge list.
Parameters
----------
G : Graph object.
Returns
-------
node_pairs : (M, 2) numpy array, where M is the number of edges. node_pairs[i,0] and node_pairs[i,1] are the endpoints of the ith edge.
w : Mx1 numpy array. w[i] is the weight of the ith edge.
node2id : Dict. A function mapping from node name to node id, i.e., node2id[node_name] gives the id.
id2node : Dict. A function mapping from node id to node name, i.e., id2node[node_id] gives the node name.
"""
node2id = dict(zip(G.nodes, range(len(G.nodes))))
id2node= dict((v,k) for k,v in node2id.items())
nx.relabel_nodes(G, node2id,False)
edges = G.edges(data="weight")
node_pairs = np.array([ [edge[0], edge[1]] for edge in edges ]).astype(int)
w = np.array([ edge[2] for edge in edges ]).astype(float)
if all(np.isnan(w)):
nx.set_edge_attributes(G, values =1, name='weight')
w[:] = 1.0
nx.relabel_nodes(G,id2node,False)
return node_pairs, w, node2id, id2node
<file_sep>/docs/generated/cpalgorithm.KM_config.rst
cpalgorithm.KM\_config
======================
.. currentmodule:: cpalgorithm
.. autoclass:: KM_config
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~KM_config.__init__
~KM_config.detect
~KM_config.get_coreness
~KM_config.get_pair_id
~KM_config.score
~KM_config.significance
<file_sep>/cpalgorithm/KM_ER.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class KM_ER(CPAlgorithm):
"""Kojaku-Masuda algorithm with the Erdos-Renyi random graph.
This algorithm finds multiple core-periphery pairs in networks.
In the detection of core-periphery pairs, the Erdos-Renyi random graph is used as the null model.
Parameters
----------
num_runs : int
Number of runs of the algorithm (optional, default: 1).
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> km = cpa.KM_ER()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> km.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = km.get_pair_id()
Retrieve the coreness:
>>> coreness = km.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
.. rubric:: Reference
[1] <NAME> and <NAME>. Finding multiple core-periphery pairs in network. Phys. Rev. 96(5):052313, 2017
"""
def __init__(self, num_runs = 10):
self.num_runs = num_runs
def detect(self, G):
"""Detect multiple core-periphery pairs.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> km = cp.KM_ER() # label switching algorithm
>>> km.detect(G)
"""
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_ER(edges=node_pairs, ws=w, num_of_runs = self.num_runs)
N = len(node2id)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_ER(edges=node_pairs, ws=w, c =_c, x = _x)
return result[1].tolist()
def significance(self):
return self.pvalues
<file_sep>/cpalgorithm/Rossa.py
import _cpalgorithm as _cp
from scipy.sparse import diags
from scipy.sparse.linalg import eigs
from .CPAlgorithm import *
class Rossa(CPAlgorithm):
"""Rossa's algorithm for finding continuous core-periphery structure.
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> rs = cpa.Rossa()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> rs.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = rs.get_pair_id()
Retrieve the coreness:
>>> coreness = rs.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
The algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
.. rubric:: Reference
<NAME>, <NAME>, and <NAME>. Profiling core-periphery network structure by random walkers. Scientific Reports, 3, 1467, 2013
"""
def __init__(self):
return
def detect(self, G):
"""Detect a single core-periphery structure.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> rs = cp.Rossa()
>>> rs.detect(G)
"""
self.c_, self.x_ = self._detect(G)
self.Q_ = self._score(G, self.c_, self.x_)
self.qs_ = self.Q_
def _score(self, G, c, x):
nodes = G.nodes()
xx = np.zeros((len(nodes),1))
for idx, nd in enumerate(nodes):
xx[idx] = x[nd]
return [1-np.sum(xx) / len(nodes)]
def _detect(self, G):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = nx.number_of_nodes(G)
deg = np.array([d[1] for d in G.degree()])
deg = np.asmatrix(deg)
M = sum(deg) / 2.0
A = nx.to_scipy_sparse_matrix(G)
x = np.zeros((N, 1))
idx = self._argmin2(np.squeeze(np.asarray(deg)))
x[idx] = 1
ak = deg[0,idx]
bk = 0
alpha = np.zeros(N)
for k in range(1, N):
denom = np.asscalar(np.max([1,np.max(ak * (ak + deg))]) )
score = (2 * ak * (x.T * A) - bk * deg) / denom
score[ x.T > 0 ] = np.Infinity
score = np.squeeze(np.asarray(score))
idx = self._argmin2(score)
x[idx] = 1
ak = ak + deg[0, idx]
bk = np.asscalar(np.dot(x.T* A, x)[0,0])
alpha[idx] = bk / max(1, ak)
c = dict(zip( [id2node[i] for i in range(N)], np.zeros(N).astype(int)))
x = dict(zip( [id2node[i] for i in range(N)], alpha))
return c, x
def _argmin2(self, b):
return np.random.choice(np.flatnonzero(b == b.min()))
<file_sep>/docs/Examples.rst
.. _examples:
########
Examples
########
Load a graph from a list of edges
---------------------------------
In many cases, network structure is described by a list of edges.
In this example, we consider a standard file format composed of three columns, where
the first and second columns are the pairs of adjacent nodes, and third column is the weight of the edge between them, e.g.,
.. code-block:: bash
source,target,weight
ACE,@BD,1
BDF,@BD,1
CEG,@BD,1
DFH,@BD,1
EGI,@BD,1
FHJ,@BD,1
GIK,@BD,1
HJL,@BD,1
IKM,@BD,1
@BD,ACE,1
BDF,ACE,1
CEG,ACE,1
DFH,ACE,1
EGI,ACE,1
FHJ,ACE,1
GIK,ACE,1
HJL,ACE,1
IKM,ACE,1
@BD,BDF,1
ACE,BDF,1
CEG,BDF,1
DFH,BDF,1
EGI,BDF,1
FHJ,BDF,1
GIK,BDF,1
HJL,BDF,1
IKM,BDF,1
@BD,CEG,1
ACE,CEG,1
BDF,CEG,1
DFH,CEG,1
EGI,CEG,1
FHJ,CEG,1
GIK,CEG,1
HJL,CEG,1
IKM,CEG,1
@BD,DFH,1
ACE,DFH,1
BDF,DFH,1
CEG,DFH,1
EGI,DFH,1
FHJ,DFH,1
GIK,DFH,1
HJL,DFH,1
IKM,DFH,1
@BD,EGI,1
ACE,EGI,1
BDF,EGI,1
CEG,EGI,1
DFH,EGI,1
@BD,FHJ,1
ACE,FHJ,1
BDF,FHJ,1
CEG,FHJ,1
DFH,FHJ,1
@BD,GIK,1
ACE,GIK,1
BDF,GIK,1
CEG,GIK,1
DFH,GIK,1
@BD,HJL,1
ACE,HJL,1
BDF,HJL,1
CEG,HJL,1
DFH,HJL,1
@BD,IKM,1
ACE,IKM,1
BDF,IKM,1
CEG,IKM,1
DFH,IKM,1
KMO,JLN,1
LNP,JLN,1
MOQ,JLN,1
NPR,JLN,1
OQS,JLN,1
PRT,JLN,1
QSU,JLN,1
RTV,JLN,1
SUW,JLN,1
JLN,KMO,1
LNP,KMO,1
MOQ,KMO,1
NPR,KMO,1
OQS,KMO,1
PRT,KMO,1
QSU,KMO,1
RTV,KMO,1
SUW,KMO,1
JLN,LNP,1
KMO,LNP,1
MOQ,LNP,1
NPR,LNP,1
OQS,LNP,1
PRT,LNP,1
QSU,LNP,1
RTV,LNP,1
SUW,LNP,1
JLN,MOQ,1
KMO,MOQ,1
LNP,MOQ,1
NPR,MOQ,1
OQS,MOQ,1
PRT,MOQ,1
QSU,MOQ,1
RTV,MOQ,1
SUW,MOQ,1
JLN,NPR,1
KMO,NPR,1
LNP,NPR,1
MOQ,NPR,1
OQS,NPR,1
PRT,NPR,1
QSU,NPR,1
RTV,NPR,1
SUW,NPR,1
JLN,OQS,1
KMO,OQS,1
LNP,OQS,1
MOQ,OQS,1
NPR,OQS,1
JLN,PRT,1
KMO,PRT,1
LNP,PRT,1
MOQ,PRT,1
NPR,PRT,1
JLN,QSU,1
KMO,QSU,1
LNP,QSU,1
MOQ,QSU,1
NPR,QSU,1
JLN,RTV,1
KMO,RTV,1
LNP,RTV,1
MOQ,RTV,1
NPR,RTV,1
JLN,SUW,1
KMO,SUW,1
LNP,SUW,1
MOQ,SUW,1
NPR,SUW,1
Save this file as example_edge_list.csv.
Loading this network and applying an algorithm are done by
.. code-block:: python
import networkx as nx
import pandas as pd
import cpalgorithm as cp
df = pd.read_csv('example_edge_list.csv', sep=',') # Load a list of edges (comma-separated file)
G = nx.from_pandas_edgelist(df) # NetworkX graph object
algorithm = cp.KM_ER()
algorithm.detect(G)
c = algorithm.get_pair_id()
x = algorithm.get_coreness()
print('Name\tPairID\tCoreness')
for key, value in sorted(c.items(), key=lambda x: x[1]):
print('%s\t%d\t%f' %(key, c[key], x[key]))
which displays
.. code-block:: bash
Name PairID Coreness
OQS 0 0.000000
LNP 0 1.000000
QSU 0 0.000000
SUW 0 0.000000
KMO 0 1.000000
MOQ 0 1.000000
PRT 0 0.000000
JLN 0 1.000000
NPR 0 1.000000
RTV 0 0.000000
IKM 1 0.000000
HJL 1 0.000000
BDF 1 1.000000
@BD 1 1.000000
EGI 1 0.000000
GIK 1 0.000000
FHJ 1 0.000000
CEG 1 1.000000
ACE 1 1.000000
DFH 1 1.000000
<file_sep>/docs/generated/cpalgorithm.Divisive.rst
cpalgorithm.Divisive
====================
.. currentmodule:: cpalgorithm
.. autoclass:: Divisive
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Divisive.__init__
~Divisive.detect
~Divisive.get_coreness
~Divisive.get_pair_id
~Divisive.score
<file_sep>/example.py
import pandas as pd
import networkx as nx
import cpalgorithm as cp
G=nx.karate_club_graph()
be = cp.Surprise()
be.detect(G)
c = be.get_pair_id()
x = be.get_coreness()
print('Name\tPairID\tCoreness')
for key, value in sorted(c.items(), key=lambda x: x[1]):
print('%s\t%d\t%f' %(key, c[key], x[key]))
<file_sep>/include/template.h
/*
*
* Header file of the BE algorithm
*
*
* Please do not distribute without contacting the authors.
*
* AUTHOR - <NAME>
*
* DATE - 04 July 2018
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
class BEAlgorithm: public BEAlgorithm{
public:
// Constructor
BEAlgorithm();
BEAlgorithm(int num_runs);
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<bool>& x,
double& Q,
vector<double>& q);
protected: // function needed to be implemented
int _num_runs;
};
/*-----------------------------
Constructor
-----------------------------*/
BEAlgorithm::BEAlgorithm(int num_runs):CPAlgorithm(){
BEAlgorithm();
_num_runs = num_runs;
};
BEAlgorithm::BEAlgorithm(): CPAlgorithm(){
_num_runs = 10;
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void BEAlgorithm::detect(const Graph& G){
_km_modmat_louvain(G.to_matrix(), _num_runs, _c, _x, _Q, _q, _mtrnd);
}
void BEAlgorithm::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<bool>& x,
double& Q,
vector<double>& q)
{
vector<vector<double>>M = G.to_matrix();
_calc_Q_modmat(M,c,x,Q,q);
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
<file_sep>/docs/Reference.rst
.. _reference:
############
Reference
############
Core-periphery detection algorithms
-----------------------------------
.. currentmodule:: cpalgorithm
.. rubric:: Algorithms for finding single core-periphery structure
.. automodule:: cpalgorithm
.. autosummary::
:toctree: generated/
.. autosummary::
BE
MINRES
SBM
LowRankCore
LapCore
LapSgnCore
Rombach
Rossa
Surprise
.. rubric:: Algorithms for finding multiple core-periphery pairs
.. automodule:: cpalgorithm
.. autosummary::
:toctree: generated/
.. autosummary::
Divisive
KM_ER
KM_config
Statistical test
----------------
.. currentmodule:: cpalgorithm
.. automodule:: cpalgorithm
.. autosummary::
:toctree: generated/
.. autosummary::
cpalgorithm.qstest
<file_sep>/docs/FAQ/Failed_to_install.rst
.. _failed_to_install_cpalgorithm:
.. role:: python(code)
:language: python
#############################
Failed to install cpalgorithm
#############################
cpalgorithm contains c++ extension modules which need to be compiled.
First, please make sure that you have one of the following compilers:
- Clang/LLVM 3.3 or newer (for Apple Xcode's clang, this is 5.0.0 or newer)
- GCC 4.8 or newer
- Microsoft Visual C++ Build Tools 2015 or newer
- Intel C++ compiler 17 or newer
- Cygwin/GCC (tested on 2.5.1)
Also, you need to install `pybind11 <https://github.com/pybind/pybind11>`_.
========================================
cpalgorithm is not compatible with Conda
========================================
Installing packages via pip may destroy `Conda <https://conda.io/docs/index.html>`_.
Consider installing the package from source. See :ref:`install_from_source`.
====================
Check python version
====================
cpalgorithm is not compatible with python 2.x.
Use python version 3.4 or newer.
=========
Change OS
=========
The library is frequently tested on Ubuntu 16.04 and CentOS 7, and occasionally on Windows 10 and MacOS.
So if you failed to install on Windows and MacOS, then consider using Ubuntu or CentOS.
.. _install_from_source:
===================
Install from source
===================
If you failed to install via pip, another option is to build from source.
Download the source code from GitHub, e.g.,
.. code-block:: bash
git clone https://github.com/skojaku/core-periphery-detection
Then, move to the directory
.. code-block:: bash
cd core-periphery-detection
Type
.. code-block:: bash
python -m pip install .
If you are luckily, you can install the package (Congratulations!).
If you could not, then find out the error messages.
In many cases, the compilers do not support std=c++11 or do not meet the requirements mentioned above.
In this case, upgrade the compilers.
<file_sep>/docs/generated/cpalgorithm.SBM.rst
cpalgorithm.SBM
===============
.. currentmodule:: cpalgorithm
.. autoclass:: SBM
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~SBM.__init__
~SBM.detect
~SBM.get_coreness
~SBM.get_pair_id
~SBM.score
<file_sep>/docs/generated/cpalgorithm.KM_ER.rst
cpalgorithm.KM\_ER
==================
.. currentmodule:: cpalgorithm
.. autoclass:: KM_ER
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~KM_ER.__init__
~KM_ER.detect
~KM_ER.get_coreness
~KM_ER.get_pair_id
~KM_ER.score
~KM_ER.significance
<file_sep>/docs/generated/cpalgorithm.Rossa.rst
cpalgorithm.Rossa
=================
.. currentmodule:: cpalgorithm
.. autoclass:: Rossa
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Rossa.__init__
~Rossa.detect
~Rossa.get_coreness
~Rossa.get_pair_id
~Rossa.score
<file_sep>/include/km_config.h
/*
*
* Header file of the KM-config algorithm (C++ version)
*
*
* An algorithm for finding multiple core-periphery pairs in networks
*
*
* Core-periphery structure requires something else in the network
* <NAME> and <NAME>
* Preprint arXiv:1710.07076
*
*
* Please do not distribute without contacting the authors.
*
*
* AUTHOR - <NAME>
*
*
* DATE - 11 Oct 2017
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
class KM_config: public CPAlgorithm{
public:
// Constructor
KM_config();
KM_config(int num_runs);
// function needed to be implemented
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected:
private:
int _num_runs;
uniform_real_distribution<double> _udist;
void _km_config_label_switching(
const Graph& G,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
);
double _calc_dQ_conf(double d_i_c,
double d_i_p,
double d_i,
double D_c,
double D_p,
double selfloop,
double x,
const double M);
void _propose_new_label(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
const vector<double>& sum_of_deg_core,
const vector<double>& sum_of_deg_peri,
const double M,
const int node_id,
int& cprime,
double& xprime,
double& dQ,
mt19937_64& mtrnd
);
void _km_config_label_switching_core(
const Graph& G,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
);
void _km_config_louvain(
const Graph& G,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
);
/*
void _km_config_louvain_core(
const Graph& G,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
);
*/
void _coarsing(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
Graph& newG,
vector<int>& toLayerId
);
void _relabeling(vector<int>& c);
};
/*-----------------------------
Constructor
-----------------------------*/
KM_config::KM_config(int num_runs):CPAlgorithm(){
KM_config();
_num_runs = num_runs;
};
KM_config::KM_config():CPAlgorithm(){
uniform_real_distribution<double> tmp(0.0,1.0);
_udist = tmp;
_num_runs = 10;
_mtrnd = _init_random_number_generator();
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void KM_config::detect(const Graph& G){
//_km_config_label_switching(G, _num_runs, _c, _x, _Q, _q, _mtrnd);
_km_config_louvain(G, _num_runs, _c, _x, _Q, _q, _mtrnd);
}
void KM_config::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
int N = G.get_num_nodes();
int K = *max_element(c.begin(), c.end()) + 1;
q.assign(K, 0.0);
vector<double> Dc(K, 0.0);
vector<double> Dp(K, 0.0);
double double_M = 0.0;
for (int i = 0; i < N; i++) {
int sz = G.degree(i);
double di = 0;
for (int j = 0; j < sz; j++) {
Neighbour nn = G.get_kth_neighbour(i, j);
int nei = nn.get_node();
double wj = nn.get_w();
q[c[i]] += wj * !!(c[i] == c[nei]) * (x[i] + x[nei] - x[i] * x[nei]);
di+=wj;
}
Dc[c[i]] += x[i] * di;
Dp[c[i]] += (1-x[i]) * di;
double_M += di;
}
Q = 0;
for (int k = 0; k < K; k++) {
q[k] = (q[k] - (Dc[k] * Dc[k] + 2 * Dc[k] * Dp[k]) / double_M) / double_M;
Q += q[k];
}
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
void KM_config::_km_config_label_switching(
const Graph& G,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
)
{
int N = G.get_num_nodes();
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, 1.0);
Q = -1;
for (int i = 0; i < num_of_runs; i++) {
vector<int> ci;
vector<double> xi;
vector<double> qi;
double Qi = 0.0;
_km_config_label_switching_core(G, ci, xi, _mtrnd);
calc_Q(G, ci, xi, Qi, qi);
if (Qi > Q) {
c = ci;
x = xi;
q.clear();
q = qi;
Q = Qi;
}
}
}
/*
void KM_config::_km_config_label_switching(
const Graph& G,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
)
{
int N = G.get_num_nodes();
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, true);
// Generate \hat q^{(s)} and \hat n^{(s)} (1 \leq s \leq S)
// create random number generator per each thread
int numthread = 1;
#ifdef _OPENMP
# pragma omp parallel
{
numthread = omp_get_num_threads();
}
#endif
cout<<numthread<<endl;
vector<mt19937_64> mtrnd_list(numthread);
for(int i = 0; i < numthread; i++){
mt19937_64 mtrnd = _init_random_number_generator();
mtrnd_list[i] = mtrnd;
}
Q = -1;
#ifdef _OPENMP
#pragma omp parallel for shared(c, x, Q, q, N, G, mtrnd_list)
#endif
for (int i = 0; i < num_of_runs; i++) {
vector<int> ci;
vector<double> xi;
vector<double> qi;
double Qi = 0.0;
int tid = 0;
#ifdef _OPENMP
tid = omp_get_thread_num();
#endif
mt19937_64 mtrnd = mtrnd_list[tid];
_km_config_label_switching_core(G, ci, xi, mtrnd);
calc_Q(G, ci, xi, Qi, qi);
#pragma omp critical
{
if (Qi > Q) {
c = ci;
x = xi;
q.clear();
q = qi;
Q = Qi;
}
}
}
}
*/
double KM_config::_calc_dQ_conf(double d_i_c,
double d_i_p,
double d_i,
double D_c,
double D_p,
double selfloop,
double x,
const double M)
{
return 2 * (d_i_c + d_i_p * (x) - d_i * (D_c + D_p * x) / (2.0 * M)) + x * (selfloop - d_i * d_i / (2.0 * M));
}
void KM_config::_propose_new_label(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
const vector<double>& sum_of_deg_core,
const vector<double>& sum_of_deg_peri,
const double M,
const int node_id,
int& cprime,
double& xprime,
double& dQ,
mt19937_64& mtrnd)
{
int N = G.get_num_nodes();
int neighbourNum = G.degree(node_id);
double deg = G.wdegree(node_id);
vector<double> edges_to_core(N, 0.0);
vector<double> edges_to_peri(N, 0.0);
double selfloop = 0;
for (int j = 0; j < neighbourNum; j++) {
Neighbour nn = G.get_kth_neighbour(node_id, j);
int nei = nn.get_node();
double wj = nn.get_w();
if(node_id == nei){
selfloop+= wj;
continue;
}
edges_to_core[c[nei]] += wj * x[nei];
edges_to_peri[c[nei]] += wj * (1-x[nei]);
}
double D_core = sum_of_deg_core[c[node_id]] - deg * x[node_id];
double D_peri = sum_of_deg_peri[c[node_id]] - deg * (1-x[node_id]);
double dQold = _calc_dQ_conf(edges_to_core[c[node_id]], edges_to_peri[c[node_id]], deg,
D_core, D_peri, selfloop, x[node_id], M);
dQ = 0;
for (int j = 0; j < neighbourNum; j++) {
Neighbour nn = G.get_kth_neighbour(node_id, j);
int nei = nn.get_node();
//double wj = nn.get_w();
int cid = c[nei];
D_core = sum_of_deg_core[cid] - deg * x[node_id] * (double)!!(c[node_id] == cid);
D_peri = sum_of_deg_peri[cid] - deg * (1-x[node_id]) * (double)!!( c[node_id] == cid );
double Q_i_core = _calc_dQ_conf(edges_to_core[cid], edges_to_peri[cid],
deg, D_core, D_peri, selfloop, 1, M);
double Q_i_peri = _calc_dQ_conf(edges_to_core[cid], edges_to_peri[cid],
deg, D_core, D_peri, selfloop, 0, M);
Q_i_core -= dQold;
Q_i_peri -= dQold;
if (MAX(Q_i_core, Q_i_peri) < dQ)
continue;
if (Q_i_peri < Q_i_core) {
xprime = 1;
cprime = cid;
dQ = Q_i_core;
}
else if (Q_i_peri > Q_i_core) {
xprime = 0;
cprime = cid;
dQ = Q_i_peri;
}
else {
cprime = cid;
if(_udist(mtrnd) < 0.5){
xprime =1;
}else{
xprime =0;
}
dQ = Q_i_core;
}
}
}
void KM_config::_km_config_label_switching_core(
const Graph& G,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
)
{
/* Variable declarations */
int N = G.get_num_nodes();
vector<double> sum_of_deg_core(N);
vector<double> sum_of_deg_peri(N);
vector<int> order(N);
vector<double> degs(N);
double M = 0;
bool isupdated = false;
fill(sum_of_deg_core.begin(), sum_of_deg_core.end(), 0.0);
fill(sum_of_deg_peri.begin(), sum_of_deg_peri.end(), 0.0);
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, 1);
for (int i = 0; i < N; i++) {
order[i] = i;
c[i] = i;
double deg = G.wdegree(i);
degs[i] = deg;
sum_of_deg_core[i] += x[i] * deg;
M += deg;
};
M = M / 2;
/* Label switching algorithm */
do {
isupdated = false;
shuffle(order.begin(), order.end(), mtrnd);
for (int scan_count = 0; scan_count < N; scan_count++) {
int i = order[scan_count];
int cprime = c[i]; // c'
double xprime = x[i]; // x'
double dQ = 0;
_propose_new_label(G, c, x, sum_of_deg_core, sum_of_deg_peri,
M, i, cprime, xprime, dQ, mtrnd);
if (dQ <= 0)
continue;
if ( (c[i] == cprime) & (x[i] == xprime) )
continue;
double deg = degs[i];
sum_of_deg_core[c[i]] -= deg * x[i];
sum_of_deg_peri[c[i]] -= deg * (1-x[i]);
sum_of_deg_core[cprime] += deg * xprime;
sum_of_deg_peri[cprime] += deg * (1-xprime);
c[i] = cprime;
x[i] = xprime;
isupdated = true;
}
} while (isupdated == true);
/* Remove empty core-periphery pairs */
std::vector<int> labs;
for (int i = 0; i < N; i++) {
int cid = -1;
int labsize = (int) labs.size();
for (int j = 0; j < labsize; j++) {
if (labs[j] == c[i]) {
cid = j;
break;
}
}
if (cid < 0) {
labs.push_back(c[i]);
cid = (int)labs.size() - 1;
}
c[i] = cid;
}
}
/* Louvain algorithm */
void KM_config::_km_config_louvain(
const Graph& G,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
){
// Intiialise variables
int N = G.get_num_nodes();
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, 1);
for (int i = 0; i < N; i++) c[i] = i;
vector<int>ct = c; // label of each node at tth iteration
vector<double>xt = x; // label of each node at tth iteration.
Graph cnet_G; // coarse network
vector<int> toLayerId; //toLayerId[i] maps 2*c[i] + x[i] to the id of node in the coarse network
_coarsing(G, ct, xt, cnet_G, toLayerId); // Initialise toLayerId
Q = 0; // quality of the current partition
int cnet_N;
do{
cnet_N = cnet_G.get_num_nodes();
// Core-periphery detection
vector<int> cnet_c; // label of node in the coarse network, Mt
vector<double> cnet_x; // label of node in the coarse network, Mt
double Qt = 0; vector<double> qt;
_km_config_label_switching(cnet_G, num_of_runs, cnet_c, cnet_x, Qt, qt, mtrnd);
//_km_config_label_switching_core(cnet_G, cnet_c, cnet_x, mtrnd);
// Update the label of node in the original network, ct and xt.
for(int i = 0; i< N; i++){
int cnet_id = toLayerId[2 * ct[i] + (int)xt[i]];
ct[i] = cnet_c[ cnet_id ];
xt[i] = cnet_x[ cnet_id ];
}
// Compute the quality
//calc_Q(G, ct, xt, Qt, qt);
calc_Q(cnet_G, cnet_c, cnet_x, Qt, qt);
if(Qt>=Q){ // if the quality is the highest among those detected so far
c = ct;
x = xt;
Q = Qt;
q = qt;
}
// Coarsing
Graph new_cnet_G;
_coarsing(cnet_G, cnet_c, cnet_x, new_cnet_G, toLayerId);
cnet_G = new_cnet_G;
//cout<<"---"<<cnet_G.get_num_nodes()<<" "<<cnet_G.get_num_edges()<<" "<<G.get_num_edges()<<"---"<<endl;
int sz = cnet_G.get_num_nodes();
if(sz == cnet_N) break;
}while( true );
_relabeling(c);
}
void KM_config::_coarsing(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
Graph& newG,
vector<int>& toLayerId
){
int N = (int) c.size();
vector<int> ids(N,0);
int maxid = 0;
for(int i = 0;i<N;i++){
ids[i] = 2 * c[i] + (int)x[i];
maxid = MAX(maxid, ids[i]);
}
_relabeling(ids);
toLayerId.clear();
toLayerId.assign(maxid+1,0);
for(int i = 0;i<N;i++){
toLayerId[2 * c[i] + (int)x[i]] = ids[i];
}
int K = *max_element(ids.begin(), ids.end()) + 1;
newG = Graph(K);
for(int i = 0;i<N;i++){
int mi = 2 * c[i] + (int)x[i];
int sz = G.degree(i);
for(int j = 0;j<sz;j++){
Neighbour nb = G.get_kth_neighbour(i, j);
int nei = nb.get_node();
double w = nb.get_w();
int mj = 2 * c[nei] + (int)x[nei];
int sid = toLayerId[mi];
int did = toLayerId[mj];
newG.addEdge(sid, did, w);
}
}
newG.compress();
}
void KM_config::_relabeling(
vector<int>& c
){
int N = (int) c.size();
std::vector<int> labs;
for (int i = 0; i < N; i++) {
int cid = -1;
int labsize = (int) labs.size();
for (int j = 0; j < labsize; j++) {
if (labs[j] == c[i]) {
cid = j;
break;
}
}
if (cid < 0) {
labs.push_back(c[i]);
cid = (int) labs.size() - 1;
}
c[i] = cid;
}
}
<file_sep>/docs/generated/cpalgorithm.Rombach.rst
cpalgorithm.Rombach
===================
.. currentmodule:: cpalgorithm
.. autoclass:: Rombach
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Rombach.__init__
~Rombach.detect
~Rombach.get_coreness
~Rombach.get_pair_id
~Rombach.score
<file_sep>/docs/generated/cpalgorithm.qstest.rst
cpalgorithm.qstest
==================
.. currentmodule:: cpalgorithm
.. autofunction:: qstest<file_sep>/cpalgorithm/BE.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class BE(CPAlgorithm):
"""Borgatti Everett algorithm.
An algorithm for finding single core-periphery pair in networks.
Parameters
----------
num_runs : int
Number of runs of the algorithm (optional, default: 10)
Run the algorithm num_runs times. Then, this algorithm outputs the result yielding the maximum quality.
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> be = cpa.BE()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> be.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = be.get_pair_id()
Retrieve the coreness:
>>> coreness = be.get_coreness()
.. note::
This algorithm accepts unweighted and undirected networks only.
Also, the algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
This algorithm is stochastic, i.e., one would obtain different results at each run.
.. rubric:: Reference
[1] <NAME> and <NAME>. Models of core/periphery structures. Soc.~Netw., 21(4):375–395, 2000.
"""
def __init__(self, num_runs = 10):
self.num_runs = num_runs
def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> be = cpa.BE()
>>> be.detect(G)
"""
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_be(edges=node_pairs, ws=w, num_of_runs = self.num_runs)
N = len(id2node)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_be(edges=node_pairs, ws=w, c=_c, x=_x)
return result[1].tolist()
<file_sep>/cpalgorithm/Divisive.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class Divisive(CPAlgorithm):
"""Divisive algorithm.
An algorithm for finding multiple core-periphery pairs in networks.
This algorithm partitions a network into communities using the Louvain algorithm.
Then, it partitions each community into a core and a periphery using the BE algorithm.
The quality of a community is computed by that equipped with the BE algorithm.
Parameters
----------
num_runs : int
Number of runs of the algorithm (optional, default: 10)
Run the algorithm num_runs times. Then, this algorithm outputs the result yielding the maximum quality.
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> dv = cpa.Divisive()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> dv.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = dv.get_pair_id()
Retrieve the coreness:
>>> coreness = dv.get_coreness()
.. note::
This algorithm accepts unweighted and undirected networks only.
This algorithm is stochastic, i.e., one would obtain different results at each run.
.. rubric:: Reference
[1] <NAME> and <NAME>. Core-periphery structure requires something else in the network. New Journal of Physics, 20(4):43012, 2018
"""
def __init__(self, num_runs = 10):
self.num_runs = num_runs
def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> dv = cpa.Divisive()
>>> dv.detect(G)
"""
node_pairs, w, node2id, id2node = self._to_edge_list(G)
# divide a network into communities
cppairs = _cp.detect_divisive(edges=node_pairs, ws=w, num_of_runs = self.num_runs)
N = len(id2node)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_divisive(edges=node_pairs, ws=w, c=_c, x=_x)
return result[1].tolist()
<file_sep>/cpalgorithm/MINRES.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class MINRES(CPAlgorithm):
"""MINRES algorithm.
MINRES algorithm for finding discrete core-periphery pairs [1], [2].
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> mrs = cpa.MINRES()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> mrs.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = mrs.get_pair_id()
Retrieve the coreness:
>>> coreness = mrs.get_coreness()
.. note::
This algorithm accepts unweighted and undirected networks only.
Also, the algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
This algorithm is deterministic, i.e, one obtains the same result at each run.
.. rubric:: References
[1] <NAME>, <NAME>, <NAME>, and <NAME>. Computing continuous core/periphery structures for social relations data with MINRES/SVD. Soc.~Netw., 32:125–137, 2010.
[2] <NAME>. A fast algorithm for the discrete core/periphery bipartitioning problem. arXiv, pages 1102.5511, 2011.
"""
def __init__(self):
self.num_runs = 0
def detect(self, G):
"""Detect a single core-periphery pair using the MINRES algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> mrs = cp.MINRES()
>>> mrs.detect(G)
"""
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_minres(edges=node_pairs, ws=w)
N = len(id2node)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_minres(edges=node_pairs, ws=w, c=_c, x=_x)
return result[1].tolist()
<file_sep>/include/km_modmat.h
/*
*
* Header file of the KM-config algorithm (C++ version)
*
*
* An algorithm for finding multiple core-periphery pairs in networks
*
*
* Core-periphery structure requires something else in the network
* <NAME> and <NAME>
* Preprint arXiv:1710.07076
*
*
* Please do not distribute without contacting the authors.
*
*
* AUTHOR - <NAME>
*
*
* DATE - 11 Oct 2017
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
class KM_modmat: public CPAlgorithm{
public:
// Constructor
KM_modmat();
KM_modmat(int num_runs);
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected: // function needed to be implemented
int _num_runs;
private:
void _km_modmat_louvain(
const vector<vector<double>>& M,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
);
void _km_modmat_louvain_core(
const vector<vector<double>>& M,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
);
void _km_modmat_label_switching(
const vector<vector<double>>& M,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
);
void _km_modmat_label_switching_core(
const vector<vector<double>>& M,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
);
void _propose_new_label_modmat(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
const int node_id,
int& cprime,
double& xprime,
double& dQ,
mt19937_64& mtrnd
);
void _calc_Q_modmat(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
void _coarsing(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
vector<vector<double>>& newM,
vector<int>& toLayerId
);
int _count_non_empty_block(
vector<int>& c,
vector<double>& x
);
void _relabeling(vector<int>& c);
};
/*-----------------------------
Constructor
-----------------------------*/
KM_modmat::KM_modmat(int num_runs):CPAlgorithm(){
KM_modmat();
_num_runs = num_runs;
};
KM_modmat::KM_modmat(): CPAlgorithm(){
_num_runs = 10;
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void KM_modmat::detect(const Graph& G){
_km_modmat_louvain(G.to_matrix(), _num_runs, _c, _x, _Q, _q, _mtrnd);
}
void KM_modmat::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
vector<vector<double>>M = G.to_matrix();
_calc_Q_modmat(M,c,x,Q,q);
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
void KM_modmat::_km_modmat_label_switching(
const vector<vector<double>>& M,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
)
{
/* Generate \hat q^{(s)} and \hat n^{(s)} (1 \leq s \leq S) */
// create random number generator per each thread
int numthread = 1;
#ifdef _OPENMP
# pragma omp parallel
{
numthread = omp_get_num_threads();
}
#endif
vector<mt19937_64> mtrnd_list(numthread);
for(int i = 0; i < numthread; i++){
mt19937_64 mtrnd = _init_random_number_generator();
mtrnd_list[i] = mtrnd;
}
Q = -1;
int N = (int) M.size();
#ifdef _OPENMP
#pragma omp parallel for shared(c, x, Q, q, N, mtrnd_list)
#endif
for (int i = 0; i < num_of_runs; i++) {
vector<int> ci;
vector<double> xi;
vector<double> qi;
double Qi = 0.0;
int tid = 0;
#ifdef _OPENMP
tid = omp_get_thread_num();
#endif
mt19937_64 mtrnd = mtrnd_list[tid];
_km_modmat_label_switching_core(M, ci, xi, mtrnd);
_calc_Q_modmat(M, ci, xi, Qi, qi);
#ifdef _OPENMP
#pragma omp critical
#endif
{
if (Qi > Q) {
for(int i = 0; i < N; i++){
c[i] = ci[i];
x[i] = xi[i];
}
q.clear();
int K = (int) qi.size();
vector<double> tmp(K,0.0);
q = tmp;
for(int k = 0; k < K; k++){
q[k] = qi[k];
}
Q = Qi;
}
}
}
}
void KM_modmat::_calc_Q_modmat(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
int N = (int) M.size();
int K = *max_element(c.begin(), c.end()) + 1;
q.assign(K, 0.0);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if( c[i] != c[j]) continue;
q[c[i]]+=M[i][j] * (x[i] + x[j] - x[i] * x[j]);
}
}
Q = 0;
for (int k = 0; k < K; k++) {
Q += q[k];
}
}
void KM_modmat::_propose_new_label_modmat(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
const int node_id,
int& cprime,
double& xprime,
double& dQ,
mt19937_64& mtrnd
)
{
int N = (int) M.size();
int K = *max_element(c.begin(), c.end()) + 1;
vector<double> dq_core(K,0.0);
vector<double> dq_peri(K,0.0);
double dq_old = 0;
for(int i = 0; i < N; i++){
if(i == node_id) continue;
dq_core[c[i]]+= M[node_id][i];
dq_peri[c[i]]+= x[i] * M[node_id][i];
dq_old+= ( x[i] + x[node_id] - x[i] * x[node_id]) * !!(c[node_id] == c[i]) * M[node_id][i];
}
double dqmax = 0;
dq_old+=!!(x[node_id])*M[node_id][node_id]/2; // add quality induced by self-edges
for(int k = 0; k < K; k++){
dq_core[k]+=M[node_id][node_id]/2; // add quality induced by self-edges
if(dq_core[k] > dq_peri[k]){
if( dq_core[k]-dq_old >0 && dq_core[k] > dqmax ){
xprime = 1.0;
cprime = k;
dqmax = dq_core[k];
dQ = dq_core[k] - dq_old;
}
}else{
if( dq_peri[k]-dq_old >0 && dq_peri[k] > dqmax ){
xprime = 0;
cprime = k;
dqmax = dq_peri[k];
dQ = dq_peri[k] - dq_old;
}
}
};
}
void KM_modmat::_relabeling(
vector<int>& c
){
int N = (int) c.size();
std::vector<int> labs;
for (int i = 0; i < N; i++) {
int cid = -1;
int labsize = (int) labs.size();
for (int j = 0; j < labsize; j++) {
if (labs[j] == c[i]) {
cid = j;
break;
}
}
if (cid < 0) {
labs.push_back(c[i]);
cid = (int)labs.size() - 1;
}
c[i] = cid;
}
}
void KM_modmat::_km_modmat_label_switching_core(
const vector<vector<double>>& M,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
)
{
/* Variable declarations */
int N = (int) M.size();
vector<int> order(N);
vector<double> degs(N);
bool isupdated = false;
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, true);
for (int i = 0; i < N; i++) {
order[i] = i;
c[i] = i;
};
/* Label switching algorithm */
do {
isupdated = false;
shuffle(order.begin(), order.end(), mtrnd);
for (int scan_count = 0; scan_count < N; scan_count++) {
int i = order[scan_count];
int cprime = c[i]; // c'
double xprime = x[i]; // x'
double dQ = 0;
_propose_new_label_modmat(M, c, x, i, cprime, xprime, dQ, mtrnd);
if (dQ <= 0)
continue;
if ( (c[i] == cprime) & (x[i] == xprime) )
continue;
c[i] = cprime;
x[i] = xprime;
isupdated = true;
}
} while (isupdated == true);
/* Remove empty core-periphery pairs */
_relabeling(c);
}
void KM_modmat::_coarsing(
const vector<vector<double>>& M,
const vector<int>& c,
const vector<double>& x,
vector<vector<double>>& newM,
vector<int>& toLayerId
){
int N = (int) c.size();
vector<int> ids(N,0);
int maxid = 0;
for(int i = 0;i<N;i++){
ids[i] = 2 * c[i] + (int)x[i];
maxid = MAX(maxid, ids[i]);
}
_relabeling(ids);
toLayerId.clear();
toLayerId.assign(maxid+1,0);
for(int i = 0;i<N;i++){
toLayerId[2 * c[i] + (int)x[i]] = ids[i];
}
int K = *max_element(ids.begin(), ids.end()) + 1;
vector<vector<double>> tmp(K, vector<double>(K,0));
newM.clear();
newM = tmp;
for(int i = 0;i<N;i++){
int mi = 2 * c[i] + (int)x[i];
for(int j = 0;j<N;j++){
int mj = 2 * c[j] + (int)x[j];
newM[ toLayerId[mi] ][ toLayerId[mj] ]+=M[i][j];
}
}
}
int KM_modmat::_count_non_empty_block(
vector<int>& c,
vector<double>& x
){
int N = (int) c.size();
vector<int> ids(N,0);
for(int i = 0; i< N; i++){
ids[i] = 2 * c[i] + (int)x[i];
}
sort(ids.begin(), ids.end());
return (int) (unique(ids.begin(), ids.end()) - ids.begin());
}
void KM_modmat::_km_modmat_louvain_core(
const vector<vector<double>>& M,
vector<int>& c,
vector<double>& x,
mt19937_64& mtrnd
){
// Intiialise variables
int N = (int) M.size();
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, 1.0);
for (int i = 0; i < N; i++) c[i] = i;
vector<int>ct = c; // label of each node at tth iteration
vector<double>xt = x; // label of each node at tth iteration.
vector<vector<double>> cnet_M; // coarse network
vector<int> toLayerId; //toLayerId[i] maps 2*c[i] + x[i] to the id of node in the coarse network
_coarsing(M, ct, xt, cnet_M, toLayerId); // Initialise toLayerId
double Qbest = 0; // quality of the current partition
int cnet_N;
do{
cnet_N = (int) cnet_M.size();
// Core-periphery detection
vector<int> cnet_c; // label of node in the coarse network, Mt
vector<double> cnet_x; // label of node in the coarse network, Mt
_km_modmat_label_switching_core(cnet_M, cnet_c, cnet_x, mtrnd);
// Update the label of node in the original network, ct and xt.
for(int i = 0; i< N; i++){
int cnet_id = toLayerId[2 * ct[i] + (int)xt[i]];
ct[i] = cnet_c[ cnet_id ];
xt[i] = cnet_x[ cnet_id ];
}
// Compute the quality
double Qt = 0; vector<double> qt;
_calc_Q_modmat(cnet_M, cnet_c, cnet_x, Qt, qt);
if(Qt>=Qbest){ // if the quality is the highest among those detected so far
c = ct;
x = xt;
Qbest = Qt;
}
// Coarsing
vector<vector<double>> new_cnet_M;
_coarsing(cnet_M, cnet_c, cnet_x, new_cnet_M, toLayerId);
cnet_M = new_cnet_M;
int sz = (int) cnet_M.size();
if(sz == cnet_N) break;
}while( true );
_relabeling(c);
}
void KM_modmat::_km_modmat_louvain(
const vector<vector<double>>& M,
const int num_of_runs,
vector<int>& c,
vector<double>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd
)
{
int N = (int) M.size();
c.clear();
x.clear();
c.assign(N, 0);
x.assign(N, 1.0);
/* Generate \hat q^{(s)} and \hat n^{(s)} (1 \leq s \leq S) */
// create random number generator per each thread
int numthread = 1;
#ifdef _OPENMP
# pragma omp parallel
{
numthread = omp_get_num_threads();
}
#endif
vector<mt19937_64> mtrnd_list(numthread);
for(int i = 0; i < numthread; i++){
mt19937_64 mtrnd = _init_random_number_generator();
mtrnd_list[i] = mtrnd;
}
Q = -1;
#ifdef _OPENMP
#pragma omp parallel for shared(c, x, Q, q, N, M, mtrnd_list)
#endif
for (int i = 0; i < num_of_runs; i++) {
vector<int> ci;
vector<double> xi;
vector<double> qi;
double Qi = 0.0;
int tid = 0;
#ifdef _OPENMP
tid = omp_get_thread_num();
#endif
mt19937_64 mtrnd = mtrnd_list[tid];
_km_modmat_louvain_core(M, ci, xi, mtrnd);
_calc_Q_modmat(M, ci, xi, Qi, qi);
#pragma omp critical
{
if (Qi > Q) {
for(int i = 0; i < N; i++){
c[i] = ci[i];
x[i] = xi[i];
}
q.clear();
int K = (int) qi.size();
vector<double> tmp(K,0.0);
q = tmp;
for(int k = 0; k < K; k++){
q[k] = qi[k];
}
Q = Qi;
}
}
}
}
<file_sep>/docs/generated/cpalgorithm.LapSgnCore.rst
cpalgorithm.LapSgnCore
======================
.. currentmodule:: cpalgorithm
.. autoclass:: LapSgnCore
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~LapSgnCore.__init__
~LapSgnCore.detect
~LapSgnCore.get_coreness
~LapSgnCore.get_pair_id
~LapSgnCore.score
<file_sep>/docs/generated/cpalgorithm.Surprise.rst
cpalgorithm.Surprise
====================
.. currentmodule:: cpalgorithm
.. autoclass:: Surprise
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~Surprise.__init__
~Surprise.detect
~Surprise.get_coreness
~Surprise.get_pair_id
~Surprise.score
<file_sep>/include/graph.h
#include <iostream>
#include <vector>
class Neighbour{
public:
int _node;
double _w;
// constracter
Neighbour();
Neighbour(int node, double w);
// Getters
int get_node() const;
double get_w() const;
};
Neighbour::Neighbour(){
_node = -1;
_w = -1;
};
Neighbour::Neighbour(int node, double w){
_node = node;
_w = w;
};
// Getter -----------
int Neighbour::get_node() const{
return _node;
}
double Neighbour::get_w() const{
return _w;
}
using namespace std;
//typedef pair<int, double> Edge; // Edge
class Graph{
public:
vector<vector<Neighbour>> _neighbours;
// constracter
Graph();
// constracter
Graph(int num_nodes);
// Getters
int get_num_nodes() const;
int get_num_edges() const;
int degree(int nid) const;
double wdegree(int nid) const;
void get_weight(int nid, int j, int& nei, double& w) const;
vector<Neighbour> get_neighbours(int nid);
void compress();
void subgraph(vector<bool>& slice, Graph& Gs);
Neighbour get_kth_neighbour(int nid, int k) const;
void print() const;
vector<vector<double>> to_matrix() const;
void addEdge(int u, int v, double w);
};
Graph::Graph(){
vector<vector<Neighbour>> tmp(0, vector<Neighbour>(0));
_neighbours = tmp;
};
Graph::Graph(int num_nodes){
vector<vector<Neighbour>> tmp(num_nodes, vector<Neighbour>(0));
_neighbours = tmp;
};
// Getter -----------
int Graph::get_num_nodes() const{
return (int) _neighbours.size();
}
int Graph::get_num_edges() const{
int N = get_num_nodes();
int M = 0;
for (int i = 0; i < N; i++) {
int sz = degree(i);
M+=sz;
}
return M/2;
}
// get the id and weight of the jth neighbour of node nid
void Graph::get_weight(int nid, int j, int& nei, double& w) const{
nei = _neighbours[nid][j].get_node();
w = _neighbours[nid][j].get_w();
}
// get neigubouring nodes
vector<Neighbour> Graph::get_neighbours(int nid){
return _neighbours[nid];
}
// get weighted degree
double Graph::wdegree(int nid) const{
int sz = (int)_neighbours[nid].size();
double deg = 0;
for (int j = 0; j < sz; j++) {
deg+= _neighbours[nid][j].get_w();
}
return deg;
}
// get degree
int Graph::degree(int nid) const{
return (int)_neighbours[nid].size();
}
Neighbour Graph::get_kth_neighbour(int nid, int k) const{
return _neighbours[nid][k];
}
// add
void Graph::addEdge(int u, int v, double w){
int sz = (int)_neighbours.size();
while( (sz <=u) ){
vector<Neighbour> tmp(0);
_neighbours.push_back(tmp);
sz++;
}
Neighbour ed1(v, w);
_neighbours[u].push_back(ed1);
/*
if(u==v){
Neighbour ed1(v, w);
_neighbours[u].push_back(ed1);
}else{
Neighbour ed1(v, w);
_neighbours[u].push_back(ed1);
Neighbour ed2(u, w);
_neighbours[v].push_back(ed2);
}*/
}
// add
void Graph::print() const{
int N = get_num_nodes();
for(int i =0; i < N;i++){
int sz = (int)_neighbours[i].size();
for(int j =0; j < sz;j++){
cout<<i<<" "<<_neighbours[i][j].get_node()<<" "<<_neighbours[i][j].get_w()<<endl;
}
}
}
// add
vector<vector<double>> Graph::to_matrix() const{
int N = get_num_nodes();
vector<vector<double>> M(N, vector<double>(N, 0));
for(int i =0; i < N;i++){
for(auto nd : _neighbours[i]){
M[i][nd.get_node()] = nd.get_w();
}
}
return M;
}
// merge multiple-edges with a single weighted edge
void Graph::compress(){
int N = get_num_nodes();
// copy
vector<vector<Neighbour>> prev_neighbours = _neighbours;
// initialise _neighbours
for(int i = 0; i < N; i++){
_neighbours[i].clear();
}
_neighbours.clear();
vector<vector<Neighbour>> tmp(N, vector<Neighbour>(0));
_neighbours = tmp;
for(int i = 0; i < N; i ++){
map<int, double> myMap;
for(auto nd: prev_neighbours[i]){
int nei = nd.get_node();
double w = nd.get_w();
if ( !myMap.insert( make_pair( nei, w ) ).second ) {
myMap[nei]+=w;
}
}
for (const auto & p : myMap) {
addEdge(i, p.first, p.second);
}
}
}
void Graph::subgraph(vector<bool>& slice, Graph& Gs){
int N = get_num_nodes();
int Ns = 0;
vector<int> node2id(N,0);
int idx = 0;
for(int i = 0; i < N; i ++){
if(slice[i]){
node2id[i] = idx;
Ns++;
idx+=1;
}
}
Graph tt(Ns);
Gs = tt;
for(int i =0; i < N;i++){
for(auto nd: _neighbours[i]){
int nei = nd.get_node();
double w = nd.get_node();;
if(slice[i] & slice[nei]){
Gs.addEdge(node2id[i], node2id[nei], w);
}
}
}
}
<file_sep>/src/_cpalgorithm_py.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <algorithm>
#include <iostream>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
/* -----------------------------------------------------
Write the algorithms to be included in the prackage here
----------------------------------------------------- */
#ifndef BE_ALGORITHM
#define BE_ALGORITHM
#include "bealgorithm.h"
#endif
#include <minres.h>
#include <km_config.h>
#include <km_modmat.h>
#include <km_er.h>
#include <rombach_label_switching.h>
#include <sbm.h>
#include <divisive.h>
using namespace std;
namespace py = pybind11;
void readEdgeTable(py::array_t<int> edges_array_t, py::array_t<double> w_array_t, Graph& G)
{
vector<int> edgeList;
vector<double> wList;
int N = 0;
auto edges = edges_array_t.data();
auto r = edges_array_t.request();
int M = (int) r.shape[0];
auto ws = w_array_t.data();
for(int i =0; i< M; i++){
int sid = edges[2*i];
int did = edges[2*i + 1];
double w = ws[i];
if (sid == did)
continue;
if (N < sid)
N = sid;
if (N < did)
N = did;
edgeList.push_back(sid);
edgeList.push_back(did);
wList.push_back(w);
}
N = N + 1;
Graph tmp(N);
G = tmp;
int wid = 0;
int edgeListsize = (int) edgeList.size();
for (int i = 0; i < edgeListsize; i += 2) {
int sid = edgeList[i];
int did = edgeList[i + 1];
double w = wList[wid];
G.addEdge(sid, did, w);
G.addEdge(did, sid, w);
wid++;
}
G.compress();
}
void readCPResult(py::array_t<int> c_array_t, py::array_t<double> x_array_t, vector<int>& c, vector<double>& x)
{
auto _c = c_array_t.data();
auto _x = x_array_t.data();
auto r = c_array_t.request();
int N = (int) r.shape[0];
vector<int> cList(N, 0);
vector<double> xList(N, 0.0);
for(int i =0; i< N; i++){
cList[i] = _c[i];
xList[i] = _x[i];
}
c = cList;
x = xList;
}
void packResults(vector<int>&c, vector<double>& x, double& Q, vector<double>&q, py::list& results)
{
int N = (int)c.size();
py::array_t<double> cids_array_t(N);
auto cids = cids_array_t.mutable_data();
py::array_t<double> xs_array_t(N);
auto xs = xs_array_t.mutable_data();
for(int i = 0; i < N; i++){
cids[i] = c[i];
xs[i] = x[i];
}
int K = (int) q.size();
py::array_t<double> qs_array_t(K);
auto qs = qs_array_t.mutable_data();
for(int i = 0; i < K; i++){
qs[i] = q[i];
}
py::array_t<double> Qs_array_t(1);
auto Qs = Qs_array_t.mutable_data();
Qs[0] = Q;
//py::list results(3);
results[0] = cids_array_t;
results[1] = xs_array_t;
results[2] = Qs_array_t;
results[3] = qs_array_t;
}
void pack_Q(double _Q, vector<double>& _q, py::list& results)
{
int K = (int) _q.size();
py::array_t<double> q_array_t(K);
auto q = q_array_t.mutable_data();
py::array_t<double> Q_array_t(1);
auto Q = Q_array_t.mutable_data();
Q[0] = _Q;
for(int i = 0; i < K; i++){
q[i] = _q[i];
}
results[0] = Q_array_t;
results[1] = q_array_t;
}
/* Divisive algorithm*/
py::list detect_divisive(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
Divisive dv = Divisive(num_of_runs);
dv.detect(G);
double Q = 0;
vector<double>q;
dv._calc_Q(G, Q, q);
vector<int> c = dv.get_c();
vector<double> x = dv.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* BE algorithm*/
py::list detect_be(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
BEAlgorithm be = BEAlgorithm(num_of_runs);
be.detect(G);
double Q = 0;
vector<double>q;
be._calc_Q(G, Q, q);
vector<int> c = be.get_c();
vector<double> x = be.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* MINRES algorithm*/
py::list detect_minres(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
MINRES minres = MINRES();
minres.detect(G);
double Q = 0;
vector<double>q;
minres._calc_Q(G, Q, q);
vector<int> c = minres.get_c();
vector<double> x = minres.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* KM algorithm based on the configuration model */
py::list detect_config(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
KM_config km = KM_config(num_of_runs);
km.detect(G);
double Q = 0;
vector<double>q;
km._calc_Q(G, Q, q);
vector<int>c = km.get_c();
vector<double>x = km.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* KM algorithm based on the Erdos-Renyi random graph */
py::list detect_ER(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
KM_ER km = KM_ER(num_of_runs);
km.detect(G);
double Q = 0;
vector<double>q;
km._calc_Q(G, Q, q);
vector<int>c = km.get_c();
vector<double>x = km.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* KM algorithm based on an arbitary null models*/
py::list detect_modmat(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs){
Graph G(0);
readEdgeTable(edges, ws, G);
KM_modmat km = KM_modmat(num_of_runs);
km.detect(G);
double Q = 0;
vector<double>q;
km._calc_Q(G, Q, q);
vector<int> c = km.get_c();
vector<double> x = km.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* Rombach algorithm based on label switching algorithm*/
py::list detect_rombach_ls(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs, double alpha, double beta){
Graph G(0);
readEdgeTable(edges, ws, G);
Rombach_LS rls = Rombach_LS(num_of_runs, alpha, beta);
rls.detect(G);
double Q = 0;
vector<double>q;
rls._calc_Q(G, Q, q);
vector<int> c = rls.get_c();
vector<double> x = rls.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
/* SBM algorithm*/
py::list detect_sbm(py::array_t<int> edges, py::array_t<double> ws, int num_of_runs, double maxItNum, double tol){
Graph G(0);
readEdgeTable(edges, ws, G);
SBM sbm= SBM(maxItNum, tol);
sbm.detect(G);
double Q = 0;
vector<double>q;
sbm._calc_Q(G, Q, q);
vector<int> c = sbm.get_c();
vector<double> x = sbm.get_x();
py::list results(4);
packResults(c, x, Q, q, results);
return results;
}
py::list calc_Q_divisive(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
Divisive dv = Divisive();
double Q = -1;
vector<double>q;
dv.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_config(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
KM_config km = KM_config();
double Q = -1;
vector<double>q;
km.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_ER(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
KM_ER km = KM_ER();
double Q = -1;
vector<double>q;
km.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_minres(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
MINRES km = MINRES();
double Q = -1;
vector<double>q;
km.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_be(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
BEAlgorithm be = BEAlgorithm();
double Q = -1;
vector<double>q;
be.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_modmat(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
KM_modmat km = KM_modmat();
double Q = -1;
vector<double>q;
km.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_rombach(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
Rombach_LS rls = Rombach_LS();
double Q = -1;
vector<double>q;
rls.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
py::list calc_Q_sbm(py::array_t<int> edges, py::array_t<double> ws, py::array_t<int> _c, py::array_t<double> _x){
vector<int> c;
vector<double> x;
Graph G(0);
readEdgeTable(edges, ws, G);
readCPResult(_c, _x, c, x);
SBM sbm = SBM();
double Q = -1;
vector<double>q;
sbm.calc_Q(G, c, x, Q, q);
py::list results(2);
pack_Q(Q, q, results);
return results;
}
PYBIND11_MODULE(_cpalgorithm, m){
m.doc() = "Core-periphery detection in networks";
// CP detection algorithm
m.def("detect_be", &detect_be, "Borgatti-Everett algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
m.def("detect_minres", &detect_minres, "MINRES algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
m.def("detect_config", &detect_config, "Use the configuration model as null models",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
m.def("detect_ER", &detect_ER, "KM algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
m.def("detect_modmat", &detect_modmat, "Use the user-provided modularity matrix",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
m.def("detect_rombach_ls", &detect_rombach_ls, "Rombach's continuous core-periphery detection algorithm ",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10,
py::arg("alpha") = 0.5,
py::arg("beta") = 0.8
);
m.def("detect_sbm", &detect_sbm, "Stochastic block model",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10,
py::arg("maxItNum") = 10,
py::arg("tol") = 1e-5
);
m.def("detect_divisive", &detect_divisive, "Divisive algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("num_of_runs") = 10
);
// Quality functions
m.def("calc_Q_be", &calc_Q_be, "Borgatti-Everett algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_minres", &calc_Q_minres, "MINRES algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_config", &calc_Q_config, "Use the configuration model as null models",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_ER", &calc_Q_ER, "Use the Erdos Renyi random graph as null models",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_modmat", &calc_Q_modmat, "Use the user-provided modularity matrix",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_rombach", &calc_Q_rombach, "Quality function for rombach's algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_sbm", &calc_Q_sbm, "Quality function for the Stochastic block model",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
m.def("calc_Q_divisive", &calc_Q_divisive, "Quality function for the Divisive algorithm",
py::arg("edges"),
py::arg("ws"),
py::arg("c"),
py::arg("x")
);
}
<file_sep>/docs/generated/cpalgorithm.LowRankCore.rst
cpalgorithm.LowRankCore
=======================
.. currentmodule:: cpalgorithm
.. autoclass:: LowRankCore
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~LowRankCore.__init__
~LowRankCore.detect
~LowRankCore.get_coreness
~LowRankCore.get_pair_id
~LowRankCore.score
<file_sep>/docs/generated/cpalgorithm.BE.rst
cpalgorithm.BE
==============
.. currentmodule:: cpalgorithm
.. autoclass:: BE
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~BE.__init__
~BE.detect
~BE.get_coreness
~BE.get_pair_id
~BE.score
<file_sep>/include/minres.h
/*
*
* Header file of the MINRES algorithm
*
*
* Please do not distribute without contacting the authors.
*
* AUTHOR - <NAME>
*
* DATE - 04 July 2018
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
class MINRES: public CPAlgorithm{
public:
// Constructor
MINRES();
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
private:
vector<int> _sortIndex(const vector<int>& Qs);
};
/*-----------------------------
Constructor
-----------------------------*/
MINRES::MINRES():CPAlgorithm(){
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void MINRES::detect(const Graph& G){
int N = G.get_num_nodes();
double M = 0.0;
std::vector<int> deg(N, 0);
for( int i = 0;i < N;i++ ) {
deg[i] = G.degree(i);
M +=deg[i];
}
vector<int> ord = _sortIndex(deg);
double Z = M;
double Zbest = numeric_limits<double>::max();
int kbest = 0;
for(int k = 0;k<N;k++){
Z = Z + k - 1 - deg[ ord[k] ];
if(Z < Zbest){
kbest = k;
Zbest = Z;
}
}
// set
vector<double> tmp2(N, 0.0);
for(int k = 0;k<=kbest;k++){
tmp2[ ord[k] ] = 1.0;
}
_x = tmp2;
// set
vector<int> tmp(N,0);
_c = tmp;
calc_Q(G, _c, _x, _Q, _q);
}
void MINRES::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
Q = 0.0;
double mcc=0;
double mpp = 0;
double ncc = 0;
int N = G.get_num_nodes();
for(int i = 0; i < N; i++){
int sz = G.degree(i);
for(int j = 0; j < sz; j++){
int nei = -1; double w = -1;
G.get_weight(i, j, nei, w);
mcc+=x[i] * x[j];
mpp+= (1-x[i]) * (1- x[j]);
}
ncc+=x[i];
}
//(ncc * ncc - mcc) number of absent edges in core
//(mpp) number of present edges in periphery
Q = (ncc * ncc - mcc) + mpp;
Q = -Q;
vector<double> tmp(1, Q);
q = tmp;
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
vector<int> MINRES::_sortIndex(const vector<int>& data){
vector<int> index((int)data.size(), 0);
for (int i = 0 ; i != index.size() ; i++) {
index[i] = i;
}
sort(index.begin(), index.end(),
[&](const int& a, const int& b) {
return (data[a] > data[b]);
}
);
return index;
}
<file_sep>/docs/generated/cpalgorithm.MINRES.rst
cpalgorithm.MINRES
==================
.. currentmodule:: cpalgorithm
.. autoclass:: MINRES
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~MINRES.__init__
~MINRES.detect
~MINRES.get_coreness
~MINRES.get_pair_id
~MINRES.score
<file_sep>/docs/Tutorial.rst
=======================
Tutorial
=======================
Preparing a graph
-----------------
All algorithms take NetworkX graph object as input.
An empty graph is created by
.. code-block:: python
import networkx as nx
G = nx.Graph()
Alternatively, one can create a graph object from a file "example.csv":
.. code-block:: python
import networkx as nx
G = nx.read_edgelist("example.csv")
.. note::
The "example.csv" is a space-separated file consisting of two columns, where
each row corresponds to a pair of adjacent nodes connected by an edge. See :ref:`examples`.
See details in `NetworkX documentation <https://networkx.github.io/documentation/stable/>`_.
Core-periphery detection
------------------------
.. role:: python(code)
:language: python
We demonstrate the KM-config algorithm, whose usage is basically the same with other algorithms.
First, create an object called KM_config:
.. code-block:: python
import cpalgorithm as cp
import networkx as nx
algorithm = cp.KM_config()
Load the karate club network:
.. code-block:: python
G = nx.karate_club_graph() # loading the karate club network
Then, pass the graph to :python:`detect()` method:
.. code-block:: python
algorithm.detect(G)
Retrieve the results by
.. code-block:: python
c = algorithm.get_pair_id()
x = algorithm.get_coreness()
:python:`c` and :python:`x` are python dict objects.
Dictionary :python:`c` takes keys representing the node names, and integer values representing the IDs of the core-periphery pair to which to the node belongs.
For example,
.. code-block:: python
c = {NodeA: 0, NodeB: 1, NodeC: 0, NodeD: 2 ...,
means that NodeA and NodeC belong to core-periphery pair 0, NoedB belongs to core-periphery pair 1 and NodeD belongs to core-periphery pair 2.
Dictionary :python:`x` takes keys representing the node names, and float values representing the coreness values ranging between 0 and 1.
Coreness value 1 and 0 indicates a core or a peripheral node, respectively. For example,
.. code-block:: python
x = {NodeA: 1, NodeB: 1, NodeC: 0, NodeD: 1 ...,
means NodeA, NodeB NodeD are core nodes and NodeC is a peripheral node.
Note that some algorithms set coreness values between 0 and 1, which indicates the extent to which the node belongs to the core.
One can use other algorithms in the same way.
For example, one needs to modify one line to use the Borgatti-Everet algorithm (e.g, cp.BE()).
.. code-block:: python
import cpalgorithm as cp
import networkx as nx
algorithm = cp.BE()
#algorithm = cp.KM_config()
G = nx.karate_club_graph()
algorithm.detect(G)
c = algorithm.get_pair_id()
x = algorithm.get_coreness()
The available algorithms are listed in :ref:`reference`.
Statistical test
----------------
Statistical test is essential because the algorithms return something even if you give random networks.
In order to confirm that the something is indeed core-periphery structure, one needs to carry out statistical test.
cpalgorithm provides a statistical test to examine the significance of individual core-periphery pairs.
The statistical test judges each detected core-periphery pair as significant if it is not explained by the degree of each node (i.e., hub and non-hub nodes largely correspond to core and peripheral nodes, respectively). Otherwise, it judges a core-periphery pair as insignificant.
To carry out the statistical write, write
.. code-block:: python
sig_c, sig_x, significant, p_values = cp.qstest(c, x, G, algorithm)
where :python:`significant` and :python:`p_values` are list objects.
`sig_c` and `sig_x` are dict objects in which the insignificant core-periphery pairs are excluded.
List :python:`significant` is a boolean list, where :python:`significant[c]=True` or :python:`significant[c]=False` flag indicates that the cth core-periphery pair is significant or insignificant, respectively, e.g.,
.. code-block:: python
significant = [True, False, False, True, ...,
List :python:`p_values` is a float list, where :python:`p_values[c]` is the p-value of the cth core-periphery pair under the configuration model, e.g.,
.. code-block:: python
p_values = [0.00001, 0.587, 0.443, 0.0001, ...,
.. note::
The statistical test examines the significance of each core-periphery pair individually, which causes the multiple-comparisons problem.
To suppress the false positives, we adopt the e Šidák correction.
The default significance level is 0.05.
<file_sep>/cpalgorithm/__init__.py
# Release data
__author__ = "<NAME>"
from .CPAlgorithm import *
from .BE import *
from .MINRES import *
from .KM_config import *
from .KM_ER import *
from .KM_modmat import *
from .Surprise import *
from .qstest import *
from .Cucuringu import *
from .Rombach import *
from .Rossa import *
from .SBM import *
from .Divisive import *
#from cpalgorithm import *
<file_sep>/docs/index.rst
=======================
Overview of cpalgorithm
=======================
This is a Python toolbox containing various algorithms for detecting core-periphery structure in networks.
Core-periphery structure is a mesoscale structure of networks, where a core is a group of densely interconnected nodes, and a periphery is a group of sparsely interconnected nodes.
Core-periphery structure has been found in various empirical networks such as social networks, biological networks and transportation networks [1, 2].
In many of these empirical networks, the core and peripheral nodes often have practical roles.
For example, in social networks, core and peripheral nodes often correspond to leaders and followers [1] (e.g., imagine PIs and Ph.D students in collaboration networks).
Another example is airport networks, where core and peripheral nodes largely correspond to hub and regional airports [3].
Many seminal works on core-periphery structure concern networks composed of a single core and a single periphery [1, 2].
Recent studies focus on networks composed of multiple cores and peripheries as shown in Fig.~1, where two core-periphery pairs are detected by the KM-ER algorithm [3] in the political blog network [4].
.. figure:: fig/poliblog.png
:scale: 70 %
:align: center
**Figure 1**: Two core-periphery pairs in the political blog network detected by the KM-ER algorithm.
The filled or open circles indicate core nodes or peripheral nodes, respectively.
The colour of each circle indicates the core-periphery pair to which the node belongs.
The open circles with a grey border indicate nodes that do not belong to any core-periphery pair.
Despite its growing interests, there are few libraries for detecting core-periphery structure in networks.
This library intends to compensate the lack of tools and offers various algorithms, which myself use for `my studies on core-periphery structure <https://scholar.google.com/citations?user=IyWt4R4AAAAJ&hl=en>`_.
References
----------
- [1] <NAME>, <NAME>, <NAME>, and <NAME>, `Journal of Complex Networks, 1, 93 (2013) <https://doi.org/10.1093/comnet/cnt016>`_
- [2] <NAME>, <NAME>, <NAME>, <NAME>, `SIAM Review, 59, 619-646 (2017) <https://doi.org/10.1137/17M1130046>`_
- [3] <NAME> and <NAME>, `Physical Review E, 96, 052313 (2017) <https://doi.org/10.1103/PhysRevE.96.052313>`_
- [4] <NAME> and <NAME>, `in Proceedings of the 3rd International Workshop on Link Discovery, 36–43 (ACM, New York, USA, 2005) <https://doi.org/10.1145/1134271.1134277>`_
.. toctree::
:maxdepth: 2
:caption: Contents:
:glob:
Installation
Tutorial
Reference
Examples
FAQ/FAQ
Contact
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>/cpalgorithm/qstest.py
import numpy as np
import networkx as nx
import copy
import multiprocessing as mp
from scipy.stats import norm
def sz_n(network, c, x):
return np.bincount(list(c.values())).tolist()
def sz_degree(network, c, x):
K = max(c.values())+1
w = [0 for i in range(K)]
for key, val in c.items():
w[val]+=network.degree(key)
return w
def config_model(G):
deg = [d[1] for d in G.degree()]
return nx.configuration_model(deg)
def erdos_renyi(G):
n = G.number_of_nodes()
p = nx.density(G)
return nx.fast_gnp_random_graph(n, p)
def qstest(pair_id, coreness, G, cpa, significance_level=0.05, null_model = config_model, sfunc = sz_n, num_of_thread = 4, num_of_rand_net = 500, q_tilde = [], s_tilde = []):
"""(q,s)-test for core-periphery structure.
This function computes the significance of individual core-periphery pairs using either the Erdos-Renyi or the configuration model as the null model.
Parameters
----------
pair_id : dict
keys and values of which are node names and IDs of core-periphery pairs, respectively.
coreness : dict
keys and values of which are node names and coreness, respectively.
G : NetworkX graph object
cpa : CPAlgorithm class object
Core-periphery detection algorithm
significance_level : float
Significance level (optional, default 0.5)
null_model : function
Null model for generating randomised networks.
Provide either config_model or erdos_renyi (optional, default config_model).
One can use another null models.
Specifically, one needs to define a function taking NetworkX graph object as input and randomised network as its output.
Then, one gives the defined function, say myfunc, to qstest by null_model=myfunc.
sfunc : function
Size function (optional, default sz_n)
In the (q,s)--test, one is required to provide a function for measuring the size of an individual core-periphery pair. By default, this function is the number of nodes in the core-periphery pair (i.e., sz_n). One can set sz_degree, which measures the size as the sum of the degree of nodes belonging to the core-periphery pair.
num_of_thread : function
Number of thread (optional, default 4)
The (q,s)--test uses multiple threads to compute the significance.
num_of_rand_net : int
Number of randomised networks (optional, default 500)
Returns
-------
sig_pair_id : dict
keys and values of which are node names and IDs of core-periphery pairs, respectively. If nodes belong to insignificant core-periphery pair, then the values are None.
sig_coreness : dict
significance[i] = True or significance[i] = False indicates core-periphery pair i is significant or insignificant, respectively. If nodes belong to insignificant core-periphery pair, then the values are None.
significance : list
significance[i] = True or significance[i] = False indicates core-periphery pair i is significant or insignificant, respectively.
p_values : list
p_values[i] is the p-value of core-periphery pair i.
Examples
--------
Detect core-periphery pairs in the karate club network.
>>> import cpalgorithm as cpa
>>> km = cpa.KM_config()
>>> km.detect(G)
>>> pair_id = km.get_pair_id()
>>> coreness = km.get_coreness()
Examine the significance of each core-periphery pair using the configuration model:
>>> sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, km)
or
>>> sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, km, null_model=config_model)
Examine the significance of each core-periphery pair using the Erdos-Renyi random graph:
>>> sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, km, null_model=erdos_renyi)
.. rubric:: Reference
<NAME> and <NAME>.
A generalised significance test for individual communities in networks.
Scientific Reports, 8:7351 (2018)
"""
q = np.array(cpa.score(G, pair_id, coreness), dtype = np.float)
s = np.array(sfunc(G, pair_id, coreness) , dtype = np.float)
C = len(q)
alpha_corrected = 1.0 - (1.0 - significance_level) ** (1.0 / float(C))
if len(q_tilde) == 0:
q_tilde = []
s_tilde = []
if num_of_thread == 1:
q_tilde, s_tilde = draw_qs_samples(G, sfunc, cpa, null_model, num_of_rand_net)
else:
private_args = [(G, sfunc, cpa, null_model, int(num_of_rand_net / num_of_thread) + 1) for i in range(num_of_thread)]
pool = mp.Pool(num_of_thread)
qs_tilde = pool.map(wrapper_draw_qs_samples, private_args)
for i in range(num_of_thread):
q_tilde += qs_tilde[i][0]
s_tilde += qs_tilde[i][1]
q_tilde = np.array(q_tilde, dtype = np.float)
s_tilde = np.array(s_tilde, dtype = np.float)
q_ave = np.mean(q_tilde)
s_ave = np.mean(s_tilde)
q_std = np.std(q_tilde, ddof = 1)
s_std = np.std(s_tilde, ddof = 1)
if (s_std <= 1e-30) or (q_std <= 1e-30):
gamma = 0.0
s_std = 1e-20
else:
gamma = np.corrcoef(q_tilde, s_tilde)[0, 1]
h = float(len(q_tilde)) ** (- 1.0 / 6.0)
p_values = [1.0] * C
significant = [False] * C
cidx = 0
cid2newcid = - np.ones(C)
for cid in range(C):
if (s_std <= 1e-30) or (q_std <= 1e-30):
continue
w = np.exp(- ( (s[cid] - s_tilde) / (np.sqrt(2.0) * h * s_std) ) ** 2)
cd = norm.cdf( ( (q[cid] - q_tilde) / (h * q_std) - gamma * (s[cid] - s_tilde) / (h * s_std) ) / np.sqrt(1.0 - gamma * gamma) )
denom = sum(w)
if denom <= 1e-30:
continue
p_values[cid] = 1.0 - (sum( w * cd ) / denom)
significant[cid] = p_values[cid] <= alpha_corrected
if significant[cid]:
cid2newcid[cid] = cidx
cidx+=1
sig_pair_id = copy.deepcopy(pair_id)
sig_coreness = copy.deepcopy(coreness)
for k, v in sig_pair_id.items():
if significant[v]:
sig_pair_id[k]=cid2newcid[ pair_id[k] ]
else:
sig_pair_id[k]=None
sig_coreness[k]=None
return sig_pair_id, sig_coreness, significant, p_values
# Private function for qstest
def draw_qs_samples(G, sfunc, cpa, null_model, num_of_rand_net):
#deg = [x[1] for x in G.degree()]
q_rand = []
s_rand = []
for i in range(num_of_rand_net):
Gr = null_model(G)
cpa.detect(Gr)
q_rand = q_rand + cpa.score()
s_rand = s_rand + sfunc(Gr, cpa.get_pair_id(), cpa.get_coreness())
return q_rand, s_rand
# Private function for qstest
def wrapper_draw_qs_samples(args):
return draw_qs_samples(*args)
<file_sep>/docs/FAQ/FAQ.rst
.. _faq:
##########################
Frequently Asked Questions
##########################
.. toctree::
:maxdepth: 1
:glob:
Failed_to_install
Program_is_too_slow
Any_other_algorithms
<file_sep>/docs/FAQ/Program_is_too_slow.rst
.. _program_is_too_slow:
.. role:: python(code)
:language: python
############################
My program is too slow. Why?
############################
cpalgorithm can be slow for some reasons and here is the workaround.
=====================
Combine multi-edges
=====================
If there are multiple edges between the same pair of nodes in your neworkx graph object :python:`G`,
consider aggregating the multiple edges into one edge, that is to replace the multiple edges with a single edge having a weight, where the weight indicates the number of edges (or the sum of the weight over the multiple edges) between the pair of nodes.
This can be done by
.. code-block:: python
Gnew = nx.Graph()
for u,v,data in G.edges(data=True):
w = data['weight'] if 'weight' in data else 1.0
if Gnew.has_edge(u,v):
Gnew[u][v]['weight'] += w
else:
Gnew.add_edge(u, v, weight=w)
where :python:`G` is the network containing multi-edges, and :python:`Gnew` is the network without multiple edges.
=================
Shorten node name
=================
cpalgorithm internally converts nodes' names, which can be string or number, into unique integers.
This process can be slow if the nodes' names are long.
One can check the nodes' names by
.. code-block:: python
G.nodes()
One can reduce the computational time by shortening the name of each node, e.g., integers.
======================
Use parallel computing
======================
Some algorithms provide different results on different runs.
cpalgorithm runs such algorithms several times with different random seeds.
Then, it chooses the one yielding the largest quality value.
If we run the algorithm in parallel, then computational time would be reduced.
Here is an example of how to do this:
.. code-block:: python
:linenos:
import networkx as nx
import cpalgorithm as cp
import numpy as np
from multiprocessing import Pool
# A function for reducing computation time in algorithm using parallel computing
def par_detect_cp(num_of_cores, num_runs = 10):
pool = Pool(num_of_cores)
results = pool.map(_detect_cp, list(range(num_runs)))
algorithm = results[np.argmax(list(map(lambda x : sum(x.score()), results)))]
pool.close()
return algorithm
# This is an internal function of detect_cp
def _detect_cp(_rubbish):
alg = cp.KM_config(num_runs = 1)
alg.detect(G)
return alg
# Construct Graph object
global G # Declare the graph object as a global variable to save memory
G = nx.karate_club_graph()
algorithm = par_detect_cp(num_of_cores = 10, num_runs=10)
c = algorithm.get_pair_id()
x = algorithm.get_coreness()
print('Name\tPairID\tCoreness')
for key, value in sorted(c.items(), key=lambda x: x[1]):
print('%s\t%d\t%f' %(key, c[key], x[key]))
In this example, the networkx graph object is constructed in lines 22 and 23.
The algorithm is set in line 16.
In line 25, we specify the number of cores by :python:`num_cores=10`.
:python:`num_runs` is the number of times that cpalglrithm runs the algorithm.
Default is :python:`num_runs=10`. :python:`num_cores` should be equal or smaller than :python:`num_runs`.
<file_sep>/cpalgorithm/SBM.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class SBM(CPAlgorithm):
"""Stochastic block model.
Core-periphery detection algorithm based on stochastic block models [1]
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> sbm = cpa.SBM()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> sbm.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = sbm.get_pair_id()
Retrieve the coreness:
>>> coreness = sbm.get_coreness()
.. note::
This algorithm accepts unweighted and undirected networks only.
Also, the algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
This algorithm is stochastic, i.e., one would obtain different results at each run.
.. rubric:: Reference
[1] <NAME>, <NAME>, and <NAME>. Identification of core-periphery structure in networks. Phys. Rev. E., 91(3):032803, 2015.
"""
def __init__(self):
return
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> sbm = cp.SBM()
>>> sbm.detect(G)
"""
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_sbm(edges=node_pairs, ws=w, num_of_runs = 1)
N = len(id2node)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_sbm(edges=node_pairs, ws=w, c=_c, x=_x)
return result[1].tolist()
<file_sep>/makefile
# Makefile
.PHONY: all
#CC := gcc
CC := g++
#CFLAGS := -O3 -std=c++11 # use this option in case openmp does not work
CFLAGS := -O3 -std=c++11 -fopenmp -Wall
all: km_config
km_config:src/* cpalgorithm/*
sudo rm -rf build cpalgorithm.egg* && sudo python3 setup.py build install
.PHONY: clean
clean:
$(RM) km_config
<file_sep>/docs/generated/cpalgorithm.LapCore.rst
cpalgorithm.LapCore
===================
.. currentmodule:: cpalgorithm
.. autoclass:: LapCore
.. automethod:: __init__
.. rubric:: Methods
.. autosummary::
~LapCore.__init__
~LapCore.detect
~LapCore.get_coreness
~LapCore.get_pair_id
~LapCore.score
<file_sep>/include/bealgorithm.h
/*
*
* Header file of the BE algorithm
*
*
* Please do not distribute without contacting the authors.
*
* AUTHOR - <NAME>
*
* DATE - 04 July 2018
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
#include <math.h>
class BEAlgorithm: public CPAlgorithm{
public:
// Constructor
BEAlgorithm();
BEAlgorithm(int num_runs);
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected: // function needed to be implemented
int _num_runs;
void _detect_(const Graph& G, vector<double>& x, mt19937_64& mtrnd);
};
/*-----------------------------
Constructor
-----------------------------*/
BEAlgorithm::BEAlgorithm(int num_runs):CPAlgorithm(){
BEAlgorithm();
_num_runs = num_runs;
};
BEAlgorithm::BEAlgorithm(): CPAlgorithm(){
_num_runs = 10;
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void BEAlgorithm::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
int N = G.get_num_nodes();
double M = 0.0;
double pa = 0;
double pb = 0;
double nc = 0;
double mcc = 0;
for( int i = 0;i < N;i++ ) {
nc+=x[i];
int sz = G.degree(i);
for( int k = 0; k < sz; k++ ) {
Neighbour nei = G.get_kth_neighbour(i, k);
int j = nei.get_node();
double w = nei.get_w();
mcc+=w * (x[i]+x[j] - x[i] * x[j]);
M++;
}
}
mcc = mcc/2;
M = M /2;
double M_b = (double)(nc * (nc-1) + 2 * nc * (N -nc))/2;
pa = M / (double)(N * (N-1)/2);
pb = M_b / (double)(N * (N-1)/2);
Q = ((double)mcc - pa * M_b ) / (sqrt(pa * (1-pa)) * sqrt(pb * (1-pb)) + 1e-30);
Q = Q / (double)(N * (N-1)/2);
if(Q > 1) Q = 1;
if(Q < -1) Q = -1;
vector<double> qtmp(1,Q);
q= qtmp;
}
void BEAlgorithm::detect(const Graph& G){
double Q = -1;
int N = G.get_num_nodes();
for (int i = 0; i < _num_runs; i++) {
vector<int> ci(N, 0);
vector<double> xi;
vector<double> qi;
double Qi = 0.0;
_detect_(G, xi, _mtrnd);
calc_Q(G, ci, xi, Qi, qi);
if (Qi > Q) {
_c = ci;
_x = xi;
_Q = Qi;
_q = qi;
}
}
}
void BEAlgorithm::_detect_(const Graph& G, vector<double>& x, mt19937_64& mtrnd){
// --------------------------------
// Initialise _x randomly
// --------------------------------
int N = G.get_num_nodes();
double M = G.get_num_edges();
double p = M / (double)(N * (N - 1) / 2 );
vector<double> tmp(N, 0.0);
x = tmp;
uniform_real_distribution<double> dis(0.0, 1.0);
double Nperi = N;
for(int i = 0;i<N; i++){
if(dis(mtrnd) < 0.5) {
x[i] = 1;
Nperi-=1;
}
}
// --------------------------------
// Maximise the Borgatti-Everett quality function
// --------------------------------
std::vector<double>xt = x;
std::vector<double>xbest(N, 0.0);
std::vector<bool>fixed(N, false);
vector<double> Dperi(N, 0);
for( int j = 0;j < N;j++){
std::fill(fixed.begin(),fixed.end(),false);
Nperi = 0.0;
double numer = 0.0;
for( int i = 0; i < N;i ++ ){
Nperi+=(1-x[i]);
Dperi[i] = 0;
int sz = G.degree(i);
for( int k = 0; k < sz;k ++ ){
int nei = G.get_kth_neighbour(i, k).get_node();
Dperi[i]+=1-x[nei];
numer+= x[i] + x[nei] - x[i] * x[nei];
}
}
numer = numer/2.0 -p*( (double)(N*(N-1.0))/2.0 - (double)Nperi*((double) Nperi-1.0)/2.0 );
double pb = 1 - (double)Nperi*(Nperi-1)/(double)(N*(N-1));
double Qold = numer / sqrt(pb*(1-pb));
double dQ = 0;
double dQmax = -1 * std::numeric_limits<double>::max();
int nid = 0;
for( int i = 0;i < N;i++){
double qmax = -1 * std::numeric_limits<double>::max();
// select a node of which we update the label
double numertmp = numer;
for(int k =0;k<N;k++){
if( fixed[k] ) continue;
double dnumer = (Dperi[k]- p * (Nperi-!!(1-xt[k])) ) * (2*(1-xt[k])-1);
double newNperi = Nperi + 2*xt[k]-1;
double pb = 1.0- (newNperi*(newNperi-1.0)) / (N*(N-1.0));
double q = (numer + dnumer) / sqrt(pb*(1-pb));
if( (qmax < q) & (pb*(1-pb)>0)){
nid = k;qmax = q;numertmp = numer + dnumer;
}
}
numer = numertmp;
Nperi+=2*xt[nid]-1;
int sz = G.degree(nid);
for(int k = 0;k<sz ;k++){
int neik = G.get_kth_neighbour(nid, k).get_node();
Dperi[ neik ]+=2*xt[nid]-1;
}
xt[ nid ] = 1-xt[ nid ];
dQ = dQ + qmax - Qold;
Qold = qmax;
//% Save the core-periphery pair if it attains the largest quality
if(dQmax < dQ){
xbest = xt;
dQmax = dQ;
}
//fixed( nid ) = true; % Fix the label of node nid
fixed[ nid ] = true; //% Fix the label of node nid
}
if (dQmax <= std::numeric_limits<double>::epsilon()){
break;
}
xt = xbest; x = xbest;
}
x = xbest;
}
<file_sep>/docs/FAQ/Any_other_algorithms.rst
=====================
Any other algorithms?
=====================
cpalgorithm mainly provides density-based core-periphery structure.
Other types of core-periphery structure such as transportation-based core-periphery structure is left for future update.
If you have a code for other algorithms and are willing to add it to this library, please contact the `developer <https://core-periphery-detection-in-networks.readthedocs.io/en/latest/Contact.html>`_.
<file_sep>/docs/_build/html/index.html
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overview of cpalgorithm — cpalgorithm 0.0.1 documentation</title>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within cpalgorithm 0.0.1 documentation"
href="_static/opensearch.xml"/>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/gallery.css" type="text/css" />
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Installation" href="Installation.html" />
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="#" class="icon icon-home"> cpalgorithm
</a>
<div class="version">
0.0.1
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="Installation.html">Installation</a></li>
<li class="toctree-l1"><a class="reference internal" href="Tutorial.html">Tutorial</a></li>
<li class="toctree-l1"><a class="reference internal" href="Reference.html">Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="Examples.html">Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="FAQ/FAQ.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="Contact.html">Contact</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="#">cpalgorithm</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="#">Docs</a> »</li>
<li>Overview of cpalgorithm</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="overview-of-cpalgorithm">
<h1>Overview of cpalgorithm<a class="headerlink" href="#overview-of-cpalgorithm" title="Permalink to this headline">¶</a></h1>
<p>This is a Python toolbox containing various algorithms for detecting core-periphery structure in networks.</p>
<p>Core-periphery structure is a mesoscale structure of networks, where a core is a group of densely interconnected nodes, and a periphery is a group of sparsely interconnected nodes.
Core-periphery structure has been found in various empirical networks such as social networks, biological networks and transportation networks [1, 2].
In many of these empirical networks, the core and peripheral nodes often have practical roles.
For example, in social networks, core and peripheral nodes often correspond to leaders and followers [1] (e.g., imagine PIs and Ph.D students in collaboration networks).
Another example is airport networks, where core and peripheral nodes largely correspond to hub and regional airports [3].</p>
<p>Many seminal works on core-periphery structure concern networks composed of a single core and a single periphery [1, 2].
Recent studies focus on networks composed of multiple cores and peripheries as shown in Fig.~1, where two core-periphery pairs are detected by the KM-ER algorithm [3] in the political blog network [4].</p>
<div class="figure align-center">
<a class="reference internal image-reference" href="_images/poliblog.png"><img alt="_images/poliblog.png" src="_images/poliblog.png" style="width: 338.79999999999995px; height: 379.4px;" /></a>
</div>
<p><strong>Figure 1</strong>: Two core-periphery pairs in the political blog network detected by the KM-ER algorithm.
The filled or open circles indicate core nodes or peripheral nodes, respectively.
The colour of each circle indicates the core-periphery pair to which the node belongs.
The open circles with a grey border indicate nodes that do not belong to any core-periphery pair.</p>
<p>Despite its growing interests, there are few libraries for detecting core-periphery structure in networks.
This library intends to compensate the lack of tools and offers various algorithms, which myself use for <a class="reference external" href="https://scholar.google.com/citations?user=IyWt4R4AAAAJ&hl=en">my studies on core-periphery structure</a>.</p>
<div class="section" id="references">
<h2>References<a class="headerlink" href="#references" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>[1] <NAME>, <NAME>, <NAME>, and <NAME>, <a class="reference external" href="https://doi.org/10.1093/comnet/cnt016">Journal of Complex Networks, 1, 93 (2013)</a></li>
<li>[2] <NAME>, <NAME>, <NAME>, <NAME>, <a class="reference external" href="https://doi.org/10.1137/17M1130046">SIAM Review, 59, 619-646 (2017)</a></li>
<li>[3] <NAME> and <NAME>, <a class="reference external" href="https://doi.org/10.1103/PhysRevE.96.052313">Physical Review E, 96, 052313 (2017)</a></li>
<li>[4] <NAME> and <NAME>, <a class="reference external" href="https://doi.org/10.1145/1134271.1134277">in Proceedings of the 3rd International Workshop on Link Discovery, 36–43 (ACM, New York, USA, 2005)</a></li>
</ul>
<div class="toctree-wrapper compound">
<p class="caption"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="Installation.html">Installation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="Installation.html#requirements">Requirements</a></li>
<li class="toctree-l2"><a class="reference internal" href="Installation.html#install">Install</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="Tutorial.html">Tutorial</a><ul>
<li class="toctree-l2"><a class="reference internal" href="Tutorial.html#preparing-a-graph">Preparing a graph</a></li>
<li class="toctree-l2"><a class="reference internal" href="Tutorial.html#core-periphery-detection">Core-periphery detection</a></li>
<li class="toctree-l2"><a class="reference internal" href="Tutorial.html#statistical-test">Statistical test</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="Reference.html">Reference</a><ul>
<li class="toctree-l2"><a class="reference internal" href="Reference.html#core-periphery-detection-algorithms">Core-periphery detection algorithms</a></li>
<li class="toctree-l2"><a class="reference internal" href="Reference.html#module-cpalgorithm">Statistical test</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="Examples.html">Examples</a><ul>
<li class="toctree-l2"><a class="reference internal" href="Examples.html#load-a-graph-from-a-list-of-edges">Load a graph from a list of edges</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="FAQ/FAQ.html">Frequently Asked Questions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="FAQ/Failed_to_install.html">Failed to install cpalgorithm</a></li>
<li class="toctree-l2"><a class="reference internal" href="FAQ/Program_is_too_slow.html">My program is too slow. Why?</a></li>
<li class="toctree-l2"><a class="reference internal" href="FAQ/Any_other_algorithms.html">Any other algorithms?</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="Contact.html">Contact</a></li>
</ul>
</div>
<div class="section" id="indices-and-tables">
<h3>Indices and tables<a class="headerlink" href="#indices-and-tables" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li><a class="reference internal" href="genindex.html"><span class="std std-ref">Index</span></a></li>
<li><a class="reference internal" href="py-modindex.html"><span class="std std-ref">Module Index</span></a></li>
<li><a class="reference internal" href="search.html"><span class="std std-ref">Search Page</span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="Installation.html" class="btn btn-neutral float-right" title="Installation" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2018-2019, <NAME>.
Last updated on Feb 24, 2019.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'0.0.1',
LANGUAGE:'None',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: false,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/copybutton.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html><file_sep>/docs/auto_examples/example.rst
.. note::
:class: sphx-glr-download-link-note
Click :ref:`here <sphx_glr_download_auto_examples_example.py>` to download the full example code
.. rst-class:: sphx-glr-example-title
.. _sphx_glr_auto_examples_example.py:
Detect core-periphery structure in empirical networks.
.. code-block:: python
import cpalgorithm as cp
import scipy.stats as stats
import networkx as nx
import cpalgorithm as cpa
import numpy as np
import sys
# load graph
G = nx.karate_club_graph()
G = G.to_undirected()
# load algorithm
alg = cpa.BE()
# Core-periphery detection
alg.detect(G)
print("core-periphery IDs")
print(alg.get_pair_id())
print("Coreness ")
print(alg.get_coreness())
**Total running time of the script:** ( 0 minutes 0.000 seconds)
.. _sphx_glr_download_auto_examples_example.py:
.. only :: html
.. container:: sphx-glr-footer
:class: sphx-glr-footer-example
.. container:: sphx-glr-download
:download:`Download Python source code: example.py <example.py>`
.. container:: sphx-glr-download
:download:`Download Jupyter notebook: example.ipynb <example.ipynb>`
.. only:: html
.. rst-class:: sphx-glr-signature
`Gallery generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
<file_sep>/docs/Installation.rst
############
Installation
############
.. role:: python(code)
:language: python
Requirements
------------
cpalgorithm is compatible with python 3.4 or newer.
You need to have the latest :python:`pip` (a package manager for Python) and one of the following compilers:
- Clang/LLVM 3.3 or newer (for Apple Xcode's clang, this is 5.0.0 or newer)
- GCC 4.8 or newer
- Microsoft Visual C++ Build Tools 2015 or newer
- Intel C++ compiler 17 or newer
- Cygwin/GCC (tested on 2.5.1)
Currently, cpalgorithm is tested on Ubuntu and CentOS.
Confirmed that cpalgorithm can also run on MacOS.
For Windows, cpalgorithm requires Visual C++ Build Tools 2015 or newer. To install, see `Windows Compilers <https://wiki.python.org/moin/WindowsCompilers/>`_.
cpalgorithm may not be compatible with conda.
Install
-------
Before installing cpalgorithm, install pybind11:
.. code-block:: bash
$ pip3 install pybind11
Then,
.. code-block:: bash
$ pip3 install cpalgorithm
If you don't have a root access, try :python:`--user` flag:
.. code-block:: bash
$ pip3 install --user cpalgorithm
You can upgrade a newer release by
.. code-block:: bash
$ pip3 install --upgrade cpalgorithm
<file_sep>/cpalgorithm/Rombach.py
import _cpalgorithm as _cp
from simanneal import Annealer
import random
from .CPAlgorithm import *
class SimAlg(Annealer):
def __init__(self, A, x, alpha, beta):
self.state=x
self.A = A
self.alpha = alpha
self.beta = beta
self.Tmax = 1
self.Tmin = 1e-8
self.steps = 10000
self.updates = 100
def move(self):
"""Swaps two nodes"""
a = random.randint(0, len(self.state) - 1)
b = random.randint(0, len(self.state) - 1)
self.state[[a,b]] = self.state[[b,a]]
def energy(self):
return self.eval(self.state)
def eval(self, od):
x = self.corevector(od, self.alpha, self.beta)
return -np.asscalar(np.dot(x.T * self.A, x)[0,0])
def corevector(self, x, alpha, beta):
N = len(x);
bn = np.floor(beta * N)
cx = (x<=bn).astype(int)
px = (x>bn).astype(int)
c = (1.0 - alpha) / (2.0 * bn) * x * cx + ((x * px - bn ) * (1.0 - alpha) / (2.0 * (N - bn)) + (1.0 + alpha) / 2.0) * px;
return np.asmatrix(np.reshape(c, (N,1)))
class Rombach(CPAlgorithm):
"""Rombach's algorithm for finding continuous core-periphery structure.
Parameters
----------
num_runs : int
Number of runs of the algorithm (optional, default: 1).
alpha : float
Sharpness of core-periphery boundary (optional, default: 0.5).
alpha=0 or alpha=1 gives the fuzziest or sharpest boundary, respectively.
beta : float
Fraction of peripheral nodes (optional, default: 0.8)
algorithm : str
Optimisation algorithm (optional, default: 'ls')
In the original paper [1], the authors adopted a simulated annealing to optimise the objective function, which is computationally demanding.
To mitigate the computational cost, a label switching algorithm is implemented in cpalgorithm.
One can choose either algorithm by specifying algorithm='ls' (i.e., label switching) or algorithm='sa' (i.e., simulated annealing).
.. note::
The parameters of the simulated annealing such as the initial temperature and cooling schedule are different from those used in the original paper [1].
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> rb = cpa.Rombach()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> rb.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = rb.get_pair_id()
Retrieve the coreness:
>>> coreness = rb.get_coreness()
.. note::
This algorithm can accept unweighted and weighted networks.
The algorithm assigns all nodes into the same core-periphery pair by construction, i.e., c[node_name] =0 for all node_name.
.. rubric:: Reference
[1] <NAME>, <NAME>, <NAME>, and <NAME>. Core-Periphery Structure in Networks (Revisited). SIAM Review, 59(3):619–646, 2017
"""
def __init__(self, num_runs = 10, alpha = 0.5, beta = 0.8, algorithm='ls'):
self.num_runs = num_runs
self.alpha = alpha
self.beta = beta
self.algorithm = algorithm
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> rb = cp.Rombach(algorithm='ls') # label switching algorithm
>>> rb.detect(G)
>>> rb = cp.Rombach(algorithm='sa') # simulated annealing
>>> rb.detect(G)
"""
Qbest = -100
cbest = 0
xbest = 0
qbest = 0
for i in range(self.num_runs):
if self.algorithm == 'ls':
self._label_switching(G, self.alpha, self.beta)
elif self.algorithm == 'sa':
self._simaneal(G, self.alpha, self.beta)
if Qbest < self.Q_:
Qbest = self.Q_
cbest = self.c_
xbest = self.x_
qbest = self.qs_
self.Q_ = Qbest
self.c_ = cbest
self.x_ = xbest
self.qs_ = qbest
def _label_switching(self, G, alpha, beta):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_rombach_ls(edges=node_pairs, ws=w, num_of_runs = 1, alpha = alpha, beta = beta)
N = len(node2id)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1]))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _simaneal(self, G, alpha, beta):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
A = nx.to_scipy_sparse_matrix(G)
N = nx.number_of_nodes(G)
nodes = list(range(N))
random.shuffle(nodes)
nodes = np.array(nodes)
sa = SimAlg(A, nodes, self.alpha, self.beta)
od, self.Q_ = sa.anneal()
self.Q_ *= -1
x = sa.corevector(od, self.alpha, self.beta)
x = x.T.tolist()[0]
self.c_ = dict(zip( [id2node[i] for i in range(N)], np.zeros(N)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], x))
self.qs_ = [-sa.eval(od)]
def _score(self, G, c, x):
A = nx.to_scipy_sparse_matrix(G)
N = nx.number_of_nodes(G)
xx = np.zeros((N,1))
for idx, nd in enumerate(G.nodes()):
xx[idx] = x[nd]
return [np.asscalar(np.dot(xx.T * A, xx)[0,0])]
<file_sep>/include/sbm.h
/*
*
* Header file of the SBM algorithm (C++ version)
*
*
* An algorithm for finding multiple core-periphery pairs in networks
*
*
* Core-periphery structure requires something else in the network
* <NAME> and Naoki Masuda
* Preprint arXiv:1710.07076
*
*
* Please do not distribute without contacting the authors.
*
*
* AUTHOR - <NAME>
*
*
* DATE - 11 Oct 2017
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
#if !defined(MAX_K)
#define MAX_K 100
#endif
class SBM: public CPAlgorithm{
public:
// Constructor
SBM();
SBM(double maxItNum, double tol);
// function needed to be implemented
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected:
int _maxItNum;
double _tol;
double _klent(double x, double y);
void update_Gamma(vector<long double>& Gamma, const int N, const int K, vector<vector<long double>>& One_point);
void update_Omega(vector<vector<long double>>& Omega, const int N, const int K,const vector<vector<int>>& adjList, const vector<int>& Degree, const vector<long double>& Gamma, map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point);
void initilize_params(const vector<vector<int>>& edgeList, const int N, const int K, vector<vector<int>>& adjList, vector<int>& Degree, vector<long double>& Gamma, vector<vector<long double>>& Omega, vector<vector<long double>>& One_point, map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point, map<pair<int,int>, array<long double,MAX_K> >& Cavity, vector<double>& External_field);
void compute_external(vector<double>& External_field, const int N, const int K, const vector<vector<long double>>& Omega, const vector<vector<long double>>& One_point);
void predict(vector<int>&Glist, const int N, const int K, vector<vector<long double>>& One_point);
void compute_one_point(vector<vector<long double>>& One_point, int N, int K, vector<vector<int>>& adjList, vector<int>& Degree, vector<long double>& Gamma, vector<vector<long double>>& Omega, map<pair<int,int>, array<long double,MAX_K> >& Cavity, vector<double>& External_field);
void compute_two_point(map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point, const int N, const int K, const vector<vector<int>>& adjList, const vector<int>& Degree, const vector<vector<long double>>& Omega, map<pair<int,int>, array<long double,MAX_K> >& Cavity);
void compute_cavity(map<pair<int,int>, array<long double,MAX_K> >& Cavity, const int N, const int K, const vector<vector<int>>& adjList, const vector<int>& Degree, const vector<long double>& Gamma, const vector<vector<long double>>& Omega, const vector<vector<long double>>& One_point, const vector<double>& External_field);
// modified
void bp(const vector<vector<int>>& edgeList, vector<int>& C, const int N, const int K, const int max_ite, const long double tol);
};
/*-----------------------------
Constructor
-----------------------------*/
SBM::SBM():CPAlgorithm(){
_maxItNum = 100;
_tol = 1e-4;
};
SBM::SBM(double maxItNum, double tol):CPAlgorithm(){
_maxItNum = (int) maxItNum;
_tol = tol;
};
/*---------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void SBM::detect(const Graph& G){
vector<vector<int>> L;
int M = 0;
int N = G.get_num_nodes();
for(int i = 0;i<N;i++){
int sz = G.degree(i);
for(int k = 0;k<sz; k++){
int j = G.get_kth_neighbour(i, k).get_node();
if(i <= j){
vector<int>edge(2);
edge[0] = i;
edge[1] = j;
L.push_back(edge);
M++;
}
}
}
// BP algorithm. C[i] = 1 or C[i] = 0 indicates a core or a peripheral node, respectively.
vector<int> C(N, 0);
_c = C;
bp(L, C, N, 2, _maxItNum, _tol);
/* Swap the core and periphery if the within-core density < within-periphery density*/
int Mcc = 0; // number of edges within core
int Mpp = 0; // # of edges within periphery
int Nc = 0; // number of core nodes
for(int i = 0; i < N; i++){
int sz = G.degree(i);
for(int k = 0;k < sz; k++){
int j = G.get_kth_neighbour(i, k).get_node();
Mcc+=C[i] * C[j];
Mpp+=(1-C[i]) * (1-C[j]);
}
Nc+=C[i];
}
int Np = N - Nc;
double rhocc = (double)Mcc / (double)(Nc * Nc);
double rhopp = (double)Mpp / (double)(Np * Np);
vector<double> tmp(N, 0.0);
_x = tmp;
if(rhocc < rhopp){
for(int i = 0; i < N; i++) _x[i] = 1-C[i];
}else{
for(int i = 0; i < N; i++) _x[i] = C[i];
}
}
double SBM::_klent(double x, double y){
double retval = 0;
if(x > 1e-20){
retval+=x*log(x);
}
if(y > 1e-20){
retval-=x*log(y);
}
return retval;
}
void SBM::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
double Mcc = 0;
double Mcp = 0;
double Mpp = 0;
int Nc = 0;
int N = G.get_num_nodes();
double rho = 0;
for(int i = 0; i < N; i++){
int sz = G.degree(i);
for(int k = 0;k < sz; k++){
int j = G.get_kth_neighbour(i, k).get_node();
Mcc+=x[i] * x[j];
Mcp+=x[i] * (1-x[j]) + x[j] * (1-x[i]);
Mpp+=(1-x[i]) * (1-x[j]);
}
Nc+=(int)x[i];
}
rho = (Mcc + Mcp + Mpp) / (double) (N * N);
int Np = N - Nc;
double rhocc = (double)Mcc / (double)(Nc * Nc);
double rhocp = (double)Mcp / (double)(2 * Nc * Np);
double rhopp = (double)Mpp / (double)(Np * Np);
if(Nc==0){
rhocc = 0; rhocp = 0;
}
if(Np==0){
rhopp = 0; rhocp = 0;
}
Q = Nc * Nc * _klent(rhocc, rho) + 2 * Nc * Np * _klent(rhocp, rho) + Np * Np * _klent(rhopp, rho);
vector<double> tmp(1, Q);
q = tmp;
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
void SBM::bp(const vector<vector<int>>& edgeList, vector<int>& C, const int N, const int K, const int max_ite, const long double tol)
{
//initialization
vector<vector<int>> adjList;
vector<int> Degree;
vector<long double> Gamma;
vector<vector<long double>> Omega;
vector<vector<long double>> One_point;
map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> > Two_point; //two point marginal
map<pair<int,int>, array<long double,MAX_K> > Cavity; //message matrix, stored the edges as keys
vector<double> External_field; //external field term as sum of logs
initilize_params(edgeList, N, K, adjList, Degree, Gamma, Omega, One_point, Two_point, Cavity, External_field);
//main loop
int ite = 0;
while (ite < max_ite)
{
//update message and two point marginal
compute_external(External_field, N, K, Omega, One_point);
compute_one_point(One_point, N, K, adjList, Degree, Gamma, Omega, Cavity, External_field);
compute_cavity(Cavity, N, K, adjList, Degree, Gamma, Omega, One_point, External_field);
//update parameters
compute_two_point(Two_point, N, K, adjList, Degree, Omega, Cavity);
update_Omega(Omega, N, K, adjList, Degree, Gamma, Two_point);
update_Gamma(Gamma, N, K, One_point);
ite++;
}
fill(C.begin(),C.end(),0);
predict(C, N, K, One_point);
}
//based on the implementation by <NAME>.
//update the parameters based on current belief
void SBM::update_Gamma(vector<long double>& Gamma, const int N, const int K, vector<vector<long double>>& One_point)
{
int r;
long int i;
long double NORM=0;
fill(Gamma.begin(), Gamma.end(), 0);
for(r = 0; r < K; r++)
{
for(i = 0; i < N; i++)
{
Gamma[r] += One_point[i][r];
}
NORM += Gamma[r];
}
//normalize
for(r=0; r < K; r++)
{
Gamma[r] = Gamma[r]/NORM;
}
/*
cout << "The Gamma is now" << endl;
cout << Gamma[0] << " " << Gamma[1] << endl;
*/
return;
}
void SBM::update_Omega(vector<vector<long double>>& Omega, const int N, const int K, const vector<vector<int>>& adjList,const vector<int>& Degree, const vector<long double>& Gamma, map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point )
{
long int i,j;
int r,s,it;
long double SIGMA;
for(r = 0; r < K; r++)
{
for(s = 0; s < K; s++)
{
SIGMA = 0;
for(i = 0; i < N; i++)
{
for(it = 0; it < Degree[i]; it++)
{
j = adjList[i][it];
SIGMA += Two_point[make_pair(i,j)][r][s];
}
}
//update the mixing matrix.
Omega[r][s] = SIGMA/(N*N*Gamma[r]*Gamma[s]);
}
}
/*
cout << "The mixing matrix is now" << endl;
cout << Omega[0][0] << " " << Omega[0][1] << endl;
cout << Omega[1][0] << " " << Omega[1][1] << endl;
*/
return;
}
//make prediction based on belief. i,e. assign node to the group with highest belief.
void SBM::predict(vector<int>&Glist, const int N, const int K, vector<vector<long double>>& One_point)
{
long int i;
for (i = 0; i < N; i++)
{
Glist[i] = (int) distance(One_point[i].begin(),max_element(One_point[i].begin(),One_point[i].end()));
//Glist[i] = distance(One_point[i],max_element(One_point[i].begin(),One_point[i].end()));
}
return;
}
void SBM::initilize_params(const vector<vector<int>>& edgeList, const int N, const int K, vector<vector<int>>& adjList, vector<int>& Degree, vector<long double>& Gamma, vector<vector<long double>>& Omega, vector<vector<long double>>& One_point, map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point, map<pair<int,int>, array<long double,MAX_K> >& Cavity, vector<double>& External_field)
{
Degree.assign(N,0);
for(int i=0; i < N; i++)
{
vector<int> tmp;
adjList.push_back(tmp);
vector<long double> tmp2(K);
One_point.push_back(tmp2);
}
for(int i=0; i < K; i++)
{
vector<long double> tmp(K);
Omega.push_back(tmp);
}
Gamma.assign(K,0.0);
External_field.assign(K,0.0);
// First we count the degrees by scanning through the list once
int sz = (int) edgeList.size();
for(int i=0; i < sz; i++)
{
int src = edgeList[i][0];
int dst = edgeList[i][1];
adjList[src].push_back(dst);
adjList[dst].push_back(src);
}
double avedeg = 0;
for(int i=0; i < N; i++)
{
Degree[i] = (int) adjList[i].size();
avedeg+=(double)Degree[i];
}
avedeg/=(double)N;
mt19937_64 mtrnd;
int seeds[624];
size_t size = 624*4; //Declare size of data
ifstream urandom("/dev/urandom", ios::in | ios::binary); //Open stream
if (urandom) //Check if stream is open
{
urandom.read(reinterpret_cast<char*>(seeds), size); //Read from urandom
urandom.close(); //close stream
}
else //Open failed
{
cerr << "Failed to open /dev/urandom" << endl;
}
seed_seq seed(&seeds[0], &seeds[624]);
mtrnd.seed(seed);
uniform_real_distribution<double> udist(0.0,1.0);
//The initialization can be achieved many ways and different initialization
//will result in possibly different results. Try different initialization
//point as well as initialization method for better results. Here the
//method is the 'apriori' method where we have a rough idea of what the parameters
//should be.
double p = (avedeg * (double) N)/ (double)(N*(N-1));
Gamma[0] = 0.5;
Gamma[1] = 0.5;
Omega[0][0] = 0.5;
Omega[0][1] = p*p;
Omega[1][0] = p*p;
Omega[1][1] = p*p*p*p;
//one could randomly generate a,b repeatedly for each node/edge. one value usually work just as well.
srand((unsigned int)time(NULL)); //random seed
long double a;
long double b;
a = ((long double) rand() / (RAND_MAX));
b = ((long double) rand() / (RAND_MAX));
//initialize one point marginal to unbalanced belief.
for(int i = 0; i < N ;i++)
{
One_point[i][0] = !!(Degree[i]>=avedeg);
One_point[i][1] = 1-!!(Degree[i]>=avedeg);
}
/*
for(int i = 0;i < K;i++){
Gamma[i] = 1.0/(double)(K);
for(int j = 0;j < K;j++){
Omega[i][j] = udist(mtrnd);
}
}
*/
//initialize the message on the edges; also initialize the two point marginal to zeros.
for(int i = 0; i < sz; i++)
{
for(int r = 0; r < K; r++)
{
Cavity[make_pair(edgeList[i][0],edgeList[i][1])][r] = r==0 ? b:1-b;
Cavity[make_pair(edgeList[i][1],edgeList[i][0])][r] = r==0 ? b:1-b;
Two_point[make_pair(edgeList[i][1],edgeList[i][0])] = {{{0,0},{0,0}}};
Two_point[make_pair(edgeList[i][0],edgeList[i][1])] = {{{0,0},{0,0}}};
}
}
}
//compute the external field term
void SBM::compute_external(vector<double>& External_field, const int N, const int K, const vector<vector<long double>>& Omega, const vector<vector<long double>>& One_point )
{
long int i;
int r,s;
long double SIGMA;
fill(External_field.begin(),External_field.end(),0);
for(r = 0; r < K; r++)
{
for(i=0; i < N; i++)
{
SIGMA = 0;
for(s = 0; s < K; s++)
{
SIGMA += One_point[i][s]*exp(-Omega[r][s]);
}
External_field[r] += log(SIGMA);
}
}
return;
}
//compute the one point marginal
void SBM::compute_one_point(vector<vector<long double>>& One_point, int N, int K, vector<vector<int>>& adjList, vector<int>& Degree, vector<long double>& Gamma, vector<vector<long double>>& Omega, map<pair<int,int>, array<long double,MAX_K> >& Cavity, vector<double>& External_field)
{
vector<double> BUFFER(K, 0.0);
long int i,j;
int r,s,it;
long double SIGMA1,SIGMA2,PROD;
for(i = 0; i < N; i++)
{
fill(BUFFER.begin(),BUFFER.end(),0);
for(r = 0; r < K; r++)
{
PROD = 0;
for(it = 0; it < Degree[i]; it++)
{
j = adjList[i][it];
SIGMA1 = 0;
SIGMA2 = 0;
for(s = 0; s < K; s++)
{
SIGMA1 += Cavity[make_pair(j,i)][s]*Omega[r][s]*exp(-Omega[r][s]);
SIGMA2 += One_point[j][s]*exp(-Omega[r][s]);
}
PROD += log(SIGMA1)- log(SIGMA2);
}
BUFFER[r] = log(Gamma[r]) + PROD + External_field[r];
}
//normalize and set the value
long double x = 1/(exp(BUFFER[0]-BUFFER[1])+1);
One_point[i][0] = 1 -x;
One_point[i][1] = x;
/*
//normalize
long double denom = 0;
long double md = 0;
for(int l =0;l<K;l++){
md +=BUFFER[l];
}
md/=(long double) K;
for(int l =0;l<K;l++){
denom+= exp(BUFFER[l]-md);
}
for(int l =0;l<K;l++){
One_point[i][l] = exp(BUFFER[l]-md) / denom;
}
*/
}
return;
}
//compute the two point marginal
void SBM::compute_two_point(map<pair<int,int>, array<array<long double,MAX_K>, MAX_K> >& Two_point, const int N, const int K, const vector<vector<int>>& adjList, const vector<int>& Degree, const vector<vector<long double>>& Omega, map<pair<int,int>, array<long double,MAX_K> >& Cavity)
{
vector<vector<double>> BUFFER(K, vector<double>(K,0.0));
long double NORM,PROD; //normalization term, sum of the individual q_{ij}^{rs}.
long int i,j;
int r,s,it;
for(i = 0; i < N; i++)
{
for(it = 0; it < Degree[i]; it++)
{
j = adjList[i][it];
NORM = 0;
fill(BUFFER[0].begin(),BUFFER[0].end(),0);
fill(BUFFER[1].begin(),BUFFER[1].end(),0);
//summing over the four possible values of two point marginal
for(r = 0; r < K; r++)
{
for(s = 0; s < K; s++)
{
PROD = Omega[r][s]*exp(Omega[r][s])*Cavity[make_pair(i,j)][r]*Cavity[make_pair(j,i)][s];
NORM += PROD;
BUFFER[r][s] = PROD;
}
}
//normalizing the two point marginal so they sum to unity
for(r = 0; r < K; r++)
{
for(s = 0; s < K; s++)
{
Two_point[make_pair(i,j)][r][s] = BUFFER[r][s]/NORM;
}
}
}
}
return;
}
//compute the message matrix
//only update the edge terms, the non-egde terms will just be the value of the one point marginal
void SBM::compute_cavity(map<pair<int,int>, array<long double,MAX_K> >& Cavity, const int N, const int K, const vector<vector<int>>& adjList, const vector<int>& Degree, const vector<long double>& Gamma, const vector<vector<long double>>& Omega, const vector<vector<long double>>& One_point, const vector<double>& External_field)
{
vector<double> BUFFER(K,0.0);
long int i,j,k;
int r,s,it1,it2; //use two iterators for two edges
long double SIGMA1,SIGMA2,PROD;
for(i = 0; i < N; i++)
{
for(it1 = 0; it1 < Degree[i]; it1++)
{
j = adjList[i][it1];
for(r = 0; r < K; r++)
{
PROD = 0;
for(it2 = 0; it2 < Degree[i]; it2++)
{
k = adjList[i][it2];
if(k != j)
{
SIGMA1 = 0;
SIGMA2 = 0;
for(s = 0; s < K; s++)
{
SIGMA1 += Cavity[make_pair(k,i)][s]*Omega[r][s]*exp(-Omega[r][s]);
SIGMA2 += One_point[k][s]*exp(-Omega[r][s]);
}
PROD += log(SIGMA1) - log(SIGMA2);
}
}
BUFFER[r] = log(Gamma[r]) + PROD + External_field[r];
}
//normalize
long double x = 1/(exp(BUFFER[0]-BUFFER[1])+1);
Cavity[make_pair(i,j)][0] = 1 - x;
Cavity[make_pair(i,j)][1] = x;
/*
//normalize
long double denom = 0;
long double md = 0;
for(int l =0;l<K;l++){
md +=BUFFER[l];
}
md/=(long double) K;
for(int l =0;l<K;l++){
denom+= exp(BUFFER[l]-md);
}
for(int l =0;l<K;l++){
Cavity[make_pair(i,j)][l] = exp(BUFFER[l]-md) / denom;
}
*/
}
}
return;
}
<file_sep>/cpalgorithm/Surprise.py
import _cpalgorithm as _cp
import scipy as sp
import numpy as np
from .CPAlgorithm import *
class Surprise(CPAlgorithm):
""" Core-periphery detection by Surprise
Parameters
----------
num_runs : int
Number of runs of the algorithm (optional, default: 1)
Run the algorithm num_runs times. Then, this algorithm outputs the result yielding the maximum quality.
Examples
--------
Create this object.
>>> import cpalgorithm as cpa
>>> spr = cpa.Surprise()
**Core-periphery detection**
Detect core-periphery structure in network G (i.e., NetworkX object):
>>> spr.detect(G)
Retrieve the ids of the core-periphery pair to which each node belongs:
>>> pair_id = spr.get_pair_id()
Retrieve the coreness:
>>> coreness = spr.get_coreness()
.. note::
The implemented algorithm accepts unweighted and undirected networks only.
The algorithm finds a single CP pair in the given network, i.e., c[node_name] =0 for all node_name.
This algorithm is stochastic, i.e., one would obtain different results at each run.
.. rubric:: Reference
[1] <NAME>, <NAME>, <NAME>. Detecting Core-Periphery Structures by Surprise. Preprint arXiv:1810.04717 (2018).
"""
def __init__(self):
self.num_runs = 1
def detect(self, G):
"""Detect a single core-periphery pair using the Borgatti-Everett algorithm.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> spr = cpa.Surprise()
>>> spr.detect(G)
"""
nodes = G.nodes()
N = len(nodes)
Cbest =np.zeros(N)
qbest = 0
for it in range(self.num_runs):
C, q = self._detect(G)
if q < qbest:
Cbest = C
qbest = q
# ------------
# Post process
# ------------
self.c_ = dict(zip(nodes, np.zeros(N).astype(int)))
self.x_ = dict(zip(nodes, Cbest.astype(int)))
self.Q_ = self._score(G, self.c_, self.x_)[0]
self.qs_ = [self.Q_]
def _detect(self, G):
# ----------
# Initialise
# ----------
A = nx.to_scipy_sparse_matrix(nx.Graph(G))
# ------------
# Main routine
# ------------
N = A.shape[0]
C = np.random.randint(2, size=N)
edges = self._sort_edges(A)
q = self._calculateSurprise(A, C)
for itnum in range(5):
for edge in edges:
u = edge[0]
v = edge[1]
# Move node u to the other group and
# compute the changes in the number of edges of different types
C[u] = 1-C[u]
# Propose a move
qp = self._calculateSurprise(A, C)
if q < qp: # If this is a bad move, then bring back the original
C[u] = 1-C[u]
else:
q = qp
if np.random.rand() >0.5:
# move 1 to 0 for n=3 nodes
nnz = np.nonzero(C)[0]
if nnz.shape[0] ==0:
continue
flip = np.random.choice(nnz, np.min([3, nnz.shape[0]]))
C[flip] = 1 - C[flip]
else:
# move 0 to 1 for n=3 nodes
nnz = np.nonzero(1-C)[0]
if nnz.shape[0] ==0:
continue
flip = np.random.choice(nnz, np.min([3, nnz.shape[0]]))
C[flip] = 1 - C[flip]
qp = self._calculateSurprise(A, C)
if q < qp:
C[flip] = 1 - C[flip]
else:
q = qp
# Flip group index if group 1 is sparser than group 0
Nc = np.sum(C)
Np = N - Nc
Ecc = np.sum(np.multiply(A * C, C))
Epp = np.sum(np.multiply(A*(1-C), (1-C)))
if Ecc * (Np *(Np-1)) < Epp * (Nc *(Nc-1)):
C = 1-C
return C, q
def _sort_edges(self, A):
r,c = A.nonzero()
deg = np.array(A.sum(axis = 0)).ravel()
s = deg[r] * deg[c]
ind = np.argsort(s)
return list(zip(r[ind], c[ind]))
def _slog(self, numer, denom, s):
if (s ==0) | (numer < 0) | (denom < 0):
return 0
denom = denom * (1.0 - 1e-10) + 1e-10
numer = numer * (1.0 - 1e-10) + 1e-10
v = s * np.log( numer / denom )
return v
def _score(self, G, c, x):
A = nx.to_scipy_sparse_matrix(nx.Graph(G))
nodes = G.nodes()
C = np.array([x[nd] for nd in nodes])
q = self._calculateSurprise(A, C)
return [-self._calculateSurprise(A, C)]
def _calculateSurprise(self, A, x):
N = A.shape[0]
Nc = x.sum()
Np = N - Nc
if (Nc <2) | (Np <2) |(Nc > N-2) | (Np >N-2) :
return 0
L = A.sum()/2
V = N * (N-1)/2
Vc = Nc * (Nc-1)/2
Vcp = Nc * Np
Ax = A * x
lc = np.sum(np.multiply(Ax, x))/2
lcp = np.sum(np.multiply(Ax, 1-x))
lp = L - lc - lcp
p = L / (N * (N -1)/2)
pc = lc / (Nc * (Nc-1)/2)
pp = lp / (Np * (Np-1)/2)
pcp = lcp / (Nc * Np)
S = self._slog( p, pp, 2 * L) + self._slog((1-p), (1-pp), 2* V-2*L) + self._slog(pp, pc, 2*lc)\
+ self._slog( (1-pp), (1-pc), 2*Vc - 2*lc) + self._slog(pp,pcp, 2*lcp)\
+ self._slog( (1-pp), (1-pcp), 2*Vcp - 2*lcp)
return S
<file_sep>/include/cpalgorithm.h
#include <algorithm>
#include <fstream>
#include <iostream>
#include <random>
#include <vector>
#include <map>
#include <numeric>
#include <cmath>
#include <graph.h>
#if !defined(MAX)
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#endif
#if !defined(MIN)
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#endif
using namespace std;
class CPAlgorithm{
public:
// Constructor
CPAlgorithm();
//CPAlgorithm(int num_runs, double significance_level);
// Getter
vector<int> get_c () const;
vector<double> get_x () const;
//vector<double> get_p_values () const;
// Setter
//void set_significance_level (double s);
//void set_num_rand_nets (double r);
// Detect significant CP pairs in networks
virtual void detect(const Graph& G) = 0;
// Compute the quality of CP pairs
void _calc_Q(
const Graph& G,
double& Q,
vector<double>& q);
virtual void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q) = 0;
protected:
vector<int> _c; // _c[i] indicates the index of the CP pair of node i
vector<double> _x; // x[i]=1 or x[i]=0 indicates a core or a periphery, respectively.
//vector<double> _p_values; // p_values
double _Q; // quality value
vector<double> _q; // quality values
//double _significance_level; // statistical significance level
//int _num_rand_nets; // number of randomised networks to be generated
int _num_runs; // Number of runs of the algorithm
mt19937_64 _mtrnd; // random number generator
/* --------------------------
Functions needed to be implemented in each algorithm
virtual void _detect_( //
const Graph& G,
vector<int>& c,
vector<bool>& x,
double& Q,
vector<double>& q,
mt19937_64& mtrnd) = 0;
-------------------------- */
// Detect CP structure and compute their quality
/* --------------------------
Statistical test
// Initialise parameter of randomised networks generator
virtual void _init_randomised_network_generator(const Graph& G)= 0;
// Generate randomised networks
virtual void _generate_randomised_network(Graph& G, mt19937_64& mtrnd) = 0;
void _estimate_statistical_significance(
const Graph& G,
const vector<int>& c,
const vector<bool>& x,
const int num_of_rand_nets,
vector<double>& p_values
);
double _normcdf(double value);
-------------------------- */
/* --------------------------
Other utility functions
-------------------------- */
mt19937_64 _init_random_number_generator();
};
CPAlgorithm::CPAlgorithm(){
_mtrnd = _init_random_number_generator();
//_num_rand_nets = 500;
_num_runs = 10;
}
mt19937_64 CPAlgorithm::_init_random_number_generator(){
mt19937_64 mtrnd;
random_device r;
seed_seq seed{ r(), r(), r(), r(), r(), r(), r(), r() };
mtrnd.seed(seed);
return mtrnd;
}
// Getter
vector<int> CPAlgorithm::get_c() const{
return _c;
}
vector<double> CPAlgorithm::get_x() const{
return _x;
}
/*
vector<double> CPAlgorithm::get_p_values() const{
return _p_values;
}
void CPAlgorithm::set_significance_level (double s){
_significance_level = s;
}
void CPAlgorithm::set_num_rand_nets (double r){
_num_rand_nets = r;
}
*/
/*
void CPAlgorithm::detect(const Graph& G){
_detect_(G, _c, _x, _Q, _q, _mtrnd);
int K = _q.size();
vector<double> tmp(K,0.0);
_p_values = tmp;
if (_significance_level < 1.0) {
_estimate_statistical_significance(G, _c, _x, _num_rand_nets, _p_values);
}
}
void CPAlgorithm::_estimate_statistical_significance(
const Graph& G,
const vector<int>& c,
const vector<bool>& x,
const int num_of_rand_nets,
vector<double>& p_values
)
{
// Initialise variables
bool noSelfloop = false;
bool isunweighted = false;
int K = *max_element(c.begin(), c.end()) + 1;
int N = G.get_num_nodes();
double Q;
vector<double> q;
vector<int> n(K);
vector<double> deg(N);
fill(n.begin(), n.end(), 0);
_calc_Q(G, c, x, Q, q);
for (int i = 0; i < N; i++) {
n[c[i]]++;
};
int numthread;// create random number generator per each thread
_init_randomised_network_generator(G);
# pragma omp parallel
{
numthread = omp_get_num_threads();
}
vector<mt19937_64> mtrnd_list(numthread);
for(int i = 0; i < numthread; i++){
mtrnd_list[i] = _init_random_number_generator();
}
vector<int> nhat;
vector<double> qhat;
#ifdef _OPENMP
#pragma omp parallel for shared(nhat, qhat, mtrnd_list)
#endif
for (int it = 0; it < num_of_rand_nets; it++) {
// Generate a randomised network using the configuration model.
Graph G_rand(N);
int tid = omp_get_thread_num();
mt19937_64 mtrnd = mtrnd_list[tid];
_generate_randomised_network(G_rand, mtrnd);
//_Chung_Lu_Algorithm(deg, deg_rank, G_rand, noSelfloop, isunweighted, mtrnd);
// Detect core-periphery pairs using the KM--config algorithm
vector<int> c_rand;
vector<bool> x_rand;
vector<double> q_rand;
double Q_rand;
_detect_(G_rand, c_rand, x_rand, Q_rand, q_rand, mtrnd);
// Save the quality and size of core-periphery pairs in the randomised network.
int K_rand = q_rand.size();
vector<int> nsr(K_rand, 0);
for (int i = 0; i < N; i++) {
nsr[c_rand[i]]++;
}
#ifdef _OPENMP
#pragma omp critical
#endif
for (int k = 0; k < K_rand; k++) {
nhat.push_back(nsr[k]);
qhat.push_back(q_rand[k]);
}
}
// Compute the mean and variance of the quality and size
int S = nhat.size();
double mu_n = (double)accumulate(nhat.begin(), nhat.end(), 0.0) / (double)S;
double mu_q = (double)accumulate(qhat.begin(), qhat.end(), 0.0) / (double)S;
double sig_nn = 0;
double sig_qq = 0;
double sig_nq = 0;
for (int s = 0; s < S; s++) {
sig_nn += pow((double)nhat[s] - mu_n, 2) / (double)(S - 1);
sig_qq += pow(qhat[s] - mu_q, 2) / (double)(S - 1);
sig_nq += ((double)nhat[s] - mu_n) * (qhat[s] - mu_q) / (double)(S - 1);
}
// Compute p-values using the Gaussian kernel density estimator
double h = MAX(pow((double)S, -1.0 / 6.0), 1e-32);
p_values.clear();
p_values.assign(K, 1.0);
for (int k = 0; k < K; k++) {
double numer = 0.0;
double denom = 0.0;
for (int s = 0; s < S; s++) {
double qbar = qhat[s] + sig_nq / sig_nn * (double)(n[k] - nhat[s]);
double t = sig_nn * (q[k] - qbar) / (sqrt(sig_nn * sig_qq - sig_nq * sig_nq) * h);
double cum = _normcdf(t);
double w = exp(- (double)pow(n[k] - nhat[s], 2) / (2.0 * h * h * sig_nn)) + 1e-33;
numer += cum * w;
denom += w;
}
p_values[k] = 1.0 - numer / denom;
}
}
double CPAlgorithm::_normcdf(double value)
{
return 0.5 + 0.5 * erf(value * M_SQRT1_2);
}
*/
void CPAlgorithm::_calc_Q(
const Graph& G,
double& Q,
vector<double>& q){
calc_Q(G, _c, _x, Q, q);
}
<file_sep>/tests/test.py
import cpalgorithm as cpa
import networkx as nx
def test_BE():
# BE =========================
G=nx.karate_club_graph()
print("Running BE algorithm ...")
be = cpa.BE()
be.detect(G)
pair_id = be.get_pair_id()
coreness = be.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, be)
def test_MINRES():
# MINRES =========================
G=nx.karate_club_graph()
print("Running MINRES algorithm ...")
mrs = cpa.MINRES()
mrs.detect(G)
pair_id = mrs.get_pair_id()
coreness = mrs.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, mrs)
def test_SBM():
# SBM =========================
G=nx.karate_club_graph()
print("Running SBM algorithm ...")
sbm = cpa.SBM()
sbm.detect(G)
pair_id = sbm.get_pair_id()
coreness = sbm.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, sbm)
def test_LowRankCore():
# LowRankCore =========================
G=nx.karate_club_graph()
print("Running LowRankCore algorithm ...")
lrc = cpa.LowRankCore()
lrc.detect(G)
pair_id = lrc.get_pair_id()
coreness = lrc.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, lrc)
def test_LapCore():
# LapCore =========================
G=nx.karate_club_graph()
print("Running LapCore algorithm ...")
lc = cpa.LapCore()
lc.detect(G)
pair_id = lc.get_pair_id()
coreness = lc.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, lc)
def test_LapSgnCore():
# LapSgnCore =========================
G=nx.karate_club_graph()
print("Running LapSgnCore algorithm ...")
lsc = cpa.LapSgnCore()
lsc.detect(G)
pair_id = lsc.get_pair_id()
coreness = lsc.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, lsc)
def test_Rombach():
# Rombach =========================
G=nx.karate_club_graph()
print("Running Rombach's algorithm ...")
rb = cpa.Rombach()
rb.detect(G)
pair_id = rb.get_pair_id()
coreness = rb.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, rb)
def test_Rossa():
# Rossa =========================
G=nx.karate_club_graph()
print("Running Rossa's algorithm ...")
rs = cpa.Rossa()
rs.detect(G)
pair_id = rs.get_pair_id()
coreness = rs.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, rs)
def test_KM_ER():
# KM--ER =========================
G=nx.karate_club_graph()
print("Running KM_ER ...")
km = cpa.KM_ER()
km.detect(G)
pair_id = km.get_pair_id()
coreness = km.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, km)
def test_KM_config():
# KM--config =========================
G=nx.karate_club_graph()
print("Running KM_config ...")
km = cpa.KM_config()
km.detect(G)
pair_id = km.get_pair_id()
coreness = km.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, km)
def test_Surprise():
# Surprise =========================
G=nx.karate_club_graph()
print("Running Surprise ...")
spr = cpa.Surprise()
spr.detect(G)
pair_id = spr.get_pair_id()
coreness = spr.get_coreness()
sig_pair_id, sig_coreness, significance, p_values = cpa.qstest(pair_id, coreness, G, spr)
test_BE()
test_MINRES()
test_SBM()
test_LowRankCore()
test_LapCore()
test_LapSgnCore()
test_Rombach()
test_Rossa()
test_KM_ER()
test_KM_config()
test_Surprise()
<file_sep>/docs/Contact.rst
.. _contact:
#######
Contact
#######
cpalgorithm is maintained by `<NAME> <https://skojaku.github.io/>`_.
<file_sep>/include/rombach_label_switching.h
/*
*
* Header file of the KM-config algorithm (C++ version)
*
*
* An algorithm for finding multiple core-periphery pairs in networks
*
*
* Core-periphery structure requires something else in the network
* <NAME> and <NAME>
* Preprint arXiv:1710.07076
*
*
* Please do not distribute without contacting the authors.
*
*
* AUTHOR - <NAME>
*
*
* DATE - 11 Oct 2017
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
class Rombach_LS: public CPAlgorithm{
public:
// Constructor
Rombach_LS();
Rombach_LS(int num_runs);
Rombach_LS(int num_runs, double alpha, double beta);
// function needed to be implemented
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected:
int _num_runs;
int _N;
double _alpha;
double _beta;
double _calc_coreness(int ord);
double _rowSum_score(const Graph& G, vector<int>& ndord, int nid, int sid);
double _calc_swap_gain(const Graph& G, vector<int>& ndord, int nid, int sid );
void _swap_nodes(vector<int>&ndord, int nid, int nextnid );
void _rombach_label_switching(const Graph& G, vector<int>& ords);
};
/*-----------------------------
Constructor
-----------------------------*/
Rombach_LS::Rombach_LS():CPAlgorithm(){
};
Rombach_LS::Rombach_LS(int num_runs):CPAlgorithm(){
_num_runs = num_runs;
};
Rombach_LS::Rombach_LS(int num_runs, double alpha, double beta):CPAlgorithm(){
_num_runs = num_runs;
_alpha = alpha;
_beta = beta;
};
/*---------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void Rombach_LS::detect(const Graph& G){
vector<int> ords;
_N = G.get_num_nodes();
_rombach_label_switching(G, ords);
vector<int> tmp2(_N, 0);
_c = tmp2;
vector<double> tmp(_N, 0.0);
_x = tmp;
for(int i = 0; i < _N; i++){
_x[i] = _calc_coreness(ords[i]);
}
}
void Rombach_LS::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
Q = 0;
int N = G.get_num_nodes();
for(int i = 0; i < N; i++){
int sz = G.degree(i);
for (int j = 0; j < sz; j++) {
Neighbour nn = G.get_kth_neighbour(i, j);
int nei = nn.get_node();
double wj = nn.get_w();
Q+= wj * x[i] * x[nei];
}
}
vector<double> tmp(1,0);
tmp[0] = Q;
q = tmp;
}
/*-----------------------------
Private functions (internal use only)
-----------------------------*/
double Rombach_LS::_calc_coreness( int ord){
double c = 0.0;
double bn = floor( _N * _beta);
if(ord <= bn ){
c = (1.0-_alpha) / (2.0*bn) * (double)ord;
}else{
c = ((double)ord-bn)*(1.0-_alpha)/(2*((double)_N-bn)) + (1+_alpha)/2.0;
}
return c;
}
double Rombach_LS::_rowSum_score(const Graph& G, vector<int>&ndord, int nid, int sid){
double retval = 0;
int sz = G.degree(nid);
for(int k = 0; k < sz; k++){
Neighbour n = G.get_kth_neighbour(nid, k);
int id = n.get_node();
double w = n.get_w();
//for( auto id : adjList[nid] ){
if(id==sid) continue;
retval+=w * _calc_coreness( ndord[id] );
}
return retval;
}
double Rombach_LS::_calc_swap_gain(const Graph& G, vector<int>&ndord, int nid, int sid ){
double c_nid = _calc_coreness( ndord[nid] );
double c_sid = _calc_coreness( ndord[sid] );
double rowSum_nid = _rowSum_score(G, ndord, nid, sid);
double rowSum_sid = _rowSum_score(G, ndord, sid, nid);
double dQ = (c_sid - c_nid) * rowSum_nid + (c_nid - c_sid) * rowSum_sid;
return dQ;
}
void Rombach_LS::_swap_nodes(vector<int>&ndord, int nid, int nextnid ){
// update ndord;
int tmp = ndord[nid];
ndord[nid] = ndord[nextnid];
ndord[nextnid] = tmp;
}
void Rombach_LS::_rombach_label_switching(const Graph& G, vector<int>& nds){
// Initialise
int N = G.get_num_nodes();
vector<int> ndord(N,0);
for(int i = 0;i < N;i++) ndord[i] = i;
vector<int> ord = ndord;
shuffle(ndord.begin(), ndord.end(), _mtrnd);
// Label Switching algorithm
bool isupdated = false;
int itmax = 100;int itnum=0;
do{
isupdated = false;
shuffle(ord.begin(), ord.end(), _mtrnd);
for(int i = 0; i < _N; i++){
int nid = ord[i]; // Get the id of node we shall update
// calculate gain obtained by swapping label of nid and other labls
int nextnid = nid;
double dQmax = -_N;
for( int sid =0;sid<_N;sid++ ){
if(sid==nid) continue;
double dQ = _calc_swap_gain(G, ndord, nid, sid);
if(dQmax < dQ){
nextnid = sid;
dQmax = dQ;
}
}
if( dQmax <= std::numeric_limits<double>::epsilon()) continue;
isupdated = true;
_swap_nodes(ndord, nid, nextnid);
}
itnum ++;
}while( isupdated & (itnum <itmax) );
nds = ndord;
}
<file_sep>/cpalgorithm/KM_modmat.py
import _cpalgorithm as _cp
from .CPAlgorithm import *
class KM_modmat(CPAlgorithm):
def __init__(self):
self.num_runs = 10
def detect(self, G):
node_pairs, w, node2id, id2node = self._to_edge_list(G)
cppairs = _cp.detect_modmat(edges=node_pairs, ws=w, num_of_runs = self.num_runs)
self.c_ = dict(zip( [id2node[i] for i in range(N)], cppairs[0].astype(int)))
self.x_ = dict(zip( [id2node[i] for i in range(N)], cppairs[1].astype(int)))
self.Q_ = cppairs[2][0]
self.qs_ = cppairs[3].tolist()
def _score(self, G, c, x):
node_pairs, w, node2id, id2node = _to_edge_list(G)
N = len(id2node)
_c = np.array([ c[id2node[i]] for i in range(N) ])
_x = np.array([ x[id2node[i]] for i in range(N) ])
result = _cp.calc_Q_modmat(edges=node_pairs, ws=w, c = _c, x=_x)
return result[1].tolist()
def significance(self):
return self.pvalues
<file_sep>/docs/test.py
def division(divident, divisor):
"""
Division function
This is an example of function documentation.
It illustrates how to document parameters, return values
and their types, and also the exception that a function
or a module may raise under certain conditions.
:param divident: operation divident
:type divident: float
:param divisor: operation divisor
:type divisor: float
:return: division result
:rtype: float
:raises ZeroDivisionError: when divisor = 0
.. note:: This function can accept :class:`int` parameters too.
.. warning:: ``divisor=0`` will cause :exc:`ZeroDivisionError` exception!
Example::
result = division(a, b)
"""
return divident / divisor
<file_sep>/docs/auto_examples/index.rst
:orphan:
.. raw:: html
<div class="sphx-glr-thumbcontainer" tooltip="Detect core">
.. only:: html
.. figure:: /auto_examples/images/thumb/sphx_glr_example_thumb.png
:ref:`sphx_glr_auto_examples_example.py`
.. raw:: html
</div>
.. toctree::
:hidden:
/auto_examples/example
.. raw:: html
<div style='clear:both'></div>
.. only :: html
.. container:: sphx-glr-footer
:class: sphx-glr-footer-gallery
.. container:: sphx-glr-download
:download:`Download all examples in Python source code: auto_examples_python.zip <//home/sada/program/core-periphery-detection/docs/auto_examples/auto_examples_python.zip>`
.. container:: sphx-glr-download
:download:`Download all examples in Jupyter notebooks: auto_examples_jupyter.zip <//home/sada/program/core-periphery-detection/docs/auto_examples/auto_examples_jupyter.zip>`
.. only:: html
.. rst-class:: sphx-glr-signature
`Gallery generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
<file_sep>/README.md
# core-periphery-detection
[](https://travis-ci.org/skojaku/core-periphery-detection)
This Python library contains various algorithms for finding core-periphery structure in networks.
See [docs](https://core-periphery-detection-in-networks.readthedocs.io/en/latest/) for installation, tutorials, and available algorithms.
<file_sep>/tests/example.py
import csv
import numpy as np
import pandas as pd
import networkx as nx
import _cpalgorithm as _cp
import cpalgorithm as cp
G=nx.karate_club_graph()
#G=nx.florentine_families_graph()
#df = pd.read_csv("karate.dat", sep='\t');
#G = nx.from_pandas_edgelist(df, "source", 'target', 'weight')
be = cp.BE()
Q = []
be.detect(G)
c = be.get_pair_id()
x = be.is_core()
print(sum(be.score()))
#significance, p_values, q_tilde, s_tilde = cp.qstest(c, x, G, be, num_of_thread = 4, null_model = cp.erdos_renyi)
print(c,x)
#print(significance, p_values)
<file_sep>/include/divisive.h
/*
*
* Header file of the Divisive algorithm
*
*
* Please do not distribute without contacting the authors.
*
* AUTHOR - <NAME>
*
* DATE - 04 July 2018
*/
#ifndef CP_ALGORITHM
#define CP_ALGORITHM
#include "cpalgorithm.h"
#endif
#ifndef BE_ALGORITHM
#define BE_ALGORITHM
#include "bealgorithm.h"
#endif
#include <math.h>
class Divisive: public CPAlgorithm{
public:
// Constructor
Divisive();
Divisive(int num_runs);
void detect(const Graph& G);
void calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q);
protected: // function needed to be implemented
int _num_runs;
void _detect_(const Graph& G, vector<int>& c, vector<double>& x, double Q, vector<double>& qs);
void _louvain(const Graph& G, const int num_of_runs, vector<int>& c, mt19937_64& mtrnd);
void _louvain_core(const Graph& G, vector<int>& C, const double M, mt19937_64& mtrnd);
double _calc_dQmod( double d, double degi, double D, double selfw, const double M );
double _calc_Qmod(const Graph& G, vector<int>& C, const double M);
void _calc_Q_be(const Graph& G, const vector<int>& c, const vector<double>& x, double& Q, vector<double>& q);
void _coarsing(const Graph& G, const vector<int>& c,Graph& newG);
void _modularity_label_switching(const Graph& G,vector<int>& C, const double M,mt19937_64& mtrnd);
void _subgraph(const Graph& G, vector<bool>&slice, Graph& Gs );
};
/*-----------------------------
Constructor
-----------------------------*/
Divisive::Divisive(int num_runs):CPAlgorithm(){
Divisive();
_num_runs = num_runs;
};
Divisive::Divisive(): CPAlgorithm(){
_num_runs = 10;
};
/*-----------------------------
Functions inherited from the super class (CPAlgorithm)
-----------------------------*/
void Divisive::calc_Q(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
int K = *max_element(c.begin(), c.end()) + 1;
vector<double> qtmp(K,0.0);
q = qtmp;
Q=0.0;
int N = G.get_num_nodes();
for(int k = 0; k < K; k++){
vector<bool> slice(N,false);
int Ns = 0;
for(int i = 0; i < N; i++){
if(c[i] == k){
slice[i] = true;
Ns++;
}
}
int idx = 0;
vector<double> xs(Ns, 0.0);
for(int i = 0; i < N; i++){
if(slice[i]){
xs[idx] = x[i];
idx++;
}
}
Graph Gs(0);
_subgraph(G, slice, Gs);
vector<double> qss;
double Qs;
_calc_Q_be(Gs, c, xs, Qs, qss);
q[k] = Qs;
Q+=Qs;
}
}
void Divisive::detect(const Graph& G){
_detect_(G, _c, _x, _Q, _q);
}
void Divisive::_detect_(const Graph& G, vector<int>& c, vector<double>& x, double Q, vector<double>& qs){
//Initialise _x and c randomly
int N = G.get_num_nodes();
vector<double> tmp(N, 0.0);
vector<int> tmpc(N, 0);
x = tmp;
c = tmpc;
uniform_real_distribution<double> dis(0.0, 1.0);
for(int i = 0;i<N; i++) c[i] = i;
// Detect communities
_louvain(G, _num_runs, c, _mtrnd);
// perform the BE algorithm for each community
BEAlgorithm be = BEAlgorithm(_num_runs);
int K = *max_element(c.begin(), c.end()) + 1;
vector<double> tmp3(K,0.0);
_q = tmp3;
_Q = 0;
for(int k = 0; k < K; k++){
vector<bool> slice(N,false);
for(int i = 0; i < N; i++){
if(c[i] == k){
slice[i] = true;
}
}
Graph Gs(0);
_subgraph(G, slice, Gs);
be.detect(Gs);
vector<double> xs = be.get_x();
vector<double> qss;
double Qs;
_calc_Q_be(Gs, c, xs, Qs, qss);
_q[k] = Qs;
_Q+=Qs;
int idx = 0;
for(int i = 0; i < N; i++){
if(c[i] == k){
x[i] = xs[idx];
idx++;
}
}
}
_c = c;
_x = x;
}
void Divisive::_calc_Q_be(
const Graph& G,
const vector<int>& c,
const vector<double>& x,
double& Q,
vector<double>& q)
{
int N = G.get_num_nodes();
if(N==1){
Q = 0;
vector<double> tmp(1,0.0);
q = tmp;
return;
}
double M = 0.0;
double pa = 0;
double pb = 0;
int nc = 0;
double mcc = 0;
for( int i = 0;i < N;i++ ) {
nc+=(int) x[i];
int sz = G.degree(i);
for( int k = 0; k < sz; k++ ) {
Neighbour nei = G.get_kth_neighbour(i, k);
int j = nei.get_node();
double w = nei.get_w();
mcc+=w * (x[i]+x[j] - x[i] * x[j]);
M+=1;
}
}
mcc = mcc/2;
M = M /2;
double M_b = (double)(nc * (nc-1) + 2 * nc * (N -nc))/2;
pa = M / (double)(N * (N-1)/2);
pb = M_b / (double)(N * (N-1)/2);
Q = ((double)mcc - pa * M_b ) / (sqrt(pa * (1-pa)) * sqrt(pb * (1-pb)) +1e-30);
Q = Q / (double)(N * (N-1)/2);
if(Q > 1) Q = 1;
if(Q < -1) Q = -1;
vector<double> qtmp(1,Q);
q= qtmp;
}
void Divisive::_subgraph(const Graph& G, vector<bool>&slice, Graph& Gs ){
int N = G.get_num_nodes();
int Ns = 0;
vector<int> node2id(N,0);
int idx = 0;
for(int i = 0; i < N; i ++){
if(slice[i]){
node2id[i] = idx;
Ns++;
idx+=1;
}
}
Graph tt(Ns);
Gs = tt;
for(int i =0; i < N;i++){
int sz = G.degree(i);
for(int j =0; j < sz;j++){
Neighbour n = G.get_kth_neighbour(i,j);
int nei = n.get_node();
double w = n.get_w();
if(slice[i] & slice[nei]){
Gs.addEdge(node2id[i], node2id[nei], w);
}
}
}
}
double Divisive::_calc_dQmod( double d, double degi, double D, double selfw, const double M ){
return 2*( d - degi*D/(2.0*M)) + (selfw-degi*degi/(2.0*M));
}
double Divisive::_calc_Qmod(
const Graph& G,
vector<int>& C,
const double M
){
double retval = 0;
int N = (int) C.size();
vector<double> degC(N, 0.0);
for(int i =0;i<N;i++){
int di = G.degree(i);
for(int j =0;j<di;j++){
Neighbour nei = G.get_kth_neighbour(i,j);
double w = nei.get_w();
int k = nei.get_node();
degC[ C[i] ]+=w;
if(C[i] == C[k]) {
retval+=w;
}
}
}
for(int i =0;i<N;i++){
retval-=degC[i]*degC[i]/(2*M);
}
retval/=(2*M);
return retval;
}
void Divisive::_coarsing(
const Graph& G,
const vector<int>& c,
Graph& newG
){
int N = (int) c.size();
int K = *max_element(c.begin(), c.end()) + 1;
newG = Graph(K);
for(int i = 0;i<N;i++){
int mi = c[i];
int sz = G.degree(i);
for(int j = 0;j<sz;j++){
Neighbour nb = G.get_kth_neighbour(i, j);
int nei = nb.get_node();
double w = nb.get_w();
int mj = c[nei];
newG.addEdge(mi, mj, w);
}
}
newG.compress();
}
void Divisive::_modularity_label_switching(
const Graph& G,
vector<int>& C,
const double M,
mt19937_64& mtrnd
){
int N= (int)C.size();
vector<int> ndord(N);
vector<double> D(N, 0);
vector<double>deg(N, 0);
for(int i = 0;i < N;i++) {
ndord[i] = i;
deg[i] = G.wdegree(i);
D[C[i]]+=deg[i];
};
// --------------------------------
// Label switching
// --------------------------------
vector<double> toC;
toC.assign(N,0.0);
bool isupdated = false;
int itNum = 0;
do{
isupdated = false;
shuffle(ndord.begin(), ndord.end(),mtrnd);
for(int i = 0;i <N;i++){
int nid = ndord[i];
int ncid = C[nid];
int neighbourNum = G.degree(nid);
fill(toC.begin(),toC.end(),0.0);
int newcid = ncid;
double selfw = 0;
for(int j = 0;j<neighbourNum;j++){
Neighbour nb = G.get_kth_neighbour(nid, j);
int nei = nb.get_node();
double w = nb.get_w();
int cid = C[nei];
if(nid==nei){
selfw+=w;
}else{
toC[cid]+= w;
}
}
double dQold = _calc_dQmod( toC[ncid], deg[nid], D[ncid] - deg[nid], selfw, M );
double dQ = 0;
for(int j = 0;j<neighbourNum;j++){
Neighbour nb = G.get_kth_neighbour(nid, j);
int nei = nb.get_node();
int cid = C[nei];
if(nei==nid) continue;
double dQc=_calc_dQmod( toC[cid], deg[nid], D[cid] - deg[nid]*(double)!!(ncid==cid), selfw, M )-dQold;
if( dQc<dQ ) continue;
newcid = cid;
dQ = dQc;
}
if(dQ< 0) continue;
if( ncid==newcid ) continue;
D[ncid]-=deg[nid];
D[newcid]+=deg[nid];
C[nid] = newcid;
isupdated = true;
}
itNum++;
}while( (isupdated == true) & (itNum<=100) );
// remove redundant cp
std::vector<int> labs;
for(int i=0;i<N;i++){
int cid = -1;
int labsize = (int)labs.size();
for(int j=0;j<labsize;j++){
if(labs[j]==C[i]){
cid = j;
break;
}
}
if (cid<0) {
labs.push_back(C[i]);
cid = (int)labs.size()-1;
}
C[i] = cid;
}
}
void Divisive::_louvain_core(
const Graph& G,
vector<int>& C,
const double M,
mt19937_64& mtrnd
){
Graph newG = G;
vector<int>Zt = C;
vector<int>Ct = C;
unsigned int prevGraphSize = (int) C.size();
double Qbest = _calc_Qmod(newG, Zt, M);
do{
prevGraphSize = newG.get_num_nodes();
_modularity_label_switching(newG, Zt, M, mtrnd);
double Qt = _calc_Qmod(newG, Zt, M);
Graph g;
_coarsing(newG, Zt, g);
newG = g;
// update C
// Ct = Ct*Zt;
int Ctsize = (int) Ct.size();
for(int i = 0;i<Ctsize;i++){
Ct[i] = Zt[ Ct[i] ];
}
vector<int> tmp(newG.get_num_nodes(),0);
for(int i = 0;i<newG.get_num_nodes();i++){
tmp[i] = i;
}
Zt = tmp;
if(Qt>Qbest){
C = Ct;
Qbest = Qt;
}
}while( newG.get_num_nodes()!= prevGraphSize);
}
void Divisive::_louvain(
const Graph& G,
const int num_of_runs,
vector<int>& C,
mt19937_64& mtrnd
){
int N = G.get_num_nodes();
vector<int> tmp(N,0);
C = tmp;
double M = 0;
for(int i =0;i<N;i++){
C[i] = i;
M+=G.wdegree(i);
}
M = M / 2;
double Q = -1;
vector<int> cbest;
for (int i = 0; i < num_of_runs; i++) {
vector<int> ci = C;
double Qi = 0.0;
_louvain_core(G, ci, M, mtrnd);
Qi = _calc_Qmod(G, ci, M);
if (Qi > Q) {
Q = Qi;
cbest = ci;
}
}
C = cbest;
}
| 2cc974f159f43aeb848cd51ef08fc04a711a4b80 | [
"HTML",
"reStructuredText",
"Markdown",
"Makefile",
"Python",
"Text",
"C++"
] | 57 | Python | lgaalves/core-periphery-detection | 0eaaa0cde08d0e59fba5442fd25eae74f663717e | 00d100b6dfafee11606daa3b0f496a6484c030e6 |
refs/heads/master | <file_sep>/*
* S/Key OTP Calculator (RFC 2289)
*
* (c) <NAME> 2009
* v1.0.0 2009-07-20 (first release)
* v1.1.0 2009-09-08 cygwin bugfixes
* v1.1.1 2018-03-24 minor code cleanup (current release)
*
* compile with:
* gcc -o skey skey.c -lmhash
*
* usage: skey [otp-<hash>] <rounds> <seed>
*
* You will be prompted for your secret password, and then skey will print the
* one-time password in hexadecimal and six-word form.
*
* For restrictions regarding usage and distribution, see license at the end of
* this file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mhash.h>
#include <string.h>
#include <termios.h>
#include "dict.h"
#include "version.h"
/*
* Read a password from the terminal, after printing prompt.
* After calling, secret is allocated to the correct size, and that size is
* stored in secret_sz.
* In case of badness, prints a helpful message and returns with secret set to
* NULL.
*/
void skey_getpass(const char *prompt, char **secret, size_t *secret_sz)
{
char c;
size_t alloc = 256;
struct termios old, new;
*secret = (char*)malloc(alloc);
*secret_sz = 0;
printf("%s", prompt);
/*
* Disable echoing input to screen. This stanza is from
* http://www.gnu.org/software/libc/manual/html_node/getpass.html
* because getpass(3) is missing on many systems, notably Cygwin.
*/
tcgetattr(fileno(stdin), &old);
new = old;
new.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), TCSAFLUSH, &new);
while (!feof(stdin) && !ferror(stdin)) {
c = getc(stdin);
if ((*secret_sz) + 1 == alloc) {
*secret = (char*)realloc(*secret, alloc+=256);
if (*secret == NULL) {
perror("error allocating password buffer");
tcsetattr(fileno(stdin), TCSAFLUSH, &old);
return;
}
}
if (c == EOF || c == '\n') {
(*secret)[*secret_sz] = '\0';
tcsetattr(fileno(stdin), TCSAFLUSH, &old);
return;
} else {
(*secret)[(*secret_sz)++] = c;
}
}
// can't get here
return;
}
/*
* fold the hash down to 64 bits
* After calling, the memory at output will point to 8 bytes.
*/
void hash_finalize(int hash, char *input, char **output)
{
int i, j, oversize;
*output = (char*) malloc(8);
oversize = mhash_get_block_size(hash) - 8;
for (i = 0; i < oversize; i++) {
input[(i%8)] ^= input[(i+8)];
}
if (hash == MHASH_SHA1) {
// each group of 4 bytes has the bytes in reverse order
// wtf.
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
(*output)[i*4+j] = input[(i+1)*4-j-1];
}
}
} else {
for (i = 0; i < 8; i++) {
(*output)[i] = input[i];
}
}
}
/*
* Run the specified hash on the input the given number of times.
* After each round, the hash output is folded to 64 bits using hash_finalize().
*/
int do_hash(int hash, int rounds, char *input, size_t input_sz, char **output, size_t *output_sz)
{
MHASH h;
char *to_free;
while (--rounds > -1) {
h = mhash_init(hash);
mhash(h, input, input_sz);
input = (char *) mhash_end(h);
to_free = input;
hash_finalize(hash, input, &input);
free(to_free);
input_sz = 8;
}
*output = input;
*output_sz = 8;
return 0;
}
/*
* Convert the hash into a hexidecimal string.
*/
void hash_hex(char *input, size_t input_sz, char **output, size_t *output_sz)
{
size_t i;
*output = (char*) malloc(2 * input_sz + 1);
for (i = 0; i < input_sz; i++) {
sprintf((*output) + 2*i, "%.2x", (unsigned char) input[i]);
}
*output_sz = 2 * input_sz;
}
/*
* Split a byte stream of inputsz bytes into chunks of chunkbits number of bits.
* The last chunk may be right-padded with zero bits if there aren't enough
* input bytes.
*
* The chunks[] array is expected to have enough storage allocated.
*
* i.e. if asked to convert 2 bytes to 7-bit chunks:
* byte 0 byte 1
* 01101101 01001101
* 0110110 1010011 0100000
* chunk 0 chunk 1 chunk 2
*/
void data_chunk(int chunkbits, int inputsz, void *hash, unsigned long chunks[])
{
int in, out, bits_in, bits_out, bit;
in = 0;
out = 0;
bits_in = 0;
bits_out = 0;
chunks[0] = 0;
/* dribble bits into buckets, making sure to change the buckets when
* they become full */
while (1) {
bit = (*((unsigned char *) hash + in) & (1 << (7 - bits_in))) >> (7 - bits_in);
chunks[out] |= bit << ((chunkbits - 1) - bits_out);
bits_in++;
bits_out++;
if (bits_in == 8) {
bits_in = 0;
in++;
if (in == inputsz) {
break;
}
}
if (bits_out == chunkbits) {
bits_out = 0;
out++;
chunks[out] = 0;
}
}
}
/*
* Break the hash into 11-bit chunks so we can turn the hash into dictionary
* words. Additionally, puts a checksum in the last two bits of chunk #5 as per
* RFC 2289.
*/
void hash_break(void *hash, unsigned long chunks[6])
{
int i, byte, checksum;
data_chunk(11, 8, hash, chunks);
checksum = 0;
for (i = 0; i < 8; i++) {
byte = *((unsigned char *) hash + i);
checksum += byte & 0x03;
checksum += (byte & 0x0C) >> 2;
checksum += (byte & 0x30) >> 4;
checksum += (byte & 0xC0) >> 6;
}
chunks[5] |= checksum & 3;
}
int main(int argc, char **argv)
{
char *input, *output, *secret, *final, *hashfunc_str;
int rounds, ret, hashfunc;
size_t input_sz, output_sz, secret_sz, final_sz;
unsigned long chunks[6];
if (argc < 3) {
fprintf(stderr, "s/key v%u.%u", VERSION_MAJOR, VERSION_RELEASE);
if (VERSION_BUILD != 0)
fprintf(stderr, ".%u", VERSION_BUILD);
fprintf(stderr, " (c) 2009 by <NAME>\n");
fprintf(stderr, "usage: %s [otp-<hash>] <rounds> <seed>\n", argv[0]);
return 1;
}
if (argc > 3) {
hashfunc_str = argv[1];
argv[1] = argv[2]; /* shift args */
argv[2] = argv[3];
if (strcmp(hashfunc_str, "otp-md4") == 0) {
hashfunc = MHASH_MD4;
} else if (strcmp(hashfunc_str, "otp-md5") == 0) {
hashfunc = MHASH_MD5;
} else if (strcmp(hashfunc_str, "otp-sha1") == 0) {
hashfunc = MHASH_SHA1;
} else {
fprintf(stderr, "%s: unknown algorithm specified: %s\n",
argv[0], hashfunc_str);
return 1;
}
} else {
hashfunc = MHASH_MD5;
}
ret = sscanf(argv[1], "%d", &rounds);
if (ret < 1 || rounds < 0) {
perror("invalid number of rounds specified");
return 1;
}
input_sz = strlen(argv[2]);
/* Use our version of getpass() */
skey_getpass("Secret: ", &secret, &secret_sz);
/* concatenate secret onto the end of the seed */
input = (char*) malloc(input_sz + secret_sz + 1);
strncpy(input, argv[2], input_sz);
strncpy(input + input_sz, secret, secret_sz);
input_sz += secret_sz;
input[input_sz] = '\0';
/* run the specified number of hash rounds */
do_hash(hashfunc, rounds + 1, input, input_sz, &output, &output_sz);
/* get a hexadecimal string */
hash_hex(output, output_sz, &final, &final_sz);
final[final_sz] = '\0';
/* break hash into word chunks */
hash_break(output, chunks);
printf("%s\n%s %s %s %s %s %s\n", final, dict[chunks[0]],
dict[chunks[1]], dict[chunks[2]], dict[chunks[3]],
dict[chunks[4]], dict[chunks[5]]);
return 0;
}
/*
Copyright (c) 2009, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of <NAME> nor the names of other
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
vim: sts=8 ts=8 noexpandtab
*/
<file_sep>CFLAGS+=-Wall -Wextra -Wpedantic
all: skey skey_read
skey: skey.o
$(CC) $(LDFLAGS) -o skey skey.o -lmhash
skey.o: skey.c dict.h
$(CC) $(CFLAGS) -c -o skey.o skey.c
skey_read: skey_read.o
$(CC) $(LDFLAGS) -o skey_read skey_read.o
skey_read.o: skey_read.c dict.h
$(CC) $(CFLAGS) -c -o skey_read.o skey_read.c
clean:
rm -f skey skey_read *.o *~
<file_sep>/*
* S/Key Reader
*
* by <NAME> 8/22/2009
*
* Reads in a 6-word RFC-2289-style OTP and outputs the corresponding
* hexadecimal hash string.
*
* usage: skey_read <word1> <word2> <word3> <word4> <word5> <word6>
*
* If run with fewer than 6 arguments, you will be promped to type the six
* words at the terminal.
*
* For restrictions regarding usage and distribution, see license at the end of
* this file.
*/
#include <stdio.h>
#include <string.h>
#include "dict.h"
#include "version.h"
int dict_search(char *word)
{
int i;
char word_copy[5];
for (i = 0; i < 5 && word[i] > 0; i++) {
word_copy[i] = word[i];
if (word[i] <= 'z' && word[i] >= 'a') {
word_copy[i] += ('A' - 'a');
} else if (word[i] < 'A' || word[i] > 'z' || (word[i] > 'Z' && word[i] < 'a')) {
fprintf(stderr, "char out of bounds: %c\n", word[i]);
return -2;
}
}
word_copy[i] = '\0';
for (i = 0; i < 2048; i++) {
if (strcmp(dict[i], word_copy) == 0) {
return i;
}
}
return -1;
}
int combine_chunks(int chunkbits, int num_chunks, void *combined, unsigned long chunks[])
{
int in, out, bits_in, bits_out;
unsigned long curr_chunk;
out = 0;
bits_out = 7;
*((unsigned char *)combined + out) = 0;
for (in = 0; in < num_chunks; in++) {
curr_chunk = chunks[in];
for (bits_in = chunkbits - 1; bits_in >= 0; bits_in--)
{
*((unsigned char *)combined + out) |= (curr_chunk & (1 << bits_in)) >> bits_in << bits_out;
bits_out--;
if (bits_out == -1) {
out++;
bits_out = 7;
*((unsigned char *)combined + out) = 0;
}
}
}
return out;
}
int main(int argc, char **argv)
{
int i, j, out;
int temp;
unsigned char combined[9]; // need two bits form #9
unsigned long chunks[6];
char words[6][5];
if (argc == 2 && (
strcmp(argv[1], "--help") == 0
|| strcmp(argv[1], "-h") == 0
)) {
fprintf(stderr, "s/key read v%u.%u", VERSION_MAJOR,
VERSION_RELEASE);
if (VERSION_BUILD != 0)
fprintf(stderr, ".%u", VERSION_BUILD);
fprintf(stderr, " (c) 2009 by <NAME>\n");
fprintf(stderr, "usage: %s [<word1> <word2> <word3> <word4> "
"<word5> <word6>]\n", argv[0]);
return -1;
}
if (argc < 7) {
fprintf(stderr, "enter s/key: ");
scanf("%4s %4s %4s %4s %4s %4s", words[0], words[1], words[2], words[3], words[4], words[5]);
} else {
for (i = 0; i < 6; i++) {
for (j = 0; j < 5 && argv[i+1][j]; j++)
words[i][j] = argv[i+1][j];
words[i][j] = '\0';
}
}
for (i = 0; i < 6; i++) {
temp = dict_search(words[i]);
if (temp < 0) {
fprintf(stderr, "unknown word \"%s\" in input\n", words[i]);
return -2;
}
chunks[i] = (unsigned long) temp;
}
out = combine_chunks(11, 6, (void*) combined, chunks);
/*
for (i = 0; i < 6; i++) {
printf("chunk %d: %lu:\t", i, chunks[i]);
for (j = 10; j >= 0; j--) {
printf("%lu%s", (chunks[i] & (1 << j)) >> j, (((i*11 + (11-j)) % 8) == 0) ? " " : "" );
}
printf("\n");
}
printf("\ncombined:");
for (i = 0; i <= out; i++) {
printf(" ");
for (j = 7; j >= 0; j--) {
printf("%d", (combined[i] & (1 << j)) >> j);
}
}
printf("\n");
*/
for (i = 0; i < 8; i++) {
printf("%.2x", combined[i]);
}
printf("\n");
return 0;
}
/*
Copyright (c) 2009, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of <NAME> nor the names of other
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
vim: sts=8 ts=8 noexpandtab
*/
<file_sep>#ifndef WRF_SKEY_VERSION_H
#define WRF_SKEY_VERSION_H
#define VERSION_MAJOR 1
#define VERSION_RELEASE 1
#define VERSION_BUILD 1
#endif
| 5c813d0d75f3e1ce7567d3b19d12687621295c54 | [
"C",
"Makefile"
] | 4 | C | wfraser/skey | 44baa99ca69ff6bede1c93c32a5e3605bdd32cd2 | bba21a357a924ef0447deb198051ed310a63b6f2 |
refs/heads/master | <repo_name>go1com/util_publishing_event<file_sep>/EventPipelineInterface.php
<?php
namespace go1\util\publishing\event;
interface EventPipelineInterface
{
/**
* Embed the additional data to the given event
*
* @param EventInterface $event
*/
public function embed(EventInterface $event): void;
}
<file_sep>/EventHandler.php
<?php
namespace go1\util\publishing\event;
use go1\util\queue\Queue;
use Exception;
class EventHandler implements EventHandlerInterface
{
public function process(EventInterface $event, array $pipelines = []): EventInterface
{
$explode = explode('.', $event->getSubject());
$isLazy = isset($explode[0]) && ('do' == $explode[0]);
if (strpos($event->getSubject(), '.update') && !$isLazy) {
$validKeys = array_filter($event->getPayload(), function ($value, $key) {
return (in_array($key, ['id', 'original']) && $value);
}, ARRAY_FILTER_USE_BOTH);
if (count($validKeys) !== 2) {
throw new Exception("Missing entity ID or original data.");
}
}
if ($service = getenv('SERVICE_80_NAME')) {
$event->addContext(Event::CONTEXT_APP, $service);
}
$event->addContext(Event::CONTEXT_TIMESTAMP, time());
!empty($pipelines) && $event->embed($pipelines);
return $event;
}
}
<file_sep>/Event.php
<?php
namespace go1\util\publishing\event;
class Event implements EventInterface
{
const CONTEXT_APP = 'app';
const CONTEXT_ACTOR_ID = 'actor_id';
const CONTEXT_REQUEST_ID = 'request_id';
const CONTEXT_TIMESTAMP = 'timestamp';
protected $subject;
protected $payload;
protected $context = [];
public function __construct($payload, string $routingKey, array $context = [])
{
$this->subject = $routingKey;
$this->payload = is_scalar($payload) ? json_decode($payload, true) : (is_object($payload) ? ((array) $payload) : $payload);
$this->context = $context;
if (!isset($this->payload['embedded'])) {
$this->payload['embedded'] = [];
}
}
public function getSubject(): string
{
return $this->subject;
}
public function getPayload(): array
{
return $this->payload;
}
public function getContext(): array
{
return $this->context;
}
public function addContext(string $key, $value): void
{
if (!isset($this->context[$key])) {
$this->context[$key] = $value;
}
}
public function addPayloadEmbed(string $key, $value): void
{
$this->payload['embedded'][$key] = $value;
}
public function embed(array $pipelines = []): void
{
/**
* @var EventPipelineInterface $pipeline
*/
foreach ($pipelines as $pipeline) {
$pipeline->embed($this);
}
}
}
<file_sep>/EventHandlerInterface.php
<?php
namespace go1\util\publishing\event;
/**
* Interface EventHandlerInterface
*/
interface EventHandlerInterface
{
/**
* Formatted the given event before adding to the queue
*
* @param EventInterface $event
* @param array $pipelines
* @return EventInterface
*/
public function process(EventInterface $event, array $pipelines): EventInterface;
}
<file_sep>/tests/EventHandlerTest.php
<?php
namespace go1\util\publishing\event\tests;
use go1\util\publishing\event\Event;
use go1\util\publishing\event\EventHandler;
use go1\util\publishing\event\EventPipeline;
class EventHandlerTest extends PublishingEventTestCase
{
public function test()
{
$event = new Event([], 'routingKey');
$handler = new EventHandler();
$newEvent = $handler->process($event);
$this->assertArrayHasKey('embedded', $newEvent->getPayload());
$this->assertArrayHasKey('timestamp', $newEvent->getContext());
}
public function testUpdateSuccess()
{
$payload = ['id' => 1, 'user' => 1];
$payload['original'] = ['id' => 1, 'user' => 2];
$event = new Event($payload, 'message.update');
$newEvent = (new EventHandler)->process($event);
$this->assertArrayHasKey('embedded', $newEvent->getPayload());
$this->assertArrayHasKey('timestamp', $newEvent->getContext());
}
public function testUpdateFail()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage("Missing entity ID or original data.");
$payload = ['id' => 1, 'user' => 1];
$event = new Event($payload, 'message.update');
(new EventHandler)->process($event);
}
public function testPipes()
{
$pipe = new EventPipeline('type', ['data' => 1]);
$event = new Event([], 'routingKey');
$newEvent = (new EventHandler)->process($event, [$pipe]);
$this->assertArrayHasKey('timestamp', $newEvent->getContext());
$payload = $newEvent->getPayload();
$this->assertArrayHasKey('embedded', $payload);
$this->assertEquals(['type' => ['data' => 1]], $payload['embedded']);
}
public function testContextService()
{
putenv('SERVICE_80_NAME=service');
$event = new Event([], 'routingKey');
$newEvent = (new EventHandler)->process($event);
$context = $newEvent->getContext();
$this->assertArrayHasKey('timestamp', $context);
$this->assertEquals('service', $context[Event::CONTEXT_APP]);
}
}
<file_sep>/EventPipeline.php
<?php
namespace go1\util\publishing\event;
class EventPipeline implements EventPipelineInterface
{
protected $type;
protected $embeds;
public function __construct(string $type, array $embeds = [])
{
$this->type = $type;
$this->embeds = $embeds;
}
public function setEmbeds(array $embeds): void
{
$this->embeds = $embeds;
}
public function embed(EventInterface $event): void
{
if ($this->type && !empty($this->embeds)) {
$event->addPayloadEmbed($this->type, $this->embeds);
}
}
}
<file_sep>/EventInterface.php
<?php
namespace go1\util\publishing\event;
interface EventInterface
{
/**
* Get the event subject
*
* @return string
*/
public function getSubject(): string;
/**
* Get the event context
*
* @return string
*/
public function getContext(): array;
/**
* Get the event payload
*
* @return string
*/
public function getPayload(): array;
/**
* Add a value to the context by the given key
*
* @param string $key
* @param $value
*/
public function addContext(string $key, $value): void;
/**
* Add a value to the payload embedded by the given key
*
* @param string $key
* @param $value
*/
public function addPayloadEmbed(string $key, $value): void;
/**
* Embed the event payload by the given pipelines
*
* @param array $pipelines
*/
public function embed(array $pipelines): void;
}
<file_sep>/tests/EventPipelineTest.php
<?php
namespace go1\util\publishing\event\tests;
use go1\util\publishing\event\Event;
use go1\util\publishing\event\EventPipeline;
class EventPipelineTest extends PublishingEventTestCase
{
public function test()
{
$event = new Event([], 'routingKey');
$pipe = new EventPipeline('type', ['id' => 100]);
$pipe->embed($event);
$payload = $event->getPayload();
$this->assertEquals(['type' => ['id' => 100]], $payload['embedded']);
}
public function testSetEmbed()
{
$event = new Event([], 'routingKey');
$pipe = new EventPipeline('type');
$pipe->setEmbeds(['id' => 100]);
$pipe->embed($event);
$payload = $event->getPayload();
$this->assertEquals(['type' => ['id' => 100]], $payload['embedded']);
}
}
<file_sep>/README.md
Publishing Event [](https://travis-ci.org/go1com/util_publishing_event)
====
- Provide the functionality to format the event message.
- Embed the data to the message depend on the provided pipelines
## Usage
```
$event = new Event($payload, 'message.update');
$pipes = [];
........
$pipes[] = new EventPipeline('type', ['id' => 100]);
$newEvent = (new EventHandler)->process($event, $pipes);
```
| 5976f9037977ad85eee889b1388b53cb98be6a29 | [
"Markdown",
"PHP"
] | 9 | PHP | go1com/util_publishing_event | b16fdd529a3c854b19c7a4abf9cf191464860d00 | 6a5f911115f4295b389c570c80b2d386577b0cde |
refs/heads/main | <repo_name>i19fukuda/FxOpenTimeTest<file_sep>/views/NoteRect.java
package views;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class NoteRect {
//final private int RECT_SIZE = 48;
private Rectangle noteRect;
private long noteId;
private long noteLength;
private int notePich;
private long noteStartTick;
private boolean isControlDown = false;
public NoteRect(int notePich, long noteLength, long noteStartTick){
System.out.println("noteRect made");
System.out.println(notePich + " " + noteLength + " " + noteStartTick);
this.notePich = notePich;
this.noteLength = noteLength;
this.noteStartTick = noteStartTick;
this.noteId = System.currentTimeMillis();
this.noteRect = new Rectangle();
this.noteRect.setHeight(20);
this.noteRect.setWidth(noteLength);
this.noteRect.setFill(Color.BLACK);
this.noteRect.setOnMouseClicked(event -> clicEventHandler(event));
//this.noteRect.setOnMouseDragged(event -> dragEventHandler(event));
this.noteRect.setOnKeyPressed(event -> keyEventHandler(event));
}
private void clicEventHandler(MouseEvent event){
if(event.getClickCount() == 1){
this.noteRect.setFill(Color.RED);
if(this.isControlDown){
System.out.println("ctrl");
this.noteRect.setFill(Color.BLUE);
this.noteLength +=50;
this.noteRect.setWidth(this.noteLength);
}
}
}
private void keyEventHandler(KeyEvent event){
if(event.isControlDown()){
this.isControlDown = true;
} else this.isControlDown = false;
}
public long getNoteId(){
return this.noteId;
}
public void setNoteId(long id){
this.noteId =id;
}
public long getnoteLength(){
return this.noteLength;
}
public void setnoteLength(long length){
this.noteLength = length;
}
public int getNotePich(){
return this.notePich;
}
public void setNotePich(int pich){
this.notePich = pich;
}
public Rectangle getRect(){
return this.noteRect;
}
public long getnoteStartTick(){
return this.noteStartTick;
}
}
<file_sep>/views/TrackBox.java
package views;
public class TrackBox {
}
<file_sep>/README.md
# FxOpenTimeTest
授業で作るアプリの起動時間を測定するためのプログラムです.
自分の環境以外でどれぐらい時間がかかるのか知りたいので...
特にそれと言って測定結果が出るようにはしていません.
# 実行方法
GitとJavaFxが実行できる環境で実行してください.
`git clone https://github.com/i19fukuda/FxOpenTimeTest.git`
`cd FxOpenTimeTest`
`javac Main.java`
または
`javac Main00.java`
`java Main`
または
`java Main00`
ウィンドウが立ち上がれば成功です. | 7e76903d77f00711d6831358c077c1f75a0bc539 | [
"Markdown",
"Java"
] | 3 | Java | i19fukuda/FxOpenTimeTest | c6aa1f3c3876d7690e73e52a243c6b864d4f125d | 6584915911ee26a79454b09a48a9781ead33ff6c |
refs/heads/master | <file_sep>class Animal {
constructor() {
this.name = name
this.isMammal = this.isMammal
}
}
class Ape {
constructor() {
function tampil() {
yell()
return Auooo
}
}
}
class Flog {
constructor() {
function musik() {
jump ()
return hiphop
}
}
}<file_sep>function login (email, password) {
const user = "<EMAIL>"
const pass = "135"
function gohome() {
document.write("<h2>" + "anda berhasil login" + "</h2>")
}
function backlogin() {
document.write( "<h1>" + "anda gagal login...silahkan ulang lagii..!" + "</h1>")
}
if (user == email && password == pass) {
return gohome()
} else if (email != user || password != pass) {
return backlogin ()
} else if (email != user && password != pass) {
return backlogin ()
} else {
document.write('anda gagal login...!');
}
}
let email2 = prompt ('silahkan masukkank email anda :')
let password2 = prompt ('silahkan masukkan password anda :')
login (email2, password2)<file_sep>var kodeUnix = [23, 89,67,29,192,6,2,129,21,872,891,901,70,61,78,62,32,90,90];
let total = kodeUnix.map(a => a - 50 + kodeUnix.length)
.filter(a => a < 20)
.reduce((a, b) => (a + b))
console.log(total); | 4cfa447702b3e51bc41c205a638a1046c1c8a569 | [
"JavaScript"
] | 3 | JavaScript | erwinbaee/Evaluasi_sprint3 | fb09d999482cbdb1ae1a037ce8ee913c494e72e4 | 6ebbed5ef13cf0eca583c41c634f5dd30c3a1ada |
refs/heads/master | <file_sep>import { Router } from 'express';
const router = Router();
//TODO: Add route configs here.
export default router;
| 49c2e02c0d5db354ddb4a6774955172737f9c8f5 | [
"JavaScript"
] | 1 | JavaScript | tsmarco/marco-tsang | 7a7229360b86569f97c10a7d68cf2320177b60f2 | 01574bf3ab25bda0073c77f033d0f4febd760a55 |
refs/heads/master | <repo_name>maru718jp/program_c<file_sep>/2020study1.c
/*
2020study1.c
2つ歯車をかみ合わせて使用するとき、主の歯数をA、従の歯数をBとして入力して、
主が10000回、回転するときに同じ歯同士がかみ合う回数とかみ合う率を求める
プログラムを作れ。A Bに0を入れると終了する。
*/
#include <stdio.h>
//#include <Windows.h>
main (){
#define PATTERN 10000
while(1){
int ga;
int gb;
int gacount=1;
int gbcount=1;
int lap_count=0;
long i;
printf("------------------------------\n");
printf("gear A B =");
scanf("%d %d",&ga,&gb);
if (ga==0) break;
for (i=1;i <=PATTERN*ga ;i++)
{
gacount= ((i % ga)+1);// printf("gacount=%d",gacount);
gbcount= ((i % gb)+1);// printf(" gbcount=%d\n",gbcount);
//Sleep(500);
if (gacount==1 && gbcount==1)
{
lap_count++;
}
}
printf("lap times=%d /%d \n",lap_count,PATTERN);
printf("lap %=%.2f%%\n\n",(double)lap_count/PATTERN*100);
}
printf("end");
return 0;
}<file_sep>/2020study4.c
/*
2020study4.c
周波数frq、表示時間time、位相pheseを入力して大きさ1のsin波形をかけ.
*/
#include <stdio.h>
#include <math.h>
#define CYCLE 50
#define DIV 20
double frq;
double time;
double phase;
double sdata;
int main()
{
int i, j;
int data;
while(1)
{
int grf[DIV][CYCLE] = {0};
//do
//{
printf("Input frequency --->");
scanf("%lf", &frq);
printf("Input times --->");
scanf("%lf", &time);
printf("Input phase --->");
scanf("%lf", &phase);
//}while()
//---------------------------------
for (i = 0; i < CYCLE; i++)
{
sdata = (2.0 * 3.14 * frq * i * time / CYCLE) + (3.14 * phase / 180.0);
//printf("sdata=%0.2f ",sdata);
data = (int)(sin(sdata) * 10);
//data = (int)(sin(sdata) * 10);
//printf("i=%d data=%d \n",i, data);
grf[DIV / 2 - data][i] = 1;
//getchar();
}
//-------------------------------
for (i = 0; i < DIV; i++)
{
for (j = 0; j < CYCLE; j++)
{
//printf("%d",grf[i][j]);
(grf[i][j] == 0) ? printf(" ") : printf("*");
}
printf("\n");
}
}
}<file_sep>/prog_6_21.c
/*
prog_6_21.c
値渡し
*/
#include <stdio.h>
int sum(int x,int y);
//-----main routine------
int main()
{
int a=1,b=2;
printf("%d",sum(3,5));
return;
}
//--- sub routine---
int sum(int x, int y){
return x+y;
}
<file_sep>/prog_6_4.c
/*
prog_6_4.c
*/
#include <stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Input factorial count --->");
scanf("%d", &n);
printf("n!=%d\n", factorial(n));
return 0;
}
int factorial(int n)
{
int fact;
if (n == 0)
{
return 1;
}
else
{
fact = n * factorial(n-1);
}
return fact;
}
<file_sep>/2020study2.c
/*
① 入力は-999.9~999.9までの数値を入力する。はずれは再入力する。
② 入力に入力した文字を昇順ソートして表示する。
⑤ 入力した数値が10個を超えたら古い入力を1つずつすてる
*/
#include <stdio.h>
double val[10];
double ind, temp;
int count = 0;
int i, flag;
int main()
{
while (1)
{
do
{
printf("Input Nnumber -->");
scanf("%lf", &ind);
} while (ind < -99.9 || ind > 99.9);
if (count > 9)
{
for (i = 0; i < 9; i++)
{
val[i] = val[i + 1];
}
val[9] = ind;
count = 9;
}
else
{
val[count] = ind;
}
count++;
//sort
do
{
flag = 0;
for (i = 0; i < count - 1; i++)
{
if (val[i] > val[i + 1])
{
temp = val[i];
val[i] = val[i + 1];
val[i + 1] = temp;
flag = 1;
}
}
} while (flag == 1);
for (i = 0; i < count; i++)
printf("No [%d] %10.1f \n",i+1, val[i]);
}
return 0;
}<file_sep>/2020study6.c
/*
2020study6.c
1 10進数を入力してそれを2進数と16進数に変換せよ。繰り返し入力する。
2 10進数は0-65536の範囲、範囲外は再入力する。
3 変換する基数を2(2進数)、16(16進数)で入力する。
NULLの場合は終了する。
4 10進数に0を入れたら終了する。
=============================================================
Input Decimal --->100000
ERROR input again !!
Input Decimal --->129
What base number ( B or H ) ? --->B
Binary Number = 1000001
=============================================================
Input Decimal --->1023
What base number ( B or H )? --->H
Hexadecimal = 3FF
=============================================================
Input Decimal --->0
*/
#include <stdio.h>
int dec;
int base;
char moji;
int sel, mod, i, j, k;
const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int main()
{
while (1)
{
int val[10] = {0};
do
{
printf("Input Decimal --->");
scanf("%d", &dec);
if (dec < 0 || dec > 65536)
printf("ERROR input again !! \n");
} while (dec < 0 || dec > 65536);
if (dec == 0)
break;
printf("What base number-->");
scanf("%c", &moji);
//dec2bin
if (moji == 'b')
{
i = 0;
do
{
val[i] = dec % 2;
dec /= 2;
i++;
} while (dec != 0);
printf("Binary number =");
for (j = i-1; j >= 0; j--)
(val[j] == 0) ? putchar('0') : putchar('1');
}
//
if (moji =='h')
{
i = 0;
do
{
val[i] = dec % 16;
dec /= 16;
i++;
} while (dec != 0);
printf("Hexadecimal number =");
for (j = i-1; j >= 0; j--)
printf("%c", hex[val[j]]);
}
printf("\n");
}
}
<file_sep>/2020study3.c
/*
2020study3.c
2つの整数A,Bを入力してA、Bの公約数を表示せよ。
<条件>
・入力数値が10000を超える場合は、再入力を行う。
・公倍数1を除く
・出力は1行10個ずつで8文字間隔にする。
*/
#define MAX 10000
#define A 0
#define B 1
#include <stdio.h>
main(){
int data[2]={0};
int i,j;
int less;
int row;
while(1){
do{
printf("Input A & B --->");
scanf("%d %d",&data[A],&data[B]);
}while( data[A]<0 || data[A]>MAX || data[B]<0 || data[B]>MAX);
less=data[A];
less=(data[A]<data[B])? data[A]:data[B];
row=0;
for (i=2; i<=less; i++)
{
if( (data[A] % i == 0) && (data[B] % i == 0) )
{
printf("%10d ",i);
row++;
row %= 5;
if (!row) putchar('\n');
}
}
putchar('\n');
}
return 0;
}
<file_sep>/2020study7.c
/*
2020study5c
10進数を入力して2~16進数にに基数変換せよ。繰り返し入力する。
1. 10進数は0-65536の範囲とする、範囲外は再入力する。
2. を入れたら終了する。
。
=============================================================
Input Decimal --->100000
ERROR input again !!
Input Decimal --->129
What base number ( B or H ) ? --->B
Binary Number = 1000001
=============================================================
Input Decimal --->1023
What base number ( B or H )? --->H
Hexadecimal = 3FF
=============================================================
Input Decimal --->0
*/
#include <stdio.h>
int dec;
int base;
int sel, mod, i, j, k;
const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int main()
{
while (1)
{
int val[10] = {0};
do
{
printf("Input Decimal --->");
scanf("%d", &dec);
if (dec < 0 || dec > 65536)
printf("ERROR input again !! \n");
} while (dec < 0 || dec > 65536);
if (dec == 0)
break;
printf("What base number-->");
scanf("%d", &base);
i = 0;
do
{
val[i] = dec % base;
dec /= base;
i++;
} while (dec != 0);
printf(" Number =");
for (j = i - 1; j >= 0; j--)
printf("%c", hex[val[j]]);
printf("\n\n");
}
}
| b2caacc62cb5feec16732a748b1333f5b6cb9d28 | [
"C"
] | 8 | C | maru718jp/program_c | 14f646d1afa565ec88f56d8b45f53f64a96d4bd4 | 76a6a0bb4c326a596cd87eede84f50e46c45b115 |
refs/heads/master | <repo_name>johngellert/c-sharp-hello-world<file_sep>/HelloWorld/Vehicles/Car.cs
using System;
namespace HelloWorld.Vehicles
{
public class Car
{
public Car()
{
}
public string year;
public string make;
public string model;
public void Description ()
{
Console.WriteLine("My car is a " + year + " " + make + " " + model);
}
}
}
<file_sep>/HelloWorld/Program.cs
using System;
using HelloWorld.Vehicles;
namespace HelloWorld
{
//// defineing a class
//public class Person
//{
// public string firstName;
// public string lastName;
// public void Introduce()
// {
// Console.WriteLine("My name is " + firstName + " " + lastName);
// }
//}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
byte number = 3;
int count = 10;
float totalPrice = 20.95f;
char character = 'A';
string firstName = "John";
bool isWorking = true;
var someNumber = 3;
var someCount = 10;
var someTotalPrice = 20.95f;
var someCharacter = 'A';
var someFirstName = "John";
var isWorkingWell = true;
Console.WriteLine(number);
Console.WriteLine(count);
Console.WriteLine(totalPrice);
Console.WriteLine(character);
Console.WriteLine(firstName);
Console.WriteLine(isWorking);
Console.WriteLine(someNumber);
Console.WriteLine(someCount);
Console.WriteLine(someTotalPrice);
Console.WriteLine(someCharacter);
Console.WriteLine(someFirstName);
Console.WriteLine(isWorkingWell);
Console.WriteLine("{0} {1}", byte.MinValue, byte.MaxValue); // string that can be used as
// a template, this is called a format string, at run time, the place holders will be replaced
// with the arguments passed in after the format string.
Console.WriteLine("{0} {1}", float.MinValue, float.MaxValue);
const float Pi = 3.14f;
// looking at type conversion
// this is implicit type conversion
// because a byte is smaller than an int, ther would be no data loss
// by converting the types so this can be implicitly converted
byte b = 1; // 00000001 one byte or 8 bits
int i = b; // 00000000 00000000 00000000 00000001 4 bytes or 32 bits
Console.WriteLine(i);
// here we get an error at complie time because there is a chance of data loss.
// cannot implicitly convert int to byte
// in this case there would not be data loss, but the compiler will not do this
// without being told. Must use explicit type conversion or casting
//int integer = 1; // 00000000 00000000 00000000 00000001 4 bytes or 32 bits
//byte by = integer;// 00000001 one byte or 8 bits
// not data loss but cast required
int x = 2; // 00000000 00000000 00000001 00000010 4 bytes or 32 bits
byte y = (byte) x;// 00000010 one byte or 8 bits
Console.WriteLine(y);
// data loss with cast brcause 300 takes more than 1 byte or 8 bits
// some of the bits are lost so s does not output 300 it outputs 44
int r = 300; // 00000000 00000000 00000001 00101100 4 bytes or 32 bits
byte s = (byte) r;
Console.WriteLine(s);
// non-compatible types
// error, cannot implicitly convert type string to int
string numberOne = "6";
//int v = numberOne;
//int q = (int) numberOne; // cannot explicitly convert either
// need to use Convert class.
int v = Convert.ToInt32(numberOne); // convert will list the .NET equivilant to the C# type
// here C# int type is mapped to .NET Int32 type.
Console.WriteLine(v);
Console.WriteLine("operators");
int a = 10;
int c = 3;
Console.WriteLine(a / c); // will output 3 becuase a and be are integers
// if I need a floating piont number, I need to cast a and c to a floating point number
// before the operation
Console.WriteLine((double)a / (double)c);
Person john = new Person();
john.firstName = "John"; // assinging value to objects firstName field
john.lastName = "Smith"; // assigning value to objects lastName field
john.Introduce(); // calling the introduce method
Car johnsCar = new Car();
johnsCar.year = "1997";
johnsCar.make = "Chevy";
johnsCar.model = "K1500";
johnsCar.Description();
// integer array of size 3
// and array is an object so the new key word is needed to allocat space the same
// way when we create an instance of a class.
// size cannot change.
int[] payment = new int[3];
payment[0] = 20;
payment[1] = 16;
payment[2] = 45;
// faster and cleaner to initialize as such
int[] fasterPayment = new int[3] { 20, 16, 45 };
for(int j = 0; i < fasterPayment.Length; j++)
{
Console.WriteLine("Your payment is: {0}",fasterPayment[j]);
}
}
}
} | 0c3a08f814c62c20e5a4c33f613b1c236d322fb1 | [
"C#"
] | 2 | C# | johngellert/c-sharp-hello-world | 1ee3c0216a29f08e7a95cddc764eb32a2eb58404 | 5e09bd7ddf450821873477fb7ec16e9e559fd099 |
refs/heads/main | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFocusGroup : MonoBehaviour
{
private bool testBool;
[SerializeField] GameObject player, testdummy,cursor;
// Start is called before the first frame update
void Start()
{
TargetGroupManager.instance.AddTarget(player,10,1);
TargetGroupManager.instance.AddTarget(cursor,5,1);
}
// Update is called once per frame
void Update()
{/*
if (Input.GetKeyDown(KeyCode.Space))
{
if (testBool)
{
TargetGroupManager.instance.AddTarget(testdummy,1,1);
}
else
{
TargetGroupManager.instance.RemoveTarget(testdummy);
}
testBool = !testBool;
}
*/
}
}
<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
public class MovementTest : MonoBehaviour
{
[SerializeField] private List<MovementExtras> extras = new List<MovementExtras>();
private void OnValidate()
{
extras.Clear();
foreach (var component in GetComponents<Component>())
{
if (component.GetComponent<MovementExtras>())
{
extras.Add(component.GetComponent<MovementExtras>());
}
}
}
private void Start()
{
Debug.Log("Extras Herd");
foreach (var extra in extras)
{
extra.ActionStart();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.LowLevel;
public class FollowCursor : MonoBehaviour
{
// Start is called before the first frame update
/*
* if (Input.GetKeyDown(KeyCode.Space))
MouseOperations.MouseEvent(MouseOperations.MouseEventFlags.LeftUp | MouseOperations.MouseEventFlags.LeftDown);
To simulate mouse press
^
|
nao funciona assim
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.GraphicRaycaster.Raycast.html outra forma
*/
private InputMaster controls;
private SpriteRenderer sp;
[SerializeField] private Sprite idleCursor;
private Vector2 currentMousePos;
private Vector2 _moveAxis;
[SerializeField] private float mouseSpeed;
private void Awake()
{
controls = new InputMaster();
sp = GetComponent<SpriteRenderer>();
}
private void OnEnable()
{
//Cursor.lockState = CursorLockMode.Confined;
controls.Player.RightAnalog.Enable();
controls.Player.RightAnalog.performed += MoveCursorHandler;
}
private void OnDisable()
{
controls.Player.RightAnalog.Disable();
}
private void MoveCursorHandler(InputAction.CallbackContext obj)
{
_moveAxis = controls.Player.RightAnalog.ReadValue<Vector2>();
currentMousePos += _moveAxis * mouseSpeed;
//Mouse.current.position.WriteValueIntoState(currentMousePos, Tstate);
Mouse.current.WarpCursorPosition(currentMousePos);
Mouse.current.MakeCurrent();
//MouseState s = new MouseState();
//s.position = currentMousePos;
//Mouse.current.position.WriteValueIntoState(currentMousePos);
}
void Start()
{
//Cursor.visible = false;
sp.sprite = idleCursor;
currentMousePos = new Vector2(Screen.width/2,Screen.height/2);
}
public void testCLick()
{
Debug.Log("Test CLick worked");
}
// Update is called once per frame
void Update()
{
Cursor.visible = false;
var worldpos = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
transform.position = new Vector3(worldpos.x,worldpos.y,0);
}
}
<file_sep>using UnityEngine;
using Unity;
public class WallRun : MovementExtras
{
public override void ActionStart()
{
base.ActionStart();
Debug.Log("WallRun Extra Worked");
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace KR.Controllers
{
[RequireComponent(typeof(Rigidbody2D), typeof(BoxCollider2D))]
public class Movement : MonoBehaviour
{
private Rigidbody2D rb2d;
private BoxCollider2D collider2d;
private Vector3 startScale;
[Header("Walking Variables")]
[SerializeField]
private Vector2 maxWalkingVelocity2D = new Vector2(4, 0);
[SerializeField] private float stepWalkingSpeed = 0.2f;
[Header("Running Variables")]
[SerializeField]
private Vector2 maxRunningVelocity2D = new Vector2(7, 0);
[SerializeField] private float stepRunningSpeed = 0.5f;
[Header("Air Variables")]
[SerializeField]
private float aircontrol = 0.7f;
private bool canJump;
[SerializeField] private float jumpForce = 5;
[SerializeField] private float gravityNormal = 1;
[SerializeField] private float gravityWall = 0.6f;
[SerializeField] private LayerMask walkable;
[Space]
[Header("Ground Checkers")]
[SerializeField]
private float sensorYOffset = 0;
[SerializeField] private float sensorYDistance = 0.05f;
[SerializeField] private float sensorXThicknessReducer = 0.07f;
private RaycastHit2D groundCheck;
public RaycastHit2D GroundCheck
{
get => groundCheck;
}
[Space]
[Header("WallCheckers")]
[SerializeField]
private float sensorXOffset = 0.02f;
private RaycastHit2D fowardCheck;
public RaycastHit2D FowardCheck
{
get => fowardCheck;
}
private RaycastHit2D backCheck;
public RaycastHit2D BackCheck => backCheck;
[SerializeField] private float sensorXDistance = 0.08f;
public float WallCheckDistance
{
get { return sensorXDistance; }
}
private RaycastHit2D downwardsEdgeCheck;
public RaycastHit2D DownwardsEdgeCheck => downwardsEdgeCheck;
[Space]
[Header("Downwards Checker")]
[SerializeField]
private float downwardsEdgeXOffset = 0;
[SerializeField] private float downwardsEdgeYOffset = 0;
[SerializeField] private float downwardsEdgeDistance = 1.49f;
[Space]
[Header("Edge/Climbing Stuff")]
[SerializeField]
private float climbingCooldown = 0.5f;
[SerializeField] private float hangingMaxTime = 1.5f;
private bool edgeClose;
private Vector3 edgepos;
private bool isHanging;
private float hangingStartTime;
private bool canClimb;
[Space]
[Header("Vault Checker. Its still not working")]
[SerializeField]
private float vaultEdgeXOffset = -0.23f;
[SerializeField] private float vaultEdgeYOffset = -0.24f;
[SerializeField] private float vaultEdgeDistance = 0.6f;
private bool vaultableObjectClose;
private Vector2 vaultpos;
private RaycastHit2D vaultCheck;
public RaycastHit2D VaultCheck => vaultCheck;
[Header("Other Stuff")] private WalkingState playerState;
private WallState playerWallState;
enum WalkingState
{
Grounded,
Air
}
enum WallState
{
None,
FrontWall,
BackWall
}
private void Awake()
{
startScale = transform.localScale;
rb2d = GetComponent<Rigidbody2D>();
collider2d = GetComponent<BoxCollider2D>();
isHanging = false;
canClimb = false;
}
private void OnDrawGizmos()
{
#region GizmosCheckersRegionFloorWall
/*
* groundCheck = Physics2D.BoxCast(
new Vector2(transform.position.x,
transform.position.y - (sensorYDistance / 2) -
(transform.GetComponent<SpriteRenderer>().size.y / 2 * transform.localScale.y) - sensorYOffset),
new Vector2(
(transform.GetComponent<SpriteRenderer>().size.x * transform.localScale.x) -
sensorXThicknessReducer, sensorYDistance),
0,
Vector2.down, 0, walkable);
*/
//GroundChecker
/*
* Gizmos.DrawWireCube(
new Vector3(transform.position.x,
transform.position.y - (sensorYDistance / 2) -
(transform.GetComponent<BoxCollider2D>().size.y / 2 * transform.localScale.y) - sensorYOffset, 0),
new Vector2(
(transform.GetComponent<BoxCollider2D>().size.x * transform.localScale.x) - sensorXThicknessReducer,
sensorYDistance)
);
*/
//GroundChecker
Gizmos.color = Color.red;
Gizmos.DrawWireCube(new Vector2(transform.position.x,
transform.position.y - (sensorYDistance / 2) -
(transform.GetComponent<BoxCollider2D>().size.y / 2 * transform.localScale.y) - sensorYOffset),
new Vector2(
(transform.GetComponent<BoxCollider2D>().size.x * Mathf.Abs(transform.localScale.x)) -
sensorXThicknessReducer, //+((transform.localScale.x > 0) ? -sensorXThicknessReducer : +sensorXThicknessReducer),
sensorYDistance));
//FowardChecker
Gizmos.color = Color.blue;
Gizmos.DrawRay(
new Vector2(
transform.position.x +
(transform.GetComponent<BoxCollider2D>().size.x / 2) * transform.localScale.x +
((transform.localScale.x > 0) ? +sensorXOffset : -sensorXOffset),
transform.position.y),
((transform.localScale.x > 0) ? transform.right : -transform.right) * sensorXDistance);
//BackCheker
Gizmos.color = Color.green;
Gizmos.DrawRay(
new Vector2(
transform.position.x -
(transform.GetComponent<BoxCollider2D>().size.x / 2) * transform.localScale.x +
((transform.localScale.x > 0) ? -sensorXOffset : +sensorXOffset),
transform.position.y),
((transform.localScale.x > 0) ? -transform.right : transform.right) * sensorXDistance);
#endregion
#region GizmosCheckersEdge
//DownwardsPosition ray
Gizmos.color = Color.magenta;
Gizmos.DrawWireCube(
new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +downwardsEdgeXOffset : -downwardsEdgeXOffset),
transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset,
0),
new Vector3(.2f, .2f, .2f)
);
//DownwardsRayDown
Gizmos.DrawLine(new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +downwardsEdgeXOffset : -downwardsEdgeXOffset),
transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset,
0), new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +downwardsEdgeXOffset : -downwardsEdgeXOffset),
transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset,
0) + Vector3.down * downwardsEdgeDistance);
//Foward Edge Ray
/*
Gizmos.color = Color.yellow;
Gizmos.DrawRay(new Vector3(transform.position.x +(transform.GetComponent<BoxCollider2D>().size.x/2 *transform.localScale.x +fowardEdgeXOffset),
transform.position.y +(transform.GetComponent<BoxCollider2D>().size.y/2 *transform.localScale.y +fowardEdgeYOffset),
0),Vector3.right);
*/
#endregion
//Edge
if (edgeClose)
{
Gizmos.DrawWireCube(
edgepos,
new Vector3(.2f, .2f, .2f)
);
}
#region GizmosCheckerVault
//VaultPosition ray
Gizmos.color = Color.red;
Gizmos.DrawWireCube(
new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +vaultEdgeXOffset : -vaultEdgeXOffset),
transform.position.y -
(transform.GetComponent<BoxCollider2D>().size.y / 4) * transform.localScale.y +
vaultEdgeYOffset,
0),
new Vector3(.2f, .2f, .2f)
);
//VaultRayFoward
Gizmos.DrawRay(new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +vaultEdgeXOffset : -vaultEdgeXOffset),
transform.position.y - (transform.GetComponent<BoxCollider2D>().size.y / 4) * transform.localScale.y +
vaultEdgeYOffset,
0), ((transform.localScale.x > 0) ? transform.right : -transform.right) * vaultEdgeDistance);
Gizmos.DrawWireCube(vaultCheck.point, new Vector3(0.2f, 0.2f, 0.2f));
#endregion
}
private void LateUpdate()
{
CheckHanging();
}
private void FixedUpdate()
{
CheckersAndEdge();
}
void CheckersAndEdge()
{
#region CheckEdge
downwardsEdgeCheck = Physics2D.Raycast(new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +downwardsEdgeXOffset : -downwardsEdgeXOffset),
transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset,
0), Vector2.down, downwardsEdgeDistance, walkable);
#endregion
#region CheckersRegionFloorWall
groundCheck = Physics2D.BoxCast(
new Vector2(transform.position.x,
transform.position.y - (sensorYDistance / 2) -
(transform.GetComponent<BoxCollider2D>().size.y / 2 * transform.localScale.y) - sensorYOffset),
new Vector2(
(transform.GetComponent<BoxCollider2D>().size.x * Mathf.Abs(transform.localScale.x)) -
sensorXThicknessReducer, //+((transform.localScale.x > 0) ? -sensorXThicknessReducer : +sensorXThicknessReducer),
sensorYDistance),
0,
Vector2.down, 0, walkable);
fowardCheck = Physics2D.Raycast(
new Vector2(
transform.position.x +
(transform.GetComponent<BoxCollider2D>().size.x / 2) * transform.localScale.x +
((transform.localScale.x > 0) ? +sensorXOffset : -sensorXOffset),
transform.position.y),
((transform.localScale.x > 0) ? Vector3.right : Vector3.left), sensorXDistance, walkable);
backCheck = Physics2D.Raycast(
new Vector2(
transform.position.x -
(transform.GetComponent<BoxCollider2D>().size.x / 2) * transform.localScale.x +
((transform.localScale.x > 0) ? -sensorXOffset : +sensorXOffset),
transform.position.y),
((transform.localScale.x > 0) ? Vector3.left : Vector3.right), sensorXDistance, walkable);
#endregion
#region Walking States and Jump
if (groundCheck.collider != null)
{
playerState = WalkingState.Grounded;
}
else
{
playerState = WalkingState.Air;
}
#endregion
#region Walls States
if ((fowardCheck && !backCheck) || (fowardCheck && backCheck))
{
playerWallState = WallState.FrontWall;
}
else if (!fowardCheck && backCheck)
{
playerWallState = WallState.BackWall;
}
else
{
playerWallState = WallState.None;
}
#endregion
//---------------------------------EdgeChecker----------------------------------------------
#region EdgeChecker
if (downwardsEdgeCheck && fowardCheck && downwardsEdgeCheck.distance > 0.05f)
{
edgeClose = true;
//edgepos = new Vector2(fowardCheck.point.x,downwardsEdgeCheck.point.y);
edgepos = new Vector2(fowardCheck.point.x, downwardsEdgeCheck.point.y);
}
if (!downwardsEdgeCheck || !fowardCheck || downwardsEdgeCheck.distance < 0.05f)
{
edgeClose = false;
}
#endregion
//---------------------------------VaultChecker---------------------------------------------
//Still not done
#region CheckerVault
vaultCheck = Physics2D.Raycast(
new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x +
((transform.localScale.x > 0) ? +vaultEdgeXOffset : -vaultEdgeXOffset),
transform.position.y -
(transform.GetComponent<BoxCollider2D>().size.y / 4) * transform.localScale.y +
vaultEdgeYOffset,
0),
((transform.localScale.x > 0) ? Vector3.right : Vector3.left), vaultEdgeDistance, walkable);
/*
* downwardsEdgeCheck = Physics2D.Raycast(new Vector3(
transform.position.x + (transform.GetComponent<BoxCollider2D>().size.x) * transform.localScale.x + ((transform.localScale.x > 0) ? +downwardsEdgeXOffset : -downwardsEdgeXOffset),
transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset,
0), Vector2.down, downwardsEdgeDistance,walkable);
*/
//I did the position.y - position.y just to understand when reading
// Debug.Log($"Downwards Distance: {downwardsEdgeCheck.distance}| Depois de: {(transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y + downwardsEdgeYOffset)- transform.position.y}");
if (downwardsEdgeCheck && vaultCheck && downwardsEdgeCheck.distance >
(transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset) - transform.position.y)
{
vaultableObjectClose = true;
vaultpos = new Vector2(vaultCheck.point.x, downwardsEdgeCheck.point.y);
// edgepos = new Vector2(fowardCheck.point.x, downwardsEdgeCheck.point.y);
}
if (!downwardsEdgeCheck || !vaultCheck || downwardsEdgeCheck.distance <=
(transform.position.y + (transform.GetComponent<BoxCollider2D>().size.y) * transform.localScale.y +
downwardsEdgeYOffset) - transform.position.y)
{
vaultableObjectClose = false;
}
#endregion
if (playerState == WalkingState.Air && playerWallState != WallState.None)
{
rb2d.gravityScale = gravityWall;
}
else
{
rb2d.gravityScale = gravityNormal;
}
}
/// <summary>
/// Makes the character move on the X axis, with the walking speed or running speed
/// </summary>
/// <param name="horizontal"></param> Variable responsible for the input
/// <param name="running"></param> Variable responsible for the state of movement
public void Move(float horizontal, bool running = false)
{
if (!isHanging)
{
//Add air control
//Add slip movement and not instant
if (horizontal < 0)
{
transform.localScale = new Vector3(-startScale.x, startScale.y, startScale.z);
}
else if (horizontal > 0)
{
transform.localScale = startScale;
}
//rb2d.AddForce(new Vector2(horizontal*speed,0),ForceMode2D.Force);
if (playerState == WalkingState.Grounded)
{
if (Mathf.Abs((running) ? maxRunningVelocity2D.x : maxWalkingVelocity2D.x) >=
Mathf.Abs(rb2d.velocity.x + horizontal * ((running) ? stepRunningSpeed : stepWalkingSpeed)))
{
rb2d.velocity =
new Vector2(
rb2d.velocity.x + horizontal * ((running) ? stepRunningSpeed : stepWalkingSpeed),
rb2d.velocity.y);
}
if (vaultableObjectClose && running && CompareNormalWithVector(vaultCheck.normal,
((horizontal > 0) ? Vector2.left : Vector2.right), 0.3f))
{
/*
transform.position = new Vector3(
vaultpos.x + ((vaultpos.x - transform.position.x > 0) ? -(transform.GetComponent<BoxCollider2D>().size.x / 4) : +(transform.GetComponent<BoxCollider2D>().size.x / 4)),
vaultpos.y + transform.GetComponent<BoxCollider2D>().size.y / 1.8f,
transform.position.z
);
*/
transform.position = new Vector3(
vaultpos.x,
vaultpos.y + transform.GetComponent<BoxCollider2D>().size.y / 2,
transform.position.z
);
}
}
else if (playerState == WalkingState.Air)
{
if (Mathf.Abs(maxWalkingVelocity2D.x) >=
Mathf.Abs(rb2d.velocity.x + horizontal * ((stepWalkingSpeed * aircontrol))))
{
rb2d.velocity = new Vector2(rb2d.velocity.x + horizontal * (stepWalkingSpeed * aircontrol),
rb2d.velocity.y);
//rb2d.velocity = new Vector2(rb2d.velocity.x + horizontal * ((running) ? stepRunningSpeed : stepWalkingSpeed), rb2d.velocity.y);
}
}
}
}
public void Jump(Vector2 input)
{
/*
if (playerState== WalkingState.Grounded || (playerState == WalkingState.Air && (fowardCheck|| backCheck)) )
{
canJump = true;
}else if (playerState == WalkingState.Air )
{
canJump = false;
}
*/
if (playerState == WalkingState.Grounded)
{
rb2d.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
canJump = false;
}
else if (playerState == WalkingState.Air)
{
if (CompareInputWithVector(input, Vector2.up, 0.8f) && fowardCheck && edgeClose && !isHanging)
{
Debug.Log("Grabbed Edge");
isHanging = true;
hangingStartTime = Time.time;
rb2d.velocity = Vector2.zero;
rb2d.isKinematic = true;
transform.position = new Vector3(
edgepos.x + ((edgepos.x - transform.position.x > 0)
? -(transform.GetComponent<BoxCollider2D>().size.x / 4)
: +(transform.GetComponent<BoxCollider2D>().size.x / 4)),
edgepos.y - transform.GetComponent<BoxCollider2D>().size.y / 2,
transform.position.z
);
/*
Debug.Log("Climbed Wall");
rb2d.velocity = Vector2.zero;
//rb2d.AddForce(transform.up * jumpForce * 1.4f, ForceMode2D.Impulse);
transform.position = new Vector3(
edgepos.x + ((edgepos.x - transform.position.x > 0) ? +(transform.GetComponent<BoxCollider2D>().size.x / 2) : -(transform.GetComponent<BoxCollider2D>().size.x / 2)),
edgepos.y + transform.GetComponent<BoxCollider2D>().size.y / 2,
transform.position.z
);
*/
}
else if (CompareInputWithVector(input, Vector2.up, 0.8f) && isHanging && canClimb)
{
Debug.Log("Climbed Wall");
rb2d.velocity = Vector2.zero;
isHanging = false;
canClimb = false;
rb2d.isKinematic = false;
//rb2d.AddForce(transform.up * jumpForce * 1.4f, ForceMode2D.Impulse);
transform.position = new Vector3(
edgepos.x + ((edgepos.x - transform.position.x > 0)
? +(transform.GetComponent<BoxCollider2D>().size.x / 2)
: -(transform.GetComponent<BoxCollider2D>().size.x / 2)),
edgepos.y + transform.GetComponent<BoxCollider2D>().size.y / 2,
transform.position.z
);
}
else if (fowardCheck)
{
Debug.Log("Jumped Wall");
//rb2d.AddForce((-transform.right) * jumpForce * 1.4f, ForceMode2D.Impulse);
rb2d.AddForce(fowardCheck.normal * jumpForce * 1.4f, ForceMode2D.Impulse);
rb2d.AddForce(transform.up * jumpForce * 0.9f, ForceMode2D.Impulse);
canJump = false;
}
}
}
private void CheckHanging()
{
if (isHanging)
{
if (climbingCooldown + hangingStartTime < Time.time)
{
canClimb = true;
}
if (hangingStartTime + hangingMaxTime < Time.time)
{
rb2d.velocity = Vector2.zero;
isHanging = false;
rb2d.isKinematic = false;
}
}
else
{
canClimb = false;
}
}
public bool CompareInputWithVector(Vector2 input, Vector2 vector, float offset)
{
input = input.normalized;
if ((input.x >= vector.x - offset && input.x <= vector.x + offset) &&
(input.y >= vector.y - offset && input.y <= vector.y + offset))
{
return true;
}
return false;
}
public bool CompareNormalWithVector(Vector2 normal, Vector2 vector, float offset)
{
normal = normal.normalized;
if ((normal.x >= vector.x - offset && normal.x <= vector.x + offset) &&
(normal.y >= vector.y - offset && normal.y <= vector.y + offset))
{
return true;
}
return false;
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
public class TargetGroupManager : MonoBehaviour
{
public static TargetGroupManager instance;
private CinemachineTargetGroup cinemachineTargetGroup;
public List<GameObject> targetobjects;
private void Awake()
{
instance = this;
cinemachineTargetGroup = GetComponent<CinemachineTargetGroup>();
}
public void AddTarget(GameObject go, float priority,float radius)
{
cinemachineTargetGroup.AddMember(go.transform,priority,radius);
}
public void RemoveTarget(GameObject go)
{
cinemachineTargetGroup.RemoveMember(go.transform);
}
}
<file_sep>using System;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerInput : MonoBehaviour
{
[SerializeField] private Movement currentMovement;
private InputMaster controls;
private Vector2 _moveAxis;
private bool runInput;
void OnEnable()
{
//controls.Player.Movement.performed += HandleMove;
controls.Player.Movement.Enable();
controls.Player.Jump.Enable();
controls.Player.Jump.performed += HandleJump;
controls.Player.Run.Enable();
//controls.Player.Dash.Enable();
//controls.Player.Dash.performed += DashHandler;
}
private void OnDisable()
{
controls.Disable();
}
private void Awake()
{
controls = new InputMaster();
//currentMovement = GetComponent<Movement>();
}
private void Update()
{
HandleInputs();
}
private void FixedUpdate()
{
if (_moveAxis.x !=0)
{
currentMovement.Move(_moveAxis.x,runInput);
}
}
private void OnDrawGizmos()
{
var input = _moveAxis;
var vector = Vector2.up;
var offset = 0.8f;
input = input.normalized;
if ((input.x >=vector.x-offset && input.x <= vector.x+offset) && (input.y >= vector.y - offset && input.y <=vector.y + offset))
{
Gizmos.color= Color.green;
}
else
{
Gizmos.color= Color.blue;
}
Gizmos.DrawRay(transform.position, _moveAxis*2f);
}
void HandleInputs()
{
_moveAxis = controls.Player.Movement.ReadValue<Vector2>();
runInput = (controls.Player.Run.ReadValue<float>() != 0f) ? true : false;
//Debug.LogError(_moveAxis);
}
void HandleJump(InputAction.CallbackContext ctx)
{
//Debug.Log("HandlerWorked");
currentMovement.Jump(_moveAxis);
}
}
<file_sep># 2D Character Movement Parkour and Camera System
2D character movement with parkour and a follow camera system
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum SceneIndexes
{
MANAGER =0,
TITLE_SCREEN =1,
TUTORIAL = 2,
GAME=3,
ENDSCREEN=4
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public GameObject loadingScreen;
//public Camera loadingCam;
public Slider bar;
private void Awake()
{
instance = this;
SceneManager.LoadSceneAsync((int) SceneIndexes.TITLE_SCREEN, LoadSceneMode.Single);
DontDestroyOnLoad(this);
}
List<AsyncOperation> scenesLoading= new List<AsyncOperation>();
public void LoadLevel(string sceneName,SceneIndexes sceneindex)
{
loadingScreen.gameObject.SetActive(true);
//loadingCam.gameObject.SetActive(true);
//scenesLoading.Add(SceneManager.UnloadSceneAsync((int) SceneIndexes.TITLE_SCREEN));
scenesLoading.Add(SceneManager.LoadSceneAsync((int) sceneindex, LoadSceneMode.Single));
StartCoroutine(GetSceneLoadProgress(sceneName));
}
/*
public void LoadGame()
{
loadingScreen.gameObject.SetActive(true);
//loadingCam.gameObject.SetActive(true);
//scenesLoading.Add(SceneManager.UnloadSceneAsync((int) SceneIndexes.TITLE_SCREEN));
scenesLoading.Add(SceneManager.LoadSceneAsync((int) SceneIndexes.GAME, LoadSceneMode.Single));
StartCoroutine(GetSceneLoadProgress("Game"));
}
public void Tutorial()
{
loadingScreen.gameObject.SetActive(true);
//loadingCam.gameObject.SetActive(true);
//scenesLoading.Add(SceneManager.UnloadSceneAsync((int) SceneIndexes.TITLE_SCREEN));
scenesLoading.Add(SceneManager.LoadSceneAsync((int) SceneIndexes.TUTORIAL, LoadSceneMode.Single));
StartCoroutine(GetSceneLoadProgress("Tutorial"));
}
*/
private float totalSceneProgress;
public IEnumerator GetSceneLoadProgress(string name)
{
for (int i = 0; i < scenesLoading.Count; i++)
{
while (!scenesLoading[i].isDone)
{
totalSceneProgress = 0;
foreach (AsyncOperation operation in scenesLoading)
{
totalSceneProgress += operation.progress;
}
totalSceneProgress = (totalSceneProgress / scenesLoading.Count) * 100f;
bar.value = Mathf.RoundToInt(totalSceneProgress);
yield return null;
}
}
SceneManager.SetActiveScene(SceneManager.GetSceneByName(name));
loadingScreen.gameObject.SetActive(false);
//loadingCam.gameObject.SetActive(false);
}
}<file_sep>using UnityEngine;
public class MovementExtras : MonoBehaviour
{
public virtual void ActionStart() { }
public virtual void ActionUpdate() { }
public virtual void ActionFixedUpdate() { }
}
| ad00e7bbd44460ec459acbe1ce8e49db69b165e3 | [
"Markdown",
"C#"
] | 11 | C# | kika2001/2DMovementParkourAndCamera | 9e0f768780e7b1dd1df27fc46a3e07cc33a33e8c | 8c08bda4e64ea5c514782d263c6278746221d942 |
refs/heads/master | <repo_name>beenjyd4/INF3044_KRAFFT_FAVIN<file_sep>/app/src/main/java/com/example/benjamin/myapplication/Main2Activity.java
package com.example.benjamin.myapplication;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main2Activity extends AppCompatActivity {
private static final int NOTIF_ID=0;
public RecyclerView rv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
rv = (RecyclerView) findViewById(R.id.rv_beer);
rv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
rv.setAdapter(new BeersAdapter(getBeersFromFiles()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public void findMoreBeer(View v){
String url = getResources().getString(R.string.url);
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
startActivity(intent);
}
public void prankToast(MenuItem item) {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast));
Toast toast = new Toast(this);
toast.setView(view);
toast.show();
}
public void createServices(View v){
GetBiersServices.startActionGetAllBiers(this);
IntentFilter intentFilter = new IntentFilter(BIERS_UPDATE);
LocalBroadcastManager.getInstance(this).registerReceiver(new BierUpdate(),intentFilter);
}
public static final String BIERS_UPDATE="com.project-tp1.info3044-11.BIERS_UPDATE";
public static final String TAG="BIERS_UPDATE";
public void createCredits(MenuItem item) {
Intent i = new Intent(this, Credits.class);
startActivity(i);
}
public class BierUpdate extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,intent.getAction());
NotificationCompat.Builder builder= (NotificationCompat.Builder) new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.filesDown)).setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.drawable.beericon));
NotificationManager nm =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(NOTIF_ID,builder.build());
((BeersAdapter)(rv.getAdapter())).setNewBeer(getBeersFromFiles());
}
}
public JSONArray getBeersFromFiles(){
try{
InputStream is = new FileInputStream(getCacheDir()+"/"+"bieres.json");
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
return new JSONArray(new String(buffer,"UTF-8"));
}catch (IOException e){
e.printStackTrace();
return new JSONArray();
} catch (JSONException e) {
e.printStackTrace();
} return new JSONArray();
}
private class BeersAdapter extends RecyclerView.Adapter<BeersAdapter.BeerHolder>{
private JSONArray beer;
public BeersAdapter(JSONArray beer){
this.beer = beer;
}
public void setNewBeer(JSONArray ju){
beer=ju;
notifyDataSetChanged();
}
@Override
public BeerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new BeerHolder (LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_beer_element,parent,false));
}
@Override
public void onBindViewHolder(BeerHolder holder, int position) {
try {
JSONObject jo = beer.getJSONObject(position);
holder.name.setText(jo.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return beer.length();
}
public class BeerHolder extends RecyclerView.ViewHolder {
public TextView name;
public BeerHolder(View itemView) {
super(itemView);
this.name = (TextView) itemView.findViewById(R.id.rv_beer_element_name);
}
}
}
}
| 838dfb83e537cfb8a88057d65231d7268c10052c | [
"Java"
] | 1 | Java | beenjyd4/INF3044_KRAFFT_FAVIN | 89a15709486b164680a2a23de972e3e2e923afba | e37cf462ef8a12acc6cc889aa102dfa8308b4a4f |
refs/heads/master | <repo_name>CactusCata/SignGenerator2.0<file_sep>/Tellraw2.0/src/com/gmail/cactus/cata/enums/HoverEvent.java
package com.gmail.cactus.cata.enums;
public enum HoverEvent {
SHOW_TEXT("show_text"),
SHOW_ITEM("show_item"),
SHOW_ENTITY("show_entity"),
SHOW_ACHIEVEMENT("show_achievement");
private String name;
private HoverEvent(String name) {
this.name = name;
}
public String getValue(Entity entity, String argument, String uuid) {
switch (this) {
case SHOW_TEXT:
return "\"hoverEvent\":{\"action\":\"" + name + "\",\"value\":\"" + argument + "\"}";
case SHOW_ITEM:
return "\"hoverEvent\":{\"action\":\"" + name + "\",\"value\":\"" + argument + "\"}";
case SHOW_ENTITY:
return "\"hoverEvent\":{\"action\":\"" + name + "\",\"value\":\"" + argument + "\"}";
case SHOW_ACHIEVEMENT:
return "\"hoverEvent\":{\"action\":\"" + name + "\",\"value\":\"" + argument + "\"}";
default:
return null;
}
}
}<file_sep>/Tellraw2.0/src/com/gmail/cactus/cata/Main.java
package com.gmail.cactus.cata;
import com.gmail.cactus.cata.enums.ClickEvent;
import com.gmail.cactus.cata.enums.Color;
import com.gmail.cactus.cata.enums.Entity;
import com.gmail.cactus.cata.enums.HoverEvent;
public class Main {
public static void main(String[] args) {
Tellraw tellraw = new Tellraw("p[r=5]");
tellraw.addText("Hello World", Color.BLUE).setParameter(TellrawText.TEXT_BOLD, true)
.addClickEvent(ClickEvent.OPEN_URL, "https://youporn.com")
.addHoverEvent(HoverEvent.SHOW_ENTITY, Entity.CREEPER, "Creepy", "9b8d31d5-420c-4f0c-80f0-de834b737a99");
tellraw.addText("Hello 2", Color.AQUA).setParameter(TellrawText.TEXT_ITALIC, true)
.addClickEvent(ClickEvent.RUN_COMMAND, "Je suis un abruti");
tellraw.addText("Hello 2", Color.AQUA).setParameter(TellrawText.TEXT_ITALIC, true)
.addHoverEvent(HoverEvent.SHOW_TEXT, "Je suis un abruti");
System.out.println(tellraw.generate());
}
}
<file_sep>/Tellraw2.0/src/com/gmail/cactus/cata/Tellraw.java
package com.gmail.cactus.cata;
import java.util.ArrayList;
import java.util.List;
import com.gmail.cactus.cata.enums.Color;
public class Tellraw {
private String command;
private List<TellrawText> texts;
public Tellraw(String selector) {
command = "/tellraw @" + selector + " [\"\",";
texts = new ArrayList<>();
}
public TellrawText addText(String value, Color color) {
TellrawText text = new TellrawText(value, color);
texts.add(text);
return text;
}
public String generate() {
int index = 0;
for (TellrawText text : texts) {
index++;
command += text.build() + (index == texts.size() ? "" : ",");
}
return command += "]";
}
} | e20649159fdbfa7005f9a3379619e9db92d03e34 | [
"Java"
] | 3 | Java | CactusCata/SignGenerator2.0 | 755a7d4561e1a01a1dbcc2d5fb9ed827abef8e5f | 61ae5a9989bfa2dbd50405569d77f44565927f4a |
refs/heads/master | <file_sep>emls
====
The EMLS provides a mailing-list system which can be entirely controlled through email including creating mailing-lists, changing the configuration etc.
The wrapper binary must be set with the setuid bit:
$> chmod 711 wrapper
$> chmod u+s wrapper
<file_sep>#
# ---------- definitions ------------------------------------------------------
#
EMSLocation = "/etc/ems/"
ListsLocation = EMSLocation + "lists/"
LogsLocation = EMSLocation + "logs/"
TemplatesLocation = EMSLocation + "templates/"
#
# ---------- packages ---------------------------------------------------------
#
import os
import re
import sys
import tempfile
import shutil
import time
import yaml
import random
import string
import email
import smtplib
#
# ---------- status -----------------------------------------------------------
#
StatusOk = 1
StatusError = 2
#
# ---------- type -------------------------------------------------------------
#
TypeUser = "user"
TypeList = "list"
#
# ---------- actions ----------------------------------------------------------
#
ActionSubscribe = "subscribe"
ActionPost = "post"
ActionHelp = "help"
ActionDump = "dump"
ActionAdd = "add"
ActionInsert = "insert"
ActionEdit = "edit"
ActionRemove = "remove"
ActionDescription = "description"
ActionTag = "tag"
ActionMembership = "membership"
ActionControl = "control"
ActionShow = "show"
ActionUnsubscribe = "unsubscribe"
ActionBehaviour = "behaviour"
#
# ---------- arguments --------------------------------------------------------
#
ArgumentsHelp = 0
ArgumentsDump = 0
ArgumentsAdd = 2
ArgumentsInsert = 1
ArgumentsEdit = 2
ArgumentsRemove = 1
ArgumentsDescription = 1
ArgumentsTag = 1
ArgumentsMembership = 1
ArgumentsControl = 1
ArgumentsUnsubscribe = 0
ArgumentsShow = 0
ArgumentsBehaviour = 1
#
# ---------- behaviours -------------------------------------------------------
#
BehaviourListener = "listener"
BehaviourSpeaker = "speaker"
BehaviourContributor = "contributor"
#
# ---------- policies ---------------------------------------------------------
#
PolicyMembershipPublic = "public"
PolicyMembershipModerated = "moderated"
PolicyMembershipPrivate = "private"
PolicyControlOpen = "open"
PolicyControlFiltered = "filtered"
#
# ---------- requirements -----------------------------------------------------
#
RequirementNone = []
RequirementManager = "manager"
RequirementMember = "member"
#
# ---------- templates --------------------------------------------------------
#
TemplateErrorAlreadySubscribed = TemplatesLocation + "ErrorAlreadySubscribed.txt"
TemplateErrorPrivateMembershipPolicy = TemplatesLocation + "ErrorPrivateMembershipPolicy.txt"
TemplateErrorNotAllowedToPost = TemplatesLocation + "ErrorNotAllowedToPost.txt"
TemplateErrorConfiguration = TemplatesLocation + "ErrorConfiguration.txt"
TemplateErrorUnexpected = TemplatesLocation + "ErrorUnexpected.txt"
TemplateErrorMissingTokens = TemplatesLocation + "ErrorMissingTokens.txt"
TemplateErrorUnknownToken = TemplatesLocation + "ErrorUnknownToken.txt"
TemplateErrorUnknownConfirmation = TemplatesLocation + "ErrorUnknownConfirmation.txt"
TemplateErrorNotSubscribed = TemplatesLocation + "ErrorNotSubscribed.txt"
TemplateErrorBadCommand = TemplatesLocation + "ErrorBadCommand.txt"
TemplateErrorUnallowedCommand = TemplatesLocation + "ErrorUnallowedCommand.txt"
TemplatePostAuthorisation = TemplatesLocation + "PostAuthorisation.txt"
TemplateRaw = TemplatesLocation + "Raw.txt"
TemplateSubscriptionConfirmation = TemplatesLocation + "SubscriptionConfirmation.txt"
TemplateSubscriptionAuthorisation = TemplatesLocation + "SubscriptionAuthorisation.txt"
TemplateSubscriptionNotification = TemplatesLocation + "SubscriptionNotification.txt"
TemplateSubscription = TemplatesLocation + "Subscription.txt"
TemplateUnsubscriptionConfirmation = TemplatesLocation + "UnsubscriptionConfirmation.txt"
TemplateUnsubscription = TemplatesLocation + "Unsubscription.txt"
TemplateAdminManagerHelp = TemplatesLocation + "AdminManagerHelp.txt"
TemplateAdminMemberHelp = TemplatesLocation + "AdminMemberHelp.txt"
TemplateAdminDump = TemplatesLocation + "AdminDump.txt"
TemplateAdminShow = TemplatesLocation + "AdminShow.txt"
TemplateAdminConfirmation = TemplatesLocation + "AdminConfirmation.txt"
TemplateAdminApplication = TemplatesLocation + "AdminApplication.txt"
#
# ---------- configuration ----------------------------------------------------
#
class Configuration:
#
# constructor
#
def __init__(self, id):
self.id = id
self.address = None
self.addresses = {}
self.description = None
self.policies = None
self.tag = ""
self.manager = None
self.members = {}
#
# this method loads a mailing-list configuration file.
#
def Load(self):
stream = None
address = None
# check the configuration file.
if not os.path.exists(ListsLocation + self.id + "/configuration"):
return StatusError
# read the configuration file.
try:
stream = yaml.load(Misc.Pull(ListsLocation + self.id + "/configuration"))
if not stream:
return StatusError
except:
return StatusError
# build the object.
self.address = stream["address"]
address = self.address.split("@")
self.addresses["subscribe"] = address[0] + "+subscribe@" + address[1]
self.addresses["confirm"] = address[0] + "+confirm@" + address[1]
self.addresses["admin"] = address[0] + "+admin@" + address[1]
self.description = stream["description"]
try:
self.tag = stream["tag"]
except:
pass
self.policies = stream["policies"]
self.manager = stream["manager"]
try:
self.members = stream["members"]
except:
pass
return StatusOk
#
# this method serialises a mailing-list object.
#
def Store(self):
stream = {}
descriptor = None
# open the output file.
descriptor = file(ListsLocation + self.id + "/configuration", 'w')
# initialise the stream
if self.address:
stream["address"] = self.address
if self.description:
stream["description"] = self.description
if self.tag:
stream["tag"] = self.tag
if self.policies:
stream["policies"] = self.policies
if self.manager:
stream["manager"] = self.manager
if self.members:
stream["members"] = self.members
# store the stream.
yaml.dump(stream, descriptor)
# close the file.
descriptor.close()
return StatusOk
#
# this method returns the complete list of users.
#
def Users(self):
users = {}
list = None
member = None
if self.members:
for member in self.members:
if self.members[member]["type"] == TypeUser:
try:
users[member]["behaviour"] = users[member]["behaviour"] | \
self.members[member]["behaviour"]
except:
users[member] = self.members[member]
elif self.members[member]["type"] == TypeList:
conf = Configuration(member)
conf.Load()
list = conf.Users()
if list:
for member in list:
try:
users[member]["behaviour"] = users[member]["behaviour"] | \
list["behaviour"]
except:
users[member] = list[member]
return users
#
# this method returns the list's listeners.
#
def Listeners(self):
listeners = {}
users = None
user = None
# retrieve the complete list of users.
users = self.Users()
# filter the listeners.
for user in users:
if (users[user]["behaviour"] == BehaviourListener) or (users[user]["behaviour"] == BehaviourContributor):
listeners[user] = users[user]
return listeners
#
# this method returns the list's speakers.
#
def Speakers(self):
speakers = {}
users = None
user = None
# retrieve the complete list of users.
users = self.Users()
# filter the speakers.
for user in users:
if (users[user]["behaviour"] == BehaviourSpeaker) or (users[user]["behaviour"] == BehaviourContributor):
speakers[user] = users[user]
return speakers
#
# ---------- queue ------------------------------------------------------------
#
class Queue:
#
# constructor
#
def __init__(self, id):
self.id = id
self.tokens = {}
#
# this method loads a mailing-list queue file.
#
def Load(self):
stream = None
# check the queue file.
if not os.path.exists(ListsLocation + self.id + "/queue"):
return StatusError
# read the configuration file.
try:
stream = yaml.load(Misc.Pull(ListsLocation + self.id + "/queue"))
except:
return StatusError
# build the object.
if stream:
self.tokens = stream
return StatusOk
#
# this method serialises a mailing-list object.
#
def Store(self):
stream = {}
descriptor = None
# open the output file.
descriptor = file(ListsLocation + self.id + "/queue", 'w')
# initialise the stream
if self.tokens:
stream = self.tokens
# store the stream.
yaml.dump(stream, descriptor)
# close the file.
descriptor.close()
#
# ---------- email ------------------------------------------------------------
#
class Email:
#
# constructor
#
def __init__(self):
self.raw = None
self.message = None
self.issuer = None
#
# this method builds an email object.
#
def Catch(self):
stream = None
index = None
# retrieve the email.
stream = Misc.Input()
if not stream:
return StatusError
# XXX
Misc.Log("<Received>\n" + stream)
# build the email object.
self.raw = stream
self.message = email.message_from_string(self.raw)
self.issuer = email.Utils.getaddresses([self.message["from"]])[0][1]
return StatusOk
#
# this method modifies a given attribute.
#
def Set(self, attribute, value):
if attribute in self.message:
del self.message[attribute]
self.message[attribute] = value
#
# this method returns a header element
#
def Get(self, attribute):
return self.message[attribute]
#
# return the email text
#
def Text(self):
return self.message.as_string()
#
# ---------- id ---------------------------------------------------------------
#
class Id:
#
# constructor
#
def __init__(self, email):
self.contents = email.Text()
self.argument = None
#
# this method builds an id object.
#
def Locate(self):
match = None
# locate the instance.
match = re.search("\[id:" + "((?:(?:\\\\])|(?:[^\]]))+)", self.contents, re.IGNORECASE | re.DOTALL)
if not match:
return
# set the string.
self.argument = match.group(1).strip(" \n")
#
# ---------- key --------------------------------------------------------------
#
class Key:
#
# constructor
#
def __init__(self, email):
self.contents = email.Text()
self.argument = None
#
# this method builds an key object.
#
def Locate(self):
match = None
# locate the instance.
match = re.search("\[key:" + "((?:(?:\\\\])|(?:[^\]]))+)", self.contents, re.IGNORECASE | re.DOTALL)
if not match:
return
# set the string.
self.argument = match.group(1).strip(" \n")
#
# ---------- command ----------------------------------------------------------
#
class Command:
#
# constructor
#
def __init__(self, email):
self.contents = email.Text()
self.string = None
self.arguments = {}
#
# this method builds an key object.
#
def Locate(self):
arguments = None
match = None
rest = None
# locate the instance.
match = re.search("\[cmd:" + "((?:(?:\\\\])|(?:[^\]]))+)\]", self.contents, re.IGNORECASE | re.DOTALL)
if not match:
return
# set the string.
self.string = match.group(1)
# locate the instance.
match = re.search("^((?:(?:\\\\])|(?:[^\] \n]))+)", self.string.lstrip(" \n"), re.IGNORECASE | re.DOTALL)
if not match:
return
# set the action in the argument list.
self.arguments["action"] = match.group(1)
# prepare the next step.
rest = self.string.lstrip(" \n")[len(match.group(1)):].lstrip(" \n").replace("\\[", "[").replace("\\]", "]")
# according to the action.
if match.group(1) == ActionHelp:
# no argument, nothing to do.
pass
elif match.group(1) == ActionDump:
# no argument, nothing to do.
pass
elif match.group(1) == ActionAdd:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsAdd:
self.arguments = None
return
self.arguments["address"] = arguments[0]
self.arguments["behaviour"] = arguments[1]
elif match.group(1) == ActionInsert:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsInsert:
self.arguments = None
return
self.arguments["id"] = arguments[0]
elif match.group(1) == ActionEdit:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsEdit:
self.arguments = None
return
self.arguments["address"] = arguments[0]
self.arguments["behaviour"] = arguments[1]
elif match.group(1) == ActionRemove:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsRemove:
self.arguments = None
return
self.arguments["member"] = arguments[0]
elif match.group(1) == ActionDescription:
self.arguments["description"] = rest
elif match.group(1) == ActionTag:
self.arguments["tag"] = rest
elif match.group(1) == ActionMembership:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsMembership:
self.arguments = None
return
self.arguments["policy"] = arguments[0]
elif match.group(1) == ActionControl:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsControl:
self.arguments = None
return
self.arguments["policy"] = arguments[0]
elif match.group(1) == ActionShow:
pass
elif match.group(1) == ActionUnsubscribe:
pass
elif match.group(1) == ActionBehaviour:
arguments = re.split("[ \n]+", rest.rstrip(" \n"), re.DOTALL)
if len(arguments) != ArgumentsBehaviour:
self.arguments = None
return
self.arguments["behaviour"] = arguments[0]
#
# ---------- misc -------------------------------------------------------------
#
class Misc:
#
# this method read the standard input.
#
def Input():
handle = None
line = None
contents = ""
for line in sys.stdin.readlines():
contents += line
return contents
#
# this method reads the contents of a single file.
#
def Pull(file):
handle = None
line = None
contents = ""
if not os.path.exists(file):
return None
try:
handle = open(file, "r")
except IOError:
return None
for line in handle.readlines():
contents += line
handle.close()
return contents
#
# this method writes the contents of a single file.
#
def Push(file, contents):
handle = None
try:
handle = open(file, "w")
except:
return StatusError
handle.write(contents)
handle.close()
return StatusOk
#
# this method generates a key.
#
def Generate(length):
key = ""
i = None
# generate the key.
for i in range(0, length):
key += random.choice("<KEY>")
return key
#
# this method generates a date.
#
def Date():
return time.strftime("%a, %d %b %Y %H:%M:%S +0100", time.gmtime())
#
# this method logs error messages.
#
def Log(message):
contents = None
d = None
t = None
# get the current date.
d = time.strftime("%Y-%m-%d")
# read the log file
contents = Misc.Pull(LogsLocation + d + ".log")
if not contents:
contents = ""
# get the current time.
t = time.strftime("%H:%M:%S")
# add the message.
contents = contents + "[" + t + "]\n" + message + "[/" + t + "]\n\n\n"
# write the file back.
Misc.Push(LogsLocation + d + ".log", contents)
#
# this method sends a template-based message to
# the given addresses.
#
def Send(sender, receivers, template, substitutions):
contents = None
tag = None
# check if the receivers list is empty.
if len(receivers) == 0:
return
# retrieve the template.
contents = Misc.Pull(template)
# perform the substitutions.
for tag in substitutions:
if tag == "<CONTENTS>":
continue
contents = contents.replace(tag, substitutions[tag])
# finally, if there is a <CONTENTS> substitution, perform it.
try:
contents = contents.replace("<CONTENTS>", substitutions["<CONTENTS>"])
except:
pass
# XXX
Misc.Log("<Sending...>\n" + contents)
# send the email.
server = smtplib.SMTP()
server.connect("localhost")
for receiver in receivers:
server.sendmail(sender, receiver, contents)
server.quit()
#
# initialisation
#
Input = staticmethod(Input)
Pull = staticmethod(Pull)
Push = staticmethod(Push)
Generate = staticmethod(Generate)
Date = staticmethod(Date)
Log = staticmethod(Log)
Send = staticmethod(Send)
<file_sep>#
# ---------- packages ---------------------------------------------------------
#
import ems
import sys
import re
import os
#
# ---------- functions --------------------------------------------------------
#
#
# this function displays the usage.
#
def Usage():
sys.stdout.write("[ems::usage] subscribe.py [mailing-list]\n")
sys.exit(0)
#
# this function performs a private subscription.
#
def Private(conf, queue, email):
# just reject the registration.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorPrivateMembershipPolicy,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
#
# this function performs a moderated subscription.
#
# postpone the registration waiting from the manager's confirmation.
#
def Moderated(conf, queue, email):
key = None
id = None
# generate an id.
id = ems.Misc.Generate(32)
# generate a key.
key = ems.Misc.Generate(32)
# add the subscription to the pending registrations.
queue.tokens[id] = { "action": ems.ActionSubscribe,
"member": { "address": email.issuer, "behaviour": ems.BehaviourContributor, "key": key },
"requirements": [ ems.RequirementManager, ems.RequirementMember ] }
# notify both the user and the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateSubscriptionConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ID>": id,
"<KEY>": key })
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateSubscriptionAuthorisation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<USER>": email.issuer,
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function performs a public subscription.
#
def Public(conf, queue, email):
key = None
id = None
# generate an id.
id = ems.Misc.Generate(32)
# generate a key.
key = ems.Misc.Generate(32)
# add the subscription to the queue, waiting user's confirmation.
queue.tokens[id] = { "action": ems.ActionSubscribe,
"member": { "address": email.issuer, "behaviour": ems.BehaviourContributor, "key": key },
"requirements": [ ems.RequirementMember ] }
# notify the user.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateSubscriptionConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ID>": id,
"<KEY>": key })
#
# this function subscribes a user according to the mailing-list
# subscription policy.
#
def Subscribe(conf, queue, email):
users = None
# retrieve the complete list of users.
users = conf.Users()
# check if the subscriber is already registered.
if email.issuer in users:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorAlreadySubscribed,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ADDRESS:ADMIN>": conf.addresses["admin"] })
return
# look at the mailing-list's subscription policy.
if conf.policies["membership"] == ems.PolicyMembershipPrivate:
Private(conf, queue, email)
elif conf.policies["membership"] == ems.PolicyMembershipModerated:
Moderated(conf, queue, email)
elif conf.policies["membership"] == ems.PolicyMembershipPublic:
Public(conf, queue, email)
else:
# notify both the sender and manager that something went wrong.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnexpected,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "your subscription from being processed" })
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateErrorConfiguration,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": email.issuer +
"'s subscription from being processed because " +
"of a unexpected membership policy '" +
conf.policies["membership"] + "'" })
#
# this is the main function.
#
def Main():
conf = None
queue = None
email = None
user = None
id = None
# retrieve the argument.
if len(sys.argv) != 2:
Usage()
# set the id.
id = sys.argv[1]
# retrieve a configuration object.
conf = ems.Configuration(id)
if conf.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the configuration file '" +
id + "'")
sys.exit(0)
# retrive the queue object.
queue = ems.Queue(id)
if queue.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the queue file '" + id + "'")
sys.exit(0)
# retrieve the email.
email = ems.Email()
if email.Catch() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to catch the incoming email")
sys.exit(0)
# try to subscribe the user to the given mailing-list.
Subscribe(conf, queue, email)
# update both the configuration and the queue.
if queue.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
if conf.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
#
# ---------- entry point ------------------------------------------------------
#
if __name__ == "__main__":
Main()
<file_sep>#
# ---------- packages ---------------------------------------------------------
#
import ems
import sys
import re
import os
#
# ---------- functions --------------------------------------------------------
#
#
# this function displays the usage.
#
def Usage():
sys.stdout.write("[ems::usage] confirm.py [mailing-list]\n")
sys.exit(0)
#
# this function returns the help to the sender.
#
def Help(conf, queue, email, command):
# send the help according to the type of user: member or manager.
if email.issuer == conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminManagerHelp,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminMemberHelp,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
#
# this function returns a human-readable dump of the mailing-list
# configuration and queue.
#
def Dump(conf, queue, email, command):
contents = None
token = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# build the configuration dump.
contents = "---[ Configuration\n"
contents += "\n"
contents += "[id] " + conf.id + "\n"
contents += "[address] " + conf.address + "\n"
contents += "\n"
contents += "[description] " + conf.description + "\n"
contents += "\n"
contents += "[tag] " + conf.tag + "\n"
contents += "\n"
contents += "[policies]\n"
contents += " [membership] " + conf.policies["membership"] + "\n"
contents += " [control] " + conf.policies["control"] + "\n"
contents += "\n"
contents += "[manager]\n"
contents += " [address] " + conf.manager["address"] + "\n"
contents += " [key] " + conf.manager["key"] + "\n"
if conf.members:
contents += "\n"
contents += "[members]\n"
for member in conf.members:
if conf.members[member]["type"] == ems.TypeUser:
contents += " [user]\n"
contents += " [address] " + member + "\n"
contents += " [behaviour] " + conf.members[member]["behaviour"] + "\n"
contents += " [key] " + conf.members[member]["key"] + "\n"
elif conf.members[member]["type"] == ems.TypeList:
contents += " [list]\n"
contents += " [id] " + member + "\n"
else:
contents += " [error::undefined]\n"
contents += " " + member + " :: " + str(conf.members[member]) + "\n"
contents += "\n"
# build the queue dump.
contents += "---[ Queue\n"
contents += "\n"
if queue.tokens:
contents += "[tokens]\n"
for token in queue.tokens:
contents += " [id] " + token + "\n"
contents += " " + str(queue.tokens[token]) + "\n"
# finally send the dump.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminDump,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": contents })
#
# this function adds a member to the list.
#
def Add(conf, queue, email, command):
key = None
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check the arguments.
if not command.arguments["behaviour"] in [ ems.BehaviourListener, ems.BehaviourSpeaker, ems.BehaviourContributor ]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# generate a key.
key = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionAdd,
"member": { "address": command.arguments["address"], "behaviour": command.arguments["behaviour"], "key": key },
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to add the user '" + command.arguments["address"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function adds a list to the list.
#
def Insert(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionInsert,
"member": command.arguments["id"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to insert the list '" + command.arguments["id"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function edits a member.
#
def Edit(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check the arguments.
if not command.arguments["behaviour"] in [ ems.BehaviourListener, ems.BehaviourSpeaker, ems.BehaviourContributor ]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionEdit,
"member": { "address": command.arguments["address"], "behaviour": command.arguments["behaviour"] },
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to edit the user '" + command.arguments["address"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function removes an entry.
#
def Remove(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check if the entry exists.
if (command.arguments["member"] in conf.members) and \
(conf.members[command.arguments["member"]]["type"] != ems.TypeUser):
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionRemove,
"member": command.arguments["member"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to remove member '" + command.arguments["member"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function edits the description.
#
def Description(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionDescription,
"description": command.arguments["description"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to set the description to '" + command.arguments["description"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function edits the tag.
#
def Tag(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionTag,
"tag": command.arguments["tag"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to set the tag to '" + command.arguments["tag"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function changes the membership policy.
#
def Membership(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check the arguments.
if not command.arguments["policy"] in [ ems.PolicyMembershipPublic, ems.PolicyMembershipModerated, ems.PolicyMembershipPrivate ]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionMembership,
"policy": command.arguments["policy"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to set the membership policy to '" + command.arguments["policy"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function changes the control policy.
#
def Control(conf, queue, email, command):
id = None
# if the email does not come from the manager, return an error.
if email.issuer != conf.manager["address"]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnallowedCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check the arguments.
if not command.arguments["policy"] in [ ems.PolicyControlOpen, ems.PolicyControlFiltered ]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionControl,
"policy": command.arguments["policy"],
"requirements": [ ems.RequirementManager ] }
# notify the manager.
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to set the control policy to '" + command.arguments["policy"] + "'",
"<ID>": id,
"<KEY>": conf.manager["key"] })
#
# this function returns a human-readable dump of the subscription.
#
def Show(conf, queue, email, command):
contents = None
# build the contents.
contents = " [address] " + email.issuer + "\n"
contents += " [behaviour] " + conf.members[email.issuer]["behaviour"] + "\n"
contents += " [key] " + conf.members[email.issuer]["key"] + "\n"
# finally send the dump.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminShow,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": contents })
#
# this function unsubscribes a user.
#
def Unsubscribe(conf, queue, email, command):
id = None
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionUnsubscribe,
"member": email.issuer,
"requirements": [ ems.RequirementMember ] }
# notify the user.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to unsubscribe from the mailing-list",
"<ID>": id,
"<KEY>": conf.members[email.issuer]["key"] })
#
# this function modifies the behaviour of the calling user.
#
def Behaviour(conf, queue, email, command):
id = None
# check the arguments.
if not command.arguments["behaviour"] in [ ems.BehaviourListener, ems.BehaviourSpeaker, ems.BehaviourContributor ]:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# generate an id.
id = ems.Misc.Generate(32)
# create an entry in the queue file.
queue.tokens[id] = { "action": ems.ActionBehaviour,
"member": { "address": email.issuer, "behaviour": command.arguments["behaviour"] },
"requirements": [ ems.RequirementMember ] }
# notify the user.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "Trying to change your behaviour to '" + command.arguments["behaviour"] + "'",
"<ID>": id,
"<KEY>": conf.members[email.issuer]["key"] })
#
# this function admins the mailing-list according to the given command.
#
def Admin(conf, queue, email):
users = None
command = None
arguments = None
# check if the subscriber is already registered.
if (conf.manager["address"] != email.issuer) and (not email.issuer in conf.members):
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorNotSubscribed,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ADDRESS:SUBSCRIBE>": conf.addresses["subscribe"] })
return
# retrieve the operation from the email.
command = ems.Command(email)
command.Locate()
if not command.arguments:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorBadCommand,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["admin"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# dispatch.
if command.arguments["action"] == ems.ActionHelp:
Help(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionDump:
Dump(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionAdd:
Add(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionAdd:
Add(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionInsert:
Insert(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionEdit:
Edit(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionRemove:
Remove(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionDescription:
Description(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionTag:
Tag(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionMembership:
Membership(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionControl:
Control(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionShow:
Show(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionUnsubscribe:
Unsubscribe(conf, queue, email, command)
elif command.arguments["action"] == ems.ActionBehaviour:
Behaviour(conf, queue, email, command)
#
# this is the main function.
#
def Main():
conf = None
queue = None
email = None
user = None
id = None
# retrieve the argument.
if len(sys.argv) != 2:
Usage()
# set the id.
id = sys.argv[1]
# retrieve a configuration object.
conf = ems.Configuration(id)
if conf.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the configuration file '" +
id + "'")
sys.exit(0)
# retrive the queue object.
queue = ems.Queue(id)
if queue.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the queue file '" + id + "'")
sys.exit(0)
# retrieve the email.
email = ems.Email()
if email.Catch() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to catch the incoming email")
sys.exit(0)
# try to perform the requested action.
Admin(conf, queue, email)
# update both the configuration and the queue.
if queue.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
if conf.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
#
# ---------- entry point ------------------------------------------------------
#
if __name__ == "__main__":
Main()
<file_sep>#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
int command(char* command)
{
const char* commands[] =
{
"subscribe",
"unsubscribe",
"admin",
"post",
"confirm",
NULL
};
unsigned int i;
for (i = 0; commands[i] != NULL; i++)
if (strcmp(commands[i], command) == 0)
return (0);
return (-1);
}
int identity(void)
{
struct passwd* password;
password = <PASSWORD>(getuid());
if (strcmp(password->pw_name, "nobody") != 0)
return (-1);
setreuid(0, -1);
return (0);
}
int launch(char* program,
char* list,
char** env)
{
#define VARIABLES_KEEP 4
#define VARIABLES_ADD 1
#define VARIABLES_NULL 1
#define ARGUMENTS 4
#define PACKAGES_DIRECTORY "/etc/ems/packages/"
#define PROGRAMS_DIRECTORY "/etc/ems/programs/"
#define PYTHON "/usr/bin/python2"
const char* variables[VARIABLES_KEEP + VARIABLES_NULL] =
{
"USER",
"PATH",
"PWD",
"SHLVL",
NULL
};
char* environment[VARIABLES_KEEP + VARIABLES_ADD + VARIABLES_NULL];
char* value;
char* arguments[ARGUMENTS];
unsigned int i;
unsigned int j;
for (i = 0, j = 0; variables[i]; i++)
if ((value = getenv(variables[i])) != NULL)
environment[j++] = value - 1 - strlen(variables[i]);
environment[j] = malloc(strlen("PYTHONPATH=") + strlen(PACKAGES_DIRECTORY) + 1);
strcpy(environment[j], "PYTHONPATH=");
strcat(environment[j++], PACKAGES_DIRECTORY);
environment[j] = NULL;
arguments[0] = PYTHON;
arguments[1] = malloc(strlen(PROGRAMS_DIRECTORY) + strlen(program) + strlen(".py") + 1);
strcpy(arguments[1], PROGRAMS_DIRECTORY);
strcat(arguments[1], program);
strcat(arguments[1], ".py");
arguments[2] = list;
arguments[3] = NULL;
execve(PYTHON, arguments, env);
return (-1);
}
int main(int argc,
char** argv,
char** env)
{
if (argc != 3)
{
fprintf(stderr, "[wrapper::usage] %s program [mailing-list]\n",
argv[0]);
exit(EXIT_FAILURE);
}
if (command(argv[1]) != 0)
{
fprintf(stderr, "[wrapper::error] illegal '%s' command\n", argv[1]);
exit(EXIT_FAILURE);
}
if (identity() != 0)
{
fprintf(stderr, "[wrapper::error] this wrapper is supposed to be run by the 'nobody' user\n");
exit(EXIT_FAILURE);
}
if (launch(argv[1], argv[2], env) != 0)
{
fprintf(stderr, "[wrapper::error] unable to launch the given command\n");
exit(EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
<file_sep>#! /usr/bin/python
#
# ---------- packages ---------------------------------------------------------
#
import ems
import sys
import re
import os
#
# ---------- functions --------------------------------------------------------
#
#
# this function displays the usage.
#
def Usage():
sys.stdout.write("[ems::usage] create.py\n")
sys.exit(1)
#
# this function inform the user of the general information
# and the next steps he/she has to go through.
#
def Inform(conf, queue):
address = None
sys.stdout.write("\n\n\n")
sys.stdout.write("Below are summarised the mailing-list informations:\n")
sys.stdout.write(" [id] " + conf.id + "\n")
sys.stdout.write(" [address] " + conf.address + "\n")
sys.stdout.write(" [description] " + conf.description + "\n")
sys.stdout.write(" [tag] " + conf.description + "\n")
sys.stdout.write(" [manager] " + conf.manager["address"] + "\n")
sys.stdout.write("\n\n\n")
address = conf.address.split("@")
sys.stdout.write("Now, you need to add the following piece of code to\n")
sys.stdout.write("the 'regexp:' file specified in the 'virtual_alias_map'\n")
sys.stdout.write("of your Postfix 'main.cf' configuration file:\n")
sys.stdout.write("\n")
sys.stdout.write("#\n# " + conf.address + "\n#\n")
sys.stdout.write("/^" + address[0] + "\\+(subscribe|confirm|admin)@" +
address[1] + "$/ ems_$1+" + conf.id + "\n")
sys.stdout.write("/^" + conf.address + "$/ ems_post+" + conf.id + "\n")
sys.stdout.write("/^" + address[0] + "\\+.*@" + address[1] +
"$/ ems_post+" + conf.id + "\n")
#
# this function asks the user information about the
# mailing-list he/she wants to create.
#
def Ask():
address = None
id = None
description = None
membership = None
control = None
tag = None
manager = None
key = None
# mailing-list address.
sys.stdout.write("mailing-list address []: ")
address = sys.stdin.readline().strip("\n")
if (len(address) == 0) or (address.find("@") == -1):
sys.stderr.write("[ems::error] incorrect mailing-list email address")
sys.exit(1)
# mailing-list identifier.
id = address.replace("@", ".")
# description.
sys.stdout.write("description []: ")
description = sys.stdin.readline().strip("\n")
# membership policy.
sys.stdout.write("membership policy (public, moderated or private) [public]: ")
membership = sys.stdin.readline().strip("\n")
if (membership != "public") and (membership != "moderated") and (membership != "private"):
membership = "public"
# control policy.
sys.stdout.write("control policy (open, filtered) [open]: ")
control = sys.stdin.readline().strip("\n")
if (control != "open") and (control != "filtered"):
control = "open"
# tag.
sys.stdout.write("tag []: ")
tag = sys.stdin.readline().strip("\n")
# manager email address.
sys.stdout.write("manager email address []: ")
manager = sys.stdin.readline().strip("\n")
if (len(manager) == 0) or (manager.find("@") == -1):
sys.stderr.write("[ems::error] incorrect manager's email address")
sys.exit(1)
# generate a key for the manager.
key = ems.Misc.Generate(32)
return (address, id, description, membership, control, tag, manager, key)
#
# this is the main function.
#
def Main():
conf = None
queue = None
email = None
address = None
id = None
description = None
membership = None
control = None
tag = None
manager = None
key = None
# ask the user for the mailing-list informations.
(address, id, description, membership, control, tag, manager, key) = Ask()
# check if the mailing-list already exist and create it if not.
if os.path.exists(ems.ListsLocation + id):
sys.stderr.write("[ems::error] the mailing-list seems to exist already\n")
sys.exit(1)
os.mkdir(ems.ListsLocation + id)
# create a configuration object.
conf = ems.Configuration(id)
conf.id = id
conf.address = address
conf.description = description
conf.policies = { "membership": membership, "control": control }
conf.tag = tag
conf.manager = { "address": manager, "key": key }
conf.members = {}
# create the queue object.
queue = ems.Queue(id)
queue.id = id
queue.tokens = {}
# serialise the configuration object.
if conf.Store() == ems.StatusError:
sys.stderr.write("[ems::error] an error occured while storing the configuration file\n")
sys.exit(1)
# serialise the queue object.
if queue.Store() == ems.StatusError:
sys.stderr.write("[ems::error] an error occured while storing the queue file\n")
sys.exit(1)
# inform the user of the next steps.
Inform(conf, queue)
#
# ---------- entry point ------------------------------------------------------
#
if __name__ == "__main__":
Main()
<file_sep>#! /usr/bin/python
#
# ---------- packages ---------------------------------------------------------
#
import ems
import sys
import re
import os
#
# ---------- functions --------------------------------------------------------
#
#
# this function displays the usage.
#
def Usage():
sys.stdout.write("[ems::usage] insert _id_ _file_\n")
sys.exit(1)
#
# this function takes a list of emails and insert them in the
# given mailing-list configuration.
#
def Insert(conf, emails):
email = None
# for every email.
for email in emails:
key = None
# generate a key.
key = ems.Misc.Generate(32)
# add the user to the list of members.
conf.members[email] = { "type": ems.TypeUser,
"behaviour": ems.BehaviourContributor,
"key": key }
try:
# finally, tell the user that her subscription went through.
ems.Misc.Send(conf.address,
[ email ],
ems.TemplateSubscription,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<DESCRIPTION>": conf.description,
"<ADDRESS:SUBSCRIBE>": conf.addresses["subscribe"],
"<ADDRESS:ADMIN>": conf.addresses["admin"],
"<ADDRESS:CONFIRM>": conf.addresses["confirm"] })
# print a message.
print "[success] " + email
except:
# print a message.
print "[failure] " + email
#
# this function extracts emails from the given file.
#
def Extract(file):
contents = None
emails = None
# read the file.
contents = ems.Misc.Pull(file).strip(" \n")
# split the contents according to the line delimiter.
emails = contents.split("\n")
return emails
#
# this is the main function.
#
def Main():
conf = None
file = None
id = None
emails = None
# retrieve the argument.
if len(sys.argv) != 3:
Usage()
id = sys.argv[1]
file = sys.argv[2]
# check if the mailing-list already exist and create it if not.
if os.path.exists(ems.ListsLocation + id) == False:
sys.stderr.write("[ems::error] the mailing-list does not seem to exist\n")
sys.exit(1)
# create a configuration object.
conf = ems.Configuration(id)
# load the configuration object.
if conf.Load() == ems.StatusError:
sys.stderr.write("[ems::error] an error occured while loading the conf file\n")
sys.exit(1)
# extract the emails from the given file.
emails = Extract(file)
# insert the emails.
Insert(conf, emails)
# finally store the modifications applied on to the configuration.
if conf.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
#
# ---------- entry point ------------------------------------------------------
#
if __name__ == "__main__":
Main()
<file_sep>../packages/ems.py<file_sep>#
# ---------- packages ---------------------------------------------------------
#
import ems
import sys
import re
import os
#
# ---------- functions --------------------------------------------------------
#
#
# this function displays the usage.
#
def Usage():
sys.stdout.write("[ems::usage] confirm.py [mailing-list]\n")
sys.exit(0)
#
# this function tries to confirm a subscription.
#
def Subscribe(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
elif (ems.RequirementMember in token["requirements"]) and \
(token["member"]["address"] == email.issuer) and \
(token["member"]["key"] == key.argument):
token["requirements"].remove(ems.RequirementMember)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# add the user to the list of members.
conf.members[token["member"]["address"]] = { "type": ems.TypeUser,
"behaviour": token["member"]["behaviour"],
"key": token["member"]["key"] }
# delete the queue token.
del queue.tokens[id.argument]
# finally, tell the user that her subscription went through.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateSubscription,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<DESCRIPTION>": conf.description,
"<ADDRESS:SUBSCRIBE>": conf.addresses["subscribe"],
"<ADDRESS:ADMIN>": conf.addresses["admin"],
"<ADDRESS:CONFIRM>": conf.addresses["confirm"] })
#
# this function tries to confirm a post.
#
def Post(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# post the message.
ems.Misc.Send(token["message"]["address"],
conf.Listeners().keys(),
ems.TemplateRaw,
{ "<CONTENTS>": token["message"]["contents"] })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a add operation.
#
def Add(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# add the user to the list of members.
conf.members[token["member"]["address"]] = { "type": ems.TypeUser,
"behaviour": token["member"]["behaviour"],
"key": token["member"]["key"] }
# finally, tell the user to her subscription went through.
ems.Misc.Send(conf.address,
[ token["member"]["address"] ],
ems.TemplateSubscription,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": token["member"]["address"],
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<DESCRIPTION>": conf.description,
"<ADDRESS:SUBSCRIBE>": conf.addresses["subscribe"],
"<ADDRESS:ADMIN>": conf.addresses["admin"],
"<ADDRESS:CONFIRM>": conf.addresses["confirm"] })
# but also to the manager who added the user.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The member '" + token["member"]["address"] +
"' has been added to the following mailing-list:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a insert operation.
#
def Insert(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# add the user to the list of members.
conf.members[token["member"]] = { "type": ems.TypeList }
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The list '" + token["member"] +
"' has been added to the following mailing-list:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a edit operation.
#
def Edit(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the user.
if token["member"]["address"] in conf.members:
conf.members[token["member"]["address"]]["behaviour"] = token["member"]["behaviour"]
# notify the mananger.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The member '" + token["member"]["address"] +
"' from the following mailing-list has been edited successfully:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a remove operation.
#
def Remove(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# remove the user.
if token["member"] in conf.members:
del conf.members[token["member"]]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The member '" + token["member"] +
"' has been removed from the following mailing-list:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a description operation.
#
def Description(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the description.
conf.description = token["description"]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The description of the following mailing-list has been modified:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a tag operation.
#
def Tag(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the description.
conf.tag = token["tag"]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The tag of the following mailing-list has been modified:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a membership operation.
#
def Membership(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the description.
conf.policies["membership"] = token["policy"]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The membership policy of the following mailing-list has been modified:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a control operation.
#
def Control(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementManager in token["requirements"]) and \
(conf.manager["address"] == email.issuer) and \
(conf.manager["key"] == key.argument):
token["requirements"].remove(ems.RequirementManager)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the description.
conf.policies["control"] = token["policy"]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "The control policy of the following mailing-list has been modified:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm an unsubscription.
#
def Unsubscribe(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementMember in token["requirements"]) and \
(token["member"] == email.issuer) and \
(conf.members[token["member"]]["key"] == key.argument):
token["requirements"].remove(ems.RequirementMember)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# remove the user.
if token["member"] in conf.members:
del conf.members[token["member"]]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "You have been unsubscribed from the following mailing-list with success:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function tries to confirm a behaviour operation.
#
def Behaviour(conf, queue, email, id, key):
token = None
# retrive the token.
token = queue.tokens[id.argument]
# try to reduce the requirements by updating the list of
# reqirements every time a confirmation comes in.
if (ems.RequirementMember in token["requirements"]) and \
(token["member"]["address"] == email.issuer) and \
(conf.members[token["member"]["address"]]["key"] == key.argument):
token["requirements"].remove(ems.RequirementMember)
else:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownConfirmation,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ID>": id.argument,
"<ADDRESS>": conf.address })
return
# then, if all the requirements have been met, perform the operation.
if ems.RequirementNone == token["requirements"]:
# edit the user's behaviour.
if token["member"]["address"] in conf.members:
conf.members[token["member"]["address"]]["behaviour"] = token["member"]["behaviour"]
# notify the manager.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateAdminApplication,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<CONTENTS>": "Your behaviour have been modified on the following mailing-list:\n\n" +
" " + conf.address + "\n" })
# delete the queue token.
del queue.tokens[id.argument]
#
# this function confirms an action according to the received email.
#
def Confirm(conf, queue, email):
id = None
key = None
# check if the subscriber is already registered.
# XXX[does not make sense since the one of the confirmation is for users to confirm
# their registration]
# if (conf.manager["address"] != email.issuer) and (not email.issuer in conf.members):
# ems.Misc.Send(conf.address,
# [ email.issuer ],
# ems.TemplateErrorNotSubscribed,
# { "<DATE>": ems.Misc.Date(),
# "<FROM>": conf.address,
# "<TO>": email.issuer,
# "<REPLY-TO>": conf.address,
# "<MAILING-LIST>": conf.id,
# "<ADDRESS>": conf.address,
# "<ADDRESS:SUBSCRIBE>": conf.addresses["subscribe"] })
# return
# retrieve the tokens from the email.
id = ems.Id(email)
key = ems.Key(email)
id.Locate()
key.Locate()
if (not id.argument) or (not key.argument):
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorMissingTokens,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address })
return
# check if this operation is registered in the queue.
if not id.argument in queue.tokens:
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnknownToken,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.addresses["confirm"],
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ID>": id.argument })
return
# according to the type of action.
if queue.tokens[id.argument]["action"] == ems.ActionSubscribe:
Subscribe(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionPost:
Post(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionAdd:
Add(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionInsert:
Insert(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionEdit:
Edit(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionRemove:
Remove(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionDescription:
Description(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionTag:
Tag(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionMembership:
Membership(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionControl:
Control(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionUnsubscribe:
Unsubscribe(conf, queue, email, id, key)
elif queue.tokens[id.argument]["action"] == ems.ActionBehaviour:
Behaviour(conf, queue, email, id, key)
else:
# notify both the sender and manager than something was wrong.
ems.Misc.Send(conf.address,
[ email.issuer ],
ems.TemplateErrorUnexpected,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": "your action from being confirmed" })
ems.Misc.Send(conf.address,
[ conf.manager["address"] ],
ems.TemplateErrorConfiguration,
{ "<DATE>": ems.Misc.Date(),
"<FROM>": conf.address,
"<TO>": email.issuer,
"<REPLY-TO>": conf.address,
"<MAILING-LIST>": conf.id,
"<ADDRESS>": conf.address,
"<ACTION>": email.issuer +
"'s action from being confirmed because " +
"of a unexpected action's type '" +
queue.tokens[id.argument]["action"] + "'" })
return
#
# this is the main function.
#
def Main():
conf = None
queue = None
email = None
user = None
id = None
# retrieve the argument.
if len(sys.argv) != 2:
Usage()
# set the id.
id = sys.argv[1]
# retrieve a configuration object.
conf = ems.Configuration(id)
if conf.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the configuration file '" +
id + "'")
sys.exit(0)
# retrive the queue object.
queue = ems.Queue(id)
if queue.Load() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to load the queue file '" + id + "'")
sys.exit(0)
# retrieve the email.
email = ems.Email()
if email.Catch() == ems.StatusError:
ems.Misc.Log("[ems::error] unable to catch the incoming email")
sys.exit(0)
# try to confirm an action.
Confirm(conf, queue, email)
# update both the configuration and the queue.
if queue.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
if conf.Store() == ems.StatusError:
ems.Misc.Log("[ems::error] an error occured while storing the queue file")
sys.exit(0)
#
# ---------- entry point ------------------------------------------------------
#
if __name__ == "__main__":
Main()
| daa0786fc7fd1d96f9c6e0e9ed63a8a971ab6949 | [
"Markdown",
"C",
"Python"
] | 9 | Markdown | mycure/emls | 2b65fafd111b56904e16732390c161b2e5c3d42d | 2b2560f5dc4a6219fed400928096c4f7d922fb82 |
refs/heads/master | <repo_name>tylerj9010/Week-2-Assessment-JUnit<file_sep>/README.md
# Week-2-Assessment-JUnit
Shape classes tested with JUnit
<file_sep>/src/tests/TestCircle.java
package tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import shapes.Circle;
public class TestCircle {
Circle circle = new Circle();
@Before
public void setUp() throws Exception {
}
//Set Delta to .001 as I rounded to 3 decimal places
@Test
public void testCircleCircumferenceOne() {
circle.setRadius(3);
assertEquals(18.849, circle.circumference(), 0.001);
}
@Test
public void testCircleCircumferenceTwo() {
circle.setRadius(78);
assertEquals(490.088, circle.circumference(), 0.001);
}
@Test
public void testCircleArea() {
circle.setRadius(8);
assertEquals(201.062, circle.area(), 0.001);
}
@Test
public void testCircleNotNull() {
circle.setRadius(8);
assertNotNull(circle);
}
}
<file_sep>/src/tests/TestRectangle.java
package tests;
import static org.junit.Assert.*;
import shapes.Rectangle;
import org.junit.Before;
import org.junit.Test;
public class TestRectangle {
Rectangle rec = new Rectangle();
@Before
public void setUp() throws Exception {
}
//Set Delta to .001 as I rounded to 3 decimal places
@Test
public void testRectanglePerimeterOne() {
rec.setLength(8d);
rec.setWidth(12d);
assertEquals(40, rec.perimeter(), 0.001);
}
@Test
public void testRectanglePerimeterTwo() {
rec.setLength(4.15);
rec.setWidth(2.62);
assertEquals(13.54, rec.perimeter(), 0.001);
}
@Test
public void testRectangleArea() {
rec.setLength(8);
rec.setWidth(12);
assertEquals(96, rec.area(), 0.001);
}
@Test
public void testRectangleIsSquare() {
rec.setLength(5);
rec.setWidth(5);
assertTrue(rec.isSquare());
}
@Test
public void testRectangleIsNotSquare() {
rec.setLength(7);
rec.setWidth(9);
assertFalse(rec.isSquare());
}
}
<file_sep>/src/shapes/Rectangle.java
package shapes;
public class Rectangle {
private double length;
private double width;
public Rectangle() {
super();
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double perimeter() {
double p = this.getLength() + this.getWidth();
p *= 2;
return p;
}
public double area() {
double a = this.getLength() * this.getWidth();
return a;
}
public Boolean isSquare() {
if (this.length == this.width)
return true;
return false;
}
}
| 22250bf6bfad72c8d18c86a4a6e211a5d9f95cb9 | [
"Markdown",
"Java"
] | 4 | Markdown | tylerj9010/Week-2-Assessment-JUnit | 10031aa39a8112ee9ff2a41e5f0d831b9668ab32 | 134d8de33ff210d5a7274bb49a3d634298d610b9 |
refs/heads/master | <repo_name>yudistiafirman/Codemi<file_sep>/Src/Redux/Reducer/QrcodeReducer/QrcodeReducer.js
import { INVISIBLE, IS_VISIBLE } from "./QrcodeType"
const data ={
isvisible:false
}
const qrcodeReducer=(state=data,action)=>{
switch(action.type){
case IS_VISIBLE:
return {...state,isvisible:true}
case INVISIBLE:
return {...state,isvisible:false}
default:
return state
}
}
export default qrcodeReducer<file_sep>/Src/Redux/Reducer/EmailReducer/EmailReducer.js
import {CHANGE_EMAIL,EMAIL_FOCUS,EMAIL_ERROR, EMAIL_BLUR}from './EmailType'
const data = {
value:'',
focus:false,
error:''
}
const emailReducer=(state=data,action)=>{
switch(action.type){
case CHANGE_EMAIL:
return {...state,value:action.payload}
case EMAIL_FOCUS:
return {...state,focus:true}
case EMAIL_ERROR:
return {...state,error:action.payload,focus:false}
case EMAIL_BLUR:
return{...state,focus:false}
default:
return state
}
}
export default emailReducer<file_sep>/Src/Redux/Reducer/PasswordReducer/PasswordReducer.js
import {CHANGE_PASSWORD,PASSWORD_FOCUS,PASSWORD_ERROR, PASSWORD_BLUR,REVEAL_PASSWORD} from './PasswordType'
const data = {
passvalue:'',
passfocus:false,
passerror:'',
reveal:false
}
const passwordReducer=(state=data,action)=>{
switch(action.type){
case CHANGE_PASSWORD:
return {...state,passvalue:action.payload}
case PASSWORD_FOCUS:
return {...state,passfocus:true}
case PASSWORD_ERROR:
return {...state,passerror:action.payload,focus:false}
case PASSWORD_BLUR:
return{...state,passfocus:false}
case REVEAL_PASSWORD:{
return {...state,reveal:!state.reveal}
}
default:
return state
}
}
export default passwordReducer<file_sep>/Src/Component/LoginContainer/LoginContainer.js
import React from 'react'
import { Dimensions, Image, StyleSheet, View, Text } from 'react-native'
import SocialLogin from '../SocialLogin/SocialLogin'
import batik from '../../Supports/Images/pattern.jpg'
const { width } = Dimensions.get('window')
const aspectRatio = 750 / 1125
const height = width * aspectRatio
const styles = StyleSheet.create({
pattern: {
width,
height,
borderBottomLeftRadius: 75
}
})
const Container = ({ children}) => {
return (
<View style={{ flex: 1, backgroundColor: "#0C0D34" }}>
<View style={{ backgroundColor: "white" }}>
<View style={{ borderBottomLeftRadius: 75, overflow: 'hidden', height: (height * 0.61), backgroundColor: 'white' }}>
<Image source={batik} style={styles.pattern} />
</View>
</View>
<View style={{ flex: 1, }}>
<Image source={batik} style={{
...StyleSheet.absoluteFillObject,
width,
height,
}} />
<View style={{ borderRadius: 75, borderTopLeftRadius: 0, backgroundColor: 'white', flex: 1 }}>
{children}
</View>
</View>
<View style={{ backgroundColor: "#0C0D34", paddingTop: 10, padding: 10 }}>
<SocialLogin/>
</View>
</View>
)
}
export default Container<file_sep>/Src/Component/Myinput/Myinput.js
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import React from "react"
import { Text, TextInput, View, StyleSheet, TouchableOpacity } from "react-native"
const MyInput = ({iconRight,iconRightSize,onPressIcon, text, icon, isPass, size,focus,onFocus,onBlur ,onChangeText, value, bgColor, placeholder,error }) => {
const styles = StyleSheet.create({
inputSection: {
flexDirection: 'row',
alignItems: "center",
justifyContent: "center",
paddingLeft: 5,
borderWidth: 1,
borderColor: focus?"#292929":error?"red":"#94b4a4",
borderRadius: 20,
overflow: 'hidden',
backgroundColor: bgColor,
},
ImageStyle: {
alignItems: 'center',
color: "#b3b3b3",
},
input: {
fontSize: 14,
color: "#b3b3b3",
},
textInput: {
fontSize: 18,
flex: 1
},
forgotPass: {
alignSelf: "flex-end",
color: "#5198e9",
fontWeight: "bold",
fontSize: 12
},
})
return (
<View style={{width:'100%'}}>
<Text style={styles.input}>{text}</Text>
<View style={styles.inputSection} >
<Icon name={icon} size={size} style={styles.ImageStyle} />
<TextInput style={styles.textInput} onFocus={onFocus} onBlur={onBlur} placeholder={placeholder} secureTextEntry={isPass} value={value} onChangeText={onChangeText} />
<TouchableOpacity style={{paddingRight:10}} onPress={onPressIcon}>
<Icon name={iconRight} size={iconRightSize} style={styles.ImageStyle} />
</TouchableOpacity>
</View>
</View>
)
}
export default MyInput<file_sep>/README.MD
# Apps Description
- aplikasi ini memiliki fitur untuk menscan qr code dari sesama users yang sudah terdaftar, setiap users mempunyai qr code nya masing-masing, sehingga ketika users menscan qr code users lain ,akan muncul foto , nama, dan umur users yg discan tersebut.
# intruksi menjalankan program
# Login
- isi form yang tersedia dengan users email dan password sebagai berikut :
1. email: <EMAIL>,password:<PASSWORD>
2. email: <EMAIL>,password:<PASSWORD>
# Main Menu
- sub-sub pada Main Menu, sebagai berikut:
- Peek and Seek : untuk menscan qr code dari user lain
- Your Qr Code is here : untuk membuka qr code dari user
- Logout : untuk keluar dari aplikasi
# Scan
- tekan peek and seek untuk mulai menscan qr code dari users lain setelah berhasi terscan maka dilayar akan muncul foto, nama, serta umur users yg telah discan , tekan tombol scan again untuk menscan lagi dan enough untuk kembali menu utama
# Users qr code
- tekan sub menu your qr code is here untuk melihat qr code users dan untuk menunjukankann kepada orang lain
# Logout
- tekan sub menu logout untuk keluar dari aplikasi<file_sep>/Src/Redux/Actions/LoginAction.js
import AsyncStorage from "@react-native-async-storage/async-storage"
import { ERROR_LOGIN, LOADING, LOGIN } from "../Reducer/LoginReducer/LoginType"
export const onLogin=(idx)=>{
return (dispatch)=>{
AsyncStorage.setItem('id',JSON.stringify(idx)).then((response)=>{
dispatch({
type:LOGIN,
payload:idx
})
}).catch((error)=>{
})
}
}
export const loggedIn =(idx)=>{
return {
type:LOGIN,
payload:idx
}
}
export const onLogout=()=>{
return(dispatch)=>{
AsyncStorage.removeItem('id')
}
}
export const isLoading=()=>{
return {
type:LOADING
}
}<file_sep>/Src/Component/Drawer/Drawer.js
import React from 'react'
import { View, Text,StyleSheet } from 'react-native'
import Icon from 'react-native-vector-icons/AntDesign'
import { RectButton } from 'react-native-gesture-handler'
const Drawer = ({ onPress, label, bgColor, name, }) => {
const styles=StyleSheet.create({
buttonContainer:{
flexDirection: 'row',
alignItems: 'center',
padding: 5
},
iconContainer:{
width: 40,
height: 40,
borderRadius: 40,
backgroundColor: bgColor,
alignItems: 'center',
justifyContent: 'center'
}
})
return (
<RectButton onPress={onPress} style={{ borderRadius: 30 }}>
<View style={styles.buttonContainer} >
<View style={styles.iconContainer}>
<Icon name={name} color="white" size={30} />
</View>
<Text style={{ marginLeft: 20 ,fontSize:16}}>{label}</Text>
</View>
</RectButton>
)
}
export default Drawer<file_sep>/Src/Redux/Reducer/index.js
import emailReducer from './EmailReducer/EmailReducer'
import passwordReducer from './PasswordReducer/PasswordReducer'
import {combineReducers}from 'redux'
import userReducer from './UserReducers/UserReducer'
import loginReducer from './LoginReducer/LoginReducer'
import qrcodeReducer from './QrcodeReducer/QrcodeReducer'
import scannerReducer from './ScannerReducer/ScannerReducer'
const rootReducer=combineReducers({
email:emailReducer,
password:<PASSWORD>,
user:userReducer,
login:loginReducer,
qrcode:qrcodeReducer,
scan:scannerReducer
})
export default rootReducer
<file_sep>/Src/Component/CustomHeader/CustomHeader.js
import React from 'react'
import { View, Text, StyleSheet, SafeAreaView, Dimensions } from 'react-native'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
const CustomHeader = ({ padding, position, children, onPress, leftIcon, rightIcon, title }) => {
const {height}=Dimensions.get('screen')
const styles = StyleSheet.create({
children: {
padding: 30,
position: position,
top: 0,
left: 0,
right: 0,
bottom: height/2/2-50,
borderTopLeftRadius: 75,
backgroundColor: "white",
justifyContent: 'center'
},
topColor:{
backgroundColor: "#0C0D34",
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
borderBottomRightRadius: 75,
flexDirection: 'row',
justifyContent: 'space-between'
}
})
return <SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 0.2, backgroundColor: 'white' }} >
<View style={styles.topColor} >
<Icon onPress={onPress} name={leftIcon} color="white" size={22} />
<Text style={{ color: "white", textAlign: 'center', marginTop: 2, marginBottom: 30 }}>{title}</Text>
<Icon name={rightIcon} color="white" size={22} />
</View>
</View>
<View style={{ flex: 0.8 ,backgroundColor:'white'}}>
<View style={{ flex: 1, backgroundColor: "#0C0D34" }} />
<View style={{ flex: 1, }} />
<View style={styles.children}>
{children}
</View>
</View>
</SafeAreaView>
}
export default CustomHeader
<file_sep>/Src/Screens/Login/Login.js
import React, { useEffect, useState } from 'react'
import { View,Text,StyleSheet } from 'react-native'
import { connect } from 'react-redux'
import Button from '../../Component/Button/Button'
import LoginContainer from '../../Component/LoginContainer/LoginContainer'
import MyInput from '../../Component/Myinput/Myinput'
import {onChangeEmail, onEmailBlur, onFocusEmail, onEmailError}from '../../Redux/Actions/EmaiAction'
import {onChangePassword,onPasswordBlur,onFocusPassword,onPasswordError,onPasswordReveal}from '../../Redux/Actions/PasswordAction'
import {onLogin}from '../../Redux/Actions/LoginAction'
import AwesomeAlert from 'react-native-awesome-alerts'
function Login({navigation,user,email,onChangeEmail,onFocusEmail,onEmailBlur,onEmailError,password,onChangePassword,onPasswordBlur,onFocusPassword,onPasswordError,onPasswordReveal,onLogin}) {
const {value,focus,error}=email
const {passvalue,passfocus,passerror,reveal}=password
const [showalert,SetAlert]=useState(false)
useEffect(()=>{
onEmailError(value)
onPasswordError(passvalue)
},[value,passvalue])
const onUserLogin=()=>{
let index= user.findIndex((v)=>v.email===value && v.password===<PASSWORD>value)
//jika index !==-
if(index!==-1){
onLogin(index)
navigation.push('main')
}else{
SetAlert(true)
}
}
return (
<LoginContainer>
<View style={styles.title}>
<Text style={[{...styles.headerText,fontSize: 24, color: '#0C0D34',}]}>Welcome Back</Text>
<Text style={styles.headerText}>use your credential below</Text>
<Text style={styles.headerText}>to login to your account</Text>
</View>
<View style={styles.inputContainer}>
{/* input untuk email */}
<MyInput
value={value}
focus={focus}
onFocus={()=>onFocusEmail(error)}
error={error}
text="enter your mail"
icon="email"
onBlur={()=>onEmailBlur(value)}
size={22}
onChangeText={onChangeEmail}
isPass={false} />
<Text style={styles.errorText}>{error}</Text>
{/* input untuk password */}
<MyInput
text="confirm your password"
value={passvalue}
focus={passfocus}
isPass={reveal?false:true}
onPressIcon={onPasswordReveal}
onBlur={()=>onPasswordBlur(passvalue)}
onFocus={()=>onFocusPassword(passerror)}
error={passerror}
onChangeText={onChangePassword}
icon={'lock'}
iconRightSize={22}
size={22}
iconRight={reveal?'eye-outline':'eye-off-outline'}
/>
<Text style={styles.errorText}>{passerror}</Text>
</View>
<View style={styles.buttonContainer}>
<Button onPress={onUserLogin} variant="primary" disabled={passerror ||error||!value||!passvalue} label="Login"/>
</View>
<AwesomeAlert
show={showalert}
title="Login failed"
message="You Have no account yet!"
closeOnTouchOutside={true}
showCancelButton={true}
cancelText="cancel"
confirmButtonColor="#DD6B55"
onCancelPressed={() => SetAlert(false)}
onConfirmPressed={()=>SetAlert(false)}
/>
</LoginContainer>
)
}
const styles= StyleSheet.create({
title:{
flex:0.1,
justifyContent:'flex-start',
alignItems:'flex-start',
margin:20
},
inputContainer:{
flex:0.4,
justifyContent:'space-around',
margin:20,
},
buttonContainer:{
flex:0.2,
justifyContent:'flex-start',
alignItems:'center',
margin:20
},
textTitle:{
fontSize:32,
fontWeight:'bold'
},
smallText:{
fontSize:12,
marginTop:20
},
errorText:{
color:'red',
fontStyle:'italic',
fontSize:12,
marginTop:5
},
headerText:{
fontWeight:'bold',
color: 'rgba(12,13,52,0.5)',
textAlign: 'center',}
})
const mapDispatchToProps={
onLogin, onChangeEmail,onFocusEmail,onEmailBlur,onEmailError,onChangePassword,onFocusPassword,onPasswordBlur,onPasswordError,onPasswordReveal
}
const mapStateToProps=(state)=>{
return {
email:state.email,
password:state.password,
user:state.user
}
}
export default connect(mapStateToProps,mapDispatchToProps) (Login)
<file_sep>/Src/Component/Button/Button.js
import React from 'react'
import { Text, StyleSheet, TouchableHighlight } from 'react-native'
const Button = ({ variant, label, onPress, loading,disabled }) => {
const styles = StyleSheet.create({
container: {
borderRadius: 50,
height: 50,
width: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: disabled ? "#dddddd" : variant === "transparent" ? '#f5f5f5' :variant === "primary" ? "#2CB9B0" : 'rgba(12,13,52,0.14)'
//
},
label: {
fontSize: 15,
fontFamily: "SF-Pro-Text-Regular",
color: variant === "primary" ? 'white' : '#0C0D34'
}
})
return (
<TouchableHighlight underlayColor="#eeeeee" style={styles.container} disabled={disabled} onPress={onPress}>
<Text style={styles.label}>{label}</Text>
</TouchableHighlight>
)
}
export default Button<file_sep>/Src/Component/ModalHeader/ModalHeader.js
import React from 'react'
import { SafeAreaView, Text,StyleSheet,View, TouchableOpacity } from 'react-native'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
function ModalHeader({iconLeft,title,IconRight,onLeftPress,onRightPress,disabled}) {
return (
<View style={style.header}>
<TouchableOpacity onPress={onLeftPress}>
<Icon name={iconLeft} size={30} color="red"/>
</TouchableOpacity>
<Text style={{fontSize:18,fontWeight:'bold'}}>{title}</Text>
<TouchableOpacity disabled={disabled} onPress={onRightPress}>
<Icon name={IconRight} size={30} color="red"/>
</TouchableOpacity>
</View>
)
}
const style=StyleSheet.create({
header:{
height:70,
borderColor:'lightgray',
flexDirection:'row',
justifyContent:'space-around',
alignItems:'center',
position:'absolute',
top:0,
left:0,
right:0
}
})
export default ModalHeader<file_sep>/Src/Redux/Reducer/QrcodeReducer/QrcodeType.js
export const IS_VISIBLE='IS_VISIBLE'
export const INVISIBLE='INSVISIBLE'<file_sep>/Src/Redux/Reducer/PasswordReducer/PasswordType.js
export const CHANGE_PASSWORD = '<PASSWORD>'
export const PASSWORD_FOCUS='<PASSWORD>'
export const PASSWORD_ERROR='<PASSWORD>'
export const PASSWORD_BLUR='<PASSWORD>'
export const REVEAL_PASSWORD='<PASSWORD>'<file_sep>/Src/Component/Modal/Modal.js
import React from 'react'
import { View } from 'react-native'
import Modal from 'react-native-modal'
import Header from '../ModalHeader/ModalHeader'
import QRCode from 'react-native-qrcode-svg';
import { connect } from 'react-redux';
function ModalSorting({isVisible,onSwipeComplete,onLeftPress,user,login}) {
const {index}=login
return (
<Modal style={{justifyContent:'flex-end',margin:0}} isVisible={isVisible} onSwipeComplete={onSwipeComplete}>
<View style={{flex:0.5,backgroundColor:'#ffff',borderTopRightRadius:20,borderTopLeftRadius:20,alignItems:'center',justifyContent:'center'}}>
<Header iconLeft="close" title="YourQrCode" onLeftPress={onLeftPress}/>
{
index? <QRCode
size={200}
value={JSON.stringify(index)}
/>
:null
}
</View>
</Modal>
)
}
const mapStateToProps=(state)=>{
return {
user:state.user,
login:state.login
}
}
export default connect(mapStateToProps,null)( ModalSorting)<file_sep>/Src/Redux/Actions/PasswordAction.js
import { CHANGE_PASSWORD, PASSWORD_BLUR, PASSWORD_ERROR, PASSWORD_FOCUS,REVEAL_PASSWORD } from "../Reducer/PasswordReducer/PasswordType"
export const onChangePassword =(text)=>{
return {
type:CHANGE_PASSWORD,
payload:text
}
}
export const onFocusPassword =(error)=>{
if(error){
return{
type:PASSWORD_ERROR,
payload:error
}
}else{
return {
type:PASSWORD_FOCUS
}
}
}
export const onPasswordBlur=(value)=>{
if(value.length===0){
return {
type:PASSWORD_ERROR,
payload:'password cannot be empty'
}
}else{
return {
type:PASSWORD_BLUR
}
}
}
export const onPasswordError=(text)=>{
const re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/
if(text.length===0){
return {
type:PASSWORD_ERROR,
}
}else if(re.test(text)){
return {
type:PASSWORD_ERROR,
}
}else{
return {
type:PASSWORD_ERROR,
payload:'password at least contain 8 character'
}
}
}
export const onPasswordReveal =()=>{
return {
type:REVEAL_PASSWORD
}
}<file_sep>/Src/Component/SocialLogin/SocialLogin.js
import React from 'react'
import { View, Text, Image } from 'react-native'
const SocialLogin = () => {
return (
<View style={{ flexDirection: 'row', justifyContent: 'space-evenly', marginHorizontal: 20 }}>
<View style={{ backgroundColor: 'white', width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../../Supports/Images/google-logo-9824.png')} style={{ width: 22, height: 22 }} />
</View>
<View style={{ backgroundColor: 'white', width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../../Supports/Images/facebook.png')} style={{ width: 22, height: 22 }} />
</View>
<View style={{ backgroundColor: 'white', width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../../Supports/Images/applelogo.png')} style={{ width: 70, height: 70 }} />
</View>
</View>
)
}
export default SocialLogin<file_sep>/index.js
/**
* @format
*/
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {Provider}from 'react-redux'
import {applyMiddleware, createStore}from 'redux'
import rootReducer from './Src/Redux/Reducer/index'
import React from 'react'
import thunk from 'redux-thunk'
const store= createStore(rootReducer,applyMiddleware(thunk))
const index =()=>{
return <Provider store={store}>
<App/>
</Provider>
}
AppRegistry.registerComponent(appName, () => index);
<file_sep>/Src/Redux/Reducer/ScannerReducer/ScannerType.js
export const SHOW_SCANNER= 'SHOW_SCANNER'
export const HIDE_SCANNER='HIDE_SCANNER'
export const RESULT='RESULT'
export const SCAN_AGAIN='SCAN_AGAIN'<file_sep>/Src/Navigation/MainRoute.js
import React from 'react'
import {createStackNavigator}from '@react-navigation/stack'
import LoginRoute from './AccountRoute'
import Welcome from '../Screens/Welcome/Welcome'
const MainStack =createStackNavigator()
function MainRoute() {
return (
<MainStack.Navigator headerMode={null}>
<MainStack.Screen name="welcome" component={Welcome}/>
<MainStack.Screen name="main" component={LoginRoute}/>
</MainStack.Navigator>
)
}
export default MainRoute
| 6b099c9db88ad64b65af809b1ddcafb2389f4ece | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | yudistiafirman/Codemi | 10551b0ad7c3eb5d47a79723e28e9405dd2b3f59 | 14c214ba0dcf5bed103c59f17cbe9701c00cf5a7 |
refs/heads/master | <repo_name>nazarzel/WCF<file_sep>/AppForWCF/Client/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Threading.Tasks;
namespace Client
{
[ServiceContract]
public interface IMyMath
{
[OperationContract]
int Add(int a, string c, int b);
}
class Program
{
static void Main(string[] args)
{
try
{
ChannelFactory<IMyMath> factory = new ChannelFactory<IMyMath>(
new WSHttpBinding(),
new EndpointAddress("http://localhost/MyMath/Ep1")
);
IMyMath channel = factory.CreateChannel();
int a;
string c;
int b;
a = Convert.ToInt32(Console.ReadLine());
c = Console.ReadLine();
b = Convert.ToInt32(Console.ReadLine());
Console.ReadLine();
int result = channel.Add(a, c, b);
try
{
Console.WriteLine("result: {0}", result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
factory.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| 33276281105b25e846d853c5c2e0b916d779b754 | [
"C#"
] | 1 | C# | nazarzel/WCF | 848c1800fd8fe834d6971c4a6dc5e7361b75bb20 | f5444db402e72b69d7bde5a3771812eb00c155b9 |
refs/heads/master | <file_sep>package com.gmail.gnoianko;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = new int[15];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 11);
}
int[] b = Arrays.copyOf(a, 30);
for (int j = 0; j < a.length; j++) {
b[j + 15] = a[j] * 2;
}
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
}
<file_sep>package com.gmail.gnoianko;
import java.io.File;
public class Main {
public static void main(String[] args) {
System.out.println(getFoldersInfo("E:\\КУРСИ JAVA\\projects\\Homework8.1.2"));
}
public static String getFoldersInfo(String address) {
StringBuilder name = new StringBuilder();
File folder = new File(address);
File[] files = folder.listFiles();
for (File x : files) {
if (x.isDirectory()) {
name.append(x.getName()+System.lineSeparator());
}
}
return name.toString();
}
}
<file_sep>package com.gmail.gnoianko;
public class Main {
public static void main(String[] args) {
String text = "My name is Bohdan";
System.out.println(countResult(text));
}
public static int countResult(String text) {
int count = 0;
String[] t = text.split("[ ]");
for (int i = 0; i < t.length; i++) {
count++;
}
return count;
}
}
<file_sep>package com.gmail.gnoianko;
import java.util.Formatter;
public class Main {
public static void main(String[] args) {
print();
}
public static void print() {
double pi = Math.PI;
Formatter form = new Formatter();
for (int i = 0; i < 10; i++) {
String h = "%." + (i + 2) + "f";
form.format(h, pi);
String text = form.toString();
System.out.println(text);
form = new Formatter();
}
}
}<file_sep>package com.gmail.gnoianko;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
int fact = 1;
System.out.println("Input digit from 5 to 15");
a = sc.nextInt();
if ((a > 4) & (a < 16)) {
for (int i = 1; i <= a; i++) {
fact = fact * i;
}
System.out.println(a + "!=" + fact);
} else {
System.out.println("Error");
}
sc.close();
}
}
<file_sep>package com.gmail.gnoianko;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input binary number:");
String bin = sc.nextLine();
toDec(bin);
sc.close();
}
static void toDec(String bin) {
char[] a = bin.toCharArray();
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') {
t = (int) (t + (1 * Math.pow(2, a.length - 1 - i)));
} else if (a[i] != '0') {
System.out.println("Incorrect input");
return;
}
}
System.out.println("\"" + bin + "\" -> " + t);
}
} | 0212f244aa406ab8347de8ccada66fa5052b1f8c | [
"Java"
] | 6 | Java | Hnoianko/prog.kiev.ua-JavaStart- | 73445f3268ca5982f8b6b07e7728f79b19c5f069 | e717cdb1cf4e39f69bb8a003baf7a0edb9b8120f |
refs/heads/master | <repo_name>koloskus/illustrator-fill-stroke-switch<file_sep>/multi-color-fillstroke-swap.jsx
/**********************************
** **
** A Simple-Ass Code **
** I think Illustrator **
** Has Been Missin': **
** **
** Swap fill for Stroke **
** on multiple shapes in **
** Adobe Illustrator CC 19 **
** **
** <NAME> 5/12/16 **
** MIT License yadda yadda **
** blah blah whatever **
** **
**********************************/
var docRef = app.activeDocument;
var selRef = docRef.selection;
if (selRef.length == 0) {alert("You haven't selected anything, dummy.")}
for (var i=0; i<selRef.length; i++) {
var pathRef = selRef[i];
if (!(pathRef.fillColor instanceof RGBColor) &&
(!(pathRef.fillColor instanceof GradientColor)) &&
(!(pathRef.fillColor instanceof NoColor)) &&
(!(pathRef.fillColor instanceof GrayColor))) {
alert("No fill color data found.")
}
if (!(pathRef.strokeColor instanceof RGBColor) &&
(!(pathRef.strokeColor instanceof GradientColor)) &&
(!(pathRef.strokeColor instanceof NoColor)) &&
(!(pathRef.strokeColor instanceof GrayColor))) {
alert("No stroke color data found.")
}
var strokeWidthHolder = pathRef.strokeWidth;
var fillColorHolder = pathRef.fillColor;
var strokeColorHolder = pathRef.strokeColor;
pathRef.stroked = false;
pathRef.stroked = true;
if (pathRef.fillColor instanceof RGBColor) {
pathRef.strokeColor = new RGBColor()
} else if (pathRef.fillColor instanceof GradientColor) {
pathRef.strokeColor = new GradientColor()
} else if (pathRef.fillColor instanceof NoColor) {
strokeWidthHolder = 0;
pathRef.strokeColor = new NoColor()
} else if (pathRef.fillColor instanceof GrayColor) {
strokeWidthHolder = 0;
pathRef.strokeColor = new GrayColor()
}
pathRef.strokeColor = fillColorHolder;
pathRef.strokeWidth = strokeWidthHolder;
pathRef.filled = false;
pathRef.filled = true;
if (pathRef.strokeColor instanceof RGBColor) {
pathRef.fillColor = new RGBColor()
} else if (pathRef.strokeColor instanceof GradientColor) {
pathRef.fillColor = new GradientColor()
} else if (pathRef.strokeColor instanceof NoColor) {
pathRef.fillColor = new NoColor()
} else if (pathRef.strokeColor instanceof GrayColor) {
pathRef.fillColor = new GrayColor()
}
pathRef.fillColor = strokeColorHolder;
}
<file_sep>/README.md
# illustrator-fill-stroke-switch
Switch multiple Fill Colors to Stroke Colors in Adobe Illustrator
As it stands by default, if you select multiple filled items in Illustrator and try to switch the Fill Color to the Outline Color it won't work. The closest and fastest approximation is to select by Fill Color and swap all fills for outlines, but what if you have hundreds of colors that you want to do this for?
How to run
----
If you're new to running scripts in Illustrator here's a rough approximation of how to do it:
If you want to run it through Illustrator:
----
Open Illustrator, make your design biz, then select the items you want to swap the fill color with the outline color. On Mac, press Command + F12. This will bring up a file browser where you can select the script file. Select the .jsx file, click "Open" and it'll swap your fills for outlines!
If you want to edit it or run it through ExtendScript Toolkit
----
Open ESTK, select "Open" from the navigation and select the .jsx file. From here you can edit it in the development environment, or you can run it directly into Illustrator by selecting the appropirate version of Illustrator from the drop-down in the top left (this has been most recently tested in Illustrator CC 19) then clicking the green play button. (tbh i don't recommend running this through ESTK b/c it's a bit antiquated. you can edit this script in any text editor and run it with the above mentioned key commands and it'll probably feel 99% more intuitive/faster. The only benefit of ESTK is the console readouts, which you shouldn't need if you've ungrouped and released all compound paths. (see below if that's confusing)
!!!!! IMPORTANT !!!!!
----
The items you select need to be ungrouped and you also need to release any compound paths that exist in the items you've selected for this to work. If you run the .jsx file as you've downloaded it and it doesn't work it's most likely because your objects are grouped or are a compound path. If you outline type you've written, you HAVE to ungroup and release compound path before this will work.
| 40f85cb9e12483d57fa3eb213b95522040576d23 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | koloskus/illustrator-fill-stroke-switch | b02df256aa69be819dfe83c866a6f2a1744f8b10 | 4da4d34cdbeefd5b2501526ab74d856275d9c1cb |
refs/heads/develop | <file_sep>/* eslint-disable no-undef */
import { render } from '@testing-library/react';
import Divider from '../../components/Divider';
describe('<Divider />', () => {
it('should render divider component', () => {
const { container } = render(<Divider />);
expect(container.querySelector('div.divider')).not.toBeNull();
});
it('should render custom height for divider', () => {
const { container } = render(<Divider height="divide-y-4" />);
expect(
container.querySelector('div[class="divider divide-y-4"]')
).not.toBeNull();
});
it('should render default height for divider', () => {
const { container } = render(<Divider />);
expect(
container.querySelector('div[class="divider divide-y-2"]')
).not.toBeNull();
});
it('should render divider color', () => {
const { container } = render(<Divider color="divide-blue-500" />);
expect(
container.querySelector('div[class="divider divide-y-2 divide-blue-500"]')
).not.toBeNull();
});
it('should render expected divided style', () => {
const { container } = render(<Divider style="divide-solid" />);
expect(
container.querySelector('div[class="divider divide-y-2 divide-solid"]')
).not.toBeNull();
});
});
<file_sep>/* eslint-disable no-undef */
import { screen, render } from '@testing-library/react';
import Label from '../../components/Label';
describe('<Label />', () => {
it('Should render label component', () => {
render(<Label text="" />);
expect(screen.getByTestId('label-normal')).toBeInTheDocument();
});
it('Should render label component with an img', () => {
render(
<Label
text=""
src="https://images.unsplash.com/photo-1616066959553-e13b2cfed557?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80"
/>
);
expect(screen.getByTestId('label-image')).toBeInTheDocument();
});
});
<file_sep>export { default as Button } from './Button';
export { default as Loader } from './Loader';
export { default as Container } from './Container';
export { default as Divider } from './Divider';
export { default as Header } from './Header';
<file_sep># tailwind-master-piece.github.io
These are the components that show whats you can do with Tailwind CSS
<file_sep>/* eslint-disable no-undef */
import { render } from '@testing-library/react';
import Header from '../../components/Header';
describe('<Header />', () => {
it('should render Header component', () => {
const { container } = render(<Header />);
expect(container).not.toBeNull();
});
it('should container have grid class', () => {
const { container } = render(<Header />);
expect(container.querySelector('div.grid')).not.toBeNull();
});
it('should render expected columns', () => {
const { container } = render(<Header columns="grid-cols-9" />);
expect(
container.querySelector('div[class="grid grid-cols-9"]')
).not.toBeNull();
});
it('should render expected backgroundColor', () => {
const { container } = render(<Header backgroundColor="bg-blue-900" />);
expect(
container.querySelector('div[class="grid bg-blue-900"]')
).not.toBeNull();
});
it('should render expected text color', () => {
const { container } = render(<Header textColor="text-pink-600" />);
expect(
container.querySelector('div[class="grid text-pink-600"]')
).not.toBeNull();
});
it('should add horizontal and vertical paddling', () => {
const { container } = render(
<Header horizontalPadding="px-60" verticalPadding="py-8" />
);
expect(
container.querySelector('div[class="grid px-60 py-8"]')
).not.toBeNull();
});
it('should add horizontal and vertical margin', () => {
const { container } = render(
<Header verticalMargin="my-8" horizontalMargin="mx-8" />
);
expect(
container.querySelector('div[class="grid mx-8 my-8"]')
).not.toBeNull();
});
it('should render children', () => {
const { container } = render(
<Header>
<h1>I am a children</h1>
<p>I am another children</p>
</Header>
);
const header = container.querySelector('div.grid');
expect(header.children.length).toBe(2);
});
});
<file_sep>/* eslint-disable no-undef */
import { render } from '@testing-library/react';
import Container from '../../components/Container';
describe('<Container />', () => {
it('should render container component', () => {
const { container } = render(<Container />);
expect(container.querySelector('div[class="container"]')).not.toBeNull();
});
it('should return the children', () => {
const { container } = render(
<Container>
<>
<h2>Hello</h2>
<p>I am a child</p>
</>
</Container>
);
expect(
container.querySelector('div[class="container"]').children
).not.toBeNull();
});
it('should center container', () => {
const { container } = render(
<Container center={true}>
<>
<h2>Hello</h2>
<p>I am a child</p>
</>
</Container>
);
expect(
container.querySelector('div[class="container mx-auto"]')
).not.toBeNull();
});
it('should no center the container', () => {
const { container } = render(
<Container center={false}>
<>
<h2>Hello</h2>
<p>I am a child</p>
</>
</Container>
);
expect(
container.querySelector('div[class="container mx-auto"]')
).toBeNull();
});
it('should add horizontal and vertical paddling', () => {
const { container } = render(
<Container horizontalPadding="px-60" verticalPadding="py-8" />
);
expect(
container.querySelector('div[class="container px-60 py-8"]')
).not.toBeNull();
});
it('should add horizontal and vertical margin', () => {
const { container } = render(
<Container verticalMargin="my-8" horizontalMargin="mx-8" />
);
expect(
container.querySelector('div[class="container mx-8 my-8"]')
).not.toBeNull();
});
it('should render expected background color', () => {
const { container } = render(<Container backgroundColor="bg-blue-100" />);
expect(
container.querySelector('div[class="container bg-blue-100"]')
).not.toBeNull();
});
it('should render expected text color', () => {
const { container } = render(<Container textColor="text-black" />);
expect(
container.querySelector('div[class="container text-black"]')
).not.toBeNull();
});
});
<file_sep>/* eslint-disable no-undef */
import { screen, render } from '@testing-library/react';
import Img from '../../components/Img';
describe('<Img />', () => {
it('Should render img component', () => {
const { container } = render(<Img />);
expect(screen.getByAltText('Description')).toBeInTheDocument();
expect(container.querySelector('.img')).toBeInTheDocument();
});
});
<file_sep>/* eslint-disable no-undef */
import { screen, render } from '@testing-library/react';
import Button from '../../components/Button';
describe('<Button />', () => {
it('should render button component', () => {
const { container } = render(<Button />);
expect(screen.getByTitle('button')).toBeInTheDocument();
expect(container.querySelector('.button')).toBeInTheDocument();
});
it('should render expected color', () => {
const { container } = render(<Button color="bg-green-800" />);
expect(container.querySelector('div.bg-green-800')).toBeInTheDocument();
});
it('should render expected radius', () => {
const { container } = render(<Button radius="rounded-full" />);
expect(container.querySelector('div.rounded-full')).toBeInTheDocument();
});
it('should render expected textColor', () => {
const { container } = render(<Button textColor="text-gray-800" />);
expect(container.querySelector('div.text-gray-800')).toBeInTheDocument();
});
it('should render expected children', () => {
const expectedText = 'hey you';
const { container } = render(
<Button
radius="rounded-full"
color="bg-green-800"
textColor="text-gray-800"
>
hey you
</Button>
);
expect(container.textContent).toBe(expectedText);
});
});
<file_sep>export type Colors =
| 'text-gray-100'
| 'text-gray-200'
| 'text-gray-300'
| 'text-gray-400'
| 'text-gray-500'
| 'text-gray-600'
| 'text-gray-700'
| 'text-gray-800'
| 'text-gray-900'
| 'text-red-100'
| 'text-red-200'
| 'text-red-300'
| 'text-red-400'
| 'text-red-500'
| 'text-red-600'
| 'text-red-700'
| 'text-red-800'
| 'text-red-900'
| 'text-yellow-100'
| 'text-yellow-200'
| 'text-yellow-300'
| 'text-yellow-400'
| 'text-yellow-500'
| 'text-yellow-600'
| 'text-yellow-700'
| 'text-yellow-800'
| 'text-yellow-900'
| 'text-green-100'
| 'text-green-200'
| 'text-green-300'
| 'text-green-400'
| 'text-green-500'
| 'text-green-600'
| 'text-green-700'
| 'text-green-800'
| 'text-green-900'
| 'text-blue-100'
| 'text-blue-200'
| 'text-blue-300'
| 'text-blue-400'
| 'text-blue-500'
| 'text-blue-600'
| 'text-blue-700'
| 'text-blue-800'
| 'text-blue-900'
| 'text-indigo-100'
| 'text-indigo-200'
| 'text-indigo-300'
| 'text-indigo-400'
| 'text-indigo-500'
| 'text-indigo-600'
| 'text-indigo-700'
| 'text-indigo-800'
| 'text-indigo-900'
| 'text-purple-100'
| 'text-purple-200'
| 'text-purple-300'
| 'text-purple-400'
| 'text-purple-500'
| 'text-purple-600'
| 'text-purple-700'
| 'text-purple-800'
| 'text-purple-900'
| 'text-pink-100'
| 'text-pink-200'
| 'text-pink-300'
| 'text-pink-400'
| 'text-pink-500'
| 'text-pink-600'
| 'text-pink-700'
| 'text-pink-800'
| 'text-pink-900'
| 'text-black'
| 'text-white';
export type Size =
| 'text-xs'
| 'text-sm'
| 'text-base'
| 'text-lg'
| 'text-xl'
| 'text-2xl'
| 'text-3xl'
| 'text-4xl'
| 'text-5xl';
export type backgroundColor =
| 'bg-transparent'
| 'bg-black'
| 'bg-white'
| 'bg-gray-50'
| 'bg-gray-100'
| 'bg-gray-200 '
| 'bg-gray-300 '
| 'bg-gray-400'
| 'bg-gray-500'
| 'bg-gray-600'
| 'bg-gray-700'
| 'bg-gray-800'
| 'bg-gray-900'
| 'bg-red-50'
| 'bg-red-100'
| 'bg-red-200'
| 'bg-red-300'
| 'bg-red-400'
| 'bg-red-500'
| 'bg-red-600'
| 'bg-red-700'
| 'bg-red-800'
| 'bg-red-900'
| 'bg-yellow-50'
| 'bg-yellow-100'
| 'bg-yellow-200'
| 'bg-yellow-300'
| 'bg-yellow-400'
| 'bg-yellow-500'
| 'bg-yellow-600'
| 'bg-yellow-700'
| 'bg-yellow-800'
| 'bg-yellow-900'
| 'bg-green-50'
| 'bg-green-100'
| 'bg-green-200'
| 'bg-green-300'
| 'bg-green-400'
| 'bg-green-500'
| 'bg-green-600'
| 'bg-green-700'
| 'bg-green-800'
| 'bg-green-900'
| 'bg-blue-50'
| 'bg-blue-100'
| 'bg-blue-200'
| 'bg-blue-300'
| 'bg-blue-400'
| 'bg-blue-500'
| 'bg-blue-600'
| 'bg-blue-700'
| 'bg-blue-800'
| 'bg-blue-900'
| 'bg-indigo-50'
| 'bg-indigo-100'
| 'bg-indigo-200'
| 'bg-indigo-300'
| 'bg-indigo-400'
| 'bg-indigo-500'
| 'bg-indigo-600'
| 'bg-indigo-700'
| 'bg-indigo-800'
| 'bg-indigo-900'
| 'bg-purple-50'
| 'bg-purple-100'
| 'bg-purple-200'
| 'bg-purple-300'
| 'bg-purple-400'
| 'bg-purple-500'
| 'bg-purple-600'
| 'bg-purple-700'
| 'bg-purple-800'
| 'bg-purple-900'
| 'bg-pink-50'
| 'bg-pink-100'
| 'bg-pink-200'
| 'bg-pink-300'
| 'bg-pink-400'
| 'bg-pink-500'
| 'bg-pink-600'
| 'bg-pink-700'
| 'bg-pink-800'
| 'bg-pink-900';
export type radius =
| 'rounded-sm'
| 'rounded'
| 'rounded-md'
| 'rounded-lg'
| 'rounded-xl'
| 'rounded-2xl'
| 'rounded-3xl'
| 'rounded-full';
export type textColor =
| 'text-transparent'
| 'text-black'
| 'text-white'
| 'text-gray-50'
| 'text-gray-100'
| 'text-gray-200 '
| 'text-gray-300 '
| 'text-gray-400'
| 'text-gray-500'
| 'text-gray-600'
| 'text-gray-700'
| 'text-gray-800'
| 'text-gray-900'
| 'text-red-50'
| 'text-red-100'
| 'text-red-200'
| 'text-red-300'
| 'text-red-400'
| 'text-red-500'
| 'text-red-600'
| 'text-red-700'
| 'text-red-800'
| 'text-red-900'
| 'text-yellow-50'
| 'text-yellow-100'
| 'text-yellow-200'
| 'text-yellow-300'
| 'text-yellow-400'
| 'text-yellow-500'
| 'text-yellow-600'
| 'text-yellow-700'
| 'text-yellow-800'
| 'text-yellow-900'
| 'text-green-50'
| 'text-green-100'
| 'text-green-200'
| 'text-green-300'
| 'text-green-400'
| 'text-green-500'
| 'text-green-600'
| 'text-green-700'
| 'text-green-800'
| 'text-green-900'
| 'text-blue-50'
| 'text-blue-100'
| 'text-blue-200'
| 'text-blue-300'
| 'text-blue-400'
| 'text-blue-500'
| 'text-blue-600'
| 'text-blue-700'
| 'text-blue-800'
| 'text-blue-900'
| 'text-indigo-50'
| 'text-indigo-100'
| 'text-indigo-200'
| 'text-indigo-300'
| 'text-indigo-400'
| 'text-indigo-500'
| 'text-indigo-600'
| 'text-indigo-700'
| 'text-indigo-800'
| 'text-indigo-900'
| 'text-purple-50'
| 'text-purple-100'
| 'text-purple-200'
| 'text-purple-300'
| 'text-purple-400'
| 'text-purple-500'
| 'text-purple-600'
| 'text-purple-700'
| 'text-purple-800'
| 'text-purple-900'
| 'text-pink-50'
| 'text-pink-100'
| 'text-pink-200'
| 'text-pink-300'
| 'text-pink-400'
| 'text-pink-500'
| 'text-pink-600'
| 'text-pink-700'
| 'text-pink-800'
| 'text-pink-900';
export type horizontalPadding =
| 'px-0'
| 'px-px'
| 'px-0.5'
| 'px-1'
| 'px-1.5'
| 'px-2'
| 'px-2.5'
| 'px-3'
| 'px-3.5'
| 'px-4'
| 'px-5'
| 'px-6'
| 'px-7'
| 'px-8'
| 'px-9'
| 'px-10'
| 'px-11'
| 'px-12'
| 'px-14'
| 'px-16'
| 'px-20'
| 'px-24'
| 'px-28'
| 'px-32'
| 'px-36'
| 'px-40'
| 'px-44'
| 'px-48'
| 'px-52'
| 'px-56'
| 'px-60'
| 'px-64'
| 'px-72'
| 'px-80'
| 'px-96';
export type verticalPadding =
| 'py-0'
| 'py-px'
| 'py-0.5'
| 'py-1'
| 'py-1.5'
| 'py-2'
| 'py-2.5'
| 'py-3'
| 'py-3.5'
| 'py-4'
| 'py-5'
| 'py-6'
| 'py-7'
| 'py-8'
| 'py-9'
| 'py-10'
| 'py-11'
| 'py-12'
| 'py-14'
| 'py-16'
| 'py-20'
| 'py-24'
| 'py-28'
| 'py-32'
| 'py-36'
| 'py-40'
| 'py-44'
| 'py-48'
| 'py-52'
| 'py-56'
| 'py-60'
| 'py-64'
| 'py-72'
| 'py-80'
| 'py-96';
export type horizontalMargin =
| 'mx-0'
| 'mx-px'
| 'mx-0.5'
| 'mx-1'
| 'mx-1.5'
| 'mx-2'
| 'mx-2.5'
| 'mx-3'
| 'mx-3.5'
| 'mx-4'
| 'mx-5'
| 'mx-6'
| 'mx-7'
| 'mx-8'
| 'mx-9'
| 'mx-10'
| 'mx-11'
| 'mx-12'
| 'mx-14'
| 'mx-16'
| 'mx-20'
| 'mx-24'
| 'mx-28'
| 'mx-32'
| 'mx-36'
| 'mx-40'
| 'mx-44'
| 'mx-48'
| 'mx-52'
| 'mx-56'
| 'mx-60'
| 'mx-64'
| 'mx-72'
| 'mx-80'
| 'mx-96';
export type verticalMargin =
| 'my-0'
| 'my-px'
| 'my-0.5'
| 'my-1'
| 'my-1.5'
| 'my-2'
| 'my-2.5'
| 'my-3'
| 'my-3.5'
| 'my-4'
| 'my-5'
| 'my-6'
| 'my-7'
| 'my-8'
| 'my-9'
| 'my-10'
| 'my-11'
| 'my-12'
| 'my-14'
| 'my-16'
| 'my-20'
| 'my-24'
| 'my-28'
| 'my-32'
| 'my-36'
| 'my-40'
| 'my-44'
| 'my-48'
| 'my-52'
| 'my-56'
| 'my-60'
| 'my-64'
| 'my-72'
| 'my-80'
| 'my-96';
export type dividerHeight =
| 'divide-y-0'
| 'divide-y-2'
| 'divide-y-4'
| 'divide-y-8';
export type divideColor =
| 'divide-transparent'
| 'divide-black'
| 'divide-white'
| 'divide-gray-50'
| 'divide-gray-100'
| 'divide-gray-200 '
| 'divide-gray-300 '
| 'divide-gray-400'
| 'divide-gray-500'
| 'divide-gray-600'
| 'divide-gray-700'
| 'divide-gray-800'
| 'divide-gray-900'
| 'divide-red-50'
| 'divide-red-100'
| 'divide-red-200'
| 'divide-red-300'
| 'divide-red-400'
| 'divide-red-500'
| 'divide-red-600'
| 'divide-red-700'
| 'divide-red-800'
| 'divide-red-900'
| 'divide-yellow-50'
| 'divide-yellow-100'
| 'divide-yellow-200'
| 'divide-yellow-300'
| 'divide-yellow-400'
| 'divide-yellow-500'
| 'divide-yellow-600'
| 'divide-yellow-700'
| 'divide-yellow-800'
| 'divide-yellow-900'
| 'divide-green-50'
| 'divide-green-100'
| 'divide-green-200'
| 'divide-green-300'
| 'divide-green-400'
| 'divide-green-500'
| 'divide-green-600'
| 'divide-green-700'
| 'divide-green-800'
| 'divide-green-900'
| 'divide-blue-50'
| 'divide-blue-100'
| 'divide-blue-200'
| 'divide-blue-300'
| 'divide-blue-400'
| 'divide-blue-500'
| 'divide-blue-600'
| 'divide-blue-700'
| 'divide-blue-800'
| 'divide-blue-900'
| 'divide-indigo-50'
| 'divide-indigo-100'
| 'divide-indigo-200'
| 'divide-indigo-300'
| 'divide-indigo-400'
| 'divide-indigo-500'
| 'divide-indigo-600'
| 'divide-indigo-700'
| 'divide-indigo-800'
| 'divide-indigo-900'
| 'divide-purple-50'
| 'divide-purple-100'
| 'divide-purple-200'
| 'divide-purple-300'
| 'divide-purple-400'
| 'divide-purple-500'
| 'divide-purple-600'
| 'divide-purple-700'
| 'divide-purple-800'
| 'divide-purple-900'
| 'divide-pink-50'
| 'divide-pink-100'
| 'divide-pink-200'
| 'divide-pink-300'
| 'divide-pink-400'
| 'divide-pink-500'
| 'divide-pink-600'
| 'divide-pink-700'
| 'divide-pink-800'
| 'divide-pink-900';
export type divideStyle =
| 'divide-solid'
| 'divide-dashed'
| 'divide-dotted'
| 'divide-double'
| 'divide-none';
export type numberOfColumns =
| 'grid-cols-1'
| 'grid-cols-2'
| 'grid-cols-3'
| 'grid-cols-4'
| 'grid-cols-5'
| 'grid-cols-6'
| 'grid-cols-7'
| 'grid-cols-8'
| 'grid-cols-9'
| 'grid-cols-10'
| 'grid-cols-11'
| 'grid-cols-12'
| 'grid-cols-none';
<file_sep># Contributing
Thanks for your interest in contributing to this project. Please take a moment to review this document **before submitting a pull request**.
## Pull requests
It's never a fun experience to have your pull request declined after investing a lot of time and effort into a new feature. To avoid this from happening, we request that contributors create [an issue](https://github.com/tailwind-master-piece/tailwind-master-piece.github.io/issues) to first discuss any significant new features. This includes things like adding new utilities, creating new at-rules, etc.
## Coding standards
Our code formatting rules are defined in [.eslintrc](https://github.com/tailwind-master-piece/tailwind-master-piece.github.io/blob/develop/.eslintrc.js). You can check your code against these standards by running:
```sh
yarn run lint
```
To automatically fix any style code violations in your code, you only have to commit:
```sh
git commit -m "message"
```
## Running tests
You can run the test suite using the following commands:
```sh
yarn run test
```
Please ensure that the tests are passing when submitting a pull request. If you're adding new features to Tailwind, please include tests.
| 8a1fc436fa12d01ed8637e5a136c31f633def829 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 10 | JavaScript | tailwind-master-piece/tailwind-master-piece.github.io | fbfa85aa7ad6781c0756220f203dbf1c6165a7b1 | 8573fc3e4aeff057e507e5f428f2858a83eaf600 |
refs/heads/master | <file_sep>var id1 = document.getElementById("one");
var id2 = document.getElementById("two");
var id3 = document.getElementById("three");
id2.innerHTML = id2.innerHTML.replace("Gunnar","Jakob");
id1.className = "active";
id3.remove()
<file_sep># Vef-JavaScript
Vor2017
| 77c5ad540a796cd6fdd387367e97358b6305e22b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Maximpop/Vef-JavaScript | 9db1a05069163593a1af46ce7feb4da690bb6c39 | b7bed52f1429f0d922d4e780231aae9c1eb6800d |
refs/heads/main | <repo_name>blorden/Printf<file_sep>/main.c
#include <stdio.h>
#include <stdlib.h>
extern void _IAprintf (const char *format, ...);
extern void _IAprintf_flush ();
int main ()
{
for (int i = 0; i < 100; ++i)
_IAprintf(":), and I %s %x %d%%%c%b\n", "LOVE", 3802, 100, 33, 255);
_IAprintf_flush();
return 0;
} | 2f36c0d199fb668b77bf929954d0f0c6b03a2c86 | [
"C"
] | 1 | C | blorden/Printf | d9115e6b15773ef6ded43c679cc3c750a9a1d1e1 | 2d1a6ea787154330848e260eeafbc0a332c4e4dc |
refs/heads/master | <repo_name>carg563/ArcGISEnterpriseToolkit<file_sep>/StartStopService.py
#-------------------------------------------------------------
# Name: Start or Stop Service
# Purpose: Starts or stops a service or services in an
# ArcGIS Enterprise site.
# Author: <NAME> (<EMAIL>)
# Date Created: 05/11/2018
# Last Updated: 05/11/2018
# ArcGIS Version: ArcGIS API for Python 1.4.2+
# Python Version: 3.6.5+ (Anaconda Distribution)
#--------------------------------
# Import main modules
import os
import sys
import logging
import smtplib
import time
import csv
# Import ArcGIS modules
useArcPy = "false"
useArcGISAPIPython = "true"
if (useArcPy == "true"):
# Import arcpy module
import arcpy
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
if (useArcGISAPIPython == "true"):
# Import arcgis module
import arcgis
# Set global variables
# Logging
enableLogging = "true" # Use within code to print and log messages - printMessage("xxx","info"), printMessage("xxx","warning"), printMessage("xxx","error")
logFile = os.path.join(os.path.dirname(__file__), "StartStopService.log") # e.g. os.path.join(os.path.dirname(__file__), "Example.log")
# Email logging
sendErrorEmail = "false"
emailServerName = "" # e.g. smtp.gmail.com
emailServerPort = 0 # e.g. 25
emailTo = ""
emailUser = ""
emailPassword = ""
emailSubject = ""
emailMessage = ""
# Proxy
enableProxy = "false"
requestProtocol = "http" # http or https
proxyURL = ""
# Output
output = None
# Start of main function
def mainFunction(siteURL,adminUser,adminPassword,servicesFolder,serviceName,serviceAction): # Add parameters sent to the script here e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
try:
# --------------------------------------- Start of code --------------------------------------- #
# Connect to GIS site
printMessage("Connecting to GIS site - " + siteURL + "...","info")
gis = arcgis.GIS(url=siteURL, username=adminUser, password=<PASSWORD>, verify_cert=False)
# Get a list of servers in the site
gisServers = gis.admin.servers.list()
# If a service name is set
if (serviceName):
# Set GIS service found to false
gisServiceFound = False
else:
# Set GIS service found to true
gisServiceFound = True
# For each server
for gisServer in gisServers:
# If a folder is set
if (servicesFolder):
# If the folder does not exist
if servicesFolder not in gisServer.services.folders:
printMessage("Services folder does not exist: " + servicesFolder, "error")
# For each service in the root directory
for gisService in gisServer.services.list():
# If no services folder set (Start/stop services in the root directory)
if (servicesFolder is None) or (servicesFolder == ""):
# If no service name set (Start/stop all services)
if (serviceName is None) or (serviceName == ""):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Service name set (Just start/stop that service)
else:
# If the service name and type is equal to the one specified
if (serviceName.lower() == gisService.properties.serviceName.lower() + "." + gisService.properties.type.lower()):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Set GIS service found to true
gisServiceFound = True
# For each folder
for gisFolder in gisServer.services.folders:
# If the services folder is equal to the one specified
if (servicesFolder.lower() == gisFolder.lower()):
# For each service in the folder
for gisService in gisServer.services.list(folder=gisFolder):
# If no service name set (Start/stop all services)
if (serviceName is None) or (serviceName == ""):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Service name set (Just start/stop that service)
else:
# If the service name and type is equal to the one specified
if (serviceName.lower() == gisService.properties.serviceName.lower() + "." + gisService.properties.type.lower()):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Set GIS service found to true
gisServiceFound = True
# If a service name was set but not found
if (gisServiceFound == False):
printMessage("Service does not exist: " + serviceName, "error")
# --------------------------------------- End of code --------------------------------------- #
# If called from ArcGIS GP tool
if __name__ == '__main__':
# Return the output if there is any
if output:
# If using ArcPy
if (useArcPy == "true"):
arcpy.SetParameter(1, output)
# ArcGIS desktop not installed
else:
return output
# Otherwise return the result
else:
# Return the output if there is any
if output:
return output
# Logging
if (enableLogging == "true"):
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logMessage.flush()
logMessage.close()
logger.handlers = []
# If error
except Exception as e:
errorMessage = ""
# Build and show the error message
# If many arguments
if (e.args):
for i in range(len(e.args)):
if (i == 0):
errorMessage = str(e.args[i]).encode('utf-8').decode('utf-8')
else:
errorMessage = errorMessage + " " + str(e.args[i]).encode('utf-8').decode('utf-8')
# Else just one argument
else:
errorMessage = e
printMessage(errorMessage,"error")
# Logging
if (enableLogging == "true"):
# Log error
logger.error(errorMessage)
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logMessage.flush()
logMessage.close()
logger.handlers = []
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage)
# End of main function
# Start of start or stop service function
def startStopService(gisService,serviceAction):
if (serviceAction.lower() == "start"):
printMessage("Starting service: " + gisService.properties.serviceName + "." + gisService.properties.type + "...", "info")
gisService.start()
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " is now " + gisService.status["realTimeState"].lower() + "...","info")
elif (serviceAction.lower() == "stop"):
printMessage("Stopping service: " + gisService.properties.serviceName + "." + gisService.properties.type + "...", "info")
gisService.stop()
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " is now " + gisService.status["realTimeState"].lower() + "...","info")
else:
printMessage("Neither start or stop has been set in the parameters...", "warning")
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " remains " + gisService.status["realTimeState"].lower() + "...","info")
# End of start or stop service function
# Start of print and logging message function
def printMessage(message,type):
# If using ArcPy
if (useArcPy == "true"):
if (type.lower() == "warning"):
arcpy.AddWarning(message)
# Logging
if (enableLogging == "true"):
logger.warning(message)
elif (type.lower() == "error"):
arcpy.AddError(message)
# Logging
if (enableLogging == "true"):
logger.error(message)
else:
arcpy.AddMessage(message)
# Logging
if (enableLogging == "true"):
logger.info(message)
else:
print(message)
# Logging
if (enableLogging == "true"):
logger.info(message)
# End of print and logging message function
# Start of set logging function
def setLogging(logFile):
# Create a logger
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# Setup log message handler
logMessage = logging.FileHandler(logFile)
# Setup the log formatting
logFormat = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s", "%d/%m/%Y - %H:%M:%S")
# Add formatter to log message handler
logMessage.setFormatter(logFormat)
# Add log message handler to logger
logger.addHandler(logMessage)
return logger, logMessage
# End of set logging function
# Start of send email function
def sendEmail(message):
# Send an email
printMessage("Sending email...","info")
# Server and port information
smtpServer = smtplib.SMTP(emailServerName,emailServerPort)
smtpServer.ehlo()
smtpServer.starttls()
smtpServer.ehlo
# Login with sender email address and password
smtpServer.login(emailUser, emailPassword)
# Email content
header = 'To:' + emailTo + '\n' + 'From: ' + emailUser + '\n' + 'Subject:' + emailSubject + '\n'
body = header + '\n' + emailMessage + '\n' + '\n' + message
# Send the email and close the connection
smtpServer.sendmail(emailUser, emailTo, body)
# End of send email function
# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE,
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
# If using ArcPy
if (useArcPy == "true"):
argv = tuple(arcpy.GetParameterAsText(i)
for i in range(arcpy.GetArgumentCount()))
else:
argv = sys.argv
# Delete the first argument, which is the script
del argv[0]
# Logging
if (enableLogging == "true"):
# Setup logging
logger, logMessage = setLogging(logFile)
# Log start of process
logger.info("Process started.")
# Setup the use of a proxy for requests
if (enableProxy == "true"):
# Setup the proxy
proxy = urllib2.ProxyHandler({requestProtocol : proxyURL})
openURL = urllib2.build_opener(proxy)
# Install the proxy
urllib2.install_opener(openURL)
mainFunction(*argv)
<file_sep>/ArcGISServerAvailability.py
#-------------------------------------------------------------
# Name: ArcGIS Server Availability
# Purpose: Checks ArcGIS server site and services and reports if site is down and/or particular
# service is down. This tool should be setup as an automated task on the server.
# Author: <NAME> (<EMAIL>)
# Date Created: 07/02/2014
# Last Updated: 22/06/2015
# Copyright: (c) Eagle Technology
# ArcGIS Version: 10.1+
# Python Version: 2.7
#--------------------------------
# Import modules
import os
import sys
import logging
import datetime
import smtplib
import httplib
import json
import urllib
import urlparse
import arcpy
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
# Set variables
enableLogging = "false"
logFile = r""
sendErrorEmail = "false"
emailTo = ""
emailUser = ""
emailPassword = ""
emailSubject = ""
emailMessage = ""
enableProxy = "false"
requestProtocol = "http" # http or https
proxyURL = ""
output = None
# Start of main function
def mainFunction(agsServerSite,username,password,service): # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
try:
# --------------------------------------- Start of code --------------------------------------- #
# Get the server site details
protocol, serverName, serverPort, context = splitSiteURL(agsServerSite)
# If any of the variables are blank
if (serverName == None or serverPort == None or protocol == None or context == None):
return -1
# Add on slash to context if necessary
if not context.endswith('/'):
context += '/'
# Add on admin to context if necessary
if not context.endswith('admin/'):
context += 'admin/'
# Get token
token = getToken(username, password, serverName, serverPort, protocol)
# If token received
if (token != -1):
# Check server web adaptor
webAdaptors = getWebAdaptor(serverName, serverPort, protocol, token)
for webAdaptor in webAdaptors:
# Get the server site details on web adaptor
protocolWeb, serverNameWeb, serverPortWeb, contextWeb = splitSiteURL(webAdaptor['webAdaptorURL'])
# Query arcgis server via the web adaptor
webStatusVersion = checkWebAdaptor(serverNameWeb, serverPortWeb, protocolWeb, contextWeb, token)
if (webStatusVersion != -1):
arcpy.AddMessage("ArcGIS Server With Web Adaptor " + webAdaptor['webAdaptorURL'] + " is running correctly on version " + str(webStatusVersion) + "...")
# Logging
if (enableLogging == "true"):
logger.info("ArcGIS Server With Web Adaptor " + webAdaptor['webAdaptorURL'] + " is running correctly on version " + str(webStatusVersion) + "...")
# Else
else:
arcpy.AddError("There is an issue with the web adaptor - " + webAdaptor['webAdaptorURL'])
# Logging
if (enableLogging == "true"):
logger.error("There is an issue with the web adaptor - " + webAdaptor['webAdaptorURL'])
# Email
if (sendErrorEmail == "true"):
# Send email
sendEmail("There is an issue with the web adaptor - " + webAdaptor['webAdaptorURL'])
# List to hold services and their status
servicesStatus = []
# If a service is provided
if (len(str(service)) > 0):
# Query the service status
realtimeStatus = getServiceStatus(serverName, serverPort, protocol, service, token)
# Check the service
serviceInfo = checkService(serverName, serverPort, protocol, service, token)
serviceDetails = {'status': realtimeStatus, 'info': serviceInfo, 'service': service}
servicesStatus.append(serviceDetails)
# Else
else:
# Get all services
services = getServices(serverName, serverPort, protocol, token)
# Query all services
# Iterate through services
for eachService in services:
# Query the service status
realtimeStatus = getServiceStatus(serverName, serverPort, protocol, eachService, token)
# Check the service
serviceInfo = checkService(serverName, serverPort, protocol, eachService, token)
serviceDetails = {'status': realtimeStatus, 'info': serviceInfo, 'service': eachService}
servicesStatus.append(serviceDetails)
stoppedServices = 0
errorServices = 0
errors = []
# Iterate through services
for eachServicesStatus in servicesStatus:
# If status is stopped add to stopped counter
if (eachServicesStatus['status'] == "STOPPED"):
stoppedServices = stoppedServices + 1
else:
# If error with service add to error counter
if 'error' in eachServicesStatus['info']:
errorServices = errorServices + 1
errors.append(eachServicesStatus['info']['error']['message'])
# If any services are stopped/have errors
if (stoppedServices > 0) or (errorServices > 0):
arcpy.AddError(str(stoppedServices) + " services are stopped...")
arcpy.AddError(str(errorServices) + " services have errors...")
for error in errors:
arcpy.AddError(error)
# Logging
if (enableLogging == "true"):
logger.error(str(stoppedServices) + " services are stopped")
logger.error(str(errorServices) + " services have errors")
for error in errors:
logger.error(error)
# Email
if (sendErrorEmail == "true"):
errorMessage = str(stoppedServices) + " services are stopped" + "\n"
errorMessage += str(errorServices) + " services have errors" + "\n" + "\n"
for error in errors:
errorMessage += error + "\n"
# Send email
sendEmail(errorMessage)
else:
arcpy.AddMessage("All services are running correctly...")
# Logging
if (enableLogging == "true"):
logger.info("All services are running correctly...")
# --------------------------------------- End of code --------------------------------------- #
# If called from gp tool return the arcpy parameter
if __name__ == '__main__':
# Return the output if there is any
if output:
arcpy.SetParameterAsText(1, output)
# Otherwise return the result
else:
# Return the output if there is any
if output:
return output
# Logging
if (enableLogging == "true"):
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logging.FileHandler.close(logMessage)
logger.removeHandler(logMessage)
pass
# If arcpy error
except arcpy.ExecuteError:
# Build and show the error message
errorMessage = arcpy.GetMessages(2)
arcpy.AddError(errorMessage)
# Logging
if (enableLogging == "true"):
# Log error
logger.error(errorMessage)
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logging.FileHandler.close(logMessage)
logger.removeHandler(logMessage)
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage)
# If python error
except Exception as e:
errorMessage = ""
# Build and show the error message
for i in range(len(e.args)):
if (i == 0):
errorMessage = unicode(e.args[i]).encode('utf-8')
else:
errorMessage = errorMessage + " " + unicode(e.args[i]).encode('utf-8')
arcpy.AddError(errorMessage)
# Logging
if (enableLogging == "true"):
# Log error
logger.error(errorMessage)
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logging.FileHandler.close(logMessage)
logger.removeHandler(logMessage)
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage)
# End of main function
# Start of get web adaptor function
def getWebAdaptor(serverName, serverPort, protocol, token):
params = urllib.urlencode({'token': token, 'f': 'json'})
# Construct URL to get the web adaptor
url = "/arcgis/admin/system/webadaptors"
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Please check if the server is running.")
# Log error
if (logging == "true") or (sendErrorEmail == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Please check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error getting web adaptor.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting web adaptor.")
sys.exit()
arcpy.AddError(str(data))
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error getting web adaptor. Please check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting web adaptor. Please check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
return dataObject['webAdaptors']
# End of get web adaptor function
# Start of get web adaptor function
def checkWebAdaptor(serverName, serverPort, protocol, webName, token):
params = urllib.urlencode({'token': token, 'f': 'json'})
# Construct URL to check the web adaptor
url = webName + "/rest/services"
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Please check if the server is running.")
# Log error
if (logging == "true") or (sendErrorEmail == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Please check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error checking web adaptor.")
# Logging
if (enableLogging == "true"):
logger.error("Error checking web adaptor.")
sys.exit()
arcpy.AddError(str(data))
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error checking web adaptor. Please check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error checking web adaptor. Please check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
return dataObject['currentVersion']
# End of get web adaptor function
# Start of get services function
def getServices(serverName, serverPort, protocol, token):
params = urllib.urlencode({'token': token, 'f': 'json'})
# Services list
services = []
# Construct URL to get services
url = "/arcgis/admin/services"
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
# Logging
if (enableLogging == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error getting services.")
arcpy.AddError(str(data))
# Logging
if (enableLogging == "true"):
logger.error("Error getting services.")
sys.exit()
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error getting services. Check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting services. Check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
# Iterate through services
for eachService in dataObject['services']:
# Add to list
services.append(eachService['serviceName'] + "." + eachService['type'])
# Iterate through folders
for folder in dataObject['folders']:
# Construct URL to get services for the folder
url = "/arcgis/admin/services/" + folder
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
# Logging
if (enableLogging == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error getting services.")
arcpy.AddError(str(data))
# Logging
if (enableLogging == "true"):
logger.error("Error getting services.")
sys.exit()
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error getting services. Check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting services. Check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
# Iterate through services
for eachService in dataObject['services']:
services.append(folder + "/" + eachService['serviceName']+ "." + eachService['type'])
# Return a list of services
return services
# End of get services function
# Start of get service status function
def getServiceStatus(serverName, serverPort, protocol, service, token):
params = urllib.urlencode({'token': token, 'f': 'json'})
# Construct URL to get the service status
url = "/arcgis/admin/services/" + service + "/status"
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
# Logging
if (enableLogging == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error getting service status.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting service status.")
sys.exit()
arcpy.AddError(str(data))
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error getting service status. Check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting service status. Check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
# Return the real time state
return dataObject['realTimeState']
# End of get service status function
# Start of check service function
def checkService(serverName, serverPort, protocol, service, token):
params = urllib.urlencode({'token': token, 'f': 'json'})
# Construct URL to get the service status
url = "/arcgis/rest/services/" + service.replace(".", "/")
# Post to the server
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
# Logging
if (enableLogging == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
sys.exit()
return -1
# If there is an error
if (response.status != 200):
arcpy.AddError("Error getting service status.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting service status.")
sys.exit()
arcpy.AddError(str(data))
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error getting service status. Check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error getting service status. Check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# On successful query
else:
dataObject = json.loads(data)
# Return the service object
return dataObject
# End of check service function
# Start of get token function
def getToken(username, password, serverName, serverPort, protocol):
params = urllib.urlencode({'username': username.decode(sys.stdin.encoding or sys.getdefaultencoding()).encode('utf-8'), 'password': password.decode(sys.stdin.encoding or sys.getdefaultencoding()).encode('utf-8'),'client': 'referer','referer':'backuputility','f': 'json'})
# Construct URL to get a token
url = "/arcgis/tokens/generateToken"
try:
response, data = postToServer(serverName, serverPort, protocol, url, params)
except:
arcpy.AddError("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
# Logging
if (enableLogging == "true"):
logger.error("Unable to connect to the ArcGIS Server site on " + serverName + ". Check if the server is running.")
sys.exit()
return -1
# If there is an error getting the token
if (response.status != 200):
arcpy.AddError("Error while generating the token.")
arcpy.AddError(str(data))
# Logging
if (enableLogging == "true"):
logger.error("Error while generating the token.")
sys.exit()
return -1
if (not assertJsonSuccess(data)):
arcpy.AddError("Error while generating the token. Check if the server is running and ensure that the username/password provided are correct.")
# Logging
if (enableLogging == "true"):
logger.error("Error while generating the token. Check if the server is running and ensure that the username/password provided are correct.")
sys.exit()
return -1
# Token returned
else:
# Extract the token from it
dataObject = json.loads(data)
# Return the token if available
if "error" in dataObject:
arcpy.AddError("Error retrieving token.")
# Logging
if (enableLogging == "true"):
logger.error("Error retrieving token.")
sys.exit()
return -1
else:
return dataObject['token']
# End of get token function
# Start of HTTP POST request to the server function
def postToServer(serverName, serverPort, protocol, url, params):
# If on standard port
if (serverPort == -1 and protocol == 'http'):
serverPort = 80
# If on secure port
if (serverPort == -1 and protocol == 'https'):
serverPort = 443
if (protocol == 'http'):
httpConn = httplib.HTTPConnection(serverName, int(serverPort))
if (protocol == 'https'):
httpConn = httplib.HTTPSConnection(serverName, int(serverPort))
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",'referer':'backuputility','referrer':'backuputility'}
# URL encode the resource URL
url = urllib.quote(url.encode('utf-8'))
# Build the connection to add the roles to the server
httpConn.request("POST", url, params, headers)
response = httpConn.getresponse()
data = response.read()
httpConn.close()
# Return response
return (response, data)
# End of HTTP POST request to the server function
# Start of split URL function
def splitSiteURL(siteURL):
try:
serverName = ''
serverPort = -1
protocol = 'http'
context = '/arcgis'
# Split up the URL provided
urllist = urlparse.urlsplit(siteURL)
# Put the URL list into a dictionary
d = urllist._asdict()
# Get the server name and port
serverNameAndPort = d['netloc'].split(":")
# User did not enter the port number, so we return -1
if (len(serverNameAndPort) == 1):
serverName = serverNameAndPort[0]
else:
if (len(serverNameAndPort) == 2):
serverName = serverNameAndPort[0]
serverPort = serverNameAndPort[1]
# Get protocol
if (d['scheme'] is not ''):
protocol = d['scheme']
# Get path
if (d['path'] is not '/' and d['path'] is not ''):
context = d['path']
# Return variables
return protocol, serverName, serverPort, context
except:
arcpy.AddError("The ArcGIS Server site URL should be in the format http(s)://<host>:<port>/arcgis")
# Logging
if (enableLogging == "true"):
logger.error("The ArcGIS Server site URL should be in the format http(s)://<host>:<port>/arcgis")
sys.exit()
return None, None, None, None
# End of split URL function
# Start of status check JSON object function
def assertJsonSuccess(data):
try:
obj = json.loads(data)
if 'status' in obj and obj['status'] == "error":
if ('messages' in obj):
errMsgs = obj['messages']
for errMsg in errMsgs:
arcpy.AddError(errMsg)
# Logging
if (enableLogging == "true"):
logger.error(errMsg)
sys.exit()
return False
else:
return True
except ValueError, e:
return False
# End of status check JSON object function
# Start of set logging function
def setLogging(logFile):
# Create a logger
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# Setup log message handler
logMessage = logging.FileHandler(logFile)
# Setup the log formatting
logFormat = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s", "%d/%m/%Y - %H:%M:%S")
# Add formatter to log message handler
logMessage.setFormatter(logFormat)
# Add log message handler to logger
logger.addHandler(logMessage)
return logger, logMessage
# End of set logging function
# Start of send email function
def sendEmail(message):
# Send an email
arcpy.AddMessage("Sending email...")
# Server and port information
smtpServer = smtplib.SMTP("smtp.gmail.com",587)
smtpServer.ehlo()
smtpServer.starttls()
smtpServer.ehlo
# Login with sender email address and password
smtpServer.login(emailUser, emailPassword)
# Email content
header = 'To:' + emailTo + '\n' + 'From: ' + emailUser + '\n' + 'Subject:' + emailSubject + '\n'
body = header + '\n' + emailMessage + '\n' + '\n' + message
# Send the email and close the connection
smtpServer.sendmail(emailUser, emailTo, body)
# End of send email function
# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE,
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
# Arguments are optional - If running from ArcGIS Desktop tool, parameters will be loaded into *argv
argv = tuple(arcpy.GetParameterAsText(i)
for i in range(arcpy.GetArgumentCount()))
# Logging
if (enableLogging == "true"):
# Setup logging
logger, logMessage = setLogging(logFile)
# Log start of process
logger.info("Process started.")
# Setup the use of a proxy for requests
if (enableProxy == "true"):
# Setup the proxy
proxy = urllib2.ProxyHandler({requestProtocol : proxyURL})
openURL = urllib2.build_opener(proxy)
# Install the proxy
urllib2.install_opener(openURL)
mainFunction(*argv)
<file_sep>/PortalServicesReport.py
#-------------------------------------------------------------
# Name: Portal Services Report
# Purpose: Queries an ArcGIS Online/Portal for ArcGIS site to find all services that are being used in web maps
# then aggregates these in a CSV file. This tool needs to be run as an ArcGIS Online/Portal administrator.
# Author: <NAME> (<EMAIL>)
# Date Created: 05/04/2016
# Last Updated: 11/04/2017
# Copyright: (c) Eagle Technology
# ArcGIS Version: ArcMap 10.4+
# Python Version: 2.7
#--------------------------------
# Import main modules
import os
import sys
import logging
import smtplib
# Set global variables
# Logging
enableLogging = "false" # Use within code - logger.info("Example..."), logger.warning("Example..."), logger.error("Example...") and to print messages - printMessage("xxx","info"), printMessage("xxx","warning"), printMessage("xxx","error")
logFile = "" # e.g. os.path.join(os.path.dirname(__file__), "Example.log")
# Email logging
sendErrorEmail = "false"
emailServerName = "" # e.g. smtp.gmail.com
emailServerPort = 0 # e.g. 25
emailTo = ""
emailUser = ""
emailPassword = ""
emailSubject = ""
emailMessage = ""
# Proxy
enableProxy = "false"
requestProtocol = "http" # http or https
proxyURL = ""
# Output
output = None
# ArcGIS desktop installed
arcgisDesktop = "true"
# If ArcGIS desktop installed
if (arcgisDesktop == "true"):
# Import extra modules
import arcpy
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
import urllib.request as urllib2
else:
# Python 2.x
import urllib2
import urllib
import json
import csv
import ssl
# Start of main function
def mainFunction(portalUrl,portalAdminName,portalAdminPassword,csvFile,csvFile2): # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
try:
# --------------------------------------- Start of code --------------------------------------- #
printMessage("Connecting to Portal - " + portalUrl + "...","info")
# Generate token for portal
token = generateToken(portalAdminName, portalAdminPassword, portalUrl)
printMessage("Getting organisation ID for portal site...","info")
# Setup parameters for organisation query
dict = {}
dict['f'] = 'json'
dict['token'] = token
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Encode parameters
params = urllib.parse.urlencode(dict)
else:
# Python 2.x
# Encode parameters
params = urllib.urlencode(dict)
params = params.encode('utf-8')
# POST the request - organisation query
context = ssl._create_unverified_context()
requestURL = urllib2.Request(portalUrl + "/sharing/rest/portals/self",params)
response = urllib2.urlopen(requestURL, context=context)
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Read json response
responseJSON = json.loads(response.read().decode('utf8'))
else:
# Python 2.x
# Read json response
responseJSON = json.loads(response.read())
# Log results
if "error" in responseJSON:
errDict = responseJSON['error']
message = "Error Code: %s \n Message: %s" % (errDict['code'],
errDict['message'])
printMessage(message,"error")
else:
# Get the organisation ID
orgID = responseJSON["id"]
# Setup the query
query = "type:\"web map\" AND -type:\"web mapping application\" AND orgid:\"" + orgID + "\""
startQueryNum = 0
# Setup the dictionary to store the web maps
webmaps = []
# Search content on the site
printMessage("Searching web maps on portal site...","info")
# Return all the web maps - 100 at a time
while (startQueryNum != -1):
totalWebmaps,nextStartID,webMapsReturned = searchWebmaps(portalUrl,token,query,startQueryNum)
startQueryNum = nextStartID
webmaps = webmaps + webMapsReturned
if (startQueryNum != -1):
printMessage("Queried " + str(nextStartID-1) + " of " + str(totalWebmaps) + " web maps...","info")
else:
printMessage("Queried " + str(totalWebmaps) + " of " + str(totalWebmaps) + " web maps...","info")
# Setup the dictionary to store the services
services = []
# For each of the web maps returned
count = 0
for webmap in webmaps:
printMessage("Querying web map - " + webmap["id"] + "...","info")
servicesReturned = servicesWebmap(portalUrl,token,webmap["id"])
services = services + servicesReturned
count = count + 1
printMessage("Number of services in web map - " + str(len(servicesReturned)),"info")
printMessage("Queried " + str(count) + " of " + str(totalWebmaps) + " web maps...","info")
printMessage("Creating full services list CSV file - " + csvFile + "...","info")
# Create a CSV file and setup header
file = open(csvFile, 'wb')
writer = csv.writer(file, delimiter=",")
# Add in header information
headerRow = []
headerRow.append("Service")
headerRow.append("Title")
headerRow.append("Web Map URL")
writer.writerow(headerRow)
# Add in rows
for service in services:
row = []
row.append(service["url"])
row.append(service["title"])
row.append(portalUrl + "/home/item.html?id=" + service["webmap"])
writer.writerow(row)
printMessage("Creating grouped services list CSV file - " + csvFile2 + "...","info")
servicesGrouped = {}
# Reference CSV file
file = open(csvFile, 'rb')
csvreader = csv.reader(file, delimiter=',')
# For each row in the file
count = 0
for row in csvreader:
key = row[0]
# If not the first row
if (count > 0):
# If service already added, increment by 1
if key in servicesGrouped:
servicesGrouped[key] = servicesGrouped[key] + 1
# If service is not added, add it
else:
servicesGrouped[key] = 1
count = count + 1
# Create a CSV file and setup header
file = open(csvFile2, 'wb')
writer = csv.writer(file, delimiter=",")
# Add in header information
headerRow = []
headerRow.append("Service")
headerRow.append("Count")
writer.writerow(headerRow)
# Sort the services by the grouping count
sortedServicesGrouped = sorted(servicesGrouped, key=servicesGrouped.__getitem__, reverse=True)
# Add in rows
for sortedServiceGrouped in sortedServicesGrouped:
row = []
row.append(sortedServiceGrouped)
row.append(servicesGrouped[sortedServiceGrouped])
writer.writerow(row)
# --------------------------------------- End of code --------------------------------------- #
# If called from gp tool return the arcpy parameter
if __name__ == '__main__':
# Return the output if there is any
if output:
# If ArcGIS desktop installed
if (arcgisDesktop == "true"):
arcpy.SetParameterAsText(1, output)
# ArcGIS desktop not installed
else:
return output
# Otherwise return the result
else:
# Return the output if there is any
if output:
return output
# Logging
if (enableLogging == "true"):
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logMessage.flush()
logMessage.close()
logger.handlers = []
# If arcpy error
except arcpy.ExecuteError:
# Build and show the error message
errorMessage = arcpy.GetMessages(2)
printMessage(errorMessage,"error")
# Logging
if (enableLogging == "true"):
# Log error
logger.error(errorMessage)
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logMessage.flush()
logMessage.close()
logger.handlers = []
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage)
# If python error
except Exception as e:
errorMessage = ""
# Build and show the error message
# If many arguments
if (e.args):
for i in range(len(e.args)):
if (i == 0):
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
errorMessage = str(e.args[i]).encode('utf-8').decode('utf-8')
else:
# Python 2.x
errorMessage = unicode(e.args[i]).encode('utf-8')
else:
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
errorMessage = errorMessage + " " + str(e.args[i]).encode('utf-8').decode('utf-8')
else:
# Python 2.x
errorMessage = errorMessage + " " + unicode(e.args[i]).encode('utf-8')
# Else just one argument
else:
errorMessage = e
printMessage(errorMessage,"error")
# Logging
if (enableLogging == "true"):
# Log error
logger.error(errorMessage)
# Log end of process
logger.info("Process ended.")
# Remove file handler and close log file
logMessage.flush()
logMessage.close()
logger.handlers = []
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage)
# End of main function
# Start of search web maps function
def searchWebmaps(portalUrl,token,query,startQueryNum):
# Setup parameters for search query
dict = {}
dict['f'] = 'json'
dict['token'] = token
dict['num'] = "100"
dict['sortField'] = "title"
dict['sortOrder'] = "asc"
#dict['restrict'] = "true"
dict['focus'] = "maps"
dict['q'] = query
dict['start'] = startQueryNum
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Encode parameters
params = urllib.parse.urlencode(dict)
else:
# Python 2.x
# Encode parameters
params = urllib.urlencode(dict)
params = params.encode('utf-8')
# POST the request - Creates a new item in the ArcGIS online site
requestURL = urllib2.Request(portalUrl + "/sharing/rest/search",params)
context = ssl._create_unverified_context()
response = urllib2.urlopen(requestURL, context=context)
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Read json response
responseJSON = json.loads(response.read().decode('utf8'))
else:
# Python 2.x
# Read json response
responseJSON = json.loads(response.read())
# Log results
if "error" in responseJSON:
errDict = responseJSON['error']
message = "Error Code: %s \n Message: %s" % (errDict['code'],
errDict['message'])
printMessage(message,"error")
else:
# Setup the dictionary to return
webmaps = []
# Get the total web maps found
totalWebmaps = responseJSON["total"]
# Get the ID to start from for the next search
nextStartID = responseJSON["nextStart"]
# For each of the results returned
for result in responseJSON["results"]:
# Append data into dictionary
webmaps.append({"id":result["id"],"title":result["title"],"owner":result["owner"],"access":result["access"]})
# Return dictionary
return totalWebmaps,nextStartID,webmaps
# End of search web maps function
# Start of services in web map function
def servicesWebmap(portalUrl,token,webmap):
# Setup parameters for web map query
dict = {}
dict['f'] = 'json'
dict['token'] = token
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Encode parameters
params = urllib.parse.urlencode(dict)
else:
# Python 2.x
# Encode parameters
params = urllib.urlencode(dict)
params = params.encode('utf-8')
# POST the request - web map query
requestURL = urllib2.Request(portalUrl + "/sharing/rest/content/items/" + webmap + "/data",params)
context = ssl._create_unverified_context()
response = urllib2.urlopen(requestURL, context=context)
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Read json response
responseJSON = json.loads(response.read().decode('utf8'))
else:
# Python 2.x
# Read json response
responseJSON = json.loads(response.read())
# Log results
if "error" in responseJSON:
errDict = responseJSON['error']
message = "Error Code: %s \n Message: %s" % (errDict['code'],
errDict['message'])
printMessage(message,"error")
else:
# Setup the dictionary to return
services = []
# For each of the operational layers returned
for operationalLayer in responseJSON["operationalLayers"]:
# If URL to service
if ("url" in operationalLayer):
# Append data into dictionary
services.append({"url":operationalLayer["url"],"title":operationalLayer["title"],"webmap":webmap})
# For each of the basemap layers returned
for basemap in responseJSON["baseMap"]["baseMapLayers"]:
# If URL to service
if ("url" in basemap):
# If URL to service
services.append({"url":basemap["url"],"title":"Basemap","webmap":webmap})
# Return dictionary
return services
# End of services in web map function
# Start of get token function
def generateToken(username, <PASSWORD>, portalUrl):
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Encode parameters
parameters = urllib.parse.urlencode({'username' : username,
'password' : <PASSWORD>,
'client' : 'referer',
'referer': portalUrl,
'expiration': 60,
'f' : 'json'})
else:
# Python 2.x
# Encode parameters
parameters = urllib.urlencode({'username' : username,
'password' : <PASSWORD>,
'client' : 'referer',
'referer': portalUrl,
'expiration': 60,
'f' : 'json'})
parameters = parameters.encode('utf-8')
try:
requestURL = urllib2.Request(portalUrl + '/sharing/rest/generateToken?',parameters)
context = ssl._create_unverified_context()
response = urllib2.urlopen(requestURL, context=context)
except Exception as e:
printMessage( 'Unable to open the url %s/sharing/rest/generateToken' % (portalUrl),'error')
printMessage(e,'error')
# Python version check
if sys.version_info[0] >= 3:
# Python 3.x
# Read json response
responseJSON = json.loads(response.read().decode('utf8'))
else:
# Python 2.x
# Read json response
responseJSON = json.loads(response.read())
# Log results
if "error" in responseJSON:
errDict = responseJSON['error']
if int(errDict['code'])==498:
message = 'Token Expired. Getting new token... '
token = generateToken(username,<PASSWORD>, portalUrl)
else:
message = 'Error Code: %s \n Message: %s' % (errDict['code'],
errDict['message'])
printMessage(message,'error')
token = responseJSON.get('token')
return token
# End of get token function
# Start of print message function
def printMessage(message,type):
# If ArcGIS desktop installed
if (arcgisDesktop == "true"):
if (type.lower() == "warning"):
arcpy.AddWarning(message)
elif (type.lower() == "error"):
arcpy.AddError(message)
else:
arcpy.AddMessage(message)
# ArcGIS desktop not installed
else:
print(message)
# End of print message function
# Start of set logging function
def setLogging(logFile):
# Create a logger
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# Setup log message handler
logMessage = logging.FileHandler(logFile)
# Setup the log formatting
logFormat = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s", "%d/%m/%Y - %H:%M:%S")
# Add formatter to log message handler
logMessage.setFormatter(logFormat)
# Add log message handler to logger
logger.addHandler(logMessage)
return logger, logMessage
# End of set logging function
# Start of send email function
def sendEmail(message):
# Send an email
printMessage("Sending email...","info")
# Server and port information
smtpServer = smtplib.SMTP(emailServerName,emailServerPort)
smtpServer.ehlo()
smtpServer.starttls()
smtpServer.ehlo
# Login with sender email address and password
smtpServer.login(emailUser, emailPassword)
# Email content
header = 'To:' + emailTo + '\n' + 'From: ' + emailUser + '\n' + 'Subject:' + emailSubject + '\n'
body = header + '\n' + emailMessage + '\n' + '\n' + message
# Send the email and close the connection
smtpServer.sendmail(emailUser, emailTo, body)
# End of send email function
# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE,
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
# Test to see if ArcGIS desktop installed
if ((os.path.basename(sys.executable).lower() == "arcgispro.exe") or (os.path.basename(sys.executable).lower() == "arcmap.exe") or (os.path.basename(sys.executable).lower() == "arccatalog.exe")):
arcgisDesktop = "true"
# If ArcGIS desktop installed
if (arcgisDesktop == "true"):
argv = tuple(arcpy.GetParameterAsText(i)
for i in range(arcpy.GetArgumentCount()))
# ArcGIS desktop not installed
else:
argv = sys.argv
# Delete the first argument, which is the script
del argv[0]
# Logging
if (enableLogging == "true"):
# Setup logging
logger, logMessage = setLogging(logFile)
# Log start of process
logger.info("Process started.")
# Setup the use of a proxy for requests
if (enableProxy == "true"):
# Setup the proxy
proxy = urllib2.ProxyHandler({requestProtocol : proxyURL})
openURL = urllib2.build_opener(proxy)
# Install the proxy
urllib2.install_opener(openURL)
mainFunction(*argv)
| e01ee64a8b027a24b791c22503e237b78ddf91e7 | [
"Python"
] | 3 | Python | carg563/ArcGISEnterpriseToolkit | bd741a26d2a1b9f2e62a618f7f600e9e66429032 | 29b41ca296c74166605e0049579c00fc5e362f9f |
refs/heads/master | <file_sep>package sprint2.product;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import sprint2.product.*;
public class AI {
private Board board;
Random rand = new Random();
private int move = 25;
private int moveFrom = 25;
private int moveTo = 25;
List<List<Integer>> closedMills = new ArrayList<List<Integer>>();
List<List<Integer>> checkedMills = new ArrayList<List<Integer>>();
int counterForm2 = 0;
public AI(Board board) {
this.board = board;
}
public boolean makeMove() {
if (board.getGameState() == GameState.PLAYING1) {
boolean status = board.makeMoveFirstPhase(move);
return status;
}
if (board.getGameState() == GameState.PLAYING2a) {
boolean status = board.makeMoveSecondPhaseA(moveFrom);
return status;
}
if (board.getGameState() == GameState.PLAYING2b1) {
board.makeMoveSecondPhaseB(moveFrom, moveTo);
//board.clearMills();
return false;
}
if (board.getGameState() == GameState.PLAYING3a || board.getGameState() == GameState.PLAYING3b) {
boolean status = board.makeMoveThirdPhase(move);
return status;
}
return false;
}
public void moveDecider() {
if (board.getGameState() == GameState.PLAYING2b1) {
moveThePiece();
makeMove();
moveFrom = 25;
moveTo = 25;
board.setGray();
} else if (board.getGameState() == GameState.PLAYING2a) {
choosePieceToMove();
makeMove();
} else if (board.getGameState() == GameState.PLAYING3a || board.getGameState() == GameState.PLAYING3b) {
removePiece();
makeMove();
} else if (formMill()) {
makeMove();
} else if (blockTwo()) {
makeMove();
} else if (formTwo()) {
this.counterForm2++;
makeMove();
} else {
while (true) {
move = rand.nextInt(24);
boolean status = makeMove();
if (status)
break;
}
}
}
private void choosePieceToMove() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.WHITE || board.grid[row][col] == Dot.WHITEMILL)
&& board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedFormMill()) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
// board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.BLACK || board.grid[row][col] == Dot.BLACKMILL)
&& board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedFormMill()&& moveTo!=25) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.WHITE || board.grid[row][col] == Dot.WHITEMILL)
&& board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedBlockTwo()) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.BLACK || board.grid[row][col] == Dot.BLACKMILL)
&& board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedBlockTwo()&& moveTo!=25) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.WHITE || board.grid[row][col] == Dot.WHITEMILL)
&& board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedFormTwo()) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.BLACK || board.grid[row][col] == Dot.BLACKMILL)
&& board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedFormTwo()&& moveTo!=25) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.WHITE || board.grid[row][col] == Dot.WHITEMILL)
&& board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedRandom()) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if ((board.grid[row][col] == Dot.BLACK || board.grid[row][col] == Dot.BLACKMILL)
&& board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
board.highlightValidMoves(row, col);
if (anyDotHighlightedRandom()&& moveTo!=25) {
moveFrom = move;
board.setGray();
board.checkMillsOnTheBoard();
//board.clearMills();
board.updateGameState(board.getCurrentTurn());
board.setGray();
return;
}
}
board.setGray();
}
}
}
private boolean anyDotHighlightedRandom() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[col][row] == Dot.HIGHLIGHTWHITE && board.currentTurn == Dot.WHITE) {
int index = board.indexOf(row, col);
moveFrom = move;
moveTo = index;
return true;
}
if (board.grid[col][row] == Dot.HIGHLIGHTBLACK && board.currentTurn == Dot.BLACK) {
int index = board.indexOf(row, col);
moveFrom = move;
moveTo = index;
return true;
}
}
}
return false;
}
private boolean anyDotHighlightedFormMill() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[col][row] == Dot.HIGHLIGHTWHITE && board.currentTurn == Dot.WHITE) {
int index = board.indexOf(row, col);
if (formMillSecondPhase(index)) {
moveTo = index;
return true;
}
}
if (board.grid[col][row] == Dot.HIGHLIGHTBLACK && board.currentTurn == Dot.BLACK) {
int index = board.indexOf(row, col);
if (formMillSecondPhase(index)) {
moveTo = index;
return true;
}
}
}
}
return false;
}
private boolean anyDotHighlightedBlockTwo() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[col][row] == Dot.HIGHLIGHTWHITE && board.currentTurn == Dot.WHITE) {
int index = board.indexOf(row, col);
if (blockTwoSecondPhase(index)) {
moveTo = index;
return true;
}
}
if (board.grid[col][row] == Dot.HIGHLIGHTBLACK && board.currentTurn == Dot.BLACK) {
int index = board.indexOf(row, col);
if (blockTwoSecondPhase(index)) {
moveTo = index;
return true;
}
}
}
}
return false;
}
private boolean anyDotHighlightedFormTwo() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[col][row] == Dot.HIGHLIGHTWHITE && board.currentTurn == Dot.WHITE) {
int index = board.indexOf(row, col);
if (formTwoSecondPhase(index)) {
moveTo = index;
return true;
}
}
if (board.grid[col][row] == Dot.HIGHLIGHTBLACK && board.currentTurn == Dot.BLACK) {
int index = board.indexOf(row, col);
if (formTwoSecondPhase(index)) {
moveTo = index;
return true;
}
}
}
}
return true;
}
private void moveThePiece() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[row][col] == Dot.HIGHLIGHTWHITE && board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
return;
}
if (board.grid[row][col] == Dot.HIGHLIGHTBLACK && board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
return;
}
}
}
}
public void printTheBoard() {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
System.out.println(board.getDot(row, col) + " " + row + " " + col);
}
}
}
public void removePiece() {
if (board.notInTheMillAvailible()) {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[row][col] == Dot.WHITE && board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
}
if (board.grid[row][col] == Dot.BLACK && board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
}
}
}
} else {
for (int row = 0; row < Board.SIZE; ++row) {
for (int col = 0; col < Board.SIZE; ++col) {
if (board.grid[row][col] == Dot.WHITE && board.currentTurn == Dot.BLACK
|| board.grid[row][col] == Dot.WHITEMILL && board.currentTurn == Dot.BLACK) {
move = board.indexOf(col, row);
}
if (board.grid[row][col] == Dot.BLACK && board.currentTurn == Dot.WHITE
|| board.grid[row][col] == Dot.BLACKMILL && board.currentTurn == Dot.WHITE) {
move = board.indexOf(col, row);
}
}
}
}
}
public boolean formMill() {
boolean millcheck = false;
for (int indexTo = 0; indexTo < board.positionOfCells.length; indexTo++) {
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (checkedMills.contains(millList)) {
millcheck = false;
}
if (millList.contains(indexTo)) {
int i = 0;
for (int neighbor : millList) {
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
board.checkMill(col, row);
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACK)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITE)) {
{
dots[i] = board.indexOf(row, col);
i++;
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 2) {
millcheck = true;
for (int neighborInMill : millList) {
int rowE = board.positionOfCells[neighborInMill][0];
int colE = board.positionOfCells[neighborInMill][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(colE, rowE) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACK)
|| (board.currentTurn == Dot.BLACK
&& board.getDot(colE, rowE) == Dot.WHITEMILL)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACKMILL)) {
if (!checkedMills.contains(millList))
checkedMills.add(millList);
millcheck = false;
}
}
for (int neighborInMill : millList) {
if (!dotsList.contains(neighborInMill) && millcheck != false) {
move = neighborInMill;
return true;
}
}
}
}
}
}
}
}
}
return millcheck;
}
public boolean formMillSecondPhase(int indexTo) {
boolean millcheck = false;
boolean check = true;
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (millList.contains(indexTo)) {
int i = 0;
check = true;
for (int neighbor : millList) {
if (!check) {
break;
}
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
board.checkMill(col, row);
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACK)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITE)) {
{
dots[i] = board.indexOf(row, col);
i++;
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 2) {
millcheck = true;
for (int neighborInMill : millList) {
int rowE = board.positionOfCells[neighborInMill][0];
int colE = board.positionOfCells[neighborInMill][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(colE, rowE) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE && board.getDot(colE, rowE) == Dot.BLACK)
|| (board.currentTurn == Dot.BLACK
&& board.getDot(colE, rowE) == Dot.WHITEMILL)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACKMILL)) {
// if (!checkedMills.contains(millList))
// checkedMills.add(millList);
millcheck = false;
}
}
for (int neighborInMill : millList) {
int rowE = board.positionOfCells[neighborInMill][0];
int colE = board.positionOfCells[neighborInMill][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(colE, rowE) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE && board.getDot(colE, rowE) == Dot.BLACK)
|| (board.currentTurn == Dot.BLACK
&& board.getDot(colE, rowE) == Dot.WHITEMILL)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACKMILL)) {
check = false;
break;
}
if (neighborInMill == move) {
continue;
}
if (!dotsList.contains(neighborInMill) && millcheck != false
&& !dotsList.contains(move) && check) {
moveTo = neighborInMill;
return true;
}
}
}
}
}
}
}
}
return false;
}
public boolean blockTwo() {
boolean millcheck = false;
for (int indexTo = 0; indexTo < board.positionOfCells.length; indexTo++) {
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (closedMills.contains(millList)) {
continue;
}
if (millList.contains(indexTo)) {
int i = 0;
for (int neighbor : millList) {
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.BLACK)) {
i++;
dots[i] = board.indexOf(row, col);
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 2) {
int j = 0;
for (int neighborInMill : millList) {
if (dotsList.contains(neighborInMill)) {
j++;
}
}
if (j == 2) {
for (int neighborInMill : millList) {
if (!dotsList.contains(neighborInMill)) {
closedMills.add(millList);
move = neighborInMill;
return true;
}
}
}
}
}
}
}
}
}
return millcheck;
}
public boolean blockTwoSecondPhase(int indexTo) {
boolean millcheck = false;
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (closedMills.contains(millList)) {
continue;
}
if (millList.contains(indexTo)) {
int i = 0;
for (int neighbor : millList) {
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.BLACK)) {
i++;
dots[i] = board.indexOf(row, col);
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 2) {
int j = 0;
for (int neighborInMill : millList) {
if (dotsList.contains(neighborInMill)) {
j++;
}
}
if (j == 2) {
for (int neighborInMill : millList) {
if (!dotsList.contains(neighborInMill)) {
closedMills.add(millList);
moveTo = neighborInMill;
return true;
}
}
}
}
}
}
}
}
return false;
}
public boolean formTwo() {
boolean millcheck = false;
for (int indexTo = 0; indexTo < board.positionOfCells.length; indexTo++) {
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (checkedMills.contains(millList)) {
millcheck = false;
}
if (millList.contains(indexTo)) {
int i = 0;
for (int neighbor : millList) {
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACK)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITE)
|| (board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACKMILL)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITEMILL)) {
{
dots[i] = board.indexOf(row, col);
i++;
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 1) {
millcheck = true;
for (int neighborInMill : millList) {
int rowE = board.positionOfCells[neighborInMill][0];
int colE = board.positionOfCells[neighborInMill][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(colE, rowE) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACK)
|| (board.currentTurn == Dot.BLACK
&& board.getDot(colE, rowE) == Dot.WHITEMILL)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACKMILL)) {
if (!checkedMills.contains(millList))
checkedMills.add(millList);
millcheck = false;
}
}
for (int neighborInMill : millList) {
if (!dotsList.contains(neighborInMill) && millcheck != false) {
move = neighborInMill;
return true;
}
}
}
}
}
}
}
}
}
return millcheck;
}
public boolean formTwoSecondPhase(int indexTo) {
boolean millcheck = false;
for (int[] mill : board.millsArray) {
List<Integer> millList = Arrays.stream(mill).boxed().collect(Collectors.toList());
int[] dots = new int[4];
if (checkedMills.contains(millList)) {
millcheck = false;
}
if (millList.contains(indexTo)) {
int i = 0;
for (int neighbor : millList) {
int row = board.positionOfCells[neighbor][0];
int col = board.positionOfCells[neighbor][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACK)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITE)
|| (board.currentTurn == Dot.BLACK && board.getDot(col, row) == Dot.BLACKMILL)
|| (board.currentTurn == Dot.WHITE && board.getDot(col, row) == Dot.WHITEMILL)) {
{
dots[i] = board.indexOf(row, col);
i++;
List<Integer> dotsList = Arrays.stream(dots).boxed().collect(Collectors.toList());
if (i == 1) {
millcheck = true;
for (int neighborInMill : millList) {
int rowE = board.positionOfCells[neighborInMill][0];
int colE = board.positionOfCells[neighborInMill][1];
if ((board.currentTurn == Dot.BLACK && board.getDot(colE, rowE) == Dot.WHITE)
|| (board.currentTurn == Dot.WHITE && board.getDot(colE, rowE) == Dot.BLACK)
|| (board.currentTurn == Dot.BLACK
&& board.getDot(colE, rowE) == Dot.WHITEMILL)
|| (board.currentTurn == Dot.WHITE
&& board.getDot(colE, rowE) == Dot.BLACKMILL)) {
if (!checkedMills.contains(millList))
checkedMills.add(millList);
millcheck = false;
}
if (neighborInMill == move) {
continue;
}
}
for (int neighborInMill : millList) {
if (!dotsList.contains(neighborInMill) && millcheck != false
&& !dotsList.contains(move)) {
moveTo = neighborInMill;
return true;
}
}
}
}
}
}
}
}
return false;
}
}
<file_sep>package sprint2.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sprint2.product.Board;
import sprint2.product.GUI;
public class TestGUIEmptyBoard {
private Board board;
@Before
public void setUp() throws Exception {
board = new Board();
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>package sprint2.product;
public enum Dot {
EMPTY, WHITE, BLACK, NOTUSED, GRAY, BLACKMILL, WHITEMILL, HIGHLIGHTWHITE, HIGHLIGHTBLACK
}<file_sep>package sprint2.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import org.junit.Test;
import sprint2.product.Board;
import sprint2.product.Dot;
import sprint2.product.GUI;
import sprint2.product.GameRegime;
import sprint2.product.GameState;
public class TestWinConditions {
private final Board board = new Board(4);
@Test
public void testWhiteOpponentBlockedBlackWins() {
board.setCurrentGameRegime(GameRegime.P1vP2);
board.setGameState(GameState.PLAYING1);
board.setCurrentTurn(Dot.WHITE);
board.makeMoveFirstPhase(6);
board.makeMoveFirstPhase(7);
board.makeMoveFirstPhase(8);
board.makeMoveFirstPhase(11);
board.makeMoveFirstPhase(15);
board.makeMoveFirstPhase(16);
board.makeMoveFirstPhase(17);
board.makeMoveFirstPhase(12);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(board.getGameState(),GameState.BLACK_WON);
}
@Test
public void testBlackOpponentBlockedWhiteWins() {
board.setCurrentGameRegime(GameRegime.P1vP2);
board.setGameState(GameState.PLAYING1);
board.setCurrentTurn(Dot.WHITE);
board.makeMoveFirstPhase(7);
board.makeMoveFirstPhase(6);
board.makeMoveFirstPhase(11);
board.makeMoveFirstPhase(8);
board.makeMoveFirstPhase(16);
board.makeMoveFirstPhase(15);
board.makeMoveFirstPhase(13);
board.makeMoveFirstPhase(17);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(13);
board.makeMoveSecondPhaseB(13, 12);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(board.getGameState(),GameState.WHITE_WON);
}
@Test
public void testWhiteOpponentLessThanThreePiecesBlackWins() {
board.setCurrentGameRegime(GameRegime.P1vP2);
board.setGameState(GameState.PLAYING1);
board.setCurrentTurn(Dot.WHITE);
board.makeMoveFirstPhase(0);
board.makeMoveFirstPhase(9);
board.makeMoveFirstPhase(1);
board.makeMoveFirstPhase(21);
board.makeMoveFirstPhase(14);
board.makeMoveFirstPhase(15);
board.makeMoveFirstPhase(23);
board.makeMoveFirstPhase(22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(14);
board.makeMoveSecondPhaseB(14, 2);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveThirdPhase(21);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(22);
board.makeMoveSecondPhaseB(22, 21);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(2);
board.makeMoveSecondPhaseB(2, 14);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(21);
board.makeMoveSecondPhaseB(21, 22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(14);
board.makeMoveSecondPhaseB(14, 2);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveThirdPhase(22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(board.getGameState(),GameState.WHITE_WON);
}
@Test
public void testBlackOpponentLessThanThreePiecesWhiteWins() {
board.setCurrentGameRegime(GameRegime.P1vP2);
board.setGameState(GameState.PLAYING1);
board.setCurrentTurn(Dot.BLACK);
board.makeMoveFirstPhase(0);
board.makeMoveFirstPhase(9);
board.makeMoveFirstPhase(1);
board.makeMoveFirstPhase(21);
board.makeMoveFirstPhase(14);
board.makeMoveFirstPhase(15);
board.makeMoveFirstPhase(23);
board.makeMoveFirstPhase(22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(14);
board.makeMoveSecondPhaseB(14, 2);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveThirdPhase(21);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(22);
board.makeMoveSecondPhaseB(22, 21);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(2);
board.makeMoveSecondPhaseB(2, 14);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(21);
board.makeMoveSecondPhaseB(21, 22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveSecondPhaseA(14);
board.makeMoveSecondPhaseB(14, 2);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
board.makeMoveThirdPhase(22);
new GUI(board);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(board.getGameState(),GameState.BLACK_WON);
}
}
<file_sep># ninemensmorris
Nine Men's Morris Game with simple Artificial Intelligence.
<file_sep>package sprint2.product;
public enum GameState {
CHOOSECOLOR, CHOOSEOPPONENT,START,PLAYING1, PLAYING2a, PLAYING2b1, PLAYING3a, PLAYING3b, DRAW, WHITE_WON, BLACK_WON
}
<file_sep>package sprint2.test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import sprint2.product.Board;
import sprint2.product.Dot;
public class TestEmptyBoard {
private final Board board = new Board();
@Test
public void testNewBoard() {
assertThat(board.getDot(0, 0), is(Dot.EMPTY));
assertThat(board.getDot(0, 1), is(Dot.NOTUSED));
assertThat(board.getDot(0, 2), is(Dot.NOTUSED));
assertThat(board.getDot(0, 3), is(Dot.EMPTY));
for (int row = 0; row != board.getTotalRows(); ++row) {
for (int col = 0; col != board.getTotalColumns(); ++col) {
assertThat(board.getDot(row, col), anyOf(is(Dot.EMPTY), is(Dot.NOTUSED)));
}
}
}
@Test
public void testInvalidRow() {
assertThat(board.getDot(board.getTotalRows(), 0), is(Dot.NOTUSED));
}
@Test
public void testInvalidColumn() {
assertThat(board.getDot(0, board.getTotalColumns()), is(Dot.NOTUSED));
}
}
| 3a135bdfce92b5655ad2ffb7babbb8fe00c6911b | [
"Markdown",
"Java"
] | 7 | Java | vladi7/nine-mens-morris | a6368bd71d16b01eb688467ad7e44ce697dfefa4 | 041c9e8b1a3feec389c2c9dfa66652e38c70bbb5 |
refs/heads/master | <file_sep>import {sum} from "./a.js";
let flag=false;
let name='XH';
console.log(sum(50,10))
<file_sep>export const name='why';
export const age='28';<file_sep>(function(){
//使用导出的对象
if(moduleA.flag){
console.log('小明是天才');
}
moduleA.sum('50',40);
})()
<file_sep>package com.cjx.demo.controller;
/**
* 类名:VuejsBackController
* 作者:cxl
* 日期:2020/3/13 17:18
* 版本:1.0
**/
public class VuejsBackController {
}
<file_sep>import Vue from 'vue'
/*来自框架*/
import Router from 'vue-router'
//import home from '@/components/home'
//import home2 from '@/components/home2'
//import user from '@/components/user'
//路由懒加载写法//一个懒加载对应一个 static/js中一个js文件
const home =()=> import('@/components/home');
const homeNews=()=>import('@/components/homeNews');
const homeMessage=()=>import('@/components/homeMessage');
const home2 =()=> import('@/components/home2');
const user =()=> import('@/components/user');
const profile=()=>import('@/components/profile');
//1.安装插件
Vue.use(Router)
//2.创建router对象
//3.router对象导出
const router= new Router({
routes: [
{
path:'',
redirect:'/home'
},
{
path: '/home',
component: home,
//嵌套路由
meta:{
title:'首页'//路由导航自动设置title
},
children:[
{ path:'',
redirect:'news'},
{
path:'news',//不用加斜杠
component:homeNews
},{
path:'message',//不用加斜杠
component:homeMessage
}
]
},
{
path: '/home2',
component: home2,
meta:{
title:'关于'
//独享路由守卫
},beforeEnter(to,from,next){
console.log('after beforeEnter');
next();
}
},
{
path: '/user/:userId',//配置动态路由
component: user,
meta:{
title:'用户'
}
},{
path:'/profile',
component:profile,
meta:{
title:'档案'
},
}
],
/*html history模式**/
mode:'history',
linkActiveClass:'active'//谁处于活跃状态谁添加此样式统一监听
})
//路由导航守卫(全局守卫)
//前置钩子(回调)
router.beforeEach((to,form,next)=>{
//from到to
document.title=to.matched[0].meta.title;
console.log(to);
next()
})
router.afterEach((to,from)=>{
console.log('after');
})
export default router;
<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
import {CXL, HD, YB,HDPROMISE} from './mutations-types'
//1.安装插件
Vue.use(Vuex)
const moduleA={
state:{
name:'张三'
},mutations:{
//rootState为根目录的state
updateName(state,rootState){
state.name="HHHHHH"
}
},getters:{
fullname(state){
return '<moduleGetter>'
}
},actions:{
//这里仅提交本模块内的的mutations
}
}
//2.创建对象
const store=new Vuex.Store({
//变量
state:{
counter:1,
cxl:'cxl',
students:[{id:110,name:'cxl',age:18},{id:111,name:'cxl2',age:10},{id:112,name:'cxl3',age:20}],
info:{
name:'cxl',
age:40,
height:1.98
}
},
mutations:{
//方法 修改state必须经过此方法
incremert(state){
state.counter++;
},
//细节
incremertCount(state,count){
state.counter= state.counter+count;
},addStudent(state,student){
state.students.push(student);
},updateInfo(state){
state.info.name="fuck"
},updateInfoR(state){
//增加属性响应式//应使用vue内部方法
Vue.set(state.info,'address','洛杉矶')
},updateInfoS(state){
Vue.delete(state.info,'age')
},[CXL](state){
state.cxl='cxl is best';
},[YB](state){
state.info.name='异步处理';
}
},
//异步处理需要此环节
actions:{
//定义一个方法
[YB](context,payload){
setTimeout(()=>{
context.commit(YB);//执行此代码证明成功执行 返回成功消息
console.log(payload)
},5000)
}, [HD](context,payload){
setTimeout(()=>{
context.commit(YB);//执行此代码证明成功执行 返回成功消息
console.log(payload.message)
payload.success();
},5000)
},[HDPROMISE](context,payload){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
context.commit(YB);
console.log(payload)
resolve()
},1000)
})
}
},
//经过变化之后
getters:{
powerCounter(state){
return state.counter*state.counter;
},
more20(state){
//过滤数组的函数式
return state.students.filter(s=>{
return s.age>=20;
})
},
more20Length(state,getters){
return getters.more20.length
},moreAgeStu(state){
return age=> {
return state.students.filter(s=>{
return s.age>=age;
})
}
}
},
//各分组件定义
modules:{
a:moduleA
}
})
//导出store独享
export default store
<file_sep>const uglifyjswebpackPlugin=require('uglifyjs-webpack-plugin');
const webpackMerge=require('webpack-merge');
const baseConfig=require('./base.config');
const webpack=require('webpack');
const HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports=webpackMerge(baseConfig,{
plugins:[
//给bundle.js在打包时添加如下文字
new webpack.BannerPlugin('最终版权归苏维埃'),
new HtmlWebpackPlugin({
template:'index.html'//根据此文件作为模板
}),
//new uglifyjswebpackPlugin()//压缩js开发时不使用
]
})
<file_sep>let name='XM';
let age=18;
let flag=true;
function sum(num1,num2){
return num1+num2;
}
//导出对象-基本写法
export{
flag,
sum
};
//导出属性
export let num1=1000;
//导出函数
export function mul(a,b){
return a*b;
}
//导出类
export class Person{
run(){
console.log('在奔跑');
}
}
//使用者自定义导入 export default
const address='北京市';
//一个js文件只能有一个
export default address;
<file_sep>(function(){
var name='小红';
var flag=false;
console.log(name);
})()
<file_sep>
const webpackMerge=require('webpack-merge');
const baseConfig=require('./base.config');
module.exports=webpackMerge(baseConfig,{
devServer:{//搭建本地服务器
contentBase:'./dist',//监听位置//修改代码界面可以自动刷新
inline:true//实时监听
}
});
<file_sep>const {add,mul}=require('./mathUtils');
console.log(add(20,30));
console.log(mul(8,9));
import{name,age} from './info'
console.log('姓名:'+name);
console.log(age+'岁');<file_sep>const app=new Vue({
el:'#app',
data:{
books:[{
id:1,
name:'《算法导论》',
date: '3006-9',
price: 85.00,
count: 1
},{
id:2,
name:'《Unix法导论》',
date: '2056-9',
price: 185.00,
count: 1
},{
id:2,
name:'《Linx导论》',
date: '2016-9',
price: 285.00,
count: 1
},{
id:3,
name:'《Dos导论》',
date: '2006-9',
price: 485.00,
count: 1
}]
},
filters:{
showPrice:function(price){
return '$'+price.toFixed(2);
}
},
methods:{
decrement:function(index){
console.log('-')
this.books[index].count--;
},
increment:function(index){
console.log('+')
this.books[index].count++;
},
remove:function(index){
this.books.splice(index,1);
}
},
computed:{
totalPrice(){
let totalPrice=0;
for(let v of this.books){
totalPrice+=v.price*v.count;
}
return totalPrice;
}
}
})<file_sep>//全部导入
import * as a from 'a.js'
export default function(){
console.log('ddddddddddddddd')
console.log(a.flag);
console.log('ppppppppppppppp')
}<file_sep>const {add,mul}=require('./js/mathUtils');
console.log(add(20,30));
console.log(mul(8,9));
import{name,age} from './js/info'
console.log('姓名:'+name);
console.log(age+'岁');
//3.依赖css文件 安装+配置
require('./css/normal.css');
//4.依赖less文件 安装+配置
require('./css/special.less');
//5.写文字
document.writeln("<h2>IQY</h2>");
//6.使用Vue
import Vue from 'vue'
import App from './vue/App.vue'
const app=new Vue({
el:'#app',
template:`<App/>`,
components:{
App
}
});
document.writeln("<button>CXL----2056-呵呵</button>")
| b97b88ade6b74298a40c3d761bf305a578c2e0d4 | [
"JavaScript",
"Java"
] | 14 | JavaScript | cxl20171104/Vue.js-exercise | 7e5eb173a1ce6d61596d2bc6955332b155886614 | f28792ac73223f154e9ef083e3aa6b2945df457a |
refs/heads/master | <repo_name>SouravG/online-message-passing-using-visual-cryptography-and-DES<file_sep>/visualCrypto/src/org/visualCrypto/UpdateName.java
package org.visualCrypto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class UpdateName
*/
public class UpdateName extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateName() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
HttpSession hs=request.getSession();
String email =request.getParameter("email");
String pwd =request.getParameter("pwd");
String name =request.getParameter("name");
if(UserData.updateName(email, name, pwd)){
out.println("1");
System.out.println("True");
}else System.out.println("False");
}
}
<file_sep>/visualCrypto/WebContent/js/ajax/updateCountry.js
function changeCountry(user)
{
var str=document.getElementById("pwd3").value;
var str1=document.getElementById("country").value;
var xmlhttp;
if (str.length==0||str1.length==0)
{ document.getElementById("countryHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText==1){
document.getElementById("countryHint").innerHTML="Country changed";
document.getElementById("pwd3").value="";
//document.getElementById("country").selectedIndex = -1;
document.getElementById("countryHint").style.color="green";
}
else{
document.getElementById("pwd3").value="";
//document.getElementById("country").selectedIndex = -1;
document.getElementById("countryHint").innerHTML="Faild to update";
document.getElementById("countryHint").style.color="red";
}
}
}
xmlhttp.open("GET","UpdateCountry?pwd="+str+"&country="+str1+"&email="+user,true);
xmlhttp.send();
}
<file_sep>/visualCrypto/src/org/visualCrypto/ForgotPass.java
package org.visualCrypto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ForgotPass
*/
public class ForgotPass extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ForgotPass() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String email=request.getParameter("email");
if(email.equals(UserData.checkEmail(email))){
String fromUser=UserData.getUserNameFromEmail(email);
out.println("<div id='res' style='border:2px solid #0000ff;background:#D6D6FF;color=blue;'> Username="+fromUser+"</div>");
}else{
out.println("<div id='res' style='border:2px solid #ff0000;background:pink;'>No user found on this email address</div>");
}
}
}
<file_sep>/visualCrypto/src/org/visualCrypto/Test.java
package org.visualCrypto;
import java.io.PrintWriter;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.rmi.transport.Transport;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message.*;
public class Test extends HttpServlet {
//default value for mail server address, in case the user
//doesn't provide one
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
PrintWriter out=response.getWriter();
String email=request.getParameter("email");
if(email.equals(UserData.checkEmail(email))){
out.println(1);
}
//System.out.println(email);
}
}//EmailServlet<file_sep>/visualCrypto/WebContent/js/passwordValidator.js
function passwordStrength(password)
{
var desc = new Array();
desc[0] = "<div style='color:#cccccc'>Very Weak </div>";
desc[1] = "<div style='color:#ff0000'>Weak</div>";
desc[2] = "<div style='color:#ff7f7f'>Better</div>";
desc[3] = "<div style='color:#56e722'>Medium</div>";
desc[4] = "<div style='color:#4dcd22'>Strong</div>";
desc[5] = "<div style='color:#399822'>Strongest</div>";
var score = 0;
//if password bigger than 4 give 1 point
if (password.length > 4) score++;
//if password has both lower and uppercase characters give 1 point
if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;
//if password has at least one number give 1 point
if (password.match(/\d+/)) score++;
//if password has at least one special caracther give 1 point
if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;
//if password bigger than 8 give another 1 point
if (password.length > 8) score++;
document.getElementById("passwordDescription").innerHTML = desc[score];
document.getElementById("passwordStrength").className = "strength" + score;
var meter=(score*50)+"px";
$("#passwordStrength").animate({width:meter});
}
<file_sep>/visualCrypto/WebContent/js/checkEmail.js
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{if(xmlhttp.responseText==1){
document.getElementById("txtHint").innerHTML="<div id='res' style='border:2px solid #ff0000;background:pink;'> This email has been registered already</div>";
document.getElementById("submit").disabled=true;
}
else{
document.getElementById("txtHint").innerHTML="";
document.getElementById("submit").disabled=false;
}
}
}
xmlhttp.open("GET","Test?email="+str,true);
xmlhttp.send();
}
<file_sep>/visualCrypto/src/org/visualCrypto/SendMailExample.java
package org.visualCrypto;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMailExample
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void mail(String email,String message,String username)
{
String[] to={email};
String fullMessage="Hello "+username+"\n"+"\n"+"\n"+"Your Activation code is= "+message+" "+"\n"+"\n"+"You can login to your account. Paste the Activation code in the login page"+"\n"+"Thank You."+"\n"+"The Encrustation Team."+"\n"+""+"\n"+""+"\n"+"from Encrustation.com Copyright © 2012 encrustation.com - All rights reserved "+"\n \n"+"This is a post-only mailing. Replies to this message are not monitored or answered. ";
//This is for google
SendMailExample.sendMail("<EMAIL>"," gijocmtgpgxxpqhk ","smtp.gmail.com","465","true","true",true,"javax.net.ssl.SSLSocketFactory","false",to,"Encrustation Account Activition Code",fullMessage);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void sendPassword(String email,String password ,String username)
{
String[] to={email};
String fullMessage="Hello "+username+"\n"+"\n"+"\n"+"Your Password is= "+password+" "+"\n"+"\n"+"You can login to your account. Use this Password in the login page"+"\n"+"Thank You."+"\n"+"The Encrustation Team."+"\n"+""+"\n"+""+"\n"+"From Encrustation.com Copyright © 2012 encrustation.com - All rights reserved "+"\n \n"+"This is a post-only mailing. Replies to this message are not monitored or answered. ";
//This is for google
SendMailExample.sendMail("<EMAIL>"," gijocmtgpgxxpqhk ","smtp.gmail.com","465","true","true",true,"javax.net.ssl.SSLSocketFactory","false",to,"Encrustation Account Password Recovery",fullMessage);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void changeLoginConfirmationEmail(String email ,String username,String ipAddr,String Os,String Country,String Browser)
{
String[] to={email};
String fullMessage="Hi "+username+"\n"+"\n"+"\n"+"We detected a login into your account from an unrecognized device "+"\n The client description is\n\n"+"IP Address : "+ipAddr+"\n Browser : "+Browser+"\n Operating System : "+Os+"\n Country : "+Country+"\n \n If this was you, please disregard this email.\n If this wasn't you, please change your password, as someone else may be accessing it.\n \n Thank You."+"\n"+"The Encrustation Team."+"\n"+""+"\n"+""+"\n"+"From Encrustation.com Copyright © 2012 encrustation.com - All rights reserved "+"\n \n"+"This is a post-only mailing. Replies to this message are not monitored or answered. ";
//This is for google
SendMailExample.sendMail("<EMAIL>"," gijocmtgpgxxpqhk ","smtp.gmail.com","465","true","true",true,"javax.net.ssl.SSLSocketFactory","false",to,"Encrustation login from an unknown device",fullMessage);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public synchronized static boolean sendMail(String userName,String passWord,String host,String port,String starttls,String auth,boolean debug,String socketFactoryClass,String fallback,String[] to,String subject,String text){
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
Session session = Session.getDefaultInstance(props, new GMailAuthenticator("noreply.encrustation", " gijocmtgpgxxpqhk "));
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("<EMAIL>"));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = <PASSWORD>;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}<file_sep>/README.md
online-message-passing-using-visual-cryptography-and-DES
========================================================
how to run:
steps
1. create a schema in mysql.
2. import userdata.sql file to the schema.
3. change database url,username,password in src/org/visualCrypto/DatabaseUtil.java file.
4. copy the full path of the \visualCrypto\WebContent\userImages folder.
5. using this path update file11 and file22 variables in src/org/visualCrypto/EmailTheImages.java file.
eg.
String file11="paste_here/visualCrypto/WebContent/userImages/"+fromUserEmail+"/encr1.png";
String file22="paste_here/visualCrypto/WebContent/userImages/"+fromUserEmail+"/encr2.png";
6. again paste the path in serverPath variable in src/org/visualCrypto/DecryptionSecond.java file and \visualCrypto\WebContent\test2.jsp
eg.
in DecryptionSecond.java
String serverPath="paste_here/visualCrypto/WebContent/userImages"+user;
in test2.jsp file
String serverPath="paste_here/visualCrypto/WebContent/userImages/"+email;
paste that in appropriate place , do not add spaces ..
7.change email host,port,userid,password in src/org/visualCrypto/test1.java file and in src/org/visualCrypto/SendMailExample.java file
8.run in a web server .
<file_sep>/visualCrypto/WebContent/js/ajax/updatePwd.js
function showHint(user)
{
var str=document.getElementById("pwd").value;
var str1=document.getElementById("password").value;
var xmlhttp;
if (str.length==0||str1.length==0)
{ document.getElementById("txtHint1").innerHTML="";
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText!=null){
document.getElementById("txtHint1").innerHTML="";
document.getElementById("txtHint").innerHTML="password changed";
document.getElementById("pwd").value="";
document.getElementById("repwd").value="";
document.getElementById("password").value="";
}
else{
document.getElementById("pwd").value="";
document.getElementById("repwd").value="";
document.getElementById("password").value="";
document.getElementById("txtHint").innerHTML="";
document.getElementById("txtHint1").innerHTML="your password was incorrect";
}
}
};
xmlhttp.open("GET","UpdatePassword?old="+str+"&new="+str1+"&user="+user,true);
xmlhttp.send();
}
<file_sep>/visualCrypto/jee schema def.sql
delimiter $$
CREATE DATABASE `jee` /*!40100 DEFAULT CHARACTER SET utf8 */$$
<file_sep>/visualCrypto/userdata.sql
delimiter $$
CREATE TABLE `userdata` (
`slno` int(8) NOT NULL AUTO_INCREMENT,
`uno` varchar(90) DEFAULT NULL,
`name` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`dob` varchar(60) DEFAULT NULL,
`sex` varchar(7) DEFAULT NULL,
`country` varchar(90) DEFAULT NULL,
`email` varchar(90) DEFAULT NULL,
`phone` int(12) DEFAULT NULL,
`active` varchar(12) DEFAULT NULL,
PRIMARY KEY (`slno`),
UNIQUE KEY `uno` (`uno`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8$$
<file_sep>/visualCrypto/src/org/visualCrypto/GenerateUUID_Bean.java
package org.visualCrypto;
import java.util.UUID;
public class GenerateUUID_Bean {
public static String getUnoByUUID(){
String uno=null;
uno=UUID.randomUUID().toString();
System.out.println(uno+"\2 hello world!\2");
return uno;
}
public static void main(String[] args) {
GenerateUUID_Bean.getUnoByUUID();
}
}
<file_sep>/visualCrypto/src/org/visualCrypto/DatabaseUtil.java
package org.visualCrypto;
import java.sql.Connection;
import java.sql.DriverManager;
public class DatabaseUtil {
public static Connection getConnection() throws Exception{
//this static method use for building mysql database connection
String driverName="com.mysql.jdbc.Driver";
Class.forName(driverName);
String url="jdbc:mysql://127.12.133.131:3306/crypto";
String uid="root";
String pwd="<PASSWORD>";
Connection con = DriverManager.getConnection(url, uid, pwd);
return con;
}
}
<file_sep>/visualCrypto/src/org/visualCrypto/Testmail.java
package org.visualCrypto;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.*;
public class Testmail
{
public synchronized static void sendEmaih(String To, String toName, String fromUser, String File1, String File2, String key) throws Exception
{
String host = "smtp.gmail.com";//host name
String from = "<EMAIL>";//sender id
String to = To;//reciever id
String pass = " <PASSWORD> ";//sender's password
String fileAttachment = File1;
String fileAttachment1 = File2;//file name for attachment
//system properties
System.out.println(to+fileAttachment+fileAttachment1+key+toName+fromUser);
Properties prop = System.getProperties();
// Setup mail server properties
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.user", from);
prop.put("mail.smtp.password", pass);
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", false);
prop.put("mail.smtp.debug", "true");
//session
Session session = Session.getInstance(prop, new GMailAuthenticator("noreply.encrustation", " gijocmtgpgxxpqhk "));
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Encrustation secret images");
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//message body
String fullMessage="Hello "+toName+"\n"+"\n"+"\n"+" I send you 2 encrypted images and a key"+"\n"+"\n"+"Key="+key+"\n"+"\n"+"Please login to your account and upload images with key to view my message"+"\n"+"Thank You."+"\n"+"From "+fromUser+"\n"+""+"\n"+""+"\n"+"From Encrustation.com Copyright © 2012 encrustation.com - All rights reserved "+"\n \n"+"This is a post-only mailing. Replies to this message are not monitored or answered.";
System.out.println(fullMessage);
messageBodyPart.setText(fullMessage);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
messageBodyPart = new MimeBodyPart();
DataSource source1 = new FileDataSource(fileAttachment1);
messageBodyPart.setDataHandler(new DataHandler(source1));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
//send message to reciever
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}<file_sep>/visualCrypto/src/org/visualCrypto/Keygen.java
package org.visualCrypto;
import java.io.File;
import java.io.FileInputStream;
//import java.io.IOException;
import java.io.InputStream;
import java.math.*;
import java.security.*;
//import java.sql.Connection;
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class Keygen {
/**
* @param args
*/
public static String key(File message){
// TODO Auto-generated method stub
//Connection con=null;
//PreparedStatement pstmt= null;
String keyword="Error!!Key Not Stored";
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream(message);
byte[] buffer = new byte[8192];
int read = 0;
try {
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
keyword = bigInt.toString(30);
/* con=DatabaseUtil.getConnection();
String qr="insert into keyData(message,keyword) values(?,?)";
pstmt=con.prepareStatement(qr,PreparedStatement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "");
pstmt.setString(2, keyword);
pstmt.executeUpdate();
return keyword;
}
catch(IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
}
finally {
try {
is.close();
}
catch(IOException e) {
throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
}
} */
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
}
return keyword;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static SecretKey generateKey(String key)throws Exception{
//KeyGenerator keyGen=KeyGenerator.getInstance("DES");
//Key key=keyGen.generateKey();
//String key = "blahasdasdasdasdasdfasdasdasdasda";
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
return desKey;
}
}<file_sep>/visualCrypto/src/org/visualCrypto/DecryptionDAO.java
package org.visualCrypto;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class DecryptionDAO
*/
public class DecryptionDAO extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DecryptionDAO() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd=null;
HttpSession hs=request.getSession();
String user=(String) hs.getAttribute("name");
String key ="";
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////--------CHANGE SERVER IMAGE PATH HERE--------//////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
String serverPath="F:/JEE/workspace/visualCrypto/WebContent/userImages";///////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
int count=0;
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
count++;
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
if(name.equals("key"))
{
key=value;
}
} else {
try {
String itemName = serverPath+"/decr"+count+".png";
File savedFile = new File(itemName);
item.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
rd=request.getRequestDispatcher("decrypting.jsp?name="+user);
request.setAttribute("key", "Image Decrypted");
rd.include(request, response);
rd=request.getRequestDispatcher("decrypting.jsp?name="+user);
request.setAttribute("key", "Key not found Image not Decrypted");
rd.include(request, response);
}}
<file_sep>/visualCrypto/src/org/visualCrypto/AccountActivationDao.java
package org.visualCrypto;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class AccountActivationDao
*/
public class AccountActivationDao extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AccountActivationDao() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String Activate=request.getParameter("Actv");
HttpSession hs=request.getSession();
String username=(String) hs.getAttribute("user");
String UID=(String)hs.getAttribute("UID");
RequestDispatcher rd=null;
System.out.println(username);
//HttpSession hs=request.getSession();
//PrintWriter out=response.getWriter();
if(UserData.updateAccStatus(Activate, username)){
rd=request.getRequestDispatcher("uploadImage.jsp");
//hs.setAttribute("key", "null");
String name=UserData.getUserNameFromEmail(username);
//out.println("<script type='text/javascript'>alert('')</script>");
hs.setAttribute("name",name);
hs.setAttribute("email", username);
hs.setAttribute("additional", "account has been successfully activated");
hs.setAttribute("UID",UID);
rd.include(request, response);
}
else{
String name=UserData.getUserNameFromEmail(username);
rd=request.getRequestDispatcher("activeAccount.jsp");
request.setAttribute("act",username);
request.setAttribute("act1", name);
hs.setAttribute("UID",UID);
request.setAttribute("res","Sorry! Account has not activated. Please enter activation no correctly");
rd.forward(request, response);
}
}
}
<file_sep>/visualCrypto/src/org/visualCrypto/SignoutDAO.java
package org.visualCrypto;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
/**
* Servlet implementation class Signout
*/
public class SignoutDAO extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SignoutDAO() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String user=(String)session.getAttribute("user");
System.out.println(user);
//session.setAttribute(user, "null");
session.removeAttribute("email");
session.removeAttribute("name");
session.invalidate();
Cookie c=null;
Cookie[] cookies = request.getCookies();
if(cookies!=null)
{
for (int i = 0; i < cookies.length; i++) {
if(cookies[i].getName().equals("UID")){
c = cookies[i];
c.setValue(null);
c.setMaxAge(0);
c.setPath("/");
}}
}
response.sendRedirect("logout.jsp");
}
}
<file_sep>/visualCrypto/src/org/visualCrypto/UserData.java
package org.visualCrypto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserData {
String name,password,email;
int phone;
public static void saveUserData(String name, String password, String dob, String sex, String country, String email, int phone) {
PreparedStatement pstmt=null;
Connection con=null;
try {
con=DatabaseUtil.getConnection();
String qr="insert into userData(uno,name,password,dob,sex,country,email,phone,active) values(?,?,?,?,?,?,?,?,?)";
pstmt=con.prepareStatement(qr,PreparedStatement.RETURN_GENERATED_KEYS);
pstmt.setString(1, GenerateUUID_Bean.getUnoByUUID());
pstmt.setString(2, name);
pstmt.setString(3, password);
pstmt.setString(4, dob);
pstmt.setString(5, sex);
pstmt.setString(6, country);
pstmt.setString(7, email);
pstmt.setInt(8, phone);
pstmt.setString(9, "not active");
pstmt.executeUpdate();
}catch (Exception e) {
// TODO: handle exception
}
finally{
try{
pstmt.close();
con.close();
}
catch (Exception e) {
}
}
}
public static String getAccStatus(String email, String password) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String status="Sorry!!No account found, please Sign Up";
try{
con=DatabaseUtil.getConnection();
String query = "select active from userData where email=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
pstmt.setString(2, password);
rs=pstmt.executeQuery();
if(rs.next()){
status=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
public static boolean updateAccStatus(String accountNo,String email) {
Connection con=null;
PreparedStatement pstmt= null;
String uno=(accountNo);
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set active='active' where uno=? and email=?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, uno);
pstmt.setString(2, email);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
public static String getEmail(String email, String password) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String UserName="Sorry!!No user found, please Sign Up";
try{
con=DatabaseUtil.getConnection();
String query = "select email from userData where email=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
pstmt.setString(2, password);
rs=pstmt.executeQuery();
if(rs.next()){
UserName=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return UserName;
}
public static String checkEmail(String email) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String Email="No email found";
try{
con=DatabaseUtil.getConnection();
String query = "select email from userData where email=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
rs=pstmt.executeQuery();
if(rs.next()){
Email=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return Email;
}
public static String checkUser(String user) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String user1="No user found";
try{
con=DatabaseUtil.getConnection();
String query = "select name from userData where name=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, user);
rs=pstmt.executeQuery();
if(rs.next()){
user1=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return user1;
}
public static String getUserNoByEmail(String email) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String userno=null;
try{
con=DatabaseUtil.getConnection();
String query = "select uno from userData where email=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
rs=pstmt.executeQuery();
if(rs.next()){
userno=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return userno;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
public static RecoveryPassBean getUserPasswordAndName(String email) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
RecoveryPassBean recov=null;
try{
con=DatabaseUtil.getConnection();
String query = "select name,password from userData where email=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
rs=pstmt.executeQuery();
if(rs.next()){
recov=new RecoveryPassBean();
recov.setUsername(rs.getString(1));
recov.setPassword(rs.getString(2));
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return recov;
}
public static String getUserNameFromEmail(String email) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String UserName="Sorry!!No user found, please Sign Up";
try{
con=DatabaseUtil.getConnection();
String query = "select name from userData where email=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
rs=pstmt.executeQuery();
if(rs.next()){
UserName=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return UserName;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static String getPasswordFromUserName(String username) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String password=null;
try{
con=DatabaseUtil.getConnection();
String query = "select passwor from userData where name=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, username);
rs=pstmt.executeQuery();
if(rs.next()){
password=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return password;
}
public static RetriveByUnoBean getEmailAndPasswordByUno(String uno) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
RetriveByUnoBean retrv=null;
try{
con=DatabaseUtil.getConnection();
String query = "select email,password from userData where uno=?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, uno);
rs=pstmt.executeQuery();
if(rs.next()){
retrv=new RetriveByUnoBean();
retrv.setEmail(rs.getString(1));
retrv.setPassword(rs.getString(2));
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return retrv;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static String getUserNoByEmailAndPassword(String email,String pwd) {
Connection con=null;
PreparedStatement pstmt= null;
ResultSet rs=null;
String userno=null;
try{
con=DatabaseUtil.getConnection();
String query = "select uno from userData where email=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, email);
pstmt.setString(2, pwd);
rs=pstmt.executeQuery();
if(rs.next()){
userno=rs.getString(1);
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
rs.close();
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return userno;
}
public static boolean updatePassword(String email,String oldPassword,String newPassword) {
Connection con=null;
PreparedStatement pstmt= null;
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set password=? where email=? and password = ?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, newPassword);
pstmt.setString(2, email);
pstmt.setString(3, oldPassword);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
public static boolean updateDOB(String email,String dob,String Password) {
Connection con=null;
PreparedStatement pstmt= null;
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set dob=? where email=? and password = ?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, dob);
pstmt.setString(2, email);
pstmt.setString(3, Password);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean updateName(String email,String name,String Password) {
Connection con=null;
PreparedStatement pstmt= null;
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set name=? where email=? and password = ?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, email);
pstmt.setString(3, Password);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
public static boolean updateCountry(String email,String country,String Password) {
Connection con=null;
PreparedStatement pstmt= null;
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set country=? where email=? and password = ?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, country);
pstmt.setString(2, email);
pstmt.setString(3, Password);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean updateUnoByEmail(String email) {
Connection con=null;
PreparedStatement pstmt= null;
boolean status=false;
try{
con=DatabaseUtil.getConnection();
String query = "update userData set uno=? where email=?";
//String query = "select active from userData where name=? and password = ?";
pstmt=con.prepareStatement(query);
pstmt.setString(1, GenerateUUID_Bean.getUnoByUUID());
pstmt.setString(2, email);
int updateno=pstmt.executeUpdate();
if(updateno==1){
status=true;
}
}
catch (Exception e) {
System.out.println("Unable to load the driver");
}
finally{
try{
pstmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
return status;
}
}
<file_sep>/visualCrypto/WebContent/js/SendImages.js
function sendImages(str1)
{
var str=document.getElementById("emailsend").value;
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint4").innerHTML="";
return;
}
var params = "name="+str1+"&email="+str;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint4").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.open("POST","EmailTheImages",true);
xmlhttp.send(params);
}
| 54c4984d78bba669f7b1f65811c5cb651ff39b6c | [
"JavaScript",
"Java",
"Markdown",
"SQL"
] | 20 | Java | SouravG/online-message-passing-using-visual-cryptography-and-DES | 8763c56aa2bcbfec3ce3ec515f8c6cc5f225ad49 | d1564c427ae96b89d8f0a2401d555802b9a401a4 |
refs/heads/master | <file_sep>/**
* Created by penghaozhong on 15/12/29.
*/
var diqu=new Array();
var yiyuan=new Array();
diqu[0]='0';
diqu[diqu.length]='c38077';
diqu[diqu.length]='c93468';
diqu[diqu.length]='c43942';
yiyuan[yiyuan.length]=new Array('cf13a0b96-0238-4f6c-94c8-5edbd751e29f','c38077');
yiyuan[yiyuan.length]=new Array('ce703db2c-8641-4326-8edd-cbb70b592726','c38077');
yiyuan[yiyuan.length]=new Array('c7406ba50-c6de-4541-bbaa-29473747603a','c38077');
yiyuan[yiyuan.length]=new Array('c14ac6b70-86a5-472c-a72d-898c272e242d','c38077');
yiyuan[yiyuan.length]=new Array('c38811e4b-1375-4667-a720-d8bafac9940e','c38077');
yiyuan[yiyuan.length]=new Array('c6dd681a6-fac2-4cbf-a5db-5fc006a87333','c38077');
yiyuan[yiyuan.length]=new Array('cb5d6c9b2-e6bf-403c-8c3f-0cf15b81a26e','c38077');
yiyuan[yiyuan.length]=new Array('cefdaad1b-2e81-462f-ae9a-eb5ae93db9de','c38077');
yiyuan[yiyuan.length]=new Array('c9a5bad1f-f8dd-46ae-a33b-c810e57bacb1','c38077');
yiyuan[yiyuan.length]=new Array('c38281553-804e-4390-8022-a77a2913371f','c38077');
yiyuan[yiyuan.length]=new Array('c1bc2600b-9547-4690-a598-a66ac484dd5c','c38077');
yiyuan[yiyuan.length]=new Array('c4e78549a-807c-4978-a859-02278cd035e7','c38077');
yiyuan[yiyuan.length]=new Array('c1fbe8842-a6d5-4733-8171-17899cebd6b7','c38077');
yiyuan[yiyuan.length]=new Array('c8b870a68-1ee4-458d-a33f-9320cd419bed','c38077');
yiyuan[yiyuan.length]=new Array('c8a41f671-74f3-4c30-8767-de5ff77a7e92','c38077');
var diqu1=new Array();
var yiyuan1=new Array();
diqu1[0]='0';
diqu1[diqu1.length]='c77071';
diqu1[diqu1.length]='c67512';
diqu1[diqu1.length]='c92091';
diqu1[diqu1.length]='c69558';
diqu1[diqu1.length]='c35420';
diqu1[diqu1.length]='c21115';
<!--口腔科(12)-->
<!--影像医学与核医学-->
/*yiyuan1[yiyuan1.length]=new Array('cb05a9646-7640-492b-921a-47e47e7fc460','');*/
yiyuan1[yiyuan1.length]=new Array('cb4eaa217-a2ba-41dc-ba4b-c6e5f55d2718','c10582');
yiyuan1[yiyuan1.length]=new Array('c6235d3f6-f302-480a-b73e-c1305d20b217','c65191');
yiyuan1[yiyuan1.length]=new Array('cedc691a4-3c47-4f37-ae09-e812a0bb3389','c65191');
yiyuan1[yiyuan1.length]=new Array('cc6f6e683-fc48-435b-a90a-c1aeabfa9bcc','c77071');
yiyuan1[yiyuan1.length]=new Array('c5f5e65ab-398e-45b9-9573-5667ff2ab347','c17772');
yiyuan1[yiyuan1.length]=new Array('cb0a814db-6767-41a5-ba96-d39a279c3d43','c10582');
yiyuan1[yiyuan1.length]=new Array('cad5628a0-76bc-45bf-b79e-67a5b88293bc','c65191');
yiyuan1[yiyuan1.length]=new Array('c0ab3934c-997c-4373-9a28-2002d316ce49','c65191');
yiyuan1[yiyuan1.length]=new Array('c406761c4-3c32-4750-8a68-b4ff3c246e1f','c21115');
yiyuan1[yiyuan1.length]=new Array('cb43d17d7-c459-46c6-87fe-7e7479c8d583','c65191');
yiyuan1[yiyuan1.length]=new Array('c58d9f8e0-f2b1-452f-aa1d-3e99e5b72fd9','c77071');
yiyuan1[yiyuan1.length]=new Array('c5eba9ec5-fe35-4eba-8482-f3c2e187cb03','c21115');
yiyuan1[yiyuan1.length]=new Array('cca1a9f9a-535d-4a93-be25-b34a53fe14f8','c77071');
yiyuan1[yiyuan1.length]=new Array('c1ecf4dbe-4703-4ca1-9474-7be0c4554baf','c21115');
yiyuan1[yiyuan1.length]=new Array('caad92c64-2dc1-4873-9f8d-7af9274f5e47','c56303');
yiyuan1[yiyuan1.length]=new Array('c4ce232b8-7235-4cb5-801f-82f55ec303a4','c65191');
yiyuan1[yiyuan1.length]=new Array('c7e94ad2e-fd5b-4c91-ba57-bf7bff099c65','c17772');
yiyuan1[yiyuan1.length]=new Array('c1971e5f2-d54d-42f6-a249-96efdb9f37b6','c67512');
yiyuan1[yiyuan1.length]=new Array('cac36ff4b-7b01-42c2-9c7d-78b77c4862cd','c10582');
yiyuan1[yiyuan1.length]=new Array('c6c141ae8-6fb5-4da0-b31e-66b2b2d2d82e','c35420');
yiyuan1[yiyuan1.length]=new Array('ccac0931c-f3e3-4390-a5cf-62656e065038','c67512');
yiyuan1[yiyuan1.length]=new Array('ca96d5113-efd7-4401-9574-6152c31347a5','c10582');
yiyuan1[yiyuan1.length]=new Array('c596a397d-d598-4237-9ed5-140cd8d624cc','c56303');
yiyuan1[yiyuan1.length]=new Array('c80dc35f0-deb9-44df-9f06-e649d15f854d','c77071');
yiyuan1[yiyuan1.length]=new Array('cea110805-2ece-4da7-985d-4dc60a519d54','c21115');
yiyuan1[yiyuan1.length]=new Array('c3e61627a-6b3c-47b9-bfad-95f8f189941b','c77071');
yiyuan1[yiyuan1.length]=new Array('cbb73437e-499e-48a3-8f02-0753f40437e2','c10582');
yiyuan1[yiyuan1.length]=new Array('c916a9a75-8ffd-4ff3-bba8-833d89f16085','c21115');
yiyuan1[yiyuan1.length]=new Array('c0c8ea831-8c6b-496e-8b87-85efd9ba8d24','c77071');
yiyuan1[yiyuan1.length]=new Array('cd0942bb4-2ab4-4e8a-942b-b6a4a464a4da','c10582');
yiyuan1[yiyuan1.length]=new Array('cf19e3d3b-f5f2-4d96-b14e-5662efea6d5e','c21115');
yiyuan1[yiyuan1.length]=new Array('c83fff522-11f0-45d3-9cd1-aea5ce184309','c77071');
yiyuan1[yiyuan1.length]=new Array('ccdd7052f-ec3a-4df5-845c-5655bf8044ec','c67512');
yiyuan1[yiyuan1.length]=new Array('c5ee822f4-c24f-4bbd-846f-417ca8888fb1','c67512');
yiyuan1[yiyuan1.length]=new Array('ca524d110-eeb3-4534-a573-13a0a417d7db','c17772');
yiyuan1[yiyuan1.length]=new Array('c23502116-ef68-4a21-9580-3d6eccdea16c','c77071');
yiyuan1[yiyuan1.length]=new Array('cf9f954e3-f56f-4a13-b598-d8958dcdabcc','c69558');
yiyuan1[yiyuan1.length]=new Array('c9c07fc0d-d4a9-429a-bda8-409666c1477d','c10582');
yiyuan1[yiyuan1.length]=new Array('cfec49cc9-9771-4297-b9f8-5f5c3aa2f10f','c67512');
yiyuan1[yiyuan1.length]=new Array('c633e4dd8-5cd2-4087-af8c-3519cb93b095','c67512');
yiyuan1[yiyuan1.length]=new Array('cb348cb9e-b25f-4b79-b556-a8838a831d9c','c17772');
yiyuan1[yiyuan1.length]=new Array('c373a2bfb-f721-44a7-a23d-092c850e28c0','c69558');
yiyuan1[yiyuan1.length]=new Array('c50fe2625-9844-4f66-818f-1de7834dbad0','c21115');
yiyuan1[yiyuan1.length]=new Array('c64094c96-92da-47da-8b93-691abe22d44c','c67512');
/*中西医结研究所(1)*/
<file_sep># jiahaow
##jquery mobile 第一个项目。
| 90947d33ccfc69be67f20f62a224186d86d1c669 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | penghaozhong/jiahaow | a94a2d5471a3430d074f7f7b5504d304f39872c5 | 7db2600a7e892b7c0a298eedd0e265c4085d0fb9 |
refs/heads/master | <file_sep>Check out the final product [Here](anggaardinatacovid19.netlify.app)
<file_sep>import React from "react";
import styled from "styled-components";
export default function Addition() {
return <Container></Container>;
}
const Container = styled.div`
width: 25%;
height: 100%;
background: lightblue;
@media (max-width: 786px) {
width: 100%;
height: 30%;
}
`;
<file_sep>import React from "react";
import styled from "styled-components/macro";
import Addition from "./Addition";
import Body from "./Body";
import Menu from "./Menu";
function CovidTracker() {
return (
<Container>
<Menu />
<Body />
<Addition />
</Container>
);
}
export default CovidTracker;
const Container = styled.div`
width: 80%;
height: 90%;
display: flex;
@media (max-width: 768px) {
flex-direction: column;
width: 100%;
height: 100%;
}
`;
<file_sep>import React, { useState, useEffect, createContext } from "react";
export const GlobalContext = createContext();
export const ContextProvider = (props) => {
const [countryList, setCountryList] = useState([]); // This is the global Data of Covid 19
const [country, setCountry] = useState("Indonesia"); // query for country that inputed to the input box
const [fullData, setFullData] = useState({
confirmed: "",
active: "",
recovered: "",
deaths: "",
});
const today = new Date();
const fullDate =
today.getFullYear() +
"-" +
(today.getMonth() + 1) +
"-" +
(today.getDate() - 1);
useEffect(() => {
(async function () {
await fetch(`https://api.covid19tracking.narrativa.com/api/${fullDate}`)
.then((res) => {
if (res.ok) {
return res.json();
} else throw Error("Error Brow");
})
.then((data) => {
// setting the Total cases Globally
console.log(data.total);
const TotalCases = data.total;
setFullData((prev) => ({
...prev,
confirmed: TotalCases.today_confirmed,
recovered: TotalCases.today_recovered,
deaths: TotalCases.today_deaths,
active:
TotalCases.today_confirmed -
TotalCases.today_recovered -
TotalCases.today_deaths,
}));
const GlobalData = Object.entries(
Object.entries(Object.entries(data.dates)[0][1])[0][1]
);
setCountryList(GlobalData);
})
.catch((err) => console.log(err));
})();
}, [country, fullDate]);
return (
<GlobalContext.Provider value={[countryList, setCountry, fullData]}>
{props.children}
</GlobalContext.Provider>
);
};
<file_sep>import React, { useContext } from "react";
import { useState } from "react";
import styled from "styled-components/macro";
import { GlobalContext } from "../GlobalContext";
import Diagram from "./Diagram";
import MapVisual from "./MapVisual";
export default function Body() {
const setCountry = useContext(GlobalContext)[1];
const cases = useContext(GlobalContext)[2];
const countries = useContext(GlobalContext)[0];
const [query, setQuery] = useState("");
console.log(useContext(GlobalContext));
const onChange = (e) => {
setQuery(e.target.value);
};
const onSubmit = (e) => {
e.preventDefault();
setCountry(query);
setQuery("");
};
return (
<Container>
<header>
<h2 style={{ color: "rgb(98, 54, 255)" }}>Covid-19 </h2>
<h2 style={{ marginLeft: "10px", fontWeight: 300 }}>Global Trend</h2>
</header>
<div className="cases">
<div className="aggregated">
<header>Aggregated</header>
<main>{cases.confirmed}</main>
<p>23%</p>
</div>
<div className="active">
<header>Active</header>
<main>{cases.active}</main>
<p>23%</p>
</div>
<div className="recovered">
<header>Recovered</header>
<main>{cases.recovered}</main>
<p>23%</p>
</div>
<div className="death">
<header>Death</header>
<main>{cases.deaths}</main>
<p>23%</p>
</div>
</div>
<div className="statistic">
<div className="city">
<div className="inputLogo">
<form action="" onSubmit={onSubmit}>
<input
type="text"
placeholder="Search Country"
onChange={onChange}
value={query}
/>
</form>
</div>
<div className="listCity">
<ul>
{countries.map((data, index) => (
<div className="Lists" key={index}>
<p>{data[1].today_confirmed}</p>
<li>{data[1].name}</li>
</div>
))}
</ul>
</div>
</div>
<div className="visualisasi">
<MapVisual />
<Diagram />
</div>
</div>
</Container>
);
}
const Container = styled.div`
width: 65%;
height: 100%;
padding-left: 2vw;
padding-right: 2vw;
background: rgb(243, 252, 255);
@media (max-width: 786px) {
width: 100%;
height: 60%;
}
header {
width: 100%;
height: 10%;
display: flex;
justify-content: flex-start;
align-items: center;
}
.cases {
width: 100%;
height: 18%;
display: flex;
justify-content: space-between;
align-items: center;
.active,
.aggregated,
.recovered,
.death {
display: flex;
height: 100%;
width: 23%;
background: white;
border-radius: 1.5vw;
flex-direction: column;
justify-content: center;
align-items: center;
transition: 1s ease-in;
header {
width: 100%;
height: 20%;
display: flex;
justify-content: center;
align-items: center;
font-size: 2vw;
}
main {
font-size: 1.5vw;
width: 100%;
height: 30%;
display: flex;
justify-content: center;
align-items: center;
margin-top: 0.7vw;
}
p {
font-size: 1vw;
}
}
.aggregated main {
color: rgb(253, 102, 132);
}
.active main {
color: rgb(255, 155, 88);
}
.recovered main {
color: rgb(157, 227, 82);
}
.death main {
color: rgb(149, 117, 255);
}
@media (max-width: 768px) {
.active,
.aggregated,
.recovered,
.death {
padding: 0.5rem;
header {
width: 100%;
height: 30%;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.1rem;
}
main {
font-size: 0.7rem;
width: 100%;
height: 30%;
display: flex;
justify-content: center;
align-items: center;
margin-top: 1vw;
}
p {
font-size: 2vw;
}
}
}
}
.statistic {
height: 65%;
width: 100%;
background: white;
display: flex;
border-radius: 1vw;
padding: 1.3vw;
.city {
display: flex;
flex-direction: column;
width: 45%;
height: 100%;
.inputLogo {
display: flex;
align-items: center;
border-radius: 50px;
width: 95%;
height: 10%;
background: rgb(0, 0, 0, 0.1);
padding-left: 0.5rem;
form {
height: 100%;
}
input {
border: none;
background: none;
outline: none;
width: 100%;
padding-left: 0.5vw;
height: 100%;
}
::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f002";
font-size: 1rem;
}
}
.listCity {
overflow-y: scroll;
padding: 0 1vw 0 1vw;
height: 80%;
margin-top: 10%;
ul {
font-size: 1vw;
height: 100%;
.Lists {
display: flex;
text-align: left;
letter-spacing: 0.8px;
margin-top: 1vh;
p {
min-width: 4vw;
}
li {
list-style: none;
padding-left: 1vw;
color: rgb(0, 0, 0, 0.5);
}
}
}
}
@media (max-width: 768px) {
.inputLogo {
padding-left: 5px;
::before {
font-size: 0.8rem;
}
}
form {
display: flex;
justify-content: center;
align-items: center;
}
input {
width: 100%;
font-size: 0.6rem;
}
}
.listCity {
ul {
font-size: 0.7rem;
letter-spacing: 0.3px;
.Lists {
p {
min-width: 2.7rem;
}
}
}
}
}
}
.visualisasi {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
padding-left: 10px;
@media (max-width: 768px) {
flex-direction: row;
.diagram {
display: none;
}
}
}
`;
| 23a65ed0233200e609c441c1e7fd0b9f2a4d23ec | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Deorigami/Covid19 | 64cb6da86d277dc4dd890361cafe380ba0574e60 | 2dd816027240733ae446fcfab5079d84419c3c65 |
refs/heads/master | <repo_name>pgg-dev/ABILITY-PUBLIC<file_sep>/front/components/presentational/molecules/HireComDescription.js
import React from 'react';
import {Container, Col, Row} from 'react-bootstrap';
import Highlight from 'react-highlight';
/**
*
* @auth 곽호원
* @summary 회사 소개하는 컴포넌트
*
*/
const comTitlecss ={
marginLeft : "1%",
marginTop : "3%",
fontSize : "1.3em"
}
const comExDescriptioncss = {
marginLeft : "1%",
fontSize : "1em"
}
const ComDescription = (props) => {
return (
<Container>
<Row style={comTitlecss}>
기업소개
</Row>
<hr />
<Row style={comExDescriptioncss}>
<Highlight innerHTML={true}>
{props.comDescription}
</Highlight>
</Row>
</Container>
);
};
export default ComDescription;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/utils/CustomerExcelWriter.java
package com.ability.utils;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import com.ability.dto.custom.UserDetail;
public class CustomerExcelWriter {
public void xlsWriter(List<UserDetail> list,HttpServletResponse response) throws Exception {
// 워크북 생성
HSSFWorkbook workbook = new HSSFWorkbook();
// 워크시트 생성
HSSFSheet sheet = workbook.createSheet();
// 행 생성
HSSFRow row = sheet.createRow(0);
// 쎌 생성
HSSFCell cell;
CellStyle headStyle = workbook.createCellStyle();
// 가는 경계선을 가집니다.
// 가는 경계선을 가집니다.
headStyle.setBorderTop(BorderStyle.THIN);
headStyle.setBorderBottom(BorderStyle.THIN);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);
// 배경색은 노란색입니다.
headStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 데이터는 가운데 정렬합니다.
headStyle.setAlignment(HorizontalAlignment.CENTER);
// 데이터용 경계 스타일 테두리만 지정
CellStyle bodyStyle = workbook.createCellStyle();
bodyStyle.setBorderTop(BorderStyle.THIN);
bodyStyle.setBorderBottom(BorderStyle.THIN);
bodyStyle.setBorderLeft(BorderStyle.THIN);
bodyStyle.setBorderRight(BorderStyle.THIN);
// 헤더 정보 구성
cell = row.createCell(0);
cell.setCellValue("유저아이디");
cell = row.createCell(1);
cell.setCellValue("닉네임");
cell = row.createCell(2);
cell.setCellValue("이름");
cell = row.createCell(3);
cell.setCellValue("이메일");
cell = row.createCell(4);
cell.setCellValue("능력치");
cell = row.createCell(5);
cell.setCellValue("가입일");
cell = row.createCell(6);
cell.setCellValue("권한");
cell = row.createCell(7);
cell.setCellValue("유저이미지");
// 리스트의 size 만큼 row를 생성
UserDetail user;
for(int rowIdx=0; rowIdx < list.size(); rowIdx++) {
user = list.get(rowIdx);
// 행 생성
row = sheet.createRow(rowIdx+1);
cell = row.createCell(0);
cell.setCellValue(user.getUserid());
cell = row.createCell(1);
cell.setCellValue(user.getNick_name());
cell = row.createCell(2);
cell.setCellValue(user.getName());
cell = row.createCell(3);
cell.setCellValue(user.getEmail());
cell = row.createCell(4);
cell.setCellValue(user.getReputation());
cell = row.createCell(5);
cell.setCellValue(user.getDate_created());
cell = row.createCell(6);
cell.setCellValue(user.getRole_name());
cell = row.createCell(7);
cell.setCellValue(user.getUser_image());
}
response.setHeader("Content-Encoding", "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=Users.xls");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
OutputStream fileOut = response.getOutputStream();
workbook.write(fileOut);
workbook.close();
fileOut.close();
}
}<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/UserListPaging.java
package com.ability.dto.custom;
import java.util.List;
/**
* @author 강기훈
* @summary 관리자페이지, 유저리스트 + 페이징 정보
*/
public class UserListPaging {
private List<UserDetail> userList;
private int totalPage;
private int currentPage;
private int startPageBlock;
private int endPageBlock;
private int pageSize;
private int totalListCount;
public List<UserDetail> getUserList() {
return userList;
}
public void setUserList(List<UserDetail> userList) {
this.userList = userList;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getStartPageBlock() {
return startPageBlock;
}
public void setStartPageBlock(int startPageBlock) {
this.startPageBlock = startPageBlock;
}
public int getEndPageBlock() {
return endPageBlock;
}
public void setEndPageBlock(int endPageBlock) {
this.endPageBlock = endPageBlock;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalListCount() {
return totalListCount;
}
public void setTotalListCount(int totalListCount) {
this.totalListCount = totalListCount;
}
}
<file_sep>/front/components/presentational/molecules/BoardListBox.js
import React, { Component } from 'react';
import {BoardSimpleList,BoardSimpleList2,BoardSimpleList3,BoardSimpleList4 } from './BoardSimpleList';
import Link from 'next/link';
import axios from 'axios';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
import { faLaptopCode } from '@fortawesome/free-solid-svg-icons';
import { faCrow } from '@fortawesome/free-solid-svg-icons';
import { faIdBadge } from '@fortawesome/free-solid-svg-icons';
/**
* @author 신선하
* @summary 보드리스트 박스
* @see 정규현 리펙토링
*
**/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const endpoint = backUrl+"/test/getpost";
const endpoint2 = backUrl+"/test/getjobpost";
const css2 = {
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
WebkitLineClamp: '1', /* 라인수 */
WebkitBoxOrient: 'vertical',
wordWrap:'break-word',
marginBottom:"10px"
}
const userWrite ={
gridArea: "2 / 2 / 3 / 4",
}
const userWriteTitle = {
fontSize: "18px",
fontWeight: "600",
marginBottom: "10px",
display: "inline-block",
color:"#636e72"
}
const userWritelist = {
margin: "0",
lineHeight: "100%",
fontSize : "12px",
}
const board_css = {
borderBottom:"1px solid #eaeaea",
marginBottom:"15px",
display:"flex",
justifyContent:"space-between"
}
const more_css ={
textAlign:"right"
}
const nextpage_css = {
marginTop:"15px",
fontSize:"12px"
}
const linkcss={
color:"#0984e3"
}
class BoardListBox extends Component {
constructor(props){
super(props);
this.props = props
this.state={
categoryid: this.props.categoryid,
postArray:[]
}
}
async componentDidMount(){
if(this.state.categoryid==4){
await axios.get(endpoint2).then(response=>{
this.setState({
postArray:response.data
})
})
}else{
await axios.get(endpoint,{
params:{
categoryid:this.state.categoryid
}
}).then(response =>{
this.setState({
postArray:response.data
})
})
}
}
render(){
function textLengthOverCut(txt, len, lastTxt) {
if (txt.length > len) {
txt = txt.substr(0, len) + lastTxt;
}
return txt;
}
const UserList= this.state.postArray.map((user,index)=>{
if(this.state.categoryid==1){
return <BoardSimpleList key={index} id={user.id} userid={user.userid} title={textLengthOverCut(user.title, '20', '...')}
date_created={user.date_created} userimage={user.user_image} tags={user.tags} reputation={user.reputation} nickname={user.nick_name} css2={css2} ></BoardSimpleList>
}else if(this.state.categoryid==2){
return <BoardSimpleList3 key={index} id={user.id} userid={user.userid} title={textLengthOverCut(user.title, '20', '...')}
date_created={user.date_created} userimage={user.user_image} tags={user.tags} reputation={user.reputation} nickname={user.nick_name} css2={css2} ></BoardSimpleList3>
}else if(this.state.categoryid==7){
return <BoardSimpleList2 key={index} id={user.id} userid={user.userid} title={textLengthOverCut(user.title, '20', '...')}
date_created={user.date_created} userimage={user.user_image} tags={user.tags} reputation={user.reputation} nickname={user.nick_name} css2={css2} ></BoardSimpleList2>
}else{
return <BoardSimpleList4 key={index} id={user.id} userid={user.userid} title={textLengthOverCut(user.title, '20', '...')}
date_created={user.date_created} userimage={user.user_image} tags={user.tags} reputation={user.reputation} nickname={user.nick_name} css2={css2} ></BoardSimpleList4>
}
});
function moreList(id){
if(id ==1){
return <Link href="/question/board"><a style={linkcss}>더보기</a></Link>
}else if(id ==7){
return <Link href="/community/board"><a style={linkcss}>더보기</a></Link>
}else if(id==2){
return <Link href="/project/board"><a style={linkcss}>더보기</a></Link>
}else{
return <Link href="/job/board"><a style={linkcss}>더보기</a></Link>
}
}
const nextpage = moreList(this.state.categoryid);
function icon(id){
if( id == "1"){
return <FontAwesomeIcon icon={faQuestionCircle} style={{width:"17px", marginRight:"7px"}}/>
}else if(id == "2"){
return <FontAwesomeIcon icon={faLaptopCode} style={{width:"17px", marginRight:"7px"}}/>
}else if(id == "7"){
return <FontAwesomeIcon icon={faCrow} style={{width:"17px", marginRight:"7px"}}/>
}
else{
return <FontAwesomeIcon icon={faIdBadge} style={{width:"17px", marginRight:"7px"}}/>
}
}
const faIcon = icon(this.state.categoryid);
return (
<>
<div style={userWrite}>
<div style={board_css}>
<span style={userWriteTitle}>
{faIcon}
{this.props.boardtitle}
</span>
<div style={nextpage_css}>{nextpage}</div>
</div>
<div style={userWritelist}>
{UserList}
</div>
<div style={more_css}>
</div>
</div>
</>
);
}
}
export default BoardListBox;
<file_sep>/front/components/presentational/molecules/ChattingProfile.js
import React from 'react';
import Image from 'react-bootstrap/Image';
/**
*
* @author 우세림
* @summary 채팅창 텍스트 박스
*/
const css = {
display: "grid",
gridGap: "3px",
gridTemplateColumns: "70px 80% 10px",
gridTemplateRows: "30px 0px",
marginBottom: "10px"
}
const css2 = {
width: "30px",
height: "30px",
marginLeft: "40px"
}
const css3 = {
fontSize: "11px",
textAlign: "right",
gridArea: "3/1/4/2",
textOverflow: "ellipsis",
overflow: "hidden"
}
const css4 = {
fontSize: "14px",
backgroundColor: "#f7f7f7",
gridArea: "1/2/4/3",
padding: "16px",
borderRadius: "7px 7px 7px 7px",
marginLeft: "10px"
}
const css5 = {
fontSize: "12px",
gridArea: "3/3/4/4",
marginLeft: "5px",
marginBottom: "0px",
marginTop: "auto",
color: "#878787"
}
export const ChattingProfile=(props)=>
<div style={css}>
<Image style={css2} src="&ssl=1" thumbnail/>
<div style={css3}>{props.id}</div>
<div style={css4}>{props.comments}</div>
<div style={css5}>{props.time}</div>
</div>
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/UserController.java
package com.ability.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ability.dto.custom.BoardListPaging;
import com.ability.dto.custom.DeveloperBoardListPaging;
import com.ability.dto.custom.DeveloperCompanyList;
import com.ability.dto.custom.DeveloperDetailList;
import com.ability.dto.custom.DeveloperPost;
import com.ability.dto.custom.DeveloperPostChart;
import com.ability.dto.custom.DeveloperPostCount;
import com.ability.dto.custom.HashtagComment;
import com.ability.dto.custom.HashtagReply;
import com.ability.dto.custom.HireBoardList;
import com.ability.dto.custom.JobBoardListPaging;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.ProjectBoardListPaging;
import com.ability.service.DeveloperService;
import com.ability.service.HashtagNicknameService;
import com.ability.utils.Pagination;
@RestController
public class UserController {
@Autowired
DeveloperService developerService;
@Autowired
HashtagNicknameService hashtagNicknameService;
@Autowired
Pagination pagination;
// 내 정보
public DeveloperDetailList listSelect(@RequestParam(value = "userid") String userid) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
DeveloperDetailList s =developerService.listSelect(view);
return developerService.listSelect(view);
}
// 내가 쓴 질문
public List<PostBoardList> questionList(@RequestParam(value = "userid") String userid,
@RequestParam(value = "start") String start, @RequestParam(value = "end") String end) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("start", start);
view.put("end", end);
return developerService.getQuestionList(view);
}
// 내가 쓴 답글
public List<DeveloperPost> answerList(@RequestParam(value = "userid") String userid,
@RequestParam(value = "start") String start, @RequestParam(value = "end") String end) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("start", start);
view.put("end", end);
return developerService.getAnswerList(view);
}
// 내가 쓴 게시물 수
public DeveloperPostCount postCount(@RequestParam(value = "userid") String userid) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
return developerService.getPostCount(view);
}
// 정보 수정
public int developerUpdate(@RequestParam(value = "userid") String userid, @RequestParam(value = "tel") String tel,
@RequestParam(value = "user_info") String user_info, @RequestParam(value = "area") String area,
@RequestParam(value = "tags") String tags) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("tel", tel);
view.put("user_info", user_info);
view.put("area", area);
view.put("tags", tags);
DeveloperDetailList detailList = new DeveloperDetailList();
int temp = developerService.getdeveloperSelect(view);
if (temp > 0) {
int result = developerService.getdeveloperUpdate(view);
if (result > 0) {
return result;
} else {
return -1;
}
} else {
return -1;
}
}
public List<HashtagComment> getComment(@RequestParam(value = "seq") String seq) {
Map<String, String> lists = new HashMap<String, String>();
lists.put("seq", seq);
List<HashtagComment> list = hashtagNicknameService.getComment(lists);
return list;
}
public List<HashtagReply> getReply(@RequestParam(value = "seq") String seq) {
Map<String, String> lists = new HashMap<String, String>();
lists.put("seq", seq);
List<HashtagReply> list = hashtagNicknameService.getReply(lists);
return list;
}
public List<DeveloperDetailList> searchDeveloper(@RequestParam(value = "nick_name") String nick_name) {
return developerService.searchDeveloper(nick_name);
}
public List<DeveloperDetailList> searchDeveloperByTags(@RequestParam(value = "tags") String tags) {
return developerService.searchDeveloperByTags(tags);
}
public int getPasswordOk(@RequestParam(value = "userid") String userid,
@RequestParam(value = "password") String password){
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("password", <PASSWORD>);
return developerService.getPasswordOk(view);
}
public int getPasswordChange(@RequestParam(value = "userid") String userid,
@RequestParam(value = "password") String password,
@RequestParam(value = "repassword") String repassword){
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("password", <PASSWORD>);
view.put("repassword", repassword);
return developerService.getPasswordChange(view);
}
public int getImageChange(@RequestParam(value = "userid") String userid,
@RequestParam(value = "files") MultipartFile files,
HttpServletRequest request){
return developerService.getImageChange(userid,files,request);
}
public List<DeveloperPostChart> getPostChart(@RequestParam(value = "userid") String userid){
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
return developerService.getPostChart(view);
}
public DeveloperBoardListPaging getuserList(@PathVariable("view")String view,
@RequestParam(value="currentpage",required=false,defaultValue="1")String currentPage,
@RequestParam(value = "word", required = false, defaultValue = "1") String word) {
DeveloperBoardListPaging developerBoardListPaging = new DeveloperBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalListCount = 0;
if (word.equals("1")) {
totalListCount = developerService.getuserTotalCount();
} else {
Map<String, String> list = new HashMap<String, String>();
list.put("word", word);
totalListCount = developerService.getuserSearchTotalCount(list);
}
int totalcount = developerService.getuserTotalCount();
int pageSize = (pagination.getPageSize())+5;
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalcount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int endpage = pagination.printEnd(pagination.getCurPage(), pageSize);
if(endpage > totalcount){
endpage=totalcount;
}
viewmap.put("view", view);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if (word.equals("1")) {
developerBoardListPaging.setPostBoardList(developerService.getMemberPostList(viewmap));
} else {
viewmap.put("word", word);
developerBoardListPaging.setPostBoardList(developerService.SeachList(viewmap));
}
developerBoardListPaging.setPostBoardList(developerService.getMemberPostList(viewmap));
developerBoardListPaging.setCurrentPage(pagination.getCurPage());
developerBoardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
developerBoardListPaging.setPageSize(pageSize);
developerBoardListPaging.setStartPageBlock(startPageBlock);
developerBoardListPaging.setTotalListCount(totalcount);
developerBoardListPaging.setTotalPage(totalPage);
return developerBoardListPaging;
}
public DeveloperBoardListPaging SeachList(@RequestParam(value="dropdown")String dropdown,
@RequestParam(value="content", required = false, defaultValue = "1")String content,
@RequestParam(value="currentpage",required=false,defaultValue="1")String currentPage
){
DeveloperBoardListPaging developerBoardListPaging = new DeveloperBoardListPaging();
Map<String, String> list = new HashMap<String, String>();
Map<String,String> viewmap = new HashMap<String,String>();
int totalListCount = 0;
if (dropdown.equalsIgnoreCase("id")) {
list.put("content", content);
list.put("dropdown", "1");
totalListCount = developerService.getuserSearchTotalCount(list);
} else if (dropdown.equalsIgnoreCase("Tag")) {
list.put("content", content);
list.put("dropdown", "2");
totalListCount = developerService.getuserSearchTotalCount(list);
} else {
totalListCount = developerService.getuserTotalCount();
}
int totalcount = developerService.getuserTotalCount();
int pageSize = (pagination.getPageSize())+5;
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalcount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int endpage = pagination.printEnd(pagination.getCurPage(), pageSize);
if(endpage > totalcount){
endpage=totalcount;
}
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if (dropdown.equalsIgnoreCase("Id")) {
viewmap.put("content", content);
viewmap.put("dropdown", "1");
developerBoardListPaging.setPostBoardList(developerService.SeachList(viewmap));
} else if (dropdown.equalsIgnoreCase("Tag")) {
viewmap.put("content", content);
viewmap.put("dropdown", "2");
developerBoardListPaging.setPostBoardList(developerService.SeachList(viewmap));
} else {
developerBoardListPaging.setPostBoardList(developerService.getMemberPostList(viewmap));
}
developerBoardListPaging.setPostBoardList(developerService.SeachList(viewmap));
developerBoardListPaging.setCurrentPage(pagination.getCurPage());
developerBoardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
developerBoardListPaging.setPageSize(pageSize);
developerBoardListPaging.setStartPageBlock(startPageBlock);
developerBoardListPaging.setTotalListCount(totalcount);
developerBoardListPaging.setTotalPage(totalPage);
return developerBoardListPaging;
}
//내가 쓴 게시글 추가 /////
public BoardListPaging getboardList(@RequestParam(value = "orderby") String orderby,
@RequestParam(value = "currentpage", required = false, defaultValue = "1") String currentPage,
@RequestParam(value = "word", required = false, defaultValue = "1") String word,
@RequestParam(value = "categoryid") String categoryid,
@RequestParam(value = "userid") String userid
) {
BoardListPaging boardListPaging = new BoardListPaging();
Map<String, String> viewmap = new HashMap<String, String>();
int totalListCount = 0;
if (word.equals("1")) {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid",categoryid);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardContentCount(view);
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid", categoryid);
view.put("word", word);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardSearchContentCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", categoryid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
viewmap.put("userid", userid);
if (word.equals("1")) {
boardListPaging.setPostBoardList(developerService.getPostList(viewmap));
} else {
viewmap.put("word", word);
boardListPaging.setPostBoardList(developerService.getSearchResult(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalListCount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
public ProjectBoardListPaging getProjectBoardList(
@RequestParam(value="orderby") String orderby,
@RequestParam(value="currentpage", required=false, defaultValue="1") String currentPage,
@RequestParam(value="word", required=false, defaultValue="1") String word,
@RequestParam(value ="categoryid") String categoryid,
@RequestParam(value="userid") String userid)
{
ProjectBoardListPaging projectBoardListPaging = new ProjectBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalListCount = 0;
if (word.equals("1")) {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid",categoryid);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardContentCount(view);
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid", categoryid);
view.put("word", word);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardSearchContentCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", categoryid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
viewmap.put("userid", userid);
if(word.equals("1")) {
projectBoardListPaging.setProjectBoardList(developerService.getProjectList(viewmap));
}else {
viewmap.put("word", word);
projectBoardListPaging.setProjectBoardList(developerService.getProjectSearchResult(viewmap));
}
projectBoardListPaging.setCurrentPage(pagination.getCurPage());
projectBoardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
projectBoardListPaging.setPageSize(pageSize);
projectBoardListPaging.setStartPageBlock(startPageBlock);
projectBoardListPaging.setTotalListCount(totalListCount);
projectBoardListPaging.setTotalPage(totalPage);
return projectBoardListPaging;
}
public BoardListPaging getboardMarkList(@RequestParam(value = "orderby") String orderby,
@RequestParam(value = "currentpage", required = false, defaultValue = "1") String currentPage,
@RequestParam(value = "word", required = false, defaultValue = "1") String word,
@RequestParam(value = "categoryid") String categoryid,
@RequestParam(value = "userid") String userid
) {
BoardListPaging boardListPaging = new BoardListPaging();
Map<String, String> viewmap = new HashMap<String, String>();
int totalListCount = 0;
if (word.equals("1")) {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid",categoryid);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardContentCount(view);
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid", categoryid);
view.put("word", word);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardSearchContentCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", categoryid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
viewmap.put("userid", userid);
if (word.equals("1")) {
boardListPaging.setPostBoardList(developerService.getPostListMark(viewmap));
} else {
viewmap.put("word", word);
boardListPaging.setPostBoardList(developerService.getSearchResultMark(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalListCount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
public ProjectBoardListPaging getProjectMarkList(
@RequestParam(value="orderby") String orderby,
@RequestParam(value="currentpage", required=false, defaultValue="1") String currentPage,
@RequestParam(value="word", required=false, defaultValue="1") String word,
@RequestParam(value ="categoryid") String categoryid,
@RequestParam(value="userid") String userid)
{
ProjectBoardListPaging projectBoardListPaging = new ProjectBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalListCount = 0;
if (word.equals("1")) {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid",categoryid);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardContentCount(view);
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("categoryid", categoryid);
view.put("word", word);
view.put("userid",userid);
totalListCount = developerService.getTotalBoardSearchContentCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", categoryid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
viewmap.put("userid", userid);
if(word.equals("1")) {
projectBoardListPaging.setProjectBoardList(developerService.getProjectMarkList(viewmap));
}else {
viewmap.put("word", word);
projectBoardListPaging.setProjectBoardList(developerService.getProjectSearchMarkResult(viewmap));
}
projectBoardListPaging.setCurrentPage(pagination.getCurPage());
projectBoardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
projectBoardListPaging.setPageSize(pageSize);
projectBoardListPaging.setStartPageBlock(startPageBlock);
projectBoardListPaging.setTotalListCount(totalListCount);
projectBoardListPaging.setTotalPage(totalPage);
return projectBoardListPaging;
}
public JobBoardListPaging getJobBoard(@RequestParam(value="orderby")String orderby,
@RequestParam(value="currentpage",required=false,defaultValue="1")String currentPage,
@RequestParam(value="userid" )String userid,
@RequestParam(value="word",required=false,defaultValue="1") String word,
@RequestParam(value = "categoryid") String categoryid
) {
JobBoardListPaging boardListPaging = new JobBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalcount = 0;
if(word.equals("1")) {
totalcount = developerService.getTotalCount();
}else {
Map<String,String> view = new HashMap<String,String>();
view.put("word", word);
totalcount = developerService.getTotalSearchCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalcount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int endpage = pagination.printEnd(pagination.getCurPage(), pageSize);
if(endpage > totalcount){
endpage=totalcount;
}
viewmap.put("orderby", orderby);
viewmap.put("userid", userid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if(word.equals("1")) {
boardListPaging.setPostBoardList(developerService.getJobBoardList(viewmap));
}else {
viewmap.put("word", word);
boardListPaging.setPostBoardList(developerService.getJobSearchResult(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalcount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
public JobBoardListPaging getJobBoardMark(@RequestParam(value="orderby")String orderby,
@RequestParam(value="currentpage",required=false,defaultValue="1")String currentPage,
@RequestParam(value="userid" )String userid,
@RequestParam(value="word",required=false,defaultValue="1") String word,
@RequestParam(value = "categoryid") String categoryid
) {
JobBoardListPaging boardListPaging = new JobBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalcount = 0;
if(word.equals("1")) {
totalcount = developerService.getTotalCount();
}else {
Map<String,String> view = new HashMap<String,String>();
view.put("word", word);
totalcount = developerService.getTotalSearchCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalcount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int endpage = pagination.printEnd(pagination.getCurPage(), pageSize);
if(endpage > totalcount){
endpage=totalcount;
}
viewmap.put("orderby", orderby);
viewmap.put("userid", userid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if(word.equals("1")) {
boardListPaging.setPostBoardList(developerService.getJobBoardMarkList(viewmap));
}else {
viewmap.put("word", word);
boardListPaging.setPostBoardList(developerService.getJobSearchMarkResult(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalcount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
//기업회원
public List<DeveloperCompanyList> getCompanylistSelect(@RequestParam(value = "userid") String userid) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
return developerService.getCompanylistSelect(view);
}
@RequestMapping(path="/users/company/board", method = RequestMethod.GET)
public List<HireBoardList> getCompanyBoard(@RequestParam(value = "userid") String userid,
@RequestParam(value = "start") String start,
@RequestParam(value = "end") String end) {
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("start", start);
view.put("end", end);
return developerService.getCompanyBoard(view);
}
public int getcompanyProfile(@RequestParam(value = "userid") String userid,
@RequestParam(value = "company_tel") String company_tel,
@RequestParam(value = "company_email") String company_email,
@RequestParam(value = "company_area") String company_area,
@RequestParam(value = "homepage_url") String homepage_url,
@RequestParam(value = "company_info") String company_info,
@RequestParam(value = "xloc") String xloc,
@RequestParam(value = "yloc") String yloc
){
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("company_tel", company_tel);
view.put("company_email", company_email);
view.put("company_area", company_area);
view.put("homepage_url", homepage_url);
view.put("company_info", company_info);
view.put("xloc", xloc);
view.put("yloc", yloc);
return developerService.getcompanyProfile(view);
}
public int companyLoc(@RequestParam(value = "userid") String userid,
@RequestParam(value = "xloc") String xloc,
@RequestParam(value = "yloc") String yloc
){
Map<String, String> view = new HashMap<String, String>();
view.put("userid", userid);
view.put("xloc", xloc);
view.put("yloc", yloc);
return developerService.companyLoc(view);
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/DataData.java
package com.ability.dto.custom;
import java.io.Serializable;
/**
*
* @author 정규현
* @summary 레디스용 디티오
*
*/
public class DataData implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String item;
public DataData() {}
public DataData(String id, String item) {
super();
this.id = id;
this.item = item;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
<file_sep>/front/components/presentational/atoms/ListgroupBootUser.js
import React from 'react';
import ListGroup from 'react-bootstrap/ListGroup'
import Tab from 'react-bootstrap/Tab';
import { Container, Row, Col } from 'react-bootstrap';
import { UserSearchbarComponent } from './SearchbarComponent';
import { SortComponent } from './SortComponent';
/**
* @author 강기훈
*/
const colcss = {
minHeight: "80px",
padding:"0 14px"
}
const left = {
display: "inline"
}
const Search_css = {
marginTop: "40px",
display: "grid",
gridTemplateColumns: "35% 40%",
justifyContent: "space-between"
}
const search_bar ={
display: "flex"
}
const ListgropBootUser = (props) => {
return (
<>
<Container id="contentRow" >
<Tab.Container id="list-group-tabs-example" defaultActiveKey="#link1">
<Row>
<Col style={colcss} md={6}>
<ListGroup id="sortbar">
<ListGroup.Item style={left} action href="#link1" onClick={props.clickEvent}>
{props.list1}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#link2" onClick={props.clickEvent}>
{props.list2}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#link3" onClick={props.clickEvent}>
{props.list3}
</ListGroup.Item>
</ListGroup>
</Col>
<Col md={{span:4,offset :2}} style={{disply:"flex"}}>
<Row id="searchrow">
<div style={search_bar}>
<SortComponent value="닉네임" name="닉네임" value2="태그" name2="태그" />
<UserSearchbarComponent onChange={props.onChange} onClick={props.onClick} content={props.placeholder} inputId={props.inputid}/>
</div>
</Row>
</Col>
</Row>
<Row id="contentRow">
<Col>
{props.children}
</Col>
</Row>
</Tab.Container>
</Container>
</>
)
}
export default ListgropBootUser;
<file_sep>/front/pages/community/write.js
import React, { useState,useEffect,useCallback } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import ProfileImageUserid from '../../components/presentational/molecules/ProfileImageUserid';
import { InputText } from '../../components/presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCrow } from '@fortawesome/free-solid-svg-icons';
import swal from 'sweetalert';
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
/**
* @auth 정규현
* @summary 글쓰기 상세 페이지
*/
const buttoncss = {
textAlign: "right"
};
const cardcss={
margin : "0px",
padding : "0px"
};
const Write = () =>{
const [userid,setUserid] = useState(0);
const [userImage,setIsUserimage] = useState("");
const [nickname, setNickname] = useState("");
const [title, setTitle] = useState("");
const [tags, setTags] = useState("");
const [content, setContent] = useState("<p></p>");
const [isLoding, setIsLoding] = useState(false);
useEffect(()=>{
setUserid(localStorage.getItem('userid'));
setIsUserimage(localStorage.getItem('user_image'));
setNickname(localStorage.getItem('nick_name'));
},[])
const onChangeTitle = useCallback((e)=>{
setTitle(e.target.value);
},[title]);
const onChangeTags = useCallback((e) => {
setTags(e.target.value);
},[tags]);
const onChangeCK = useCallback((e) =>{
setContent(e.editor.getData());
},[content]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const onSubmit = useCallback((e)=> {
setIsLoding(true);
e.preventDefault();
if(!localStorage.getItem('userid')){
setIsLoding(false);
swal({
text: "글쓰기 권한이 없습니다.",
title: "권한 없음",
timer: "10000",
icon: "/static/image/Logo2.png"
});
Router.push("/user/login");
return;
}
if(title == null || title == "" || title == undefined || !title.trim().length>0){
setIsLoding(false);
swal({
text: "제목을 입력해주세요.",
title: "필수 입력 사항",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
if(content == null || content == "" || content == undefined) {
setIsLoding(false);
swal({
text: "답변을 입력해주세요.",
title: "필수 입력 사항",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
const regex = /^[ㄱ-ㅎ가-힣a-zA-Z0-9,-\s]+$/;
if(!regex.exec(tags) && tags!=null && tags!=""){
setIsLoding(false);
swal({
text: "태그는 [한글], [영문], [-]만 가능하며 콤마(,)로 구분됩니다.",
title: "태그 오류",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
let result = 0;
let Forms = new FormData();
Forms.append("userid",userid);
Forms.append("title",title);
Forms.append("content",content);
Forms.append("tags",tags);
axios({
method :'post',
baseURL : backUrl,
data : Forms
}).then((response)=>{
setIsLoding(false);
result = response.data;
if(result > 0){
result = response.data;
swal({
title: "등록 성공",
text: "능력치가 +3 올랐습니다.",
icon: "/static/image/Logo2.png",
});
Router.push("/community/board");
}else {
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
Router.push("/community/board");
}
}).catch((xhr)=>{
setIsLoding(false);
});
},[userid,title,content,tags]);
return(
<>
<Container>
<TitleComponent title="자유 게시판">
<FontAwesomeIcon style={{width:"35px",height:"auto"}} icon={faCrow}/>
</TitleComponent>
<Row>
<Col>
<ProfileImageUserid user_image={userImage} style={cardcss} writer={nickname} />
<InputText id="title" content="제목을 입력해주세요" onChange={onChangeTitle} maxLength="50"/>
<small style={{position:"absolute",left:"85%",top:"95px", color:"grey"}}>({title.length}/50)</small>
<InputText id="tags" content="태그를 입력해 주세요 (ex. mysql,java,뷰)" onChange={onChangeTags} maxLength="50"/>
<small style={{position:"absolute",left:"85%",top:"165px", color:"grey"}}>({tags.length}/50)</small>
<CkeditorOne2 onChange={onChangeCK} data="<p></p>" />
<hr />
<div style={buttoncss}>
<ButtonComponent name="취소" variant='info' onclick={()=>Router.push("/community/board")}/>
<ButtonComponent name="등록" onclick={onSubmit} disabled={isLoding}/>
</div>
</Col>
</Row>
</Container>
</>
);
}
export default Write;<file_sep>/Ability-SpringBoot1/src/main/resources/static/js/loginform.js
/**
* @author 정규현
* @summary 로그인 로직 구현
*/
let isEmpty = (value)=> {
if( value == "" || value == null || value == undefined || ( value != null && typeof value == "object" && !Object.keys(value).length ) ){
return true
}else{
return false
}
};
function isEmail(email) {
const pattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
if (pattern.test(email)) return true;
else return false;
}
function isPassword(password) {
const pattern = /^(?=.*[a-zA-Z])((?=.*\d)|(?=.*\W)).{8,20}$/;
if (pattern.test(password)) return true;
else return false;
}
function isIncludeSpace(str) {
const pattern = /\s/;
if (str.match(pattern)) return true;
else return false;
}
$(function(){
$("#a-login-submit-btn").click(()=>{
if(isEmpty($('#login-email').val())||isEmpty($('#login-password').val())){
swal({
title:"모든 값을 입력해 주세요.",
icon:"warning",
className:"swal-hover"
});
return false;
}else if(isIncludeSpace($('#login-email').val())) {
$('#a-login-submit').empty();
$('#a-login-submit').html("<p style='color:red'>이메일에는 공백을 포함할 수 없습니다</p>")
return false;
}else if(!isEmail($('#login-email').val())){
$('#a-login-submit').empty();
$('#a-login-submit').html("<p style='color:red'>이메일 형식을 확인해 주세요</p>");
return false;
}else if(!isPassword($('#login-password').val())){
$('#a-login-submit').empty();
$('#a-login-submit').html("<p style='color:red'>비밀번호 8~20자리</p><p style='color:red'>영문, 숫자, 특수문자 1자리 이상 포함입니다</p>");
return false;
}
}); //a-login-submit-btn End
})<file_sep>/front/components/presentational/atoms/ChattingModal.js
import React, {Component} from 'react';
import { Modal, Button} from 'react-bootstrap';
import { InputText } from '../atoms/InputboxComponent';
import axios from 'axios';
/**
*
* @author 우세림
* @summary 채팅방 만들기 모달
*
*/
class ChattingModal extends Component {
constructor(props, context) {
super(props, context);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handlesubmit = this.handlesubmit.bind(this);
this.onChangetitle = this.onChangetitle.bind(this);
this.onChangepeople = this.onChangepeople.bind(this);
this.onChangetags = this.onChangetags.bind(this);
this.state = {
show: false,
roomid : "",
people:"",
name:"",
tags : "",
link:""
};
}
onChangetitle(e){
this.setState({
name : e.target.value
})
}
onChangepeople(e){
this.setState({
people : e.target.value
})
}
onChangetags(e){
this.setState({
tags : e.target.value
})
}
async handlesubmit() {
const backUrl = process.env.NODE_ENV === 'production'? "?" : "";
let Forms = new FormData();
Forms.append("name",this.state.name);
Forms.append("people",this.state.people);
Forms.append("tags",this.state.tags);
await axios({
method :'post',
baseURL : backUrl,
url :"/chat/room",
data : Forms
}).then(()=>{
this.setState({ show: false });
});
}
handleClose() {
this.setState({ show: false });
}
handleShow() {
this.setState({ show: true });
}
render() {
return (
<>
<Button variant="primary" onClick={this.handleShow}>
방만들기
</Button>
<Modal
{...this.props}
size="md"
aria-labelledby="contained-modal-title-vcenter"
show={this.state.show} onHide={this.handleClose}
onExited={this.props.onExited}
centered
>
<Modal.Header closeButton>
<Modal.Title>방만들기</Modal.Title>
</Modal.Header>
<Modal.Body>
방 제목 <InputText id="name" type="text" content="방 이름을 입력하세요" onChange={this.onChangetitle}/>
인원 <InputText id="people" type="text" content="인원 입력하세요" onChange={this.onChangepeople}/>
태그 <InputText id="tags" type="text" content="JAVA, JSP" onChange={this.onChangetags}/>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.handleClose}>
취소
</Button>
<Button variant="primary" onClick={this.handlesubmit}>
확인
</Button>
</Modal.Footer>
</Modal>
</>
);
}
}
export default ChattingModal;<file_sep>/front/pages/project/detail.js
import React, {useCallback, useState, useEffect} from 'react';
import {Col,Row, Container} from 'react-bootstrap';
import dynamic from 'next/dynamic';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLaptopCode } from '@fortawesome/free-solid-svg-icons';
import {ButtonComponent} from '../../components/presentational/atoms/ButtonComponent';
import Router from 'next/router';
import axios from 'axios';
import swal from 'sweetalert';
import ReplyList from '../../components/presentational/molecules/ReplyList';
import { ProjectDetail, ProjectTitle2, Content } from '../../components/presentational/molecules/ProjectDetails';
/**
* @autho 신선하
* @summary 비디오 게시판 상세보기 페이지
*/
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
const Detail = () => {
const [seq, setSeq] = useState(0);
const [content, setContent] = useState("");
const [boardid, setBoardid] = useState(0);
const [likecount, setLikecount] = useState(0);
const [nickname, setNickname] = useState("");
const [replycount, setReplycount] = useState(0);
const [reputation, setReputation] = useState(0);
const [tags, setTags] = useState("");
const [title, setTitle] = useState("");
const [userImage, setUserImage] = useState("");
const [userid, setUserid] = useState(0);
const [viewCount, setViewCount] = useState(0);
const [dateCreated, setDateCreated] = useState(0);
const [replyList, setReplyList] = useState([]);
const [totalReply, setTotalReply] =useState(0);
const [reply, setReply] = useState("<p></p>");
const [currentUserId, setCurrentUserId] = useState(0);
const [file_path, setFile_path] = useState(0);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
useEffect(()=>{
setSeq(Router.query["seq"]);
axios.get(
backUrl+"/project/detail",
{
params:{
seq: Router.query["seq"]
}
}
)
.then((res)=>{
setBoardid(res.data.id);
setContent(res.data.content);
setLikecount(res.data.likecount);
setNickname(res.data.nick_name);
setReplycount(res.data.replycount);
setReputation(res.data.reputation);
setTags(res.data.tags);
setFile_path(res.data.file_path);
setTitle(res.data.title);
setUserImage(res.data.user_image);
setUserid(res.data.userid);
setViewCount(res.data.view_count);
setDateCreated(res.data.date_created);
setCurrentUserId(localStorage.getItem("userid"));
})
.catch((res)=>{
console.log(res);
})
},[]);
useEffect(()=>{
axios.get(backUrl,
{
params:{
seq:Router.query["seq"]
}
})
.then((res)=>{
setTotalReply(res.data.length);
setReplyList(res.data);
})
.catch((res)=>{
console.log(res);
})
},[totalReply]);
const setRecommandMain = useCallback((num)=>{
if(!localStorage.getItem('userid')){
swal({
text: "추천/비추천 기능은 로그인 후 이용이 가능합니다..",
title: num == 1?"추천 실패":"비추천 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
axios.get(backUrl+"/project/detail/recommand",
{
params:{
seq:Router.query["seq"],
userid:localStorage.getItem('userid'),
counta:num
}
})
.then((res)=>{
if(res.data =="success"){
swal({
text: num == 1?"글을 추천 했습니다.":"글을 비추천 했습니다.",
title: num == 1?"능력 +1":"능력 -1",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(num == 1? likecount+1 : likecount-1);
}else if(res.data=="plus"){
swal({
text: num == 1?"글을 추천 했습니다.":"글 추천을 취소 했습니다.",
title: num == 1?"능력 +1":"능력 -1",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(likecount-1);
}else if(res.data=="minus"){
swal("비추천 내역이 삭제 되었습니다.");
setLikecount(likecount+1);
}else{
swal({
text: "이미 투표한 글입니다. 투표 내역을 삭제 하시겠습니까?",
title: num == 1?"추천 실패":"비추천 실패",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((cancelok)=>{
if(cancelok){
setRecommandMain(0);
}
})
}
})
.catch((res)=>{
console.log(res);
})
},[likecount]);
const onClickDelte = useCallback(()=>{
swal({
text: "삭제한 게시물은 절대 복구할 수 없습니다. 게시물을 정말 삭제하시겠습니까?",
title: "삭제 경고",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
axios.get(backUrl+"/project/detail/delete",
{
params:{
seq:Router.query["seq"]
}
})
.then((res)=>{
if(res.data=="success"){
swal({
title: "삭제 완료",
text: "능력치가 -3 떨어졌습니다",
icon: "/static/image/Logo2.png",
});
}else{
swal("[Error0577] 게시물이 삭제 실패");
}
Router.push("/project/board");
})
.catch((res)=>{
console.log("오류발생",res);
})
}
})
},[]);
const onClickUp = useCallback(() =>{
setRecommandMain(1);
},[likecount]);
const onClickDown = useCallback(()=>{
setRecommandMain(-1);
},[likecount]);
const onChangeCkeditor = useCallback((e)=>{
setReply(e.editor.getData());
},[reply]);
const handleBench = (data) =>{
setTotalReply(totalReply-data);
};
const onClickReplyRegister = useCallback(() =>{
if(reply.trim().replace(/[ ]|[\s]/gi,"") !== "<></>" && currentUserId !=0){
axios.get(
backUrl+'/project/detail/replyok',
{
params:{
userid:currentUserId,
reply:reply,
seq:seq
}
},
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}
)
.then((res)=>{
setTotalReply(totalReply+1);
setReply(<p></p>);
})
.catch((res)=>{
console.log(res);
})
}else{
swal({
text: "답변 내용을 입력해 주세요.",
title: "답변 등록 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
}
},[reply,currentUserId,seq]);
return (
<>
<Container>
<TitleAndButtonComponent
title="프로젝트 게시판"
name="영상 올리기"
path='/project/write'>
<FontAwesomeIcon
style={{width:"35px",height:"auto"}}
icon={faLaptopCode}/>
</TitleAndButtonComponent>
<ProjectTitle2
title={title}
onclick3={onClickDelte}
tags={tags}
boardid={seq}
seq={seq}
viewcount={viewCount}
userid={userid}
currentUserId={currentUserId}
/>
<hr style={{marginTop:"0.5rem"}}/>
<ProjectDetail
content={content}
nickname={nickname}
userid={userid}
ability={reputation}
imagepath={userImage}
file_path={file_path}
date={dateCreated}
count={likecount}
onClickUp={onClickUp}
onClickDown={onClickDown}
/><br/>
<ReplyList
replyList={replyList}
totalReply={totalReply}
benchmark={handleBench}
/>
<Row style={{marginBottom:"4rem"}}>
<Col md={11} style={{paddingRight:"0"}}>
<div style={{backgroundColor:"rgba(0,0,0,.03)",
padding:"0.75rem 1.25rem",
border:"1px solid #c6badf"}}>
{currentUserId==0 || currentUserId==null ?
"로그인 후 답변 기능을 사용할 수 있습니다.":
"명쾌한 답변으로 질문자의 능력을 향상 시켜주세요!"}
</div>
{currentUserId==0 || currentUserId==null ? "":
(<>
<CkeditorOne2
onChange={onChangeCkeditor}
data={reply}
/>
<div className="text-right"
style={{marginTop:"0.8rem",
marginBottom:"1rem",
marginRight:"0.4rem"}}>
<ButtonComponent
variant="info"
name="목록가기"
onclick={()=>Router.push("/project/board")}
/>
<ButtonComponent
name="등록하기"
onclick={onClickReplyRegister}
/>
</div>
</>
)}
</Col>
</Row>
</Container>
</>
);
};
export default Detail;<file_sep>/front/pages/project/board.js
import React,{useState, useCallback, useEffect} from 'react';
import { Row, Col,ToggleButtonGroup,ToggleButton, Container } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLaptopCode } from '@fortawesome/free-solid-svg-icons';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import axios from 'axios';
import { UserSearchbarComponent } from '../../components/presentational/atoms/SearchbarComponent';
import LodingComponent from '../../components/presentational/atoms/LodingComponent';
import Page from '../../components/presentational/molecules/Page';
import VideoCard from '../../components/presentational/molecules/VideoCard';
/**
* @author 신선하
* @summary 비디오게시판 입니다
*/
const css = {
verticalAlign:"middle",
}
const wrapper = {
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gridAutoRows: 'minmax(50px, auto)',
gridGap: '1rem',
align: 'center',
};
const Board = ()=>{
const [searchWord, setSearchWord] = useState('');
const [dataList, setDataList] = useState([]);
const [placeHolder, setPlaceHolder] = useState('글 제목 검색');
const [isLoding, setIsLoding] = useState(false);
const [orderby, setOrderby] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [endPageBlock, setEndPageBlock] = useState(1);
const [pageSize, setPageSize] = useState(15);
const [startPageBlock, setStartPageBlock] = useState(1);
const [totalListCount, setTotalListCount] = useState(0);
const [totalPage, setTotalPage] = useState(1);
const [isSearch, setIsSearch] = useState(0)
const onChangeSearchInput = useCallback((e) =>{
setSearchWord(e.target.value);
},[searchWord]);
const onKeyPressSearch = useCallback((e)=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
}else if(e.charCode == 13){
setIsSearch(isSearch+1);
}
},[searchWord,placeHolder])
const onClickSearchButton = useCallback(()=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
};
setIsSearch(isSearch+1);
},[searchWord,placeHolder]);
const onChangeToggle = useCallback((e)=>{
const str = e.pop();
if(typeof str != "string"){
return;
}
setOrderby(str);
},[orderby]);
const handlePageChange= useCallback((pageNumber)=> {
setCurrentPage(pageNumber);
},[currentPage]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
useEffect( () =>{
window.scrollTo(0,0);
setIsLoding(true);
axios.get(backUrl+"/project",
{
params : {
orderby:orderby,
currentpage:currentPage,
word: isSearch!=0 ? searchWord : ""
}
})
.then((res) => {
setIsLoding(false);
setCurrentPage(res['data']['currentPage']);
setEndPageBlock(res['data']['endPageBlock']);
setPageSize(res['data']['pageSize']);
setStartPageBlock(res['data']['startPageBlock']);
setTotalListCount(res['data']['totalListCount']);
setTotalPage(res['data']['totalPage']);
setDataList(res['data']['projectBoardList']);
})
.catch((res)=>{
setIsLoding(false);
console.log(res);
});
},[orderby,totalListCount,currentPage,isSearch]);
const path = ("https://img.youtube.com/vi/"+dataList.map((videoContent)=>{videoContent.file_path})+"/hqdefault.jpg");
if(path == null){
path = "?"
}
return(
<>
{isLoding && <LodingComponent/>}
<TitleAndButtonComponent
title="프로젝트 자랑"
name="글 올리기"
path='/project/write'
>
<FontAwesomeIcon style={{width:"35px",height:"auto"}}
icon={faLaptopCode}/>
</TitleAndButtonComponent>
<Row style={{marginTop:"25px"}}>
<Col sm={6} md={8} style={css}>
<ToggleButtonGroup
type="checkbox"
value={orderby}
onChange={onChangeToggle}
>
<ToggleButton
value="0"
style={{backgroundColor:"#fff",
color:"#5F4B8B",
borderColor:"rgba(0,0,0,.125)"}}
variant="dark"
>최신순
</ToggleButton>
<ToggleButton
value="1"
style={{backgroundColor:"#fff",
color:"#5F4B8B",
borderColor:"rgba(0,0,0,.125)"}}
variant="dark"
>조회순
</ToggleButton>
</ToggleButtonGroup>
</Col>
<Col sm={6} md={4}>
<UserSearchbarComponent
name="user_searchbar"
onChange={onChangeSearchInput}
onClick={onClickSearchButton}
onKeyPress={onKeyPressSearch}
content={placeHolder}
/>
</Col>
</Row>
<style>
{`
@media screen and (max-width:480px){
#videocontent {
display : block!important;
}
#loading{
top : 50%!important;
}
}
`}
</style>
<hr style={{marginBottom:"5px"}}/><br/>
{dataList.length!==0 ?
<Container style={wrapper} id="videocontent">
{
dataList.map((videoContent)=>{
return(
<div key={JSON.stringify(videoContent['id'])}>
<VideoCard
seq={videoContent.id}
tags={videoContent.tags.replace('"','').replace('"','').replace("0",'')}
title={videoContent.title.replace('"','').replace('"','')}
view_count={videoContent.view_count}
likecount={videoContent.likecount}
reputation={videoContent.reputation}
id={videoContent.nick_name.replace('"','').replace('"','')}
image={"https://img.youtube.com/vi/"+videoContent.file_path+"/hqdefault.jpg"}
path="/project/detail"
userid={videoContent.userid}
content={videoContent.content}
date_created={videoContent.date_created}
videoCss={{padding:'1rem 0 1rem 0',
backgroundColor:'black'}}
/>
</div>
);
})
}
</Container>
:
<div
style={{marginTop:"30%",
marginLeft:"50%"}}>
검색한 결과가 없습니다.
</div>
}
<Row
style={{marginTop:"1.4rem",
marginBottom:"2rem",
justifyContent:"center"
}}>
<div style={{textAlign:"center"}}>
<Page
currentPage={currentPage}
totalListCount={totalListCount}
handlePageChange={handlePageChange}
/>
</div>
</Row>
</>
);
}
export default Board;<file_sep>/front/components/presentational/atoms/ProfileImageComponent.js
import React from 'react';
import Image from 'react-bootstrap/Image';
/**
*
* @author 강기훈
* @summary 게시글 프로필이미지 컴포넌트
*/
const css={
width:"32px",
height:"32px",
border:"1px solid #CDCECF",
marginRight: "0.5rem",
marginTop: "0.8rem"
}
export const ProfileImageComponent=(props)=>
<Image style={props.css?props.css: css} src={props.user_image ? props.user_image : ""} roundedCircle/>
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/User_Company_Detail.java
package com.ability.dto;
import java.sql.Date;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class User_Company_Detail {
private int userid;
private String company_email;
private String company_name;
private String company_tel;
private String manager_tel;
private String company_area;
private String logo;
private String register_number;
private String register_file;
private String homepage_url;
private String company_info;
private Date date_created;
private Date last_updated;
private String xloc;
private String yloc;
private List<MultipartFile> files;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getCompany_tel() {
return company_tel;
}
public void setCompany_tel(String company_tel) {
this.company_tel = company_tel;
}
public String getManager_tel() {
return manager_tel;
}
public void setManager_tel(String manager_tel) {
this.manager_tel = manager_tel;
}
public String getXloc() {
return xloc;
}
public void setXloc(String xloc) {
this.xloc = xloc;
}
public String getYloc() {
return yloc;
}
public void setYloc(String yloc) {
this.yloc = yloc;
}
public List<MultipartFile> getFiles() {
return files;
}
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
public String getCompany_email() {
return company_email;
}
public void setCompany_email(String company_email) {
this.company_email = company_email;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getCompany_area() {
return company_area;
}
public void setCompany_area(String company_area) {
this.company_area = company_area;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getRegister_number() {
return register_number;
}
public void setRegister_number(String register_number) {
this.register_number = register_number;
}
public String getRegister_file() {
return register_file;
}
public void setRegister_file(String register_file) {
this.register_file = register_file;
}
public String getHomepage_url() {
return homepage_url;
}
public void setHomepage_url(String homepage_url) {
this.homepage_url = homepage_url;
}
public String getCompany_info() {
return company_info;
}
public void setCompany_info(String company_info) {
this.company_info = company_info;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public Date getLast_updated() {
return last_updated;
}
public void setLast_updated(Date last_updated) {
this.last_updated = last_updated;
}
@Override
public String toString() {
return "User_Company_Detail [userid=" + userid + ", company_email=" + company_email + ", company_name="
+ company_name + ", company_tel=" + company_tel + ", manager_tel=" + manager_tel + ", company_area="
+ company_area + ", logo=" + logo + ", register_number=" + register_number + ", register_file="
+ register_file + ", homepage_url=" + homepage_url + ", company_info=" + company_info
+ ", date_created=" + date_created + ", last_updated=" + last_updated + "]";
}
}<file_sep>/front/components/presentational/molecules/ChartRadius.js
import React, { Component } from 'react';
import ReactHighcharts from 'react-highcharts';
/**
*
* @author 강기훈
* @summary admin 메인 페이지에 사용하는 원형그래프 입니다.
*
*/
class ChartRadius extends Component {
constructor(props){
super(props);
this.props = props;
this.state={
question:0,
freeboard:0,
project:0,
job:0
}
}
async componentWillReceiveProps(props) {
await this.setState({
question: props.question,
freeboard: props.freeboard,
project: props.project,
job: props.job
})
}
render(){
const config ={
chart: {
styledMode: true
},
title: {
text: '총 게시물 통계 ',
style:{
color:'#5F4B8B',
fontWeight:'bold',
fontFamily:'sans-serif'
}
},
series: [{
type: 'pie',
allowPointSelect: true,
keys: ['name', 'y', 'selected', 'sliced'],
data: [
['질의응답', this.state.question , false],
['프로젝트', this.state.project, false],
['자유게시판', this.state.freeboard, false],
['구인구직', this.state.job, true,true],
],
showInLegend: true
}]
}
return(
<ReactHighcharts config={config}></ReactHighcharts>
);
}
}
export default ChartRadius;<file_sep>/front/components/presentational/molecules/ContentTitle.js
import React from 'react';
import {ButtonComponent,ButtonComponent2} from "../atoms/ButtonComponent";
import {_} from 'underscore';
import {Col, Row} from "react-bootstrap";
import Router from 'next/router';
import Link from 'next/link';
import {TagListBoard} from './TagList';
/**
* @author 곽호원
* @summary 글제목 + 글쓰기 컴포넌트
* @see 정규현 컴포넌트 추가(커스텀)
* @see 정규현 커스텀 컴포넌트 추가/ 보드용
* */
const button = {
width : "90px",
}
const divcss ={
minWidth : "194px"
}
const rowcss = {
paddingTop : "1.5rem"
}
const colcss ={
padding:"0px",
textAlign:"center"
}
const ContentTitle = (props) => {
const userid = localStorage.getItem("userid");
return(
<>
<Col md={8} style={{color: "#8278ad"}}>
<h5>{props.title}</h5>
</Col>
<Col md={4} style={{padding : "0px",paddingRight:"8px", textAlign : "right"}} >
{ props.userid == userid ?
<div style={divcss}>
<ButtonComponent2 css={{width : "90px", color:"#762873", border :"0.5px solid #762873"}} name="삭제" onclick={props.onclick3}/>
<ButtonComponent2 css={{width : "90px", color:"#762873", border :"0.5px solid #762873"}} onclick={() =>Router.push(props.path, "/modify")} name="수정"/>
</div>
: ""
}
</Col>
</>
)
}
export const ContentTitle2 = (props) => {
return(
<>
<Row style={rowcss}>
<Col md={9}>
<TagListBoard hashtag={props.tags} boardid={props.boardid} viewcount={props.viewcount}/>
<h5 style={{color: "#8278ad"}}> {props.title}</h5>
</Col>
<Col md={3} style={colcss} >
{props.writer !== 0 && props.userid !== 0 ?
<>
{ props.writer == props.userid ?
<div style={divcss}>
<ButtonComponent variant="info" css={button} name="삭제" onclick={props.onclick3}/>
<Link href={props.to ? props.to : "/"}>
<ButtonComponent css={button} onclick={() =>Router.push("/community/modify?seq="+props.seq, '/community/modify')} name="수정"/>
</Link>
</div>
:""
}
</>
: ""
}
</Col>
</Row>
</>
)
}
export default ContentTitle;
<file_sep>/front/components/container/organisms/dashboard.js
import React, {Component} from 'react';
import AdminBox from '../../presentational/molecules/AdminBox';
import BoardListBox from '../../presentational/molecules/BoardListBox';
import ChartRadius from '../../presentational/molecules/ChartRadius';
import ChartLine from '../../presentational/molecules/ChartLine';
import ChartBar from '../../presentational/molecules/ChartBar'
import {Row, Col} from 'react-bootstrap';
import axios from 'axios';
const EndPoint = process.env.NODE_ENV === 'production'? "?/test" : "?/test";
const title={
fontSize:"25px",
fontWeight:"bold",
fontFamily:"sans-serif",
color:"#5F4B8B"
}
const title_div={
marginBottom:"25px",
marginTop:"20px"
}
const chartline={
display:"flex",
justifyContent:"center"
}
const marginBottom={
marginBottom:"100px"
}
class DashBoard extends Component {
constructor(props){
super(props);
this.state = {
allpost:0,
usercount:0,
leavemember:0,
todayjoin:0,
question:0,
freeboard:0,
project:0,
delete:0,
noanswer:0,
jobcount:0
}
}
async componentDidMount(){
await axios.get(EndPoint,{
auth:{
userid:"69"
}
}).then(response => {
this.setState({
allpost:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
usercount:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
leavemember:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
todayjoin:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
question:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
freeboard:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
project:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
delete:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
noanswer:response.data
})
});
await axios.get(EndPoint).then(response =>{
this.setState({
jobcount:response.data
})
});
}
render(){
let data = this.state;
return (
<>
<Row>
<Col sm={12} md={12}>
<AdminBox total= {data.allpost}
question={data.question}
project={data.project}
totaluser={data.usercount}
newuser={data.todayjoin}
outuser={data.leavemember}
untreated={data.accuse}
freeboard={data.freeboard}
delete={data.delete}
noanswer={data.noanswer}
jobcount={data.jobcount}
/>
</Col>
</Row>
<Row>
<Col sm={12} md={12} style={chartline}>
<ChartLine/>
</Col>
</Row>
<Row>
<Col sm={12} md={6}>
<ChartRadius question={data.question} freeboard={data.freeboard} project={data.project} job={data.jobcount}></ChartRadius>
</Col>
<Col sm={12} md={6}>
<ChartBar/>
</Col>
</Row>
<br></br>
<Row>
</Row>
<div style={title_div}>
<span style={title}>최근 게시물</span>
</div>
<Row>
<Col sm={12} md={6}>
<BoardListBox boardtitle="질의응답" categoryid="1"/>
</Col>
<Col sm={12} md={6}>
<BoardListBox boardtitle="자유게시판" categoryid="7"/>
</Col>
</Row>
<br/><br/>
<Row>
<Col sm={12} md={6}>
<BoardListBox boardtitle="프로젝트 게시판" categoryid="2"/>
</Col>
<Col sm={12} md={6}>
<BoardListBox boardtitle="구인구직 게시판" categoryid="4"/>
</Col>
</Row>
<div style={marginBottom}></div>
</>
);
}
}
export default DashBoard;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dao/ReplyMapper.java
package com.ability.dao;
import java.util.List;
import java.util.Map;
import com.ability.dto.Reply;
import com.ability.dto.Reply_Vote;
import com.ability.dto.custom.ReplyCustom;
public interface ReplyMapper {
public List<ReplyCustom> listSelect(Map<String, String> view);
public int insertReply(Map<String, String> view);
public int updateReply(Map<String, String> view);
public int deleteReply(Map<String, String> view);
public int view_count(Map<String,String> view);
public Reply getModifyContent(Map<String, String> seq);
public int checkReplyVote(Map<String, String> contents) throws Exception;
public int cancelReplyVote(Map<String, String> contents) throws Exception;
public int insertReplyVote(Map<String, String> contents) throws Exception;
public int setModifyReplyOk(Map<String, String> view) throws Exception;
public Reply listSelectOne(Map<String,String> view);
public Reply_Vote checkReplyVoteByUserid(Map<String,String> view);
}
<file_sep>/front/components/container/templatses/UserUpdate.js
import React ,{Component}from 'react';
import { UserImageComponent } from '../../presentational/atoms/UserImageComponent';
import { InputTextBox, InputTextBoxReadonly, InputTextarea } from '../../presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import CkeditorOne from '../../presentational/atoms/CkeditorOne';
/**
* @author 우세림
* @summary 개발자들 정보수정
*/
const user_mod_input_css ={
height: "35px",
width: "100%"
}
const user_mod_input_css2 ={
height: "35px",
width: "85%",
marginRight: "10px"
}
const user_mod_input_css3 ={
height: "35px",
width: "45%"
}
const user_md_img_btn ={
width: "100%",
marginTop: "15px"
}
const user_btn = {
height: "35px",
}
class UserUpdate extends Component {
render(){
return (
<>
<div className="user_md">
<div className="user_image">
<UserImageComponent/>
<ButtonComponent css={user_md_img_btn} name="이미지 변경" />
</div>
<div className="user_md_profile">
<div className="user_md_profile_div">
<span className="user_md_profile_span">이름</span>
<InputTextBoxReadonly formcss={user_mod_input_css} placeholder="이름" />
</div>
<div className="user_md_profile_div">
<span className="user_md_profile_span">닉네임</span>
<InputTextBox formcss={user_mod_input_css2} placeholder="닉네임"/>
<ButtonComponent css={user_btn} name="중복확인" />
</div>
<div className="user_md_profile_div">
<span className="user_md_profile_span">이메일</span>
<InputTextBox formcss={user_mod_input_css2} placeholder="이메일"/>
<ButtonComponent css={user_btn} name="중복확인" />
</div>
<div className="user_md_profile_div">
<span className="user_md_profile_span">전화번호</span>
<InputTextBox formcss={user_mod_input_css3} placeholder="전화번호"/>
<span className="user_md_profile_span2">위치</span>
<InputTextBox formcss={user_mod_input_css3} placeholder="위치"/>
</div>
<div className="user_md_profile_div">
<span className="user_md_profile_span">태그</span>
<InputTextarea row="3" formcss={user_mod_input_css} placeholder="태그, 태그"/>
</div>
</div>
</div>
<div>
<span className="user_md_profile_span2">소개</span>
<hr/>
<CkeditorOne />
</div>
<div className="user_md_btn">
<ButtonComponent name="취소" />
<ButtonComponent name="확인" />
</div>
</>
);
}
}
export default UserUpdate;<file_sep>/front/pages/developer/page.js
import React ,{Component} from 'react';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import axios from 'axios';
import Router from 'next/router';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUsers } from '@fortawesome/free-solid-svg-icons';
import Info from '../../components/container/organisms/info';
import CInfo from '../../components/container/organisms/cinfo';
import Post from '../../components/container/organisms/post';
import Bookmark from '../../components/container/organisms/bookmark';
import PQuestion from '../../components/container/organisms/pquestion';
import PFreeBoard from '../../components/container/organisms/pfreeboard';
import PProject from '../../components/container/organisms/pproject';
import PJob from '../../components/container/organisms/pjob';
import BQuestion from '../../components/container/organisms/bquestion';
import BFreeBoard from '../../components/container/organisms/bfreeboard';
import BProject from '../../components/container/organisms/bproject';
import BJob from '../../components/container/organisms/bjob';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
/**
*
* @author 우세림
* @summary 개발자들 상세 TabMeun
* @see 정규현 파라미터 받아주고 감..;;
*/
const endpoint = process.env.NODE_ENV === 'production'? "?" : "?";
class Page extends Component {
constructor(props){
super(props);
this.state = {
userdata : [],
userid : 0,
userid2 : 0,
userid3 : 0,
userid4 : 0
};
};
async componentDidMount() {
const user = Router.query['userid'];
const user2 = localStorage.getItem('userid');
const user3 = localStorage.getItem('role_name');
this.setState({
userid :user,
userid2 :user2,
userid3 : user3
})
await axios.get(endpoint, {
params : {
userid : Router.query['userid']
}
}).then((Response) => {
this.setState({
userdata : Response.data,
userid4: Response.data.role_name
});
});
}
render(){
let userdata = this.state.userdata;
if(userdata !== null){
return (
<>
<TitleComponent title="개발자 정보" >
<FontAwesomeIcon icon={faUsers} style={{width:"35px",height:"auto"}}/>
{ this.state.userid !== 0 ?
<>
{this.state.userid == this.state.userid2 || this.state.userid3 == "ROLE_ADMIN" ?
<Link href={{pathname: "/developer/update" , query:{userid: this.state.userid} }} as={"/developer/"+this.state.userid}>
<a><ButtonComponent css={{float: "right"}} name="프로필수정"/></a>
</Link> : ""}
{this.state.userid == this.state.userid2 && this.state.userid3 == "ROLE_COMPANY" || this.state.userid3 == "ROLE_ADMIN" && this.state.userid4 == "ROLE_COMPANY" ?
<Link href={{pathname: "/developer/company/cupdate" , query:{userid: this.state.userid} }} as={"/developer/"+this.state.userid}>
<a><ButtonComponent css={{float: "right", marginRight: "10px"}} name="기업수정"/></a>
</Link> : ""}
</> : ""
}
</TitleComponent>
<Tabs>
<TabList>
<Tab>프로필</Tab>
{this.state.userid4 == "ROLE_COMPANY" ?
<Tab>기업정보</Tab> : "" }
<Tab>작성한 글</Tab>
{this.state.userid == this.state.userid2 ?
<Tab>즐겨찾기</Tab> : "" }
</TabList>
<TabPanel>
<Info user_image={userdata.user_image} nick_name={userdata.nick_name} reputation={userdata.reputation}
name={userdata.name} email={userdata.email} user_info={userdata.user_info} tel={userdata.tel} area={userdata.area}
date_created={userdata.date_created} last_updated={userdata.last_updated} tags={userdata.tags}
userid={this.state.userid} />
</TabPanel>
{this.state.userid4 == "ROLE_COMPANY" ?
<TabPanel>
<CInfo />
</TabPanel>: "" }
<TabPanel>
<Post />
<Tabs>
<TabList>
<Tab>질의응답</Tab>
<Tab>자유게시판</Tab>
<Tab>프로젝트</Tab>
{this.state.userid4 == "ROLE_COMPANY" ?
<Tab>구인구직</Tab> : "" }
</TabList>
<TabPanel>
<PQuestion/>
</TabPanel>
<TabPanel>
<PFreeBoard/>
</TabPanel>
<TabPanel>
<PProject/>
</TabPanel>
<TabPanel>
<PJob/>
</TabPanel>
</Tabs>
</TabPanel>
<TabPanel>
<Bookmark />
<Tabs>
<TabList>
<Tab>질의응답</Tab>
<Tab>자유게시판</Tab>
<Tab>프로젝트</Tab>
<Tab>구인구직</Tab>
</TabList>
<TabPanel>
<BQuestion/>
</TabPanel>
<TabPanel>
<BFreeBoard/>
</TabPanel>
<TabPanel>
<BProject/>
</TabPanel>
<TabPanel>
<BJob/>
</TabPanel>
</Tabs>
</TabPanel>
</Tabs>
</>
);
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
export default Page;<file_sep>/front/components/container/templatses/Users.js
import React,{Component} from 'react';
import {SearchbarComponent} from '../../presentational/atoms/SearchbarComponent';
import UserCard from '../../presentational/molecules/UserCard';
import { GridArea } from '../organisms/GridArea';
import TitleComponent from '../../presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUsers } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
import ListgroupComponent from '../../presentational/atoms/ListgroupComponent';
/**
* @author 강기훈
* @summary 유저게시판 페이지 컴포넌트
* @see 정규현 게시판 메인 컴포넌트로 통일
*/
const EndPoint = process.env.NODE_ENV === 'production'? "" : "";
const Search_css={
marginTop:"40px",
display:"grid",
gridTemplateColumns: "35% 25%",
justifyContent:"space-between"
}
const User_css={
display: "grid",
gridTemplateColumns: "24% 24% 24% 24%",
gridGap:"30px 15px",
marginTop:"20px"
}
const sortbar={
height:"38px",
textAlign:"center"
}
class UserListJson extends Component{
constructor(props){
super(props);
this.state= {
userList:[]
}
}
async componentDidMount() {
await axios.get(EndPoint+"/ability"
).then((Response) => {
this.setState({
userList : Response.data
});
});
}
render(){
return this.state.userList.map((user)=>{
let tags = user.tags.split(',');
let minTags="";
for(let i=0 ; i<3; i++){
if(!tags[i+1]||i===2){
minTags += tags[i]+" "
break;
}else{
minTags += tags[i]+", ";
}
}
return <UserCard key={user.userid} userid={user.userid} userImage={user.user_image} name={user.nick_name} area={user.area} reputation={user.reputation} tags={minTags}></UserCard>
});
}
}
class UserListJson1 extends Component{
constructor(props){
super(props);
this.state= {
userList:[]
}
}
async componentDidMount() {
await axios.get(EndPoint+"/newUser"
).then((Response) => {
this.setState({
userList : Response.data
});
});
}
render(){
return this.state.userList.map((user)=>{
let tags = user.tags.split(',');
let minTags="";
for(let i=0 ; i<3; i++){
if(!tags[i+1]||i===2){
minTags += tags[i]+" "
break;
}else{
minTags += tags[i]+", ";
}
}
return <UserCard key={user.userid} userid={user.userid} userImage={user.user_image} name={user.nick_name} area={user.area} reputation={user.reputation} tags={minTags}></UserCard>
});
}
}
class UserListJson2 extends Component{
constructor(props){
super(props);
this.state= {
userList:[]
}
}
async componentDidMount() {
await axios.get(EndPoint
).then((Response) => {
this.setState({
userList : Response.data
});
});
}
render(){
return this.state.userList.map((user)=>{
let tags = user.tags.split(',');
let minTags="";
for(let i=0 ; i<3; i++){
if(!tags[i+1]||i===2){
minTags += tags[i]+" "
break;
}else{
minTags += tags[i]+", ";
}
}
return <UserCard key={user.userid} userid={user.userid} userImage={user.user_image} name={user.nick_name} area={user.area} reputation={user.reputation} tags={minTags}></UserCard>
});
}
}
const Users = () =>{
return (
<>
<GridArea>
<TitleComponent title="개발자들">
<FontAwesomeIcon icon={faUsers}/>
</TitleComponent>
<span className="sub_scss"></span>
<div style={Search_css}>
<ListgroupComponent css={sortbar} name="Ability" name1="New user" name2="Name"/>
<SearchbarComponent/>
</div>
<div className="tab-content" id="nav-tabContent">
<div className="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
<div style={User_css}>
<UserListJson />
</div>
</div>
<div className="tab-pane fade" id="list-profile" role="tabpanel" aria-labelledby="list-profile-list">
<div style={User_css}>
<UserListJson1 />
</div>
</div>
<div className="tab-pane fade" id="list-messages" role="tabpanel" aria-labelledby="list-messages-list">
<div style={User_css}>
<UserListJson2/>
</div>
</div>
</div>
</GridArea>
</>
);
}
export default Users<file_sep>/front/pages/donation/board.js
import React,{useState} from 'react';
import {ButtonComponent} from '../../components/presentational/atoms/ButtonComponent';
/**
* @author 정규현
* @summary 후원게시판 생성 // 결제시스템
*/
const Board = () =>{
const [msg, setMsg] = useState('');
const onclickDonation = (e)=>{
setMsg(`1,000만원이 후원되었습니다.
감사합니다!`);
};
return(
<>
<div style={{textAlign:"center"}}>
<h1 style={{marginTop:"3rem"}}>Team-Ability에게 후원해 주세요!</h1>
<hr/>
<p>후원해 주신 소중한 금액은 저희의 홈페이지의 서버 유지비 등으로 사용됩니다.</p>
<ButtonComponent onclick={onclickDonation} name="후원하기"/>
<h2 style={{color:"red",marginTop:"5rem"}}>{msg}</h2>
</div>
</>
);
};
export default Board;
<file_sep>/front/pages/question/content.js
import React, { Component } from 'react';
import axios from 'axios';
import {_} from 'underscore';
import Router from 'next/router';
import ReplyComplete from '../../components/presentational/molecules/ReplyComplete'
import PostDetail from '../../components/presentational/molecules/PostDetail'
import swal from 'sweetalert';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
import { Container } from 'react-bootstrap';
/**
* @author 곽호원
* @summary 게시글 상세보기 컴포넌트
* @author 정진호
* @version 세션 체크후 댓글, 답글 컴포넌트 생성 없으면 게시글만 보임.
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const plistEndPoint = backUrl;
const deleteBaord = backUrl;
class Content extends Component{
constructor(props){
super(props);
this.state = {
postlist : [],
replys : [],
comments : [],
userlist : [],
list : [],
seq : 0,
userid : 0
};
this.delete = this.delete.bind(this);
}
async componentDidMount() {
this.setState({
seq : Router.query['seq'],
userid : localStorage.getItem('userid')
});
const param = Router.query['seq'];
await axios.get(plistEndPoint,{
params : {
seq: param
}
}).then((response) => {
this.setState({
postlist : response.data
});
})
const getComment = backUrl
await axios.get(getComment,{
params : {
seq: param
}
}).then((response) => {
this.setState({
comments : response.data.map(list=>({id : list.id , name : list.comment,image : list.image}))
});
});
const getReply = backUrl
await axios.get(getReply,{
params : {
seq: param
}
}).then((response) => {
this.setState({
replys : response.data.map(list=>({id : list.id, name : list.reply,image : list.image}))
});
});
this.setState({
userlist : [...this.state.comments, ...this.state.replys, {id : this.state.postlist.userid,name :this.state.postlist.nick_name, image : this.state.postlist.user_image}]
});
this.setState({
list : _.uniq(this.state.userlist,(item)=>{
return item.name;
})
});
}
async delete(){
const willDelete = await swal({
title: "삭제 하시겠습니까?",
text: "해당 게시글을 삭제하시겠습니까?",
icon: "/static/image/Logo2.png",
});
if(willDelete){
axios.get(deleteBaord,{
params : {
seq : this.state.seq
}
}).then(() => {
swal({
title: "삭제 완료",
text: "능력치가 -3 떨어졌습니다",
icon: "/static/image/Logo2.png",
});
Router.push('/question/board');
})
}
}
render(){
const seq = this.state.seq;
const postlist = this.state.postlist;
const list = this.state.list;
if(postlist !== null && list.length > 0 && seq !== 0){
return(
<Container>
<TitleAndButtonComponent title="질의 응답" path="/question/write" name="글쓰기">
<FontAwesomeIcon icon={faQuestionCircle} style={{width:"27.73px"}} />
</TitleAndButtonComponent>
<PostDetail seq={seq}
userid={postlist.userid}
title={postlist.title}
id={postlist.nick_name}
date_created={postlist.date_created}
reputation={postlist.reputation}
user_image={postlist.user_image}
view_count={postlist.view_count}
likecount={postlist.likecount}
content={postlist.content}
hashtag={postlist.tags}
onclick3={this.delete}>
<hr />
<ReplyComplete seq={seq} oninsert={this.insert} list={list} />
</PostDetail>
</Container>
)
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
export default Content;<file_sep>/front/components/presentational/molecules/ChatTagList.js
import React from 'react';
import Badge from 'react-bootstrap/Badge';
import Link from 'next/link';
/**
*
* @author 정규현
* @summary props 값으로 tags= ? 값을 넘겨주면 , (콤마)로 값을 구분해서 태그를 생성해 줌.
*
* @version 수정 정진호--태그 통일
* @version 수정 정규현--Modify TagList Scope
*/
const tagcss = {
marginRight : "0.2rem",
backgroundColor: "#D1BADF",
}
const tag = {
color:"white",
textDecoration:"none"
}
const ChatTagList = (props) =>{
const taglist = [];
if(props.hashtag !== null && props.hashtag !== "" && props.hashtag !== undefined){
const list = props.hashtag.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
const hashtags = taglist.map((value, index)=>(
<Badge key={index} variant="light" style={tagcss} id={"tag"+index}>
<Link key={index} href="/tag"><a style={tag}>{value}</a></Link>
</Badge>));
return(
<>
<h6>{hashtags}</h6>
</>
)
}else{
return(
<h6> </h6>
);
}
}
export default ChatTagList;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/service/MainService.java
package com.ability.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ability.dao.MainMapper;
import com.ability.dto.Banner;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.ProjectBoardList;
import com.ability.utils.Vaildation;
import com.google.gson.Gson;
/**
*
* @author 정규현
* @summary 메인 화면 서비스 처리
*
*/
@Service
public class MainService {
private static Logger logger = LoggerFactory.getLogger(MainService.class);
@Autowired
MainMapper mapper;
@Autowired
Vaildation vaildation;
public void getSelectAllTags(){
logger.info("Current Thread : {}", Thread.currentThread().getName());
HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
List<String> newList = new ArrayList<String>();
if(mapper.getPostBoardAllTags() != null) {
newList.addAll(mapper.getPostBoardAllTags());
}
if(mapper.getJobBoardAllTags() != null) {
newList.addAll(mapper.getJobBoardAllTags());
}
if(mapper.getUserDetailAllTags() != null) {
newList.addAll(mapper.getUserDetailAllTags());
}
if(newList.size() > 0) {
String str = newList.toString().replace(" ", "");
String parse = Vaildation.removeSpecialCharacters(str);
StringTokenizer stringTokenizer = new StringTokenizer(parse,",");
while (stringTokenizer.hasMoreTokens()){
String key = stringTokenizer.nextToken();
if(!hashmap.containsKey(key)) {
hashmap.put(key, 1);
}else {
hashmap.put(key, hashmap.get(key)+1);
}
}
Gson gson = new Gson();
mapper.setTags(gson.toJson(hashmap), hashmap.size());
}else {
mapper.setTags(" ", 0);
}
}
//board list(qa, community board)
public List<PostBoardList> getPostList(Map<String, String> view) {
return mapper.getCommunityList(view);
}
//project board list
public List<ProjectBoardList> getVideoList(Map<String, String> view) {
return mapper.listSelect(view);
}
//getBannerList
public List<Banner> getBannerList(){
return mapper.getBannerList();
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Role.java
package com.ability.dto;
public class Role {
private int userid;
private String role_name;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
@Override
public String toString() {
return "Roll [userid=" + userid + ", role_name=" + role_name + "]";
}
}<file_sep>/front/components/presentational/molecules/HireList.js
import React from 'react';
import TagList from '../molecules/TagList';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faEye } from '@fortawesome/free-regular-svg-icons';
import Link from 'next/link';
import { Container ,Row,Col } from 'react-bootstrap';
import TimeAgo from 'react-timeago';
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter';
import ko from 'react-timeago/lib/language-strings/ko';
import { JobContentComponent, JobPeriodComponent } from '../atoms/AbilityComponent';
const formatter = buildFormatter(ko);
/**
*
* @auth 곽호원
* @summary 구인공고 리스트 페이지 1개의 컴포넌트
* @수정 신선하 UI 수정
*
*/
const divRight = {
flex: '0.5',
color:'grey',
textAlign: 'right',
margin : '20px 0 0.5rem 0'
}
const add = {
fontSize:'0.75rem',
margin : '0 0 0.5rem 0'
}
const title = {
fontSize:'12px',
margin : '0 0 1rem 0'
}
const HireList = (props) => {
const value = {
text : "",
styles : {
backgroundColor : "",
fontSize :"11px"
}
}
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
if((day+"").length <2){
day = "0"+day;
}
let temp = props.event.split("-");
let results = Number(temp[0]);
results += Number(temp[1]);
results += Number(temp[2]);
let getDates = year+month+day;
if(eval(results) === eval(getDates)){
value.text = "당일 마감";
value.styles.backgroundColor = "red";
}else if(eval(results-1) === eval(getDates)){
value.text = "마감전";
value.styles.backgroundColor = "red";
}else if(eval(results) < eval(getDates)){
value.text= "마감";
value.styles.backgroundColor = "gray";
}else{
value.text ="모집중";
value.styles.backgroundColor = "#cd6133";
}
return (
<>
<Container style={{padding : '0rem 0rem 1rem 0rem'}}>
<Row style={{borderBottom : "1px solid #e2e2e2", width:"99.5%"}}>
<Col md={9}>
<Link href={{pathname:"/job/detail" ,query: {seq : props.seq} }} as={"/content/"+props.seq} replace>
<a style={{height:'100%', color : "#5f4b8b", fontSize:"18px"}} onClick={props.onClick}>
[{props.subtitle}]
{props.hireTitle2} <JobPeriodComponent css={value.styles} val={value.text}></JobPeriodComponent>
</a>
</Link>
<br></br>
<div style={title}>
{props.subCompany} {props.Title}
</div>
<div style={add}>
<span style={{color:'#cd6133'}}>{props.company}</span>
<span style={{color:'darkblue'}}>{props.loaction}</span>
</div>
<TagList hashtag={props.hashtag}/>
</Col>
<Col md={3}>
<div style={divRight}>
<FontAwesomeIcon icon={faEye} style={{textAlign:'right', color:"#5f4b8b"}}/> {props.hits}<br></br>
<TimeAgo date={props.date} formatter={formatter} /><br></br>
{ props.scrap === 0?
<>
<span style={{color:"rgb(198, 186, 223)"}}>★</span> <JobContentComponent val={"+"+props.allscrap} style={{fontSize:"18px"}}></JobContentComponent>
</>
:<>
<span style={{color:"orange"}}>★</span> <JobContentComponent val={"+"+props.allscrap} style={{fontSize:"18px"}}></JobContentComponent>
</>
}
</div>
</Col>
</Row>
</Container>
</>
);
};
export default HireList;<file_sep>/front/components/presentational/molecules/BoardListAll.js
import React,{useState, useEffect} from 'react';
import axios from 'axios';
import BoardList from './BoardList';
/**
* @author 정규현
* @summary 배너 리스트
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const BoardListAll = ()=>{
const [dataList, setDataList] = useState([]);
const [orderby, setOrderby] = useState(0);
const getApiData = () =>{
axios.get(backUrl,
{
params : {
orderby:orderby,
start: 0,
end: 15
}
})
.then((res) => {
setDataList(res['data']);
})
.catch((res)=>{
setIsLoding(false);
console.log(res);
});
}
useEffect( ()=>{
getApiData();
},[]);
const result = dataList.map((content)=>{
<div key={JSON.stringify(content['id'])}>
<BoardList seq={JSON.stringify(content['id'])}
hashtag={JSON.stringify(content['tags']).replace('"','').replace('"','')}
title={JSON.stringify(content['title']).replace('"','').replace('"','')}
view_count={JSON.stringify(content['view_count'])}
like={JSON.stringify(content['likecount'])}
answer={JSON.stringify(content['replycount'])}
reputation={JSON.stringify(content['reputation'])}
id={JSON.stringify(content['nick_name']).replace('"','').replace('"','')}
day={JSON.stringify(content['date_created']).replace('"','').replace('"','')}
imagepath={JSON.stringify(content['user_image']).replace('"','').replace('"','')}
path="detail"/>
<hr style={{marginTop:"5px", marginBottom:"5px"}}/>
{JSON.stringify(content['id'])}
</div>
});
return (
<>
{result}
</>
);
}
export default BoardListAll;
<file_sep>/front/components/presentational/molecules/ReplyList.js
import React from 'react';
import {Recommend3} from './Recommend';
import BoardReply from './BoardReply';
import {Col,Row} from 'react-bootstrap';
/**
* @author 정규현
* @summary 리플라이 리스트
*/
const ReplyList = (props) =>{
const handleBench = (data) =>{
props.benchmark(data);
};
if(props.replyList){
const repliesList = props.replyList.map((replies)=>
<div key={replies.reply_id}>
<Row style={{width:"99%"}}>
<Col md={11} style={{paddingRight:"0"}}>
<BoardReply content={replies.reply_content} img={replies.user_image} nickname={replies.nick_name} ability={replies.reputation} date={replies.date_created} userid={replies.userid} replyid={replies.reply_id} benchmark={handleBench} />
</Col>
<Col md={1} className="text-left" style={{padding:"0"}}>
<Recommend3 count={replies.vote_count} replyid={replies.reply_id} userid={replies.userid}/>
</Col>
</Row>
<hr style={{width:"99%"}}/>
</div>
);
return(
<>
<div style={{paddingLeft:"0.6rem"}}><b>답변({props.totalReply})</b></div>
<hr style={{width:"99%",marginTop:"10px"}}/>
{repliesList}
</>
);
}else{
return(
" "
);
};
};
export default ReplyList;<file_sep>/front/components/presentational/atoms/TitleComponent.js
import React, {useState,useEffect} from 'react';
import { ButtonComponent } from './ButtonComponent';
import Link from 'next/link';
import {Row, Col} from 'react-bootstrap';
/**
* @author 정규현
* @summary 게시판별 리스트에 나타나는 메인 제목
* @version 정규현 TitleAndButtonComponent 컴포넌트 추가
*/
const css = {
color:'#5F4b8b',
fontWeight:'700',
marginTop:'1rem',
marginBottom:'2.2rem'
};
const css1 = {
fontWeight:'700',
marginTop:'1rem',
marginBottom:'2.2rem',
textAlign:"right"
};
const TitleComponent = (props) =>
<div style={css}>
<h3>
<b>
{props.children}
{props.title}
</b>
</h3>
</div>
export const TitleAndButtonComponent = (props) =>{
const [isauth, setIsauth] = useState("0");
useEffect( () => {
const temp = localStorage.getItem('userid');
setIsauth(temp);
},[isauth]);
return(
<>
<Row id="boardtitle">
<Col sm={6} md={6} style={css} id="boardcol">
<h3>
<b>
{props.children}
{props.title}
</b>
</h3>
</Col>
<Col sm={6} md={6} style={css1}>
{isauth!== "0" && isauth !== null && isauth !== undefined
?
<Link href={props.path}>
<a><ButtonComponent name={props.name} onclick={props.onclick} css={props.style}/></a>
</Link>
:
""
}
</Col>
</Row>
</>
)
}
const css2 = {
color:'#5F4b8b',
fontWeight:'700',
marginTop:'1rem',
marginBottom:'2.2rem',
paddingRight: "0px"
};
export const TitleAndButtonComponent2 = (props) =>{
const [isauth, setIsauth] = useState("0");
useEffect( () => {
const temp = localStorage.getItem('userid');
setIsauth(temp);
},[isauth]);
return(
<>
<Row>
<Col sm={11} md={11} style={css2}>
<h3>
<b>
{props.children}
{props.title}
</b>
</h3>
</Col>
<Col sm={1} md={1} style={css1}>
{isauth!== "0" && isauth !== null && isauth !== undefined
?
<Link href={props.path}>
<a><ButtonComponent name={props.name} onclick={props.onclick} css={props.style}/></a>
</Link>
:
""
}
</Col>
</Row>
</>
)
}
export default TitleComponent;<file_sep>/front/components/container/organisms/Footer.js
import React from 'react';
import { Row, Col } from 'react-bootstrap';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMapMarkerAlt } from '@fortawesome/free-solid-svg-icons';
import { faEnvelope } from '@fortawesome/free-regular-svg-icons';
import { faGithub } from '@fortawesome/free-brands-svg-icons';
/**
* @auth 신선하
* @summary 푸터디자인
*/
const footer = {
backgroundColor:'#5F4B8B',
color:'#FFF',
marginTop:"2.5rem",
textAlign:"center",
}
const footer2 = {
backgroundColor:'#5F4B8B',
}
const title ={
margin : '1.5rem 1rem 1rem 1rem',
fontSize : '15px'
}
const content = {
margin : '1rem',
lineHeight : '1.5rem',
textAlign:'center',
color:'#FFF',
fontSize : '11px'
}
const content1 = {
lineHeight : '1.5rem',
textAlign : 'right',
color:'#FFF',
fontSize : '11px'
}
const content2 = {
lineHeight : '1.5rem',
textAlign :'left',
color:'#FFF',
fontSize : '11px'
}
const content5 = {
lineHeight : '1.5rem',
textAlign :'center',
color:'#FFF',
fontSize : '11px'
}
const icon = {
width:"auto",
height:"14px"
}
const copyRight = {
textAlign:"title",
color:'#FFF',
textAlign:'center',
fontSize:'11px'
}
export const GitLink = (props) => {
return (
<>
<Link href={props.href} >
<a id={props.id} style={{color:"white!important"}} target="_blank">
{props.name}
<FontAwesomeIcon
id={props.id}
style={icon}
icon={faGithub}
/></a>
</Link>
</>
)
}
export const Footer = () => {
return (
<>
<style>
{`
#footer {
color : white!important
}
`}
</style>
<Row style={footer}>
<Col sm={4} md={4}>
<div style={title}>
<b>About Ability</b>
</div>
<Row>
<Col sm={4} md={3} />
<Col sm={4} md={6}>
<div style={content5}>
<Link href="/ability/Info">
<a id="footer">소개영상</a>
</Link><br/>
<Link href="/donation/board">
<a id="footer">후원하기</a>
</Link><br/>
<Link href="/user/reputation">
<a id="footer">능력치 제도</a>
</Link>
</div>
</Col>
<Col sm={4} md={3} />
</Row>
</Col>
<Col sm={4} md={4}>
<div style={title}>
<b>Contact</b>
</div>
<div style={content}>
<FontAwesomeIcon
style={{width:"auto",height:"14px"}}
icon={faEnvelope}
/>
<EMAIL><br/>
<FontAwesomeIcon
style={icon}
icon={faMapMarkerAlt}
/>
서울특별시 강남구 테헤란로5길 11 YBM빌딩 2층
</div>
</Col>
<Col sm={4} md={4}>
<div style={title}>
<b>Members</b>
</div>
<Row id="named">
<Col sm={4} md={6} style={{paddingRight:'7.5px'}} id="nameline">
<div style={content1}>
<GitLink id="footer" name="정규현" href="https://github.com/JungKyuHyun" /><br/>
<GitLink id="footer" name="강기훈" href="https://github.com/alkalisummer" /><br/>
<GitLink id="footer" name="신선하" href="https://github.com/sunha-shin" /><br/>
</div>
</Col>
<Col sm={4} md={6} style={{paddingLeft:'7.5px'}} id="nameline" >
<div style={content2}>
<GitLink id="footer" name="곽호원" href="https://github.com/kwakhowon" /><br/>
<GitLink id="footer" name="정진호" href="https://github.com/jhguma" /><br/>
<GitLink id="footer" name="우세림" href="https://github.com/selim0915" /><br/>
</div>
</Col>
</Row>
</Col>
</Row>
<Row style={footer2}>
<Col sm={6} md={2} />
<Col sm={6} md={8} style={copyRight} >
ⓒ 2019 <b>team-ability.</b> All rights reserved.<br/><br/>
</Col>
<Col sm={6} md={2} />
</Row>
</>
);
};<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/ReplyBoard.java
package com.ability.dto.custom;
import java.util.Date;
/*
* @author 정규현
* @summary 댓글 관련 정보 DTO, 대댓글은 따로 구현 예정. 절대 하나로 하지 말것.
*/
public class ReplyBoard {
private int userid;
private String nick_name;
private int reputation;
private String user_image;
private String reply_content;
private Date date_created;
private int vote_count;
private int reply_id;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getReply_content() {
return reply_content;
}
public void setReply_content(String reply_content) {
this.reply_content = reply_content;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getVote_count() {
return vote_count;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public int getReply_id() {
return reply_id;
}
public void setReply_id(int reply_id) {
this.reply_id = reply_id;
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/ProjectBoardModify.java
package com.ability.dto.custom;
/**
* @author 신선하
* @summary 프로젝트 보드 수정 DTO
*/
public class ProjectBoardModify {
private String title;
private String content;
private String file_path;
private String tags;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
}
<file_sep>/server/routes/post.js
const express = require('express');
const path = require('path');
const multer = require('multer');
const AWS = require('aws-sdk');
const multerS3 = require('multer-s3');
const router = express.Router();
const mysql = require('mysql');
const dbconfig = require('../config/config').development;
const connection = mysql.createConnection(dbconfig);
const ip = require('ip');
module.exports = router;
/**
* @author 정규현
* @summary upload등을 처리하기 위한 라우터
*/
AWS.config.update({
region: 'ap-northeast-2',
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
});
const upload = multer({
storage: multerS3({
s3:new AWS.S3(),
bucket:'react-ability',
key(req, file, cb){
cb(null, `original/${+new Date()}${path.basename(file.originalname)}`);
},
}),
limits:{fileSize: 20*1024*1024},
});
router.post('/', upload.array('image'), (req, res) =>{
res.json(req.files.map(v=>v.location));
});
router.post('/', (req, res)=>{
const sql = "insert into banner(title,banner_desc,connect_url,client,file_path) values ?";
const values = [
[req.body.title, req.body.desc, req.body.url,req.body.client, req.body.filepath]
];
connection.query(sql,[values] ,(err, result)=>{
if(err){
console.log('my sql error : ' + err);
res.send(err);
}else {
console.log('mysql is connected successfully'+ result.affectedRows);
};
res.send(result);
});
});
router.post('/', (req, res)=>{
const sql = "insert into banner_click(banner_id, ip) values ?";
const values = [
[req.body.id, ip.address()]
];
connection.query(sql,[values] ,(err, result)=>{
if(err){
console.log('my sql error : ' + err);
res.send(err);
}else {
console.log('mysql is connected successfully'+ result.affectedRows);
};
res.send(result);
});
});<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/ChatRoomController.java
package com.ability.controller;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ability.dto.ChatRoom;
import com.ability.dto.ChatUser;
import com.ability.dto.Chat_FileUpload;
import com.ability.service.ChatRoomRepository;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class ChatRoomController {
private final ChatRoomRepository repository;
public List<ChatUser>userList = new ArrayList<ChatUser>();
public List<ChatRoom>roomList = new ArrayList<ChatRoom>();
@Autowired
public ChatRoomController(ChatRoomRepository repository) {
this.repository = repository;
roomList = room();
}
@ResponseBody// 모든 채팅방 목록 반환
public List<ChatRoom> room() {
return repository.findAllRoom();
}
@ResponseBody// 채팅방 생성
public ChatRoom createRoom(@RequestParam(value="name")String name,
@RequestParam(value="people")String people,
@RequestParam(value="tags")String tags
){
ChatRoom newRoom = repository.createChatRoom(name, people, tags);
roomList.add(newRoom);
return newRoom;
}
public String roomDetail(@PathVariable("roomId") String roomId,
String nick_name,
String user_image,
int userid,
Model model
) {
ChatUser user = new ChatUser(Integer.parseInt(Integer.toString(userid)),nick_name,user_image);
ChatRoom room = repository.findRoomById(roomId);
a:for(int i=0; i<roomList.size(); i++) {
if(roomList.get(i).getRoomId().equals(room.getRoomId())) {
for(int j=0; j<roomList.get(i).getUserList().size();j++) {
if(roomList.get(i).getUserList().get(j).getUserid()==user.getUserid()) {
break a;
}
}
roomList.get(i).joinRoom(user);
}
}
for(int i=0; i<roomList.size(); i++) {
if(roomList.get(i).getRoomId().equals(room.getRoomId())) {
model.addAttribute("userlist",roomList.get(i).getUserList());
}
}
model.addAttribute("room",room);
model.addAttribute("nick_name",nick_name);
model.addAttribute("user_image",user_image);
model.addAttribute("userid",userid);
return "chatting/chat";
}
@ResponseBody
public int deleteRoom(@RequestParam(value="roomId")String roomId) {
return repository.deleteRoom(roomId);
}
@ResponseBody
public int deleteuser(@RequestParam(value="userId")String userId,
@RequestParam(value="roomID")String roomID
){
int userCount = 0;
a:for(int i=0; i<roomList.size(); i++) {
if(roomList.get(i).getRoomId().equals(roomID)) {
for(int j=0; j<roomList.get(i).getUserList().size();j++) {
if(roomList.get(i).getUserList().get(j).getUserid()==Integer.parseInt(userId)) {
roomList.get(i).getUserList().remove(j);
userCount=roomList.get(i).getUserList().size();
break a;
}
}
}
}
return userCount;
}
@ResponseBody
public List<ChatUser>getUserList(@RequestParam(value="roomID")String roomID){
List<ChatUser>userList = new ArrayList<>();
for(int i=0; i<roomList.size(); i++) {
if(roomList.get(i).getRoomId().equals(roomID)) {
userList= roomList.get(i).getUserList();
}
}
return userList;
}
@ResponseBody
public int getUserCount(@RequestParam(value="roomID")String roomID){
int userCount = 0;
for(int i=0; i<roomList.size(); i++) {
if(roomList.get(i).getRoomId().equals(roomID)) {
userCount= roomList.get(i).getUserList().size();
}
}
return userCount;
}
@ResponseBody
public String fileUpload(@RequestParam MultipartFile upload ,@ModelAttribute("Chat_FileUpload") Chat_FileUpload chat_FileUpload ,HttpServletResponse response, HttpServletRequest request , Model model){
JsonObject json = new JsonObject();
HttpSession session = request.getSession();
String rootPath = session.getServletContext().getRealPath("/WEB-INF/classes/static/image");
OutputStream out = null;
PrintWriter printWriter = null;
upload = chat_FileUpload.getUpload();
byte[] bytes = null;
try {
bytes = upload.getBytes();
} catch (IOException e1) {
e1.printStackTrace();
}
String filename = "";
String fileurl="";
if(upload != null){
filename = upload.getOriginalFilename();
filepath= rootPath+"/"+filename;
chat_FileUpload.setFilename(filename);
fileurl = request.getContextPath() +"/resources/static/image/bg1.jpeg";
try{
File file = new File(rootPath+"/"+filename);
upload.transferTo(file);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
try {
out = new FileOutputStream(new File(rootPath+"/"+filename));
try {
out.write(bytes);
printWriter = response.getWriter();
response.setContentType("text/html");
json.addProperty("uploaded", 1);
json.addProperty("fileName",filename);
json.addProperty("url",fileurl);
printWriter.println(json);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(printWriter != null) {
printWriter.close();
}
}
return null;
}
}
<file_sep>/front/components/presentational/atoms/PostChart.js
import React , {Component} from 'react';
import Highcharts from 'react-highcharts';
import Router from 'next/router';
import axios from 'axios';
const endpoint = process.env.NODE_ENV === 'production'? "?" : "?";
class PostChart extends Component {
constructor(props){
super(props);
this.state = {
userid : 0,
chartdata : []
};
};
async componentDidMount() {
let user = Router.query['userid'];
this.setState({
userid : user
})
await axios.get(endpoint+'/postChart', {
params : {
userid : Router.query['userid']
}
}).then((Response) => {
this.setState({
chartdata : Response.data
});
});
}
render() {
let {chartdata} = this.state;
let boardDay =[];
let category_id =[];
let postCount =[];
for(var i=0; i<chartdata.length; i++){
boardDay[i] = this.state.chartdata[i].boardDay;
category_id[i] = this.state.chartdata[i].category_id;
postCount[i] = this.state.chartdata[i].postCount;
}
let dayArr= [];
let sampleArr = [];
var date = new Date();
var year = ''+date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
year =year.slice(2,4);
if(month <10) month="0"+month;
for(var i=0; i<7; i++){
day = date.getDate()-i;
if(day <10) day="0"+day;
dayArr[i] =year+"."+month+"."+day;
sampleArr.push(dayArr[i]);
}
sampleArrSort =sampleArr.sort();
let postCountResult_1=[];
let postCountResult_2=[];
let postCountResult_7=[];
for(var i=0; i<sampleArr.length; i++){//2
postCountResult_1[i] = 0;
for(var j=0; j<boardDay.length; j++){//4
if(sampleArr[i]==boardDay[j]){
if(category_id[j]==1){
postCountResult_1[i] = postCount[j];
}
}
}
}
for(var i=0; i<sampleArr.length; i++){//2
postCountResult_2[i] = 0;
for(var j=0; j<boardDay.length; j++){//4
if(sampleArr[i]==boardDay[j]){
if(category_id[j]==2){
postCountResult_2[i] = postCount[j];
}
}
}
}
for(var i=0; i<sampleArr.length; i++){//2
postCountResult_7[i] = 0;
for(var j=0; j<boardDay.length; j++){//4
if(sampleArr[i]==boardDay[j]){
if(category_id[j]==7){
postCountResult_7[i] = postCount[j];
}
}
}
}
const config = {
chart: {
type: 'column',
height: '300px'
},
title: {
text: '사용자의 최근 일주일 활동 정보',
style: {
fontWeight: 'bold',
fontSize: '20px'
}
},
xAxis: {
categories: sampleArr
},
yAxis: {
allowDecimals: false,
min: 0,
title: {
text: ''
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
shadow: false
},
tooltip: {
headerFormat: '<b>Total: {point.stackTotal}</b><br/>',
pointFormat: '{series.name}: {point.y}'
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'whiblate'
}
}
},
series: [{
name: '질의응답',
color: '#d8bfd9',
data: postCountResult_1
}, {
name: '자유게시판',
color: '#e3e3e3',
data: postCountResult_7
}, {
name: '프로젝트',
color: '#aed1b3',
data: postCountResult_2
}]
};
return (
<>
<Highcharts config={config}></Highcharts>
</>
);
}
}
export default PostChart;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/ReplyController.java
package com.ability.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.ability.dto.Reply;
import com.ability.dto.Reply_Vote;
import com.ability.dto.custom.ReplyCustom;
import com.ability.service.ReplyService;
@RestController
public class ReplyController {
@Autowired
ReplyService replyService;
public List<ReplyCustom> getReplyList(@RequestParam(value="seq")String seq){
Map<String, String> viewReply = new HashMap<String, String>();
viewReply.put("id", seq);
List<ReplyCustom> rList = replyService.getReplyList(viewReply);
return rList;
}
public int setReplyInsert(@RequestParam(value="userid")String userid,
@RequestParam(value="seq")String seq,
@RequestParam(value="reply_content")String reply_content) {
Map<String, String>contents = new HashMap<String, String>();
contents.put("board_id", seq);
contents.put("userid", userid);
contents.put("reply_content", reply_content);
int result = replyService.replyInsert(contents);
if(result > 0) {
return result;
}
return -1;
}
public int modifyReply(@RequestParam(value="id")String id,
@RequestParam(value="reply_content")String reply_content) {
Map<String, String> contents = new HashMap<String, String>();
contents.put("id", id);
contents.put("reply_content", reply_content);
int result = replyService.replyUpdate(contents);
if(result > 0) {
return result;
}
return result;
}
public int deleteReply(@RequestParam(value="id")String id) {
Map<String, String> contents = new HashMap<String, String>();
contents.put("id", id);
int result = replyService.replyDelete(contents);
if(result > 0) {
return result;
}
return -1;
}
public String postReplyRecommand(@RequestParam(value="seq") String seq,
@RequestParam(value="userid") String userid,
@RequestParam(value="counta") String counta) {
String result = "fail";
Map<String,String> contents = new HashMap<String,String>();
contents.put("seq",seq);
contents.put("userid",userid);
contents.put("counta",counta);
contents.put("category_id", "1");
if(counta.equals("0")) {
return replyService.cancelReplyVote(contents);
}
if(!replyService.checkReplyVote(contents)) {
result = "success";
}
return result;
}
public Reply modifyContent(@RequestParam(value="seq") String seq) {
Map<String, String> contents = new HashMap<String, String>();
contents.put("seq",seq);
return replyService.getModifyContent(contents);
}
public String modifyContentOk(@RequestParam(value="seq")String seq,
@RequestParam(value="content")String content) {
Map<String, String> view = new HashMap<String, String>();
view.put("seq", seq);
view.put("content", content);
view.put("category_id", "1");
return replyService.setModifyReplyOk(view);
}
public Reply getReplyListtOne(@RequestParam(value="id")String id){
Map<String, String> viewReplyComment = new HashMap<String, String>();
viewReplyComment.put("id", id);
Reply rList = replyService.getReplyListOne(viewReplyComment);
return rList;
}
public int modifyReplyComment(@RequestParam(value="id" )String id,
@RequestParam(value="reply_content") String reply_content) {
Map<String, String> contents = new HashMap<String, String>();
contents.put("id", id);
contents.put("reply_content", reply_content);
int result = replyService.replyUpdate(contents);
if(result > 0) {
return result;
}
return -1;
}
public Reply_Vote checkReplyVote(@RequestParam(value="seq")String seq,
@RequestParam(value="userid")String userid) {
Map<String, String> contents = new HashMap<String, String>();
contents.put("seq", seq);
contents.put("userid", userid);
Reply_Vote replyVote = replyService.checkReplyVoteByUserid(contents);
if(replyVote != null) {
return replyVote;
}
return null;
}
}
<file_sep>/front/components/presentational/atoms/CkeditorTwoHorizon.js
/**
* @author 정규현
* @summary ckeditor 커스텀 / 미리보기 구현
*/
import React,{Component}from'react';
import CKEditor from'ckeditor4-react';
class CkeditorTwoHorizon extends Component{
constructor(props){
super(props);
this.state={
data:'<p> </p>'
};
this.handleChange=this.handleChange.bind(this);
this.onEditorChange=this.onEditorChange.bind(this)
};
onEditorChange(evt){
this.setState({data:evt.editor.getData()})
};
handleChange(changeEvent){
this.setState({
data:changeEvent.target.value})
};
render(){
return(
<div>
<div className="row"style={{overflow:'auto'}}>
<div className="col-6">
<CKEditor config={{toolbar:[['Bold','Italic','Strike','Blockquote','uploadImage','Styles','Format','-','Image','Table','Indent','-','NumberedList','BulletedList','Clipboard','Undo','Redo','editing','HorizontalRule','SpecialChar','Source','CodeSnippet']],extraPlugins:'codesnippet, easyimage,sourcedialog,justify,embed,autoembed,image2,autogrow ',uiColor:'#c6badf',height:'200px',width:'99.7%',resize_enabled:true,codeSnippet_theme:'atelier-heath.light',contentsCss:['http://cdn.ckeditor.com/4.11.4/full-all/contents.css','https://ckeditor.com/docs/vendors/4.11.4/ckeditor/assets/css/widgetstyles.css',],embed_provider:'//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}',image2_alignClasses:['image-align-left','image-align-center','image-align-right'],image2_disableResizer:true,removePlugins:'resize, image'}}data={this.state.data}onChange={this.onEditorChange}/>
</div>
<div className="col-6"><EditorPreview data={this.state.data}/>
</div>
</div>
</div>)
}
};
class EditorPreview extends Component{
render(){
return(
<div className="editor-preview"style={{background:"white",border:"1px solid #b0aabc",overflow:'auto'}}>
<h6 style={{textAlign:"center",marginTop:"0.5rem",marginBottom:"0.5rem"}}>미리보기</h6>
<hr/>
<div dangerouslySetInnerHTML={{__html:this.props.data}}>
</div>
</div>
)
}
};
export default CkeditorTwoHorizon;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/DeveloperDetailList.java
package com.ability.dto.custom;
import java.sql.Date;
/**
*
* @author 우세림
* @summary 유저게시판 user, user_detail Join
*
*/
public class DeveloperDetailList {
private int userid;
private String email;
private String password;
private String nick_name;
private String name;
private int enabled;
private String area;
private Date date_created;
private int reputation;
private Date last_updated;
private String user_image;
private long tel;
private String user_info;
private String tags;
private String role_name;
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date data_created) {
this.date_created = data_created;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public Date getLast_updated() {
return last_updated;
}
public void setLast_updated(Date last_updated) {
this.last_updated = last_updated;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public long getTel() {
return tel;
}
public void setTel(long tel) {
this.tel = tel;
}
public String getUser_info() {
return user_info;
}
public void setUser_info(String user_info) {
this.user_info = user_info;
}
@Override
public String toString() {
return "DeveloperDetailList [userid=" + userid + ", email=" + email + ", password=" + <PASSWORD> + ", nick_name="
+ nick_name + ", name=" + name + ", enabled=" + enabled + ", area=" + area + ", data_created="
+ date_created + ", reputation=" + reputation + ", last_updated=" + last_updated + ", user_image="
+ user_image + ", tel=" + tel + ", user_info=" + user_info + "]";
}
}
<file_sep>/front/pages/developer/company/cupdate.js
import React ,{Component}from 'react';
import { UserImageComponent2 } from '../../../components/presentational/atoms/UserImageComponent';
import { InputTextBox, InputText } from '../../../components/presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUsers } from '@fortawesome/free-solid-svg-icons';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import TitleComponent from '../../../components/presentational/atoms/TitleComponent';
import { Button } from 'react-bootstrap';
import swal from 'sweetalert';
import ReactGoogleMapLoader from "react-google-maps-loader"
import ReactGooglePlacesSuggest from "react-google-places-suggest"
import Geocode from "react-geocode";
const CkeditorOne2 = dynamic(() =>import('../../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
/**
* @author 우세림
* @summary 기업정보수정
*/
const user_mod_input_css ={
height: "35px",
width: "100%",
color: "gray"
}
const user_img = {
width: "100%",
height:"auto"
}
const user_md = {
paddingTop : "1rem",
display: "grid",
gridTemplateColumns: "18% 82%",
marginBottom: "10px"
}
const user_md_profile = {
paddingLeft: "15px",
}
const user_md_profile_div = {
display: "flex"
}
const user_md_profile_span = {
display: "inline-block",
padding: "0.500em",
color: "rgb(71, 71, 71)",
textAlign: "right",
fontWight: "500",
width: "120px",
marginRight: "5px"
}
const user_md_profile_span2 = {
display: "inline-block",
padding: "0.500em",
color: "rgb(71, 71, 71)",
textAlign: "right",
fontWight: "500",
width: "135px",
marginRight: "5px"
}
const user_md_btn = {
display: "flex",
marginTop: "3.000em",
justifyContent: "space-between"
};
class CUpdate extends Component {
constructor(props){
super(props);
this.state = {
userid : 0,
userlist: [],
companydata : [],
result : 0,
image : '',
company_tel: '',
company_area: '',
company_email: '',
homepage_url: '',
company_info: '',
image: '',
imagePreviewUrl: '',
isEdit: false,
value : "",
search : ""
};
this.onSubmit = this.onSubmit.bind(this);
this.Onchangeimg = this.Onchangeimg.bind(this);
this.saveImg = this.saveImg.bind(this);
this.onChangeTel = this.onChangeTel.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangehomepage = this.onChangehomepage.bind(this);
this.onChangeCk = this.onChangeCk.bind(this);
this.onChangeArea=this.onChangeArea.bind(this);
this.handleSelectSuggest=this.handleSelectSuggest.bind(this);
this.handleNoResult = this.handleNoResult.bind(this);
this.handleStatusUpdate = this.handleStatusUpdate.bind(this);
};
Onchangeimg(e){
let reader = new FileReader();
let file = e.target.files[0];
const imageFormData = new FormData();
[].forEach.call(e.target.files, (f)=>{
imageFormData.append('image', f);
});
axios.post(backUrl,
imageFormData,
)
.then((res)=>{
this.setState({
isEdit:true,
image: res.data,
});
});
reader.onloadend = () => {
this.setState({
imagePreviewUrl: reader.result,
});
}
reader.readAsDataURL(file)
}
saveImg(){
axios.post(backUrl2,{
file:this.state.image,
userid:Router.query['userid']
})
.then((res)=>{
this.setState({
isEdit:false,
});
swal({
text: "이미지가 저장되었습니다.",
title: "이미지 저장",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
})
}
async componentDidMount() {
let user = Router.query['userid'];
this.setState({
userid : user
})
await axios.get(EndPoint, {
params : {
userid : Router.query['userid']
}
}).then((Response) => {
this.setState({
companydata : Response.data[0],
company_tel : Response.data[0].company_tel,
company_email : Response.data[0].company_email,
homepage_url : Response.data[0].homepage_url,
company_info : Response.data[0].company_info,
company_area : Response.data[0].company_area
});
});
}
onChangeTel(e){
this.setState({
company_tel : e.target.value
})
}
onChangeEmail(e){
this.setState({
company_email : e.target.value
})
}
onChangehomepage(e){
this.setState({
homepage_url : e.target.value
})
}
onChangeCk(e){
this.setState({
company_info : e.editor.getData()
})
}
onChangeArea(e){
this.setState({search: e.target.value, value: e.target.value});
}
handleSelectSuggest = (geocodedPrediction, originalPrediction) => {
this.setState({
search: "",
value: geocodedPrediction.formatted_address,
});
}
async onSubmit() {
const telrex = /^[0-9\b]+$/;
const emailrex = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
let tel = this.state.company_tel;
let email = this.state.company_email;
let homepage = this.state.homepage_url;
let info = this.state.company_info;
Geocode.setApiKey("?");
Geocode.enableDebug();
Geocode.fromAddress(this.state.value.replace(/[\s]/g,"").length >0 ? this.state.value : this.state.company_area).then(
response => {
const { lat, lng } = response.results[0].geometry.location;
if (telrex.test(tel)){
if(emailrex.test(email)){
let result = 0;
let Forms = new FormData();
Forms.append("userid", Router.query['userid']);
Forms.append("company_tel", tel);
Forms.append("company_email", email);
Forms.append("company_area",this.state.value.replace(/[\s]/g,"").length >0 ? this.state.value : this.state.company_area);
Forms.append("homepage_url",homepage);
Forms.append("xloc",lat);
Forms.append("yloc",lng);
Forms.append("company_info",info);
axios({
method :'put',
baseURL : EndPoint,
data : Forms
}).then((Response)=>{
result = Response.data;
if (result > 0) {
swal({
text: "기업 프로필이 수정되었습니다.",
title: "기업 프로필 수정",
timer: "3000",
icon: "/static/image/Logo2.png"
});
Router.push("/developer/page?userid="+Router.query['userid'], "/developer/page/"+Router.query['userid']);
} else {
alert("ddd");
}
});
}else {
swal({
text: "이메일 양식을 확인해주세요.",
title: "이메일 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}
} else {
swal({
text: "전화번호는 [숫자] 11자리 이하로 입력해주세요.",
title: "전화번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
document.getElementById('tel').value ="";
document.getElementById('tel').focus();
return;
}
},
error => {
console.error(error);
}
);
}
async onCancle() {
Router.push("/developer/page?userid="+Router.query['userid'], "/developer/page/"+Router.query['userid']);
};
render(){
let {companydata} = this.state;
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<UserImageComponent2 id="image" css={user_img} imagepath={imagePreviewUrl} />);
} else {
$imagePreview = (<UserImageComponent2 id="image" css={user_img} imagepath={companydata.logo} />);
}
if(this.state.companydata !== null && this.state.userid > 0){
return (
<>
<TitleComponent title="기업 정보수정">
<FontAwesomeIcon icon={faUsers} style={{width:"1em",height:"auto"}}/>
</TitleComponent>
<div style={user_md} id="info_main">
<div>
<div className="imgPreview">
{$imagePreview}
</div>
{!this.state.isEdit ?
<b>
<InputText label="로고 업로드" id="user_image" name="user_image" accept=".jpg, .gif, .png"
className="user_image" for="user_image" type="file" onChange={this.Onchangeimg}/>
</b>
:
<Button block="true" variant="danger" onClick={this.saveImg} style={{marginTop:"2px"}}>변경한 로고 저장</Button>
}
</div>
<div style={user_md_profile}>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>회사 전화번호</span>
<InputTextBox type="tel" id="tel" value={this.state.company_tel} maxLength="11" formcss={user_mod_input_css} onChange={this.onChangeTel}/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>회사 이메일</span>
<InputTextBox id="email" value={this.state.company_email} formcss={user_mod_input_css} onChange={this.onChangeEmail}/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>회사 위치</span>
<ReactGoogleMapLoader
params={{
key: "",
libraries: "places,geocode",
}}
render={googleMaps =>
googleMaps && (
<ReactGooglePlacesSuggest
googleMaps={googleMaps}
autocompletionRequest={{
input: this.state.search,
}}
onNoResult={this.handleNoResult}
onSelectSuggest={this.handleSelectSuggest}
onStatusUpdate={this.handleStatusUpdate}
textNoResults="My custom no results text"
customRender={prediction => (
<div className="customWrapper">
{prediction
? prediction.description
: "My custom no results text"}
</div>
)}
>
<InputTextBox type="text"
value={this.state.value}
onChange={this.onChangeArea}
id="area"
placeholder={companydata.company_area}
/>
</ReactGooglePlacesSuggest>
)
}
/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>홈페이지</span>
<InputTextBox id="homepage" value={this.state.homepage_url} formcss={user_mod_input_css} onChange={this.onChangehomepage}/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span2}>회사 소개</span>
<CkeditorOne2 id="ckvalue" data={this.state.company_info} onChange={this.onChangeCk} />
</div>
</div>
</div>
<div style={user_md_btn}>
<div>
</div>
<div>
<ButtonComponent name="뒤로가기" onclick={this.onCancle} variant="info"/>
<ButtonComponent name="확인" onclick={this.onSubmit}/>
</div>
</div>
</>
)
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
export default CUpdate;<file_sep>/front/components/presentational/molecules/ChattingUser.js
import React from 'react';
import UserCard from '../molecules/UserCard';
import {NavLink} from 'react-router-dom';
/**
*
* @author 우세림
* @summary 20190620 채팅 중인 유저정보
*
*/
const css={
border:"1px solid #dfe6e9",
width:"240px",
height:"100%",
borderRadius:"6px",
boxShadow:"1px 1px #b2bec3",
marginBottom:"20px"
}
const css2 = {
marginTop:"10px",
fontWeight:"bold",
color:"#5F4B8B"
}
const css3 = {
height:"35px",
borderBottom:"1px solid #dfe6e9",
paddingLeft:"15px",
paddingRight:"15px"
}
const css4 = {
textAlign: "center",
marginBottom: "10px"
}
const ChattingUser = (props) =>
<div style={css}>
<div style={css3}>
<h5 style={css2}>{props.title}</h5>
</div>
<UserCard id={props.id} name={props.name} area={props.area} reputation={props.reputation}/>
<div style={css4}>
<NavLink>더보기</NavLink>
</div>
</div>
export default ChattingUser;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dao/ChattingMapper.java
package com.ability.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ability.dto.ChatRoom;
public interface ChattingMapper {
/**
* 채팅게시판 관련 Mapper
*
* @author 강기훈
* @summary 채팅게시판 DAO
*
*/
public int insert(@Param(value="room_id") String room_id,
@Param(value="room_name") String room_name,
@Param(value="max_people") int max_people,
@Param(value="tags") String tags
);
public List <ChatRoom>getRoomList();
public ChatRoom getRoomById(@Param(value="room_id") String room_id);
public int delete(@Param(value="room_id") String room_id);
}
<file_sep>/front/components/presentational/molecules/UserPost.js
import React from 'react';
/**
*
* @author 우세림
* @summary 개발자들 상세 페이지 게시글 정보
*
*/
const userPostsNum ={
width: "100%",
fontSize: "18px",
margin: "7px auto 4px auto",
display: "inline-block",
fontFamily: "bold"
}
const userPosts ={
height: "60px",
float: "left",
textAlign: "center",
fontFamily: "bold",
fontSize: "13px",
padding: "0px",
border: "1px solid #ededed"
}
const UserPost = (props) => {
return (
<>
<div style={userPosts}>
<div style={userPostsNum}>{props.question}</div>
<span>질문</span>
</div>
<div style={userPosts}>
<div style={userPostsNum}>{props.answer}</div>
<span>답글</span>
</div>
<div style={userPosts}>
<div style={userPostsNum}>{props.comment}</div>
<span>덧글</span>
</div>
</>
);
};
export default UserPost;<file_sep>/front/components/presentational/atoms/AbilityComponent.js
import React from 'react';
import Badge from 'react-bootstrap/Badge';
/**
* @author 우세림
* @summary 20190615 능력치 UI
* @see 정규현 // css 추가
* @see 정규현 // 조건문 추가, 시나리오 대로 자리수 별로 조회수 문자열 변경
*/
const css = {
backgroundColor:"#cd6133",
paddingBottom:"3px"
};
export const AbilityComponent = (props)=>
{
let reputation = props.val ? props.val : 0;
const strReputation = reputation.toString();
const strReputationLength = reputation.toString().length;
if(strReputationLength >9){
reputation = strReputation.substr(0, strReputationLength-9)+"G";
}else if(strReputationLength >6){
reputation = strReputation.substr(0, strReputationLength-6)+"M";
}else if(strReputationLength >3){
reputation = strReputation.substr(0, strReputationLength-3)+"K";
}
return(
<Badge id={props.id} style={css} variant="primary">능력 {reputation}</Badge>
);
}
export const AbilityComponent2 = (props)=> {
return(
<Badge style={css} variant="primary">능력 {props.val}</Badge>
);
}
export const JobContentComponent = (props) => {
return(
<Badge style={css} variant="primary">{props.val}</Badge>
);
}
export const JobPeriodComponent = (props) => {
return(
<Badge style={props.css} variant="primary">{props.val}</Badge>
);
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/AdminController.java
package com.ability.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.ability.dto.custom.AnswerRate;
import com.ability.dto.custom.BannerClickCountToday;
import com.ability.dto.custom.BannerList;
import com.ability.dto.custom.BoardListPaging;
import com.ability.dto.custom.JobBoardListPaging;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.ProjectBoardListPaging;
import com.ability.dto.custom.UserDetail;
import com.ability.dto.custom.UserListPaging;
import com.ability.dto.custom.UserMonthlyStatistics;
import com.ability.service.AdminService;
import com.ability.utils.CustomerExcelWriter;
import com.ability.utils.Pagination;
/**
* 관리자페이지 관련 컨트롤러
*
* @author 강기훈
* @address /auth/admin
*
*/
@RestController
public class AdminController {
@Autowired
AdminService adminService;
@Autowired
Pagination pagination;
public int allPostCount() {
int result = 0;
result = adminService.allPostCount();
return result;
}
public int userCount() {
int result = 0;
result = adminService.userCount();
return result;
}
public int leaveMember() {
int result = 0;
result = adminService.leaveMember();
return result;
}
public int todayJoinCount() {
int result = 0;
result = adminService.todayJoinCount();
return result;
}
public int questionCount() {
int result = 0;
result = adminService.questionCount();
return result;
}
public int freeboardCount() {
int result = 0;
result = adminService.freeboardCount();
return result;
}
public int projectCount() {
int result = 0;
result = adminService.projectCount();
return result;
}
public int accuseCount() {
int result = 0;
result = adminService.accuseCount();
return result;
}
public List<UserMonthlyStatistics> monthJoin() {
List<UserMonthlyStatistics> monthjoin = adminService.monthJoin();
return monthjoin;
}
public List<UserMonthlyStatistics> monthLeave() {
List<UserMonthlyStatistics> monthleave = adminService.monthLeave();
return monthleave;
}
public List<String> getTags() {
List<String> taglist = new ArrayList<>();
taglist = adminService.getTags();
return taglist;
}
public int getDeleteCount() {
int result = 0;
result = adminService.getDeleteCount();
return result;
}
public int noAnswerCount() {
int result = 0;
result = adminService.noAnswerCount();
return result;
}
public int jobCount() {
int result = 0;
result = adminService.jobCount();
return result;
}
public String deletePost(@RequestParam(value = "id")int id) {
int result = 0;
result = adminService.deletePost(id);
if(result>0) {
return "success";
}else {
return "false";
}
}
@RequestMapping(path = "/deleteuser", method = RequestMethod.PUT)
public String deleteUser(@RequestParam(value = "idList")ArrayList<Integer> id) {
int result = 0;
for(int i=0; i<id.size();i++) {
result+=adminService.deleteUser(id.get(i));
}
if(result>0) {
return "success";
}else {
return "false";
}
}
public String recoverUser(@RequestParam(value = "idList")ArrayList<Integer> id) {
int result = 0;
for(int i=0; i<id.size();i++) {
result+=adminService.recoverUser(id.get(i));
}
if(result>0) {
return "success";
}else {
return "false";
}
}
public String recoverPost(@RequestParam(value = "id")int id) {
int result = 0;
result = adminService.recoverPost(id);
if(result>0) {
return "success";
}else {
return "false";
}
}
public String deleteJobPost(@RequestParam(value = "id")int id) {
int result = 0;
result = adminService.deleteJobPost(id);
if(result>0) {
return "success";
}else {
return "false";
}
}
public String recoverJobPost(@RequestParam(value = "id")int id) {
int result = 0;
result = adminService.recoverJobPost(id);
if(result>0) {
return "success";
}else {
return "false";
}
}
public List<PostBoardList> getPostBoard(@RequestParam(value = "categoryid") int categoryid) {
List<PostBoardList> postList = new ArrayList<>();
postList = adminService.getPostBoard(categoryid);
return postList;
}
public List<PostBoardList> getJobBoard() {
List<PostBoardList> postList = new ArrayList<>();
postList = adminService.getJobBoard();
return postList;
}
public List<AnswerRate> getChartbar() {
List<AnswerRate> replyCount = new ArrayList<>();
List<AnswerRate> questionCount = new ArrayList<>();
replyCount = adminService.getReplyCount();
questionCount = adminService.getQuestionCount();
for(int i= 0;i<replyCount.size();i++) {
replyCount.get(i).setPostcount(Math.round((replyCount.get(i).getPostcount()/questionCount.get(i).getPostcount())*100));
}
return replyCount;
}
public BoardListPaging getboardList(@RequestParam(value = "orderby") String orderby,
@RequestParam(value = "currentpage", required = false, defaultValue = "1") String currentPage,
@RequestParam(value = "word", required = false, defaultValue = "1") String word,
@RequestParam(value = "categoryid") String categoryid
) {
BoardListPaging boardListPaging = new BoardListPaging();
Map<String, String> viewmap = new HashMap<String, String>();
int totalListCount = 0;
if (word.equals("1")) {
if(orderby.equals("3")) {
totalListCount = adminService.totalDeleteContentCount(categoryid);
}else {
totalListCount = adminService.totalContentCount(categoryid);
}
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("category_id", categoryid);
view.put("word", word);
if(orderby.equals("3")) {
totalListCount = adminService.getTotalDeleteSearchContentCount(view);
}else {
totalListCount = adminService.getTotalBoardSearchContentCount(view);
}
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", categoryid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if (word.equals("1")) {
boardListPaging.setPostBoardList(adminService.getPostList(viewmap));
} else {
viewmap.put("word", word);
boardListPaging.setPostBoardList(adminService.getSearchResult(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalListCount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
public ProjectBoardListPaging getProjectBoardList(
@RequestParam(value="orderby") String orderby,
@RequestParam(value="currentpage",
required=false,
defaultValue="1") String currentPage,
@RequestParam(value="word",
required=false,
defaultValue="1") String word,
@RequestParam(value = "categoryid") String categoryid)
{
ProjectBoardListPaging projectBoardListPaging = new ProjectBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalListCount =0;
if(word.equals("1")) {
totalListCount = adminService.totalContentCount("2");
}else {
Map<String,String> view = new HashMap<String,String>();
view.put("category_id", "2");
view.put("word", word);
totalListCount = adminService.getTotalBoardSearchContentCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if(printEnd>totalListCount) {
printEnd=totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("category", "2");
viewmap.put("start",String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if(word.equals("1")) {
projectBoardListPaging.setProjectBoardList(adminService.getProjectList(viewmap));
}else {
viewmap.put("word", word);
projectBoardListPaging.setProjectBoardList(adminService.getProjectSearchResult(viewmap));
}
projectBoardListPaging.setCurrentPage(pagination.getCurPage());
projectBoardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
projectBoardListPaging.setPageSize(pageSize);
projectBoardListPaging.setStartPageBlock(startPageBlock);
projectBoardListPaging.setTotalListCount(totalListCount);
projectBoardListPaging.setTotalPage(totalPage);
return projectBoardListPaging;
}
public JobBoardListPaging getJobBoard(@RequestParam(value="orderby")String orderby,
@RequestParam(value="currentpage",required=false,defaultValue="1")String currentPage,
@RequestParam(value="userid", required=false,defaultValue="0")String userid,
@RequestParam(value="word",required=false,defaultValue="1") String word
) {
JobBoardListPaging boardListPaging = new JobBoardListPaging();
Map<String,String> viewmap = new HashMap<String,String>();
int totalcount = 0;
if(word.equals("1")) {
totalcount = adminService.getTotalCount();
}else {
Map<String,String> view = new HashMap<String,String>();
view.put("word", word);
totalcount = adminService.getTotalSearchCount(view);
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalcount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int endpage = pagination.printEnd(pagination.getCurPage(), pageSize);
if(endpage > totalcount){
endpage=totalcount;
}
viewmap.put("orderby", orderby);
viewmap.put("userid", userid);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if(word.equals("1")) {
boardListPaging.setPostBoardList(adminService.getJobBoardList(viewmap));
}else {
viewmap.put("word", word);
boardListPaging.setCount(adminService.JobboardSearchCount(viewmap));
boardListPaging.setPostBoardList(adminService.getJobSearchResult(viewmap));
}
boardListPaging.setCurrentPage(pagination.getCurPage());
boardListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
boardListPaging.setPageSize(pageSize);
boardListPaging.setStartPageBlock(startPageBlock);
boardListPaging.setTotalListCount(totalcount);
boardListPaging.setTotalPage(totalPage);
return boardListPaging;
}
public UserListPaging gerUserList(@RequestParam(value = "orderby") String orderby,
@RequestParam(value = "currentpage", required = false, defaultValue = "1") String currentPage,
@RequestParam(value = "word", required = false, defaultValue = "1") String word
) {
UserListPaging userListPaging = new UserListPaging();
Map<String, String> viewmap = new HashMap<String, String>();
int totalListCount = 0;
if (word.equals("1")) {
if(orderby.equals("3")) {
totalListCount = adminService.leaveMember();
}else {
totalListCount = adminService.userCount();
}
} else {
Map<String, String> view = new HashMap<String, String>();
view.put("word", word);
if(orderby.equals("3")) {
totalListCount = adminService.getTotalDeleteUserSearchContentCount(view);
}else {
totalListCount = adminService.getTotalUserSearchContentCount(view);
}
}
int pageSize = pagination.getPageSize();
pagination.setCurPage(Integer.parseInt(currentPage));
int totalPage = pagination.totalPage(totalListCount, pageSize);
int startPageBlock = pagination.startPageBlock(pagination.getCurPage(), pageSize);
int printEnd = pagination.printEnd(pagination.getCurPage(), pageSize);
if (printEnd > totalListCount) {
printEnd = totalListCount;
}
viewmap.put("orderby", orderby);
viewmap.put("start", String.valueOf(pagination.printStart(pagination.getCurPage(), pageSize)));
viewmap.put("end", String.valueOf(pageSize));
if (word.equals("1")) {
userListPaging.setUserList(adminService.getUserList(viewmap));
} else {
viewmap.put("word", word);
userListPaging.setUserList(adminService.getUserSearchResult(viewmap));
}
userListPaging.setCurrentPage(pagination.getCurPage());
userListPaging.setEndPageBlock(pagination.endPageBlock(startPageBlock, pageSize, totalPage));
userListPaging.setPageSize(pageSize);
userListPaging.setStartPageBlock(startPageBlock);
userListPaging.setTotalListCount(totalListCount);
userListPaging.setTotalPage(totalPage);
return userListPaging;
}
public void excelDownload(HttpServletResponse response)
throws Exception {
List<UserDetail> list = adminService.getExcelUserList();
CustomerExcelWriter excelWriter = new CustomerExcelWriter();
//xls 파일 쓰기
excelWriter.xlsWriter(list, response);
}
public String changeRole(@RequestParam(value = "userid")int userid,
@RequestParam(value = "role_name")String role_name
) {
Map<String, Integer> viewmap = new HashMap<String, Integer>();
int result = 0;
int role = 0;
if(role_name.equals("user")) {
role = 1;
viewmap.put("role", role);
viewmap.put("userid",userid);
result = adminService.changeRole(viewmap);
}else if(role_name.equals("company")) {
role = 2;
viewmap.put("role", role);
viewmap.put("userid",userid);
result = adminService.changeRole(viewmap);
}else {
role = 3;
viewmap.put("role", role);
viewmap.put("userid",userid);
result = adminService.changeRole(viewmap);
}
if(result>0) {
return "success";
}else {
return "false";
}
}
public List<BannerList> getBanner() {
List<BannerList> bannerList = new ArrayList<BannerList>();
bannerList= adminService.getBanner();
return bannerList;
}
public BannerClickCountToday clickToday(@RequestParam(value="id") int id) {
BannerClickCountToday banner = new BannerClickCountToday();
banner= adminService.clickToday(id);
return banner;
}
}
<file_sep>/front/components/container/templatses/WriteDetail.js
import React, { Component } from 'react';
import { GridArea } from "../organisms/GridArea"
import { Container, Row, Col } from 'react-bootstrap';
import ProfileImageUserid from '../../presentational/molecules/ProfileImageUserid';
import { InputText } from '../../presentational/atoms/InputboxComponent';
import CkeditorOne from '../../presentational/atoms/CkeditorOne';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import axios from 'axios';
/**
*
* @auth 곽호원
* @summary 글쓰기 상세 페이지
*
* @auth 정진호
* @version selectmenu 반복문처리
*/
const buttoncss = {
textAlign: "right"
}
const cardcss={
margin : "0px",
padding : "0px"
}
let userid = window.sessionStorage.getItem('userid');
const WriteDetail = () =>{
return(
<>
<GridArea >
<Container >
<br />
<h3 className="title">#질의응답</h3>
<br/>
{tabpanel()}
<br/>
</Container>
</GridArea>
</>
)
}
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
export class Contents extends Component {
async onSubmit() {
const contentEndPoint = backUrl+"/question/insert?";
let title = "";
let tags = "";
let con = "";
if(document.getElementById('title') !== null || document.getElementById('title') !== "" || document.getElementById('title') !== undefined){
title = document.getElementById('title').value;
}else{
alert("제목을 입력해주세요.");
return
}
if(document.getElementById('ckvalue').innerHTML !== null || document.getElementById('ckvalue').innerHTML !== "" || document.getElementById('ckvalue').innerHTML !== undefined) {
con = document.getElementById('ckvalue').innerHTML;
}
if(document.getElementById('tags') !== null || document.getElementById('tags') !== "" || document.getElementById('tags') !== undefined) {
tags = document.getElementById('tags').value;
}
let {data : result} = await axios.get(contentEndPoint,{
params : {
userid: 58,
title: title,
content: con,
tags: tags
}
}).catch((res)=> {console.log(res)});
if(result > 0){
alert("등록 성공");
window.history.go(-1);
}else {
alert("등록실패");
}
}
render(){
return(
<Row>
<Col>
<div className="tab-content" id="nav-tabContent">
<form action="" method="post">
<div id="dropdown-item">
<ProfileImageUserid style={cardcss} writer={userid} />
</div>
<InputText id="title" content="제목을 입력해주세요" />
<InputText id="tags" content="Tags" />
<CkeditorOne />
<hr />
<div style={buttoncss}>
<ButtonComponent name="취소" />
<ButtonComponent name="등록" onclick={this.onSubmit.bind(this)} />
</div>
</form>
</div>
</Col>
</Row>
)
}
}
export const tabpanel =() => {
return(
<div className="tab-content" id="nav-tabContent">
<div key="1" className="tab-pane fade show active" id="question" role="tabpanel" aria-labelledby="board-list-question">
<Contents/>
</div>
</div>
)
}
export default WriteDetail;
<file_sep>/front/sagas/user.js
import { all, call, takeLatest, fork, put, takeEvery, delay } from 'redux-saga/effects';
import { LOG_IN_SUCCESS, LOG_IN_FAILURE, LOG_IN_REQUEST, LOG_IN_MAINTAIN_REQUEST, LOG_IN_MAINTAIN_FAILURE,LOG_IN_MAINTAIN_SUCCESS } from '../reducers/user';
import axios from 'axios';
import Router from 'next/router';
/**
* @author 정규현
* @summary 리덕스 사가를 활용한 로그인
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
function loginAPI(loginData){
return axios.post(backUrl,
{
email:loginData.inputEmail,
password:<PASSWORD>
},{
withCredentials:true,
})
.catch((res)=>{console.log(res)});
}
function* login(action){
try{
const result = yield call(loginAPI, action.data);
if(result.data.token !== null && result.data.token !== "null"){
yield put({
type:LOG_IN_SUCCESS,
data: result.data
});
localStorage.setItem("userid",result.data.user['userid']);
localStorage.setItem("email",result.data.user['email']);
localStorage.setItem("nick_name",result.data.user['nick_name']);
localStorage.setItem("user_image",result.data.user['user_image']);
localStorage.setItem("reputation",result.data.user['reputation']);
localStorage.setItem("role_name",result.data.user['role_name']);
localStorage.setItem("token",result.data.token);
localStorage.setItem("isLogin",true);
Router.push('/');
}else{
yield put({
type:LOG_IN_FAILURE,
logInErrorReason:"일치하는 회원정보가 없습니다."
});
}
}catch(e){
console.error(e);
yield put({
type:LOG_IN_FAILURE,
logInErrorReason:"일치하는 회원정보가 없습니다."
});
}
}
function* watchLogin(){
yield takeLatest(LOG_IN_REQUEST, login);
}
function loginMaintainToken(){
if ( localStorage.getItem('token')=== "null" || localStorage.getItem('token') === null ){
return;
}
return axios.get(backUrl,
{params:{
token:localStorage.getItem('token'),
}
})
.catch((res)=>{console.log(res)});
}
function* loginMaintainAPI(){
const result = yield call(loginMaintainToken);
if(result.data === "success"){
return {
token:localStorage.getItem('token'),
user:{
userid:localStorage.getItem('userid'),
role_name:localStorage.getItem('role_name'),
nick_name:localStorage.getItem('nick_name'),
isLogin:localStorage.getItem('isLogin'),
email:localStorage.getItem('email'),
user_image:localStorage.getItem('user_image'),
reputation:localStorage.getItem('reputation'),
}
}
}else{
Router.push('/user/login');
}
}
function* loginMaintain(){
try {
const result = yield call(loginMaintainAPI);
if(result === undefined || result===null || result === "null"){
return;
}
yield put({
type:LOG_IN_MAINTAIN_SUCCESS,
data:result,
})
} catch (e) {
console.error(e);
yield put({
type:LOG_IN_MAINTAIN_FAILURE,
})
}
}
function* watchLoginCheck(){
yield takeLatest(LOG_IN_MAINTAIN_REQUEST, loginMaintain)
}
export default function* userSaga(){
yield all([
fork(watchLogin),
fork(watchLoginCheck),
]);
}<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/DeveloperPostCount.java
package com.ability.dto.custom;
public class DeveloperPostCount {
private int board_count;
private int reply_count;
private int comment_count;
public int getBoard_count() {
return board_count;
}
public void setBoard_count(int board_count) {
this.board_count = board_count;
}
public int getReply_count() {
return reply_count;
}
public void setReply_count(int reply_count) {
this.reply_count = reply_count;
}
public int getComment_count() {
return comment_count;
}
public void setComment_count(int comment_count) {
this.comment_count = comment_count;
}
}
<file_sep>/front/pages/user/reputation.js
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSitemap,faCrown ,faQuestionCircle, faComments,faIdBadge } from '@fortawesome/free-solid-svg-icons';
import { Container, Row, Badge, Col } from 'react-bootstrap';
/**
* @autho 정진호
* @summary 능력치 제도 안내페이지
*/
const h3_css={
color:"#5F4B8B",
fontFamily:"sans-serif",
fontWeight:"bold",
marginLeft:"10px",
marginBottom:"30px",
fontSize:"28px"
}
const title={
marginBottom:"60px",
marginLeft:"20px",
marginTop:"30px"
}
const icon ={
width:"40px",
height:"40px",
color:"#5F4B8B",
paddingBottom:0,
paddingTop:"10px"
}
const icon2 ={
width:"30px",
height:"30px",
color:"#5F4B8B",
paddingBottom:0,
paddingTop:"5px"
}
const p = {
marginTop:"3px",
marginBottom:"5px",
fontWeight:"bold"
}
const reputation = () => {
return (
<>
<div style={title}>
<FontAwesomeIcon icon={faSitemap} style={icon}/>
<span style={h3_css}>능력치 제도</span>
</div>
<Container style={{border :"1px solid #5f4b8b",height:"400px",borderRadius:"10px",borderBottom:"1px solid #5f4b8b",width:"90%"}}>
<Row style={{height:"25%",justifyContent:"center",paddingBottom :"5px",borderBottom:"1px solid #5f4b8b"}}>
<div style={{textAlign:"center"}}>
<FontAwesomeIcon icon={faCrown} style={icon}/>
<br/>
<span style={{color : "#5f4b8b"}}><b>ABILITY</b></span><br/>
<Badge variant="light" style={{width :"60px",height:"20px",fontSize:"12px",backgroundColor :"#cd6133"}}>능력치 20</Badge>
</div>
</Row>
<Row style={{height:"25%",justifyContent:"center"}}>
<Col xs={6} style={{textAlign:"center",borderBottom:"1px solid #5f4b8b",borderRight:"1px solid #5f4b8b",paddingTop :"5px"}}>
<div>
<FontAwesomeIcon icon={faQuestionCircle} style={icon2}/> <br/>
<span style={{color : "#5f4b8b"}}><b>질의응답 답변 기준</b></span><br/>
<Badge variant="light" style={{width :"60px",height:"20px",fontSize:"12px",backgroundColor :"#cd6133"}}>능력치 20</Badge>
</div>
</Col>
<Col xs={6} style={{textAlign:"center",borderBottom:"1px solid #5f4b8b",paddingTop :"5px"}}>
<div>
<FontAwesomeIcon icon={faComments} style={icon2}/> <br/>
<span style={{color : "#5f4b8b"}}><b>채팅 접속 기준</b></span><br/>
<Badge variant="light" style={{width :"60px",height:"20px",fontSize:"12px",backgroundColor :"#cd6133"}}>능력치 10</Badge>
</div>
</Col>
</Row>
<Row style={{height:"50%",justifyContent:"center"}}>
<Col xs={6} style={{paddingTop:"3em",textAlign:"center",borderRight:"1px solid #5f4b8b"}}>
<FontAwesomeIcon icon={faIdBadge} style={icon2}/> <br/>
<span style={{color : "#5f4b8b"}}><b>개발자 모집</b></span><br/>
<p style={{marginTop:"1em"}}><b>기업 등록후 공고를 올리실 수 있습니다.</b></p>
</Col>
<Col xs={6} style={{textAlign:"center",paddingTop:"1em"}}>
<span style={{color : "#5f4b8b",marginTop:"10px"}}><b>능력치 부여 기준</b></span>
<p style={p}>글 작성 +3</p>
<p style={p}>답변 작성 +5</p>
<p style={p}>본인 게시글 추천 받을 시 +5</p>
<p style={p}>게시글 추천시 +1</p>
<p style={p}>본인 답변 추천 받을 시 +3</p>
<p style={p}>답변 추천시 +1</p>
</Col>
</Row>
</Container>
</>
)
}
export default reputation;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Visit.java
package com.ability.dto;
import java.sql.Date;
public class Visit {
private int id;
private Date visit_day;
private String visit_ip;
private String visit_refer;
private String visit_user_agent;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getVisit_day() {
return visit_day;
}
public void setVisit_day(Date visit_day) {
this.visit_day = visit_day;
}
public String getVisit_ip() {
return visit_ip;
}
public void setVisit_ip(String visit_ip) {
this.visit_ip = visit_ip;
}
public String getVisit_refer() {
return visit_refer;
}
public void setVisit_refer(String visit_refer) {
this.visit_refer = visit_refer;
}
public String getVisit_user_agent() {
return visit_user_agent;
}
public void setVisit_user_agent(String visit_user_agent) {
this.visit_user_agent = visit_user_agent;
}
@Override
public String toString() {
return "Visit [id=" + id + ", visit_day=" + visit_day + ", visit_ip=" + visit_ip + ", visit_refer="
+ visit_refer + ", visit_user_agent=" + visit_user_agent + "]";
}
}
<file_sep>/front/components/container/templatses/ChattingDetail.js
import React from 'react';
import {Container} from 'react-bootstrap';
import {ChattingProfile} from '../../presentational/molecules/ChattingProfile';
import ChattingRooms from '../../presentational/atoms/ChattingRooms';
import ChattingUser from '../../presentational/molecules/ChattingUser';
import {UserImageComponent} from '../../presentational/atoms/UserImageComponent';
import {InputTextBtn} from '../../presentational/atoms/InputboxComponent';
const chatdetail = {
display: "grid",
gridTemplateColumns:"75% 25%"
}
const chatdetail_chat = {
padding: "10px",
gridArea: "1 / 1 / 2 / 2",
minHeight: "700px",
display: "table"
}
const chatdetail_box ={
width: "100%",
minHeight: "700px",
verticalAlign: "bottom",
display: "table-cell",
overflowY: "hidden auto"
}
const chatdetail_sub = {
padding: "0px 0px 0px 10px",
gridArea: "1/2/2/3",
}
const chatdetail_text = {
textAlign: "center",
fontSize: "12px",
color: "#515151",
margin: "20px auto",
}
const chatdetail_write = {
display: "flex",
position:"fixed",
bottom:"0",
width:"100%",
height:"85px",
background:"#ede8ed",
}
const chat_userimg ={
width: "55px",
height: "55px",
margin: "15px"
}
const chat_usertext ={
width: "300px",
height: "55px",
margin: "auto"
}
const chat_logo ={
width: "140px",
height: "28px",
marginLeft :"24%",
marginTop : "2%"
}
const ChattingDetail = () => {
return(
<Container style={chatdetail}>
<div style={chatdetail_chat}>
<div style={chatdetail_box}>
<div style={chatdetail_text}>
2019년 9월 13일
</div>
<div style={chatdetail_text}>
우세림님이 입장 했습니다.
</div>
<div>
<ChattingProfile id="seri53ff5" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="se222255" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="serim09rrrrrrrrrrrrrr1222255" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="serim091222255" comments="글요소를 block 값으로 변경했기에 자동적으로 요소의 너비는 부모 너비의 100%를 차지하도록 변경된다. 만약 inline-block 과 같이 콘텐츠에 따라 유동적인 너비를 가진다면 직접 요소의 너비를 설정해야 한다. 즉, 일정한 고정된 너비를 가지는 것이 전제 조건이다." time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="se222255" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="serim09rrrrrrrrrrrrrr1222255" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="serim091222255" comments="글요소를 block 값으로 변경했기에 자동적으로 요소의 너비는 부모 너비의 100%를 차지하도록 변경된다. 만약 inline-block 과 같이 콘텐츠에 따라 유동적인 너비를 가진다면 직접 요소의 너비를 설정해야 한다. 즉, 일정한 고정된 너비를 가지는 것이 전제 조건이다." time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="se222255" comments="밥먹자 " time="17:33"/>
<ChattingProfile id="serim09rrrrrrrrrrrrrr1222255" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="serim091222255" comments="글요소를 block 값으로 변경했기에 자동적으로 요소의 너비는 부모 너비의 100%를 차지하도록 변경된다. 만약 inline-block 과 같이 콘텐츠에 따라 유동적인 너비를 가진다면 직접 요소의 너비를 설정해야 한다. 즉, 일정한 고정된 너비를 가지는 것이 전제 조건이다." time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
<ChattingProfile id="serim091222255" comments="글요소를 block 값으로 변경했기에 자동적으로 요소의 너비는 부모 너비의 100%를 차지하도록 변경된다. 만약 inline-block 과 같이 콘텐츠에 따라 유동적인 너비를 가진다면 직접 요소의 너비를 설정해야 한다. 즉, 일정한 고정된 너비를 가지는 것이 전제 조건이다." time="17:33"/>
<ChattingProfile id="seri53ff5" comments="밥먹자 "time="17:33"/>
</div>
</div>
</div>
<div xs={4} style={chatdetail_sub}>
<div>
<ChattingRooms id="wooo33" title="자유채팅방" content="아무나 와요" master="kihoon" tags="java, jsp" roomUserCount="7" />
</div>
<div>
<ChattingUser title="접속중인 이용자" id="ssad" name="홍길동" area="Korea"/>
</div>
</div>
<div style={chatdetail_write}>
<UserImageComponent css={chat_userimg}/>
<InputTextBtn css={chat_usertext} content="채팅을 입력해주세요." name={<i class="fas fa-plus"></i>}/>
<img src="../../../image/Logo.png" alt="..." style={chat_logo}></img>
</div>
</Container>
)
}
export default ChattingDetail;<file_sep>/front/components/presentational/atoms/ChattingRooms.js
import React, { Component } from 'react';
import ChatTagList from '../molecules/ChatTagList';
import { ButtonComponent } from './ButtonComponent';
import axios from 'axios';
import {chat_chatcard,chat_title,chat_usercount,chat_hr2,chat_tag_div,chat_tag,chat_btn_div} from '../../container/organisms/css/Chatting'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { UserImageComponent2 } from './UserImageComponent';
import Link from 'next/link';
import swal from 'sweetalert';
import { InputText } from './InputboxComponent';
import { Form } from 'react-bootstrap';
/**
*
* @author 강기훈
* @summary 채팅방 컴포넌트
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const chat_btn = {
width: "100%"
}
const icon ={
textAlign:"right",
}
const userList={
height:"100px",
display:"flex",
justifyContent:"center",
margin:"90px 0 30px 0"
}
const userImage={
width:"40px",
height:"40px",
marginRight:"5px"
}
class ChattingRooms extends Component{
constructor(props){
super(props);
this.deleteRoom = this.deleteRoom.bind(this);
this.getUserInfo = this.getUserInfo.bind(this);
this.state = {
title:props.title,
roomId:props.roomId,
roomUserMaxCount:props.roomUserMaxCount,
tags:props.tags,
link:props.link,
userList:[],
userCount:0,
userRole:""
}
}
async componentDidMount(){
this.setState({
userRole:localStorage.getItem('role_name'),
isDelete:0
})
await axios.get(endpoint2,{
params:{roomID: this.state.roomId}
}).then(response =>{
this.setState({
userList:response.data
})
})
await axios.get(endpoint3, {
params:{
roomID: this.state.roomId
}
}).then(response=>{
this.setState({
userCount:response.data
})
})
}
deleteRoom(){
swal({
text: "채팅방을 정말 삭제하시겠습니까?",
title: "채팅방 삭제",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
axios.get(endpoint,{
params:{
roomId:this.state.roomId
}
})
}
})
}
async getUserInfo(){
if(!localStorage.getItem('nick_name')){
swal({
text: "로그인이 필요합니다!",
title: "Login",
icon: "/static/image/Logo2.png",
buttons: true
})
}else if(this.state.userCount==this.state.roomUserMaxCount){
swal({
text: "인원이 가득 찼습니다!",
title: "인원 초과",
icon: "/static/image/Logo2.png",
buttons: true
})
}else if(localStorage.getItem('reputation')<20){
swal({
text: "능력치가 20이상이여야 입장이 가능합니다!",
title: "능력치 부족",
icon: "/static/image/Logo2.png",
buttons: true
})
}
else{
let nick_name = localStorage.getItem('nick_name');
let user_image= localStorage.getItem('user_image');
let userid = localStorage.getItem('userid');
const forms = document.chat;
window.open('',"chatting",'width=1000, height=700, toolbar=no, menubar=no,resizable=yes,location=no', "chatting");
if(forms[0].type){
forms.action = this.state.link;
forms.method ="post";
forms.target ="chatting";
forms.userid.value = userid;
forms.user_image.value = user_image;
forms.nick_name.value = nick_name;
forms.submit();
}else{
forms[this.props.index].action = this.state.link;
forms[this.props.index].method ="post";
forms[this.props.index].target ="chatting";
forms[this.props.index].userid.value = userid;
forms[this.props.index].user_image.value = user_image;
forms[this.props.index].nick_name.value = nick_name;
forms[this.props.index].submit();
}
}
}
render(){
let props = this.state;
const userLists = props.userList.map((user)=>{
return <Link href={{pathname: "/developer/page" , query:{userid: user.userid} }}><a title={user.nick_name}><UserImageComponent2 css={userImage} imagepath = {user.user_image}/></a></Link>
});
return(
<>
<div id="container" onMouseOver={(()=>{
var m;
m = document.getElementById(`${props.title}`);
if(this.state.userRole=='ROLE_ADMIN'){
m.style.visibility = "visible";
}
}).bind(this)} onMouseOut={(()=>{
var m;
m = document.getElementById(`${props.title}`);
m.style.visibility = "hidden"
}).bind(this)} >
<div style={icon}><FontAwesomeIcon icon={faTimes} id={props.title} onClick={this.deleteRoom}/></div>
<div className="chat_chatcard usercard" style={chat_chatcard}>
<div className="chat_title_div">
<div className="chat_title" style={chat_title}>{props.title}</div>
<div className="chat_usercount" style={chat_usercount}>{props.userCount} / {props.roomUserMaxCount}명</div>
</div >
<hr className="chat_hr2" style={chat_hr2}/>
<div className="chat_tag_div" style={chat_tag_div}>
<ChatTagList hashtag={props.tags} className="chat_tag" style={chat_tag} />
</div>
<div style={userList}>
{userLists}
</div>
<div className="chat_btn_div" style={chat_btn_div}>
<Form name="chat">
<InputText type="hidden" name="userid" value=""></InputText>
<InputText type="hidden" name="nick_name" value=""></InputText>
<InputText type="hidden" name="user_image" valeu=""></InputText>
</Form>
<ButtonComponent onclick={this.getUserInfo} id="enterRoom" css={chat_btn} name="입장하기"/>
</div>
</div>
</div>
</>
)}
}
export default ChattingRooms<file_sep>/front/reducers/main.js
/**
* @author 정규현
* @summary 리덕스
*/
export const initalState = {
fBoard:[],
pBoard:[],
qBoard:[],
banner: [],
};
export const MAIN_DATA_REQUEST = "MAIN_DATA_REQUEST";
export const MAIN_DATA_SUCCESS = "MAIN_DATA_SUCCESS";
export const MAIN_DATA_FAILURE = "MAIN_DATA_FAILURE";
const reducer = (state=initalState, action) =>{
switch(action.type){
case MAIN_DATA_REQUEST :{
return{
...state,
};
}
case MAIN_DATA_SUCCESS :{
return{
...state,
fBoard:[...action.data.fBoard],
pBoard:[...action.data.pBoard],
qBoard:[...action.data.qBoard],
banner: [...action.data.banner],
};
}
case MAIN_DATA_FAILURE :{
return{
...state,
};
}
default :{
return{
...state,
}
}
};
};
export default reducer;<file_sep>/front/components/container/templatses/UserPage.js
import React ,{Component} from 'react';
import {UserImageComponent2} from '../../presentational/atoms/UserImageComponent';
import TagList from '../../presentational/molecules/TagList';
import {BoardSimpleList, BoardSimpleForm} from '../../presentational/molecules/BoardSimpleList';
import UserProfile from '../../presentational/molecules/UserProfile';
import UserSub from '../../presentational/molecules/UserSub';
import UserPost from '../../presentational/molecules/UserPost';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import UserWrite from './UserWrite';
import {NavLink} from 'react-router-dom';
import axios from 'axios';
/**
*
* @author 우세림
* @summary 개발자들 상세 페이지
*
*/
const titlecss = {
fontSize : "15px"
}
const user_img = {
width: "100%"
}
const endpoint = process.env.NODE_ENV === 'production'? "?" : "?";
class UserPage extends Component {
constructor(props){
super(props);
this.state = {
userdata : [],
userdata2 : [],
userid : props.userid
}
}
async componentDidMount() {
await axios.get(endpoint, {
params : {
userid : this.state.userid,
start : 0,
end : 5
}
}).then((Response) => {
this.setState({
userdata : Response.data
});
});
await axios.get(endpoint, {
params : {
userid : this.state.userid,
start : 0,
end : 5
}
}).then((Response) => {
this.setState({
userdata2 : Response.data
});
});
}
render(){
const UserList= this.state.userdata.map((user)=>{
return <BoardSimpleList key={user.id} id={user.id} title={user.title} date_created={user.date_created} />
});
const UserList2= this.state.userdata2.map((user)=>{
return <BoardSimpleList key={user.id} id={user.id} reply_content={user.reply_content} date_created={user.date_created} />
});
if(this.state.userdata !== null){
return (
<>
<div className="user_ok">
<div className="user_image">
<UserImageComponent2 css={user_img} imagepath={this.props.user_image}/>
</div>
<div className="userContent">
<UserProfile nick_name={this.props.nick_name} reputation={this.props.reputation} name={this.props.name} email={this.props.email} user_info={this.props.user_info}/>
</div>
<div className="userSub">
<div className="userPostNum">
<UserPost question="1" answer="293" comment="1131"/>
</div>
<UserSub tel={this.props.tel} area={this.props.area} date_created={this.props.date_created} last_updated={this.props.last_updated}/>
</div>
</div>
<div className="userWrite">
<div className="userWriteTag">
<span className="userWriteTitle">
<i className="fas fa-tag"></i>
관심있는 태그
</span>
<hr/>
<TagList hashtag={this.props.tags} />
</div>
<div className="user_question">
<BoardSimpleForm css={titlecss} head="최근 작성 한 질문" postCount={UserList.length} to={<UserWrite/>}/>
{(UserList!=null&&UserList!="")?UserList: "작성한 질문 글이 없습니다."}
</div>
<div className="user_answer">
<BoardSimpleForm css={titlecss} head="최근 작성 한 답변" postCount={UserList2.length} to={<UserWrite/>}/>
{(UserList2!=null&&UserList2!="")?UserList2: "작성한 답변 글이 없습니다."}
</div>
</div>
<div className="user_md_btn">
<NavLink to={"/usermodify/"+this.props.userid} >
<ButtonComponent name="수정하기" />
</NavLink>
</div>
</>
);
}
}
}
export default UserPage;<file_sep>/front/components/presentational/molecules/RecommandComment.js
import React, {useCallback, useEffect, useState} from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faThumbsUp } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
import {Badge} from 'react-bootstrap';
/**
* @author 정규현
* @summary 추천/비추천
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const RecommendComment = (props) => {
const [likecount, setLikecount] = useState(0);
const setRecommandMain = useCallback((num)=>{
if(!localStorage.getItem('userid')){
swal({
text: "추천/비추천 기능은 로그인 후 이용이 가능합니다..",
title: num == 1?"추천 실패":"비추천 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
axios.get(backUrl,
{
params:{
seq:props.commentid,
userid:localStorage.getItem('userid'),
counta:num
}
})
.then((res)=>{
if(res.data =="success"){
swal({
text: num == 1?"댓글을 추천 했습니다.":"댓글을 비추천 했습니다.",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(num == 1? likecount+1 : likecount-1);
}else if(res.data=="plus"){
swal({
text: num == 1?"댓글을 추천 했습니다.":"댓글을 비추천 했습니다.",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(likecount-1);
}else if(res.data=="minus"){
swal("비추천 내역이 삭제 되었습니다.");
setLikecount(likecount+1);
}else{
swal({
text: "이미 투표한 댓글입니다. 투표 내역을 삭제 하시겠습니까?",
title: num == 1?"추천 실패":"비추천 실패",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((cancelok)=>{
if(cancelok){
setRecommandMain(0);
}
})
}
})
.catch((res)=>{
console.log(res);
})
},[likecount]);
useEffect(()=>{
setLikecount(props.count);
setReplyid(props.commentid);
setUserid(props.userid);
},[]);
const onClickUp = useCallback(() =>{
setRecommandMain(1);
},[likecount]);
const onClickDown = useCallback(()=>{
setRecommandMain(-1);
},[likecount]);
return (
<>
<span onClick={onClickUp}>
<Badge variant="primary" style={{marginRight:"0.5rem",backgroundColor:"#5F4B8B"}}>
<FontAwesomeIcon style={{width:"10px",height:"auto"}} icon={faThumbsUp}/>
</Badge>
</span>
{likecount}
</>
);
};
export default RecommendComment;<file_sep>/front/components/presentational/molecules/ProfileImageUserid.js
import React from 'react';
import { Card, Col} from "react-bootstrap";
import { ProfileImageComponent } from "../atoms/ProfileImageComponent";
/**
*
* @auth 곽호원
* @summary 프로필 이미지 + 아이디 보여주는 컴포넌트
*
*/
const cardcss = {
display: "grid",
width: "100%"
}
const colcss = {
marginBottom : "0.8rem",
}
const spancss = {
position: "relative",
top: "0.5rem"
}
const ProfileImageUserid = (props) => {
return (
<Card style={cardcss}>
<Col style={colcss}>
<ProfileImageComponent user_image={props.user_image} /><span style={spancss}>{props.writer}</span>
</Col>
</Card>
);
};
export default ProfileImageUserid;<file_sep>/front/components/presentational/molecules/UserSub.js
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPhoneAlt, faMapMarkedAlt, faUserClock, faEdit, faAt } from '@fortawesome/free-solid-svg-icons';
/**
*
* @author 우세림
* @summary 개발자들 상세 페이지 부가정보
*
*/
const userSubDate = {
width: "100%",
display: "inline-block",
fontSize: "13px",
marginBottom: "5px"
}
export const UserSub = (props)=> {
return (
<>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faPhoneAlt } style={{width:"1em",height:"auto"}} />
{props.tel?props.tel:"등록한 번호가 없습니다."}
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faMapMarkedAlt } style={{width:"1em",height:"auto"}}/>
{props.area?props.area:"등록한 위치가 없습니다."}
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faUserClock } style={{width:"1em",height:"auto"}}/>
{props.date_created?props.date_created:"-"} 에 가입
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faEdit } style={{width:"1em",height:"auto"}}/>
{props.last_updated?props.last_updated:"-"} 프로필 수정
</span>
</>
)
}
export const UserSub2 = (props)=> {
return (
<>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faPhoneAlt } style={{width:"1em",height:"auto"}} />
{props.tel?props.tel:"등록한 번호가 없습니다."}
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faAt } style={{width:"1em",height:"auto"}}/>
{props.company_email?props.company_email:"등록한 이메일이 없습니다."}
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faUserClock } style={{width:"1em",height:"auto"}}/>
{props.date_created?props.date_created:"-"} 에 등록
</span>
<span style={userSubDate}>
<FontAwesomeIcon icon={ faEdit } style={{width:"1em",height:"auto"}}/>
{props.last_updated?props.last_updated:"-"} 기업정보 수정
</span>
</>
)
}
export default UserSub;<file_sep>/front/components/presentational/molecules/CardNavBar.js
import React from 'react';
import {Container,Row,Col} from 'react-bootstrap';
import {ButtonComponent} from '../atoms/ButtonComponent'
import {ProfileNav} from '../atoms/ProfileNavComponent'
import {NavLink} from 'react-router-dom';
/**
*
* @author 정진호
* @summary 구인구직 컨텐츠 상단바
* @todo ,기준으로 여러 카드 생성가능 -- Nav카드 라우터 적용 완료
*/
const containercss = {
marginTop : "1.5rem"
}
const btncss ={
float :"right",
marginBottom : "0.8em",
width :"99.6px",
marginRight: "0px"
}
const CardNavBar =(props) => {
return(
<Container style={containercss}>
<Row>
<Col>
<ProfileNav css={props.css} card={props.navname} href={props.href}/>
</Col>
<Col sm={2}>
<NavLink to={props.to}>
<ButtonComponent css={btncss} name={props.btnname}/>
</NavLink>
</Col>
</Row>
<hr></hr>
</Container>
)
}
export default CardNavBar;<file_sep>/front/components/presentational/atoms/ListgroupComponent.js
import React,{Component} from 'react';
import HireList from '../molecules/HireList'
import ListGroup from 'react-bootstrap/ListGroup'
import Tab from 'react-bootstrap/Tab';
/**
* @author 정규현
* @summary 리스트 그룹을 나타내 주는 컴포넌트 입니다.
*
* @author 정진호
* @version react-bootstrap 을 이용한 Tab 나누기추가
*/
const ListgroupComponent = (props) =>{
return(
<>
<div className="list-group list-group-horizontal-sm" id="list-tab" role="tablist" style={props.css}>
<a className="list-group-item list-group-item-action active" id="list-home-list" data-toggle="list" href="#" role="tab" aria-controls="home">{props.name}</a>
<a className="list-group-item list-group-item-action" id="list-profile-list" data-toggle="list" href="#" role="tab" aria-controls="profile">{props.name1}</a>
<a className="list-group-item list-group-item-action" id="list-messages-list" data-toggle="list" href="#" role="tab" aria-controls="messages">{props.name2}</a>
</div>
</>
)
}
export const ListgroupBoot = () => {
return(
<>
<Tab.Container id="list-group-tabs-example" defaultActiveKey="#link1">
<ListGroup>
<ListGroup.Item action href="#link1">
Ability
</ListGroup.Item>
<ListGroup.Item action href="#link2">
New User
</ListGroup.Item>
<ListGroup.Item action href="#link3">
Name
</ListGroup.Item>
</ListGroup>
<Tab.Content>
<Tab.Pane eventKey="#link1">
안녕1
</Tab.Pane>
<Tab.Pane eventKey="#link2">
안녕2
</Tab.Pane>
<Tab.Pane eventKey="#link3">
안녕3
</Tab.Pane>
</Tab.Content>
</Tab.Container>
</>
)
}
export default ListgroupComponent;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/ChatController.java
package com.ability.controller;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import com.ability.dto.Chat_Message;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class ChatController {
private final SimpMessagingTemplate template;
@Autowired
public ChatController(SimpMessagingTemplate template) {
this.template = template;
}
public void hello(Chat_Message message) throws Exception {
message.setSendDate(LocalDateTime.now());
template.convertAndSend("/topic/chat/room/"+message.getRoomId(), message);
}
public void message(Chat_Message message) throws Exception {
message.setSendDate(LocalDateTime.now());
template.convertAndSend("/topic/chat/room/"+message.getRoomId(), message);
}
public void exit(Chat_Message message) throws Exception {
message.setSendDate(LocalDateTime.now());
template.convertAndSend("/topic/chat/room/"+message.getRoomId(), message);
}
public void refresh(Chat_Message message) throws Exception {
message.setSendDate(LocalDateTime.now());
template.convertAndSend("/topic/chat/room/"+message.getRoomId(), message);
}
Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
@EventListener
private void onSessionConnectedEvent(SessionConnectedEvent event) {
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
mySet.add(sha.getSessionId());
}
@EventListener
private void onSessionDisconnectEvent(SessionDisconnectEvent event) {
StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
mySet.remove(sha.getSessionId());
}
}
<file_sep>/front/components/presentational/molecules/Advertise.js
import React from 'react';
/**
* @author 정규현
* @summary 광고 영역
* @version 임시 보류 // 디자인 레이아웃 상 보류
*/
const Advertise = () =>{
return(
<>
<div style={{background:"#6c757d",width:"200px",height:"auto",marginTop:"2rem"}}>
<img src="/static/image/howon2.png" alt="banner"/>
</div>
<div style={{background:"#6c757d",width:"200px",height:"auto",marginTop:"2rem"}}>
<img src="/static/image/howon.png" alt="banner"/>
</div>
</>
);
};
export default Advertise;<file_sep>/front/pages/job/write.js
import React ,{useState,useCallback,useEffect ,useReducer} from 'react';
import { Button, Container } from 'react-bootstrap';
import { AboutJob, JobSkills, CompanyDetail, JobDetail, Benefits, Manager } from '../../components/presentational/molecules/JobOpening';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faIdBadge } from '@fortawesome/free-solid-svg-icons';
import swal from 'sweetalert';
import axios from 'axios';
import Router from 'next/router';
/**
@auth 정진호
* @summary 구인구직 게시판 글쓰기 기능 , 예외처리 ,정규표현식, 파일업로드
*/
const greyBox = {
position: 'relative',
color: '#212529',
padding: '1rem',
marginRight: '0',
marginLeft: '0',
border: '.2rem solid #ececec',
borderRadius: '8px',
}
function reducer(state,action){
return {
...state,
[action.name] : action.value
}
}
const Write = () => {
const[Form,setForm] = useReducer(reducer,{title:"",subtitle:"",period:"",job_type:"",job_time:"",job_dept:"",email:"",
phone:"",tags:"",career:"", file :""});
const {title,subtitle,period,job_type,job_time,job_dept,email,phone,tags,career} = Form;
const [dropdown,setDropdown] = useState("인원 선택");
const [data,setData] = useState("<p></p>");
const [file,setFile] = useState("");
const [filename,setFilename] = useState("");
const [fileurl,setFileurl]= useState("");
const [file1,setFile1] = useState("");
const [filename1,setFilename1] = useState("");
const [userrole,setUserrole] = useState("");
const onChangeInput = e =>{
setForm(e.target);
};
const onChangeFile = useCallback((e)=>{
let reader = new FileReader()
let files = e.target.files[0];
reader.onloadend = () => {
setFileurl(reader.result);
}
reader.readAsDataURL(files);
setFilename(e.target.files[0].name);
setFile(e.target.files[0]);
},[filename,file,fileurl]);
const onChangeFile2 = useCallback((e)=>{
setFilename1(e.target.files[0].name);
setFile1(e.target.files[0]);
},[filename1,file1]);
const dropdownEvent = useCallback((e)=>{
setDropdown(e.target.name);
},[dropdown]);
const ChangeData = useCallback((e)=>{
setData(e.editor.getData());
},[data]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const SubmitBoard = useCallback(()=>{
if(title === "" &&subtitle === "" &&period === "" &&job_type === "" &&job_time === "" &&job_dept === "" &&email === "" &&phone === "" &&tags === "" &&career === ""&&filename === "" && dropdown =="인원 선택"){
swal({
text: "빈칸은 등록이 불가능합니다.",
title: "공백 오류",
timer: "4000",
icon: "/static/image/Logo2.png"
});
return;
}else if(title === " " &&subtitle === " " &&period === " " &&job_type === " " &&job_time === " " &&job_dept === " " &&email === " " &&phone === " " &&tags === " " &&career === " "){
swal({
text: "빈칸은 등록이 불가능합니다.",
title: "공백 오류",
timer: "4000",
icon: "/static/image/Logo2.png"
});
return;
}else if(title.includes(" ") &&subtitle.includes(" ") &&period.includes(" ") &&job_type.includes(" ") &&job_time.includes(" ") &&job_dept.includes(" ") &&email.includes(" ") &&phone.includes(" ") &&tags.includes(" ") &&career.includes(" ")){
swal({
text: "빈칸은 등록이 불가능합니다.",
title: "공백 오류 errorCode-공백 2개 발견",
timer: "4000",
icon: "/static/image/Logo2.png"
});
return;
}else{
const regex = /^[ㄱ-ㅎ가-힣a-zA-Z0-9,-\s]+$/;
const regEmail = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
const regphone = /^\d{3}-\d{3,4}-\d{4}$/;
const date = new Date();
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
if((day+"").length <2){
day = "0"+day;
}
let temp = period.split("-");
let results = Number(temp[0]);
results += Number(temp[1]);
results += Number(temp[2]);
let getDates = year+month+day;
if(!regex.exec(tags)){
swal({
text: "태그는 [한글], [영문], [-]만 가능하며 콤마(,)로 구분됩니다.",
title: "태그 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}else if(!regEmail.exec(email)){
swal({
text: "이메일 형식으로 입력해주세요.",
title: "이메일 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}else if(!regphone.exec(phone)){
swal({
text: "연락처가 올바르지 않습니다.",
title: "담당자 번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}else if(eval(getDates) > eval(results)){
swal({
text: "공고 기간은 현재 날짜보다 뒤에 존재할수 없습니다.",
title: "기간 오류",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}else{
if(file !== undefined && file !== "" &&file !== null && file1 !== undefined && file1 !== "" &&file1 !== null){
let Forms = new FormData();
Forms.append('files',file);
Forms.append('files2',file1);
Forms.append('title',title);
Forms.append('userid',localStorage.getItem("userid"));
Forms.append('subtitle',subtitle);
Forms.append('job_type',job_type);
Forms.append('job_time',job_time);
Forms.append('job_dept',job_dept);
Forms.append('scale',dropdown);
Forms.append('email',email);
Forms.append('phone',phone);
Forms.append('tags',tags);
Forms.append('content',data);
Forms.append('career',career);
Forms.append('period',period);
axios({
method :'post',
baseURL : backUrl,
url :"/job/insert",
data : Forms,
headers :{'Content-Type':'multipart/form-data'}
}).then(()=>{
Router.push("/job/board");
swal({
title: "등록 성공",
text: "능력치가 +3 올랐습니다.",
icon: "/static/image/Logo2.png",
});
}).catch((xhr)=>{
console.log(xhr);
});
}else{
swal({
text: "파일이 존재하지 않습니다.",
title: "로고 or 이력서 양식 필수!",
timer: "3000",
icon: "/static/image/Logo2.png"
});
}
}
}
});
useEffect(()=>{
setUserrole(localStorage.getItem("role_name"));
},[])
return (
<>
{ userrole == "ROLE_COMPANY" ?
<>
<Container>
<TitleComponent title="구인구직 게시판">
<FontAwesomeIcon style={{width:"21px",height:"auto"}} icon={faIdBadge}/>
</TitleComponent>
<br/><AboutJob border={greyBox} onChange={onChangeInput}/>
<br/><br/><JobSkills border={greyBox} onChange={onChangeInput}/>
<br/><br/><JobDetail border={greyBox} data={data} onChange={ChangeData}/>
<br/><br/><CompanyDetail border={greyBox} dropdown={dropdownEvent} dropdownName={dropdown} onChangeFile={onChangeFile} filename={filename}
onChangeFile2={onChangeFile2} logoSrc={fileurl} filename2={filename1}/>
<br/><br/><Manager border={greyBox}/>
<br/><br/>
<Button variant="primary" type="submit" style={{float:"right"}} onClick={SubmitBoard}>
등록하기
</Button>
</Container>
<br/><br/>
</>
: "잘못된 접근입니다."
}
</>
);
}
export default Write;<file_sep>/front/components/presentational/molecules/AdminWordcloud.js
import React, { Component } from 'react';
import * as am4core from "@amcharts/amcharts4/core";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import * as am4plugins_wordCloud from "@amcharts/amcharts4/plugins/wordCloud";
import axios from 'axios';
/**
*
* @author 강기훈
* @summary admin 메인 페이지에 사용하는 워드클라우드 입니다.
*
*/
const endpoint = process.env.NODE_ENV === 'production'? "?/test/tags" : "?/test/tags";
am4core.useTheme(am4themes_animated);
class AdminWordcloud extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
let chart = am4core.create("chartdiv", am4plugins_wordCloud.WordCloud);
let tags = "";
let series = chart.series.push(new am4plugins_wordCloud.WordCloudSeries());
let title = chart.titles.create();
title.fontSize = 18;
title.marginBottom = 0;
title.fontFamily="sans-serif";
title.fontWeight="bold";
title.fill=am4core.color("#5F4B8B");
axios.get(endpoint).then(response => {
let taglist = "";
for (let i = 0; i < response.data.length; i++) {
taglist += response.data[i] + " ,";
}
for (let i = 0; i < response.data.length; i++) {
taglist += response.data[i] + " 1,";
}
for (let i = 0; i < response.data.length; i++) {
taglist += response.data[i] + " ,";
}
series.accuracy = 5;
series.step = 15;
series.rotationThreshold = 0.7;
series.maxCount = 200;
series.minWordLength = 1;
series.minValue = 0;
series.labels.template.margin(4, 4, 4, 4);
series.maxFontSize = am4core.percent(30);
series.minFontSize = am4core.percent(6);
series.colors = new am4core.ColorSet();
series.colors.passOptions = {}; // makes it loop
series.text = taglist;
series.angles = [0, -90];
series.fontWeight = "700";
this.chart = chart;
});
}
componentWillUnmount() {
if (this.chart) {
this.chart.dispose();
}
}
render() {
return (
<div style={{ border:"1px soild #e2e2e2" }}>
<div id="chartdiv" style={{ width: "100%", height: "400px", border:"1px soild #e2e2e2" }}></div>
</div>
);
}
}
export default AdminWordcloud;<file_sep>/front/components/presentational/molecules/Pagination.js
import React from "react";
import Pagination from "react-pagination-library";
import "react-pagination-library/build/css/index.css"; //for css
class PaginationUI extends React.Component {
state = {
currentPage: 1
};
changeCurrentPage = numPage => {
this.setState({ currentPage: numPage });
};
render() {
return (
<div>
<Pagination
currentPage={this.state.currentPage}
totalPages={100}
changeCurrentPage={this.changeCurrentPage}
theme="square-fill"
/>
<h2>current Page:{this.state.currentPage}</h2>
</div>
);
}
}
export default PaginationUI;<file_sep>/README.md

<br><br><br>
# ABILITY [](https://travisci.org/joemccann/dillinger)
ABILITY는 약 1개월 동안 준비한 비트캠프 3조(팀명: ABILITY)의 파이널 프로젝트입니다. 6개월 간의 배운 것을 총 활용해서 만든 프로젝트이며, 6명의 팀원이 함께 만들었습니다. 하지만, 뷰 라이브러리로 적용한 React는 별도의 스터디를 병행하며 진행한 것이며, 따로 배우지는 않았습니다. 그렇기 때문에 처음 리액트 설계부분에 부족함이 있어, 서버사이드 렌더링을 일부에만 적용했다는가, 리덕스나 리덕스 사가를 모든 페이지에 적용하지 못한 문제가 있습니다. 하지만, 준비 기간이 2개월(실제 코딩기간 45일) 동안 스터디를 병행하며, 한 사이트를 만들었다는 것을 높게 평가해 주시면 좋겠습니다.
<br>
## 프로젝트 개요
우리 프로젝트는 한국형 Stack overflow를 지향하고 있습니다.
여러가지 트랜드를 반영한 최신 기술과 고급 기술들을 많이 적용해서 만든 기술 중심형 프로젝트입니다.
사용자들은 질문을 통해 개발에 대한 해결방안을 얻고, 답변을 통해 일정한 포인트(능력치)를 얻을 수 있는 사이트 입니다.또한 사용자들은 페이지를 통해 구인을 원하는 기업에 지원할 수 있고, 사용자 간의 채팅도 가능하며, 본인이 만든 프로젝트 영상을 다른 사용자들에게 보여줄 수 있는 공간을 제공합니다.
<br>
## 프로젝트 주제 선정 배경
1. 한국에는 철저히 개발자를 위하며, 질문과 답변 중심의 커뮤니티가 부족하다.
2. 실제로 우리가 개발을 하면서 필요한 정보를 **쉽게** 찾을 수 있는 사이트가 필요하다.
3. 내가 만든 프로젝트를 평가 받거나 자랑할 수 있는 공간이 없다.
4. 6개월 동안 배운 기술을 최대한으로 활용하여 사이트 구축을 할 수 있다.
<br>
## Target
- 초기 : 개발 입문자 - 영어에 약하고 원하는 정보를 찾을 수 있는 능력이 부족하다.
- 그 이후 : 개발 입문자 & 숙련된 개발자 - 초기부터 사용하고 있는 개발자들을 중심으로 꾸준히 사이트 규모를 늘려나가며, 많은 수의 질문과 답변을 기반으로 더 많은 개발자들을 모은다.
<br>
## 프로젝트 기본 설정
- 기본색 : #5F4B8B(울트라 바이올렛), #F3F3F3(화이트), #242729 (검정)
- line-height : 1.3
- 기본 폰트 : font-family : Noto Sans,Arial, "Helvetica Neue", Helvetica, sans-serif
- 텍스트 에디터 폰트, 코드 폰트 : hack, Arial, "Helvetica Neue", Helvetica, sans-serif
- 연속된 버튼은 다른 색으로 한다.
- 메인 버튼이나 중요한 버튼은 #5F4B8B 색상(PRIMARY를 강제로 색상 변경 - 전역)으로 한다.
- 대부분의 버튼은 "오른쪽"에 위치 시킨다.(모바일 사용자의 편의성 극대화)
<br>
## URL : www.team-ability.com
<br>
## ABILITY 프론트엔드 사이트 로드맵

<br>
## 통계 데이터 활용

<br>
- 메인 배너에 대한 클릭 수 또한 통계 데이터로 수집하며, 광고 수익 구조는 CPC 방식으로 계산 해보았습니다.
<br>

<br>
## 아토믹 디자인 패턴 적용
리액트로 처음 프로젝트를 진행하다보니, 프로젝트 시작전 폴더 구조의 분할에 대한 공부를 했습니다.. 그 중에서 아모믹 디자인 패턴을 적용하여 폴더 구조를 "atoms/, molecules/, organisms/, templates/, pages/"로 구분하였고, 실제로 느낀 장점은 컴포넌트 분류가 일정한 패턴이라 필요한 컴포넌트를 찾아서 재사용하기 좋았습니다.

<br>
## NEXT 프레임 워크 사용
코드 스플리팅 및 prefetch, 원활한 SSR 적용을 위한 next 프레임워크 사용

<br>
## IE 최적화

<br>
## 서버사이드 렌더링(SSR)

<br>
## 서버사이드 렌더링(SSR) 개선
기존의 서버 사이드 렌더링의 문제는 데이터만 서버에서 렌더링이 먼저 되기 때문에, 최초 접속시 혹은 새로 고침시 CSS가 깨지거나 흔들리는 현상이 나타났습니다. 여기에 대한 개선책으로 styled-components를 사용하고 styled-components에 SSR을 적용했습니다.

<br>
## Redux-Reducer 설계

<br>
## Redux-saga를 활용한 로그인 유지 기능

<br>
## EsLint 사용
팀원의 코딩스타일을 통일하기 위해 사용(프론트에서는 react-recommand, 백엔드 node.js에서는 airbnb 적용)

<br/>
## ABILITY 백엔드 사이트 로드맵

<br>
## DATABASE ERD

<br>
## MySQL 저장 프로시저와 스케줄러

<br>
## MySQL Trigger

<br>
## Mybatis

<br>
## CLOUD COMPUTING

<br>
## 배포전 번들 사이즈 분석

<br>
## 데몬 & 무중단 배포

<br>
## 로봇 배제 표준

<br>
## 형상관리 및 도구
Git - SourceTree, BASH, ZSH
<br>
Git Commit Message Convention - 첫 문장(이하 '타이틀')은 영어로 작성한다, 타이틀은 동사로 시작하며 명령문을 유지한다, 타이틀과 본문은 한줄의 간격을 둔다, 본문은 한글로 작성해도 된다

<br>
## 이슈 관리
프로젝트 도중에는 깃을 통한 이슈관리를 시간 관계상 진행하지 않았고, 모든 이슈는 Slack 채널을 활용하며 이슈를 공유했습니다.
<br>
하지만, 프로젝트가 종료된 이후에는 이슈 관리 부분을 git의 issues를 활용하여 관리했습니다.

<br>
## 구글 애널리틱스에 의한 추적
사이트 방문자 추적을 위한 구글 애널리틱스를 적용했습니다. 물론 직접 로직을 만들어 구현할 수도 있었지만, 일전에 미니 프로젝트에서 구현해본 결과, 구글 애널리틱스를 활용하는 것이 정확도 측면이나 효율적인 측면에서 더 우수했습니다. 또한 직접 구현하는 것뿐만 아니라, 좋은 기술 혹은 모듈, 라이브러리 등을 찾아서 사용하는 것도 개발자의 중요한 능력 중 하나라고 판단되었습니다.

<br>
## ABILITY 구성원 : 정규현(리더), 신선하, 강기훈, 정진호, 곽호원, 우세림
- 정규현 : https://github.com/JungKyuHyun/ , https://blog.naver.com/ajdkfl6445
- 신선하 : https://github.com/sunha-shin/
- 강기훈 : https://github.com/alkalisummer
- 정진호 : https://github.com/jhguma
- 곽호원 : https://github.com/kwakhowon
- 우세림 : https://github.com/selim0915
<br>
## 공통 업무
기존 프로젝트 분석(프로젝트 및 PPT) 및 문서화, 목업툴을 통한 페이지별 디자인 및 레이아웃 구성, 시나리오 수정
<br>
## 구성원별 수행 업무






<file_sep>/front/components/presentational/atoms/CkeditorComponent.js
import React from 'react';
import CKEditor from 'ckeditor4-react';
/**
*
* @auth 곽호원
* @summary CkEditor 컴포넌트
*
*/
export const CkeditorComponent = (props) =>
<CKEditor data={props.data}
config = {{
toolbar : [['Bold', 'Italic', 'Strike','Blockquote','uploadImage','-', 'Styles' ,'Format', '-','Image', 'Table', 'Indent','-','NumberedList', 'BulletedList', 'Clipboard', 'Undo','Redo', 'editing','HorizontalRule','SpecialChar','Source']],
extraPlugins : 'codesnippet'
}}
/><file_sep>/front/components/presentational/molecules/ModifyComment.js
import React, {useState, useCallback, useEffect} from 'react';
import axios from 'axios';
import {AbilityComponent} from '../atoms/AbilityComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faReply,faThumbsUp,faThumbsDown } from '@fortawesome/free-solid-svg-icons';
import Link from 'next/link';
import {Badge} from 'react-bootstrap';
/**
* @author 정규현
* @param {*} props
*/
const inputCss = {
borderRadius:"10px",
border:"1px solid #5F4B8B",
padding:"0.3rem",
marginRight:"0.5rem"
};
const ModifyComment = (props) =>{
const [isModify, setIsModify] = useState(false);
const [modifyComment, setModifyComment] = useState("");
useEffect(()=>{
setModifyComment(props.modifyComment);
},[])
const onClickReplyModifyOk = useCallback((e)=>{
setIsModify(false);
},[isModify]);
const onChangeModifyComment = useCallback((e) =>{
setModifyComment(e.target.value);
},[modifyComment]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const onClickReplyCommentDelete = useCallback((commentid)=>{
swal({
text: "삭제한 댓글은 절대 복구할 수 없습니다. 댓글을 정말 삭제하시겠습니까?",
title: "삭제 경고",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
axios.get(backUrl,
{
params:{
seq:commentid
}
})
.then((res)=>{
if(res.data=="success"){
swal("답변이 삭제 되었습니다.");
setCommentReset(commentid);
}else{
swal("[Error0577] 답변 삭제 실패");
}
})
.catch((res)=>{
console.log("오류발생",res);
})
}
})
},[]);
return(
<>
{props.isModify
?
<>
<input style={inputCss} type={"string"}
value={props.data.comment_content}
onChange={onChangeModifyComment}
/>
<span style={{color:"#F79F1F",marginRight:"0.3rem"}} onClick={onClickModifyCancel}>
<small><b>[취소]</b></small>
</span>
<span style={{color:"#0652DD"}} onClick={onClickReplyModifyOk}>
<small><b>[수정 완료]</b></small>
</span>
</>
:
<>
<Col md={10}>
<div style={{marginLeft:"3rem"}}>
{props.data.comment_content}
<i> - <small>
<Link href={{pathname:"/developer/page",query:{userid:props.data.userid}}}>
<a>{props.data.nick_name}</a>
</Link>
</small>
</i>
<small>
<AbilityComponent val={props.data.reputation}/>
</small>
<i>
<small>({props.data.date_created} 작성)</small>
</i>
</div>
</Col>
<Col md={2}>
<div style={{marginRight:"0.3rem",marginBottom:"0.3rem"}}>
<span onClick={onClickCommentPlus}>
<Badge variant="primary" style={{marginRight:"0.5rem",backgroundColor:"#5F4B8B"}}>
<FontAwesomeIcon style={{width:"10px",height:"auto"}} icon={faThumbsUp}/>
</Badge>
</span>
{props.data.counta}
<span onClick={onClickCommentMinus}>
<Badge variant="secondary" style={{marginLeft:"0.5rem"}}>
<FontAwesomeIcon style={{width:"10px",height:"auto"}} icon={faThumbsDown}/>
</Badge>
</span>
</div>
<span style={{color:"#F79F1F",marginRight:"0.3rem"}} onClick={()=>onClickReplyCommentDelete(props.data.id)}>
<small><b>[삭제]</b></small>
</span>
<span style={{color:"#0652DD"}} onClick={()=>setIsModify(true)}>
<small><b>[수정]</b></small>
</span>
</Col>
</>
}
</>
);
};
export default ModifyComment;<file_sep>/front/components/presentational/atoms/MainCardComponent.js
import React from 'react';
import {Card, Col,Row} from 'react-bootstrap';
import Link from 'next/link';
import { AbilityComponent } from './AbilityComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faShare } from '@fortawesome/free-solid-svg-icons';
import TimeAgo from 'react-timeago';
import ko from 'react-timeago/lib/language-strings/ko';
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter';
const formatter = buildFormatter(ko);
/**
* @author 정규현
* @summary 메인 index 페이지에 들어갈 카드 입니다.
*/
const MainCardComponent = (props) =>{
if(props.data){
const contents = props.data.map((boardData)=>
<div key={boardData.id.toString()}>
<Card.Text style={{margin:"0"}}>
<b>[{props.category}]</b>
<Link href={{pathname: props.titlepath, query:{seq:boardData.id}}}>
<a>{boardData.title}</a>
</Link>
<small>
-
<Link href={{pathname:"/developer/page",query:{userid:boardData.userid}}}>
<a>{boardData.nick_name}</a>
</Link>
<AbilityComponent val={boardData.reputation}/>
- <i><TimeAgo date={boardData.date_created} formatter={formatter} /></i>
</small>
</Card.Text>
<hr style={{margin:"0.3rem"}}/>
</div>
);
return(
<>
<div className="text-right" style={{marginBottom:"0.3rem",marginRight:"0.3rem"}}>
<Link href={props.path}>
<a>
<b>
{props.more} 더보기 <FontAwesomeIcon style={{width:"14px",height:"auto"}} icon={faShare}/>
</b>
</a>
</Link>
</div>
<Card bg="light" style={{ width: '100%', height:'100%' }}>
<Card.Body style={{ paddingRight:"15px", paddingLeft:"15px", backgroundColor:"white"}}>
{contents}
</Card.Body>
</Card>
</>
);
}else{
return(
" "
)
}
};
export const MainVideoCardComponent = (props) =>{
if(props.data){
const contents = props.data.map((boardData)=>
<Col sm={12} md={4} key={boardData.id.toString()}>
<div className="embed-responsive embed-responsive-16by9 m-b-2" style={{marginTop:"0.5rem"}}>
<iframe className="embed-responsive-item"
src={"https://www.youtube.com/embed/"+boardData.file_path}></iframe>
</div>
</Col>
);
return(
<>
<div className="text-right" style={{marginBottom:"0.3rem",marginRight:"0.3rem"}}>
<Link href={props.path}>
<a>
<b>
{props.more} 더보기 <FontAwesomeIcon style={{width:"14px",height:"auto"}} icon={faShare}/>
</b>
</a>
</Link>
</div>
<div style={{ width: '100%', height:'100%' }}>
<div style={{ paddingRight:"15px", paddingLeft:"15px", backgroundColor:"white"}}>
<Row style={{border:"1px solid #c6badf",padding:"0.5rem",borderRadius:"10px"}}>
{contents}
</Row>
</div>
</div>
</>
);
}else{
return(
" "
)
}
};
export default MainCardComponent;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dao/MainMapper.java
package com.ability.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.ability.dto.Banner;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.ProjectBoardList;
public interface MainMapper {
public List<String> getPostBoardAllTags();
public List<String> getJobBoardAllTags();
public List<String> getUserDetailAllTags();
public int setTags(@Param("tags") String tags,@Param("count") int count);
public List<PostBoardList> getCommunityList(Map<String, String> view);
public List<ProjectBoardList> listSelect(Map<String, String> view);
public List<Banner> getBannerList();
}
<file_sep>/front/components/presentational/molecules/HireJobDescription.js
import React from 'react';
import {Col, Row,Container} from 'react-bootstrap';
/**
*
* @auth 곽호원
* @summary 회사의 직무 소개 컴포넌트
*
*/
const comTitlecss ={
marginLeft : "1%",
marginTop : "3%",
fontSize : "1.3em"
}
const comExDescriptioncss = {
marginLeft : "1%",
fontSize : "1em"
}
const HireJobDescription = (props) => {
return (
<Container style={{}}>
<Row style={comTitlecss}>
업무 설명서
</Row>
<hr />
<Row style={comExDescriptioncss}>
<div dangerouslySetInnerHTML={ {__html: props.jobDescription} } ></div>
</Row>
</Container>
);
};
export default HireJobDescription;<file_sep>/front/components/presentational/molecules/VideoCard.js
import React from 'react';
import { Card, Badge } from 'react-bootstrap';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faThumbsUp, faEye } from '@fortawesome/free-regular-svg-icons';
/**
* @author 신선하
* @summary 비디오 카드 컴포넌트
* @usage <VideoCard title="" text="" writer="" hits="" time=""/>
**/
const cardTitle= {
marginBottom: '0rem',
lineHeight:'130%',
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
WebkitLineClamp: '2', /* 라인수 */
WebkitBoxOrient: 'vertical',
wordWrap:'break-word',
marginBottom:'0.75rem',
minHeight: "52px"
};
const cardTags= {
marginBottom: '1.25rem',
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
WebkitLineClamp: '1', /* 라인수 */
WebkitBoxOrient: 'vertical',
wordWrap:'break-word',
minHeight: "18.44px"
};
const cardText= {
height:'2.275rem',
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
WebkitLineClamp: '2', /* 라인수 */
WebkitBoxOrient: 'vertical',
wordWrap:'break-word',
marginBottom:'0.75rem'
};
const VideoCard=(props)=>{
const taglist = [];
if(props.tags !== null
&& props.tags !== ""
&& props.tags !== undefined
&& props.tags !== "null"){
const list = props.tags.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
}
const tags = taglist.map((value,index)=>(
<Badge key={index}
variant="light"
style={{marginRight : "0.2rem"}}
>
{value}
</Badge>
))
return(
<>
<Card style={{width:'17.875rem'}} id="videocard">
<Card.Img variant="top" src={props.image}/>
<Card.Body>
<Card.Title style={cardTitle}>
<span>
<Link
href={{pathname:props.path,
query: {seq : props.seq}
}}
as={"/content/"+props.seq}
eplace
>
<a>
{props.title}
</a>
</Link>
</span>
</Card.Title>
<Card.Text style={cardTags}>
{tags}
</Card.Text>
</Card.Body>
<Card.Footer>
<small className="text-muted">
<Link
href={{ pathname : "/developer/page",
query :{userid : props.userid ? props.userid : ""}}
} as={"/developer/page"+props.userid}>
<a>{props.id}</a>
</Link><br/>
<FontAwesomeIcon
icon={ faEye }/>
{props.view_count}
<FontAwesomeIcon
icon={ faThumbsUp }/>
{props.likecount}
{props.date_created}
</small>
</Card.Footer>
</Card>
</>
);
}
export default VideoCard;<file_sep>/front/pages/admin/board.js
import React from 'react';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import Users from '../../components/container/organisms/users';
import DashBoard from '../../components/container/organisms/dashboard';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserCog } from '@fortawesome/free-solid-svg-icons';
import FreeBoard from '../../components/container/organisms/freeboard';
import Question from '../../components/container/organisms/question';
import Project from '../../components/container/organisms/project';
import Job from '../../components/container/organisms/job';
import BannerRegister from '../../components/container/organisms/BannerRegister';
import BannerInfo from '../../components/container/organisms/bannerinfo';
/**
* @author 신선하
* @summary
* @see 정규현 리펙토링/ 반응형
*/
const Board =()=>{
return (
<>
<TitleAndButtonComponent title="관리자 페이지">
<FontAwesomeIcon icon={faUserCog} style={{width:"1em",height:"auto"}}/>
</TitleAndButtonComponent>
<Tabs>
<TabList>
<Tab>대쉬보드</Tab>
<Tab >게시판 관리</Tab>
<Tab>회원 관리</Tab>
<Tab>배너 등록</Tab>
<Tab>배너 조회</Tab>
</TabList>
<TabPanel>
<DashBoard/>
</TabPanel>
<TabPanel>
<Tabs>
<TabList>
<Tab>질의응답</Tab>
<Tab>자유게시판</Tab>
<Tab>프로젝트</Tab>
<Tab>구인구직</Tab>
</TabList>
<TabPanel>
<Question/>
</TabPanel>
<TabPanel>
<FreeBoard/>
</TabPanel>
<TabPanel>
<Project/>
</TabPanel>
<TabPanel>
<Job/>
</TabPanel>
</Tabs>
</TabPanel>
<TabPanel>
<Users/>
</TabPanel>
<TabPanel>
<BannerRegister/>
</TabPanel>
<TabPanel>
<BannerInfo/>
</TabPanel>
</Tabs>
</>
);
};
export default Board;
<file_sep>/front/components/presentational/molecules/ReplyComment.js
import React, { Component } from "react";
import { ProfileImageComponent } from "../atoms/ProfileImageComponent";
import { Col, Row } from "react-bootstrap";
import axios from 'axios';
import { ReplyComponent } from "../atoms/ReplyComponent";
import { ButtonComponent2 } from "../atoms/ButtonComponent";
const col = {
margin : "0px",
padding : "0px"
}
const row = {
width : "100%"
}
const font = {
padding : "0px",
margin : "0px",
paddingTop : "20px",
paddingLeft : "0px",
textAlign : "left",
border : "0"
}
const inputcss = {
width : "100%",
height : "36px"
}
const textcss = {
width : "100%",
height : "120%",
backgroundColor : "#e6e6e6",
border : "1px solid #c6badf",
paddingLeft : "20px",
font : "5f4b8b"
}
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
class ReplyComment extends Component {
constructor(props) {
super(props);
const user_image = localStorage.getItem('user_image');
const nick_name = localStorage.getItem('nick_name');
const userid = localStorage.getItem('userid');
this.state = ({
comments: [],
user_image : user_image,
nick_name : nick_name,
userid : userid,
values : "",
comment_content : "",
comment_content2 : "",
comment_content3 : "",
modify : false,
reply_id : "",
id : "",
replyOwner : "",
targetid : ""
});
this.deleteComment = this.deleteComment.bind(this);
this.insertComment = this.insertComment.bind(this);
this.getCommentList = this.getCommentList.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
this.modifyCommentOk = this.modifyCommentOk.bind(this);
this.onChangeContent = this.onChangeContent.bind(this);
this.modifyComment = this.modifyComment.bind(this);
this.getCommentListOne = this.getCommentListOne.bind(this);
this.onModifyCancel = this.onModifyCancel.bind(this);
}
async componentDidMount() {
await this.getCommentList();
}
async getCommentList() {
await axios.get(backUrl, {
params: {
seq: this.props.seq,
reply_id : this.props.reply_id
}
}).then((response) => {
this.setState({
comments: response.data
})
})
}
onChangeHandler(e) {
this.setState({
values : e.target.value
})
}
async getCommentListOne(e){
await axios.get(backUrl, {
params : {
id : e.target.id
}
}).then((response)=>{
this.setState({
replyOwner : response.data.userid,
comment_content : response.data.comment_content,
modify : true
})
})
}
async insertComment() {
let data = this.props.seq;
let reply_id = this.props.reply_id;
const replyCommentpoint = backUrl;
const userid = localStorage.getItem('userid');
await axios.get(replyCommentpoint, {
params: {
userid: userid,
seq: data,
comment_content: this.state.values,
reply_id : reply_id
}
}).then(() => {
this.getCommentList();
this.setState({
values : ""
})
});
}
async deleteComment(e) {
let id = e.target.id;
const willDelete = await swal({
title: "삭제 하시겠습니까?",
text: "해당 댓글을 삭제하시겠습니까?"
});
if(willDelete){
await axios.get(backUrl, {
params: {
id: id
}
}).then(() => {
swal("삭제완료 해당 댓글을 삭제 하였습니다.");
this.getCommentList();
})
}
}
onChangeContent(e){
this.setState({
comment_content : e.target.value
})
}
async modifyComment(e){
await axios.get(backUrl, {
params : {
id : e.target.id
}
}).then((response)=>{
this.setState({
targetid : response.data.id,
replyOwner : response.data.userid,
comment_content : response.data.comment_content,
modify : true
})
})
}
async modifyCommentOk(e){
await axios.get(backUrl,{
params : {
id : e.target.id,
comment_content : this.state.comment_content
}
}).then((response)=>{
this.setState({
modify : false,
comment_content : this.state.comment_content,
})
this.getCommentList();
})
}
onModifyCancel(){
this.setState({
modify : false
})
}
render() {
let comment = this.state.comments;
if (comment.length > 0) {
return (
<>
<div style={{backgroundColor:"#d6c286", backgroundColor:"rgba( 232, 226, 201, 0.3)",borderTop :"1px solid #e2e2e2"}}>
<div style={row}>
<Col xs={12} style={col}>
{comment.map((comment, index) => {
return (<ReplyComponent
onclick={this.deleteComment}
userids = {this.state.userids}
id={comment.id}
userid={comment.userid}
seq={this.props.seq}
reply_id = {comment.reply_id}
user_image={comment.user_image}
nick_name={comment.nick_name}
date_created={comment.date_created}
onChangeInput={this.onChangeContent}
modifyCommentOk={this.modifyCommentOk}
replyOwner = {this.state.replyOwner}
modify={this.state.modify}
comment_content={comment.comment_content}
comment_content2={this.state.comment_content2}
comment_content3={this.state.comment_content3}
modifyComment={this.modifyComment}
getCommentListOne={this.getCommentListOne}
targetid={this.state.targetid}
counta = {comment.counta}
onModifyCancel={this.onModifyCancel}
userscounta = {this.state.userscounta}
key={index} />
)
})}
</Col>
</div>
{this.state.userid != undefined && this.state.userid != "" && this.state.userid != 0 ?
<div style={{display:"flex", backgroundColor:"#d6c286", backgroundColor:"rgba( 232, 226, 201, 0.3)"}}>
<Col xs={2} style={{verticalAlign:"middle",textAlign:"center",paddingTop:"20px"}}>
<ProfileImageComponent css={{width:"32px",height:"32px",border:"1px solid #CDCECF",margin:"0px!",marginRight: "0.5rem"}} user_image={this.state.user_image} />
<br/>{this.state.nick_name}
</Col>
<Col xs={9} style={{paddingTop:"22px",marginBottom:"1.2rem"}}>
<input maxLength="255" style={inputcss} type="text" id="replyComment" placeholder="댓글을 입력해주세요" onChange={this.onChangeHandler} value={this.state.values}/>
</Col>
<Col xs={1} style={font}>
<ButtonComponent2 css={{color:"#762873", border :"0.5px solid #762873"}} name="작성" onclick={this.insertComment}/>
</Col>
</div>
:
<div style={{backgroundColor:"#f2f2f2" , padding:"15px" , border:"1px solid #c6badf"}}>
<Row>
<Col md={1}>
<ProfileImageComponent css={{width:"32px",height:"32px",border:"1px solid #CDCECF",margin:"0px!",marginRight: "0.5rem" ,marginTop:"0.3rem", marginLeft:"0.5rem"}} user_image={this.state.user_image} />
</Col>
<Col md={11}>
<input type="text" value="댓글은 로그인 후 입력할 수 있습니다" readOnly style={textcss}/>
</Col>
</Row>
</div>
}
</div>
</>
)
} else {
return (
<>
<div style={{backgroundColor:"#d6c286", backgroundColor:"rgba( 232, 226, 201, 0.3)",borderTop :"1px solid #e2e2e2"}}>
<div style={row}>
<div style={{display:"flex"}}>
<Col xs={2} style={{verticalAlign:"middle",textAlign:"center",paddingTop:"20px"}}>
<ProfileImageComponent css={{width:"32px",height:"32px",border:"1px solid #CDCECF",margin:"0px!",marginRight: "0.5rem"}} user_image={this.state.user_image} />
<br/>
{this.state.nick_name}
</Col>
<Col xs={9} style={{paddingTop:"22px",marginBottom:"1.2rem"}}>
<input style={inputcss} type="text" id="replyComment" placeholder="댓글을 입력해주세요" onChange={this.onChangeHandler} value={this.state.values}/>
</Col>
<Col xs={1} style={font}>
<ButtonComponent2 css={{color:"#762873", border :"0.5px solid #762873"}} name="작성" onclick={this.insertComment}/>
</Col>
</div>
</div>
</div>
</>
)
}
}
};
export default ReplyComment;<file_sep>/front/pages/question/modify.js
import React, { Component } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import ProfileImageUserid from '../../components/presentational/molecules/ProfileImageUserid';
import { InputText } from '../../components/presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import swal from 'sweetalert';
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
/**
*
* @auth 곽호원
* @summary 글쓰기 수정 페이지
*
* @auth 정진호
* @version selectmenu 반복문처리
*/
const buttoncss = {
textAlign: "right"
}
const cardcss = {
margin: "0px",
padding: "0px"
}
let data = "";
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const plistEndPoint = backUrl;
class Modify extends Component {
constructor(props) {
super(props);
this.state = {
seq: 0,
postlist: [],
title: this.props.title,
tags: '',
content: '',
data: '<p></p>',
userid : ""
};
this.onChangeCk = this.onChangeCk.bind(this);
this.onChangetitle = this.onChangetitle.bind(this);
this.onChangetags = this.onChangetags.bind(this);
this.onClickBack = this.onClickBack.bind(this);
}
onClickBack(){
Router.push('/question/content?seq='+Router.query['seq'])
}
async componentDidMount() {
this.setState({
seq : Router.query['seq'],
userid : localStorage.getItem("userid")
})
data = Router.query['seq'];
await axios.get(plistEndPoint, {
params: {
seq: data
}
}).then((response)=> {
this.setState({
title : response.data.title,
tags : response.data.tags,
data : response.data.content,
postlist : response.data
});
}); // ERROR;
}
onChangeCk(e){
this.setState({
data : e.editor.getData()
})
}
onChangetitle(e){
this.setState({
title : e.target.value
})
}
onChangetags(e){
this.setState({
tags : e.target.value
})
}
async onSubmit() {
const contentEndPoint = backUrl;
let result = 0;
if(this.state.title !== "" && this.state.title !== " " && !this.state.title.includes(" ") && this.state.data !== "<p></p>" && this.state.tags !== " " && !this.state.tags.includes(" ")){
let Forms = new FormData();
Forms.append("tags",this.state.tags);
Forms.append("title",this.state.title);
Forms.append("seq",Router.query['seq']);
Forms.append("content",this.state.data);
await axios({
method :'put',
baseURL : backUrl,
url :"/question/modifyWriteOk",
data : Forms
}).then((response)=>{
result = response.data
if (result > 0) {
Router.push('/question/content?seq='+Router.query['seq']);
} else {
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
}
}).catch((xhr)=>{
console.log(xhr);
});
}else{
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
return
}
}
render() {
const { postlist } = this.state;
if (postlist !== null && this.state.data !=="<p></p>" && this.state.userid !== "") {
return (
<>
{postlist.userid == this.state.userid ?
<Container >
<br />
<h3 className="title">#질의응답</h3>
<br />
<div className="tab-content" id="nav-tabContent">
<div key="1" className="tab-pane fade show active" id="question" role="tabpanel" aria-labelledby="board-list-question">
<Row>
<Col>
<div className="tab-content" id="nav-tabContent">
<form action="" method="post">
<div id="dropdown-item">
<ProfileImageUserid style={cardcss} writer={postlist.nick_name} />
</div>
<InputText id="title" value={this.state.title} onChange={this.onChangetitle} maxLength="35"/>
<small style={{position:"absolute",left:"85%",top:"89px", color:"grey"}}>({this.state.title.length}/35)</small>
<InputText id="tags" value={this.state.tags} onChange={this.onChangetags} maxLength="30"/>
<small style={{position:"absolute",left:"85%",top:"159px", color:"grey"}}>({this.state.tags.length}/30)</small>
<CkeditorOne2 id="content" data={this.state.data} onChange={this.onChangeCk} />
<hr />
<div style={buttoncss}>
<ButtonComponent name="이전" variant="info" onclick={this.onClickBack} />
<ButtonComponent name="수정" onclick={this.onSubmit.bind(this)} />
</div>
</form>
</div>
</Col>
</Row>
</div>
</div>
<br />
</Container>
: "잘못된 접근입니다."
}
</>
)
} else {
return (
<>
<h6> </h6>
</>
)
}
}
}
export default Modify;
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/BannerList.java
package com.ability.dto.custom;
import java.util.Date;
public class BannerList {
private int id;
private int click_count;
private String image;
private Date date_created;
private String title;
private String url;
private String client;
private String banner_desc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getClick_count() {
return click_count;
}
public void setClick_count(int click_count) {
this.click_count = click_count;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getBanner_desc() {
return banner_desc;
}
public void setBanner_desc(String banner_desc) {
this.banner_desc = banner_desc;
}
}
<file_sep>/front/pages/question/write.js
import React, {useState,useEffect,useCallback } from 'react';
import { Container } from 'react-bootstrap';
import ProfileImageUserid from '../../components/presentational/molecules/ProfileImageUserid';
import { InputText } from '../../components/presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import swal from 'sweetalert';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
/**
*
* @auth 곽호원
* @summary 글쓰기 상세 페이지
*
* @auth 정진호
* @version selectmenu 반복문처리했음
*/
const buttoncss = {
textAlign: "right"
}
const cardcss={
margin : "0px",
padding : "0px"
}
const Write = () =>{
const [isuserid,setIsUserid] = useState(0);
const [isuserimage,setIsUserimage] = useState("");
const [isnickname,setIsnickname] = useState("");
const [data,setData] = useState("<p></p>");
const [tag,setTag] = useState("");
const [title,setTitle] = useState("");
useEffect(()=> {
setIsUserid(localStorage.getItem('userid'));
setIsUserimage(localStorage.getItem('user_image'));
setIsnickname(localStorage.getItem('nick_name'));
},[]);
const ckdata = useCallback((e)=>{
setData(e.editor.getData());
},[data]);
const onChangeTitle = useCallback((e)=>{
setTitle(e.target.value);
},[setTitle])
const onChangeTag = useCallback((e)=>{
setTag(e.target.value);
},[tag]);
const back = useCallback(()=>{
Router.push('/question/board')
},[]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const onSubmit= useCallback(async()=>{
let result = 0;
if(title.replace(" ","").length > 0 && data !== "<p></p>" && tag !== " " && !tag.includes(" ")){
let Forms = new FormData();
Forms.append("userid",isuserid);
Forms.append("title",title);
Forms.append("content",data);
Forms.append("tags",tag);
await axios({
method :'post',
baseURL : backUrl,
url :"/question/insert",
data : Forms
}).then((response)=>{
result = response.data;
if(result > 0){
swal({
title: "등록 성공",
text: "능력치가 +3 올랐습니다.",
icon: "/static/image/Logo2.png",
});
Router.push("/question/board");
}else {
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
}
}).catch((xhr)=>{
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
});
}else{
swal({
title: "등록 실패",
text: "글쓰기 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
})
}
},[data,tag,isuserid,title])
return(
<>
{setIsUserid !== 0 ? <Container >
<br />
<TitleComponent title="질의 응답">
<FontAwesomeIcon style={{width:"35px",height:"auto"}} icon={faQuestionCircle}/>
</TitleComponent>
<br/>
<div>
<ProfileImageUserid user_image={isuserimage} style={cardcss} writer={isnickname} />
<InputText id="title" content="제목을 입력해주세요" onChange={onChangeTitle} maxLength="50"/>
{title.length > 50 ? swal({title: "제목이 너무 깁니다.",text: "제목은 최대 35자 이내로 작성해주세요.",icon: "/static/image/Logo2.png"}) : "" }
<small style={{position:"absolute",left:"85%",top:"215px", color:"grey"}}>({title.length}/50)</small>
{tag.length > 50 ? swal({title: "태그가 너무 깁니다.",text: "태그는 최대 30자 이내로 작성해주세요.",icon: "/static/image/Logo2.png"}) : "" }
<InputText id="tags" content="Tags" onChange={onChangeTag} maxLength="30"/>
<small style={{position:"absolute",left:"85%",top:"285px", color:"grey"}}>({tag.length}/30)</small>
<CkeditorOne2 data={data} onChange={ckdata} />
<hr />
<div style={buttoncss}>
<ButtonComponent name="목록으로" variant="info" onclick={back}/>
<ButtonComponent name="등록" onclick={onSubmit} />
</div>
</div>
<br/>
</Container> : Router.push("/question/board")}
</>
)
}
export default Write;
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Tags.java
package com.ability.dto;
public class Tags {
private int id;
private String tag_name;
private String tag_info;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTag_name() {
return tag_name;
}
public void setTag_name(String tag_name) {
this.tag_name = tag_name;
}
public String getTag_info() {
return tag_info;
}
public void setTag_info(String tag_info) {
this.tag_info = tag_info;
}
}
<file_sep>/front/components/presentational/atoms/SearchbarComponent.js
import React from 'react';
import {InputGroup, Button, FormControl, Container, Row, Col} from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import ListGroup from 'react-bootstrap/ListGroup'
import Link from 'next/link';
/**
* @author 정규현
* @summary 검색바 컴포넌트를 생성 props.
*
*/
const formCss ={
border:"1px solid #5F4B8B",
borderRadius:"15px 0 0 15px",
borderRightStyle:"none",
};
const formCss3 ={
border:"1px solid #5F4B8B",
borderRadius:"0 0 0 0px",
borderRightStyle:"none",
borderLeft:"none"
};
const formCss2 ={
border:"1px solid #5F4B8B",
borderLeftStyle:"none",
borderRadius:"0 15px 15px 0",
};
const searchCss ={
borderStyle:"none",
height : "38px",backgroundColor:"white"
};
const searchCss2 ={
position : "absolute",
right : "0px",
bottom : "0px",
border:"1px solid #5F4B8B",
borderLeftStyle:"none",
borderRadius:"0 15px 15px 0",
};
const searchCss3 ={
right : "0px",
bottom : "0px",
border:"1px solid #5F4B8B",
borderLeftStyle:"none",
borderRadius:"0 15px 15px 0",
};
export const SearchbarComponent = (props) =>
<InputGroup id={props.name}>
<FormControl style={formCss}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
/>
<InputGroup.Append>
<Button variant="outline-secondary"><i className="fas fa-eraser"></i></Button>
<Button variant="outline-secondary"><i className="fas fa-search"></i></Button>
</InputGroup.Append>
</InputGroup>
export const UserSearchbarComponent = (props) =>
<>
<InputGroup id={props.name}>
<FormControl style={formCss}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
onKeyDown={props.input}
id={props.inputId}
maxLength="30"
onChange={props.onChange}
onKeyPress={props.onKeyPress}
value={props.value}
/>
<InputGroup.Append>
<ListGroup style={searchCss}>
<ListGroup.Item action href="#search" style={searchCss}>
<Button variant="outline-secondary" id="userSearch_btn" style={searchCss2} onClick={props.onClick}>
<FontAwesomeIcon icon={faSearch} style={{color:"#5F4B8B"}}/>
</Button>
</ListGroup.Item>
</ListGroup>
</InputGroup.Append>
</InputGroup>
</>
export const UserSearchbarComponent3 = (props) =>
<>
<Container>
<Row>
<Col style={{width:"32rem"}}>
<InputGroup id={props.name}>
<FormControl style={formCss}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
onKeyDown={props.input}
id={props.inputId}
maxLength="30"
onChange={props.onChange}
onKeyPress={props.onKeyPress}
value={props.value}
/>
<InputGroup.Append>
<div style={props.serach? props.serach: searchCss}>
<div style={searchCss}>
<Link href={{pathname:props.path ,query: {word : props.word} }} as="/" replace>
<Button variant="outline-secondary" id="userSearch_btn" style={props.serach?props.serach:searchCss3} onClick={props.onClick}>
<FontAwesomeIcon icon={faSearch} style={{color:"#5F4B8B"}}/>
</Button>
</Link>
</div>
</div>
</InputGroup.Append>
</InputGroup>
</Col>
</Row>
</Container>
</>
export const AllSearchComponent = (props) =>{
return(
<>
<style>
</style>
<Container id="searchbox" style={{minWidth:"150px"}}>
<Row>
<Col style={{width:"32rem"}} id="searchbox">
<InputGroup id={props.name}>
<FormControl style={formCss}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
onKeyDown={props.input}
id={props.inputId}
maxLength="30"
onChange={props.onChange}
onKeyPress={props.onKeyPress}
value={props.value}
/>
<InputGroup.Append>
<div style={props.serach? props.serach: searchCss}>
<div style={searchCss}>
<Link href={{pathname:props.path ,query: {word : props.word} }} as="/" replace>
<Button variant="outline-secondary" id="userSearch_btn" style={props.serach?props.serach:searchCss3} onClick={props.onClick}>
<FontAwesomeIcon icon={faSearch} style={{color:"#5F4B8B"}}/>
</Button>
</Link>
</div>
</div>
</InputGroup.Append>
</InputGroup>
</Col>
</Row>
</Container>
</>
)
}
export const UserSearchbarComponent2 = (props) =>
<>
<InputGroup id={props.name}>
<FormControl style={formCss3}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
onKeyDown={props.input}
id={props.inputId}
maxLength="30"
onChange={props.onChange}
/>
<InputGroup.Append>
<Button variant="outline-secondary" id="userSearch_btn" style={formCss2} onClick={props.onClick}>
<FontAwesomeIcon icon={faSearch} style={{color:"#5F4B8B"}}/>
</Button>
</InputGroup.Append>
</InputGroup>
</>
export const SingleSeachbarComponent = (props) =>
<InputGroup id={props.name}>
<FormControl style={formCss}
placeholder={props.content}
aria-label={props.content}
aria-describedby="basic-addon2"
/>
</InputGroup>
export const SingleButtonComponent = () => {
return(
<InputGroup.Append>
<Button variant="outline-secondary"><i className="fas fa-search"></i></Button>
</InputGroup.Append>
)
}
<file_sep>/front/components/presentational/molecules/ContentTop.js
import React from 'react';
import ListgroupComponent from '../../presentational/atoms/ListgroupComponent';
import {ButtonComponent} from '../../presentational/atoms/ButtonComponent';
import {Container,Row,Col} from 'react-bootstrap';
import Link from 'next/link';
/**
*
* @author 정진호
* @summary 컨텐츠 상단에 최신순 ,조회순 ,추천순.. 글쓰기 버튼을 구현하는 블록
*
*/
const css = {
width : "90px"
}
const css1 = {
display :"inline-block",
borderBottom : "2px solid #eaeaea",
paddingBottom : "1rem",
width : "100%"
}
const sortbar = {
width :"295px",
textAlign:"center"
}
const ContentTop = () => {
return (
<>
<Container style={css1} id="Question_Borad_Top">
<Row id="Question_row">
<Col xs={{offset: 0}}><ListgroupComponent css={sortbar} name="최신순" name1="조회순" name2="댓글순" /></Col>
<Col xs={{ span: 2 , offset: 2}}>
<Link href="/question/write">
<ButtonComponent css={css} name = "글쓰기" />
</Link>
</Col>
</Row>
</Container>
</>
)
}
export default ContentTop;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dao/AdminMapper.java
package com.ability.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.ability.dto.custom.AnswerRate;
import com.ability.dto.custom.BannerClickCountToday;
import com.ability.dto.custom.BannerList;
import com.ability.dto.custom.HireBoardList;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.ProjectBoardList;
import com.ability.dto.custom.UserDetail;
import com.ability.dto.custom.UserMonthlyStatistics;
/**
* 관리자페이지 관련 Mapper
*
* @author 강기
* @summary 관리자페이지 DAO
*
*/
public interface AdminMapper {
public int allPostCount();
public int userCount();
public int leaveMember();
public int todayJoinCount();
public int questionCount();
public int freeboardCount();
public int projectCount();
public int accuseCount();
public int getDeleteCount();
public int noAnswerCount();
public int jobCount();
public int deletePost(int id);
public int recoverPost(int id);
public int deleteJobPost(int id);
public int recoverJobPost(int id);
public List<UserMonthlyStatistics> monthJoin();
public List<UserMonthlyStatistics> monthLeave();
public List<String> getTags();
public List<PostBoardList> getPostBoard(int categoryid);
public List<PostBoardList> getJobBoard();
public List<AnswerRate> getReplyCount();
public List<AnswerRate> getQuestionCount();
public List<ProjectBoardList> getProjectList(Map<String, String> view);
public List<ProjectBoardList> getProjectSearchResult(Map<String, String> view);
public int getTotalBoardContentCount(@Param("category_id") String category_id) throws Exception;
public int getTotalDeleteContentCount(@Param("category_id") String category_id);
public int getTotalBoardSearchContentCount(Map<String, String> view) throws Exception;
public int getTotalDeleteSearchContentCount(Map<String, String> view) throws Exception;
public List<PostBoardList> getCommunityList(Map<String, String> view);
public List<PostBoardList> getSearchResult(Map<String, String> view);
public int getTotalSearchCount(Map<String, String> view);
public List<HireBoardList> getJobBoardList(Map<String,String> viewmap);
public List<HireBoardList> getJobSearchResult(Map<String,String> board);
public int getTotalCount();
public int getTotalUserSearchContentCount(Map<String, String> view);
public int getTotalDeleteUserSearchContentCount(Map<String, String> view);
public List<UserDetail> getUserList(Map<String, String> view);
public List<UserDetail> getUserSearchResult(Map<String, String> view);
public int deleteUser(int id);
public int recoverUser(int id);
public int JobboardSearchCount(Map<String,String> count);
public List<UserDetail> getExcelUserList();
public int changeRole(Map<String,Integer> viewmap);
public List<BannerList> getBanner();
public BannerClickCountToday clickToday(int id);
}
<file_sep>/front/components/presentational/molecules/BoardReply.js
import React, {useState, useCallback, useEffect} from 'react';
import {Card ,InputGroup,FormControl,Col,Row,Form} from 'react-bootstrap';
import {UserImageComponent2} from "../atoms/UserImageComponent";
import {AbilityComponent} from '../atoms/AbilityComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faReply } from '@fortawesome/free-solid-svg-icons';
import Link from 'next/link';
import axios from 'axios';
import TimeAgo from 'react-timeago';
import ko from 'react-timeago/lib/language-strings/ko';
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter';
import swal from 'sweetalert';
import RecommendComment from './RecommandComment';
import dynamic from 'next/dynamic';
import { ButtonComponent } from '../atoms/ButtonComponent';
import Highlight from 'react-highlight';
const formatter = buildFormatter(ko);
const CkeditorOne2 = dynamic(() =>import('../atoms/CkeditorOne2'),{
ssr : false
});
/**
* @author 정규현
* @summary props 값: content: 답변 본문, img: 답변이 프로필 이미지, nickname:답변이 닉네임,ability:답변이 능력치,date:답변쓴 시간
* ,userid = 답변이 userid
*/
const imgCss={
padding:'0',
borderRadius:"50%",
width:"30px",
height:"30px",
marginRight:"0.5rem"
};
const BoardReply = (props) => {
const [comment ,setComment] = useState("");
const [commentList, setCommentList] = useState([]);
const [commentReset, setCommentReset] =useState(0);
const [beforeReply, setBeforeReply] = useState("");
const [isModify, setIsModify] = useState(false);
useEffect(()=>{
getComment();
},[commentReset]);
useEffect(()=>{
setBeforeReply(props.content);
},[]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const getComment = useCallback(()=>{
axios.get(backUrl+"/community/detail/comment",{
params:{
replyid:props.replyid
}
})
.then((res)=>{
setCommentList(res.data);
})
.catch((res)=>{
console.log(res);
})
},[commentList]);
const onChangeComment = useCallback((e) =>{
setComment(e.target.value);
},[comment]);
const onKeyPressComment = useCallback((e)=>{
if(e.charCode == 13){
if(localStorage.getItem('userid') == null || localStorage.getItem('userid') == ""){
swal("로그인한 사용자만 댓글을 작성할 수 있습니다.");
return;
}else if(comment.trim().length<3){
swal("(공백 제외) 3글자 이상 댓글을 작성해야 합니다.");
return;
}
axios.get(backUrl,{
params:{
replyid:props.replyid,
userid:localStorage.getItem('userid'),
comment:comment
}
})
.then(()=>{
setComment("");
getComment();
})
.catch((res)=>{
console.log(res);
})
}
},[comment]);
const onClickReplyCommentDelete = useCallback((commentid)=>{
swal({
text: "삭제한 댓글은 절대 복구할 수 없습니다. 댓글을 정말 삭제하시겠습니까?",
title: "삭제 경고",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
axios.get(backUrl,
{
params:{
seq:commentid
}
})
.then((res)=>{
if(res.data=="success"){
swal("댓글이 삭제 되었습니다.");
setCommentReset(commentid);
}else{
swal("[Error0577] 댓글 삭제 실패");
}
})
.catch((res)=>{
console.log("오류발생",res);
})
}
})
},[commentReset]);
const onClickReplyModify= useCallback((id, content)=>{
swal({
text: `기존 댓글: ${content}`,
title: "댓글 수정(250글자 이내)",
content: "input",
icon: "/static/image/Logo2.png",
buttons:["취소","수정"],
})
.then((value) => {
if(value.length<3){
swal("댓글은 3글자 이상 입력 가능합니다.");
}else if(value.length>250){
swal("댓글은 250글자 이하 입력 가능합니다.");
}else{
axios.get(backUrl,
{
params:{
commentid:id,
content:value
}
})
.then((res)=>{
swal("수정 성공");
setCommentReset(value);
})
.catch((res)=>{
console.log("실패",res);
})
}
})
.catch(()=>{
return;
});
},[commentReset]);
const onClickModify = useCallback(() =>{
setIsModify(true);
},[isModify]);
const onChangeCkeditor = useCallback((e)=>{
setBeforeReply(e.editor.getData());
},[beforeReply]);
const onClickModifyOk = useCallback(()=>{
setIsModify(false);
axios.post(backUrl,
{
seq:props.replyid,
content:beforeReply
})
.catch((res)=>{
console.log("실패",res);
})
},[isModify,beforeReply]);
const onClickModifyCancel = useCallback(()=>{
setIsModify(false);
},[isModify]);
const onClickReplyDelete = useCallback(()=>{
swal({
text: "삭제한 게시물은 절대 복구할 수 없습니다. 게시물을 정말 삭제하시겠습니까?",
title: "삭제 경고",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
let Forms = new FormData();
Forms.append("seq",props.replyid);
axios({
method :'put',
baseURL : backUrl,
data : Forms
}).then((res)=>{
if(res.data=="success"){
swal("게시물이 삭제 되었습니다.");
props.benchmark(1);
}else{
swal("[Error0577] 답변 게시물 실패");
}
})
.catch((res)=>{
console.log("오류발생",res);
})
}
})
},[]);
const GetCommentList = useCallback(() =>{
if(commentList){
const DefineCommentList = commentList.map((DefineComment)=>
<div key={DefineComment.id}>
<Row style={{marginBottom:"0.3rem"}}>
<Col md={10}>
<div style={{marginLeft:"3rem"}}>
{DefineComment.comment_content}
<i> - <small>
<Link href={{pathname:"/developer/page",query:{userid:DefineComment.userid}}}>
<a>{DefineComment.nick_name}</a>
</Link>
</small>
</i>
<small>
<AbilityComponent val={DefineComment.reputation}/>
</small>
<i>
<small>({DefineComment.date_created} 작성)</small>
</i>
</div>
</Col>
<Col md={2}>
<div style={{marginRight:"0.3rem",marginBottom:"0.3rem"}}>
<RecommendComment commentid={DefineComment.id} userid={DefineComment.userid} count={DefineComment.counta}/>
</div>
{ props.userid == localStorage.getItem("userid")?
<>
<span style={{color:"#F79F1F",marginRight:"0.3rem"}} onClick={()=>onClickReplyCommentDelete(DefineComment.id)}>
<small style={{cursor:"pointer"}}><b>[삭제]</b></small>
</span>
<span style={{color:"#0652DD"}} onClick={()=>onClickReplyModify(DefineComment.id, DefineComment.comment_content)}>
<small style={{cursor:"pointer"}}><b>[수정]</b></small>
</span>
</>
: ""
}
</Col>
</Row>
<hr style={{width:"95%"}}/>
</div>
);
return(
<>
<hr style={{width:"95%"}}/>
{DefineCommentList}
</>
);
}else{
return(
""
);
};
},[commentList]);
return (
<Card>
<Card.Header className="text-muted text-right" style={{padding:"0 1rem!important"}}>
<UserImageComponent2 imagepath={props.img} css={imgCss}/>
<Link href={{pathname:"/developer/page",query:{userid:props.userid}}}>
<a>{props.nickname}</a>
</Link>
<AbilityComponent val={props.ability}/>
<i style={{marginRight:"0.5rem",marginLeft:"0.5rem"}}>
<TimeAgo date={props.date} formatter={formatter} />
</i>
{ props.userid == localStorage.getItem("userid") ?
<>
<span style={{color:"#F79F1F",marginRight:"0.3rem"}} onClick={onClickReplyDelete}>
<b>[삭제]</b>
</span>
{!isModify ?
<span style={{color:"#0652DD"}} onClick={onClickModify}>
<b>[수정]</b>
</span>
:
" "
} </>: "" }
</Card.Header>
{isModify
?
<>
<CkeditorOne2 onChange={onChangeCkeditor} data={beforeReply}/>
<div className="text-right" style={{marginRight:"0.5rem"}}>
<ButtonComponent name="취소" css={{marginTop:"0.3rem",marginRight:"0.3rem"}} onclick={onClickModifyCancel} variant="info"/>
<ButtonComponent name="답변 수정" css={{marginTop:"0.3rem"}} onclick={onClickModifyOk}/>
</div>
</>
:" " }
<Card.Body>
<Card.Text style={{minHeight:"5rem",paddingTop:"0.5rem"}}>
<Highlight innerHTML={true}>
{beforeReply}
</Highlight>
</Card.Text>
<GetCommentList editorable="true"/>
<br/>
<Form.Group>
<InputGroup className="mb-3" >
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1">
<FontAwesomeIcon icon={faReply}/>
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder={localStorage.getItem('userid') == null?"댓글은 로그인 후 이용 가능합니다.":"댓글을 입력하세요"}
aria-label="Username"
aria-describedby="basic-addon1"
onChange={onChangeComment}
onKeyPress={onKeyPressComment}
value={comment}
maxLength="250"
readOnly={localStorage.getItem('userid') == null?true:false}
/>
</InputGroup>
</Form.Group>
</Card.Body>
</Card>
);
};
export default BoardReply;<file_sep>/front/components/presentational/molecules/BoardAddList.js
import React from 'react';
import { Question, Like, Answer } from '../atoms/LikeQnAComponent';
/**
* @author 우세림
* @summary 게시판 더 추가 된 리스트
**/
const content = {
marginBottom: "16px",
color: "#565656",
display: "grid",
gridTemplateColumns: "5% 15% 50% 20% 10%",
}
const css4 = {
display: "flex",
}
export const BoardAddList = (props)=>{
return (
<>
<div style={content}>
<div style={props.css1}>{props.id}</div>
<div style={props.css2}>{props.category}</div>
<div style={props.css3}>
</div>
<div style={css4}>
<Question question={props.view}/>
<Like like={props.like}/>
<Answer answer={props.answer}/>
</div>
<div style={props.css5}>{props.day}</div>
</div>
<hr/>
</>
)
}
export default BoardAddList;<file_sep>/front/components/presentational/molecules/JobOpening.js
import React ,{useState , useEffect , useCallback}from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserAstronaut } from '@fortawesome/free-solid-svg-icons';
import { Container,Form, Row, Col, DropdownButton, InputGroup, Dropdown, Button } from 'react-bootstrap';
import UserCard from './UserCard';
import axios from 'axios';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import { InputText } from '../atoms/InputboxComponent';
/**
* @auth 정진호
* @summary 구인구직 게시판 컴포넌트
*/
const CkeditorOne2 = dynamic(() =>import('../atoms/CkeditorOne2'),{
ssr : false
});
export const JobWriteCatgoryName=(props)=>{
return(
<>
<h5>
<FontAwesomeIcon
icon={faUserAstronaut} style={{width:"17.5px"}} />
{props.title}
</h5>
</>
);
}
export const AboutJob=(props)=>{
return(
<>
<JobWriteCatgoryName title="모집정보"/>
<Form
style={props.border}
noValidate >
<Form.Group as={Row}>
<Form.Label column sm={2}
id="">제목</Form.Label>
<Col sm={12}>
<Form.Control type="text"
placeholder="제목을 입력해주세요."
name="title"
onChange={props.onChange}
defaultValue={props.title}
required maxLength="90"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
<hr></hr>
<Form.Group as={Row}>
<Form.Label column sm={2}
id=""
>부제목</Form.Label>
<Col sm={4}>
<Form.Control type="text"
placeholder="OO모집"
name="subtitle"
onChange={props.onChange}
defaultValue={props.subtitle}
required maxLength="10"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
<Form.Label column sm={2}
id="">모집 부류</Form.Label>
<Col sm={4}>
<Form.Control type="text"
placeholder="신입 or 경력직"
name="career"
onChange={props.onChange}
defaultValue={props.career}
required maxLength="30"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={2}
id="">직종</Form.Label>
<Col sm={4}>
<Form.Control type="text"
placeholder="프론트엔드, 백엔드 개발자"
name="job_type"
onChange={props.onChange}
defaultValue={props.job_type}
maxLength="50"
/>
</Col>
<Form.Label column sm={2}
id="">근무 시간</Form.Label>
<Col sm={4}>
<Form.Control type="text"
placeholder="월~금 00:00~00:00"
name="job_time"
onChange={props.onChange}
defaultValue={props.job_time}
required maxLength="60"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={2}
id="">근무 부서</Form.Label>
<Col sm={4}>
<Form.Control type="text"
placeholder="부서명 "
name="job_dept"
onChange={props.onChange}
defaultValue={props.job_dept}
required maxLength="30"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
<Form.Label column sm={2}
id="">EMAIL</Form.Label>
<Col sm={4}>
<Form.Control type="email"
placeholder="<NAME>"
name="email"
onChange={props.onChange}
defaultValue={props.email}
required maxLength="50"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
<Form.Group as={Row}>
<Form.Label column sm={2}
id="">모집 기간</Form.Label>
<Col sm={4}>
<Form.Control type="date"
name="period"
onChange={props.onChange}
defaultValue={props.period}
required/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
<Form.Label column sm={2}
id="">담당자 번호</Form.Label>
<Col sm={4}>
<Form.Control type="tel"
placeholder="010-0000-0000"
name="phone"
onChange={props.onChange}
defaultValue={props.phone}
required maxLength="15"/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid">필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
</Form>
</>
);
}
export const JobSkills=(props)=>{
return(
<>
<JobWriteCatgoryName title="사용기술"/>
<Form
style={props.border}
noValidate>
<Form.Group as={Row}>
<Form.Label column sm={2}
id="skills"
required>
태그
</Form.Label>
<Col sm={10}>
<Form.Control type="text"
placeholder="자바,노드..[,콤마로 구분]"
name="tags"
onChange={props.onChange}
defaultValue={props.tags}
required/>
<Form.Control.Feedback></Form.Control.Feedback>
<Form.Control.Feedback type="invalid" required>필수입력 사항입니다</Form.Control.Feedback>
</Col>
</Form.Group>
</Form>
</>
);
}
export const CompanyDetail=(props)=>{
return(
<>
<JobWriteCatgoryName title="회사정보" />
<Form
style={props.border}
noValidate
>
<Form.Group as={Row}>
<Form.Label column sm={1}
id="people">규모</Form.Label>
<Col xs={6}>
<DropdownButton
as={InputGroup.Prepend}
variant="outline-secondary"
title={props.dropdownName}
id="input-group-dropdown-1">
<Dropdown.Item eventKey="1" name="10명 이하" onClick={props.dropdown}>10명 이하</Dropdown.Item>
<Dropdown.Item eventKey="2" name="10~50명 미만" onClick={props.dropdown}>10~50명 미만</Dropdown.Item>
<Dropdown.Item eventKey="3" name="50~100명 미만" onClick={props.dropdown}>50~100명 미만</Dropdown.Item>
<Dropdown.Item eventKey="4" name="100명 이상" onClick={props.dropdown}>100명 이상</Dropdown.Item>
</DropdownButton>
</Col>
</Form.Group>
<hr></hr>
<Container>
<Row>
<Col xs={4}>
<Form.Group as={Row}>
<Container>
<Row>
<Col>
<Form.Label
id="">로고첨부</Form.Label>
<InputText label="파일 찾기" id="user_image" name="file" accept=".gif, .jpg, .png"
className="user_image" for="user_image" type="file" name="file" onChange={props.onChangeFile}/><span style={{margin : "23px 0px 0px 23px", color:"rgb(205, 97, 51)"}}>{props.filename ? props.filename+"을 선택하였습니다." : ""+props.logo}</span>
</Col>
</Row>
<Row>
<Col>
<Form.Label
id="">이력서 양식</Form.Label>
<InputText label="파일 찾기" id="user_image1" name="file1" accept=".hwp , .xls , xlsx"
className="user_image" for="user_image1" type="file" name="file1" onChange={props.onChangeFile2}/><span style={{margin : "23px 0px 0px 23px", color:"rgb(205, 97, 51)"}}>{props.filename2 ? props.filename2+"을 선택하였습니다." : ""+props.resume}</span>
</Col>
</Row>
</Container>
</Form.Group>
</Col>
<Col style={{textAlign:"center"}}><img src={props.logoSrc ? props.logoSrc : ""}></img></Col>
</Row>
</Container>
</Form>
</>
);
}
export const JobDetail=(props)=>{
return(
<>
<JobWriteCatgoryName title="직무상세"/>
<Form
style={props.border}
noValidate
>
<Form.Group as={Row}>
<Form.Label column sm={2}
id=""
required>
직무상세설명
</Form.Label>
<Col sm={10}>
<CkeditorOne2 data={props.content ? props.content : props.data} onChange={props.onChange}/>
</Col>
</Form.Group>
</Form>
</>
);
}
export const Manager =(props)=>{
const [userid,setUserid] = useState("");
const [username,setUsername] = useState("");
const [image,setImage] = useState("");
const [area,setArea] = useState("");
const [reputation,setReputation] = useState("");
const [tags,setTags] = useState("");
const endpoint = process.env.NODE_ENV === 'production'? "?" : "?";
useEffect(()=>{
setUserid(localStorage.getItem("userid"));
setUsername(localStorage.getItem("nick_name"));
setImage(localStorage.getItem("user_image"));
axios.get(endpoint, {
params : {
userid : localStorage.getItem("userid")
}
}).then((Response) => {
setArea(Response.data.area);
setReputation(Response.data.reputation);
setTags(Response.data.tags);
});
},[])
return(
<>
<JobWriteCatgoryName title="담당자"/>
<UserCard userImage={image} userid={userid} name={username} area={area} reputation={reputation} tags={tags} />
</>
);
}<file_sep>/front/components/presentational/atoms/ProfileImageEditComponent.js
import React from 'react';
/**
*
* @author 강기훈
* @summary 마이페이지 프로필 이미지 컴포넌트
*/
const css ={
display:"inline-block",
verticalAlign: "middle",
padding: "12px",
border: "1px solid #CDCECF",
backgroundColor: "#FFF",
cursor:"pointer",
width:"186px",
height:"210px",
textAlign:"center",
borderRadius:"6px"
}
const css_image ={
width:"150px",
height:"150px",
}
const css_file ={
width: "1px",
height: "1px",
border:"0px",
margin:"-1px",
overflow:"hidden",
padding:"0px",
clip: "rect(0px, 0px, 0px, 0px)",
}
const css_label ={
display:"inline-block",
padding:".5em .75em",
color: "#fff",
fontSize: "inherit",
lineHeight:"normal",
verticalAlign:"middle",
backgroundColor:"#5F4B8B",
cursor: "pointer",
border: "1px solid",
borderRadius:".25em",
transition: "background-color 0.2s"
}
export const ProfileImageEditComponent=()=>
<div className="ProfileImage" style={css}>
<img style={css_image} src="https://i2.wp.com/bugsy-net.com/diet/wp-content/plugins/speech-bubble/img/blank-profile.png?w=840&ssl=1"/>
<label for="file" style={css_label}>사진변경</label>
<input type="file" style={css_file} id="file"></input>
</div><file_sep>/Ability-SpringBoot1/src/main/java/com/ability/service/UserService.java
package com.ability.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.ability.dao.DbMapper;
import com.ability.dto.custom.PostBoardComment;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.PostBoardModify;
import com.ability.dto.custom.ReplyBoard;
import com.ability.dto.custom.Reputation;
import com.ability.dto.custom.UserSimple;
import com.ability.utils.CreateRandomPassword;
import com.ability.utils.FindPasswordMail;
import com.ability.utils.RandomImageAPI;
import com.ability.utils.SignUpAuthMail;
/**
*
* @author jkh
* @summary 회원가입, 로그인 등 회원 관련 서비스를 처리하는 로직
*
*/
@Service
public class UserService {
@Autowired
DbMapper mapper;
@Autowired
SignUpAuthMail signUpAuthMail;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
FindPasswordMail findPasswordMail;
@Autowired
CreateRandomPassword createRandomPassword;
//login
public UserSimple authenticate(String email, String password) {
UserSimple userSimple = null;
return userSimple;
}
//sign up
public int signUpUser(String email, String password, String nick_name, String name, String area) {
return result;
}
//sign up mail_security_key
public Boolean signUpMailAuthConfirm(String security_key) {
return result;
}
//confirm overlap email
public Boolean isOverlapEmail(String email) {
Boolean result = false;
return result;
}
//confirm overlap nick_name
public Boolean isOverlapNickName(String nickname) {
return result;
}
//check account
public int checkAccount(String email, String name) {
return userid;
}
//community board list
public List<PostBoardList> getPostList(Map<String, String> view) {
return mapper.getCommunityList(view);
}
//insert board
public int setBoard(Map<String,String> content) {
int result = mapper.insertBoard(content);
if(result > 0) {
return result;
}
return -1;
}
//getTotalBoardContentCount
public int totalContentCount(String category_id) {
int result = 0;
try {
result = mapper.getTotalBoardContentCount(category_id);
} catch (Exception e) {
result = 0;
}
return result;
}
//getTotalBoardSearchContentCount
public int getTotalBoardSearchContentCount(Map<String, String> view) {
int result = 0;
try {
result = mapper.getTotalBoardSearchContentCount(view);
} catch (Exception e) {
result = 0;
}
return result;
}
//getPostListOne
public PostBoardList getPostListOne(Map<String, String> view) {
return mapper.listDetail(view);
}
//setPostBoardUpdate
public int setPostBoardUpdate(Map<String,String> content) {
int result = mapper.updatePostBoard(content);
if(result > 0) {
return result;
}else {
return -1;
}
}
//updateViewCount
public void updateViewCount(Map<String, String> boardid) {
mapper.updateViewCount(boardid);
}
//getModifyContent
public PostBoardModify getModifyContent(Map<String, String> seq) {
return mapper.getModifyContent(seq);
}
//getReply
public List<ReplyBoard> getReply(Map<String, String> seq){
return mapper.getReply(seq);
}
//setReply
public int setReply(Map<String, String> contents) {
return mapper.setReply(contents);
}
//setComment
public int setComment(Map<String, String> contnents) {
return mapper.setComment(contnents);
}
//getCommentList
public List<PostBoardComment> getCommentList(Map<String,String> contents){
return mapper.getCommentList(contents);
}
//checkPostVote
public Boolean checkPostVote(Map<String, String> contents) {
Boolean result = true;
try {
if(mapper.checkPostVote(contents) != 1 && mapper.checkPostVote(contents) != -1) {
result = false;
mapper.insertPostVote(contents);
}
} catch (Exception e) {
result = true;
}
return result;
}
//cancelPostVote
public String cancelPostVote(Map<String, String> contents) {
String result = "plus";
try {
if(mapper.checkPostVote(contents) != 1) {
result="minus";
}
mapper.cancelPostVote(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
//checkPostReplyVote
public Boolean checkPostReplyVote(Map<String, String> contents) {
Boolean result = true;
try {
if(mapper.checkPostReplyVote(contents) != 1 && mapper.checkPostReplyVote(contents) != -1) {
result = false;
mapper.insertPostReplyVote(contents);
}
} catch (Exception e) {
result = true;
}
return result;
}
//cancelPostVote
public String cancelPostReplyVote(Map<String, String> contents) {
String result = "plus";
try {
if(mapper.checkPostReplyVote(contents) != 1) {
result="minus";
}
mapper.cancelPostReplyVote(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
//cancelPostMark
public String cancelPostMark(Map<String, String> contents) {
String result = "fail";
try {
result="success";
mapper.cancelPostMark(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
//checkPostCommentVote
public Boolean checkPostCommentVote(Map<String, String> contents) {
Boolean result = true;
try {
if(mapper.checkPostCommentVote(contents) != 1 && mapper.checkPostCommentVote(contents) != -1) {
result = false;
mapper.insertPostCommentVote(contents);
}
} catch (Exception e) {
result = true;
}
return result;
}
//cancelCommentVote
public String cancelPostCommentVote(Map<String, String> contents) {
String result = "plus";
try {
if(mapper.checkPostCommentVote(contents) != 1) {
result="minus";
}
mapper.cancelPostCommentVote(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
//fakeDelete
public Boolean fakeDelete(Map<String, String> contents) {
Boolean result = false;
try {
mapper.fakeDelete(contents);
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
//fakeReplyDelete
public Boolean fakeReplyDelete(Map<String, String> contents) {
Boolean result = false;
try {
mapper.fakeReplyDelete(contents);
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
//fakeCommentDelete
public Boolean fakeCommentDelete(Map<String, String> contents) {
Boolean result = false;
try {
mapper.fakeCommentDelete(contents);
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
//postBoardCommentModify
public String postBoardCommentModify(Map<String, String> contents) {
String result = "fail";
try {
mapper.postBoardCommentModify(contents);
result = "success";
} catch (Exception e) {
result = "fail";
}
return result;
}
//getSearchResult
public List<PostBoardList> getSearchResult(Map<String, String> view) {
return mapper.getSearchResult(view);
}
//setPostBoardMark
public int setPostBoardMark(Map<String, String> view) {
int result = -1;
try {
if(mapper.checkPostBoardMark(view) == 0) {
mapper.setPostBoardMark(view);
result = 1;
}
} catch (Exception e) {
e.printStackTrace();
result = -1;
}
return result;
}
//setModifyReplyOk
public String setModifyReplyOk(Map<String, String> view) {
String result = "fail";
try {
mapper.setModifyReplyOk(view);
result = "success";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Reputation getReputation(int userid) {
return mapper.getReputation(userid);
}
}
<file_sep>/front/components/presentational/molecules/ProjectDetails.js
import React from 'react';
import YouTube from 'react-youtube';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHeart, faStar, faShareAlt, faReply } from '@fortawesome/free-solid-svg-icons';
import { Row, Col, InputGroup, FormControl, Card} from 'react-bootstrap';
import { AbilityComponent } from '../atoms/AbilityComponent';
import { UserImageComponent2 } from '../atoms/UserImageComponent';
import ContentTitle from './ContentTitle';
import { TagListBoard } from './TagList';
import { ButtonComponent } from '../atoms/ButtonComponent';
import Link from 'next/link';
import TimeAgo from 'react-timeago';
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter';
import ko from 'react-timeago/lib/language-strings/ko';
import { Recommend2 } from './Recommend';
import {_} from 'underscore';
import Router from 'next/router';
import PropTypes from "prop-types";
import Highlight from 'react-highlight';
/**
* @author 신선하
* @summary 비디오 카드 디테일
* @usage
**/
const formatter = buildFormatter(ko);
const iconSize = {
width:'14px',
height:'auto'
}
const imgCss={
padding:'0',
borderRadius:"50%",
width:"30px",
height:"30px",
marginRight:"0.5rem"
};
const button = {
width : "90px",
}
const divcss ={
minWidth : "194px"
}
const rowcss = {
paddingTop : "1.5rem"
}
const colcss ={
padding:"0px",
textAlign:"center"
}
export const TItleNModify = (props) => {
return(
<>
<ContentTitle
seq={props.seq}
title={props.title}
userid={props.userid}
path={"/project/modify?seq="+props.seq}
onclick3={props.onclick3}
/>
</>
);
}
export const VideoId = (props) => {
YouTube.propTypes = {
videoId: PropTypes.string
}
return (
<>
<br/>
<div style={{background:'#FFF'}}>
<YouTube
videoId={props.file_path}
id="작성자아이디"
className="클래스네임"
opts={props.style}
/>
</div>
</>
);
}
export const TitleViewCount =(props)=>{
return(
<>
<Row>
<div className="col-12"><br/>
<h5>{props.title}</h5>
</div>
</Row>
<Row style={{color:'darkgrey'}}>
<div className="col-6">
조회수 {props.view_count}
</div>
<div className="col-6"
style={{textAlign:'right'}}>
<FontAwesomeIcon icon={faHeart} style={iconSize}/>
좋아요
<FontAwesomeIcon icon={faStar} style={iconSize}/>
즐겨찾기
<FontAwesomeIcon icon={faShareAlt} style={iconSize}/>
링크복사
</div>
</Row>
</>
);
}
export const ReplyProjectDetail =(props)=>{
return(
<>
<Row>
<div className="col-12">
댓글[10]개<br/><br/>
<div className="row">
<div className="col-1">
<UserImageComponent2
css={imgcss}
imagepath={props.imagepath} />
</div>
<div className="col-11">
<InputGroup className="mb-3" >
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon1" >
<FontAwesomeIcon icon={faReply}/>
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
placeholder="댓글을 입력하세요"
aria-label="Username"
aria-describedby="basic-addon1"
/>
</InputGroup>
</div>
</div>
</div>
</Row><br/>
</>
);
}
export const ProjectDetail = (props) =>{
return (
<>
<Row>
<Col md={11} style={{textAlign:"left", paddingRight:'0'}}>
<VideoId
file_path={props.file_path}
onClick={props.onClick}
style={{width:'100%', height:'450px'}}
/><br/><br/>
</Col>
<br/><br/>
<Col md={1} className="text-left" style={{padding:"0"}}>
<Recommend2
count={props.count}
onClickUp={props.onClickUp}
onClickDown={props.onClickDown}
style={{textAlign:"left"}}
/>
</Col>
</Row>
<Row style={{width:"99%"}}>
<Col md={11} style={{paddingRight:"0"}}>
<Card style={{border:"1px solid #c6badf!important",
width:'828.33px'}} id="replyvideo">
<Card.Header
className="text-muted text-right"
style={{padding:"0.4rem 1rem"}}
>
<UserImageComponent2
imagepath={props.imagepath}
css={imgCss}
/>
<Link
href={{pathname:"/developer/page",
query:{userid:props.userid}}}
as={"/developer/page/"+props.userid}>
<a>{props.nickname}</a>
</Link>
<AbilityComponent val={props.ability}/>
- <i><TimeAgo date={props.date} formatter={formatter} /></i>
</Card.Header>
<Card.Body style={{minHeight:"20rem"}}>
<Card.Text>
<Highlight innerHTML={true}>
{props.content}
</Highlight>
</Card.Text>
</Card.Body>
</Card><br/>
</Col>
<Col md={1} className="text-left" style={{padding:"0"}}/>
</Row><br/>
</>
);
}
export const ProjectTitle2 = (props) => {
return (
<>
<Row style={rowcss}>
<Col md={9}>
<TagListBoard
hashtag={props.tags}
boardid={props.boardid}
viewcount={props.viewcount}
/>
<h2> {props.title}</h2>
</Col>
<Col md={3} style={colcss}>
{ props.userid !== 0 && props.currentUserId !== 0 ? <>
{ props.userid == props.currentUserId ?
<div style={divcss}>
<ButtonComponent
variant="info"
css={button}
name="삭제"
onclick={props.onclick3}
/>
<Link href={props.to ? props.to : "/"}>
<ButtonComponent
css={button}
onclick={() =>Router.push("/project/modify?seq="+props.seq, '/project/modify')}
name="수정"
/>
</Link>
</div>
: "" }
</>
: ""}
</Col>
</Row>
</>
)}<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/AuthenticationToken.java
package com.ability.dto.custom;
/**
*
* @author 정규현
* @summary 로그인 사용
*
*/
public class AuthenticationToken {
private UserSimple user;
private String token;
public AuthenticationToken(UserSimple user, String token) {
this.user = user;
this.token = token;
}
public UserSimple getUser() {
return user;
}
public void setUser(UserSimple user) {
this.user = user;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
<file_sep>/front/components/presentational/molecules/UserProfile.js
import React from 'react';
import { AbilityComponent2 } from '../atoms/AbilityComponent';
/**
*
* @author 우세림
* @summary 개발자들 상세 페이지 프로필 정보
*
*/
const userContentId ={
width: "100%",
fontSize: "29px",
fontWeight: "700"
}
const userContentDiv ={
marginBottom: "20px"
}
const userContentAbili ={
fontSize: "16px",
marginLeft: "15px"
}
const userContentEmail ={
width: "100%",
color: "#57606f",
display: "inline-block",
marginTop: "15px"
}
const usermaster={
display: "inline-block",
marginBottom: "4px"
}
const userContentIntro ={
width: "100%",
height: "70%",
display: "inline-block",
marginTop: "10px",
overflow: "auto",
backgroundColor: "#f2f2f2",
padding: "10px"
}
export const UserProfile = (props)=> {
return (
<>
<span style={userContentId}>
{props.nick_name}
</span>
<span style={userContentAbili}>
<AbilityComponent2 val={props.reputation}/>
</span>
<span style={userContentEmail}>
{props.name} {props.email}
</span>
<span style={userContentIntro}>
<div dangerouslySetInnerHTML={ {__html:props.user_info } } ></div>
</span>
</>
)
}
export const UserProfile2 = (props)=> {
return (
<div style={userContentDiv}>
<span style={userContentId}>
{props.company_name}
</span> <a href={props.homepage_url}>{props.homepage_url}</a>
<span style={userContentEmail}>
<span style={usermaster}>담당자 : {props.name} </span> <br/>
<span style={usermaster}>담당자 이메일: {props.email} </span>
</span>
</div>
)
}
export const UserProfile3 = (props)=> {
return (
<>
<span style={userContentIntro}>
<div dangerouslySetInnerHTML={ {__html:props.company_info } } ></div>
</span>
</>
)
}
export default UserProfile;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/PostBoardComment.java
package com.ability.dto.custom;
import java.sql.Date;
/**
*
* @author 정규현
* @summary 댓글을 받기 위한 디티오
*
*/
public class PostBoardComment {
private int id;
private int reply_id;
private int userid;
private Date date_created;
private String comment_content;
private int counta;
private int reputation;
private String nick_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getReply_id() {
return reply_id;
}
public void setReply_id(int reply_id) {
this.reply_id = reply_id;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public String getComment_content() {
return comment_content;
}
public void setComment_content(String comment_content) {
this.comment_content = comment_content;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public int getCounta() {
return counta;
}
public void setCounta(int counta) {
this.counta = counta;
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Confirm_Email.java
package com.ability.dto;
import java.sql.Date;
public class Confirm_Email {
private int id;
private int userid;
private String securitiy_key;
private Date date_created;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getSecuritiy_key() {
return securitiy_key;
}
public void setSecuritiy_key(String securitiy_key) {
this.securitiy_key = securitiy_key;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/service/ChatRoomRepository.java
package com.ability.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.ability.dao.ChattingMapper;
import com.ability.dto.ChatRoom;
@Service
@Repository
public class ChatRoomRepository {
@Autowired
ChattingMapper chattingMapper;
private Map<String, ChatRoom> chatRoomMap = new HashMap<String, ChatRoom>();
@PostConstruct
private void init() {
chatRoomMap = new LinkedHashMap<>();
}
public List<ChatRoom> findAllRoom() {
// 채팅방 생성순서 최근 순으로 반환
List<ChatRoom>chatRooms = new ArrayList<>();
chatRooms = chattingMapper.getRoomList();
Collections.reverse(chatRooms);
return chatRooms;
}
public ChatRoom findRoomById(String id) {
ChatRoom chatRoom = chattingMapper.getRoomById(id);
return chatRoom;
}
public ChatRoom createChatRoom(String name, String people, String tags) {
int result = 0;
ChatRoom chatRoom = ChatRoom.create(name, people, tags);
chatRoomMap.put(chatRoom.getRoomId(), chatRoom);
result = chattingMapper.insert(chatRoom.getRoomId(), name, Integer.parseInt(people), tags);
return chatRoom;
}
public int deleteRoom(String roomId) {
int result = chattingMapper.delete(roomId);
return result;
}
}
<file_sep>/front/components/presentational/atoms/AlertMsgComponent.js
import React from 'react';
/**
* @author 정규현
* @summary 로그인 메인화면 쪽지 알람용 아이콘
*/
const msgCss={
fontSize:"1.8rem",
borderRadius:"50%",
color:"#a29bfe",
padding:"0.4rem",
marginRight:"0.4rem"
}
const AlertMsgComponent = () =>
<div style={{verticalAlign: "middle"}}>
<div style={msgCss}><i className="far fa-envelope"></i></div>
</div>
export default AlertMsgComponent;<file_sep>/front/components/presentational/atoms/SelectMenuComponent.js
import React from 'react';
import './css/SelectMenu.css'
/**
*
* @auth 곽호원
* @summary 메뉴 셀렉트 박스 만드는 컴포넌트
*
*/
const SelectMenuComponent = (props) => {
const selectlist = [];
if(props.menu !== null && props.menu !== "" && props.menu !== undefined){
const list = props.menu.split(',');
for(var i=0; i<list.length; i++){
selectlist.push(list[i]);
}
const selectmenu = selectlist.map((value, index)=>(<option value={index}>{value}</option>));
return (
<select className="custom-select">
<option>{props.title}</option>
{selectmenu}
</select>
);
};
}
export default SelectMenuComponent;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/controller/ajax/IsExistAccountAjax.java
package com.ability.controller.ajax;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ability.service.UserService;
/**
*
* @author 정규현
* @summary 비밀번호 찾기에서 비동기를 처리하기 위한 처리
*
*/
@RestController
public class IsExistAccountAjax {
@Autowired
UserService userService;
public String isOverlapEmail(Model model, @Param("email") String email, @Param("name") String name) {
String result = "false";
if(userService.checkAccount(email, name)!=-1) {
result = "true";
}
return result;
}
}
<file_sep>/front/components/presentational/atoms/TitleDropDownComponent.js
import React, { Component } from 'react';
import Dropdown from 'react-bootstrap/Dropdown';
/**
*
* @author 곽호원
* @summary 게시판 만드는 컴포넌트
*
*/
const dropcss = {
width : "100%",
textAlign : "center"
}
export class TitleDropDownComponent extends Component {
constructor(props){
super(props)
this.state = {
values : "게시판을 선택해주세요"
}
this.values = this.HandleChange.bind(this)
}
HandleChange=(e)=>{
this.setState({values: e.target.name})
}
render(){
return(
<Dropdown id="titleSelect" >
<Dropdown.Toggle style={dropcss} variant="primary" id="dropdown-basic" >
{this.state.values}
</Dropdown.Toggle>
<Dropdown.Menu style={dropcss}>
<Dropdown.Item eventKey="1" value={this.props.value} name={this.props.name} onClick={this.HandleChange}>{this.props.name}</Dropdown.Item>
<Dropdown.Item eventKey="2" value={this.props.value2} name={this.props.name2} onClick={this.HandleChange}>{this.props.name2}</Dropdown.Item>
<Dropdown.Item eventKey="3" value={this.props.value3} name={this.props.name3} onClick={this.HandleChange}>{this.props.name3}</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
)
}
}
<file_sep>/front/components/presentational/atoms/LikeQnAComponent.js
import React, {Component} from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {faCommentAlt,faThumbsUp,faEye, faMehRollingEyes, faLaugh,faGrinHearts,faAngry} from "@fortawesome/free-regular-svg-icons";
/**
* @auth 신선하
* @summary 추천수, 조회수, 답변수 컴포넌트
* @see 정규현 컴포넌트 수정 / 시나리오에 맞게, 조건문 적용
*/
function changeUnit(value){
let result = value;
const strResult = result.toString();
const strResultLength = result.toString().length;
if(strResultLength >9){
result = strResult.substr(0, strResultLength-9)+"G";
}else if(strResultLength >6){
result = strResult.substr(0, strResultLength-6)+"M";
}else if(strResultLength >3){
result = strResult.substr(0, strResultLength-3)+"K";
}
return result;
}
export class Like extends Component { //추천수
render(){
const view = changeUnit(this.props.like);
let icon = <div><FontAwesomeIcon icon={ faThumbsUp }/>{' '} {view}</div>;
if(this.props.like<-9){
icon = <div style={{color:"#EA2027",fontWeight:"bold"}}><FontAwesomeIcon icon={ faAngry }/>{' '} {view}</div>;
}else if(this.props.like<0){
icon = <div style={{color:"#EE5A24",fontWeight:"bold"}}><FontAwesomeIcon icon={ faMehRollingEyes }/>{' '} {view}</div>;
}else if(this.props.like>9){
icon = <div style={{color:"#9b59b6",fontWeight:"bold"}}><FontAwesomeIcon icon={ faLaugh }/>{' '} {view}</div>;
}else if(this.props.like>29){
icon = <div style={{color:"#8e44ad",fontWeight:"bold"}}><FontAwesomeIcon icon={ faGrinHearts }/>{' '} {view}</div>;
}else if(this.props.like>0){
icon = <div style={{color:"#FDA7DF",fontWeight:"bold"}}><FontAwesomeIcon icon={ faThumbsUp }/>{' '} {view}</div>;
}
return(
<>
{icon}
</>
);
}
}
export class Question extends Component { //조회수
render(){
const view = changeUnit(this.props.question);
let qColor = "";
const css = {
color: "",
fontWeight:""
};
if(this.props.question>1000){
qColor = "#1e90ff";
css.color = qColor;
css.fontWeight = "bold";
}else if(this.props.question>1000000){
qColor = "#5352ed";
css.color = qColor;
css.fontWeight = "bold";
}else if(this.props.question>1000000000){
qColor = "#3742fa";
css.color = qColor;
css.fontWeight = "bold";
}
return(
<div style={css}>
<FontAwesomeIcon icon={ faEye }/>{' '} {view}
</div>
);
}
}
export class Answer extends Component { //답변수
render(){
const view = changeUnit(this.props.answer);
return(
<div style={{color:(this.props.answer>0?"#009432":""), fontWeight:(this.props.answer>0?"bold":""),}} >
<FontAwesomeIcon icon={ faCommentAlt }/>{' '} {view}
</div>
);
}
}<file_sep>/front/components/presentational/molecules/Button.js
import React from 'react';
import './css/Button.css';
import {ButtonComponent} from '../atoms/ButtonComponent';
import {NavLink} from 'react-router-dom';
/**
* @author 정진호
* @summary Top 영역에 들어가는 로그인/회원가입 버튼
* @see 정규현 기존 버튼 수정 / 스프링 부트(시큐리티 적용완료)와 로그인 회원가입 연동
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const ConnectSpringSignUp = ()=>{
window.open(backUrl+"/signup","ABILITY SIGN UP","width=430, height=796,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no");
};
const btnCss = {
left: "80%",
top: "0.9rem",
zIndex: "1",
position: "absolute",
width:"11.5625rem",
height:"auto",
marginLeft:"0",
marginRight:"auto",
padding:"0"
};
const NavLayOut = () =>
<>
<div className="SighForm" style={btnCss}>
<NavLink to="/login">
<ButtonComponent name="로그인" id="Login"/>
</NavLink>
<ButtonComponent onclick={ConnectSpringSignUp} name="회원가입" id="Sihgup"/>
</div>
</>
export default NavLayOut;<file_sep>/front/components/presentational/atoms/GoogleSuggest.js
import React from "react"
import ReactGoogleMapLoader from "react-google-maps-loader"
import ReactGooglePlacesSuggest from "react-google-places-suggest"
import { InputTextBox } from "./InputboxComponent";
/**
*
* @author 곽호원
* @summary 도시 검색시 자동완성 컴포넌트
*
*/
const MY_API_KEY = ""
export default class GoogleSuggest extends React.Component {
constructor(props){
super(props);
this.state = {
search: this.props.search,
value: this.props.value,
}
}
handleInputChange = (e) => {
this.setState({search: e.target.value, value: e.target.value});
}
handleSelectSuggest = (geocodedPrediction, originalPrediction) => {
this.setState({search: "", value: geocodedPrediction.formatted_address})
}
render() {
const {search, value} = this.state
return (
<ReactGoogleMapLoader
params={{
key: "",
libraries: "",
}}
render={googleMaps =>
googleMaps && (
<ReactGooglePlacesSuggest
googleMaps={googleMaps}
autocompletionRequest={{
input: search,
}}
onNoResult={this.handleNoResult}
onSelectSuggest={this.handleSelectSuggest}
onStatusUpdate={this.handleStatusUpdate}
textNoResults="My custom no results text"
customRender={prediction => (
<div className="customWrapper">
{prediction
? prediction.description
: "My custom no results text"}
</div>
)}
>
<InputTextBox type="text"
value={value}
onChange={this.handleInputChange}
id={this.props.id}
placeholder={this.props.placeholder}
/>
</ReactGooglePlacesSuggest>
)
}
/>
)
}
}<file_sep>/front/pages/index.js
import React from 'react';
import {useSelector} from 'react-redux';
import {Container,Row,Col} from 'react-bootstrap';
import RollingBannerComponent from '../components/presentational/atoms/RollingBannerComponent';
import MainCardComponent, {MainVideoCardComponent} from '../components/presentational/atoms/MainCardComponent';
import HelMet from 'react-helmet';
import dynamic from 'next/dynamic';
import { MAIN_DATA_REQUEST } from '../reducers/main';
const AdminWordcloud = dynamic(() =>import('../components/presentational/molecules/AdminWordcloud'),{
ssr : false
});
/**
* @author 정규현
* @summary 메인 페이지
*/
const rowCss = {
marginTop:"2rem",
marginBottom:"3rem",
};
const rowCss2 = {
marginBottom:"2.4rem",
};
const cloud = {
border:"1px solid #c6badf",
marginTop:"0.9rem",
borderRadius:"10px"
};
const Home = ()=>{
const {pBoard, qBoard, fBoard, banner} = useSelector(state=>state.main);
return (
<>
<HelMet
title={`ABILITY에 오신걸 환영합니다.`}
description={`여러가지 트랜드를 반영한 최신 기술과 고급 기술들을 많이 적용해서 만든 기술 중심형 프로젝트입니다. 사용자들은 질문을 통해 개발에 대한 해결방안을 얻고,
답변을 통해 일정한 포인트(능력치)를 얻을 수 있는 사이트 입니다. 또한 사용자들은 페이지를 통해 구인을 원하는 기업에 지원할 수 있고, 사용자 간의 채팅도 가능하며,
본인이 만든 프로젝트 영상을 다른 사용자들에게 보여줄 수 있는 공간을 제공합니다.`}
/>
<Container style={{marginBottom:"5rem"}}>
<Row style={rowCss}>
<RollingBannerComponent data={banner}/>
</Row>
<Row style={rowCss2}>
<Col sm={12} md={12} style={{padding:"0"}}>
<div style={{width:"100%",height:"auto"}}>
<MainCardComponent data={qBoard}
path="/question/board"
category="질의 응답"
titlepath="/question/content"
more="최신글"
/>
</div>
</Col>
</Row>
<Row style={rowCss2}>
<div style={{width:"100%",height:"auto"}}>
<MainVideoCardComponent data={pBoard}
path="/project/board"
more="프로젝트 영상"
/>
</div>
</Row>
<Row style={rowCss2}>
<Col sm={12} md={6}>
<div style={cloud}>
<AdminWordcloud/>
</div>
</Col>
<Col sm={12} md={6} style={{padding:"0"}}>
<div style={{width:"100%",height:"auto"}}>
<MainCardComponent data={fBoard}
path="/community/board"
category="자유 게시판"
titlepath="/community/detail"
more="최신글"
/>
</div>
</Col>
</Row>
</Container>
</>
);
};
Home.getInitialProps = (context) =>{
context.store.dispatch({
type:MAIN_DATA_REQUEST,
})
};
export default Home;<file_sep>/Ability-SpringBoot1/src/main/resources/static/js/findpassword.js
/**
* @author 정규현
* @summary 비밀번호 찾기 로직 구현
*/
let isEmpty = (value)=> {
if( value == "" || value == null || value == undefined || ( value != null && typeof value == "object" && !Object.keys(value).length ) ){
return true
}else{
return false
}
};
function isEmail(email) {
const pattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
if (pattern.test(email)) return true;
else return false;
};
function isIncludeSpace(str) {
const pattern = /\s/;
if (str.match(pattern)) return true;
else return false;
};
const closeWindow = ()=>{
setTimeout(window.close(),10000);
};
const successComplete = ()=>{
swal({
title:"입력하신 이메일로 임시비밀번호가 발급되었습니다.",
icon:"success",
className:"swal-hover"
});
};
async function successHandler(){
await successComplete();
await closeWindow();
}
$(function(){
$("#a-find-submit-btn").click(()=>{
if(isEmpty($('#find-name').val())||isEmpty($('#find-email').val())){
swal({
title:"모든 값을 입력해 주세요.",
icon:"warning",
className:"swal-hover"
});
return false;
}else if(isIncludeSpace($('#find-email').val())) {
$('#a-find-submit').empty();
$('#a-find-submit').html("<p style='color:red'>이메일에는 공백을 포함할 수 없습니다</p>")
return false;
}else if(isIncludeSpace($('#find-name').val())) {
$('#a-find-submit').empty();
$('#a-find-submit').html("<p style='color:red'>이름에는 공백을 포함할 수 없습니다</p>")
return false;
}else if(!isEmail($('#find-email').val())){
$('#a-find-submit').empty();
$('#a-find-submit').html("<p style='color:red'>이메일 형식을 확인해 주세요</p>");
return false;
}else{
const csrf = $('#find-csrf').val();
console.log(csrf);
$.ajax({
url:"user/find",
dataType:"html",
type:"POST",
data:{
email:$('#find-email').val(),
name:$('#find-name').val()
},
beforeSend : function(xhr) {
$('#a-find-submit').empty();
$('#a-find-submit').html("<p style='color:green'>확인중...잠시만 기달려 주세요.</p>");
$('a-find-submit-btn').attr('disabled',true);
xhr.setRequestHeader('X-CSRF-Token', csrf);
},
success: (data)=>{
if(data==="false"){
$('a-find-submit-btn').removeAttr('disabled');
$('#a-find-submit').empty();
$('#a-find-submit').html("<p style='color:red'>일치하는 회원정보가 없습니다.</p>");
return false;
}else{
successHandler();
}
}
})
}
}); //a-find-submit-btn End
})<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Banner.java
package com.ability.dto;
import java.sql.Date;
public class Banner {
private int id;
private Date date_created;
private Date last_updated;
private String title;
private String banner_desc;
private String connect_url;
private int enabled;
private String client;
private String file_path;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public Date getLast_updated() {
return last_updated;
}
public void setLast_updated(Date last_updated) {
this.last_updated = last_updated;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBanner_desc() {
return banner_desc;
}
public void setBanner_desc(String banner_desc) {
this.banner_desc = banner_desc;
}
public String getConnect_url() {
return connect_url;
}
public void setConnect_url(String connect_url) {
this.connect_url = connect_url;
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
}<file_sep>/front/components/presentational/atoms/ButtonComponent.js
import React from 'react';
import {Button} from 'react-bootstrap';
/**
* @author 정규현
* @summary 버튼을 만드는 컴포넌트
*/
export const ButtonComponent=(props)=>{
return(
<Button as="input"
key={props.key}
variant={props.variant ? props.variant : "primary"}
onClick={props.onclick}
style={props.css}
id={props.id}
value={props.name}
size={props.size} disabled={props.disabled}
>
</Button>
);
}
export const ButtonComponent2=(props)=>{
return(
<Button as="input"
key={props.key}
variant={props.variant ? props.variant : "light"}
onClick={props.onclick}
style={props.css}
id={props.id}
value={props.name}
size={props.size} disabled={props.disabled}
>
</Button>
);
}
export const ButtonComponentCustom = (props)=>
<Button variant="primary" size={props.size} style={props.css}><b>{props.name}</b></Button><file_sep>/front/components/presentational/molecules/UserList.js
import React, { Component } from 'react';
import User from '../store/User';
/**
* @author 정규현
* @summary 유저의 view 담당
*/
class UserList extends Component {
onEdit = user => {
this.props.onEdit(user)
};
onDelete = user => {
this.props.onDelete(user)
};
render () {
const userList = this.props.users.map(user => (
<User data={ user } key={ user.id }
onEdit={ this.onEdit }
onDelete={ this.onDelete } />
))
return <div>{ userList }</div>
};
};
export default UserList;<file_sep>/front/components/container/organisms/SideBar.js
import React, {useEffect,useState} from 'react';
import {ListGroup} from 'react-bootstrap';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faComments, faHome, faQuestionCircle, faCrow, faUsers, faIdBadge, faLaptopCode, faUserShield } from '@fortawesome/free-solid-svg-icons';
/**
* @auth 정진호
* @summary 사이드바 컴포넌트 ++ 라우터처리
* @see 정규현 리펙토링 / 넥스트 적용
*/
const SideBar = (props) =>{
const [windowGlobal,setWindowGlobal]=useState("");
const [isAdmin,setIsAdmin]=useState(false);
useEffect(()=>{
setWindowGlobal(location.pathname);
if(localStorage.getItem('role_name')=='ROLE_ADMIN'){
setIsAdmin(true);
}
});
function loadAdmin(){
if (isAdmin) {
return <Link href="/admin/board" >
<ListGroup.Item action active={windowGlobal === "/admin/board" ? true : false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faUserShield} style={{ width: "auto", height: "14px" }} /> 관리자</a>
</ListGroup.Item>
</Link>
}
}
const Admin = loadAdmin();
return (
<>
<div id="sideBarHover">
<ListGroup variant="flush" className="text-center">
<Link href="/" >
<ListGroup.Item action active={windowGlobal==="/"?true:false} onClick={props.onClick}>
<a><FontAwesomeIcon icon={faHome} style={{width:"auto",height:"14px"}}/> Home</a>
</ListGroup.Item>
</Link>
<h6 style={{marginRight:"70px",marginBottom:"0px",marginTop:"10px"}}>PUBLIC</h6>
<Link href="/question/board" >
<ListGroup.Item action active={windowGlobal==="/question/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faQuestionCircle} style={{width:"auto",height:"14px"}}/> 질의 응답
</a>
</ListGroup.Item>
</Link>
<Link href="/community/board" >
<ListGroup.Item action active={windowGlobal==="/community/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faCrow} style={{width:"auto",height:"14px"}}/> 자유 게시판</a>
</ListGroup.Item>
</Link>
<Link href="/developer/board" >
<ListGroup.Item action active={windowGlobal==="/developer/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faUsers} style={{width:"auto",height:"14px"}}/> 개발자들</a>
</ListGroup.Item>
</Link>
<Link href="/job/board" >
<ListGroup.Item action active={windowGlobal==="/job/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faIdBadge} style={{width:"auto",height:"14px"}}/> 개발자 모집</a>
</ListGroup.Item>
</Link>
<Link href="/project/board" >
<ListGroup.Item action active={windowGlobal==="/project/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faLaptopCode} style={{width:"auto",height:"14px"}}/> 프로젝트 자랑</a>
</ListGroup.Item>
</Link>
<Link href="/chat/board" >
<ListGroup.Item action active={windowGlobal==="/chat/board"?true:false} onClick={props.onClick} id="sidebar">
<a><FontAwesomeIcon icon={faComments} style={{width:"auto",height:"14px"}}/> 채팅</a>
</ListGroup.Item>
</Link>
{Admin}
</ListGroup>
</div>
</>
);
}
export default SideBar;<file_sep>/front/components/presentational/molecules/BannerCard.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
/**
* @author 강기훈
* @summary 배너 조회 게시판 배너 카드 컴포넌트
*/
const endpoint = process.env.NODE_ENV === 'production'? "?" : "?";
const container = {
display: "flex",
justifyContent: "space-around",
marginBottom: "50px"
}
const banner_info = {
display: "flex",
flexDirection: "column",
}
const image = {
width: "500px",
height: "250px"
}
const info_css = {
marginBottom: "10px",
fontFamily: "sans-serif",
color: "#636e72"
}
const info_title = {
marginBottom: "10px",
fontFamily: "sans-serif",
color: "#5F4B8B",
fontWeight: "bold",
fontSize: "36px"
}
const hrCss = {
borderTop: "1px solid #dfe6e9",
marginBottom: "50px",
width: "95%",
marginLeft: "15px"
}
const price = {
fontWeight: "bold",
color: "#5F4B8B",
fontSize: "20px"
}
const link = {
color: "#0984e3",
fontWeight: "bold"
}
const font_css = {
fontWeight: "bold",
}
function date(date_created) {
let year = date_created.substring(0, 4);
let month = date_created.substring(5, 7);
let day = date_created.substring(8, 10);
let edit_created = `${year}-${month}-${day}`;
return edit_created;
}
const BannerCard = (props) => {
const [todayCount, setTodayCount] = useState(0);
const [bannerId, setBannerId] = useState(props.id);
useEffect(() => {
axios.get(endpoint + "/clicktoday", {
params: {
id: bannerId
}
}).then(response => {
setTodayCount(response.data.count);
})
},[bannerId])
return (
<>
<div style={container}>
<img style={image} src={props.image} />
<div style={banner_info}>
<span style={info_title}>{props.title}</span>
<span style={info_css}>{props.description ? props.description : "등록된 소개가 없습니다."}</span>
<span style={info_css}><span style={font_css}>광고주 : </span>{props.client}</span>
<span style={info_css}><span style={font_css}>누적 클릭수 : </span>{props.click_count}</span>
<span style={info_css}><span style={font_css}>금일 클릭수 : </span>{todayCount}</span>
<span style={info_css}><span style={font_css}>등록일 : </span>{date(props.date_created)}</span>
<span style={info_css}><span style={font_css}>URL : </span><a style={link} href={props.url}>{props.url ? props.url : "등록된 url이 없습니다."}</a></span>
<span style={info_css}><span style={font_css}>광고이익 : </span> (클릭수*1) -> <span style={price}>{props.click_count * 1}원</span></span>
</div>
</div>
<div style={hrCss}></div>
</>
)
}
export default BannerCard<file_sep>/Ability-SpringBoot1/src/main/resources/static/js/companySignup.js
/**
* @author 정진호
* @summary Company 관련 js
*/
let isEmpty = (value)=> {
if( value == "" || value == null || value == undefined || ( value != null && typeof value == "object" && !Object.keys(value).length ) ){
return true
}else{
return false
}
};
function isEmail(email) {
const pattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
if (pattern.test(email)) return true;
else return false;
}
function isPassword(password) {
const pattern = /^(?=.*[a-zA-Z])((?=.*\d)|(?=.*\W)).{8,20}$/;
if (pattern.test(password)) return true;
else return false;
}
function isIncludePasswordSpace(password) {
const pattern = /\s/;
if (password.match(pattern)) return true;
else return false;
}
function isIncludePasswordSpecial(password) {
const pattern = /[`~!@#$%^&*|\\\'\";:\/?\-]/;
if (password.match(pattern)) return true;
else return false;
}
function isIncludeCompanyTelSpecial(company_tel) {
const pattern = /^\d{2,3}-\d{3,4}-\d{4}$/;
if (company_tel.match(pattern)) return true;
else return false;
}
function isIncludeEnglish(str) {
const pattern = /[a-zA-Z]/;
if (str.match(pattern)) return true;
else return false;
}
function isIncludeNumber(str) {
const pattern = /[0-9]/;
if (str.match(pattern)) return true;
else return false;
}
function isIncludeKorean(str) {
const pattern = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/;
if (str.match(pattern)) return true;
else return false;
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#register_image').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#register_file").change(function() {
readURL(this);
});
$(function(){
$("#signup").click(()=>{
if(isEmpty($('#company_name').val())||isEmpty($('#userid').val())||isEmpty($('#company_area').val())||isEmpty($('#company_email').val())||isEmpty($('#company_tel').val())||isEmpty($('#manager_tel').val())||isEmpty($('#homepage_url').val())||isEmpty('#register_number').val()){
alert("입력 사항을 모두 입력해주세요.");
return false;
}else if($('#email_check').text()!="확인완료"||$('#register_numbercheck').text()!="확인완료") {
$('#signup_check').empty();
$('#signup_check').html("<b style='color:red'> 중복 확인을 해주세요.</b>")
return false;
}
}); //signup end
$('#register_number').click(()=>{
$('#register_number_btn').attr('background','#5F4B8B');
$('#register_number_btn').html('중복확인');
$('#register_number_btn').removeAttr('disabled');
$('#register_numbercheck').empty();
$('#register_number').val('');
}); //nick_name click event end
$('#register_number_btn').click(()=>{
var address = "";
var xloc="";
var yloc="";
address = document.getElementById('company_area').value;
console.log(address);
var geocoder= new google.maps.Geocoder();
geocoder.geocode({'address':address,'partialmatch':true},googlexy);
function googlexy(result,status){
if(status=='OK'&&result.length > 0){
console.log(result[0].geometry.location.lat()," : lat");
console.log(result[0].geometry.location.lng()," : lng");
xloc =result[0].geometry.location.lat();
yloc =result[0].geometry.location.lng();
$('#xloc').val(xloc);
$('#yloc').val(yloc);
console.log("xloc",$('#xloc').val());
console.log("yloc",$('#yloc').val());
}else{
$('#email_btn').attr('background','#c6badf');
$('#register_file').focus();
}
}
const servicekey = "<KEY>";
let register_number = $("#register_number").val();
if(isEmpty(register_number)){
$('#register_numbercheck').html('<small style="color:red"> 사업자 등록번호를 입력해 주세요.</small>');
}else if(isIncludePasswordSpace(register_number)){
$('#register_numbercheck').html('<small style="color:red"> 공백은 사용할 수 없습니다.</small>');
$('#register_numbercheck').val('');
}else{
$.ajax({
url:"https://business.api.friday24.com/closedown/"+register_number,
beforeSend : function(xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader('Authorization',"Bearer <KEY>");
},
type:"get",
success: (data)=>{
if(data.state === "normal") {
$('#register_numbercheck').empty();
$('#register_numbercheck').html('<small style="color:green"> 확인완료</small>')
}else{
$('#register_numbercheck').empty();
$('#register_numbercheck').html('<small style="color:red"> 확인실패</small>')
}
},
error: (xhr)=> {
$('#register_numbercheck').empty();
$('#register_numbercheck').html('<small style="color:red"> 올바른 사업자번호가 아닙니다.</small>')
}
})
}
}); // nick_name_btn click event end
$('#company_email').click(()=>{
$('#email_btn').attr('background','#5F4B8B');
$('#email_btn').html('중복확인');
$('#email_btn').removeAttr('disabled');
$('#email_check').empty();
$('#company_email').val('');
}); //email click event end
$("#email_btn").click(()=>{
let email = $("#company_email").val();
if(isEmpty(email)){
$('#email_check').html('<small style="color:red"> 이메일을 입력해 주세요.</small>');
}else if(!isEmail(email)){
$('#email_check').html('<small style="color:red"> 올바른 이메일 형식이 아닙니다.</small>');
}else{
$.ajax({
url:"ajax/companyemail",
dataType:"html",
type:"GET",
data:{
company_email:email
},
success: (data)=>{
if(data=="true"){
$('#email_check').html('<small style="color:red"> 이미 존재하는 이메일 입니다.</small>');
$('#company_email').focus();
}else{
$('#email_check').html('<small style="color:green"> 사용할 수 있는 이메일 입니다.</small>');
$('#email_btn').attr('disabled',true);
$('#email_btn').empty();
$('#email_btn').html('<b>확인완료</b>');
$('#email_btn').attr('background','#c6badf');
$('#company_tel').focus();
}
}
})
}
}); // email_btn click event end
$('#register_number').keyup(()=>{
if(isIncludePasswordSpecial($('#register_number').val())){
$('#register_numbercheck').empty();
$('#register_numbercheck').html('<small style="color:red"> \"-\"는 생략해주세요</small>');
}
});
$('#company_tel').keyup(()=>{
if(isIncludeCompanyTelSpecial($('#company_tel').val())){
$('#company_tel_numbercheck').empty();
$('#company_tel_numbercheck').html('<small style="color:red"> 올바르지 않는 형식입니다.</small>');
}
});
/* $('#password, #repassword').keyup(()=>{
if($('#password').val().length<8){
$('#password_check').empty();
$('#password_recheck').empty();
$('#password_check').html('<small> 영문, 숫자, 특수문자 포함 8~20자리 입력</small>')
}else if(!isIncludeEnglish($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<small style="color:red"> 영문자를 포함해 주세요</small>');
}else if(!isIncludePasswordSpecial($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<small style="color:red"> 특수문자를 포함해 주세요</small>');
}else if(!isIncludeNumber($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<small style="color:red"> 숫자를 포함해 주세요</small>');
}else if($('#password').val() != $('#repassword').val()){
$('#password_check').empty();
$('#password_recheck').html('<small style="color:red"> 비밀번호 불일치</small>');
}else{
$('#password_recheck').html('<small style="color:green"> 비밀번호 일치</small>');
}
});*/
})<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/UserSimple.java
package com.ability.dto.custom;
/**
*
* @author jkh
* @summary 자주 쓰이는 데이터만 받아오는 UserDTO(as UserSimple).
* @desc User 테이블과 role 테이블을 조인함.
*
*/
public class UserSimple {
private int userid;
private String email;
private String nick_name;
private String user_image;
private int reputation;
private String role_name;
private String password;
private int enabled;
public UserSimple() {}
public UserSimple(int userid, String email, String nick_name, String user_image, int reputation, String role_name) {
super();
this.userid = userid;
this.email = email;
this.nick_name = nick_name;
this.user_image = user_image;
this.reputation = reputation;
this.role_name = role_name;
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
}
<file_sep>/front/components/container/templatses/Chatting.js
import React,{Component} from 'react';
import ChattingRooms from '../../presentational/atoms/ChattingRooms';
import ChattingModal from '../../presentational/atoms/ChattingModal';
import { GridArea } from '../organisms/GridArea';
import TitleComponent from '../../presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faComments } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';
/**
*
* @author 강기훈
* @summary 채팅 게시판 페이지
* @see 정규현 메인 타이틀 컴포넌트로 통일
*/
const EndPoint = process.env.NODE_ENV === 'production'? "?" : "?";
const EndPoint2 = process.env.NODE_ENV === 'production'? "?" : "?";
const chat_hr = {
height: "420px",
width: "48.5%",
position: "absolute",
borderRight: "1px solid #d6d6d6",
zIndex: "-1"
};
class Chatting extends Component {
constructor(props){
super(props);
this.state = {
roomList :[]
}
}
async componentDidMount(){
await axios.get(EndPoint).then(response=>{
this.setState({
roomList:response.data
})
})
}
render(){
const RoomList = this.state.roomList.map((room)=>{
return <ChattingRooms key={room.roomId} roomId={room.roomId} title={room.name} tags={room.tags} roomUserMaxCount={room.people} link={EndPoint2+"/chat/room/"+room.roomId}/>
});
return(
<GridArea>
<div className="chat_sub_div">
<TitleComponent title="채팅">
<FontAwesomeIcon icon={faComments}/>
</TitleComponent>
<div className="chat_sub_btn">
<ChattingModal name="방만들기"/>
</div>
</div>
<div style={chat_hr}>
</div>
<div className="chat_rooms">
{RoomList}
</div>
</GridArea>
);
}
}
export default Chatting;
<file_sep>/front/components/container/organisms/bjob.js
import React,{useState,useEffect,useCallback} from 'react';
import HireList from '../../presentational/molecules/HireList';
import {Row,Col, ToggleButton, ToggleButtonGroup, Container} from 'react-bootstrap';
import { UserSearchbarComponent3 } from '../../presentational/atoms/SearchbarComponent';
import axios from 'axios';
import LodingComponent from '../../presentational/atoms/LodingComponent';
import Page from '../../presentational/molecules/Page';
import Router from 'next/router';
/**
* @author 신선하
* @summary
*
* @author 정진호
* @summary Job_Board 게시판 구현
*/
const css = {
verticalAlign:"middle"
}
const Job = ()=>{
const [searchWord, setSearchWord] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [isSearch, setIsSearch] = useState(0);
const [isLoding, setIsLoding] = useState(false);
const [dataList, setDataList] = useState([]);
const [placeHolder, setPlaceHolder] = useState('글 제목 검색');
const [orderby, setOrderby] = useState(0);
const [totalListCount, setTotalListCount] = useState(0);
const [userrole,setUserrole] = useState("");
const onChangeSearchInput = useCallback((e) =>{
setSearchWord(e.target.value);
},[searchWord]);
const handlePageChange= useCallback((pageNumber)=> {
setCurrentPage(pageNumber);
},[currentPage]);
const onKeyPressSearch = useCallback((e)=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
}else if(e.charCode == 13){
setIsSearch(isSearch+1);
}
},[searchWord,placeHolder])
const onClickSearchButton = useCallback(()=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
};
setIsSearch(isSearch+1);
},[searchWord,placeHolder]);
const onChangeToggle = useCallback((e)=>{
const str = e.pop();
if(typeof str != "string"){
return;
}
setOrderby(str);
setIsSearch(0);
},[orderby,isSearch]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
useEffect( () =>{
setIsLoding(true);
setDataList([]);
setUserrole(localStorage.getItem("role_name"));
const endpoint = backUrl;
axios.get(endpoint,{
params : {
orderby : orderby,
currentpage : currentPage,
userid: Router.query['userid'],
word: isSearch!=0 ? searchWord : "",
categoryid:4
}
}).then(() => {
setIsLoding(false);
setDataList(response.data.postBoardList);
setCurrentPage(response.data.currentPage);
setTotalListCount(response.data.totalListCount);
})
.catch(()=>{
setIsLoding(false);
});
},[orderby,currentPage,totalListCount,isSearch]);
return(
<>
{isLoding && <LodingComponent/>}
{ userrole == "ROLE_COMPANY" ?
<>
</> :
<>
</>
}
<Container>
<Row style={{marginTop:"25px"}} >
<Col sm={6} md={8} style={css}>
<ToggleButtonGroup
type="checkbox"
value={orderby}
onChange={onChangeToggle}
>
<ToggleButton value="0" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">최신순</ToggleButton>
<ToggleButton value="1" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">조회순</ToggleButton>
</ToggleButtonGroup>
</Col>
<Col sm={6} md={4}><UserSearchbarComponent3 onChange={onChangeSearchInput} onClick={onClickSearchButton} content={placeHolder}
onKeyPress={onKeyPressSearch}/></Col>
</Row>
<hr style={{marginBottom:"5px"}}/><br/>
{ dataList.length > 0 ? <>
{
dataList.map((content)=> {
return(
<div key={content.id}>
<HireList key={content.id}
seq={content.id}
event={content.period.substr(0,10)}
hireTitle2={content.title}
subCompany={content.job_type}
company={content.company_name}
subtitle={content.subtitle}
loaction={content.area}
count={content.viewcount}
hashtag={content.tags}
hits={content.view_count}
date={content.date_created}
allscrap={content.allscrap}
scrap={content.scrap}/>
</div>
);
})
}
<Row style={{marginTop:"1.4rem",marginBottom:"2rem",justifyContent:"center"}}>
<div style={{textAlign:"center"}}>
<Page currentPage={currentPage} totalListCount={totalListCount} currentPage={currentPage} handlePageChange={handlePageChange}/>
</div>
</Row>
</>: <div style={{margin: "3% 38%", width: "100%"}}>즐겨찾기한 글이 없습니다.</div>}
</Container>
</>
);
}
export default Job;
<file_sep>/front/sagas/main.js
import {all, fork, takeLatest, put, call} from 'redux-saga/effects';
import axios from 'axios';
import { MAIN_DATA_FAILURE, MAIN_DATA_SUCCESS, MAIN_DATA_REQUEST } from '../reducers/main';
/**
* @author 정규현
* @summary 메인 페이지 saga
* @version 퍼블릭 배포용으로 변경
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
function getMainDataAPI(){
return axios.post(backUrl+"/home");
}
function* getMainPageData() {
try {
const result = yield call(getMainDataAPI);
yield put({
type: MAIN_DATA_SUCCESS,
data: result.data,
});
} catch (error) {
console.error(error);
yield put({
type:MAIN_DATA_FAILURE,
error: error,
});
}
}
function* watchGetMainPageData(){
yield takeLatest(MAIN_DATA_REQUEST, getMainPageData);
};
export default function* mainSaga(){
yield all([
fork(watchGetMainPageData)
])
}<file_sep>/front/components/presentational/molecules/ReplyComplete.js
import React, {Component} from 'react';
import {ButtonComponent} from '../atoms/ButtonComponent';
import dynamic from 'next/dynamic'
import {ReplyCompleteComponent} from '../atoms/ReplyComponent';
import { Row,Col } from "react-bootstrap";
import axios from 'axios';
import Router from 'next/router';
import swal from 'sweetalert';
const buttoncss = {
textAlign : 'right',
marginTop : "1rem"
};
const CkeditorOne2 = dynamic(() =>import('../atoms/CkeditorOne2'),{
ssr : false
});
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
class ReplyComplete extends Component {
constructor(props){
super(props);
this.state = ({
replys : [],
data : "<p></p>",
seq : this.props.seq,
userid : localStorage.getItem("userid"),
modify : false,
targetid : "",
replyOwner : "",
reply_content : "",
reply_content2 : "",
isModify : false,
id : "",
reputation: 0
});
this.delete = this.delete.bind(this);
this.getList = this.getList.bind(this);
this.insert = this.insert.bind(this);
this.onChangeCk = this.onChangeCk.bind(this);
this.getReplyListOne = this.getReplyListOne.bind(this);
this.modifyReplyOk = this.modifyReplyOk.bind(this);
this.onClickModifyCancel = this.onClickModifyCancel.bind(this);
this.onChangeCkeditor = this.onChangeCkeditor.bind(this);
}
componentDidMount(){
if(this.state.seq !== ""){
this.getList();
let userid = localStorage.getItem("userid");
if(userid !== "" &&userid!==null && userid!==undefined){
axios.get(backUrl+"/user/getreputation",{
params : {
userid : Number(localStorage.getItem("userid"))
}
}).then((res)=>{
this.setState({
reputation : res.data.reputation
})
})
}
}else {
return
}
}
async getReplyListOne(e){
await axios.get(backUrl, {
params : {
id : e.target.id
}
}).then((response)=>{
this.setState({
replyOwner : response.data.userid,
reply_content2 : response.data.reply_content,
id : response.data.id,
targetid : response.data.id,
isModify : true
})
})
}
async modifyReplyOk(e){
let Forms = new FormData();
Forms.append("id",e.target.id);
Forms.append("reply_content",this.state.reply_content2);
await axios({
method :'put',
baseURL : backUrl,
data : Forms
}).then((response)=>{
this.setState({
isModify : false,
reply_content : this.state.reply_content2
});
}).catch((xhr)=>{
swal({
title: "등록 실패",
text: "답글 양식에 맞지 않습니다.",
icon: "/static/image/Logo2.png",
});
});
this.getList();
}
async getList(){
await axios.get(backUrl,{
params : {
seq: this.state.seq
}
}).then((response) => {
this.setState({
replys : response.data
});
}).catch(xhr =>{
alert(xhr);
})
}
async delete(e){
let id = e.target.id;
const willDelete = await swal({
title: "삭제 하시겠습니까?",
text: "해당 답변을 삭제하시겠습니까?"
});
if(willDelete){
axios.get(backUrl,{
params : {
id : id
}
}).then(()=> {
swal({
title: "삭제 완료",
text: "능력치가 -5 떨어졌습니다",
icon: "/static/image/Logo2.png",
});
this.getList();
})
}
}
onChangeCk(e){
this.setState({
data : e.editor.getData()
})
}
onClickModifyCancel(){
this.setState({
isModify : false
})
}
onChangeCkeditor(e){
this.setState({
reply_content2 : e.editor.getData()
})
}
insert=()=> {
if(this.state.data !== "" && this.state.data.trim().replace(/[ ]|[\s]/gi,"") !== "<></>"){
if(Number(this.state.reputation) >= 20){
const userid = localStorage.getItem('userid');
let Forms = new FormData();
Forms.append("userid",userid);
Forms.append("seq",this.state.seq);
Forms.append("reply_content",this.state.data);
axios({
method :'post',
baseURL : backUrl,
data : Forms
}).then(()=>{
this.setState({
reply : this.state.reply,
data : "<p></p>"
})
swal({
title: "등록 성공",
text: "능력치가 +5 올랐습니다.",
icon: "/static/image/Logo2.png",
});
this.getList();
}).catch((xhr)=>{
console.log(xhr);
});
}else{
swal({
title:"작성 실패",
text:"능력치 [20] 부터 작성이 가능합니다.",
icon:"/static/image/Logo2.png"
})
}
}else{
swal({
title:"작성 실패",
text:"빈칸은 입력이 불가능합니다.",
icon:"/static/image/Logo2.png"
})
return;
}
}
render() {
let reply =this.state.replys;
return(
<>
<Row>
<Col xs={12}>
<small style={{paddingLeft:"10px", color:"#b5a5b5", marginBottom:"5px"}}>답글 ({reply.length})</small>
{reply.length > 0 ?
reply.map((reply, index) => {
return (
<ReplyCompleteComponent userid={reply.userid}
onclick={this.delete}
seq={this.props.seq}
id={reply.id}
user_image={reply.user_image}
nick_name={reply.nick_name}
date_created={reply.date_created}
reply_content={reply.reply_content} key={index}
reply_content2={this.state.reply_content2}
vote_count = {reply.vote_count}
modify={this.state.modify}
getReplyListOne = {this.getReplyListOne}
modifyReplyOk = {this.modifyReplyOk}
isModify = {this.state.isModify}
targetid = {this.state.targetid}
onClickModifyCancel = {this.onClickModifyCancel}
onChangeCkeditor = {this.onChangeCkeditor}
/>
)
})
: <div style={{textAlign:"center"}}>
<small>등록된 답변이 없습니다.</small>
<br/>
<br/>
</div>
}
<br/>
<br/>
{this.state.userid != undefined && this.state.userid != "" && this.state.userid != 0?
<CkeditorOne2 data={this.state.data} onChange={this.onChangeCk} list={this.props.list}/>
:
<h6></h6>
}
</Col>
<Col xs={12} style={buttoncss}>
<br></br>
<br></br>
<ButtonComponent onclick={() => Router.push('/question/board')} name="목록" />
{this.state.userid != undefined && this.state.userid != "" && this.state.userid != 0 ?
<ButtonComponent onclick={this.insert} name="답변 제출" />
:
<h6></h6>
}
</Col>
</Row>
</>
)
}
};
export default ReplyComplete;<file_sep>/Ability-SpringBoot1/src/main/resources/static/js/signup.js
/**
* @author jkh
* @summary 회원 관련 로직 구현
*/
let isEmpty = (value)=> {
if( value == "" || value == null || value == undefined || ( value != null && typeof value == "object" && !Object.keys(value).length ) ){
return true
}else{
return false
}
};
function isEmail(email) {
const pattern = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
if (pattern.test(email)) return true;
else return false;
}
function isPassword(password) {
const pattern = /^(?=.*[a-zA-Z])((?=.*\d)|(?=.*\W)).{8,20}$/;
if (pattern.test(password)) return true;
else return false;
}
function isIncludePasswordSpace(password) {
const pattern = /\s/;
if (password.match(pattern)) return true;
else return false;
}
function isIncludePasswordSpecial(password) {
const pattern = /[`~!@#$%^&*|\\\'\";:\/?]/;
if (password.match(pattern)) return true;
else return false;
}
function isIncludeEnglish(str) {
const pattern = /[a-zA-Z]/;
if (str.match(pattern)) return true;
else return false;
}
function isIncludeNumber(str) {
const pattern = /[0-9]/;
if (str.match(pattern)) return true;
else return false;
}
function isIncludeKorean(str) {
const pattern = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/;
if (str.match(pattern)) return true;
else return false;
}
const closeWindow = ()=>{
window.close();
}
$(function(){
$("#signup").click(()=>{
if(isEmpty($('#name').val())||isEmpty($('#nick_name').val())||isEmpty($('#area').val())||isEmpty($('#email').val())||isEmpty($('#password').val())||isEmpty($('#repassword').val())){
swal({
title:"모든 값을 입력해 주세요.",
icon:"warning",
className:"swal-hover"
});
return false;
}else if($('#nick_name_btn').text()!="확인완료" || $('#email_btn').text()!="확인완료") {
$('#signup_check').empty();
$('#signup_check').html("<b style='color:red'> 중복 확인을 해주세요.</b>")
return false;
}else if($('#password_recheck').text().trim()!="비밀번호 일치"){
$('#signup_check').empty();
$('#signup_check').html("<b style='color:red'> 비밀번호 일치 여부 확인을 해주세요.</b>");
return false;
}else{
const email = $('#email').val();
swal({
title:email,
text:"이메일 주소로 인증번호가 발송되었습니다. 24시간 동안만 유효한 인증번호이며, 24시간 경과시 회원가입 이력은 삭제됩니다.",
icon:"success",
}).then((bntValue)=>{
window.close();
})
}
}); //signup end
$('#nick_name').click(()=>{
$('#nick_name_btn').attr('background','#5F4B8B');
$('#nick_name_btn').html('중복확인');
$('#nick_name_btn').removeAttr('disabled');
$('#nick_name_check').empty();
$('#nick_name').val('');
}); //nick_name click event end
$('#nick_name_btn').click(()=>{
let nick_name = $("#nick_name").val();
if(isEmpty(nick_name)){
$('#nick_name_check').html('<b style="color:red"> 닉네임을 입력해 주세요.</b>');
}else if(isIncludePasswordSpace(nick_name)){
$('#nick_name_check').html('<b style="color:red"> 공백은 사용할 수 없습니다.</b>');
$('#nick_name').val('');
}else{
$.ajax({
url:"user/ajax/nick",
dataType:"html",
type:"GET",
data:{
nickname:nick_name
},
success: (data)=>{
if(data=="true"){
$('#nick_name_check').html('<b style="color:red"> 이미 존재하는 닉네임 입니다.</b>');
$('#nick_name').focus();
}else{
$('#nick_name_check').html('<b style="color:green"> 사용할 수 있는 닉네임 입니다.</b>');
$('#nick_name_btn').attr('disabled',true);
$('#nick_name_btn').empty();
$('#nick_name_btn').html('<b>확인완료</b>');
$('#nick_name_btn').attr('background','#c6badf');
$('#area').focus();
}
}
})
}
}); // nick_name_btn click event end
$('#email').click(()=>{
$('#email_btn').attr('background','#5F4B8B');
$('#email_btn').html('중복확인');
$('#email_btn').removeAttr('disabled');
$('#email_check').empty();
$('#email').val('');
}); //email click event end
$("#email_btn").click(()=>{
let email = $("#email").val();
if(isEmpty(email)){
$('#email_check').html('<b style="color:red"> 이메일을 입력해 주세요.</b>');
}else if(!isEmail(email)){
$('#email_check').html('<b style="color:red"> 옳바른 이메일 형식이 아닙니다.</b>');
}else{
$.ajax({
url:"user/ajax/email",
dataType:"html",
type:"GET",
data:{
email:email
},
success: (data)=>{
if(data=="true"){
$('#email_check').html('<b style="color:red"> 이미 존재하는 이메일 입니다.</b>');
$('#email').focus();
}else{
$('#email_check').html('<b style="color:green"> 사용할 수 있는 이메일 입니다.</b>');
$('#email_btn').attr('disabled',true);
$('#email_btn').empty();
$('#email_btn').html('<b>확인완료</b>');
$('#email_btn').attr('background','#c6badf');
$('#password').focus();
}
}
})
}
}); // email_btn click event end
$('#password, #repassword').keyup(()=>{
if($('#password').val().length<8){
$('#password_check').empty();
$('#password_recheck').empty();
$('#password_check').html('<b> 영문, 숫자, 특수문자 포함 8~20자리 입력</b>')
}else if(!isIncludeEnglish($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<b style="color:red"> 영문자를 포함해 주세요</b>');
}else if(!isIncludePasswordSpecial($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<b style="color:red"> 특수문자를 포함해 주세요</b>');
}else if(!isIncludeNumber($('#password').val())){
$('#password_check').empty();
$('#password_check').html('<b style="color:red"> 숫자를 포함해 주세요</b>');
}else if($('#password').val() != $('#repassword').val()){
$('#password_check').empty();
$('#password_recheck').html('<b style="color:red"> 비밀번호 불일치</b>');
}else{
$('#password_recheck').html('<b style="color:green"> 비밀번호 일치</b>');
}
}); //#password confirm event end
})<file_sep>/front/components/container/templatses/UserDelete.js
import React ,{Component}from 'react';
import { InputTextBox} from '../../presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
/**
* @author 우세림
* @summary 개발자들 회원탈퇴
*/
const user_mod_input_css ={
height: "35px"
}
class UserModify extends Component {
render(){
return (
<>
<h5 className="user_add_title">
회원탈퇴
</h5>
<div className="user_del">
<div className="user_md_profile_div">
<span className="user_md_profile_span">비밀번호</span>
<InputTextBox css={user_mod_input_css} type="password"/>
</div>
<div className="user_md_profile_div">
<span className="user_md_profile_span">비밀번호 확인</span>
<InputTextBox css={user_mod_input_css} type="password"/>
</div>
</div>
<div className="user_md_btn">
<ButtonComponent name="취소" />
<ButtonComponent name="탈퇴하기" />
</div>
</>
);
}
}
export default UserModify;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/JobBoardListPaging.java
package com.ability.dto.custom;
import java.util.List;
/**
* 구인게시판 페이징
*
* @author 정진호
* @summary Job_Board 페이징구현
*/
public class JobBoardListPaging {
private List<HireBoardList> postBoardList;
private int totalPage;
private int currentPage;
private int startPageBlock;
private int endPageBlock;
private int pageSize;
private int totalListCount;
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<HireBoardList> getPostBoardList() {
return postBoardList;
}
public void setPostBoardList(List<HireBoardList> postBoardList) {
this.postBoardList = postBoardList;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getStartPageBlock() {
return startPageBlock;
}
public void setStartPageBlock(int startPageBlock) {
this.startPageBlock = startPageBlock;
}
public int getEndPageBlock() {
return endPageBlock;
}
public void setEndPageBlock(int endPageBlock) {
this.endPageBlock = endPageBlock;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalListCount() {
return totalListCount;
}
public void setTotalListCount(int totalListCount) {
this.totalListCount = totalListCount;
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/BoardListPaging.java
package com.ability.dto.custom;
import java.util.List;
/**
* @author 정규현
* @summary (자유, 포스트) 게시판 리스트 + 페이징 정보
*/
public class BoardListPaging {
private List<PostBoardList> postBoardList;
private int totalPage;
private int currentPage;
private int startPageBlock;
private int endPageBlock;
private int pageSize;
private int totalListCount;
private int Allcount;
public int getAllcount() {
return Allcount;
}
public void setAllcount(int allcount) {
Allcount = allcount;
}
public List<PostBoardList> getPostBoardList() {
return postBoardList;
}
public void setPostBoardList(List<PostBoardList> postBoardList) {
this.postBoardList = postBoardList;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getStartPageBlock() {
return startPageBlock;
}
public void setStartPageBlock(int startPageBlock) {
this.startPageBlock = startPageBlock;
}
public int getEndPageBlock() {
return endPageBlock;
}
public void setEndPageBlock(int endPageBlock) {
this.endPageBlock = endPageBlock;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalListCount() {
return totalListCount;
}
public void setTotalListCount(int totalListCount) {
this.totalListCount = totalListCount;
}
}
<file_sep>/front/components/presentational/atoms/MapComponent.js
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
/**
* @author 신선하
* @summary 지도 컴포넌트 --> 장소 검색 가능하게 수정예정
* @usage
**/
const style = {
width: '98%',
height: '100%'
}
export class MapComponent extends Component {
constructor(props){
super(props);
this.state={
map : 0,
activeMarker : "",
showingInfoWindow : "",
selectedPlace : "",
}
this.onClickMap = this.onClickMap.bind(this);
this.onClickMap2 =this.onClickMap2.bind(this);
}
onClickMap(props){
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
}
onClickMap2(props, marker, e){
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
}
render() {
let xloc = this.props.xloc;
let yloc = this.props.yloc;
return (
<>
{xloc !== "" && yloc !== "" ?
<Map google={this.props.google}
style={style}
initialCenter={{
lat: xloc,
lng: yloc
}}
center={{lat:xloc,lng:yloc}}
zoom={15}
onClick={this.onClickMap}
>
<Marker onClick={this.onClickMap2}
name={this.props.name} />
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}>
<div>
<h6>{this.state.selectedPlace.name}</h6>
</div>
</InfoWindow>
</Map>
: ""}
</>);
}
}
export default GoogleApiWrapper({
apiKey: (""),
language : "korean"
})(MapComponent)<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Banner_Click.java
package com.ability.dto;
import java.sql.Date;
public class Banner_Click {
private int id;
private int banner_id;
private int click_count;
private Date date_created;
private String ip;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBanner_id() {
return banner_id;
}
public void setBanner_id(int banner_id) {
this.banner_id = banner_id;
}
public int getClick_count() {
return click_count;
}
public void setClick_count(int click_count) {
this.click_count = click_count;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
<file_sep>/front/components/presentational/atoms/ReplyComponent.js
import React, { Component, useState, useCallback, useEffect} from "react";
import Card from 'react-bootstrap/Card';
import { ProfileImageComponent } from "./ProfileImageComponent";
import { ButtonComponent, ButtonComponent2 } from "../atoms/ButtonComponent";
import { Container, Row, Col } from "react-bootstrap";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faThumbsUp } from '@fortawesome/free-solid-svg-icons';
import Link from 'next/link';
import axios from 'axios';
import ReplyComment from "../molecules/ReplyComment";
import { InputText } from "./InputboxComponent";
import { Recommend4 } from "../molecules/Recommend";
import {Badge} from 'react-bootstrap';
import dynamic from 'next/dynamic';
import Highlight from 'react-highlight'
const CkeditorOne2 = dynamic(() =>import('../atoms/CkeditorOne2'),{
ssr : false
});
/**
* @author 곽호원
* @summary 댓글 컴포넌트
*
* @author 정진호
* @version ReplyCompleteComponent 수정
* */
const font = {
padding: "0px",
margin: "0px",
paddingTop: "28px",
paddingLeft: "0px",
textAlign: "left",
border: "0"
}
const datecss = {
textAlign: "right",
marginTop: "30px"
}
const buttoncss = {
textAlign: "right",
marginTop: "15px"
}
const textcss = {
width : "100%",
height : "120%",
backgroundColor : "#e6e6e6",
border : "1px solid #c6badf",
paddingLeft : "20px",
font : "#5f4b8b"
}
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
export const ReplyComponent = (props) => {
const [likecount, setLikecount] = useState(0);
const [userid, setUserid] = useState(0);
const setRecommandMain = useCallback((num)=>{
if(!localStorage.getItem('userid')){
swal({
text: "추천/비추천 기능은 로그인 후 이용이 가능합니다..",
title: num == 1?"추천 실패":"비추천 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}
axios.get(backUrl,
{
params:{
seq:props.id,
userid:localStorage.getItem('userid'),
counta:num
}
})
.then((res)=>{
if(res.data =="success"){
swal({
text: num == 1?"댓글을 추천 했습니다.":"댓글을 추천을 취소 했습니다.",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(num == 1? likecount+1 : likecount-1);
}else if(res.data=="plus"){
swal({
text: num == 1?"댓글을 추천 했습니다.":"댓글을 추천을 취소 했습니다.",
timer: "5000",
icon: "/static/image/Logo2.png",
});
setLikecount(likecount-1);
}else if(res.data=="minus"){
swal("비추천 내역이 삭제 되었습니다.");
setLikecount(likecount+1);
}else{
swal({
text: "이미 투표한 댓글입니다. 투표 내역을 삭제 하시겠습니까?",
title: num == 1?"추천 실패":"비추천 실패",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((cancelok)=>{
if(cancelok){
setRecommandMain(0);
}
})
}
})
.catch((res)=>{
console.log(res);
})
},[likecount]);
const onClickUp = useCallback(() => {
setLikecount(setRecommandMain(1))
},[likecount]);
useEffect(()=>{
setLikecount(props.counta);
setReplyid(props.id);
setUserid(props.userid);
},[]);
return (
<Container>
<Row style={{ paddingBottom: "8px", borderBottom: "1px solid #e2e2e2" }} >
<Col md={2} style={{ verticalAlign: "middle", textAlign: "center", paddingTop: "20px" }} >
<ProfileImageComponent css={{ width: "32px", height: "32px", border: "1px solid #CDCECF", margin: "0px!", marginRight: "0.5rem" }} user_image={props.user_image} />
<br />
<Link href={{ pathname: "/developer/page", query: { userid: props.userid } }}>
<a>{props.nick_name}</a>
</Link>
</Col>
{props.modify !== true || props.userid !== props.replyOwner || props.id !== props.targetid ?
<>
<Col md={4} style={{ verticalAlign: "middle", paddingTop: "20px" }}>
<span>{props.comment_content}</span>
</Col>
<Col md={2} style={datecss}>
<div>{props.date_created}</div>
</Col>
{props.userid == userid ?
<Col md={4} style={buttoncss}>
<span onClick={onClickUp}>
<Badge variant="primary" style={{marginRight:"0.5rem",backgroundColor:"#5F4B8B"}}>
<FontAwesomeIcon style={{width:"10px",height:"auto"}} icon={faThumbsUp}/>
</Badge>
{likecount}
</span>
{localStorage.getItem("userid") != userid ?
""
:
<>
<span id={props.id} style={{ color: "rgb(247, 159, 31)", cursor: "pointer" }} onClick={props.onclick}>[삭제]</span>
<span id={props.id} style={{ color: "rgb(6, 82, 221)", cursor: "pointer" }} onClick={props.modifyComment}>[수정]</span>
</>
}
</Col>
:
<>
<Col md={3}>
</Col>
</>
}
</>
:
<>
<Col md={7}>
<InputText defaultValue={props.comment_content} onChange={props.onChangeInput} ></InputText>
</Col>
<Col md={3} style={buttoncss}>
<ButtonComponent id={props.id} onclick={props.onModifyCancel} name="취소" />
<ButtonComponent id={props.id} onclick={props.modifyCommentOk} name="수정" />
</Col>
</>
}
</Row>
</Container>
)
}
const titlecss2 = {
width: "100%",
fontSize: "12px",
paddingTop: "1rem"
}
const hrcss = {
marginTop: "0px"
}
const cardcss = {
padding: 0,
margin: "0px 5px 10px 10px",
}
const rightcss = {
width : "100%",
textAlign: "right"
}
export class ReplyCompleteComponent extends Component {
constructor(props) {
super(props);
const user_image = localStorage.getItem('user_image');
const nick_name = localStorage.getItem('nick_name');
const userid = localStorage.getItem('userid');
this.state = {
comments: [],
user_image: user_image,
nick_name: nick_name,
userid: userid,
seq: this.props.seq,
id: this.props.id,
comment: "",
beforeReply : "",
reply_content : props.reply_content
};
this.insertComment = this.insertComment.bind(this);
this.getCommentList = this.getCommentList.bind(this);
this.onChangeComment = this.onChangeComment.bind(this);
this.onChangeCkeditor = this.onChangeCkeditor.bind(this);
}
async componentDidMount() {
await this.getCommentList();
}
onChangeComment(e) {
this.setState({
comment: e.target.value
})
}
onChangeCkeditor(e){
this.state.setBeforeReply = e.editor.getData();
}
async getCommentList() {
if (this.state.seq !== null && this.state.id !== null) {
await axios.get(backUrl, {
params: {
seq: this.state.seq,
reply_id: this.state.id
}
}).then((response) => {
this.setState({
comments: response.data
})
})
} else {
return;
}
}
async insertComment() {
const replyCommentpoint = backUrl;
const userid = localStorage.getItem('userid');
await axios.get(replyCommentpoint, {
params: {
userid: userid,
seq: this.state.seq,
comment_content: this.state.comment,
reply_id: this.state.id,
}
}).then(() => {
this.getCommentList();
});
}
render() {
let comment = this.state.comments;
if (comment.length > 0) {
return (
<>
<Row >
<Col>
<Card style={{ paddingTop: "1.2rem", marginBottom: "5px" }}>
<Container>
<Row>
<Col md={4}>
<ProfileImageComponent css={{ width: "32px", height: "32px", border: "1px solid #CDCECF", margin: "0px!", marginRight: "0.5rem" }} user_image={this.props.user_image} />
<Link href={{ pathname: "/developer/page", query: { userid: this.props.userid } }}>
<a>{this.props.nick_name}</a>
</Link>
</Col>
<Col md={4} style={rightcss}>
<Card.Title style={titlecss2}>{this.props.date_created}</Card.Title>
</Col>
<Col md={4} style={rightcss}>
{localStorage.getItem("userid") == this.props.userid ?
<>
<span id={this.props.id} onClick={this.props.onclick} name="삭제" style={{ color: "rgb(247, 159, 31)", cursor: "pointer" }}>[삭제]</span>
<span name="수정" id={this.props.id} onClick={this.props.getReplyListOne} style={{ color: "rgb(6, 82, 221)", cursor: "pointer" }}>[수정]</span>
</> : ""
}
</Col>
<>
</>
{this.props.isModify
?
<>
<CkeditorOne2 onChange={this.props.onChangeCkeditor} data={this.props.reply_content2}/>
<Highlight innerHTML={true}>
{this.state.data}
</Highlight>
<div className="text-right" style={{marginRight:"0.5rem",textAlign:"right", width:"100%"}}>
<ButtonComponent name="취소" css={{marginTop:"0.3rem",marginRight:"0.3rem"}} onclick={this.props.onClickModifyCancel} variant="info"/>
<ButtonComponent name="답변 수정" id={this.props.id} css={{marginTop:"0.3rem"}} onclick={this.props.modifyReplyOk}/>
</div>
</>
:" " }
</Row>
</Container>
<br />
<hr style={hrcss} />
<Card.Body style={cardcss} >
<Row>
<Col md={10}>
<Highlight innerHTML={true}>
{this.props.reply_content}
</Highlight>
</Col>
<Col md={2}>
<Recommend4 counta={this.props.usercounta} count={this.props.vote_count} userid={this.props.userid} replyid={this.props.id} />
</Col>
</Row>
</Card.Body>
<ReplyComment seq={this.props.seq} reply_id={this.props.id} />
</Card>
</Col>
</Row>
</>
);
} else {
return (
<>
<Row>
<Col md={12}>
<Card style={{ paddingTop: "1.2rem", marginBottom: "5px" }}>
<Container>
<Row>
<Col xs={4}>
<ProfileImageComponent css={{ width: "32px", height: "32px", border: "1px solid #CDCECF", margin: "0px!", marginRight: "0.5rem" }} user_image={this.props.user_image} />
<Link href={{ pathname: "/developer/page", query: { userid: this.props.userid } }}>
<a>{this.props.nick_name}</a>
</Link>
</Col>
<Col xs={4} style={rightcss}>
<Card.Title style={titlecss2}>{this.props.date_created}</Card.Title>
</Col>
<Col xs={4} style={rightcss}>
{this.state.userid == this.props.userid ?
<>
<span id={this.props.id} onClick={this.props.onclick} name="삭제" style={{ color: "rgb(247, 159, 31)", cursor: "pointer" }}>[삭제]</span>
<span name="수정" id={this.props.id} onClick={this.props.getReplyListOne} style={{ color: "rgb(6, 82, 221)", cursor: "pointer" }}>[수정]</span>
</> : ""
}
</Col>
{this.props.isModify && this.props.id == this.props.targetid
?
<>
<CkeditorOne2 onChange={this.props.onChangeCkeditor} data={this.props.reply_content2}/>
<div style={rightcss} className="text-right" style={{marginRight:"1.2rem", width:"100%", textAlign:"right"}}>
<ButtonComponent name="취소" css={{marginTop:"0.3rem",marginRight:"0.3rem"}} onclick={this.props.onClickModifyCancel} variant="info"/>
<ButtonComponent name="답변 수정" id={this.props.id} css={{marginTop:"0.3rem"}} onclick={this.props.modifyReplyOk}/>
</div>
</>
:" " }
</Row>
</Container>
<br />
<hr style={hrcss} />
<Card.Body style={cardcss} >
<Row>
<Col md={10}>
<Highlight innerHTML={true}>
{this.props.reply_content}
</Highlight>
</Col>
<Col md={2}>
<Recommend4 counta={this.props.usercounta}count={this.props.vote_count} userid={this.props.userid} replyid={this.props.id} voter={this.props.voter} />
</Col>
</Row>
</Card.Body>
{this.state.userid != undefined && this.state.userid != "" && this.state.userid != 0 ?
<div style={{ display: "flex", backgroundColor: "#d6c286", backgroundColor: "rgba( 232, 226, 201, 0.5)", borderTop: "1px solid #e2e2e2" }}>
<Col xs={2} style={{ verticalAlign: "middle", textAlign: "center", paddingTop: "30px" }}>
<ProfileImageComponent css={{ width: "32px", height: "32px", border: "1px solid #CDCECF", margin: "0px!", marginRight: "0.5rem" }} user_image={this.state.user_image} />
<br />
<Link href={{ pathname: "/developer/page", query: { userid: this.state.userid } }}>
<a>{this.state.nick_name}</a>
</Link>
</Col>
<Col xs={9} style={{ paddingTop: "10px" }}>
<InputText content="댓글을 입력해주세요." value={this.state.comment} onChange={this.onChangeComment} />
</Col>
<Col xs={1} style={font}>
<ButtonComponent2 css={{ color: "#762873", border: "0.5px solid #762873" }} name="작성" onclick={this.insertComment} />
</Col>
</div>
:
<div style={{backgroundColor:"#f2f2f2" , padding:"15px", border:"1px solid #c6badf"}}>
<Row>
<Col md={1}>
<ProfileImageComponent css={{width:"32px",height:"32px",border:"1px solid #CDCECF",margin:"0px!",marginRight: "0.5rem" ,marginTop:"0.3rem" , marginLeft:"0.5rem"}} user_image={this.state.user_image} />
</Col>
<Col md={11}>
<input type="text" value="댓글은 로그인 후 입력할 수 있습니다" readOnly style={textcss}/>
</Col>
</Row>
</div>
}
</Card>
</Col>
</Row>
</>
)
}
}
}
<file_sep>/front/components/presentational/atoms/UserImageComponent.js
import React from 'react';
import Image from 'react-bootstrap/Image';
/**
*
* @author 강기훈
* @summary 유저게시판 프로필이미지 컴포넌트
* @see 정규현 / 이미지 컴포넌트 추가 / props 형태로 바꿈
*
*/
export const UserImageComponent=(props)=>
<Image style={props.css} src="" thumbnail/>
export const UserImageComponent2 = (props) =>
<Image style={props.css} src={props.imagepath} id={props.id} thumbnail/><file_sep>/front/components/container/organisms/users.js
import React,{useState, useCallback, useEffect} from 'react';
import { Row, Col,ToggleButtonGroup,ToggleButton, Container,Table} from 'react-bootstrap';
import axios from 'axios';
import { UserSearchbarComponent3 } from '../../presentational/atoms/SearchbarComponent';
import LodingComponent from '../../presentational/atoms/LodingComponent';
import Page from '../../presentational/molecules/Page';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import AdminReportTbody from '../../presentational/molecules/AdminReportTbody';
import AdminReportThead from '../../presentational/molecules/AdminReportThead';
import swal from 'sweetalert';
import filesaver from 'file-saver';
/**
* @author 신선하
* @summary 회원관리
*
* @author 강기훈
* @summary 회원관리 로직구현
*/
const css = {
verticalAlign:"middle",
}
const deleteBtn ={
width:"50px",
height:"30px",
fontSize:"13px",
marginLeft:"45px",
padding:"0",
marginTop:"5px"
}
const excelBtn ={
width:"50px",
height:"30px",
fontSize:"13px",
marginLeft:"45px",
padding:"0"
}
const btncss ={
textAlign:"right",
marginTop:"10px",
marginRight:"10px",
}
const usercount_div ={
marginTop:"40px",
marginBottom:"8px",
display:"flex",
justifyContent:"space-between"
}
const usercount={
fontFamily:"sans-serif",
fontWeight:"bold",
color:"#5F4B8B",
marginRight:"3px"
}
const usercount_div_child={
marginTop:"10px"
}
const count={
fontFamily:"sans-serif",
fontWeight:"bold",
color:"#5F4B8B",
marginRight:"15px"
}
const Users = ()=>{
const [searchWord, setSearchWord] = useState('');
const [dataList, setDataList] = useState([]);
const [placeHolder, setPlaceHolder] = useState('닉네임 검색');
const [isLoding, setIsLoding] = useState(false);
const [orderby, setOrderby] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [totalListCount, setTotalListCount] = useState(0);
const [isSearch, setIsSearch] = useState(0)
const [isdelok,setIsdelok] =useState();
const [totalUser,setTotalUser] =useState("0");
const [deletUser,setDeleteUser] =useState("0");
const [isChecked,setIsChecked] = useState();
const onChangeSearchInput = useCallback((e) =>{
setSearchWord(e.target.value);
},[searchWord]);
const onKeyPressSearch = useCallback((e)=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
}else if(e.charCode == 13){
setIsSearch(isSearch+1);
}
},[searchWord,placeHolder])
const onClickSearchButton = useCallback(()=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
};
setIsSearch(isSearch+1);
},[searchWord,placeHolder]);
const onChangeToggle = useCallback((e,event)=>{
const str = e.pop();
if(typeof str != "string"){
return;
}
setOrderby(str);
setIsSearch(0);
},[orderby, isSearch]);
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const onClickExcelButton = useCallback(()=>{
axios.get(backUrl,
{ responseType: 'arraybuffer'})
.then(response=>{
var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
filesaver.saveAs(blob, "Users.xls");
swal({
text: "현재 회원 목록을 Excel 파일로 다운로드 완료하였습니다.",
title: "회원 목록 다운로드",
icon: "/static/image/Logo2.png",
buttons: true
})
});
})
let userIdList = [];
const onClickCheckBox = useCallback((e)=>{
if(e.target.checked==true){
userIdList.push(e.target.id);
}else{
userIdList.splice(userIdList.indexOf(e.target.id),1);
}
});
const handlePageChange= useCallback((pageNumber)=> {
setCurrentPage(pageNumber);
},[currentPage]);
const onClickDeleteButton = useCallback((e)=>{
if(orderby == 3){
swal({
text: "유저를 복구시키겠습니까?",
title: "회원 복구",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((recoverok)=>{
if(recoverok){
let form = new FormData();
form.append("idList",userIdList);
axios({
method :'put',
baseURL : backUrl,
data : form
}).then((res)=>{
if(res.data=="success"){
swal("유저가 복구 되었습니다.");
setIsdelok(true);
}else{
swal("[Error0577] 복구 실패");
}
})
.catch((res)=>{
console.log("오류발생",res);
})
}
},[isdelok])
}else{
swal({
text: "유저를 탈퇴 시키겠습니까?",
title: "유저 추방",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
let form = new FormData();
form.append("idList",userIdList);
axios({
method :'put',
baseURL : backUrl,
url :"/test/deleteuser",
data : form
}).then((res)=>{
if(res.data=="success"){
swal("유저를 강퇴시켰습니다.");
setIsdelok(true);
}else{
swal("[Error0577] 삭제 실패");
}
})
.catch((res)=>{
console.log("오류발생",res);
})
}
},[isdelok])
}
});
const modalRedirect =useCallback(()=>{
setIsdelok(true);
})
useEffect( () =>{
setIsdelok(false);
setIsLoding(true);
setDataList([]);
axios.get(backUrl,
{
params : {
orderby:orderby,
currentpage:currentPage,
word: isSearch!=0 ? searchWord : ""
}
})
.then((res) => {
setIsLoding(false);
setCurrentPage(res['data']['currentPage']);
setEndPageBlock(res['data']['endPageBlock']);
setPageSize(res['data']['pageSize']);
setStartPageBlock(res['data']['startPageBlock']);
setTotalListCount(res['data']['totalListCount']);
setTotalPage(res['data']['totalPage']);
setDataList(res['data']['userList']);
})
.catch((res)=>{
setIsLoding(false);
console.log(res);
});
axios.get(backUrl).then((res) =>{
setTotalUser(res['data']);
})
axios.get(backUrl).then((res) =>{
setDeleteUser(res['data']);
})
},[orderby,totalListCount,currentPage,isSearch,isdelok]);
let btnName = "";
if(orderby==3){
btnName = "복구";
}else{
btnName = "추방";
}
return(
<>
{isLoding && <LodingComponent/>}
<Container>
<Row style={{marginTop:"25px"}}>
<Col sm={6} md={8} style={css}>
<ToggleButtonGroup
type="checkbox"
value={orderby}
onChange={onChangeToggle}
>
<ToggleButton value="0" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">능력치순</ToggleButton>
<ToggleButton value="1" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">신규순</ToggleButton>
<ToggleButton value="2" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">이름순</ToggleButton>
<ToggleButton value="3" style={{backgroundColor:"#fff",color:"#5F4B8B",borderColor:"rgba(0,0,0,.125)"}} variant="dark">탈퇴 회원</ToggleButton>
</ToggleButtonGroup>
</Col>
<Col sm={6} md={4}>
<UserSearchbarComponent3 onChange={onChangeSearchInput} onClick={onClickSearchButton}
onKeyPress={onKeyPressSearch} content={placeHolder}/>
</Col>
</Row>
<div style={usercount_div}>
<div style={usercount_div_child}>
<span style={usercount}>총 회원수:</span>
<span style={count}>{totalUser}</span>
<span style={usercount}>탈퇴 회원수:</span>
<span style={count}>{deletUser}</span>
</div>
<ButtonComponent id="excelbtn" name="Excel" css={excelBtn} onclick={onClickExcelButton}/>
</div>
<Table>
<AdminReportThead
n2="#" n3="닉네임" n4="이름"
n5="권한" n6="가입일" n7="이메일" n8="능력치"/>
{dataList.length!==0 ? <>
{
dataList.map((content)=>{
return(
<tr key={JSON.stringify(content['userid'])}>
<AdminReportTbody checked={isChecked}
onChange = {onClickCheckBox}
onExited = {modalRedirect}
userid={JSON.stringify(content['userid'])}
user_image={JSON.stringify(content['user_image']).replace('"','').replace('"','')}
nick_name={JSON.stringify(content['nick_name']).replace('"','').replace('"','')}
name={JSON.stringify(content['name']).replace('"','').replace('"','')}
role_name={JSON.stringify(content['role_name']).replace('"','').replace('"','')}
date_created={JSON.stringify(content['date_created']).replace('"','').replace('"','')}
email={JSON.stringify(content['email']).replace('"','').replace('"','')}
reputation={JSON.stringify(content['reputation'])}
/>
</tr>
);
})
}
<div style={btncss}>
<ButtonComponent id="deletebtn" name={btnName} css={deleteBtn} onclick={onClickDeleteButton}/>
</div>
<Row style={{marginTop:"1.4rem",marginBottom:"2rem",justifyContent:"center"}}>
<div style={{textAlign:"center"}}>
<Page currentPage={currentPage} totalListCount={totalListCount} currentPage={currentPage} handlePageChange={handlePageChange}/>
</div>
</Row>
</>: <div style={{marginTop:"30%",marginLeft:"50%"}}>검색한 결과가 없습니다.</div>}
</Table>
</Container>
</>
);
}
export default Users;<file_sep>/front/pages/_app.js
import React from 'react';
import Head from 'next/head';
import PropTypes from 'prop-types';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import AppLayout from '../components/AppLayout';
import {createStore, compose, applyMiddleware} from 'redux';
import reducer from '../reducers';
import rootSaga from '../sagas';
import {Provider} from 'react-redux';
import createSagaMiddleware from '@redux-saga/core';
/**
* @author 정규현
* @summary 공통부분 및 리덕스 스토어 적용, 미들웨어 적용
*/
const Ability = ({Component, store, pageProps})=> {
return (
<>
<Provider store={store}>
<Head>
<title>ABILITY</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="<KEY>"
crossOrigin="anonymous"
/>
<meta
name="viewport"
content="initial-scale=1.0, width=device-width"
key="viewport"
/>
<link rel="shortcut icon" type="image/x-icon" href="/static/favicon.ico" />
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+KR:300,400,500,700,900&display=swap" rel="stylesheet"></link>
<link rel="stylesheet" href="https://highlightjs.org/static/demo/styles/a11y-dark.css" />
</Head>
<AppLayout>
<Component {...pageProps}/>
</AppLayout>
</Provider>
</>
);
};
Ability.propTypes = {
Component:PropTypes.elementType.isRequired,
store:PropTypes.object.isRequired,
pageProps: PropTypes.object.isRequired,
};
Ability.getInitialProps = async (context) =>{
const {ctx, Component} = context;
let pageProps = {};
if(Component.getInitialProps){
pageProps = await Component.getInitialProps(ctx) || {};
}
return {pageProps};
};
const configureStore = (initialState, options) => {
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const enhancer = process.env.NODE_ENV === 'production'
? compose(applyMiddleware(...middlewares))
: compose(
applyMiddleware(...middlewares),
!options.isServer && typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined' ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
);
const store = createStore(reducer, initialState, enhancer);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
};
export default withRedux(configureStore)(withReduxSaga(Ability));<file_sep>/front/pages/job/board.js
import React,{useState,useEffect,useCallback} from 'react';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faIdBadge } from '@fortawesome/free-solid-svg-icons';
import HireList from '../../components/presentational/molecules/HireList';
import {Row,Col, ToggleButton, ToggleButtonGroup, Container} from 'react-bootstrap';
import { UserSearchbarComponent } from '../../components/presentational/atoms/SearchbarComponent';
import axios from 'axios';
import LodingComponent from '../../components/presentational/atoms/LodingComponent';
import Page from '../../components/presentational/molecules/Page';
import Router from 'next/router';
import swal from 'sweetalert';
/**
* @author 신선하
* @summary
*
* @author 정진호
* @summary Job_Board 게시판 구현
*/
const css = {
verticalAlign:"middle",
}
const Board = ()=>{
const [searchWord, setSearchWord] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [isSearch, setIsSearch] = useState(0);
const [isLoding, setIsLoding] = useState(false);
const [dataList, setDataList] = useState([]);
const [placeHolder, setPlaceHolder] = useState('');
const [orderby, setOrderby] = useState(0);
const [totalListCount, setTotalListCount] = useState(0);
const [userrole,setUserrole] = useState("");
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const companySigh = useCallback(()=>{
if(!localStorage.getItem("userid")){
swal({
text: "로그인 후 이용이 가능합니다.",
title: "등록 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
}else{
axios.get(backUrl+"/signup/companysignup",{
params : {
userid : localStorage.getItem("userid")
}
}).then(()=>{
const screenW = screen.availWidth; // 스크린 가로사이즈
const screenH = screen.availHeight; // 스크린 세로사이즈
const posL=( screenW-430 ) / 2; // 띄울창의 가로 포지션
const posT=( screenH-796 ) / 2; // 띄울창의 세로 포지션
window.open(backUrl+"/signup/companysignup?userid="+localStorage.getItem("userid"),"ABILITY SIGN UP","width=860, height=796,top="+posT+",left="+posL+", toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no");
});
}
});
const onChangeSearchInput = useCallback((e) =>{
setSearchWord(e.target.value);
},[searchWord]);
const handlePageChange= useCallback((pageNumber)=> {
setCurrentPage(pageNumber);
},[currentPage]);
const onKeyPressSearch = useCallback((e)=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
}else if(e.charCode == 13){
setIsSearch(isSearch+1);
}
},[searchWord,placeHolder])
const onClickSearchButton = useCallback(()=>{
if(searchWord.trim().replace(' ','').length===0){
setSearchWord('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
};
setIsSearch(isSearch+1);
},[searchWord,placeHolder]);
const onChangeToggle = useCallback((e)=>{
const str = e.pop();
if(typeof str != "string"){
return;
}
setOrderby(str);
setIsSearch(0);
Router.push("/job/board");
},[orderby,isSearch]);
useEffect( () =>{
window.scrollTo(0,0);
setIsLoding(true);
setDataList([]);
setUserrole(localStorage.getItem("role_name"));
const endpoint = backUrl+"/job/getlist";
axios.get(endpoint,{
params : {
orderby : orderby,
currentpage : currentPage,
userid : localStorage.getItem("userid")?localStorage.getItem("userid"):0,
word: isSearch!=0 ? searchWord : ""
}
}).then((response) => {
setIsLoding(false);
setDataList(response.data.postBoardList);
setCurrentPage(response.data.currentPage);
setTotalListCount(response.data.totalListCount+1);
})
.catch((response)=>{
setIsLoding(false);
});
},[orderby,currentPage,totalListCount,isSearch]);
return(
<>
{isLoding && <LodingComponent/>}
{ userrole == "ROLE_COMPANY" ?
<>
<TitleAndButtonComponent title="구인구직 게시판" name="공고 올리기" path='/job/write'>
<FontAwesomeIcon icon={faIdBadge} style={{width:"21px"}}/>
</TitleAndButtonComponent>
</> :
<>
<TitleAndButtonComponent title="구인구직 게시판" name="기업 등록" path='/job/board' onclick={companySigh}>
<FontAwesomeIcon icon={faIdBadge} style={{width:"21px"}}/>
</TitleAndButtonComponent>
</>
}
<Row >
<Col sm={6} md={8} style={css} id="togglegroup">
<ToggleButtonGroup
type="checkbox"
value={orderby}
onChange={onChangeToggle}
>
<ToggleButton value="0" variant="info">최신순</ToggleButton>
<ToggleButton value="1" variant="info">조회순</ToggleButton>
</ToggleButtonGroup>
</Col>
<Col sm={6} md={4}><UserSearchbarComponent onChange={onChangeSearchInput} onClick={onClickSearchButton} content={placeHolder}
onKeyPress={onKeyPressSearch}/></Col>
</Row>
<hr/>
{ dataList.length > 0 ?
dataList.map((content)=>{
return(
<div key={content.id}>
<HireList key={content.id}
seq={content.id}
event={content.period.substr(0,10)}
hireTitle2={content.title}
subCompany={content.job_type}
company={content.company_name}
subtitle={content.subtitle}
loaction={content.area}
count={content.viewcount}
hashtag={content.tags}
hits={content.view_count}
date={content.date_created}
allscrap={content.allscrap}
scrap={content.scrap}/>
</div>
);
})
: ""}
<Row style={{marginTop:"1.4rem",marginBottom:"2rem",justifyContent:"center"}}>
<div style={{textAlign:"center"}}>
<Page currentPage={currentPage} totalListCount={totalListCount} currentPage={currentPage} handlePageChange={handlePageChange}/>
</div>
</Row>
</>
);
}
export default Board;
<file_sep>/front/components/presentational/molecules/HireTable.js
import React from 'react';
import {Row, Col,Table, Container} from 'react-bootstrap';
/**
*
* @auth 곽호원
* @summary 구인공고 상세페이지 회사 소개하는 컴포넌트
*
*/
const hirecss = {
textAlign : "right",
fontSize : "1em",
paddingBottom :"10px"
}
const jobWritecss = {
fontSize : "1em",
borderTop: "1px solid #e2e2e2",
paddingTop :"20px",
paddingBottom :"0.7rem"
}
const tablecss = {
border : "none"
}
const HireTable = (props) => {
function date(str){
let dates = str.substr(0,11);
return dates;
}
function autoHypenPhone(str){
str = str.replace(/[^0-9]/g, '');
var tmp = '';
if( str.length < 4){
return str;
}else if(str.length < 7){
tmp += str.substr(0, 3);
tmp += '-';
tmp += str.substr(3);
return tmp;
}else if(str.length < 11){
tmp += str.substr(0, 3);
tmp += '-';
tmp += str.substr(3, 3);
tmp += '-';
tmp += str.substr(6);
return tmp;
}else{
tmp += str.substr(0, 3);
tmp += '-';
tmp += str.substr(3, 4);
tmp += '-';
tmp += str.substr(7);
return tmp;
}
return str;
}
return (
<Container>
<Row>
<Col style={{textAlign:"right",paddingBottom :"0.7rem", fontSize:"0.8rem"}}>
공고 시작일 : {date(props.hireStartDate)}~
<br/>
공고 마감일 : {props.hireEndDate}
</Col>
</Row>
<Row style={jobWritecss}>
<Col style={{borderRight:"1px solid #e2e2e2"}}><span style={{}}>직업유형</span> : {props.jobType} </Col>
<Col><span style={{}}>회사 규모</span> : {props.comScale} </Col>
</Row>
<Row style={jobWritecss}>
<Col style={{borderRight:"1px solid #e2e2e2"}}><span style={{}}>근무 부서</span> : {props.jobdept}</Col>
<Col><span style={{}}>도메인</span> : {props.domain}</Col>
</Row>
<Row style={jobWritecss}>
<Col style={{borderRight:"1px solid #e2e2e2"}}><span style={{}}>근무시간</span> : {props.jobTime}</Col>
<Col><span style={{}}>경력 수준 : {props.career}</span></Col>
</Row>
<Row style={jobWritecss}>
<Col style={{borderRight:"1px solid #e2e2e2"}}><span style={{}}>담당자 연락처</span> : {autoHypenPhone(props.phone)}</Col>
<Col><span style={{}}>담당자 이메일</span> : {props.email}</Col>
</Row>
</Container>
);
};
export default HireTable;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/utils/CreateRandomPassword.java
package com.ability.utils;
import java.util.Random;
import org.springframework.stereotype.Component;
/**
* @author 정규현
* @summary 랜덤으로 패스워드를 생성 // 비밀번호 찾기 전용
*/
@Component
public class CreateRandomPassword {
public String randomPassword() {
String specialCharacters = "!#$^&*-=~";
StringBuilder randomPassword = new StringBuilder();
Random rnd = new Random();
randomPassword.append((char) ((int) (rnd.nextInt(26)) + 65));
for (int i = 0; i < 11; i++) {
int rIndex = rnd.nextInt(4);
switch (rIndex) {
case 0:
// a-z
randomPassword.append((char) ((int) (rnd.nextInt(26)) + 97));
break;
case 1:
// A-Z
randomPassword.append((char) ((int) (rnd.nextInt(26)) + 65));
break;
case 2:
// 0-9
randomPassword.append((rnd.nextInt(10)));
break;
case 3:
randomPassword.append(specialCharacters.charAt(rnd.nextInt(specialCharacters.length())));
break;
}
}
return randomPassword.toString();
}
}
<file_sep>/front/components/presentational/molecules/css/LoginInfoCss.js
export const divCss1={
boxSizing: "border-box"
}
export const divCss2={
boxSizing: "border-box",
verticalAlign: "middle",
width:"10rem",
textOverflow: 'ellipsis',
display: '-webkit-box',
wordWrap:'break-word',
WebkitLineClamp:'1',
WebkitBoxOrient: 'vertical',
marginTop:"0.2rem",
overflow: "hidden",
padding:"0",
}
export const imageCss = {
width:"3.2rem",
height:"3.2rem",
borderRadius:"50%",
marginRight:"0.5rem",
overflow: "auto",
top:"0",
left: "0",
padding:"0",
marginTop:"0.1rem"
}
export const spanCss = {
display: "block",
paddingTop:"0.3rem",
height:"19px"
}
export const badgeCss1= {
marginRight:"0.2rem",
backgroundColor:"#5f4b8b",
}
export const badgeCss2= {
marginRight:"0.2rem",
}<file_sep>/front/components/presentational/atoms/AnswerComponent.js
import React from "react";
import {Card} from 'react-bootstrap';
import {ProfileImageComponent} from "./ProfileImageComponent";
import TagList from "../molecules/TagList";
const titlecss = {
position : "Absolute",
paddingLeft :"3.5em",
paddingTop: "0.8em",
margin : "0"
}
const labelcss = {
width : "100%",
border : "none",
backgroundColor : "#ecf0f1",
margin : "0"
}
const subcss = {
position : "Absolute",
paddingLeft : "60px",
paddingTop : "-5px",
fontSize : "11px"
}
const subcss2 = {
position : "Absolute",
paddingLeft : "150px",
paddingTop : "-5px",
fontSize : "11px"
}
const subcss3 = {
paddingLeft : "230px",
paddingTop : "-5px",
fontSize : "11px"
}
const hrcss = {
marginTop : "10px"
}
const cardcss = {
paddingTop : "0px",
paddingLeft : "10px"
}
/**
*
* @auth 곽호원
* @summary 답변의 수도 포함되어 있는 답변 컴포넌트
*
*/
export const AnswerComponent = (props) =>
<>
<label title="답변" value="답변" style={labelcss}>답변 {props.count}</label>
<Card>
<>
<ProfileImageComponent />
<Card.Title style={titlecss}>제목을 입력해주세요하하하하하핳</Card.Title>
</>
<Card.Body style={cardcss}>
<Card.Subtitle style={subcss}>{props.writer}</Card.Subtitle>
<Card.Subtitle style={subcss2}>{props.date}</Card.Subtitle>
<Card.Subtitle style={subcss3}><TagList hashtag="java, javascript" /></Card.Subtitle>
<>
<hr style={hrcss}/>
</>
<Card.Text>글 내용</Card.Text>
</Card.Body>
</Card>
</><file_sep>/front/components/presentational/atoms/ProjectInput.js
import React from 'react';
import { InputGroup, FormControl } from 'react-bootstrap';
import { VideoId } from '../molecules/ProjectDetails';
/**
* @author 신선하
* @summary 프로젝트보드 내 input박스 모음
* @usage
**/
const ph ={
fontSize: '90%'
};
export const InputLabelDefault = (props) => {
return (
<>
<label>{props.label}</label>
<InputGroup className="mb-3">
<FormControl
style={ph}
id={props.id}
type={props.type}
name={props.name}
placeholder={props.placeholder}
defaultValue={props.value}
onChange={props.onChange}
onClick={props.onClick}
maxLength={props.maxLength}
/>
</InputGroup>
</>
);
}
export const InputLabelText = (props) => {
return (
<>
<label>{props.label}</label>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text style={ph}>
{props.text}
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
style={ph}
type={props.type}
id={props.id}
name={props.name}
placeholder={props.placeholder}
defaultValue={props.value}
onChange={props.onChange}
onClick={props.onClick}
maxLength={props.maxLength}
/>
</InputGroup>
</>
);
}
export const InputLabelTextarea = (props) => {
return (
<>
<label>{props.label}</label>
<InputGroup className="mb-3">
<FormControl
style={ph}
as="textarea"
rows={props.rows}
id={props.id}
name={props.name}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
onClick={props.onClick}
maxLength={props.maxLength}
/>
</InputGroup>
</>
);
}
export const VideoPreview = (props) => {
return (
<>
<label>{props.label}</label>
<VideoId
file_path={props.file_path}
onChange={props.onChange}
style={props.style}
/>
</>
);
}
<file_sep>/front/components/presentational/atoms/ProfileNavComponent.js
import React from 'react';
import Nav from 'react-bootstrap/Nav';
import {NavLink} from 'react-router-dom';
/**
*
* @author 우세림
* @summary 20190615, tab navmenu UI
* @version 수정 정진호 -- 필요한 갯수에 따라 카드 생성
*/
export const ProfileNav = (props)=>{
const cardlist = [];
if(props.card !== null && props.card !== ""){
let list = props.card.split(',');
for(var i=0; i<list.length; i++){
cardlist.push(list[i]);
}
}
const cards = cardlist.map((label, index)=>(
<Nav.Item id="card_nav" key={index}>
<NavLink to={props.href} >{label}</NavLink>
</Nav.Item>)
);
return(
<Nav fill variant="tabs" defaultActiveKey={props.href} style={props.css}>
{cards}
</Nav>
)
}
<file_sep>/front/components/container/organisms/Top.js
import React , {Component} from 'react';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem} from 'reactstrap'; // 리액스트랩 네비바
import 'bootstrap/dist/css/bootstrap.css'; //리액트 부트스트랩 Css
import {NavLink} from 'react-router-dom';
/**
* @auth 정진호
* @summary 상단 네비바 컴포넌트
**/
export class Top extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
login: 0,
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<div>
<Navbar color="light" light expand="md">
<NavbarToggler onClick={this.toggle} />
<img src = "/Image/Logo2.png" className="Logo-ABILITY" alt = "로고"/>
<Collapse isOpen={this.state.isOpen} navbar>
<NavbarBrand href="/">
</NavbarBrand>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink to={"/question"} >질의 응답</NavLink>
</NavItem>
<NavItem>
<NavLink to={"/test"}>개발자들</NavLink>
</NavItem>
<NavItem>
<NavLink to="/jobopening">개발자 모집</NavLink>
</NavItem>
<NavItem>
<NavLink to="/project">Project 보기</NavLink>
</NavItem>
<NavItem>
<NavLink to="/chat">#Chatting</NavLink>
</NavItem>
<NavItem>
<NavLink to="/test">Test</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
<hr/>
</div>
);
}
}
<file_sep>/Ability-SpringBoot1/src/main/resources/application.properties
spring.datasource.hikari.jdbc-url=
spring.datasource.hikari.username=
spring.datasource.hikari.password=
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.sql-script-encoding=UTF-8
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
server.port=8080
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.resources.add-mappings=true
spring.session.store-type=REDIS
spring.redis.database=0
spring.redis.lettuce.pool.max-active=100
spring.redis.lettuce.pool.max-idle=100
spring.redis.lettuce.pool.min-idle=2
server.error.whitelabel.enabled = false
<file_sep>/front/components/container/templatses/ModifyHelpWanted.js
import React from 'react';
import {PrecautionsComponent} from '../../presentational/atoms/PrecautionsComponent';
import {HelpWantedComponent} from '../../presentational/atoms/HelpWantedComponent';
import {ButtonComponent} from '../../presentational/atoms/ButtonComponent';
import CkeditorOne from '../../presentational/atoms/CkeditorOne';
import {GridArea} from '../organisms/GridArea';
/**
*
* @author 곽호원
* @summary 구인공고 수정 페이지
*/
const buttoncss = {
textAlign : "right",
paddingRight : "10px",
marginTop : "10px"
}
const ModifyHelpWanted = () => {
return (
<GridArea>
<PrecautionsComponent />
<HelpWantedComponent />
<h6>기업 설명</h6>
<CkeditorOne />
<h6>직무 소개</h6>
<CkeditorOne />
<div style={buttoncss}>
<ButtonComponent name="돌아가기" />
<ButtonComponent name="수정"/>
</div>
</GridArea>
);
};
export default ModifyHelpWanted;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/JobBoardDetailList.java
package com.ability.dto.custom;
public class JobBoardDetailList {
private String title;
private String content;
private String subtitle;
private String date_created;
private String period;
private String job_type;
private String scale;
private String job_dept;
private String homepage_url;
private String job_time;
private String company_name;
private String manager_tel;
private String company_email;
private String company_info;
private String userid;
private String view_count;
private String xloc;
private String yloc;
private String career;
private String company_area;
private String logo;
private String resume;
private String tags;
private int scrap;
private int allscrap;
private String email;
private String phone;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public int getAllscrap() {
return allscrap;
}
public void setAllscrap(int allscrap) {
this.allscrap = allscrap;
}
public int getScrap() {
return scrap;
}
public void setScrap(int scrap) {
this.scrap = scrap;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getCompany_area() {
return company_area;
}
public void setCompany_area(String company_area) {
this.company_area = company_area;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getView_count() {
return view_count;
}
public void setView_count(String view_count) {
this.view_count = view_count;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getDate_created() {
return date_created;
}
public void setDate_created(String date_created) {
this.date_created = date_created;
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getJob_type() {
return job_type;
}
public void setJob_type(String job_type) {
this.job_type = job_type;
}
public String getScale() {
return scale;
}
public void setScale(String scale) {
this.scale = scale;
}
public String getJob_dept() {
return job_dept;
}
public void setJob_dept(String job_dept) {
this.job_dept = job_dept;
}
public String getHomepage_url() {
return homepage_url;
}
public void setHomepage_url(String homepage_url) {
this.homepage_url = homepage_url;
}
public String getJob_time() {
return job_time;
}
public void setJob_time(String job_time) {
this.job_time = job_time;
}
public String getManager_tel() {
return manager_tel;
}
public void setManager_tel(String manager_tel) {
this.manager_tel = manager_tel;
}
public String getCompany_email() {
return company_email;
}
public void setCompany_email(String company_email) {
this.company_email = company_email;
}
public String getCompany_info() {
return company_info;
}
public void setCompany_info(String company_info) {
this.company_info = company_info;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getXloc() {
return xloc;
}
public void setXloc(String xloc) {
this.xloc = xloc;
}
public String getYloc() {
return yloc;
}
public void setYloc(String yloc) {
this.yloc = yloc;
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/utils/ResumeSendMail.java
package com.ability.utils;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
/**
*
* @author 정진호
* @summary 이력서 지원했을때 파일 첨부 메일 보내기.
*
*/
@Component
public class ResumeSendMail {
Transport transport;
private final String FROM = "";
private final String FROMNAME = "";
private final String SMTP_USERNAME = "";
private final String SMTP_PASSWORD = "";
private final String HOST = "";
private final int PORT = ;
public void ResumeMail(String to_email,String filepath, String filename ,String introduce){
String to = to_email;
String subject = "[ABILITY] - 올리신 구인공고에 지원 신청서가 도착했습니다.";
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
try {
MimeMessage message = new MimeMessage(session);
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(new InternetAddress(FROM, FROMNAME));
messageHelper.setTo(new InternetAddress(to));
messageHelper.setSubject(subject);
messageHelper.setText(introduce);
// 파일첨부
FileSystemResource fsr = new FileSystemResource(filepath);
messageHelper.addAttachment(filename, fsr);
transport = session.getTransport();
transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception ex) {
System.out.println("Error message: " + ex.getMessage());
} finally {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/front/components/presentational/atoms/UserUpdateModal.js
import React, {Component} from 'react';
import { Modal, Button} from 'react-bootstrap';
import { InputText } from './InputboxComponent';
import axios from 'axios';
import Router from 'next/router';
/**
*
* @author 우세림
* @summary 유저삭제방 만들기 모달
*
*/
const EndPoint = process.env.NODE_ENV === 'production'? "" : "";
class UserUpdateModal extends Component {
constructor(props, context) {
super(props, context);
this.state = {
show: false,
userid : 0,
result : 0,
};
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
}
async handleClose() {
this.setState({ show: false });
}
async handleShow() {
this.setState({ show: true });
}
async componentDidMount() {
let user = Router.query['userid'];
this.setState({
userid : user
})
}
isEmpty(str){
if(typeof str == "undefined" || str == null || str == "")
return true;
else
return false ;
}
async handlesubmit() {
let pattern = /^(?=.*[a-zA-Z])((?=.*\d)|(?=.*\W)).{8,20}$/;
let password = document.getElementById('password').value;
let repassword = document.getElementById('repassword').value;
let repasswordok = document.getElementById('repasswordok').value;
let result = 0;
if(password && repassword && repasswordok) {
if (pattern.test(repassword)) {
if(repassword==repasswordok){
await axios.get(EndPoint+"/change", {
params : {
userid : Router.query['userid'],
password :<PASSWORD>,
repassword :<PASSWORD>
}
}).then((Response) => {
result = Response.data;
if(result>0){
swal({
text: "비밀번호 변경이 되었습니다.",
title: "비밀번호 변경 성공",
timer: "3000",
icon: "/static/image/Logo2.png"
});
Router.push("/developer/page?userid="+Router.query['userid']);
} else{
swal({
text: "현재 비밀번호와 입력한 비밀번호가 다릅니다.",
title: "비밀번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return false;
}
})
} else {
swal({
text: "새 비밀번호와 비밀번호 확인이 일치하지 않습니다.",
title: "비밀번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
}
} else{
swal({
text: "새 비밀번호는 숫자, 문자, 특수문자를 포함하여 8자이상 20자 이하로 작성해주세요.",
title: "비밀번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
document.getElementById('repassword').value ="";
document.getElementById('repassword').focus();
}
} else {
swal({
text: "빈칸을 입력해주세요.",
title: "비밀번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}
}
render() {
return (
<>
<Button variant="primary" onClick={this.handleShow} variant="info">
비밀번호 변경
</Button>
<Modal
{...this.props}
size="md"
aria-labelledby="contained-modal-title-vcenter"
show={this.state.show} onHide={this.handleClose}
centered
>
<Modal.Header closeButton>
<Modal.Title>비밀번호 변경</Modal.Title>
</Modal.Header>
<Modal.Body>
<div>- 비밀번호 변경을 원하시면 현재 비밀번호와 변경하실 비밀번호를 입력해주세요.</div>
<hr/>
현재 비밀번호 <InputText id="password" type="<PASSWORD>"/>
변경할 비밀번호 <InputText id="repassword" type="<PASSWORD>"/>
비밀번호 확인 <InputText id="repasswordok" type="password"/>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.handleClose}>
취소
</Button>
<Button variant="primary" onClick={this.handlesubmit}>
확인
</Button>
</Modal.Footer>
</Modal>
</>
);
}
}
export default UserUpdateModal;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/config/SchedulerConfig.java
package com.ability.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
*
* @author 정규현
* @summary 스케줄러 설정
*
*/
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE=10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("tags-Auto-Insert-scheduled-task-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/service/QuestionBoardService.java
package com.ability.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ability.dao.QuestionMapper;
import com.ability.dto.custom.PostBoardList;
/**
* 질문게시판 관련 서비스
*
* @author 정진호
* @category 질문게시판 서비스
*
*/
@Service
public class QuestionBoardService {
@Autowired
QuestionMapper questionMapper;
public List<PostBoardList> getPostList(Map<String, String> view) {
List<PostBoardList> list = questionMapper.listSelect(view);
return list;
}
public PostBoardList getPostListOne(Map<String, String> view) {
PostBoardList listOne = questionMapper.listDetail(view);
return listOne;
}
public int setPostBoard(Map<String,String> content) {
int result = questionMapper.insertPostBoard(content);
if(result > 0) {
return result;
}
return -1;
}
public int setPostBoardUpdate(Map<String,String> content) {
int result = questionMapper.updatePostBoard(content);
if(result > 0) {
return result;
}else {
return -1;
}
}
public int deletePostBoard(Map<String, String> content) {
int result = questionMapper.deletePostBoard(content);
if(result > 0) {
return result;
}else {
return -1;
}
}
public List<PostBoardList> SeachList(Map<String,String> content) {
List<PostBoardList> list = questionMapper.SeachList(content);
return list;
}
public int getTotalCount() {
int result = questionMapper.getTotalCount();
return result;
}
//checkPostVote
public Boolean checkPostVote(Map<String, String> contents) {
Boolean result = true;
try {
if(questionMapper.checkPostVote(contents) != 1 && questionMapper.checkPostVote(contents) != -1) {
result = false;
questionMapper.insertPostVote(contents);
}
} catch (Exception e) {
result = true;
}
return result;
}
//cancelPostVote
public String cancelPostVote(Map<String, String> contents) {
String result = "plus";
try {
if(questionMapper.checkPostVote(contents) != 1) {
result="minus";
}
questionMapper.cancelPostVote(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
//cancelPostMark
public String cancelPostMark(Map<String, String> contents) {
String result = "fail";
try {
result="success";
questionMapper.cancelPostMark(contents);
} catch (Exception e) {
result = "fail";
}
return result;
}
public int setPostBoardMark(Map<String, String> view) {
int result = -1;
try {
if(questionMapper.checkPostBoardMark(view) == 0) {
questionMapper.setPostBoardMark(view);
result = 1;
}
} catch (Exception e) {
e.printStackTrace();
result = -1;
}
return result;
}
public List<PostBoardList> getSearchResult(Map<String, String> view) {
return questionMapper.getSearchResult(view);
}
public int getTotalBoardSearchContentCount(Map<String, String> view) {
int result = 0;
try {
result = questionMapper.getTotalBoardSearchContentCount(view);
} catch (Exception e) {
result = 0;
}
return result;
}
public int totalContentCount() {
int result = 0;
try {
result = questionMapper.getTotalBoardContentCount();
} catch (Exception e) {
result = 0;
}
return result;
}
public int AllSearchCount(Map<String,String> count) {
int result = 0;
result = questionMapper.AllSearchCount(count);
if(result > 0) {
return result;
}
return result;
}
}
<file_sep>/front/components/presentational/molecules/BoardList.js
import React from 'react';
import {DateCreatedComponentability} from '../atoms/WriteDetail';
import {Like, Question, Answer} from '../atoms/LikeQnAComponent';
import {UserImageComponent2} from '../atoms/UserImageComponent'
import Link from 'next/link';
import Badge from 'react-bootstrap/Badge';
import {Col,Row, Container} from 'react-bootstrap';
/**
* @author 정진호
* @summary 게시판 리스트 Molecules 태그 목록 , 스플릿 단위로 끊지만 마지막에 ,적어줘야 전부 적용됨.(추후 수정)
**/
const content = {
display: "grid",
maxWidth:"1140px",
gridTemplateColumns: "5% 55% 20% 20%",
};
const titlecss = {
fontSize : "17px",
textDecoration : "none"
};
const imgcss = {
width:"3.2rem",
height:"3.2rem",
borderRadius:"50%",
marginRight:"0.5rem",
overflow: "auto",
top:"0",
left: "0",
padding:"0",
marginTop:"0.1rem",
gridColumnStart: 2,
gridRow: "1/4",
bottom: "8px",
marginLeft : "10px",
};
const imgright = {
paddingRight : "0px",
textAlign : "right",
maxWidth:"100px",
};
const colcss={
paddingLeft: "0",
paddingRight:"0",
verticalAlign:"middle"
};
const tagcss = {
marginRight : "0.2rem"
};
const seqcss ={
marginRight : "1.5rem"
};
const BoardList = (props)=>{
const taglist = [];
if(props.hashtag !== null && props.hashtag !== "" && props.hashtag !== undefined && props.hashtag !== "null"){
const list = props.hashtag.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
}
const taglistSet = [...new Set(taglist)];
const hashtags = taglistSet.map((value)=>(<Badge key={value} variant="light" style={tagcss}>{value}</Badge>))
return (
<>
<div className="div_Content" style = {content} id={props.seq}>
<small style={seqcss}>{props.seq}</small>
<div className="Question Content_item">
<h6 style = {titlecss}>
<Link href={{pathname:props.path ,query: {seq : props.seq}}} as={"/content/"+props.seq} replace>
<a style={titlecss} >{props.title}</a>
</Link>
</h6>
<div className="Question tagLine">
<h6>{hashtags}</h6>
</div>
</div>
<div className="Question Content_item Detail">
<Question question={props.view_count}/>
<Like like={props.like}/>
<Answer answer={props.answer}/>
</div>
<div className="Content_item_like">
<Container>
<Row style={{verticalAlign:"middle"}} id="writerRow">
<Col style={imgright} id="userimg">
<UserImageComponent2 css={imgcss} imagepath={props.imagepath}/>
</Col>
<Col style={colcss} id="writer">
<small><Link href={{ pathname : "/developer/page", query:{userid : props.userid ? props.userid : ""}} } ><a>{props.id}</a></Link></small>
<DateCreatedComponentability label={props.day} reputation={props.reputation}></DateCreatedComponentability>
</Col>
</Row>
</Container>
</div>
</div>
</>
)
}
export const BoardListAll = (props)=>{
const taglist = [];
if(props.hashtag !== null && props.hashtag !== "" && props.hashtag !== undefined && props.hashtag !== "null"){
const list = props.hashtag.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
}
const taglistSet = [...new Set(taglist)];
const hashtags = taglistSet.map((value)=>(<Badge key={value} variant="light" style={tagcss}>{value}</Badge>))
return (
<>
<div className="div_Content" style = {content} id={props.seq}>
<small style={seqcss}>{props.seq}</small>
<div className="Question Content_item">
<h6 style = {titlecss}><small style={{color:props.color}}><b>[{props.menu}] </b></small>
<Link href={{pathname:props.path ,query: {seq : props.seq} }} replace>
<a style={titlecss} onClick={props.onClick}>{props.title}</a>
</Link>
</h6>
<div className="Question tagLine">
<h6>{hashtags}</h6>
</div>
</div>
<div className="Question Content_item Detail">
<Question question={props.view_count}/>
<Like like={props.like}/>
<Answer answer={props.answer}/>
</div>
<div className="Content_item_like">
<Row style={{verticalAlign:"middle"}}>
<Col style={imgright}>
<UserImageComponent2 css={imgcss} imagepath={props.imagepath}/>
</Col>
<Col style={colcss}>
<small><Link href={{ pathname : "/developer/page", query:{userid : props.userid ? props.userid : ""}} } ><a onClick={props.onClick}>{props.id}</a></Link></small>
<DateCreatedComponentability label={props.day} reputation={props.reputation}></DateCreatedComponentability>
</Col>
</Row>
</div>
</div>
</>
)
}
export default BoardList;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/custom/BannerClickCountToday.java
package com.ability.dto.custom;
public class BannerClickCountToday {
int id;
int count;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
<file_sep>/front/components/presentational/molecules/Header.js
import React, {Component} from 'react';
import {Top} from '../../container/organisms/Top';
import {SearchbarComponent} from '../atoms/SearchbarComponent';
import SideBar from '../../container/organisms/SideBar';
/**
* @author 정규현
* @summary 기존 파일을 기존 로직에 맞추기 위해 생성
* 홈페이지 상단 바(header) 부분을 나타내는 컴포넌트
*/
class Header extends Component{
render(){
return(
<>
<div id="root" className="item1">
<div className="navbar-LayOut">
<Top/>
<SearchbarComponent name="SeachBar"/>
</div>
</div>
<div className="SideBar_Ability">
<SideBar/>
{this.props.children}
</div>
</>
);
}
}
export default Header;<file_sep>/front/components/presentational/atoms/BookmarkComponent.js
import React from 'react';
import {Button, Table, Badge} from 'react-bootstrap';
/**
*
* @author 강기훈
* @summary 즐겨찾기를 만드는 컴포넌트
*/
const css ={
display:"block",
width:"110px",
height:"40px",
border: "1px solid #c6badf",
borderRadius:"6px",
fontFamily:"sans-serif"
}
export const BookmarkComponent=(props)=>
<div id="Bookmark">
<Button style={css} onClick={function(e){}.bind(this)}><i className="fas fa-star"></i> 즐겨찾기</Button>
<Table striped bordered hover>
<thead>
<tr>
<th colSpan="4"><i className="fas fa-star"></i> 즐겨찾기</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="">웹퍼블리셔 모집</a></td>
<td>신입,경력</td>
<td>우아한 형제들</td>
<td>6/16~6/24</td>
</tr>
<tr>
<td><a href="">풀스택개발자 모집</a></td>
<td>신입,경력</td>
<td>우아한 형제들</td>
<td>6/16~6/24</td>
</tr>
<tr></tr>
</tbody>
</Table>
</div><file_sep>/front/components/container/templatses/ErrorPage.js
import React from 'react';
import { Row, Col, Image } from 'react-bootstrap';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import Link from 'next/link';
/**
* @auth 신선하
* @summary 에러페이지
*/
const title ={
textAlign : 'center',
fontSize : '36px',
margin : '1rem 0 0.5rem 0'
}
const middle = {
textAlign : 'center',
fontSize : '18px',
marginBottom : '0.5rem'
}
const content = {
textAlign : 'center',
fontSize : '17px',
marginBottom : '1rem'
}
const img = {
width : "30%",
height : "auto",
lineHeight : 'auto',
verticalAlign : 'middle',
textAlign : "center"
}
const textAlignCenter = {
textAlign : 'center'
}
const fontColor = {
color:'#5F4B8B'
}
const ErrorPage = (props) => {
return (
<>
<br/>
<Row>
<div style={textAlignCenter}>
<Image
src="/static/image/ErrorRobot.png"
alt="404"
style={img}
/>
</div>
</Row>
<Row>
<Col sm={6} md={12} style={{padding:'0 0 0 30px'}}>
<div style={title}>
<b>
요청하신 페이지를 <span style={fontColor}> 찾을 수 없습니다 [{props.errorNum}]
</span>
</b>
</div><br/>
<div style={middle}>
<b>
찾으시려는 웹페이지의 이름이 바뀌었거나 삭제되어 현재 사용할 수 없습니다.
</b>
</div>
<div style={content}>
입력하신 페이지 주소가 정확한지 다시 한번 확인해보시기 바랍니다.<br/>
</div><br/>
<div style={textAlignCenter}>
<Link href="/">
<a><ButtonComponent name="메인페이지 바로가기" /></a>
</Link>
</div>
</Col>
</Row>
<br/>
</>
);
};
export default ErrorPage;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/service/HashtagNicknameService.java
package com.ability.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ability.dao.HashtagNicknameMapper;
import com.ability.dto.custom.HashtagComment;
import com.ability.dto.custom.HashtagReply;
/**
* Ckeditor tag 관련 서비스
*
* @author 정진호
* @category Ckeditor tag 서비스
*
*/
@Service
public class HashtagNicknameService {
@Autowired
HashtagNicknameMapper hashtagNicknameMapper;
public List<HashtagComment> getComment(Map<String,String> list){
List<HashtagComment> nicknames = hashtagNicknameMapper.getComment(list);
return nicknames;
}
public List<HashtagReply> getReply(Map<String,String> list){
List<HashtagReply> nicknames = hashtagNicknameMapper.getReply(list);
return nicknames;
}
}
<file_sep>/front/components/container/templatses/ModifyProjectUpload.js
import React from 'react';
import { GridArea } from '../organisms/GridArea';
import { Form, InputGroup, FormControl } from 'react-bootstrap';
import VideoComponent from '../../presentational/atoms/VideoComponent';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
/**
* @author 곽호원
* @summary 프로젝트 보기 수정 페이지
* @usage
**/
const placeholder ={
fontSize: '90%'
};
const ModifyProjectUpload = () => {
return (
<GridArea>
<div className="container-fluid">
<div className="row">
<div className="col-4">
동영상 미리보기<br></br>
<VideoComponent vidoeId="LaW8Sc2MTMk"/><br></br>
동영상 업로드 완료... <br></br>
동영상 url = www.naver.com <br></br><br></br><br></br><br></br>
파일첨부 버튼
</div>
<div className="col-8">
<Form>
<Form.Group controlId="title">
<Form.Label>제목</Form.Label>
<Form.Control style={placeholder} placeholder="제목을 입력해주세요" />
</Form.Group>
</Form>
<label htmlFor="basic-url">유튜브 비디오ID</label>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Text id="basic-addon3" style={placeholder}>
https://www.youtube.com/watch?v=
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl id="basic-url" aria-describedby="basic-addon3"
placeholder="유튜브 비디오아이디입력" style={placeholder} />
</InputGroup>
<Form>
<Form.Group controlId="decs">
<Form.Label>상세설명</Form.Label>
<Form.Control style={placeholder} placeholder="상세설명을 입력해주세요"
as="textarea" rows="5" />
</Form.Group>
<Form.Group controlId="tags">
<Form.Label>태그</Form.Label>
<Form.Control style={placeholder} placeholder="태그를 입력해주세요" />
</Form.Group>
</Form>
</div>
<div className="col-12" style={{textAlign:'right'}}>
<ButtonComponent name="돌아가기" />
<ButtonComponent name="수정" />
</div>
</div>
</div>
</GridArea>
);
};
export default ModifyProjectUpload;<file_sep>/front/components/container/templatses/Login.js
import React,{Component} from 'react';
import axios from 'axios';
import {b1Css,b2Css,btnCss,containerCss,h1Css,tboxCss,tboxInputCss} from './css/LoginCss';
/**
* @author 정규현
* @summary 비동기 rest 로그인
* @version 정규현 리덕스 추가
*/
const backUrl = process.env.NODE_ENV === 'production'? "?/user/login" : "?/user/login";
class Login extends Component {
constructor(props){
super(props);
this.state = {
inputEmail:'',
inputPassword:'',
errors:'',
isLoding: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = (e) =>{
this.setState({
[e.target.name]: e.target.value
})
};
handleSubmit = (e) =>{
e.preventDefault();
axios.post(backUrl,
{
email:this.state.inputEmail,
password:this.state.inputPassword
})
.then(res => {
this.setState({
inputEmail:'',
inputPassword:'',
isLoding:false,
});
localStorage.setItem("userid",this.state.user.userid);
localStorage.setItem("email",this.state.user.email);
localStorage.setItem("nick_name",this.state.user.nick_name);
localStorage.setItem("user_image",this.state.user.user_image);
localStorage.setItem("reputation",this.state.user.reputation);
localStorage.setItem("role_name",this.state.user.role_name);
localStorage.setItem("token",this.state.token);
this.props.history.push('/');
})
.catch(res => {
console.log(res)
this.setState({
errors:"로그인 정보를 다시 확인해 주세요",
isLoding:false,
})
});
};
render() {
return (
<>
<div className='container' style={containerCss}>
<h1 style={h1Css}><b>ABILITY</b></h1>
<form>
<div className="tbox" style={tboxCss}>
<input style={tboxInputCss} type="text" id="login-email" name="inputEmail" maxLength="100" placeholder="Email" value={this.state.inputEmail} onChange={this.handleChange}/>
</div>
<div className="tbox" style={tboxCss}>
<input type="password" style={tboxInputCss} id="login-password" name="inputPassword" maxLength="20" placeholder="<PASSWORD>" value={this.state.inputPassword} onChange={this.handleChange} />
</div>
<span style={{color:'red',fontWeight:"bold"}} id='a-login-submit'>{this.state.errors}</span>
<input className="btn" style={btnCss} id="a-login-submit-btn" type="submit" name="button" value="LOG IN" onClick={this.handleSubmit} disabled={this.state.isLoding}/>
</form>
<a className="b1" style={b1Css} href="/ability3/signup">회원가입</a>
<a className="b2" style={b2Css} href="/ability3/login/forgot">Forgot Password?</a>
</div>
</>
);
}
}
export default Login;<file_sep>/front/pages/job/detail.js
import React ,{useState,useCallback,useEffect} from 'react';
import {Container,Row,Col,} from 'react-bootstrap';
import {ButtonComponent2} from '../../components/presentational/atoms/ButtonComponent';
import HireTitle from '../../components/presentational/molecules/HireTitle';
import HireComDescription from '../../components/presentational/molecules/HireComDescription';
import HireJobDescription from '../../components/presentational/molecules/HireJobDescription';
import HireTable from '../../components/presentational/molecules/HireTable';
import MapComponent from "../../components/presentational/atoms/MapComponent";
import axios from 'axios';
import Router from 'next/router';
import { TitleAndButtonComponent } from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faIdBadge } from '@fortawesome/free-solid-svg-icons';
import swal from 'sweetalert';
import ResumeModal from '../../components/presentational/atoms/ResumeModal';
/**
* @auth 곽호원
* @summary 구인 공고 상세페이지
*
* @auth 정진호
* @version css 수정, 실데이터 반영, 이벤트 추가 , 즐겨찾기 기능 추가
*/
const buttoncss={
textAlign:"right"
}
const mapcss = {
width:"400px",
height : "300px"
}
const Detail = () => {
const [isseq,setIsseq] = useState('');
const [title,setTitle] = useState('');
const [hireStartDate,setHireStartDate] = useState('');
const [hireEndDate,setHireEndDate] = useState('');
const [jobType,setJobType] = useState('');
const [comScale,setComScale] = useState('');
const [jobdept,setJobdept] = useState('');
const [viewcount,setViewcount] = useState('');
const [domain,setDomain] = useState('');
const [jobTime,setJobTime] = useState('');
const [comDescription,setComDescription] = useState('');
const [jobDescription,setJobDescription] = useState('');
const [xloc,setXloc] = useState('');
const [yloc,setYloc] = useState('');
const [userid,setUserid] = useState('');
const [company_name,setCompany_name] = useState('');
const [career,setCareer] = useState("");
const [company_area,setCompany_area] = useState("")
const [path,setPath] = useState("");
const [scrap,setScrap] = useState(0);
const [allscrap,setAllscrap] = useState(0);
const [manager_email,setManager_email] = useState("");
const [manager_tel,setManager_tel] = useState("");
const [guest,setGuest] = useState("");
const [resume,setResume] = useState("");
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const onClickScrap = useCallback( async()=>{
if(guest === null && guest === undefined){
swal({
text: "즐겨찾기(스크랩) 기능은 로그인 후 이용이 가능합니다.",
title: "게시물 즐겨찾기 추가 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}else{
let Forms = new FormData();
Forms.append("userid",localStorage.getItem("userid"));
Forms.append("boardid",Router.query["seq"]);
Forms.append("category_id","4");
await axios({
method :'post',
baseURL : backUrl,
data : Forms
}).then((response)=>{
if(response.data == 1){
swal({
title : "즐겨찾기 등록완료",
text : "제목 : "+title+" 를(을) 스크랩 하였습니다.",
timer :"3000"
})
setAllscrap(allscrap+1);
}else {
setAllscrap(Number(allscrap)-1);
swal({
title : "즐겨찾기 등록취소",
text : "스크랩을 취소하였습니다.",
timer :"3000"
})
}
setScrap(response.data);
});
}
});
useEffect(()=>{
setGuest(localStorage.getItem("userid"));
setIsseq(Router.query["seq"]);
axios.get(backUrl,{
params : {
seq : Router.query["seq"],
userid : localStorage.getItem("userid")
}
}).then((response)=>{
setTitle(response.data.title);
setJobDescription(response.data.content);
setSubtitle(response.data.subtitle);
setHireStartDate(response.data.date_created);
setHireEndDate(response.data.period);
setJobType(response.data.job_type);
setComScale(response.data.scale);
setJobdept(response.data.job_dept);
setViewcount(response.data.view_count);
setDomain(response.data.homepage_url);
setJobTime(response.data.job_time);
setPhone(response.data.manager_tel);
setEmail(response.data.company_email);
setComDescription(response.data.company_info);
setXloc(response.data.xloc);
setYloc(response.data.yloc);
setUserid(response.data.userid);
setCompany_name(response.data.company_name);
setCareer(response.data.career);
setCompany_area(response.data.company_area)
setPath(response.data.logo);
setScrap(response.data.scrap);
setAllscrap(response.data.allscrap);
setManager_tel(response.data.phone);
setManager_email(response.data.email);
setResume(response.data.resume);
})
},[]);
const resumedown = useCallback(()=>{
swal({
title:"다운로드",
text:"이력서를 다운로드 하시겠습니까?",
icon:"/static/image/Logo2.png",
buttons: true
}).then((res)=>{
if(res){
window.open(resume);
}else{
return;
}
});
})
const del = useCallback(()=>{
if(!localStorage.getItem("userid")){
swal({
text: "로그인 후 이용이 가능합니다.",
title: "삭제 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
return;
}else{
swal({
text: "게시글을 정말 삭제하시겠습니까?",
title: "삭제 경고",
icon: "/static/image/Logo2.png",
buttons: true
})
.then((deleteok)=>{
if(deleteok){
let form = new FormData();
form.append("seq",isseq);
axios({
method :'put',
baseURL : backUrl,
data : form,
headers :{'Content-Type':'application/json'}
}).then((res)=>{
if(res.data=="success"){
swal({
title: "삭제 완료",
text: "능력치가 -3 떨어졌습니다",
icon: "/static/image/Logo2.png",
});
Router.push("/job/board");
}else{
swal("[Error0577] 삭제 실패");
}
})
.catch((res)=>{
console.log(isseq,"?");
console.log("오류발생",res);
});
}
});
}
})
return (
<>
<Container>
<TitleAndButtonComponent title="구인구직 게시판" name="이력서 받기" path={'/job/detail?seq='+isseq} onclick={resumedown}>
<FontAwesomeIcon icon={faIdBadge} style={{width:"21px"}}/>
</TitleAndButtonComponent>
<Row style={{display:"flex",paddingRight:"17px", justifyContent:"flex-end"}}>
{ guest == userid ?
<>
<span style={{color :"rgb(6,82,221)" , cursor :"pointer"}} onClick={()=>{
if(!localStorage.getItem("userid")){
swal({
text: "로그인 후 이용이 가능합니다.",
title: "수정 실패",
timer: "10000",
icon: "/static/image/Logo2.png"
});
}else{
Router.push("/job/modify?seq="+Router.query["seq"], "/content/"+Router.query["seq"])}
}
}>[수정]</span>
<span style={{color :"rgb(247,159,31)" ,cursor :"pointer"}} onClick={del}>[삭제]</span>
</> :""
}
</Row>
<HireTitle title={title} company_name={company_name} count={viewcount} company_area={company_area} career={career}
scrapValue={scrap} scrap={onClickScrap} allscrap={allscrap} event={hireEndDate.substr(0,10)} image={"https://react-ability.s3.ap-northeast-2.amazonaws.com/spring/LogoImage"+path}/>
<br /><br />
<HireTable hireStartDate={hireStartDate} hireEndDate={hireEndDate.substr(0,10)} jobType={jobType} comScale={comScale} jobdept={jobdept} domain={domain}
jobTime={jobTime} phone={manager_tel} email={manager_email} career={career}/>
<Row>
<Col>
<hr />
</Col>
</Row>
<HireComDescription comDescription={comDescription} />
<br />
<HireJobDescription jobDescription={jobDescription} />
<br /><br />
<Row>
<Col xs={12}>
<div style={mapcss}>
<MapComponent xloc={xloc} yloc={yloc} name={company_name}/>
</div>
</Col>
</Row>
<Row>
<Col>
<div style={buttoncss}>
<br />
<ButtonComponent2 css={{backgroundColor :"#ffffff", border:"1px solid grey", color:"grey"}} name="목록으로" onclick={()=>{Router.push("/job/board")}} />
{guest !== undefined && guest!== null ? <ResumeModal email={manager_email}/> : ""}
</div>
</Col>
</Row>
</Container>
</>
);
};
export default Detail;<file_sep>/front/components/container/templatses/PostList.js
import React ,{Component} from 'react';
import BoardList from '../../presentational/molecules/BoardList';
import ContentTop from '../../presentational/molecules/ContentTop'
import { GridArea } from '../organisms/GridArea';
import axios from 'axios';
import TitleComponent from '../../presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
/**
*
* @author 정진호
* @summary 게시판 리스트
* @see 정규현 // 오류수정
* @see 정규현 // main title ui 추가
*/
const plistEndPoint = process.env.NODE_ENV === 'production'? "?" : "?";
const plistparameter = "?category=1&start=0&end=10";
class PostListJson extends Component{
constructor(props){
super(props);
this.state = {
postlist : []
};
}
async componentDidMount() {
let {data : postlist} = await axios.get(plistEndPoint+"/0"+plistparameter);
this.setState({
postlist
});
}
render(){
const {postlist} = this.state;
if(postlist.length > 0){
return postlist.map(postContent=>(
<BoardList key={postContent.id} seq={postContent.id} hashtag={postContent.tags} title={postContent.title} view_count={postContent.view_count} like={postContent.likecount} answer={postContent.replycount} reputation={postContent.reputation} id={postContent.nick_name} day={postContent.date_created} imagepath={postContent.user_image}/>
));
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
class PostListJson1 extends Component{
constructor(props){
super(props);
this.state = {
postlist1 : []
};
}
async componentDidMount() {
let {data : postlist1} = await axios.get(plistEndPoint+"/1"+plistparameter);
this.setState({
postlist1
});
}
render(){
const {postlist1} = this.state;
if(postlist1.length > 0){
return postlist1.map(postContent=>(
<BoardList key={postContent.id} seq={postContent.id} hashtag={postContent.tags} title={postContent.title} view_count={postContent.view_count} like={postContent.likecount} answer={postContent.replycount} reputation={postContent.reputation} id={postContent.nick_name} day={postContent.date_created} imagepath={postContent.user_image}/>
));
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
class PostListJson2 extends Component{
constructor(props){
super(props);
this.state = {
postlist : []
};
}
async componentDidMount() {
let {data : postlist} = await axios.get(plistEndPoint+"/2"+plistparameter);
this.setState({
postlist
});
}
render(){
const {postlist} = this.state;
if(postlist.length > 0){
return postlist.map(postContent=>(
<BoardList key={postContent.id} seq={postContent.id} hashtag={postContent.tags} title={postContent.title} view_count={postContent.view_count} like={postContent.likecount} answer={postContent.replycount} reputation={postContent.reputation} id={postContent.nick_name} day={postContent.date_created} imagepath={postContent.user_image}/>
));
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
const PostList = () => {
return (
<>
<GridArea>
<TitleComponent title="질의 응답">
<FontAwesomeIcon icon={faQuestionCircle} />
</TitleComponent>
<ContentTop/>
<div className="tab-content" id="nav-tabContent">
<div className="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
<PostListJson />
</div>
<div className="tab-pane fade" id="list-profile" role="tabpanel" aria-labelledby="list-profile-list">
<PostListJson1 />
</div>
<div className="tab-pane fade" id="list-messages" role="tabpanel" aria-labelledby="list-messages-list">
<PostListJson2/>
</div>
</div>
</GridArea>
</>
)
}
export default PostList;<file_sep>/front/components/presentational/atoms/InputboxComponent.js
import React from 'react';
import Form from 'react-bootstrap/Form';
import {InputGroup, FormControl, Button} from 'react-bootstrap';
/**
*
* @author 우세림
* @summary 20190616, 우세림, 20190616
* @see 정규현 InputText 에 온체인지 추가
*/
export const InputText = (props)=>
<Form.Group>
<Form.Label className={props.className} htmlFor={props.for}>{props.label}</Form.Label>
<Form.Control id={props.id} type={props.type} defaultValue={props.defaultValue} name={props.name} placeholder={props.content} style={props.css} value={props.value} onChange={props.onChange} onClick={props.onClick} maxLength={props.maxLength} accept={props.accept} checked={props.checked}/>
</Form.Group>
export const InputTextBtn = (props)=>
<InputGroup >
<FormControl placeholder={props.content} maxLength={props.maxLength} style={props.css}/>
<InputGroup.Append>
<Button variant="outline-secondary" style={props.css9}>{props.name}</Button>
</InputGroup.Append>
</InputGroup>
// check, radio
export const InputCheck = (props)=>
<Form.Check inline type={props.type} label={props.label} name={props.name}/>
export const InputSelect = (props)=>
<Form.Group>
<Form.Label>{props.label}</Form.Label>
<Form.Control as="select">
<option>{props.option1}</option>
<option>{props.option2}</option>
</Form.Control>
</Form.Group>
export const InputTextarea = (props)=>
<Form.Group style={props.formcss}>
<Form.Control id={props.id} as="textarea" rows={props.row} placeholder={props.placeholder}/>
</Form.Group>
export const InputTextBox = (props)=>
<Form.Group style={props.formcss}>
<Form.Control id={props.id} name={props.name} style={props.css}
maxLength={props.maxLength} placeholder={props.placeholder}
onKeyPress={props.onKeyPress} onKeyUp={props.onKeyUp}
type={props.type} defaultValue={props.defaultValue} onChange={props.onChange} value={props.value}
/>
</Form.Group>
export const InputTextBoxReadonly = (props)=>
<Form.Group style={props.formcss}>
<Form.Control style={props.css} placeholder={props.placeholder} readOnly />
</Form.Group><file_sep>/front/components/container/organisms/css/Chatting.js
export const chat_sub_div = {
display: "flex",
justifyContent: "space-between",
marginBottom: "10px"
}
export const chat_sub_btn = {
marginTop: "20px"
}
export const chat_hr = {
marginBottom: "25px"
}
export const chat_rooms = {
display: "grid",
gridTemplateColumns: "49% 49%",
gridGap: "20px",
width:"100%"
}
export const chat_chatcard = {
width: "100%",
height: "100%",
/* border: 0.067em solid #dfe6e9; */
padding: "3.000em"
}
export const chat_title ={
fontWeight: "bold",
fontSize: "2.875em",
color:"#5F4B8B",
marginBottom:"0.3em",
textAlign: "center"
}
export const chat_usercount = {
fontSize: "0.875em",
marginBottom:"0.7em",
color: "#91959E",
textAlign:"center"
}
export const chat_hr2 ={
width:"30px",
marginTop:"20px"
}
export const chat_tag_div = {
marginTop:"1.3em",
marginBottom:"2.000em",
textAlign: "center",
height:"10px"
}
export const chat_tag = {
display: "flex"
}
export const chat_btn_div = {
textAlign: "center",
width: "50%",
margin: "auto"
}
<file_sep>/front/pages/developer/update.js
/* global google */
import React ,{Component}from 'react';
import { UserImageComponent2 } from '../../components/presentational/atoms/UserImageComponent';
import { InputTextBox, InputText } from '../../components/presentational/atoms/InputboxComponent';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUsers } from '@fortawesome/free-solid-svg-icons';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import UserDeleteModal from '../../components/presentational/atoms/UserDeleteModal';
import UserUpdateModal from '../../components/presentational/atoms/UserUpdateModal';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { Button } from 'react-bootstrap';
import swal from 'sweetalert';
import GoogleSuggest from '../../components/presentational/atoms/GoogleSuggest';
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
/**
* @author 우세림
* @summary 개발자들 정보수정
*/
const user_mod_input_css ={
height: "35px",
width: "100%",
color: "gray"
}
const user_img = {
width: "100%",
height:"auto"
}
const user_md = {
paddingTop : "1rem",
display: "grid",
gridTemplateColumns: "18% 82%",
marginBottom: "10px"
}
const user_md_profile = {
paddingLeft: "15px",
}
const user_md_profile_div = {
display: "flex"
}
const user_md_profile_span = {
display: "inline-block",
padding: "0.500em",
color: "rgb(71, 71, 71)",
textAlign: "right",
fontWight: "500",
width: "80px",
marginRight: "5px"
}
const user_md_profile_span3 = {
display: "inline-block",
padding: "0.500em",
color: "rgb(71, 71, 71)",
textAlign: "right",
fontWeight: "500",
width: "60px",
marginRight: "5px"
}
const user_md_btn = {
display: "flex",
marginTop: "3.000em",
justifyContent: "space-between"
}
const EndPoint = process.env.NODE_ENV === 'production'? "?" : "?";
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
class Update extends Component {
constructor(props){
super(props);
this.state = {
userid : 0,
userlist: [],
userdata : [],
result : 0,
image : '',
tel: '',
area: '',
tags: '',
user_info: '',
image: '',
imagePreviewUrl: '',
isEdit:true,
};
this.onSubmit = this.onSubmit.bind(this);
this.onCancle = this.onCancle.bind(this);
this.Onchangeimg = this.Onchangeimg.bind(this);
this.saveImg = this.saveImg.bind(this);
this.onChangeTel = this.onChangeTel.bind(this);
this.onChangeTags = this.onChangeTags.bind(this);
this.onChangeCk = this.onChangeCk.bind(this);
};
Onchangeimg(e){
let reader = new FileReader();
let file = e.target.files[0];
const imageFormData = new FormData();
[].forEach.call(e.target.files, (f)=>{
imageFormData.append('image', f);
});
axios.post(backUrl,
imageFormData,
)
.then((res)=>{
this.setState({
isEdit:false,
image: res.data,
});
});
reader.onloadend = () => {
this.setState({
imagePreviewUrl: reader.result,
isEdit:false,
});
}
reader.readAsDataURL(file)
}
saveImg(){
axios.post(backUrl+"/user/register",{
file:this.state.image,
userid:Router.query['userid']
})
.then((res)=>{
this.setState({
isEdit:true,
});
swal({
text: "이미지가 저장되었습니다.",
title: "이미지 저장",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
})
}
async componentDidMount() {
let user = Router.query['userid'];
this.setState({
userid : user
})
await axios.get(EndPoint+"/users", {
params : {
userid : Router.query['userid']
}
}).then((Response) => {
this.setState({
userdata : Response.data,
tel: Response.data.tel,
tags: Response.data.tags,
user_info: Response.data.user_info,
});
});
}
onChangeTel(e){
this.setState({
tel : e.target.value
})
}
onChangeTags(e){
this.setState({
tags : e.target.value
})
}
onChangeCk(e){
this.setState({
user_info : e.editor.getData()
})
}
async onSubmit() {
const telrex = /^[0-9\b]+$/;
const tagrex = /^[ㄱ-ㅎ가-힣a-zA-Z0-9,-\s]+$/;
let tel = document.getElementById('tel').value;
let area = document.getElementById('area').value;
let tags = document.getElementById('tags').value;
let user_info = this.state.user_info;
if(!area){
area = document.getElementById('area').placeholder;
}
if (telrex.test(tel)){
if(tagrex.test(tags)){
let result = 0;
let Forms = new FormData();
Forms.append("userid", Router.query['userid']);
Forms.append("tel", tel);
Forms.append("area",area);
Forms.append("tags",tags);
Forms.append("user_info",user_info);
await axios({
method :'put',
baseURL :EndPoint,
url :"/users/modify",
data : Forms
}).then((Response)=>{
result = Response.data;
if (result > 0) {
swal({
text: "프로필이 수정되었습니다.",
title: "프로필 수정",
timer: "3000",
icon: "/static/image/Logo2.png"
});
Router.push("/developer/page?userid="+Router.query['userid'],"/developer/page/"+Router.query['userid']);
}
})
}else {
swal({
text: "태그는 [한글], [영문], [-]만 가능하며 콤마(,)로 구분됩니다.",
title: "태그 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}
} else {
swal({
text: "전화번호는 [숫자] 11자리 이하로 입력해주세요.",
title: "전화번호 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
document.getElementById('tel').value ="";
document.getElementById('tel').focus();
return;
}
}
async onCancle() {
Router.push("/developer/page?userid="+Router.query['userid'], "/developer/page/"+Router.query['userid']);
};
render(){
let {userdata} = this.state;
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<UserImageComponent2 id="image" css={user_img} imagepath={imagePreviewUrl} />);
} else {
$imagePreview = (<UserImageComponent2 id="image" css={user_img} imagepath={userdata.user_image} />);
}
if(this.state.userdata !== null && this.state.userid > 0){
return (
<>
<TitleComponent title="개발자들 정보수정">
<FontAwesomeIcon icon={faUsers} style={{width:"1em",height:"auto"}}/>
</TitleComponent>
<div style={user_md} id="info_main">
<div>
<div className="imgPreview">
{$imagePreview}
</div>
{this.state.isEdit ?
<b>
<InputText label="프로필 이미지 업로드" id="user_image" name="user_image" accept=".jpg, .gif, .png"
className="user_image" for="user_image" type="file" onChange={this.Onchangeimg}/>
</b>
:
<Button block="true" variant="danger" onClick={this.saveImg} style={{marginTop:"2px"}}>변경한 이미지 저장</Button>
}
</div>
<div style={user_md_profile}>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>전화번호</span>
<InputTextBox type="tel" id="tel" value={this.state.tel} maxLength="11" formcss={user_mod_input_css} onChange={this.onChangeTel}/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>위치</span>
<GoogleSuggest id="area" value={this.state.area} onChange={this.onChangeArea} placeholder={userdata.area} />
</div>
<div id="keyword"style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>태그</span>
<InputTextBox id="tags" value={this.state.tags} formcss={user_mod_input_css} onChange={this.onChangeTags}/>
</div>
<div id="keyword" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span3}></span>
<div style={user_mod_input_css} > - 관심있는 키워드를 ,로 구분하여 입력해주세요.</div>
</div>
<div id="ckdiv" style={user_md_profile_div}>
<span id="ment" style={user_md_profile_span}>소개</span>
<CkeditorOne2 id="ckvalue" data={this.state.user_info} onChange={this.onChangeCk} />
</div>
</div>
</div>
<div style={user_md_btn}>
<div>
<UserDeleteModal />
<UserUpdateModal />
</div>
<div id="developer_btn">
<ButtonComponent name="뒤로가기" onclick={this.onCancle} variant="info"/>
<ButtonComponent name="저장" onclick={this.onSubmit}/>
</div>
</div>
</>
)
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
export default Update;<file_sep>/front/components/presentational/atoms/ListgroupBootFree.js
import React from 'react';
import ListGroup from 'react-bootstrap/ListGroup'
import Tab from 'react-bootstrap/Tab';
import {Container,Row,Col} from 'react-bootstrap';
import { UserSearchbarComponent } from './SearchbarComponent';
/**
* @author 정규현
* @see 정규현 UserSearchbarComponent 컴포넌트 리펙토링, 필요한 값이 props로 전달이 안됨
*/
const css1 = {
borderBottom : "2px solid #eaeaea",
}
const padding = {
paddingTop: "22px"
}
const colcss ={
minHeight:"80px"
}
const left = {
display : "inline"
}
const ListgropBootFree =(props) => {
return(
<>
<Container id="contentRow2" >
<Tab.Container id="list-group-tabs-community" defaultActiveKey="#cdata1">
<Row style={css1}>
<Col style={colcss} md={6}>
<ListGroup id="sortbar2">
<ListGroup.Item style={left} action href="#cdata1">
{props.list1}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#cdata2">
{props.list2}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#cdata3">
{props.list3}
</ListGroup.Item>
</ListGroup>
</Col>
<Col md={{span:3,offset :3}}>
<Row style={padding}>
<UserSearchbarComponent onChange={props.onChange} onClick={props.onClick} content={props.placeholder}/>
</Row>
</Col>
</Row>
<Row id="contentRow2">
<Col>
{props.children}
</Col>
</Row>
</Tab.Container>
</Container>
</>
)
}
export default ListgropBootFree;
<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dao/DbMapper.java
package com.ability.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.ability.dto.TestUserDto;
import com.ability.dto.custom.PostBoardComment;
import com.ability.dto.custom.PostBoardList;
import com.ability.dto.custom.PostBoardModify;
import com.ability.dto.custom.ReplyBoard;
import com.ability.dto.custom.Reputation;
import com.ability.dto.custom.UserSimple;
/**
* @author 정규현
* @summary 마이바티스 사용을 위한 인터페이스 정의
*/
public interface DbMapper {
public List<TestUserDto> getList() throws Exception;
public UserSimple getUser(@Param("email") String email) throws Exception;
public int signUpUser(@Param("email") String email,
@Param("password") String password,
@Param("nick_name") String nick_name,
@Param("name") String name,
@Param("area") String area,
@Param("user_image") String user_image) throws Exception;
public String getSecurityKey(@Param("email") String email) throws Exception;
public int confirmSecurityKey(@Param("security_key") String security_key) throws Exception;
public int isOverlapEmail(@Param("email") String email) throws Exception;
public int isOverlapNickName(@Param("nickname") String nickname) throws Exception;
public int isExistAccount(@Param("email") String email,@Param("name") String name) throws Exception;
public int updateTemporaryPassword(@Param("userid") int userid,
@Param("temporaryPassword") String temporaryPassword) throws Exception;
public List<PostBoardList> getCommunityList(Map<String, String> view);
public List<PostBoardList> getSearchResult(Map<String, String> view);
public int insertBoard(Map<String, String> content);
public int getTotalBoardContentCount(@Param("category_id") String category_id) throws Exception;
public int getTotalBoardSearchContentCount(Map<String, String> view) throws Exception;
public PostBoardList listDetail(Map<String, String> view);
public int updatePostBoard(Map<String, String> content);
public void updateViewCount(Map<String, String> boardid);
public PostBoardModify getModifyContent(Map<String, String> seq);
public List<ReplyBoard> getReply(Map<String, String> seq);
public int setReply(Map<String, String> contents);
public int setComment(Map<String,String> contents);
public List<PostBoardComment> getCommentList(Map<String,String> contents);
public int checkPostVote(Map<String, String> contents) throws Exception;
public int insertPostVote(Map<String, String> contents) throws Exception;
public int cancelPostVote(Map<String, String> contents) throws Exception;
public int fakeDelete(Map<String, String> contents) throws Exception;
public int fakeReplyDelete(Map<String, String> contents) throws Exception;
public int fakeCommentDelete(Map<String, String> contents) throws Exception;
public int checkPostReplyVote(Map<String, String> contents) throws Exception;
public int cancelPostReplyVote(Map<String, String> contents) throws Exception;
public int insertPostReplyVote(Map<String, String> contents) throws Exception;
public int postBoardCommentModify(Map<String, String> contents) throws Exception;
public int checkPostCommentVote(Map<String, String> contents) throws Exception;
public int cancelPostCommentVote(Map<String, String> contents) throws Exception;
public int insertPostCommentVote(Map<String, String> contents) throws Exception;
public int setPostBoardMark(Map<String, String> view) throws Exception;
public int cancelPostMark(Map<String, String> view) throws Exception;
public int checkPostBoardMark(Map<String, String> contents) throws Exception;
public int setModifyReplyOk(Map<String, String> view) throws Exception;
public Reputation getReputation(int userid);
}
<file_sep>/front/components/container/templatses/UserWrite.js
import React ,{Component}from 'react';
import {BoardAddList} from '../../presentational/molecules/BoardAddList';
import { Pagination } from 'react-bootstrap';
/**
*
* @author 우세림
* @summary 개발자들 사용자 전체게시글
*
*/
const UserArray2=[
{id:"1", title:"첫 번째 질문" ,category:"질의응답" ,like:"3" ,answer:"4" ,view:"12" ,day:"2019-06-19"},
{id:"2", title:"첫 번째 질문첫 번째 질문" ,category:"질의응답" ,like:"3" ,answer:"4" ,view:"12" ,day:"2019-06-19"},
{id:"3", title:"두두두 번째" ,category:"개발자 모집" ,like:"3" ,answer:"4" ,view:"12" ,day:"2019-06-19"},
{id:"4", title:"가나다라마바사아자" ,category:"프로젝트" ,like:"3" ,answer:"4" ,view:"12" ,day:"2019-06-19"},
{id:"5", title:"코딩이 적성에 안 맞아요" ,category:"질의응답" ,like:"3" ,answer:"4" ,view:"12" ,day:"2019-06-19"}
]
const user_write_page ={
margin: "70px auto",
}
class UserWrite extends Component {
render(){
const UserList= UserArray2.map((user)=>{
return <BoardAddList key={user.id} id={user.id} title={user.title} category={user.category} like={user.like} answer={user.answer} view={user.view} day={user.day}></BoardAddList>
});
return (
<>
<h5 className="user_add_title">
작성한 게시글
</h5>
<hr />
<div className="user_add_list">
{UserList}
</div>
<div style={user_write_page}>
<Pagination>
<Pagination.First />
<Pagination.Prev />
<Pagination.Item>{1}</Pagination.Item>
<Pagination.Ellipsis />
<Pagination.Item>{10}</Pagination.Item>
<Pagination.Item>{11}</Pagination.Item>
<Pagination.Item active>{12}</Pagination.Item>
<Pagination.Item>{13}</Pagination.Item>
<Pagination.Item disabled>{14}</Pagination.Item>
<Pagination.Ellipsis />
<Pagination.Item>{20}</Pagination.Item>
<Pagination.Next />
<Pagination.Last />
</Pagination>
</div>
</>
);
}
}
export default UserWrite;<file_sep>/front/components/presentational/molecules/AdminReportTbody.js
import React, {useState} from 'react';
import Link from 'next/link';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import axios from 'axios';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCrown,faBuilding,faUserCircle } from '@fortawesome/free-solid-svg-icons';
import { AbilityComponent } from '../atoms/AbilityComponent';
/**
*
* @author 신선하
* @summary admin 신고내역 테이블 컴포넌트 바디부분
* @Usage
*
*/
const modifyCss = {
color: "#0984e3",
fontFamily: "sans-serif",
cursor: "pointer"
}
const image_css = {
width: "30px",
height: "30px",
marginRight: "15px"
}
const logo={
width:"100px",
height:"20px",
marginBottom:"40px",
padding:"0"
}
function date(date_created) {
let year = date_created.substring(2, 4);
let month = date_created.substring(5, 7);
let day = date_created.substring(8, 10);
let edit_created = `${year}/${month}/${day}`;
return edit_created;
}
const name_css = {
width: "100px",
}
const profile_css = {
padding: "6px 12px 0 35px",
textAlign: "left",
fontWeight: "bold",
width: "210px"
}
const emailCss = {
width: "210px"
}
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const AdminReportTbody = (props) => {
let role_name = props.role_name;
let userid= props.userid;
function roleModal(role_name,userid,onExited) {
if (role_name == "ROLE_USER") {
role_name = "일반회원"
} else if (role_name == "ROLE_COMPANY") {
role_name = "기업회원"
} else {
role_name = "관리자"
}
const modalCss = {
display:"flex",
flexDirection:"column"
}
const radioCss = {
marginTop:"10px",
marginBottom:"10px",
display:"flex",
justifyContent:"space-around"
}
const radioBtn = {
display:"none"
}
const labelCss = {
display:"flex"
}
const role_css = {
marginTop:"27px",
marginRight:"5px",
color:"#636e72",
cursor:"pointer"
}
const role_span = {
color:"#5F4B8B",
cursor:"pointer"
}
const modalTitle={
fontFamily:"sans-serif",
fontWeight:"bold",
color:"#5F4B8B",
padding:"0"
}
const description = {
textAlign:"center",
fontFamily:"sans-serif",
fontWeight:"bold",
color:"#636e72"
}
const buttonTitle = role_name;
const [show, setShow] = useState(false);
const [roleValue, setRoleValue] = useState("default");
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleRadio = (e) => {
let obj = {};
obj[e.target.value] = e.target.checked;
setRoleValue(e.target.value);
}
const handleSubmit = () => {
let form = new FormData();
form.append("role_name",roleValue);
form.append("userid",userid);
axios({
method :'PUT',
baseURL : backUrl,
url :"/test/changerole",
data : form
}).then((res)=>{
if(res.data=="success"){
swal("권한을 변경하였습니다.");
setShow(false);
}else{
swal("[Error0577] 변경 실패");
}
})
}
return (
<>
<span style={role_span} onClick={handleShow}>
{buttonTitle}
</span>
<Modal show={show} onHide={handleClose} onExited={onExited}>
<Modal.Header closeButton>
<Modal.Title> <img src ="../../../static/image/Logo2.png" className="Logo-ABILITY" style={logo} alt="로고"/><span style={modalTitle}>권한 수정</span></Modal.Title>
</Modal.Header>
<Modal.Body>
<div style={modalCss}>
<div style={description}><span>수정할 권한을 선택하세요</span></div>
<div style={radioCss}>
<input type="radio" id="user" name="role" value="user" style={radioBtn} onChange={handleRadio} />
<label for="user" style={labelCss}>
<span style={role_css} id="userlabel"><FontAwesomeIcon icon={faUserCircle}/> 일반회원</span>
</label>
<input type="radio" id="company" name="role" value="company" style={radioBtn} onChange={handleRadio} />
<label for="company" style={labelCss}>
<span style={role_css} id="companylabel"><FontAwesomeIcon icon={faBuilding}/> 기업회원</span>
</label>
<input type="radio" id="admin" name="role" value="admin" style={radioBtn} onChange={handleRadio} />
<label for="admin" style={labelCss}>
<span style={role_css} id="adminlabel"><FontAwesomeIcon icon={faCrown}/> 관리자</span>
</label>
</div>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleSubmit}>
변경
</Button>
<Button variant="primary" onClick={handleClose}>
취소
</Button>
</Modal.Footer>
</Modal>
</>
);
}
const date_function = date(props.date_created);
const role_function = roleModal(role_name,userid,props.onExited);
return (
<>
<td><input type="checkbox" id={props.userid} checked={props.checked} onChange={props.onChange} /></td>
<td>{props.userid}</td>
<td style={profile_css}><img style={image_css} src={props.user_image} /><Link href={{ pathname: "/developer/page", query: { userid: props.userid } }}><a>{props.nick_name}</a></Link></td>
<td style={name_css}>{props.name}</td>
<td>{role_function}</td>
<td>{date_function}</td>
<td style={emailCss}>{props.email}</td>
<td><AbilityComponent val={props.reputation}></AbilityComponent></td>
<td><Link href={{ pathname: "/developer/update", query: { userid: props.userid } }}><a href=""><span style={modifyCss}>수정</span></a></Link></td>
</>
);
};
export default AdminReportTbody;<file_sep>/front/components/presentational/atoms/LodingComponent.js
import React, {Component} from 'react';
/**
* @author 정규현
* @summary 로딩 아이콘 구현
*/
const opts2 = {
top: '30%', // Top position relative to parent
left: '50%', // Left position relative to parent
shadow: '0 0 1px transparent', // Box-shadow for the lines
position: 'absolute' // Element positioning
};
class LodingComponent extends Component{
render(){
return(
<div>
<img id="loading" src="/static/image/loding.gif" style={opts2} alt="loading"/>
</div>
);
}
};
export default LodingComponent;<file_sep>/front/components/presentational/molecules/TagList.js
import React from 'react';
import Badge from 'react-bootstrap/Badge';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faEye } from '@fortawesome/free-solid-svg-icons';
/**
* @author 정규현
* @summary props 값으로 tags= ? 값을 넘겨주면 , (콤마)로 값을 구분해서 태그를 생성해 줌.
*
* @version 수정 정진호--태그 통일
* @version 수정 정규현--Modify TagList Scope
* @see 정규현 중복값 제거
*/
const tagcss = {
marginRight : "0.2rem",
paddingBottom:"0.24rem"
};
const tagcss2= {
backgroundColor:"#5F4B8B",
marginRight : "0.2rem",
paddingBottom:"0.24rem"
};
const TagList = (props) =>{
const taglist = [];
if(props.hashtag !== null && props.hashtag !== "" && props.hashtag !== undefined){
const list = props.hashtag.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
const taglistSet = [...new Set(taglist)];
const hashtags = taglistSet.map((value)=>(
<Badge key={value} variant="light" style={tagcss} id={value}>
{value}
</Badge>));
return(
<>
<h6>{hashtags}</h6>
</>
)
}else{
return(
<h6> </h6>
);
}
};
export const TagListBoard = (props) =>{
const taglist = ["#"+props.boardid, "조회수 "+ props.viewcount];
if(props.hashtag!=null){
const list = props.hashtag.split(',');
for(var i=0; i<list.length; i++){
taglist.push(list[i]);
}
}
const taglistSet = [...new Set(taglist)];
const hashtags = taglistSet.map((value,index)=>(
index>1?
<Badge key={value} variant="light" style={tagcss}>
{value}
</Badge>
:
<Badge key={value} variant="primary" style={tagcss2}>
{value}
</Badge>
));
return(
<>
<h6>{hashtags}</h6>
</>
)
}
export default TagList;<file_sep>/server/index.js
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const expressSession = require('express-session');
const dotenv = require('dotenv');
const userAPIRouter = require('./routes/user');
const postAPIRouter = require('./routes/post');
const companyAPIRouter = require('./routes/company');
/**
* @author 정규현
* @summary 익스 프레스 및 기본 설정들(미들웨어)
*/
dotenv.config();
const app = express();
passportConfig();
app.use(morgan('dev'));
app.use('/',express.static('uploads'));
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(cors({
origin:true,
credentials:true,
}));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(expressSession({
resave:false,
saveUninitialized:false,
secret:process.env.COOKIE_SECRET,
cookie:{
httpOnly:true,
secure:false, //https를 쓸때 true
},
name:'masterjung'
}));
app.use('/api/user', userAPIRouter);
app.use('/api/post', postAPIRouter);
app.use('/api/company', companyAPIRouter);
app.listen(process.env.NODE_ENV === 'production' ? process.env.PORT : 9208, ()=>{
console.log(`server is running on ${process.env.PORT}`);
});<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/TestUserDto.java
package com.ability.dto;
import lombok.Data;
//테스트용으로 삭
@Data
public class TestUserDto {
private int seq;
private String itemid;
@Override
public String toString() {
return "userDto [seq=" + seq + ", itemid=" + itemid + "]";
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
}
<file_sep>/front/pages/question/board.js
import React ,{Component,useState,useCallback} from 'react';
import BoardList from '../../components/presentational/molecules/BoardList';
import ListgropBoot from '../../components/presentational/atoms/ListgroupBoot';
import Tab from 'react-bootstrap/Tab';
import axios from 'axios';
import {TitleAndButtonComponent} from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
import LodingComponent from '../../components/presentational/atoms/LodingComponent';
import Page from '../../components/presentational/molecules/Page';
import { Row, Col } from 'react-bootstrap';
/**
*
* @author 정진호
* @summary 게시판 리스트
* @see 정규현 // 오류수정
* @see 정규현 // main title ui 추가
*/
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
const sortbar = {
width :"295px",
textAlign:"center"
};
const contentsize ={
height : "auto"
};
export class PostListJson extends Component{
constructor(props){
super(props);
this.state = {
postlist : [],
currentPage : 1,
totalListCount : 0,
};
this.getlist = this.getlist.bind(this);
this.onChangePage = this.onChangePage.bind(this);
}
async componentDidMount() {
await this.getlist();
}
componentDidUpdate() {
window.scrollTo(0,0);
}
getlist(){
axios.get(this.props.path,{
params : {
currentpage : this.state.currentPage
}
}).then((response) => {
this.setState({
postlist : response.data.postBoardList,
totalListCount : response.data.totalListCount+1
});
});
}
onChangePage(pageNumber){
this.setState({
currentPage : pageNumber
},()=> this.getlist());
}
render(){
let postlist = this.state.postlist;
return(
<>
{postlist.length > 0
? postlist.map(postContent=>(
<BoardList key={postContent.id}
seq={postContent.id}
hashtag={postContent.tags}
title={postContent.title}
userid={postContent.userid}
view_count={postContent.view_count}
like={postContent.likecount}
answer={postContent.replycount}
reputation={postContent.reputation}
id={postContent.nick_name}
day={postContent.date_created}
imagepath={postContent.user_image}
path="/question/content"/>
))
:
<>
<h6> </h6>
</>
}
<Row style={{marginTop:"2rem",justifyContent:"center"}}>
<div style={{textAlign:"center"}}>
<Page currentPage={this.state.currentPage} totalListCount={this.state.totalListCount} handlePageChange={this.onChangePage}/>
</div>
</Row>
</>
);
}
}
const Board = () => {
const [isvalue,setIsvalue] = useState("");
const [isdata,setIsdata] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [placeHolder, setPlaceHolder] = useState('검색어를 입력하세요');
const [value,setValue] = useState("");
let changeValue = useCallback((e)=> {
setIsvalue(e.target.value);
},[isvalue]);
const handlePageChange= useCallback((pageNumber)=> {
setCurrentPage(pageNumber);
},[currentPage]);
const onKeyPressSearch = useCallback((e)=>{
if(isvalue.trim().replace(' ','').length===0){
setIsvalue('');
setPlaceHolder('검색할 내용이 없습니다!');
return;
}
},[isvalue,placeHolder]);
const inputValue = useCallback((e)=>{
e.preventDefault();
if(isvalue.trim().replace(' ','').length===0){
setValue('');
setIsvalue('');
setPlaceHolder('검색할 내용이 없습니다!');
setIsdata([]);
return;
}else{
setIsdata([]);
setLoading(true);
const endpoint = backUrl
axios.get(endpoint,{
params :{
title : isvalue
}
}).then((response)=> {
setLoading(false);
setIsdata(response.data);
setIsvalue("");
setValue(isvalue);
}).catch((xhr) => {
console.log("실패 : ",xhr);
});
}
},[isdata,isvalue,loading]);
return (
<>
{loading && <LodingComponent/>}
<TitleAndButtonComponent title="질의 응답" path="/question/write" name="글쓰기">
<FontAwesomeIcon icon={faQuestionCircle} style={{width:"27.73px"}} />
</TitleAndButtonComponent>
<ListgropBoot style={sortbar} inputid="search" list1="최신순" list2="조회순" list3="답변순" onKeyPress={onKeyPressSearch} value={isvalue} onChange={changeValue} onClick={inputValue} placeholder={placeHolder}>
<Tab.Content style={contentsize}>
<Tab.Pane eventKey="#link1" >
<PostListJson path={plistEndPoint+"/0"}/>
</Tab.Pane>
<Tab.Pane eventKey="#link2" >
<PostListJson path={plistEndPoint+"/1"}/>
</Tab.Pane>
<Tab.Pane eventKey="#link3">
<PostListJson path={plistEndPoint+"/2"}/>
</Tab.Pane>
<Tab.Pane eventKey="#search">
{isdata.length > 0 ?
isdata.map(searchlist => {
return(
<BoardList key={searchlist.id}
seq={searchlist.id}
hashtag={searchlist.tags}
title={searchlist.title}
userid={searchlist.userid}
view_count={searchlist.view_count}
like={searchlist.likecount}
answer={searchlist.replycount}
reputation={searchlist.reputation}
id={searchlist.nick_name}
day={searchlist.date_created}
imagepath={searchlist.user_image}
path="/question/content"/>
)
}) : <>
<Row style={{marginTop:"11rem", paddingTop:"1.8em",textAlign:"center",border:"3px solid #5f4b8b",width:"95%",marginLeft:"3em",borderRadius:"10px"}}>
<Col style={{paddingBottom:"1.3rem"}}>
<img src="/static/image/Logo2.png" alt="Ability"/><br/><br/>
<hr/>
<h5>조회하신 "{value}" 에 대한 검색결과가 존재하지 않습니다.</h5>
<br></br>
<hr/>
<small style={{color:"darkred"}}>Error-Code 404 Not Found Search Result</small>
</Col>
</Row>
</>
}
</Tab.Pane>
<hr></hr>
</Tab.Content>
</ListgropBoot>
</>
)
}
export default Board;<file_sep>/front/pages/project/modify.js
import React, { useState,useCallback,useEffect } from 'react';
import { Container, Row } from 'react-bootstrap';
import ProfileImageUserid from '../../components/presentational/molecules/ProfileImageUserid';
import { ButtonComponent } from '../../components/presentational/atoms/ButtonComponent';
import axios from 'axios';
import Router from 'next/router';
import dynamic from 'next/dynamic';
import TitleComponent from '../../components/presentational/atoms/TitleComponent';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLaptopCode } from '@fortawesome/free-solid-svg-icons';
import { InputLabelText, InputLabelDefault } from '../../components/presentational/atoms/ProjectInput';
/**
* @auth 신선하
* @summary 글쓰기 수정 페이지(퀘스찬 보드 가져옴)
*/
const CkeditorOne2 = dynamic(() =>import('../../components/presentational/atoms/CkeditorOne2'),{
ssr : false
});
const cardcss = {
margin: "0px",
padding: "0px"
};
const Modify = ()=> {
const [seq, setSeq] = useState(0);
const [title, setTitle] = useState("");
const [tags, setTags] = useState("");
const [data, setData] = useState('<p></p>');
const [content, setContent] = useState("");
const [nick_name, setNick_name] = useState("");
const [user_image, setUser_image] = useState("");
const [file_path, setFile_path] = useState("");
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
useEffect(()=> {
setSeq(Router.query['seq']);
setNick_name(localStorage.getItem("nick_name"));
setUser_image(localStorage.getItem("user_image"));
const endPoint = backUrl;
axios.get(endPoint, {
params: {
seq: Router.query['seq']
}
})
.then((res)=> {
setTitle(res.data.title);
setTags(res.data.tags);
setTitle(res.data.title);
setContent(res.data.content);
setFile_path(res.data.file_path);
setData(res.data.content);
});
},[]);
const onChangeCk=useCallback((e)=>{
setData(e.editor.getData());
},[data]);
const onChangetitle=useCallback((e)=>{
setTitle(e.target.value)
},[title]);
const onChangetags=useCallback((e)=>{
setTags(e.target.value);
},[tags]);
const onChangeFile_path=useCallback((e)=>{
setFile_path(e.target.value);
},[file_path]);
const onClickSubmit = useCallback(() => {
const regex = /^[ㄱ-ㅎ가-힣a-zA-Z0-9,-\s]+$/;
if((tags.substr.length -1)==!regex){
tags.substr.length.replace(tags.substr.length -1, "")
}
if(title !== "" && data !== ""){
let Forms = new FormData();
Forms.append("seq",seq);
Forms.append("title",title);
Forms.append("content",data);
Forms.append("tags",tags);
Forms.append("file_path",file_path);
axios({
method :'put',
baseURL : backUrl,
data : Forms
}).then((res)=>{
if (res.data > 0) {
Router.push('/project/detail?seq='+seq);
} else {
alert("수정 실패");
}
});
}else{
alert("공백은 작성 불가능합니다.");
return;
}
},[seq,title,data,tags,file_path]);
return (
<>
<Container>
<form action="" method="post">
<TitleComponent title="프로젝트 자랑">
<FontAwesomeIcon
style={{width:"35px", height:"auto"}}
icon={faLaptopCode}/>
</TitleComponent>
<hr/><br/>
<Row>
<div className="col-11">
<InputLabelDefault
label="제목"
id="title"
value={title}
onChange={onChangetitle}
maxLength="66"
/>
<InputLabelText
label="유튜브 비디오ID"
text="https://www.youtube.com/watch?v="
id="youtubeId"
value={file_path}
onChange={onChangeFile_path}
maxLength="30"
/>
<InputLabelDefault
label="태그"
id="tags"
value={tags}
onChange={onChangetags}
maxLength="60"
/>
<CkeditorOne2
id="content"
data={data}
onChange={onChangeCk}
maxLength="1000"
/>
<hr />
<ProfileImageUserid
style={cardcss}
user_image={user_image}
writer={nick_name}
/><br/>
</div>
<div className="col-11" style={{textAlign:'right'}}><br/>
<ButtonComponent
name="취소"
variant="secondary"
css={{marginRight:"7px"}}
/>
<ButtonComponent
name="수정"
onclick={onClickSubmit}
/>
</div>
</Row>
</form>
</Container>
</>
);
}
export default Modify;<file_sep>/front/components/presentational/atoms/UserDeleteModal.js
import React, {Component} from 'react';
import { Modal, Button} from 'react-bootstrap';
import { InputText } from './InputboxComponent';
import axios from 'axios';
import Router from 'next/router';
/**
*
* @author 우세림
* @summary 유저삭제방 만들기 모달
*
*/
const EndPoint = process.env.NODE_ENV === 'production'? "?" : "?";
class UserDeleteModal extends Component {
constructor(props, context) {
super(props, context);
this.state = {
show: false,
userid : 0,
result : 0,
};
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
}
async handleClose() {
this.setState({ show: false });
}
async handleShow() {
this.setState({ show: true });
}
async componentDidMount() {
let user = Router.query['userid'];
this.setState({
userid : user
})
}
async handlesubmit() {
let password = document.getElementById('password').value;
let result = 0;
if(password){
await axios.get(EndPoint, {
params : {
userid : Router.query['userid'],
password :<PASSWORD>
}
}).then((Response) => {
result = Response.data;
if(result>0){
swal({
text: "회원탈퇴 되었습니다.",
title: "회원탈퇴 성공",
timer: "3000",
icon: "/static/image/Logo2.png"
});
Router.push("/");
} else {
swal({
text: "회원탈퇴가 일치하지 않습니다.",
title: "회원탈퇴 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}
});
} else{
swal({
text: "빈칸을 입력해주세요",
title: "회원탈퇴 오류",
timer: "3000",
icon: "/static/image/Logo2.png"
});
return;
}
}
render() {
return (
<>
<Button variant="primary" onClick={this.handleShow} variant="info">
회원탈퇴
</Button>
<Modal
{...this.props}
size="md"
aria-labelledby="contained-modal-title-vcenter"
show={this.state.show} onHide={this.handleClose}
centered
>
<Modal.Header closeButton>
<Modal.Title>회원탈퇴</Modal.Title>
</Modal.Header>
<Modal.Body>
<div>- 회원탈퇴를 원하시면 비밀번호를 입력해주세요.</div>
<hr/>
비밀번호 <InputText id="password" type="<PASSWORD>"/>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.handleClose}>
취소
</Button>
<Button variant="primary" onClick={this.handlesubmit}>
확인
</Button>
</Modal.Footer>
</Modal>
</>
);
}
}
export default UserDeleteModal;<file_sep>/Ability-SpringBoot1/src/main/java/com/ability/dto/Sal.java
package com.ability.dto;
public class Sal {
private int sal_id;
private int min_sal;
private int max_sal;
private String text_sal;
public int getSal_id() {
return sal_id;
}
public void setSal_id(int sal_id) {
this.sal_id = sal_id;
}
public int getMin_sal() {
return min_sal;
}
public void setMin_sal(int min_sal) {
this.min_sal = min_sal;
}
public int getMax_sal() {
return max_sal;
}
public void setMax_sal(int max_sal) {
this.max_sal = max_sal;
}
public String getText_sal() {
return text_sal;
}
public void setText_sal(String text_sal) {
this.text_sal = text_sal;
}
}
<file_sep>/front/components/presentational/molecules/CardArea.js
import React from 'react';
import {Card} from "react-bootstrap";
/**
*
* @author 정규현
* @summary 디테일 영역에 사용할 카드 영역 입니다.
*
*/
const CardArea = (props)=>{
return(
<Card border="Secondary" style={{ width: '30rem' }}>
<Card.Header>{props.title}</Card.Header>
<Card.Body>
<Card.Text>
{props.content}
</Card.Text>
</Card.Body>
</Card>
);
}
export default CardArea;<file_sep>/front/sagas/index.js
import { all, call } from 'redux-saga/effects';
import user from './user';
import post from './post';
import main from './main';
/**
* @author 정규현
* @summary saga index
*/
export default function* rootSaga(){
yield all([
call(user),
call(post),
call(main)
]);
}<file_sep>/front/components/container/templatses/PostDetail.js
import React, { Component } from 'react';
import { Row, Container, Col } from 'react-bootstrap';
import { ButtonComponent } from '../../presentational/atoms/ButtonComponent';
import CkeditorOne from "../../presentational/atoms/CkeditorOne";
import ContentTitle from "../../presentational/molecules/ContentTitle";
import Recommend from "../../presentational/molecules/Recommend";
import { ReplyCompleteComponent , ReplyComponent } from '../../presentational/atoms/ReplyComponent'
import { GridArea } from "../organisms/GridArea";
import TagList from "../../presentational/molecules/TagList"
import axios from 'axios';
import {_} from 'underscore';
/**
* @author 곽호원
* @summary 게시글 상세보기 컴포넌트
* @author 정진호
* @version 세션 체크후 댓글, 답글 컴포넌트 생성 없으면 게시글만 보임.
*/
const buttoncss = {
textAlign: "right"
}
const writercss = {
textAlign: "right",
marginRight: ".5rem"
}
const backUrl = process.env.NODE_ENV === 'production'? "?" : "?";
let userid = window.sessionStorage.getItem('userid');
let data = "";
class Postcontent extends Component{
constructor(props){
super(props);
this.state = {
postlist : [],
replys : [],
comments : [],
userlist : [],
replysimage : [],
commentsimage : [],
list : [],
insert : 0,
seq : props.match.params.seq
};
}
async componentDidMount() {
data = this.state.seq;
await axios.get(plistEndPoint,{
params : {
seq:data
}
}).then((response) => {
this.setState({
postlist : response.data
});
}) // ERROR;
const getComment = backUrl
await axios.get(getComment,{
params : {
seq:data
}
}).then((response) => {
this.setState({
comments : response.data.map(list=>({id : list.id , name : list.comment,image : list.image}))
});
});
const getReply = backUrl
await axios.get(getReply,{
params : {
seq:data
}
}).then((response) => {
this.setState({
replys : response.data.map(list=>({id : list.id, name : list.reply,image : list.image}))
});
});
this.setState({
userlist : [...this.state.comments, ...this.state.replys, {id : this.state.postlist.userid,name :this.state.postlist.nick_name, image : this.state.postlist.user_image}]
});
let result =[]
result.push(_.uniq(this.state.userlist,(item,key,name)=>{
return item.name;
}));
this.setState({
list : _.uniq(this.state.userlist,(item,key,name)=>{
return item.name;
})
});
}
delete(){
data = this.state.seq;
axios.get(deleteBaord,{
params : {
seq : data
}
}).then(() => {
alert(this.state.seq+'번 글 삭제 하였습니다.');
window.location.href = "/question"
})
}
insert=(e)=> {
let content = document.getElementById('ckvalue').innerHTML;
axios.get(replyendpoint,{
params : {
userid : 74,
seq : data,
reply_content : content
}
}).then(()=> {
this.setState({
reply : this.state.reply
})
window.history.go(0);
});
}
render(){
const postlist = this.state.postlist;
const list = this.state.list;
if(postlist !== null && list.length > 0){
return(
<>
<PostDetail seq={this.state.seq} title={postlist.title} id={postlist.nick_name} view_count={postlist.view_count} likecount={postlist.likecount} content={postlist.content} hashtag={postlist.hashtag} list={list} onClick={this.delete.bind(this)} oninsert={this.insert.bind()}/>
</>
)
}else {
return (
<>
<h6> </h6>
</>
)
}
}
}
const commentcss = {
width : "100%",
border: "1px solid #e2e2e2",
padding : "1.1rem",
display : "grid"
}
const contentcss ={
backgroundColor :"#f8f9fa",
paddingTop :"2rem",
paddingLeft : "0.7rem",
paddingBottom : "1rem",
width : "100%"
}
const replycss ={
display :"flex"
}
export const PostDetail = (props) => {
function sessioncheck() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = yyyy + '-' + mm + '-' + dd;
if(userid !==null || userid !== "" || userid !== undefined){
return(
<>
<ReplyCompleteComponent on={replycss} seq={props.seq} date={today} />
<CkeditorOne list={props.list} image={props.image} /><br />
</>
)
}else{
return(
<>
<br></br>
</>
)
}
}
return (
<GridArea>
<Container>
<ContentTitle title={props.title} to={"/modifyWrite/"+props.seq} onClick={props.onClick}/>
<hr />
<div style={writercss}>
<h6>작성자 : {props.id} </h6>
<i className="fas fa-eye"> {props.view_count}</i>
</div>
<Row>
<Recommend count={props.likecount}/>
<Col xs={10} >
<br />
<div style={contentcss} dangerouslySetInnerHTML={ {__html: props.content} } ></div>
<hr/>
<small>#태그 </small><TagList hashtag={props.hashtag} />
<hr/>
<div style={commentcss}>
<small>댓글</small>
<div></div>
<ReplyComponent/>
</div>
<br></br>
<div>
{sessioncheck()}
<br /><br />
</div>
<div style={buttoncss}>
<ButtonComponent name="목록"/>
<ButtonComponent name="답변 제출" onclick={props.oninsert} />
</div>
</Col>
</Row>
</Container>
</GridArea>
)
}
export default Postcontent;<file_sep>/front/reducers/post.js
/**
* @author 정규현
* @summary 리덕스
*/
export const initalState = {
mainPosts:[],
imagePaths: [],
imageTitle: [],
imageDesc: [],
imageUrl: [],
imageRegisting: false,
};
export const UPLOAD_IMAGES_REQUEST = 'UPLOAD_IMAGES_REQUEST';
export const UPLOAD_IMAGES_SUCCESS = 'UPLOAD_IMAGES_SUCCESS';
export const UPLOAD_IMAGES_FAILURE = 'UPLOAD_IMAGES_FAILURE';
export const REMOVE_IMAGE = 'REMOVE_IMAGE';
export const UPLOAD_BANNER_REGISTER_REQUEST = 'UPLOAD_BANNER_REGISTER_REQUEST';
export const UPLOAD_BANNER_REGISTER_SUCCESS = 'UPLOAD_BANNER_REGISTER_SUCCESS';
export const UPLOAD_BANNER_REGISTER_FAILURE = 'UPLOAD_BANNER_REGISTER_FAILURE';
const reducer = (state=initalState, action) =>{
switch(action.type){
case UPLOAD_IMAGES_REQUEST: {
return {
...state,
};
}
case UPLOAD_IMAGES_SUCCESS: {
return {
...state,
imagePaths: [...state.imagePaths, ...action.data],
};
}
case UPLOAD_IMAGES_FAILURE: {
return {
...state,
};
}
case REMOVE_IMAGE: {
return {
...state,
imagePaths: state.imagePaths.filter((v, i) => i !== action.index),
};
}
case UPLOAD_BANNER_REGISTER_REQUEST: {
return {
...state,
imagePaths: [...state.imagePaths],
imageTitle: [...state.imageTitle],
imageDesc: [...state.imageDesc],
imageUrl: [...state.imageUrl],
imageRegisting: true,
};
}
case UPLOAD_BANNER_REGISTER_SUCCESS: {
return {
...state,
imagePaths: [],
imageRegisting: false,
};
}
case UPLOAD_BANNER_REGISTER_FAILURE: {
return {
...state,
};
}
default: {
return {
...state,
};
}
}
};
export default reducer;<file_sep>/front/components/container/templatses/UserModify.js
import React ,{Component}from 'react';
import { GridArea } from '../organisms/GridArea';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import UserUpdate from './UserUpdate';
import UserDelete from './UserDelete';
/**
*
* @author 우세림
* @summary 개발자들 수정 TabMeun
*
*/
class UserModify extends Component {
render(){
return (
<>
<GridArea>
<Tabs>
<TabList>
<Tab>정보수정</Tab>
<Tab>회원탈퇴</Tab>
</TabList>
<TabPanel>
<UserUpdate/>
</TabPanel>
<TabPanel>
<UserDelete/>
</TabPanel>
</Tabs>
</GridArea>
</>
);
}
}
export default UserModify;<file_sep>/front/components/presentational/atoms/ListgroupBoot.js
import React from 'react';
import ListGroup from 'react-bootstrap/ListGroup'
import Tab from 'react-bootstrap/Tab';
import {Container,Row,Col} from 'react-bootstrap';
import { UserSearchbarComponent } from './SearchbarComponent';
/**
* @author 정진호
* @see 정규현 UserSearchbarComponent 컴포넌트 리펙토링, 필요한 값이 props로 전달이 안됨
*/
const css1 = {
borderBottom : "2px solid #eaeaea",
}
const padding = {
paddingTop: "22px"
}
const colcss ={
minHeight:"80px"
}
const left = {
display : "inline"
}
const ListgropBoot =(props) => {
return(
<>
<Container id="contentRow" >
<Tab.Container id="list-group-tabs-example" defaultActiveKey="#link1">
<Row style={css1}>
<Col style={colcss} md={6} id="contentcol">
<ListGroup id="sortbar">
<ListGroup.Item style={left} action href="#link1">
{props.list1}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#link2">
{props.list2}
</ListGroup.Item>
<ListGroup.Item style={left} action href="#link3">
{props.list3}
</ListGroup.Item>
</ListGroup>
</Col>
<Col md={{span:3,offset :3}}>
<Row style={padding} id="searchrow">
<UserSearchbarComponent onChange={props.onChange} onKeyPress={props.onKeyPress} value={props.value} onClick={props.onClick} content={props.placeholder} inputId={props.inputid}/>
</Row>
</Col>
</Row>
<Row id="contentRow">
<Col >
{props.children}
</Col>
</Row>
</Tab.Container>
</Container>
</>
)
}
export default ListgropBoot;
<file_sep>/front/components/presentational/molecules/PostContent.js
import React from 'react';
import {Col} from "react-bootstrap";
/**
*
* @auth 곽호원
* @summary 질의 응답 상세페이지 코드와 에러 위치 설명 등등 컴포넌트
*
*/
const PostContent = (props) => {
return (
<Col xs={10}>
<p>{props.content}</p>
</Col>
);
};
export default PostContent; | af30a4c84da9823cde32856ac75975776b6f08ea | [
"JavaScript",
"Java",
"Markdown",
"INI"
] | 169 | JavaScript | pgg-dev/ABILITY-PUBLIC | 3d5a72e8f714964692cafcde32eedc2fa74a1211 | 548aa8fe2b66d32236322618a860ee93029857e8 |
refs/heads/main | <repo_name>zagdiablo/simple-python-port-scanner<file_sep>/README.md
# Simple python port scanner
Just a simple port scanner
## Usage
```bash
python3 simple-port-scanner.py <ip>
```
## License
[MIT](https://choosealicense.com/licenses/mit/)
<file_sep>/simple-port-scanner.py
import socket
import sys
import threading
def scanTarget(target_ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((target_ip, port))
socket.setdefaulttimeout(1)
if result == 0:
print(f"port {port} is open.")
s.close()
def main():
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1])
else:
print(
f"invalid amount of argument, requires 1 argument but {len(sys.argv)-1} was given.")
print("Usage: python3 simple-port-scanner.py <ip>")
print("Example: python3 simple-port-scanner.py 192.168.0.1")
exit()
threads = []
try:
for port in range(1000):
threads.append(threading.Thread(
target=scanTarget, args=(target, port)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
except KeyboardInterrupt:
print("Exiting...")
except socket.gaierror:
print("Host name could not be resolved.")
except socket.error:
print("Cannot connect to target.")
exit()
if __name__ == "__main__":
main()
| f5de2472326419ad5ee9c2212174a90ba683ff55 | [
"Markdown",
"Python"
] | 2 | Markdown | zagdiablo/simple-python-port-scanner | 025220bbf322eec4bf1929e7da6bc0545e96f69d | 1e02bff66b4ee16b92fcff97f74d05a76ceeab33 |
refs/heads/main | <repo_name>gabi-lovera/vision-artificial<file_sep>/Practico4/FrameSize.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
fourcc = cv2.VideoWriter_fourcc('X ', 'V', 'I', 'D')
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print('width, height:', width, height)
width = int(width)
height = int(height)
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width, height))
while cap.isOpened():
ret, frame = cap.read()
if ret is True:
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
<file_sep>/Practico2/ForAnidado/segmentation.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
img = cv2.imread('hoja.png', 0)
thr = 200
for i, row in enumerate(img):
for j, col in enumerate(row):
if col >= thr:
img[i, j] = 255
else:
img[i, j] = 0
cv2.imwrite('resultado.png', img)
cv2.imshow('resultado', img)
cv2.waitKey(0)
<file_sep>/Practico13/classificar.py
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
import matplotlib.pyplot as plt
''' El dataset contiene tres clases: elefantes, rinoserontes y bufalos
y cada una de estas clases tiene alrededor de 200 imagenes de entranamiento
y 50 de prueba '''
train_datagen = ImageDataGenerator(rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2)
test_datagen = ImageDataGenerator(rescale=1. / 255)
training_set = train_datagen.flow_from_directory('./dataset/train',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory('./dataset/test',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
model = tf.keras.models.Sequential([
tf.keras.layers.experimental.preprocessing.Resizing(64, 64,
interpolation='bilinear'),
tf.keras.layers.Conv2D(6, (6, 6), activation='relu',
input_shape=(64, 64, 3)),
tf.keras.layers.Conv2D(12, (5, 5), strides=(2, 2), activation='relu'),
tf.keras.layers.Conv2D(24, (4, 4), strides=(2, 2), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(rate=.25),
tf.keras.layers.Dense(200, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
optimizer = tf.keras.optimizers.Adam(decay=.0001)
model.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_set, epochs=25)
model.evaluate(test_set)
b = test_set.next()
print(b[1][0:5]) # Imprimo las etiquetas verdaderas
model.predict(b[0][0:5]) # Calculo las probabilidades con el modelo
# ----------------------------------
img = keras.preprocessing.image.load_img(
"./dataset/380.jpg", color_mode='rgb', target_size=None
)
img2 = keras.preprocessing.image.load_img(
"./dataset/009.jpg", color_mode='rgb', target_size=None
)
def predic(img):
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)
predictions = model.predict(img_array)
return predictions
predictions = predic(img)
predictions2 = predic(img2)
f = plt.figure()
f.add_subplot(1, 2, 1)
plt.title(str(predictions))
plt.suptitle('Imagenes separadas del dataset')
plt.imshow(img)
f.add_subplot(1, 2, 2)
plt.title(str(predictions2))
plt.imshow(img2)
plt.show(block=True)
score = predictions[0]
print("La primera imagen obtiene como presicion: " + str(score))
score2 = predictions2[0]
print("Y la segunda imagen: " + str(score2))
<file_sep>/Practico2/PIL/segmentation.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image # Usando la libreria PIL
foto = Image.open('hoja.png')
if foto.mode != 'L':
foto = foto.convert('L')
umbral = 200
datos = foto.getdata()
datos_binarios = []
for x in datos:
if x < umbral:
datos_binarios.append(0)
continue
datos_binarios.append(1)
nueva_imagen = Image.new('1', foto.size)
nueva_imagen.putdata(datos_binarios)
nueva_imagen.save('resultado.png')
im = Image.open('resultado.png')
im.show()
nueva_imagen.close()
foto.close()
<file_sep>/Practico2/Opencv/segmentation.py
import cv2
img = cv2.imread('hoja.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
while True:
ret, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
cv2.imwrite('resultado.png ', thresh)
cv2.imshow('hoja binarizada', thresh)
if cv2.waitKey(1) == ord('q'):
break
cv2.destroyAllWindows()
<file_sep>/Practico2/Numpy/segmentation.py
import cv2
img = cv2.imread('hoja.png', 0)
thr = 200
img[img >= thr] = 255
img[img < thr] = 0
cv2.imwrite('resultado.png', img)
cv2.imshow('resultado', img)
cv2.waitKey(0)
<file_sep>/Practico9/rectificando.py
import cv2
import numpy as np
refPt = []
i = True
def draw_circle(event, x, y, flags, param):
global i
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
refPt.append((x, y))
if np.shape(refPt) == (4, 2):
i = False
rectification(refPt)
def rectification(refPt):
img = cv2.imread('smartv.jpg')
# funciona con el siguiente orden: arriba, abajo, derecha y arriba
input_pts = np.float32(refPt)
output_pts = np.float32([[0, 0], [0, 500], [800, 500], [800, 0]])
M = cv2.getPerspectiveTransform(input_pts, output_pts)
out = cv2.warpPerspective(img, M, (800, 500))
cv2.imwrite('result.jpg', out)
cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('image', draw_circle)
img = cv2.imread('smartv.jpg')
while 1:
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if not i:
break
while True:
result = cv2.imread('result.jpg')
cv2.imshow('image', result)
k = cv2.waitKey(1) & 0xFF
if k == 27 or k == ord('q'):
break
cv2.destroyAllWindows()
<file_sep>/Practico3/FrameRate.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import time
cap = cv2.VideoCapture('video.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
fps = int(fps)
print("Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
while cap.isOpened():
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if (cv2.waitKey(fps) & 0xFF) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
<file_sep>/Practico6/transformacionEuclidiana.py
import numpy as np
import cv2
from matplotlib import pyplot as plt
import pylab as pl
def euclidiana(angle, tx, ty):
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# translation
(h, w) = (img.shape[0], img.shape[1])
T = np.float32([[1, 0, tx], [0, 1, ty]])
shifted = cv2.warpAffine(img, T, (w, h))
# rotation
(h, w) = shifted.shape[: 2]
center = (w / 2, h / 2)
R = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(shifted, R, (w, h))
pl.gray(), pl.axis('equal'), pl.axis('off')
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(rotated), plt.title('Output')
plt.show()
euclidiana(10, 100, 100)
<file_sep>/Practico12/alineación.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
MIN_MATCH_COUNT = 10
imag1 = cv2.imread("Imagen3.jpg")
imag2 = cv2.imread("Imagen4.jpg")
dscr = cv2.SIFT_create()
kp1, des1 = dscr.detectAndCompute(imag1, None)
kp2, des2 = dscr.detectAndCompute(imag2, None)
matcher = cv2.BFMatcher(cv2.NORM_L2)
matches = matcher.knnMatch(des1, des2, k=2)
good = []
for m, n in matches:
if m.distance < 0.7 * n.distance:
good.append(m)
if len(good) > MIN_MATCH_COUNT:
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
H, mask = cv2.findHomography(dst_pts, src_pts, cv2.RANSAC, 5.0)
wimg2 = warp = cv2.warpPerspective(imag2, H, (560, 420))
alpha = 0.5
blend = np.array(wimg2 * alpha + imag1 * (1 - alpha), dtype=np.uint8)
cv2.imwrite('SIFT.jpg', blend)
cv2.imshow("image", blend)
cv2.waitKey()
<file_sep>/Practico10/r.py
import cv2
import numpy as np
from scipy.spatial import distance
i = True
e = True
refPt = []
coord = []
def reset():
global i, e, refPt, coord
refPt = []
coord = []
i = True
e = True
def draw_circle(event, x, y, flags, param):
global i, e, refPt, coord
if i == True:
if event == cv2.EVENT_LBUTTONDOWN:
if e == True:
cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
coord.append((x, y))
if np.shape(coord) == (2, 2):
cv2.line(img, coord[0], coord[1], (0, 0, 255), 2)
D = distance.euclidean(coord[0], coord[1])/2.52
(mX, mY) = midpoint(coord[0], coord[1])
cv2.putText(img, "{:.1f}cm".format(D), (int(mX), int(mY - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 0, 0), 2)
e = False
def midpoint(p1, p2):
return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2
cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('image', draw_circle)
img = cv2.imread('result.jpg')
while True:
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if k == 27 or k == ord('q'):
break
if k == ord('r'):
cv2.destroyAllWindows()
reset()
break
<file_sep>/Practico13/README.md
**Dataset:** [African Wildlife](https://www.kaggle.com/biancaferreira/african-wildlife) from kaggle.<file_sep>/Practico8/transformacionAfín.py
import cv2
import numpy as np
from PIL import Image, ImageDraw
refPt = []
i = True
def draw_circle(event, x, y, flags, param):
global i
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
refPt.append((x, y))
if np.shape(refPt) == (3, 2):
i = False
trasnfomacionAfin(refPt)
def trasnfomacionAfin(refPt):
img = cv2.imread('imgblue.jpg')
print(refPt)
pts1 = np.float32(refPt)
rows, cols, ch = img.shape
pts2 = np.float32([[0, 0], [0, rows], [cols, rows]])
matrix = cv2.getAffineTransform(pts1, pts2)
result = cv2.warpAffine(img, matrix, (cols, rows))
cv2.imwrite('result.jpg', result)
im1 = Image.open('imgshelf.jpg')
im2 = Image.open('result.jpg')
mask_im = Image.new("L", im2.size, 0)
draw = ImageDraw.Draw(mask_im)
# funciona cuando los puntos se hacen arriba primero, abajo y a la derecha
p4 = (refPt[2][0] - refPt[1][0] + refPt[0][0], refPt[2][1] - refPt[1][1] + refPt[0][1])
points = (refPt[0], refPt[1], refPt[2], p4)
draw.polygon(points, fill=255)
mask_im.save('mask.jpg', quality=95)
back_im = im1.copy()
back_im.paste(im2, (0, 0), mask_im)
back_im.save('final.jpg', quality=95)
cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('image', draw_circle)
img = cv2.imread('imgshelf.jpg')
while 1:
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if not i:
break
while True:
result = cv2.imread('final.jpg')
cv2.imshow('image', result)
k = cv2.waitKey(1) & 0xFF
if k == 27 or k == ord('q'):
break
cv2.destroyAllWindows()
<file_sep>/Practico10/medicionObjeto.py
import cv2
import numpy as np
from r import reset
i = True
e = True
def function():
def rectification():
img = cv2.imread('imagen.jpeg')
puntos=(204, 0), (217, 551), (690, 571), (715, 2)
pts1 = np.float32(puntos)
alt = puntos[1][1] - puntos[0][1]
anch = puntos[3][0] - puntos[0][0]
pts2 = np.float32([[0, 0], [0, alt], [anch, alt], [anch, 0]])
M = cv2.getPerspectiveTransform(pts1, pts2)
imagen_alineada = cv2.warpPerspective(img, M, (anch, alt))
cv2.imwrite('result.jpg', imagen_alineada)
rectification()
reset()
function()
cv2.destroyAllWindows()
<file_sep>/Practico5/cortar rectangulo.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
def funtion():
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode, crop_img
drawing = False # true if mouse is pressed
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
crop_img = img[iy:y, ix:x]
cv2.rectangle(img, (ix, iy), (x, y), (255, 0, 0), 0)
cv2.namedWindow('Output', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('Output', draw_circle)
img = cv2.imread('imagen.jpg')
while 1:
cv2.imshow('Output', img)
k = cv2.waitKey(1) & 0xFF
if k == ord('g'):
cv2.imwrite('resultado.png', crop_img)
break
if k == ord('r'):
cv2.destroyAllWindows()
funtion()
break
elif k == ord('q'):
break
cv2.destroyAllWindows()
funtion()<file_sep>/Practico11/README.md
# Trabajo Práctico 11:
*Aplicación ArUco*

<file_sep>/README.md
# Vision por computadora
Trabajos Prácticos: Visión Artificial
## UTN Facultad Regional San Francisco
#### Alumnos:
- `<NAME>.`
- `<NAME>.`
#### Carrera:
Ingeniería en Sistemas de Información.
| bfbcdac0fbd5e1cd9417f38b65bb9f4bf87b3871 | [
"Markdown",
"Python"
] | 17 | Python | gabi-lovera/vision-artificial | d72fe6450a053a517c9282d67701f65794280368 | 6e0eabcc731662eb5aefadc8f960cb0da846553c |
refs/heads/master | <file_sep>json.extract! @rating, :id, :value, :idea_id, :created_at, :updated_at
| e45289d25e26616673e9c66262e3ac9c4de1227d | [
"Ruby"
] | 1 | Ruby | canf/myapps | 4aa2d4d6f969adbe269b883cb821ac50fc0a8548 | 2f371a114fb02ff3a8b73d858bef2f441e189a65 |
refs/heads/master | <file_sep>// chapter 01
// 01 Write a script to greet your website visitor using JS alert box.
alert("Welcome to our website!");
// 02 Write a script to display following message on your web page:
alert("Error! Please enter a valid password.");
// 3.Write a script to display following message on your webpage:(Hint:Use line break)
alert("Welcome to JS Land...\n Happy Coding!");
// 4. Write a script to display following messages in sequence:
alert("Welcome to JS Land...");
// chapter 02
// 1. Declare a variable called username.
let userName;
// 2. Declare a variable called myName & assign to it a string
// that represents your Full Name.
let myName = "<NAME>";
// 3. Write script to
// a) Declare a JS variable, titled message.
// b) Assign “Hello World” to variable message
// c) Display the message in alert box.
let message = "Hello World";
alert(message);
// 4. Write a script to save student’s bio data in JS variables and
// show the data in alert boxes.
let studentName = "<NAME>";
let studentage = 23;
let studentCertification = "Certified Mobile Application Development";
alert(studentName);
alert(studentage);
alert(studentCertification);
// 5. Write a script to display the following alert using one JS variable:
// 6. Declare a variable called email and assign to it a string that
// represents your Email Address(e.g.<EMAIL>).
// Show the blow mentioned message in an alert box.(Hint: use
// string concatenation)
let email = "<EMAIL>";
alert("My email address is " + email);
// 7. Declare a variable called book & give it the value “A
// smarter way to learn JavaScript”.Display the following
// message in an alert box:
let book = "A smarter way to learn JavaScript";
alert("I am trying to learn from the book " + book);
// 8. Write a script to display this in browser through JS
let heading = document.createElement("h1");
heading.textContent = "Yah! I can write HTML content through JavaScript";
document.querySelector("body").appendChild(heading);
// 9. Store following string in a variable and show in alert and
// browser through JS
let demoVariable = "▬▬▬▬▬▬▬▬▬ஜ ۩۞۩ ஜ▬▬▬▬▬▬▬▬▬";
alert(demoVariable);
let heading = document.createElement("h1");
heading.textContent = demoVariable;
document.querySelector("body").appendChild(heading);
// Chapter 03
// 1. Declare a variable called age & assign to it your age.Show
// your age in an alert box.
let age = 23;
alert(age);
// 3. Declare a variable called birthYear & assign to it your
// birth year.Show the following message in your browser:
let birthYear = 1997;
let contentToDisplay = document.createElement("h1");
contentToDisplay.textContent = "My birth year is " + birthYear;
document.querySelector("body").appendChild(contentToDisplay);
// 4. A visitor visits an online clothing store www.xyzClothing.com.Write a script to store in variables the following information: a.Visitor’s name b.Product title c.Quantity i.e.how many products a visitor wants to order Show the following message in your browser: “<NAME> ordered 5 T - shirt(s) on XYZ Clothing store”.
let VisitorName = "<NAME>";
let productTitle = "Shampoo";
let qunatity = 5;
let contentToDisplay = document.createElement("h1");
contentToDisplay.textContent = `${vistorName} ordered ${qunatity} ${productTitle} on AR Clothing Store`;
document.querySelector("body").appendChild(contentToDisplay);
// chapter 04
// 1. Declare 3 variables in one statement.
let vOne, vTwo, vThree;
// 2. Declare 5 legal & 5 illegal variable names.
// legal ones
let var1, var2, var3, var4, var5;
// the illegal ones
// let 1var,2var,3var,4var,5var
// chapter 05
// 1. Write a program that take two numbers & add them in a new variable.Show the result in your browser.
let numOne = 5;
let numTwo = 10;
let sum = numOne + numTwo;
let displayer = document.createElement("h1");
displayer.textContent = `Sum of ${numOne} and ${numTwo} is ${sum}`;
document.querySelector("body").appendChild(displayer);
// 2. Repeat task1 for subtraction, multiplication, division & modulus.
// for subtraction
let sub = numTwo - numOne;
displayer.textContent = `${numTwo} - ${numOne} is ${sub}`;
document.querySelector("body").appendChild(displayer);
// for multiplication
let product = numOne * numTwo;
displayer.textContent = `The product of ${numOne} and ${numTwo} is ${product}`;
document.querySelector("body").appendChild(displayer);
// for division
let division = numOne / numTwo;
displayer.textContent = `${numOne} / ${numTwo} is ${division}`;
document.querySelector("body").appendChild(displayer);
// 3. Do the following using JS Mathematic Expressions
let desiredVariable;
let displayer = document.createElement("h1");
displayer.textContent = `Value after variable declaration is ${desiredVariable}`;
document.querySelector("body").appendChild(displayer);
desiredVariable = 6;
displayer.textContent = `Initial value: ${desiredVariable}`;
document.querySelector("body").appendChild(displayer);
desiredVariable++;
displayer.textContent = `Value after incrementation is ${desiredVariable}`;
desiredVariable = desiredVariable + 7;
displayer.textContent = `Value after addition is ${desiredVariable}`;
desiredVariable--;
displayer.textContent = `Value after decrement is ${desiredVariable}`;
desiredVariable = desiredVariable % 3;
displayer.textContent = `The remainder is ${desiredVariable}`;
// 4. Cost of one movie ticket is 600 PKR.Write a script to store ticket price in a variable & calculate the cost of buying 5 tickets to a movie.
let ticketRate = 600;
let totalAmount = ticketRate * 5;
let displayer = document.createElement("h1");
displayer.textContent = `Total cost to buy 5 tickets to a movie is ${totalAmount}PKR`;
document.querySelector("body").appendChild(displayer);
// chapter 6-9
// 1. Write a program to take a number in a variable, do the required arithmetic to display the following result in your browser:
let a = 10;
let displayOne = document.createElement("h2");
displayOne.textContent = `Result:\nThe value of a is: ${a}\n............`;
document.querySelector("body").appendChild(displayOne);
let displayTwo = document.createElement("h2");
displayTwo.textContent = `The value of ++a is: ${
a + 1
}\nNow the value of a is: ${a + 1}`;
document.querySelector("body").appendChild(displayTwo);
// 3. Write a program that takes input a name from user & greet the user.
let userName = prompt("Enter your name");
document.write("Welcome " + userName);
// 5. Write a program to take input a number from user & display it’s multiplication table on your browser.If user does not enter a new number, multiplication table of 5 should be displayed by default.
let userInput = prompt("Enter a number");
if (userInput !== "") {
for (let i = 1; i <= 10; i++) {
document.write(`${i} * ${userInput} = ${i * userInput}`);
}
} else {
for (let i = 1; i <= 10; i++) {
document.write(`${i} * 5 = ${i * 5}`);
}
}
// chapter 17-20
// 1. Declare and initialize an empty multidimensional array. (Array of arrays)
const exampleArray = [[], [], []];
// 2. Declare and initialize a multidimensional array representing the following matrix:
const exampleArray = [
[0, 1, 2, 3],
[1, 0, 1, 2],
[2, 1, 0, 1],
];
// 3. Write a program to print numeric counting from 1 to 10.
for (let i = 1; i <= 10; i++) {
document.writeln(i);
}
// 4. Write a program to print multiplication table of any number using for loop.
let userInput = prompt("Enter a number");
for (let i = 1; i <= 10; i++) {
document.write(`${i} * ${userInput} = ${i * userInput}`);
}
// 5. Write a program to print items of the following array using for loop: fruits = [“apple”, “banana”, “mango”, “orange”, “strawberry”]
const fruits = ["apple", "banana", "mango", "orange", "strawberry"];
fruits.forEach((fruit) => {
document.write(fruit + " ");
});
// 6. Generate the following series in your browser.
// See example output.
// a.Counting: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
// b.Reverse counting: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
// c.Even: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
// d.Odd: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
// e.Series: 2k, 4k, 6k, 8k, 10k, 12k, 14k, 16k, 18k, 20k
// a
let i;
document.writeln("Counting:");
for (i = 1; i <= 10; i++) {
document.writeln(i + " ");
}
// b
document.writeln("Reverse Counting:");
for (i = 10; i >= 1; i - 1) {
document.writeln(i + " ");
}
// c
document.writeln("Even:");
for (i = 0; i <= 20; i++) {
if (i % 2 === 0) {
document.writeln(i + " ");
}
}
// d
document.writeln("Odd:");
for (i = 0; i <= 20; i++) {
if (i % 2 !== 0) {
document.writeln(i + " ");
}
}
// e
document.writeln("Odd:");
for (i = 2; i <= 20; i++) {
if (i % 2 === 0) {
document.writeln(i + "k");
}
}
// 7. You have an array A = [“cake”, “apple pie”, “cookie”, “chips”, “patties”] Write a program to enable “search by user input” in an array.After searching, prompt the user whether the given item is found in the list or not.
const A = ["cake", "apple pie", "cookie", "chips", "patties"];
const userInput = prompt(
"Welcome to AR Bakery. What do you want to order sir/ma'am?"
);
if (A.includes(userInput)) {
document.write(
`${userInput} is available at ${A.indexOf(userInput)} in our bakery.`
);
} else {
document.write(`${userInput} is not available in our bakery.`);
}
// 8. Write a program to identify the largest number in the given array.
// A = [24, 53, 78, 91, 12].
const A = [24, 53, 78, 91, 12];
document.write(`Array items: ${A}`);
document.write(`The largest number is ${Math.max(24, 53, 78, 91, 12)}`);
// 9. Write a program to identify the smallest number in the given array.A = [24, 53, 78, 91, 12]
const A = [24, 53, 78, 91, 12];
document.write(`Array items: ${A}`);
document.write(`The smallest number is ${Math.min(24, 53, 78, 91, 12)}`);
// 10. Write a program to print multiples of 5 ranging 1 to 100.
for (let i = 1; i <= 100; i++) {
if (i % 5 === 0) {
document.write(i + " ");
}
}
// chapter 21-25
// 1. Write a program that takes two user inputs for first and last name using prompt and merge them in a new variable titled fullName.Greet the user using his full name.
const firstName = prompt("Enter your first name");
const lastName = prompt("Enter your last name");
alert(`Your full name is ${firstName} ${lastName}`);
// 2. Write a program to take a user input about his favorite mobile phone model.Find and display the length of user input in your browser
const favoriteMobileModel = prompt("What is your favorite mobile model?");
document.write(`Length of string: ${favoriteMobileModel.length}`);
// 3. Write a program to find the index of letter “n” in the word “Pakistani” and display the result in your browser.
const givenString = "Pakistani";
const indexOfN = givenString.indexOf("n");
document.write(`String: ${givenString}`);
document.write(`Index of 'n': ${indexOfN}`);
// 4. Write a program to find the last index of letter “l” in the word “Hello World” and display the result in your browser.
const givenString = "Hello World";
const lastIndexOfL = givenString.lastIndexOf("l");
document.write(`String: ${givenString}`);
document.write(`Last index of 'l': ${lastIndexOfL}`);
// 5. Write a program to find the character at 3rd index in the word “Pakistani” and display the result in your browser.
const givenString = "Pakistani";
const charAtIndex3 = givenString[3];
document.write(`String: ${givenString}`);
document.write(`Character at index 3: ${charAtIndex3}`);
// 6. Repeat Q1 using string concat() method.
const firstName = prompt("Enter your first name");
const lastName = prompt("Enter your last name");
const fullName = firstName.concat(lastName);
alert(`Your full name is ${fullName}`);
// 7. Write a program to replace the “Hyder” to “Islam” in the word “Hyderabad” and display the result in your browser.
let cityName = "Hyderabad";
const newName = cityName.replace("Hyder", "Islam");
document.write(`City: ${cityName}`);
document.write(`After replacement: ${newName}`);
// 8. Write a program to replace all occurrences of “and” in the string with “&” and display the result in your browser.
let message =
"Ali and Sami are best friends.They play cricket and football together.";
document.write(message.replace("and", "&"));
// 9. Write a program that converts a string “472” to a number 472. Display the values & types in your browser.
const givenString = "472";
const converted = Number(givenString);
document.write(`Value: ${givenString}`);
document.write(`Type: ${typeof givenString}`);
document.write(`Value: ${converted}`);
document.write(`Type: ${typeof converted}`);
// 10. Write a program that takes user input.Convert and show the input in capital letters.
let userInput = "peanuts";
document.write(`User input: ${userInput}`);
document.write(`Upper case: ${userInput.toUpperCase()}`);
// 11. Write a program that takes user input.Convert and show the input in title case.
let userInput = prompt("Your favorite programming language");
document.write(`User input: ${userInput}`);
document.write(`Title case: ${userInput.titleCase()}`);
// 12. Write a program that converts the variable num to string.var num = 35.36; Remove the dot to display “3536” display in your browser.
let num = 35.36;
document.write(`Number: ${num}`);
document.write(" Converted to string: " + num.toString());
// 13. Write a program to take user input and store username in a variable.If the username contains any special symbol among[@ . , !], prompt the user to enter a valid username.
const userName = prompt("User name");
if (
userName.includes("@") ||
userName.includes(".") ||
userName.includes(",") ||
userName.includes("!")
) {
alert("Please enter a valid username!");
}
// 14. You have an array A = [cake”, “apple pie”, “cookie”, “chips”, “patties”]
// Write a program to enable “search by user input” in an array.After searching, prompt the user whether the given item is found in the list or not.
const a = ["cake", "apple pie", "cookie", "chips", "pattries"];
const userInput = prompt("Search your item").toLowerCase();
if (a.includes(userInput)) {
alert(`${userInput} is available!`);
} else {
alert(`${userInput} is not available!`);
}
// 16. Write a program to convert the following string to an array using string split method.var university = “University of Karachi”; Display the elements of array in your browser.
const university = "University of Karachi";
const splitted = university.split("");
splitted.forEach((letter) => document.writeln(letter));
// 17. Write a program to display the last character of a user input.
const userInput = prompt("Your input");
document.writeln(`User input: ${userInput}`);
const userInputLength = userInput.length;
document.write(`Last character of input: ${userInput[userInputLength - 1]}`);
// 18. You have a string “The quick brown fox jumps over the lazy dog”.Write a program to count number of occurrences of word “the” in given string.
// chapter 26-30
// 1. Write a program that takes a positive integer from user & display the following in your browser.a.number b.round off value of the number c.floor value of the number d.ceil value of the number
const number = 3.45214;
document.write(`number: ${number}`);
document.write(`round off value: ${Math.round(number)}`);
document.write(`floor value: ${Math.floor(number)}`);
document.write(`ceil value: ${Math.ceil(number)}`);
// 2. Write a program that takes a negative floating point number from user & display the following in your browser.a.number b.round off value of the number c.floor value of the number d.ceil value of the number
const number = prompt("Please enter a negative floating point number");
document.write(`number: ${number}`);
document.write(`round off value: ${Math.round(number)}`);
document.write(`floor value: ${Math.floor(number)}`);
document.write(`ceil value: ${Math.ceil(number)}`);
// 3. Write a program that displays the absolute value of a number.
const number = prompt("Please enter a number");
document.write(`The absolute value of ${number} is ${Math.abs(number)}`);
// 4. Write a program that simulates a dice using random() method of JS Math class.Display the value of dice in your browser.
const randomNumber = Math.round(Math.random() * 6);
document.write(`random dice value: ${randomNumber}`);
// 5. Write a program that simulates a coin toss using random() method of JS Math class.Display the value of coin in your browser
const tossValues = ["heads", "tails"];
const targetingIndex = Math.round(Math.random());
document.write(`random coin value: ${tossValues[targetingIndex]}`);
// 6. Write a program that shows a random number between 1 and 100 in your browser.const randomNumber = Math.round(Math.random() * 100)
document.write(`Random number between 1 and 100: ${randomNumber}`);
// 7. Write a program that asks the user about his weight.Parse the user input and display his weight in your browser.Possible user inputs can be: a. 50 b. 50kgs c. 50.2kgs d. 50.2kilograms
const userWeight = prompt("Enter your weight");
document.write(`The weight of user is ${parseFloat(userWeight)} kilograms`);
// 8. Write a program that stores a random secret number from 1 to 10 in a variable.Ask the user to input a number between 1 and 10. If the user input equals the secret number, congratulate the user.
const secretNumber = Math.round(Math.random() * 10);
document.write(secretNumber);
const userInput = Number(prompt("I have a secret number. Can you guess it?"));
if (userInput === secretNumber) {
document.write("Congratulations, you did it!");
} else {
document.write("Sorry you failed!");
}
// chapter 31-34
// 1. Write a program that displays current date and time in your browser.
document.write(new Date().toString());
// 2. Write a program that alerts the current month in words.
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const currentTime = new Date();
const targettedMonth = currentTime.getMonth();
document.write(`Current month: ${months[targettedMonth]}`);
// 3. Write a program that alerts the first 3 letters of the current
// day, for example if today is Sunday then alert will show Sun.
const months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
const currentTime = new Date();
const targettedMonth = currentTime.getMonth();
document.write(`Today is: ${months[targettedMonth]}`);
// 4. Write a program that displays a message “It’s Fun day” if its Saturday or Sunday today.
const currentTime = new Date();
const today = currentTime.getDay();
if (today === 0 || today === 6) {
document.write("It's fun day!");
}
// 5. Write a program that shows the message “First fifteen days of the month” if the date is less than 16th of the month else shows “Last days of the month”.
const currentTime = new Date();
const today = currentTime.getDate();
if (today < 16) {
document.write("First fifteen days of the month");
} else {
document.write("Last days of the month");
}
// 6. Write a program that determines the minutes since midnight, Jan. 1, 1970 and assigns it to a variable that hasn't been declared beforehand. Use any variable you like to represent the Date object.
const past = new Date("January 1, 1970");
const present = new Date();
const elapsedTimeInMilliseconds = present - past;
const elapsedTimeInMinutes = elapsedTimeInMilliseconds / 60000;
document.write(`Current Date: ${present}`);
document.write(
`Elapsed milliseconds since January 1, 1970: ${elapsedTimeInMilliseconds}`
);
document.write(
`Elapsed minutes since January 1, 1970: ${elapsedTimeInMinutes}`
);
// chapter 35-38
// 1. Write a function that displays current date & time in your browser.
const currentTime = function () {
document.write(new Date());
};
// 2. Write a function that takes first & last name and then it greets the user using his full name.
const greetUser = function (firstName, lastName) {
document.write(`Hello ${firstName} ${lastName}`);
};
// 3. Write a function that adds two numbers(input by user) and returns the sum of two numbers.
const add = function (numOne, numTwo) {
return numOne + numTwo;
};
// 5. Write a function that squares its argument.
const square = function (number) {
return number * number;
};
// 6. Write a function that computes factorial of a number.
// 7. Write a function that take start and end number as inputs
// & display counting in your browser.
const counterPrinter = function () {
let start = Number(prompt("Enter a number to start with"));
const end = Number(prompt("Enter a number to end with"));
while (start <= end) {
document.write(start);
start++;
}
};
// 9. Write a function that calculates the area of a rectangle.
// A = width * height
// Pass width and height in following manner:
// i.Arguments as value
// ii.Arguments as variables
const rectangleArea = function (width, height) {
area = width * height;
return area;
};
const width = 10;
const height = 16;
document.write(rectangleArea(20, 3));
document.write(rectangleArea(width, height));
// 10. Write a JavaScript function that checks whether a passed string is palindrome or not ?
const passedString = prompt("Please enter a word");
const stringLength = passedString.length;
let reversed = "";
for (let i = stringLength - 1; i >= 0; i--) {
reversed += passedString[i];
}
if (passedString === reversed) {
document.write(`${passedString} is a palindrome.`);
} else {
document.write(`${passedString} is not a palindrome.`);
}
// chapter 38-42
// 2. Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.
function check_leapyear() {
//define variables
var year;
//get the entered year from text box
year = document.getElementById("year").value;
//three conditions to find out the leap year
if ((0 == year % 4 && 0 != year % 100) || 0 == year % 400) {
alert(year + " is a leap year");
} else {
alert(year + " is not a leap year");
}
}
// Write a function to delete all vowels from a sentence.Assume that the sentence is not more than 25 characters long.
// chapter 58-67
// i.Get element of id “main - content” and assign them in a variable.
const desiredElement = document.getElementById("main-content");
// ii.Display all child elements of “main - content” element.
console.log(desiredElement.childNodes);
// iii.Get all elements of class “render” and show their innerHTML in browser.
const renderElements = document.getElementsByClassName("render");
renderElements.forEach((element) => {
console.log(element.innerHTML);
});
// iv.Fill input value whose element id first - name using javascript.
const theElement = document.getElementById("first-name");
theElement.innerHTML = "mehtab";
// v.Repeat part iv for id ”last - name” and “email”.
// for last-name
const lnElement = document.getElementById("last-name");
lnElement.innerHTML = "alam";
// for email
const emailElement = document.getElementById("email");
emailElement.innerHTML = "<EMAIL>";
// i.What is node type of element having id “form - content”.
const theEl = document.getElementById("form-content");
console.log(theEl.nodeType);
// output: 1
// ii.Show node type of element having id “lastName” and its child node.
const theEl = document.getElementById("lastName");
console.log(theEl.nodeType);
//the node type is 1
//child node is 3
// iii.Update child node of element having id “lastName”.
const theEl = document.getElementById("lastName");
const child = theEl.firstChild;
child.textContent = "updated";
console.log(child);
// iv.Get First and last child of id “main - content”.
const targetEl = document.getElementById("main-content");
const first = targetEl.firstChild;
const last = targetEl.lastChild;
// v.Get next and previous siblings of id “lastName”.
const targetEl = document.getElementById("lastName");
const next = targetEl.nextSibling;
const previous = targetEl.previousSibling;
// vi.Get parent node and node type of element having id “email”
const targetElement = document.getElementById("email");
const parent = targetElement.parentNode;
console.log(parent.nodeType);
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// ***ASSIGNMENT ENDED HERE*** //
// //
//////////////////////////////////////////////////////////////////////////////////////////////
<file_sep># saylani-web-mobile-js-assignments-solution
This repo contains the solution of js assignments from saylani's online web and mobile app dev course.
| d5da242485df6011b03ae54fb5091ba6d4b4524a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | alammehtab/saylani-web-mobile-js-assignments-solution | 743e35f0bfe7a158293686f7852610780368e9bf | e8abae11966a0b8915958969f49a24dcf9a22ded |
refs/heads/master | <repo_name>MaffC/BlogAlba<file_sep>/posts/post8.md
---
layout: post
title: How to set up effective mail systems, pt. 1
date: 2012-06-11 00:31:00
tags: gentoo, guide, howto, linux, mail, postfix, servers, sysadmin
---
So a few months ago, I moved my primary mail hosting to my own VPS. Over the months since then, I've been tweaking and adding to my mail system, and I figure it'd help both myself and others if I documented what I've done, so I'll start with a list of all the software I use.
### Main Software
* **Gentoo** – My VPS runs **Gentoo**. I personally prefer it over other distros, as it's both lighter and less screwed up.
* **postfix** – I was originally going to use **Exim**, but found it strangely difficult to configure, plus **postfix** seems to universally have lower transaction times.
* **dovecot 2** – I'm switching away from **Gmail**, so obviously the things I would've missed most would be things like push email and mail filters. Dovecot supports IMAP IDLE, and has sieve/managesieve, so it was easy to port my Gmail filters over.
* **saslauthd** – While dovecot has its own SASL authentication, I prefer to use this when authenticating over SMTP. **EDIT:** I have since switched from **saslauthd** to Dovecot 2 for SASL authentication. Dovecot works well enough for it that I questioned why I actually needed **saslauthd**.
* **Mutt** – Mutt is my primary MUA. I'll also be discussing configuration changes I made to **Mutt**, and ways I made it work more like **Gmail**.
### Extra Software
* **Spamassassin** – This should be obvious. Does a great deal to cut down on spam. Plus, with a filter set up with **dovecot**'s sieve, I have a spam folder like before. **EDIT:** When I first published this post, I had only just set up **Postgrey** and had no idea what kind of impact it would have on incoming spam/junk mail. It had a massive impact – I haven't received a single spam email since. **Spamassassin** and **Amavisd** may actually be unnecessary when using **Postgrey** (Unless of course you plan to host mail for others, or if you receive a \*lot\* of spam).
* **Postgrey** – This does a fantastic job of cutting down on spam.
* **Amavisd** – Somewhat necessary for making **postfix** work with **SpamAssassin**, but also makes it easy to offload the antispam part of the mail system to another server. **Amavisd** can also be used for integrating antivirus systems into your mail scanning process, but I don't need that.
* **OpenDKIM** – Used for signing outgoing mail with my DKIM key, and for validating incoming signed mail. This does a good job of ensuring that mail sent from my domain is actually coming from one of my servers.
* **policyd-spf** – Originally, I used **pypolicyd-spf**, but it quite literally breaks every time there's an update to python, it's since been replaced with [this perl equivalent][1] which has never had any issues. This uses SPF to validate incoming mail, and ensure that the sending server is actually authorised to send mail for the given domain.
* **fail2ban** – This isn't strictly part of the process I go through when setting mail up, but **fail2ban** helps cut down load a lot when bots are trying (and failing) to use a server as an unauthenticated relay.
In the near future, I'll write a second post detailing how I linked all this together, including config excerpts, but in this post I'm just discussing the software I used, as well as why I use each package. I'll also leave you with a list of extremely good tips.
* **Get an SSL certificate.** This makes setting secure mail up a **lot** easier, especially if you plan to send or receive mail remotely with stuff like IMAP.
* If you do get an SSL certificate, **disable or firewall unencrypted mail ports**. Obviously leave port 25 in place, but if you're sending or receiving mail remotely, disable the unencrypted IMAP/POP3 ports (143 for IMAP and 110 for POP3), and set your MTA up to only accept submission mail through 465.
* **Set up SPF records for your domain appropriately**. SPF does a good job of telling other mail systems who is or is not allowed to send mail for your domain.
* **Generate a DKIM key, and add it to your domain's DNS**. As with SPF, DKIM (DomainKeys Identified Mail) does a fantastic job of indicating to other mail systems whether an email is actually legitimate or not.
* **Use blacklists**. There's a large number of DNS-based blacklists which indicate whether a given IP address is known for sending spam or for attempting to compromise servers. This can go a long way in preventing spam.
* **Report any spam you receive.** Reporting received spam to places like **SpamCop** not only reduces the chance of you receiving similar spam in the future, but it helps others too. It helps identify servers that send spam (Contributing to blacklists), helps identify possible domains used for spam (again, contributing to blacklists), and can contribute to the accuracy of antispam systems like **SpamAssassin**.
* **Monitor your services extensively**. This is definitely a big one. It's not easy to monitor your server by looking at logs, and often unless you've got systems set up to email you when anything out of the ordinary happens, you just plain don't know what's happening with your server. Packages like [**Monitorix**][2] (disclaimer: I'm the package maintainer for **monitorix** on **Gentoo**), do a fantastic job of showing you at-a-glance whether anything abnormal is happening, so it's easy to see if and when your mail server is rejecting mail. This can also be great for indicating when you've misconfigured something.
* **Use external monitoring services**. Services like [**MXToolbox**][3] have free accounts, and you can use them to set up checks so that you get an email if your server's IP is on any IP blacklists. Services like [**Pingdom**][4] are also great for monitoring both uptime and external availability.
* **Make sure your forward and reverse DNS match** and that your reverse DNS is your primary mail domain (or what your server actually identifies itself as). This is definitely a good way of ensuring your mail isn't identified as spam.
One final thing to note, the guide and so on will discuss **my** current mail setup. This means it assumes you'll be using sockets for things like **Postgrey**. Please read everything carefully before making configuration changes to your own mail setup, as what works for me may not work for you.
That's all for now, but I'll be adding to this list, and writing a second post documenting how I actually set my mail system up, very soon. **EDIT:** Disregard that. Second part of this post will arrive _eventually_ but I am tremendously lazy.
[1]: https://launchpad.net/postfix-policyd-spf-perl/
[2]: http://www.monitorix.org/
[3]: http://mxtoolbox.com/
[4]: http://www.pingdom.com/
<file_sep>/posts/20151106.onencryption.md
---
title: On encryption and jails
date: 2015-11-06 00:51
tags: encryption,tls,freebsd,jails,ezjail
---
It was [reported recently][1] that [Let's Encrypt][2] had recently launched their private beta. As someone who does their best to ensure encryption is as widely-available as possible, I was excited.
Yesterday, I got my email stating that the domain maff.scot had been whitelisted for issuance using the [letsencrypt][3] utility. Awesome! Let's see how you get it set up. To the best of my knowledge, there was no FreeBSD port or package for the utility, which meant I had to `git clone` their repo and set things up.
Depending on how your system's set up, this might be a breeze, or it might be a challenge.
A few things to note, going in:
* FreeBSD by default ships with `csh` as the default shell, and no `sudo`.
* I very strongly embraced the BSD way of doing things, so that was still the case.
* The `letsencrypt` utility has some questionable defaults, in that it will attempt to run its own server temporarily for use in verifying ownership of your domain. It can also futz with your Apache/nginx config files.
* It doesn't take into account what platform it's running on, and as such, flies in the face of the FreeBSD filesystem hierarchy, documented in `hier(7)`, defaulting to `/etc/letsencrypt` for configuration and storage, and `/var/lib/letsencrypt` for its working directory.
* The [documentation][4] was a bit confusing on what I actually had to do to get things up and running in the event that a binary package was not available.
With all these in mind, I felt it might be prudent to just set it all up inside a FreeBSD Jail. This would allow all dependencies to be satisifed from the `letsencrypt` client's point of view, and would allow it to place files where it pleased, without making a mess of my main server.
### Preparing to run Jails
I already had a jail system set up on my server, but I'll document the process here anyway. To simplify things, I used the EzJail system to get everything set up for me, and did final configuration and such using a `flavour`.
To start off, I ran `pkg install ezjail` to install ezjail. While the package itself is called "ezjail", the utility used to actually work with it is `ezjail-admin`.
After installing the package, the "base system", what all jails will draw from, must be installed. This can be compiled from source, but if you're running a RELEASE version of FreeBSD, it's perfectly fine (and easier) to simply use the same distribution bundles that you installed your host FreeBSD system from. To install the base system, just run `ezjail-admin install`, adding `-m` and `-p` to include man pages and the ports tree, respectively. This will download the FreeBSD base and userland, manpages (if desired), and will invoke `portsnap` to download the ports tree, and install it all to `/usr/jails/basejail`, by default.
After this, I set up my `flavour` for the jails I'd be running. A flavour is a set of files and configuration options that will be added to a jail you're creating, and allows for decent customisation; specific flavours can have certain packages preinstalled, services pre-enabled or pre-configured. I just set up a default flavour, which disabled services like `sendmail`, and pre-populated `/etc/resolv.conf`. This can be easily done by copying the example flavour bundled with ezjail, and editing the name and files where appropriate.
Since the machine I'm running on only has one IPv4 address, I needed to NAT traffic from my jails, by adding the following rules to my `pf.conf`:
```
jails="10.0.1.0/24"
wan="re0"
wan_ip="0.0.0.0" # replaced with your real IP, obviously
nat pass on $wan from $jails to any -> $wan_ip
pass in from $jails to $jails # to allow inter-jail traffic
```
It's also a good idea to give jails their own loopback interface, separate from the host's, by adding `cloned_interfaces="lo1"` to your `rc.conf`, and restart networking.
### Setting up the Let's Encrypt jail
Now, finally, we're ready to create the jail itself, by running `ezjail-admin create -f yourflavour letsencrypt 're0|10.0.1.10,lo1|127.0.1.10'`, which will create a jail named 'letsencrypt' using the flavour 'yourflavour', and will give it a private IP of 10.0.1.10 and a loopback IP of 127.0.1.10. These IPs haven't been pre-configured on your machine, but will be added on-the-fly when the jail is started; hence why the interface names `re0` and `lo1` are specified.
I then ran `ezjail-admin start letsencrypt` to actually start the jail. At this point, you may receive a warning about using `jail.conf` instead of `JAIL_` variables if you're running FreeBSD 10; this is a fault in ezjail, but has no impact on the operation of the actual jail, as it's converted on-the-fly.
Now you're able to enter into the jail using `ezjail-admin console letsencrypt`, but before doing that, we need to install packages for the jail. To prepare it for running `letsencrypt`, install base dependencies using `pkg -j letsencrypt install pkg git sudo bash` on the host. This will install git and pkg inside the jail, so that `letsencrypt-auto` can install all packages it needs to operate. It will also install bash, necessary for running `letsencrypt-auto`, and sudo, necessary because `letsencrypt` expects to be run as an unprivileged user with sudo access.
### Entering the jail, installing Let's Encrypt
Now we can enter the jail with `ezjail-admin console letsencrypt`. This'll give you a root shell inside your jail, from which we can create our unprivileged user with `pw user add -n leuser -m -s /usr/local/bin/bash -G wheel`, followed by `passwd leuser` to set the password you'll enter when sudo prompts for one. Then, set up sudo by running `visudo` and adding `%wheel ALL=(ALL) ALL`. You'll also need to run `mkdir -p /etc/letsencrypt/www` to create the directory which will be used for proving to the Let's Encrypt systems that you own the domain you're requesting a certificate for.
Drop down to the unprivileged user with `su - leuser`, which gives us a clean login environment as the user, then pull down the Let's Encrypt client with `git clone https://github.com/letsencrypt/letsencrypt`, and cd into the directory. From here, just run `./letsencrypt-auto`, which will install all necessary packages, python modules, and finally sort out the `letsencrypt` binary itself.
The documentation then dictates that you swap out all instances of the `letsencrypt` command with `./letsencrypt-auto`, but this isn't necessary every time, as `letsencrypt-auto` will check each and every time for updates to packages and python modules before actually doing anything, which can be very irritating to wait on. After running it once, you can simply make a symbolic link to the actual `letsencrypt` program by running `ln -s $HOME/.local/share/letsencrypt/bin/letsencrypt $HOME/letsenc`. From then on, you can simply run `sudo ./letsenc ...` from the unprivileged user's home directory.
### Getting the host system ready for Let's Encrypt
As I mentioned, I wasn't comfortable with letting the `letsencrypt` client run its own server for domain validation. Thankfully, an alternate authentication method was made available to me: webroot. Using this, the `letsencrypt` client will simply create a file in the webroot directory, which will then be requested by the validation service, at `http://your-domain/.well-known/acme/`. It will also expect the webroot path to remain the same, irrespective of whether you're requesting a certificate for multiple domains.
Thankfully, since I know it expects the file to be served at `/.well-known/acme/`, and I run nginx, I was able to set up a redirect across all vhosts in the same manner that a standard 404 page is served in nginx: Adding a root `location` directive, beneath nginx's standard `location 403.html, 404.html, 50x.html` directive.
```
location ~^/\.well-known\/acme-challenge\/.*$ {
root /usr/local/www/jail_symlinks/letsencrypt;
}
```
Followed by creating the symbolic link nginx would look for, via `ln -s /usr/jails/letsencrypt/etc/letsencrypt/www /usr/local/www/jail_symlinks/letsencrypt`. As I was using jails for serving web applications, I had a separate folder specifically for access to jails, but you can change this to any path you desire, of course.
### Using Let's Encrypt to get a certificate
Now that all setup is out of the way, we can finally get our certificate. To do this, I ran `sudo ./letsenc --agree-dev-preview --server https://acme-v01.api.letsencrypt.org/directory certonly -a webroot --webroot-path /etc/letsencrypt/www`. This presented me with a few dialogs, prompting me for an email address and list of domains to request certificates for. Once this was done, it performed validation that I owned the domains in question. This succeeded, and the certificates were issued and stored into `/etc/letsencrypt/live`. From here, you can simply use symlinks to provide nginx with your `fullchain.pem` and `privkey.pem` files, which contain the certificate and chain, and private key, respectively.
At this point, I've successfully got Let's Encrypt set-up, and a certificate issued. After adding `ssl_certificate /path/to/fullchain.pem` and `ssl_certificate_key /path/to/privkey.pem` to my site's `server` block in nginx, I was up and running. You can also use the `chain.pem` file provided by `letsencrypt` to easily set up OCSP stapling. After doing this, your `server` block should contain something like the following (providing you also run `ln -s /usr/jails/letsencrypt/etc/letsencrypt/live /etc/ssl/letsencrypt`):
```
ssl_certificate /etc/ssl/letsencrypt/maff.scot/fullchain.pem;
ssl_certificate_key /etc/ssl/letsencrypt/maff.scot/privkey.pem;
ssl_trusted_certificate /etc/ssl/letsencrypt/maff.scot/chain.pem;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 valid=300;
resolver_timeout 10s;
```
### A few notes on the resulting setup
Having gone through all this, setting up new domains with a Let's Encrypt certificate should be quite painless, as is renewing certificates. Let's Encrypt issues certificates with a 90-day validity period, and they recommend renewing within 60 days of issuing, such that if something goes wrong, you have a month's time to notice and fix it.
While looking at how renewal works, I noticed there was a `letsencrypt-renewer` program included with `letsencrypt`. I'm not sure if this is fully-functioning as of yet, as the documentation states that an automated renewal system is not yet in-place.
[1]: https://www.eff.org/deeplinks/2015/10/lets-encrypt-enters-private-beta
[2]: https://letsencrypt.org
[3]: https://github.com/letsencrypt/letsencrypt
[4]: http://letsencrypt.readthedocs.org/en/stable/using.html<file_sep>/posts/20150310.newsitefantasticallyperlybecausewhynot.md
---
title: New site, fantastically perl-y, because why not
date: 2015-03-10 01:39
tags: life, perl, personal, programming, website
---
Oops, and then I didn't have a blog for a few months. I pulled down my old blog (formerly located at blog.maff.me.uk), partially the .scot TLD launched and I wanted to move to maff.scot as soon as possible, and partially because I wanted a blog system I was happier working with (The old blog was dotClear-based, and hosted at [Gandi][1] because it was a free addon and I was lazy. I'd looked around for a while to see what blogging systems I could try out, but I didn't want to go near Wordpress and none of the other systems really appealed to me. Some friends suggested I try Jekyll, but I couldn't really grok that; I also found Dapper online, but as far as static-site platforms go it wasn't the best for a blog. So I wrote my own.
To rewind a bit, I've been steadily improving my Perl skills for a good while now, so when it came to hunting for blogging software I was biased towards perl-based systems. It turns out there are quite a few! Unfortunately most were either too complex to work with, or didn't have features I needed. What most of them _did_ offer, was a simple publishing system based around YAML and Markdown. This actually seems pretty great, because [Markdown][2] is well-documented and easy to write posts in, without me having to faff about much with formatting. It also allows me to keep post metadata at the top of each post, in my editor.
So having seen what other systems were like, and knowing what I did and didn't like about each, I wrote my own, (slightly patriotically) named [BlogAlba][3]. It's a single ~150-line perl script, designed to run as an application (though it could easily be changed to just output static HTML files and such). It's been quite a fun learning project, and should (at this point) be quite easy to maintain and extend.
The _styling_ of my site has also changed; this time based around [Bootstrap][4] and a theme [found on bootply][5] via [BootstrapZero][6], written by user [cskelly][7]. I've cut it down somewhat and modified it to fit my own preferences, but credit where it's due of course :)
Hopefully now that it's a lot easier for me to write up posts, and everything's being published on software I'm intimately familiar with, my site'll see the love it deserves. If you've got any comments or questions, look to my twitter because I'm not gonna deal with the noise of an actual comments system.
[1]: http://gandi.net/
[2]: https://daringfireball.net/projects/markdown/syntax
[3]: https://github.com/Maffsie/BlogAlba/
[4]: http://getbootstrap.com/
[5]: http://www.bootply.com/69873
[6]: http://bootstrapzero.com/bootstrap-template/flathood
[7]: http://www.bootply.com/users/cskelly
<file_sep>/posts/post11.md
---
title: UnrealIRCd and SANICK
date: 2012-07-22 03:17:00
tags: C, development, irc, servers, unrealircd
---
I know, I still haven't done that mail server post. It's coming.
I just wanted to quickly write a post about a module I've just finished working on for UnrealIRCd 3.2.x.
Unreal has the `m_svsnick` module, which is specifically meant to be used by U-lined servers, such as IRC services. This module facilitates the forced changing of nicks. Other IRCd's have a command like that built-in and usable by regular opers, but not Unreal. The reasoning for this is that such a command could easily be abused, and the management of nicks is Services' job anyway. This is all fine and dandy as some IRC services packages such as Anope come with an SVSNICK command available in operserv by default, and other services packages may have 3rd-party modules to add such a command. However, what if you're running UnrealIRCd and Atheme 6.x? Unreal has no user-accessable SVSNICK command, and atheme doesn't have such a command either. That's where the subject of this post comes in.
I've just finished working on `m_sanick.c`, a module which adds a SANICK command, accessible by IRC opers, which force-changes a given user's nick.
### Download
You can download the module source here: [m_sanick.c][1]
Source is licensed under the GPL, original code by Mouse, some code used by this module was pulled from `m_svsnick.c`.
### Installation
* Download the module to `src/modules/m_sanick.c` in the Unreal3.2 source directory
* `./Config` and `make` unreal as normal, if you haven't already done so or if the source directory is completely clean
* Run `make custommodule MODULEFILE="m_sanick"`
* Copy the resulting .so (which will be at `src/modules/m_sanick.so`) to the Unreal modules directory. If you installed unreal as a package, it'll probably be `/usr/lib/unrealircd/modules`. If you compiled unreal yourself, the modules directory will be in the unreal configuration directory you set during configuration. This is usually inside the source directory or at `/etc/unrealircd/modules`.
* Add `loadmodule "/your/module/directory/m_sanick.so";` to your unrealircd.conf
* `unreal rehash` your server.
If you run an Unreal-based network with multiple servers, you'll need to repeat this process in full on every server.
### Usage
Once installed, run `/sanick TargetNick NewNick` where TargetNick is the nick you wish to change, and NewNick is the nick you wish to change the user's nick to.
If this does not work, `/quote sanick TargetNick NewNick` should work. In irssi, you will have to use this command instead. Alternatively, in irssi, you can use [dispatch.pl][2] or add sanick as an alias with the following command: `/alias sanick quote sanick`
### Disclaimer
The original source was written by Mouse, and was modified by myself in order for it to compile and function correctly. The "CHGNICK" function was removed. Parts of this module are copyright to Mouse and the UnrealIRCd dev team. I am not liable under any circumstance for any damage, service disruption or any other issues that may arise during the installation or use of this module. This module contains no malicious code and is freely downloadable and may be modified by anyone. This module is in use on at least one production IRC network, however no guarantees are made as to the module's stability. Use at your own risk. This module will not work on other IRCd's and may not work on older (3.2.8 or older) versions of UnrealIRCd.
This module is an unofficial third-party module and is unsupported. However if you experience issues while compiling or using this module, please [email me](/about) and I'll try to help as best I can.
[1]: https://pub.maff.scot/code/m_sanick.c
[2]: http://scripts.irssi.org/scripts/dispatch.pl
<file_sep>/scripts/new-post
#!/bin/sh
read -ep 'Title of new post: ' TITLE
read -ep 'Tags for new post, comma-separated: ' TAGS
DATE=`date '+%Y-%m-%d %H:%M'`
FNAME="`date '+%Y%m%d'`.`echo "$TITLE"|tr '[:upper:]' '[:lower:]'|tr -cd '[:alnum:]'`.md"
cp posts/post.template posts/$FNAME
env V="$TITLE" perl -pi -e 's/^(title: )/$1$ENV{V}/' posts/$FNAME
env V="$DATE" perl -pi -e 's/^(date: )/$1$ENV{V}/' posts/$FNAME
env V="$TAGS" perl -pi -e 's/^(tags: )/$1$ENV{V}/' posts/$FNAME
[ -z "$EDITOR" ] && echo "EDITOR environment variable not set. Please set this to your preferred editor, or open $FNAME manually" && exit
$EDITOR posts/$FNAME
<file_sep>/posts/post5.md
---
layout: post
title: Google Drive, or Why People Need To Stop Causing Unnecessary Drama
date: 2012-04-27 04:17:00
tags: drama, google, google drive, idiots, rant, terms of service
---
So there's been some ruckus lately because, following the launch of Google Drive, people took to the internet to compare the Terms & Conditions of Google Drive, to that of Dropbox and SkyDrive. The main point seems to be that people see Google Drive's T&Cs as being too unrestrictive. Case in point: [https://twitter.com/#!/jmacdonald/s...][1]
What I have a big problem with, is that people don't seem to have properly read the relevant portion of Google's terms and conditions. The full text of this portion is as follows:
> Some of our Services allow you to submit content. You retain ownership of any intellectual property rights that you hold in that content. In short, what belongs to you stays yours.
>
> When you upload or otherwise submit content to our Services, you give Google (and those we work with) a worldwide license to use, host, store, reproduce, modify, create derivative works (such as those resulting from translations, adaptations or other changes we make so that your content works better with our Services), communicate, publish, publicly perform, publicly display and distribute such content. The rights you grant in this license are for the limited purpose of operating, promoting, and improving our Services, and to develop new ones. This license continues even if you stop using our Services (for example, for a business listing you have added to Google Maps). Some Services may offer you ways to access and remove content that has been provided to that Service. Also, in some of our Services, there are terms or settings that narrow the scope of our use of the content submitted in those Services. Make sure you have the necessary rights to grant us this license for any content that you submit to our Services.
What this essentially states is "You retain full rights to all content you submit to a google service. When you do this, you grant us and our partners the right to store, copy, modify (This is for things like converting document formats), create derivative works (This is things like thumbnails, scaled/rotated/edits that you perform to photos in Picasa's photo editor), communicate (Transmit over the internet), publish (Display on a blog post, for instance), publicly display (Displaying things on the internet is a public display) and distribute the content (Transmitting your data through various google services). This license you grant us, only allows us to use the agreed rights when operating our services, promoting our services (Remember, this is not a google drive specific Terms & Conditions, this is for all of google's services, so this can include things like reviews on Google Maps), improving our services, and creating new services."
The main issue that people seem to have is they don't read the line that states google can only use the agreed rights when operating/improving/promoting their services, or when creating new services. It also states that there are "terms or settings" which further narrow down what google is actually allowed to do with your data, and chances are there is, or soon will be, a supplimentary Terms & Conditions page specific to Google Drive.
The jist of this is, you retain full rights to all content you put on google drive. Google is only allowed to do things like convert your files between data formats (Word Document to RTF, for instance, or JPG to PNG), or transfer your data between their servers. The license includes stuff like that because you clicking "Convert my document to Word please" does not constitute you giving google the right to actually perform that action, they have to have the rights in the license to avoid any legal issues. Google does not, contrary to what everyone seems to believe, reserve the right to take your holiday photos from Google Drive and use it as the background on the main google home page.
Calm down, people. It's not nearly as bad as you claim.
[1]: https://twitter.com/#!/jmacdonald/status/195184740209401856/photo/1 "https://twitter.com/#!/jmacdonald/status/195184740209401856/photo/1"
<file_sep>/.githooks/post-receive
#!/bin/sh
cat > /dev/null
BASE=/usr/home/sites; export BASE; APP=blogalba; export APP
git --git-dir $BASE/$APP/.git --work-tree $BASE/$APP pull
git --git-dir $BASE/$APP.mirror.git fetch
git --git-dir $BASE/$APP.mirror.git push
echo "Restarting $APP"; $BASE/$APP/start<file_sep>/posts/post10.md
---
layout: post
title: File descriptor counting
date: 2012-07-01 04:03:00
tags: bash, linux, one-liners, servers
---
Yes I know I still haven't done part two of that mail server post. I'll get it done soon, I promise.
While chatting on IRC, someone mentioned that they were having a problem with a process going mental and creating a bunch of file descriptors in linux, eventually hitting the "max FD limit" linux has. They couldn't figure out which process it was and they couldn't find a program that would list a count of how many FDs a process has open. A few minutes later I'd thrown together this bash one-liner for him. I'm posting it here just in case someone else might find it useful.
```
echo "$(for pid in $(ls -a /proc|egrep '^([0-9])*$'|sort -n 2>/dev/null); do if [ -e /proc/$pid/fd ]; then FHC=$(ls -l /proc/$pid/fd|wc -l); if [ $FHC -gt 0 ]; then PNAME="$(cat /proc/$pid/comm)"; echo "$FHC files opened by $pid ($PNAME)"; fi; fi; done)"|sort -r -n|head -n4
```
To explain: It loops through every file/folder in /proc that is a process ID, then checks that there's a file descriptor folder. Then it gets a count of all the FDs that process currently holds, gets the process name and outputs how many file descriptors that process has open, as well as the process name. This is then reverse-sorted and cut down to only the four processes with the most FDs open.
<file_sep>/posts/post9.md
---
layout: post
title: I hate the term 'unlimited'.
date: 2012-06-26 01:40:00
tags: bullshit, fair use, mobile phones, rant, tariffs, ThreeUK, Virgin Mobile
---
Okay yes I know I said the second part of my mail server post was incoming, it still is, but for now I'd like to break out and complain about something again.
Virgin Media recently announced a new 'Premiere' tariff for Virgin Mobile. This tariff gives you unlimited calls to landlines, 2500 minutes to mobiles, unlimited texts and unlimited data, for as low as £21 for existing Virgin Media customers.
As soon as I read "all-you-can-eat data", I was skeptical. Very few mobile operators offer truly unlimited data (and I'm with Three UK, who are one of maybe two operators here that offer proper unlimited data - their policies state that customers have an effective data cap of 1TB per month). So I did what anyone else does, and I looked up their policies (which you can find [here][1]), which state that:
> **Unlimited Mobile internet for daily use by Pay Monthly customers:** We'll monitor how much mobile internet you use each month so that we can protect the network we use for all of our customers. **If we consider your use to be excessive**, we won't charge you any more, **but we may restrict your access to the mobile web depending on how often and how excessive we think your usage is. As a rule of thumb, we are likely to consider any usage over 1GB per month to be excessive.** Unlimited use is within the UK and is for your personal, non-commercial use only. It doesn't include making internet phone or video calls, peer to peer file sharing, using your phone as a modem, or while you are abroad.
Virgin Mobile are basically stating that they'll either restrict or throttle you if you use more than 1GB of data a month. That's hardly unlimited.
Then you've got the unlimited texts and landline minutes. But Maff, you may cry. How can Virgin screw up unlimited texts and landline calls? Quite easy. From the same document on virgin's website:
> **Unlimited texts:** Unlimited texts are **subject to a fair use allowance of 3000 texts per month**. If your usage exceeds this amount then **we reserve the right to charge you for the excessive element of your usage** at the text rate for other mobile networks for your tariff outlined in our Tariff Table. Unlimited use is within the UK and is for your personal, non-commercial use only. It **doesnt include texts to shortcode services, group text, or picture messages** and any of these uses will be charged at the text rate for other mobile networks for your tariff outlined in our Tariff Table.
>
> **Unlimited landline minutes:** Unlimited landline minutes are **subject to a fair use allowance of 9000 minutes per quarter (3 months).** If your usage exceeds this amount then **we reserve the right to charge you for the excessive element of your usage at the rate for calls to landlines** for your tariff outlined in our Tariff Table. Unlimited use is only for UK originating calls from the eligible Virgin Media phone to UK landlines (01,02 and 03 numbers). All other call types will be charged at the rates indicated in the Tariff Table and are not included in the allowance of minutes. Unlimited minutes are for your personal, non-commercial use only.
Right there. "Unlimited texts" actually means "3000 texts per month and we'll probably charge you standard rates if you go over that". "Unlimited landline minutes" actually means "9000 minutes per quarter year, and we'll probably charge you standard rates if you go over that".
Now it's fair to assume that most people won't use more than 3000 minutes or texts per month, but please, don't call that unlimited. It's misleading. As for Virgin's so-called unlimited data, I really don't understand how it can be called "unlimited data" when Virgin considers usage exceeding 1GB per month "excessive".
I really have nothing against Virgin, they were one of the first operators I was with (The other was BT CELLNET, now o2), and I'm sure their 3G network is great (I last used Virgin's network several years before 3G was even a thing in the UK so I have no idea, but the 2G network they had was good and coverage was always great), but it just rubs me up the wrong way when an ISP or mobile network provider claims that a service is "unlimited" - I did the same thing with BT when I discovered their top-tier "Unlimited 8mbps" broadband plan was actually subject to a fair use cap of 100GB. We didn't find this out until BT emailed us saying we'd hit 80GB that month and that we'd be billed for any usage past 100GB.
I'm happy to change this if I just found the wrong policies page on Virgin's website. If I pointed out the wrong policies and Virgin's "Premiere" tariff is subject to different policies, please point it out and I'll happily reflect that in this post.
[1]: http://www.virginmobile.com/vm/genericContent.do?contentId=our.service.footer.sm068#Our%20Fair%20Use%20Policies
<file_sep>/posts/post14.md
---
layout: post
title: Why I never (or rarely) place phone calls
date: 2013-01-19 22:35:00
---
If I want or need to contact someone, typically the first thing I check is my instant messenger. I use [Trillian][1], which keeps me logged into every IM service I use regularly (AIM, MSN and Gtalk). I also log into Skype on it if I need to. If the person I want to talk to isn't online or available there, I check Steam. If they're not available there, I text them. If I don't have their number or something, I message them on Facebook.
Calling people is, for me, an absolute last resort.
This is entirely because, while I have way more minutes and texts on my phone contract than I will reasonably use in a month, I grew up with SMS and instant messaging as my primary form of communication. I know that, if I send a message to someone, they're not required to act upon it immediately and can respond when they're ready to. Phone calls don't afford that luxury. If someone phones you, you have to decide to answer or decline the phone call right there. If you miss the call, you have to contact the person later to find out why they were calling you, unless they left a voicemail (and who does that?).
So when I want to phone someone, I have to take into consideration how busy that person is and how likely it is that they'll be available to both answer the phone and have a chat. I'm not sure if this is simply a problem I have or something, but I generally have no idea what time is a good time to call someone (which is why, in the years that she's been living away from home, I've barely called my sister even once.) I rarely even call my best friend for this reason.
This isn't to say I think phone calls are bad. Not at all, I'll defend the importance of phone calls to the ends of the earth. I simply think they could be improved. Skype (and other internet-based voice calling systems) give you a good indicator, by whether or not the person: A) is online, and B) has their status set to "Available".
Yes, I know I haven't posted anything in quite a while. I have quite a few draft posts, and for the most part I _just can't be bothered finishing them._ I will eventually, don't worry. I also have a lot more stuff I want to talk about.
[1]: http://trillian.im
<file_sep>/posts/post3.md
---
layout: post
title: s/keyboard/leopard/
date: 2012-04-08 03:06:00
tags: short
---
A while ago I installed [this script][1] which was inspired by [this xkcd comic][2]. I keep forgetting it's installed, but that itself makes for some hilarious double-take moments when bowsing.
![][3]
[1]: http://userscripts.org/scripts/show/128626
[2]: http://xkcd.com/1031/
[3]: http://s.fag.wf/Ok.png
<file_sep>/posts/post6.md
---
layout: post
title: Virtual Servers and their providers
date: 2012-04-28 02:48:00
tags: benchmarks, bhost, rant, review, servers, simplexwebs, thrustvps, VPS
---
Since I figure it's bad form to have a blog and /only/ use it for ranting, here's a somewhat useful post. I've been with [a][1] [number][2] [of][3] [different][4] [hosts][5] over the past year or two, and I figure it'd be useful for others to know why I like or don't like them.
### **[SimplexWebs][6]**
SimplexWebs has been in the hosting business for quite a while now, and do enterprise webhosting, online radio hosting and domains, as well as VPS (Xen, powered by OnApp) hosting. I was lucky enough to grab one of their limited birthday sale servers, which gave you 256MB RAM, decent CPU speed, 20GB disk and 100GB monthly bandwidth, for £25 a year.
This server's basically been my primary server/main workhorse - despite initially purchasing it to run a VPN server, and has held up ridiculously well. Uptime has been fantastic - my server's only been down a few times over the last half a year or so, including migrations between their old SolusVM platform to their new OnApp platform, and including the recent downtime when they moved datacentres.
Server and network speed are _really_ good. I think this is one of the fastest servers I've ever used, and that includes the brief time I was with Linode. Support is fantastic, their team is always quick to respond and very helpful, and you definitely get the feeling that they actually care about their customers. Overall, they're one of the best hosts I've ever been with, and I don't feel I'll ever need to move to another host.
Here's some benchmarks:
Network speed:
```nohilight
~ wget cachefly.cachefly.net/100mb.test -O /dev/null
--2012-04-28 02:34:32-- http://cachefly.cachefly.net/100mb.test
Resolving cachefly.cachefly.net... 192.168.3.11
Connecting to cachefly.cachefly.net|192.168.3.11|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104857600 (100M) [application/octet-stream]
Saving to: `/dev/null'
100%[======>] 104,857,600 11.8M/s in 8.7s
2012-04-28 02:34:41 (11.5 MB/s) - `/dev/null' saved [104857600/104857600]
```
Disk I/O:
```nohilight
~ dd if=/dev/zero of=/tmp/disktest bs=64k count=16k
16384+0 records in
16384+0 records out
1073741824 bytes (1.1 GB) copied, 4.52632 s, 237 MB/s
```
### **[Bhost][7]**
Bhost are a UK-centric VPS provider, primarily dealing with OpenVZ servers although they've recently launched Xen PV plans. I should mention their servers are some of the cheapest you can get, the cheapest OpenVZ server being £4.70 (before VAT) and including 512MB RAM and 512MB burst RAM.
Their support is pretty great, considering they're a budget host, and the servers themselves are quite speedy. I do have some issues with the OS templates they have available - their Arch images are broken due to the host kernel being too old, although I'd say that's an Arch issue, and their Gentoo image is too old to actually use. Debian works fine though, so that's what I'm using. Overall, network and server speed is _really_ good. Uptime is fantastic, in the entire time I've been with them (a number of months now), my server's almost never been down. Definitely one of the most reliable hosts I've been with.
Here's some benchmarks, since I still have a server with them: Network speed:
```nohilight
# wget cachefly.cachefly.net/100mb.test -O /dev/null
--2012-04-28 02:30:40-- http://cachefly.cachefly.net/100mb.test
Resolving cachefly.cachefly.net... 192.168.3.11
Connecting to cachefly.cachefly.net|192.168.3.11|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104857600 (100M) [application/octet-stream]
Saving to: `/dev/null'
100%[======>] 104,857,600 10.2M/s in 9.8s
2012-04-28 02:30:49 (10.2 MB/s) - `/dev/null' saved [104857600/104857600]
```
Disk I/O:
```nohilight
# dd if=/dev/zero of=/tmp/disktest bs=64k count=16k
16384+0 records in
16384+0 records out
1073741824 bytes (1.1 GB) copied, 8.31944 s, 129 MB/s
```
### **[ThrustVPS][8]**
This was actually the first VPS host I'd ever been with. I found them after browsing [LowEndBox][9], and was interested by their very low pricing. Their website design made me feel like they were a good host, and so I bought a server there (Xen HVM, 512MB RAM, 1TB bandwidth, four cores). The setup time really should've indicated something, though, as it took somewhere between a day or two before my server actually got provisioned.
The speed of the server itself was reasonably good - network speed was great (Less ThrustVPS's doing and more that it's just a good datacentre in general), disk I/O and general performance was good. It never felt _speedy_, but it got the job done without delay. Uptime was, for the most part, good. It wasn't often down, and when it was, it was down for less than an hour at most. I quickly learned (through talking with others in their IRC channel - #thrustvps on OFTC) that this was a rarity, and that I was on one of their "good" nodes. Complaints of servers being down were oddly common. Their support was nothing really to write home about. It was neither good nor bad. Your issues did get resolved (eventually - by someone who usually had less than stellar english skills), but you never got the feel that they actually cared.
My main issues with ThrustVPS started in September, when I got an email stating that the node my server was on, had experienced some issues and they were investigating it. After it came back online, my server was left without internet connectivity. Nothing was wrong as far as I could see, so I emailed their support asking what was wrong. Eventually I was told that the connectivity issue had been resolved, though no explanation about what happened was ever given. 9 days later, the same thing happened again - Node went down, my server had no connectivity when it came back. I emailed support again, and was eventually told that I'd been DDOSed and that my server's IP had been null-routed. I explained to them that I had done nothing to warrant an attack, and asked if they were sure - as I could find absolutely no evidence that this was actually the case. Their support claimed that what they were saying was true, and refused to restore connectivity until I reinstalled my server's operating system. So I backed up the data on my server to a separate drive, quick-installed Debian, got them to restore connectivity and then sent my backup to another server.
In summary, while the servers and prices themselves are good, uptime is a bit unpredictable, support is unpleasant and they seem to have a habit of restricting your server without explanation, or without supplying any actual evidence to back up their claims. I wouldn't recommend them to anyone.
[1]: http://thrustvps.com
[2]: http://linode.com
[3]: http://bhost.net
[4]: http://simplexwebs.com
[5]: http://vps6.net
[6]: http://www.simplexwebs.com
[7]: http://www.bhost.net
[8]: http://www.thrustvps.com
[9]: http://lowendbox.com
<file_sep>/posts/post15.md
---
layout: post
title: Gone, but never forgotten
date: 2013-02-22 00:29:00
tags: personal
---
Just a short post today.
![][1]
Yesterday (Wednesday the 20th), we took our dog to the vet for what we thought was a stomach bug. He's had diabetes since about July of last year, and can't have insulin without food, so we were concerned that he wasn't eating. He was diagnosed with Pancreatitis, which is treated through starving him for a few days until the pancreas heals a bit, however due to his diabetes, this could have an extremely adverse effect - he'd lost 1.5 stone over the course of a day or so already, and was in a tremendous amount of pain.
The vet informed us that, even if he pulled through and his pancreas got better, he'd be in a terribly fragile state and would have a long time to go before he regains weight - and there's a high chance of recurrence, meaning he could be in and out of the vet very often, and he was in so much pain due to it.
He was put to sleep yesterday afternoon. We were with him the whole time, and right to the end, he was wagging his tail because he was so happy to see us.
Here's to you, Max. You were a better friend and companion than anyone could ever have asked for.
[1]: https://pub.maff.scot/files/max.png
<file_sep>/posts/post4.md
---
layout: post
title: The Journey of a Thousand Frustrations Begins with a Single Step
date: 2012-04-16 13:45:00
tags: bash, gentoo, linux, one-liners, rant
---
There are times when linux frustrates me. Not with issues specific to one distro, but software packages in general which are written for linux.
My prime example here is Watch. In Gentoo, it's included in the [procps package][1]. I recently was confused to find that my ident daemon, which I keep running because I'm an avid IRC user, was being flooded with traffic near constantly. Netstat told me it was because of two IRC servers I ran. So I logged in, checked netstat there, and sure enough, it was them. But I had no idea what process on the servers was actually creating the connections.
I assumed it would be the ircd itself, but I wanted proof before investigating further. No problem, I thought, I'll just run `watch --differences=cumulative -n 0.1 'lsof +M -i4|grep auth'`, which according to watch's manpage, would show what's changed in a command's output, rather than clearing the screen and displaying the output every .1 seconds. It did do this, in a way, however, because the program creating the connection to my ident server only kept that connection for a fraction of a second, the output vanished, and thanks to the unhelpful way that watch handles output which only shows up once, all I got was some white blocks showing that there had at one point been text there.
My solution? Throw together a bash one-liner which looped infinitely until the offending program was identified: `while true; do UNR=$(lsof -M -i4|grep auth); if [ -n "$UNR" ]; then echo "$UNR"; break; fi; done`
This did eventually work, and it turned out to be a runaway process on my personal box constantly creating connections to both IRC servers.
[1]: http://packages.gentoo.org/package/sys-process/procps
<file_sep>/posts/post13.md
---
layout: post
title: Why I love lighttpd
date: 2012-09-04 00:35:00
---
It's a well-known fact that I absolutely adore lighttpd. Why, you ask?
I run lighttpd on a small cluster of web servers that serve a mix of static and dynamic content. One web server is dedicated to serving static content, and the other two are dedicated to serving dynamic content. The average memory use across all three is around 3.5MB. Average CPU use is almost zero.
But it's not just the low resource usage that I love about lighttpd. It's the downright gorgeous configuration syntax.
We recently began rolling out proper SSL to all of our client-accessable services at work. We're primarily an Apache shop at work, but one server runs lighttpd. Forcing all connections to run over SSL was as simple as:
```
server.modules += ("mod_redirect")
$HTTP["scheme"] == "http" {
$HTTP["host"] =~ "(.*)" {
url.redirect = ("^/(.*)" => "https://%1/$1")
}
}
```
And then there's the fact that managing vhosts is just brilliant. Adding a new vhost is as simple as `mkdir /var/www/new-vhost` and adding the following to my lighttpd config file:
```
$HTTP["host"] =~ "^new\.vhost\.net$" {
server.document-root = var.basedir + "/new-vhost"
accesslog.filename = var.logdir + "/access-new-vhost.log"
}
```
There's a lot more to love about lighttpd, though. I'll be updating this post with more tips and config snippets as I go.
Adding on to the earlier config snippet for forcing SSL across all vhosts, it might even be possible to have a single block for all vhosts (I haven't personally tested this, use at your own risk):
```
$HTTP["host"] =~ "(.*)" {
server.document-root = var.basedir + "/$1"
accesslog.filename = var.logdir + "/access-$1.log"
}
```
This would, in theory, accept any vhost as long as it has a corresponding folder in /var/www.
<file_sep>/pages/about.md
---
title: About Me
---
Hi! I'm <NAME>, best known as Maff.
I'm a Systems Administrator, hobbyist photographer and scripting fanatic from Scotland. I currently manage infrastructure at [IPXcore][1] and work on (mostly Perl) [projects][2] in my spare time. My current "constantly improving" project is my home network, which I've added multiple access points to, and have set up external monitoring for my OpenWRT-based hardware through [Munin][3], for which I've developed the [openwrt-munin-node][4] project. As well as this, I've worked on other projects including a [daemon][5] for monitoring directories and performing actions on files added to them, and a [basic blogging system][6] which powers this site.
Contact information:
- email: [<EMAIL>][11]
- PGP: [0x7B8A457D282B7CB6][9] (keybase: [maff][10])
- iMessage: <EMAIL>
- telegram: [@Maffsie][13]
- skype: [matthew.connelly][14]
- twitter: [@Maffsie][12]
- irc: Maff @ [Freenode][7] and [EntropyNet][8]
[1]: https://www.ipxcore.com/
[2]: https://github.com/Maffsie/
[3]: http://munin-monitoring.org/
[4]: https://github.com/Maffsie/openwrt-munin-node/
[5]: https://github.com/Maffsie/ayudante-lobo/
[6]: https://github.com/Maffsie/BlogAlba/
[7]: https://freenode.net/
[8]: https://entropynet.net/
[9]: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x7B8A457D282B7CB6
[10]: https://keybase.io/maff/
[11]: mailto:<EMAIL>
[12]: https://twitter.com/maffsie
[13]: https://telegram.me/Maffsie
[14]: skype:matthew.connelly?chat
<file_sep>/posts/post1.md
---
layout: post
title: Start as you mean to go on
date: 2012-02-12 20:09:00
tags: introduction, life, linux
---
So for the millionth time, I'm starting a blog. Hopefully, this time I'll actually have stuff to write about. As a bit of an introduction, I'm Maff. I'm a computer science student, sysadmin and server support drone from Scotland. I'm also a bit of a designer, a developer and a security dork. I also love videogames, music and a whole host of other things.
I'm starting this blog in part because I want somewhere to document my pursuits (software or otherwise), but also as a place to post about the funny things that happen in real life, and as a place to rant. I may also post about the software I write, from time to time - I'm a semi-active developer over at [github][1], and I'm the gentoo package maintainer for [Monitorix][2].
[1]: http://github.com/maffc/
[2]: http://monitorix.org
<file_sep>/posts/post2.md
---
layout: post
title: The case for not using Arch
date: 2012-02-28 17:04:00
tags: arch, arch linux, linux, rant, sysadmin
---
I run a number of different servers from a number of different providers. I also run servers for friends. In this post, I'll be discussing one server in particular, a friend's server that's primarily used for IRC, web hosting and minecraft. This server runs Arch.
Now I'm going to start by saying I don't always make fantastic decisions and I'm not always known for making sure everything's perfect before rebooting a server. I have, in the past, screwed servers up. But this case was a little different.
Yesterday I log into the server to update a firewall rule, and discover that, because I've never used the nat table in iptables before on that box, the module was never loaded. Of course, the box has fantastic uptime and hasn't been rebooted in over 160 days. Now I'll stop for a second to mention how Arch handles kernel upgrades. When the kernel's upgraded, the previous kernel is left on the system, and all kernels older than that are removed completely. This includes the currently running kernel, and all modules. And this box hadn't been rebooted since kernel 3 was released. I have the box set up to be as zero-maintenance as possible. Emails whenever anything happens, cronjobs taking care of updates and removal of old packages from the cache, scripts to reboot any services that have crashed, gone down or have stopped responding. But as I discovered during a routine check a week prior, the Arch box hadn't been upgrading any of its packages due to a [ recent change][1] to the filesystem package. I manually started the update process, it informed me that it couldn't upgrade the system because of a file conflict (as the news article mentioned). No problem, I force-installed the update to filesystem and then upgraded the rest of the system as usual.
Now fast-forward back to yesterday, I'm telling my friend I need to reboot his server to apply the firewall rule. He gives the okay, and I reboot the server. Emails flood in saying that various services are down and that the server's offline, as always. But then a few minutes pass, there's no email that everything's back online again. I ping the server, nothing. Log into the server host's control panel, it's listed as online, so I VNC into it to see what the issue is. It can't find the harddrive and has thrown itself into a recovery terminal. What.
I figure a kernel change has messed with the partitions, so I boot the server into my usual recovery system - the gentoo live CD. Nothing seems out of place with grub or the fstab, so I look at the next culprit - the config file for mkinitcpio. It's blank.
Somehow, pacman disregarded the usual rules about protecting config files against being overwritten and messed with the config file, so the initramfs Arch needs in order to boot up properly was completely broken. No problem, I'll just chroot in -- OH WAIT. The Gentoo LiveCD runs kernel 2.6.31, and arch refuses to do /absolutely anything/ unless the kernel is new enough (In this case it had to be 2.6.32 or newer). The server host isn't exactly good, and doesn't provide any recent install media. Cue ten minutes of me googling for the kernel versions of everything in the media list, eventually settling for a Fedora 13 disk that had a recent-enough kernel. I get chrooted in, fix the mkinitcpio config and start generating the images. It complains that /dev isn't mounted. Okay. I look at the source for mkinitcpio, discover it's trying to access /dev/fd, which somehow doesn't exist. I symlink it over from /proc/self/fd and start it again. Everything seems to work, so I reboot.
This time, it recognises the hard drive, but the partition device names have changed. It's now seeing the disk as /dev/xvda. Bizarre, but has happened before. I boot the gentoo livecd again, edit grub's menu.lst and fstab, reboot back into Arch. It boots! But doesn't have a network connection. By this point, I'm close to pulling out my hair. I google around and find that because I included a bunch of xen drivers that mkinitcpio forgot before, everything's working a little differently. Specifically, it now works closer with Xen, and is trying to unplug everything at boot. No problem, I'll put `xen-emul-unplug=none` in the kernel boot line. Reboot the server and the harddrive device name has changed again. I boot into gentoo, change menu.lst and fstab to use /dev/sda again, and reboot.
Finally, the server's booted and has a network connection. And this is why I no longer install arch on any of my boxen. I can't trust it to reboot without throwing a hissy fit and killing itself.
**TL;DR Arch package issue sends me on an hour-long crusade to make a box boot again.**
[1]: http://www.archlinux.org/news/filesystem-upgrade-manual-intervention-required/
| 1e30c316fd106d212e36d087a8ad03e1001a777b | [
"Markdown",
"Shell"
] | 18 | Markdown | MaffC/BlogAlba | a589ec7ed941f3d0c972267c42bd3c2d30b75408 | 100a84790a8511220639f121e6336347b2e1bdb5 |
refs/heads/master | <file_sep>using System;
namespace ConsoleApp13
{
class Program
{
static void Main(string[] args)
{
int[] names = {67, 56, 89};
string[] name = {"alex", "kim", "joy"};
int myvalue = names[1];
int mysecondvalue = names[0];
int result = myvalue + mysecondvalue;
Console.WriteLine(myvalue);
Console.WriteLine(mysecondvalue);
Console.WriteLine(result);
Console.ReadKey();
}
}
} | 613fc40bca02cbdf2ef325e80c75abb2299a0600 | [
"C#"
] | 1 | C# | Alexkimathi/kim | da288c0ad510a262456722a1f67a1170940dccdf | 3dcabf8bdf39febe815213f62faebc09acb3617c |
refs/heads/master | <repo_name>endrton/hyperion<file_sep>/readme.md
## Recommendations
Editor: [Visual Studio Code](https://code.visualstudio.com/)
Extensions:
* Instant Markdown
* Auto-Open Markdown Preview
# Getting started
If Node.js and npm aren't already on your machine, [install them](https://nodejs.org/en/).
Required versions:
* node.js: **v4.x.x**
* npm: **3.xx**
Additionally you will need [yarn](https://yarnpkg.com/) for dependency management:
```
npm install yarn -g
```
## Install packages
```
yarn
```
If the **typings** folder doesn't show up after running ```yarn```, you'll need to install it manually with:
```
yarn run typings install
```
## Start application
Open a command line and enter this command:
```
yarn start
```
<file_sep>/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Machine } from './models/machine';
import { MachineService } from './services/machine.service';
@Component({
selector: 'root',
template: `
<div class="container-fluid">
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-10"></div>
</div>
</div>
`
})
export class AppComponent implements OnInit {
title = 'Title';
machines: Machine[];
constructor(private machineService: MachineService) { }
ngOnInit(): void {
this.getMachines();
}
getMachines(): void {
this.machineService.getMachines().then(machines => this.machines = machines);
}
}
| 23dde494bb607eac42fad6ffc4ebfab063f9146c | [
"Markdown",
"TypeScript"
] | 2 | Markdown | endrton/hyperion | 1209520537eca65fbc25e864d8485e9e48eb009f | d412bba1ed0c212d91d1d73d0ea556e8c1114804 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\product;
class ProductController extends Controller
{
public function add(Request $req )
{
$add= new product;
$add->productname=$req->productname;
$add->price=$req->price;
$add->qunatity=$req->qunatity;
$result=$add->save();
if($result)
{
return["Result"=>"data has been saved"];
}
else{
return["Result"=>"data has not saved"];
}
}
function update(Request $req)
{
$data=product::find($req->id);
$data->productname=$req->productname;
$data->price=$req->price;
$data->qunatity=$req->qunatity;
$result=$data->save();
if($result)
{
return["Result"=>"Data is updated"];
}
else
{
return["Result"=>"Data is not Updated"];
}
}
function delete($id)
{
$product=product::find($id);
$result=$product->delete();
if($result)
{
return["Result"=>"Record is deleted succesfully"];
}
else
{
return["Result"=>"Record is deleted succesfully"];
}
}
function full()
{
return product::all();
}
function displaywithid($id)
{
return product::find($id);
}
}
//
| eda7be519f0657573f3e98acd9738f43e430f6ae | [
"PHP"
] | 1 | PHP | Nafeeslogiciel/crudop | f7e411e21d3fb929b6f4b1482db38cfd60e1f3bb | d66f34f6e680f13880c2a4988e6903a98f61659a |
refs/heads/master | <file_sep>import { Given, Then, When } from "cucumber";
import { browser } from "protractor";
import { view } from "../../framework/factory";
import { SignInView } from "../../views/account/signInView";
When("User enters email {string} and password {string} on login screen", async (email: string, password: string) => {
await view(SignInView)
.then((signInView) => signInView.assertDisplayed())
.then((signInView) => signInView.setEmail(email))
.then((signInView) => signInView.clickNext())
.then((signInView) => signInView.setPassword(password))
.then((signInView) => signInView.clickSignIn());
});
Then("Error is displayed {string}", async (error: string) => {
await view(SignInView)
.then((signInView) => signInView.assertError(error));
});
Given("Open page {string}", async (url: string) => {
await browser.get(url);
});
<file_sep>export const config = {
displayTimeout: 5000,
};
<file_sep>import * as reporter from "cucumber-html-reporter";
const cucumberReporterOptions = {
jsonFile: "report.json",
output: "report.html",
reportSuiteAsScenarios: true,
theme: "bootstrap",
};
export function generateReport() {
reporter.generate(cucumberReporterOptions);
}
<file_sep>import { expect } from "chai";
import { browser, by, element, ElementFinder } from "protractor";
import { View } from "../../framework/view";
import { waitForPresence, waitForVisibility } from "../../framework/waiter";
export class SignInView implements View {
private loginContainer = element(by.css(".login"));
private email = element(by.css("#MainContent_login_UserName"));
private password = element(by.css("#MainContent_login_txtPassword"));
private signInButton = element(by.css("#MainContent_login_btnLogin"));
private nextButton = element(by.css("#MainContent_login_btnNext"));
private error = element(by.css("#SystemMessageContent_statusMessage"));
private errorMessage = element(by.css("#SystemMessageContent_statusMessage li"));
public async assertDisplayed(): Promise<SignInView> {
await waitForPresence(this.loginContainer);
return Promise.resolve(this);
}
public async setEmail(email): Promise<SignInView> {
await waitForPresence(this.email);
await this.email.sendKeys(email);
return Promise.resolve(this);
}
public async setPassword(password: string): Promise<SignInView> {
await waitForPresence(this.password);
await this.password.sendKeys(password);
return Promise.resolve(this);
}
public async clickSignIn(): Promise<SignInView> {
await waitForVisibility(this.signInButton);
await this.signInButton.click();
return Promise.resolve(this);
}
public async clickNext(): Promise<SignInView> {
const isDisplayed = await this.nextButton.isDisplayed();
// click next only if next button is displayed
if (isDisplayed) {
await this.nextButton.click();
}
return Promise.resolve(this);
}
public async assertError(expectedMessage: string): Promise<SignInView> {
await waitForVisibility(this.error);
const errorMessage = await this.errorMessage.getText();
expect(errorMessage).to.equal(expectedMessage);
return Promise.resolve(this);
}
}
<file_sep>export interface View {
assertDisplayed(): Promise<View>;
}
<file_sep>import { browser, element, ElementFinder, ExpectedConditions } from "protractor";
import { Locator } from "selenium-webdriver";
import { config } from "./config";
export async function waitForPresence(selector: Locator | ElementFinder): Promise<void> {
const elementForPresence: ElementFinder = selector instanceof ElementFinder ? selector : element(selector);
await browser.wait(ExpectedConditions.presenceOf(elementForPresence), config.displayTimeout);
}
export async function waitForVisibility(selector: Locator | ElementFinder): Promise<void> {
const elementForVisibility: ElementFinder = selector instanceof ElementFinder ? selector : element(selector);
await browser.wait(ExpectedConditions.visibilityOf(elementForVisibility), config.displayTimeout);
}
export async function waitForInVisibility(selector: Locator | ElementFinder): Promise<void> {
const elementForInvisibility: ElementFinder = selector instanceof ElementFinder ? selector : element(selector);
await browser.wait(ExpectedConditions.invisibilityOf(elementForInvisibility), config.displayTimeout);
}
<file_sep>[](https://circleci.com/gh/vitali-shcharbin-epam/bdd-typescript/tree/master)
# bdd-typescript
BDD + TypeScript + Selenium example of automation
# Frameworks
* TypeScript
* Cucumber.js
* Selenium-webdriver
* Protractor
## Features and Scenarios structure
features/
feature area/
story.feature
steps/
feature area/
steps.step.ts
views/
view area/
view.view.ts
<img src="design-framework.svg">
## References
* Cucumber - https://docs.cucumber.io/
* Protractor - https://www.protractortest.org/#/
<file_sep>import { View } from "./view";
export function view<TView extends View>(type: { new (): TView }): Promise<TView> {
return Promise.resolve(new type());
}
| 866d3b4061bef063c0f2c02435f0aeb6c6bbabeb | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | vitali-s/bdd-typescript | 0dd5519fbcc63901aefb208efcd967a014862f8a | 6cae52387dbb11937c555febb14f0d933a3b8963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.